@floless/app 0.155.2 → 0.157.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 (64) hide show
  1. package/cli-actions.mjs +392 -0
  2. package/dist/floless-server.cjs +182734 -141519
  3. package/dist/schemas/drawing-check.profile.v1.schema.json +15 -2
  4. package/dist/schemas/steel.model.v2.schema.json +25 -1
  5. package/dist/skills/floless-app-actions/SKILL.md +199 -0
  6. package/dist/skills/floless-app-approval/SKILL.md +8 -5
  7. package/dist/skills/floless-app-bridge/SKILL.md +12 -9
  8. package/dist/skills/floless-app-knowledge/SKILL.md +50 -14
  9. package/dist/skills/floless-app-new-workflow/SKILL.md +26 -10
  10. package/dist/skills/floless-app-onboarding/SKILL.md +31 -1
  11. package/dist/skills/floless-app-onboarding/references/aware-runtime.md +4 -4
  12. package/dist/skills/floless-app-queue/SKILL.md +10 -6
  13. package/dist/skills/floless-app-report-issue/SKILL.md +15 -12
  14. package/dist/skills/floless-app-rfi/SKILL.md +98 -73
  15. package/dist/skills/floless-app-routines/SKILL.md +27 -15
  16. package/dist/skills/floless-app-routines/references/routines-api.md +8 -2
  17. package/dist/skills/floless-app-steel-model/SKILL.md +1 -1
  18. package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +4 -2
  19. package/dist/skills/floless-app-tweak-contract/SKILL.md +25 -5
  20. package/dist/skills/floless-app-workflows/SKILL.md +50 -13
  21. package/dist/skills/floless-app-workflows/references/agent-steps.md +119 -0
  22. package/dist/web/agent-steps.js +1750 -0
  23. package/dist/web/agents.js +33 -8
  24. package/dist/web/app.css +681 -4
  25. package/dist/web/app.js +111 -11
  26. package/dist/web/aware-update-client.js +1 -0
  27. package/dist/web/aware.js +1257 -202
  28. package/dist/web/chat-landing-scene.js +372 -0
  29. package/dist/web/chat.css +254 -1
  30. package/dist/web/chat.js +2657 -87
  31. package/dist/web/commands-drawing-check.js +17 -0
  32. package/dist/web/commands-shell.js +1108 -4
  33. package/dist/web/commands-steel.js +6 -0
  34. package/dist/web/connections.js +1 -0
  35. package/dist/web/drawing-check-editor.html +33 -5
  36. package/dist/web/drawing-check-editor.js +538 -22
  37. package/dist/web/drawing-check-overlay.js +13 -0
  38. package/dist/web/flo-avatar.js +28 -3
  39. package/dist/web/guide.js +7 -2
  40. package/dist/web/index.html +171 -7
  41. package/dist/web/instructor.js +6 -4
  42. package/dist/web/leave-guard.js +4 -2
  43. package/dist/web/left-pane.js +8 -3
  44. package/dist/web/model-revit-module.js +15 -0
  45. package/dist/web/model-view-query.js +12 -2
  46. package/dist/web/model-viewport-revit-adapter.js +3 -1
  47. package/dist/web/pages.js +891 -36
  48. package/dist/web/panels.js +8 -5
  49. package/dist/web/parser-setup-recovery.js +12 -4
  50. package/dist/web/project-access.js +549 -0
  51. package/dist/web/project-reconciliation.js +357 -0
  52. package/dist/web/report-files.js +50 -0
  53. package/dist/web/revit-editor.js +116 -27
  54. package/dist/web/startup-admission.js +132 -0
  55. package/dist/web/steel-3d-core.js +9 -0
  56. package/dist/web/steel-editor.html +642 -22
  57. package/dist/web/steel-model-v2-commands.js +63 -5
  58. package/dist/web/step-rename.js +287 -0
  59. package/dist/web/terminal-requests.js +590 -0
  60. package/dist/web/tool-updates.js +148 -13
  61. package/dist/web/workspace-root-management.js +39 -0
  62. package/dist/web/workspaces.js +1879 -74
  63. package/launch.mjs +82 -2
  64. package/package.json +3 -1
package/dist/web/chat.js CHANGED
@@ -19,7 +19,7 @@
19
19
  historyToggle: el('chat-history-toggle'), newChat: el('chat-new'), refresh: el('chat-refresh'), history: el('chat-history'),
20
20
  title: el('chat-title'), rename: el('chat-rename'), scope: el('chat-scope'), settingsToggle: el('chat-settings-toggle'),
21
21
  settings: el('chat-settings'), provider: el('chat-provider'), switchAccount: el('chat-switch-account'), model: el('chat-model'),
22
- effort: el('chat-effort'), permission: el('chat-permission'), guideAccess: el('chat-guide-access'), integrations: el('chat-integrations'), ownConnectors: el('chat-own-connectors'),
22
+ effort: el('chat-effort'), permission: el('chat-permission'), suggest: el('chat-suggest'), guideAccess: el('chat-guide-access'), integrations: el('chat-integrations'), ownConnectors: el('chat-own-connectors'),
23
23
  desktopValue: el('chat-desktop-value'), desktopReason: el('chat-desktop-reason'), picker: el('chat-picker'),
24
24
  feed: el('chat-feed'), offscreenActivity: el('chat-offscreen-activity'), recovery: el('chat-recovery'),
25
25
  approvalTray: el('chat-approval-tray'), recoveryCopy: el('chat-recovery-copy'),
@@ -42,6 +42,8 @@
42
42
  };
43
43
 
44
44
  const state = {
45
+ // #2438: the picks waiting to go with the next message (per conversation), and the open @ list.
46
+ mentions: {}, mentionMenu: null, mentionDismissed: null,
45
47
  scopeView: null, scopeViewChatId: null, scopeChoice: null, scopeEditing: false, scopePickerOpen: false,
46
48
  accessExplanationExpanded: readAccessExplanationPreference(),
47
49
  // signInPending is keyed by provider: a wait started in one conversation must not paint an
@@ -51,7 +53,8 @@
51
53
  displayUnits: null, displayUnitsGeneration: 0,
52
54
  // #1890 PR 3b: the workspace history's pointer rows, the move notice on screen, and moves being followed now.
53
55
  movedChats: [], movedChatsKnown: null, moveNotice: null, moveNoticeTimer: null, followingMoves: new Set(), movingPoll: null,
54
- sessionReady: false, scope: null, chats: [], archivedChats: [], unreadableChats: [], chat: null, events: [], capability: null, signInPending: new Set(), desktop: null,
56
+ sessionReady: false, sessionOperation: null, sessionLifecycle: 0, sessionDisposed: false, sessionRecoveryHint: null,
57
+ scope: null, chats: [], archivedChats: [], unreadableChats: [], chat: null, events: [], capability: null, signInPending: new Set(), desktop: null,
55
58
  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,
56
59
  instructorAnswers: [], historyLoading: false, historyRequestGeneration: 0, picker: null, loading: false,
57
60
  draftTimer: null, localDraft: null, backgroundDrafts: new Map(), draftWrites: new Map(), draftVersions: new Map(), unknownFollowups: new Map(), refreshTimer: null, scopeGeneration: 0, selectionGeneration: 0, openInGeneration: 0, choosingProvider: false,
@@ -71,6 +74,7 @@
71
74
  reportHold: null,
72
75
  // Only this exact report announcement may be removed when its composer reason ends (#1704).
73
76
  reportLiveMessage: null,
77
+ pendingSettings: null,
74
78
  // A Tekla model library carried over from a Graft receipt but not yet bound to its chat. It is
75
79
  // browser-only until Send: opening, editing or removing it never calls the binding route.
76
80
  // pendingTeklaLibrary waits for the provider chooser to create the chat it belongs to.
@@ -137,6 +141,13 @@
137
141
  }
138
142
 
139
143
  async function request(path, options = {}) {
144
+ const scopeGeneration = state.scopeGeneration;
145
+ const sessionLifecycle = state.sessionLifecycle;
146
+ await globalThis.flolessStartupAdmission?.admit(path, { method: options.method, signal: options.signal });
147
+ // A new scope adopts the server-wide cookie/readiness handshake; scoped reads keep their original owner.
148
+ if (path === '/api/chat/session') {
149
+ if (state.sessionDisposed || sessionLifecycle !== state.sessionLifecycle) throw Object.assign(new Error('Chat page is closed.'), { code: 'chat-page-closed' });
150
+ } else if (scopeGeneration !== state.scopeGeneration) throw Object.assign(new Error('Chat scope changed.'), { code: 'chat-page-closed' });
140
151
  const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 30000;
141
152
  const init = { credentials: 'same-origin', ...options };
142
153
  delete init.timeoutMs;
@@ -170,6 +181,8 @@
170
181
  error.code = body?.code || null;
171
182
  error.reason = body?.reason || null;
172
183
  error.recovery = Array.isArray(body?.recovery) ? body.recovery : null;
184
+ // The subscription gate's answer (state + reason) decides which sign-in sentence errorMessage shows.
185
+ if (response.status === 402 && body && typeof body === 'object') error.body = body;
173
186
  // #2061: who holds a busy project, so the person can be asked: wait, stop it, or open it.
174
187
  error.holder = body?.holder && typeof body.holder === 'object' ? body.holder : null;
175
188
  error.status = response.status;
@@ -210,7 +223,7 @@
210
223
  }
211
224
 
212
225
  function errorMessage(error) {
213
- // A sentence written by plainError (an attachment refused in the browser) is already the whole
226
+ // A sentence written by plainError for a browser check is already the whole
214
227
  // plain-English explanation for this moment.
215
228
  if (error?.plainSentence) return error.message;
216
229
  const raw = error instanceof Error ? error.message : String(error);
@@ -228,6 +241,10 @@
228
241
  if (code === 'local-timeout' && raw) return raw;
229
242
  // #1907: the server marks a not-sent reason it already wrote for the person; it is shown as is.
230
243
  if (code === 'chat-send-refused-plain' && raw) return raw;
244
+ // A lapsed FloLess sign-in or subscription refuses every chat request with 402. It used to read as "could not
245
+ // complete this chat action, reload", which no reload fixes; the one sentence every surface shows says to sign in.
246
+ const access = globalThis.flolessBridge?.accountAccessText?.(error);
247
+ if (access) return access;
231
248
  const codeMessages = {
232
249
  // #1890 PR 3b: the server's own sentences name the workflow.
233
250
  'chat-moving': raw,
@@ -406,9 +423,11 @@
406
423
  return !raw || /sign in|auth|account/i.test(raw);
407
424
  }
408
425
 
409
- function capabilityMessage(provider, reason) {
426
+ function capabilityMessage(provider, reason, accountAccess = false) {
410
427
  const label = providerLabels[provider] || 'AI service';
411
428
  const raw = String(reason || '');
429
+ // FloLess's own sign-in or subscription (readCapability): its sentence already says what to do.
430
+ if (accountAccess && raw) return raw;
412
431
  // A check that timed out (this computer or FloLess was busy) says nothing about the AI: say that, not "not ready".
413
432
  if (/timed out|took too long|computer was busy|\bis busy\b/i.test(raw)) return `FloLess couldn’t finish checking ${label} because this computer was busy. Try again in a moment.`;
414
433
  if (signInNeeded(raw)) return `Sign in to ${label} first.`;
@@ -425,6 +444,7 @@
425
444
  }
426
445
 
427
446
  function report(error, prefix = '', messages = null) {
447
+ if (error?.code === 'chat-page-closed') return;
428
448
  const code = String(error && error.code || '');
429
449
  // #1890 PR 3b: a conversation that moved is not a failure — request() already follows it into its workflow.
430
450
  if (code === 'chat-moved' && error?.movedTo) return;
@@ -513,6 +533,16 @@
513
533
  ui.hint.classList.add('error');
514
534
  return;
515
535
  }
536
+ const pending = state.sessionRecoveryHint;
537
+ if (pending && sameScope(pending.scope, pending.generation)) {
538
+ ui.hint.classList.remove('working'); ui.hint.removeAttribute('aria-label');
539
+ ui.hint.textContent = pending.message;
540
+ if (!pending.announced) {
541
+ pending.announced = true;
542
+ announce(pending.message, () => state.sessionRecoveryHint === pending && sameScope(pending.scope, pending.generation));
543
+ }
544
+ return;
545
+ }
516
546
  const message = requestExecutionBlocked()
517
547
  ? 'Another AI Chat is changing this project or workflow. Wait for it to finish or stop it before sending here.'
518
548
  : state.followupUnknownId || hasUnknownFollowup()
@@ -523,7 +553,7 @@
523
553
  : state.chat && state.capability?.runtime && state.capability.runtime.state !== 'installed'
524
554
  ? runtimeNotice(state.chat.provider, state.capability.runtime).body
525
555
  : state.chat && !providerReady()
526
- ? `${capabilityMessage(state.chat.provider, state.capability?.reason)} You can still write a message; Send will retry the connection.`
556
+ ? `${capabilityMessage(state.chat.provider, state.capability?.reason, state.capability?.accountAccess)} You can still write a message; Send will retry the connection.`
527
557
  : state.chat?.state === 'recovery'
528
558
  ? 'Check the last AI response before continuing.'
529
559
  : !state.scope?.owner
@@ -531,6 +561,9 @@
531
561
  // #1776/#1859: a drawing read running in this conversation is where a message goes, on any screen.
532
562
  : paintFilterComposer().replyToRead
533
563
  ? READ_REPLY_HINT
564
+ // #2438: in a project, @ names a member or sheet.
565
+ : state.scope.owner.kind === 'project'
566
+ ? 'Enter to send · Shift+Enter for a new line · @ to mention a member or sheet'
534
567
  : 'Enter to send · Shift+Enter for a new line';
535
568
  if (turnIsVisiblyActive() && !state.followupUnknownId && !hasUnknownFollowup()
536
569
  && state.imageLimitChatId !== state.chat?.chatId) {
@@ -587,7 +620,7 @@
587
620
  const selectedStep = document.querySelector('#ws-step-tabs [aria-selected="true"]')?.getAttribute('data-step');
588
621
  const workspaceSurface = {
589
622
  drawings: 'drawing-filter', model: 'project-model', exports: 'project-exports',
590
- history: 'project-history', knowledge: 'project-knowledge',
623
+ history: 'project-history', knowledge: 'project-knowledge', pages: 'project-pages',
591
624
  }[selectedStep || ''] || 'project-list';
592
625
  const workspaceProjectOpen = document.getElementById('ws-project')?.hidden === false;
593
626
  const dashboardVisible = document.getElementById('dashboard')?.hidden === false;
@@ -632,6 +665,7 @@
632
665
  case 'project-exports': return shellText('ws-exports');
633
666
  case 'project-history': return shellText('ws-history');
634
667
  case 'project-knowledge': return shellText('ws-knowledge');
668
+ case 'project-pages': return shellText('ws-pages');
635
669
  case 'project-list': return shellText('ws-landing');
636
670
  case 'workflow-list': return shellText('wf-landing');
637
671
  case 'agent-list': case 'agent-page': return shellText('agents-surface');
@@ -647,7 +681,7 @@
647
681
  function floLessContextLabel(context = currentFloLessContext()) {
648
682
  const labels = {
649
683
  'drawing-filter': 'Drawing Filter', 'project-model': 'project model', 'project-exports': 'project exports',
650
- 'project-history': 'project history', 'project-knowledge': 'project Knowledge', 'project-list': 'project list',
684
+ 'project-history': 'project history', 'project-knowledge': 'project Knowledge', 'project-pages': 'project Pages', 'project-list': 'project list',
651
685
  'workflow-canvas': 'workflow canvas', dashboard: 'dashboard', report: 'report', '3d-report': '3D report',
652
686
  'model-editor': 'model editor', 'workflow-list': 'workflow list', 'agent-list': 'list of agents', 'agent-page': 'agent page',
653
687
  };
@@ -890,6 +924,8 @@
890
924
  row.append(choice);
891
925
  }
892
926
  empty.append(strong, copy, row);
927
+ // Flo building Workspaces, Workflows and Agents behind the start screens (web/chat-landing-scene.js); decorative.
928
+ if (typeof chatLandingScene === 'function') chatLandingScene(empty, `chooser:${scopeKey(state.scope)}`);
893
929
  const accounts = document.createElement('div');
894
930
  accounts.className = 'ai-chat-provider-accounts';
895
931
  accounts.textContent = 'Checking signed-in accounts…';
@@ -1075,6 +1111,7 @@
1075
1111
  const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy';
1076
1112
  copy.textContent = 'Each project or workflow keeps its own chat history in its folder.';
1077
1113
  empty.append(strong, copy);
1114
+ if (typeof chatLandingScene === 'function') chatLandingScene(empty, 'unscoped');
1078
1115
  ui.feed.append(empty);
1079
1116
  ui.title.textContent = 'AI Chat';
1080
1117
  ui.scope.textContent = 'No project or workflow selected';
@@ -1922,14 +1959,82 @@
1922
1959
  }[character]));
1923
1960
  }
1924
1961
 
1962
+ /*
1963
+ * #2437: an answer's inline directives — `:cite[anchor]` after a claim, `:assume[words]` on an assumption. While an
1964
+ * assistant answer is being rendered, `inlineSlots` collects each one and the text holds only an empty slot whose
1965
+ * number is ours; the slot becomes a real control afterwards through DOM calls (`fillInlineSlots`), so nothing the
1966
+ * model wrote ever becomes markup. Outside an answer (the person's own words) the same text stays literal.
1967
+ */
1968
+ let inlineSlots = null;
1969
+ const CITE_ANCHOR = /^[a-z0-9-]{1,16}$/;
1970
+ const INLINE_DIRECTIVE = /:(cite|assume)\[([^\]\n]{1,120})\]/g;
1971
+
1972
+ function markdownEmphasis(html) {
1973
+ return html.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>').replace(/__([^_\n]+)__/g, '<strong>$1</strong>')
1974
+ .replace(/\*([^*\n]+)\*/g, '<em>$1</em>').replace(/_([^_\n]+)_/g, '<em>$1</em>');
1975
+ }
1976
+
1977
+ /** Plain text with emphasis and (inside an answer) directive slots; the slot markers are characters no text can hold. */
1978
+ function markdownRun(text) {
1979
+ if (!text) return '';
1980
+ const marked = inlineSlots ? text.replace(INLINE_DIRECTIVE, (all, kind, value) => {
1981
+ if (kind === 'cite' && !CITE_ANCHOR.test(value)) return all;
1982
+ const n = inlineSlots.push(kind === 'cite' ? { kind, anchor: value } : { kind, text: value }) - 1;
1983
+ return `${n}`;
1984
+ }) : text;
1985
+ return markdownEmphasis(escapeMarkdownHtml(marked)).replace(/(\d+)/g, '<span class="ai-chat-inline-slot" data-inline-slot="$1"></span>');
1986
+ }
1987
+
1988
+ /**
1989
+ * Text between code spans: links first, so their address is never parsed for anything. A link's words cannot hold a
1990
+ * directive (its `]` ends them) and are only escaped, so a marker never lands inside a link.
1991
+ */
1992
+ function markdownText(text) {
1993
+ const out = [];
1994
+ let last = 0;
1995
+ for (const match of text.matchAll(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g)) {
1996
+ out.push(markdownRun(text.slice(last, match.index)));
1997
+ out.push(`<a href="${escapeMarkdownHtml(match[2])}" target="_blank" rel="noreferrer">${markdownEmphasis(escapeMarkdownHtml(match[1]))}</a>`);
1998
+ last = match.index + match[0].length;
1999
+ }
2000
+ out.push(markdownRun(text.slice(last)));
2001
+ return out.join('');
2002
+ }
2003
+
1925
2004
  function markdownInline(value) {
1926
- let html = escapeMarkdownHtml(value);
1927
- html = html.replace(/`([^`\n]+)`/g, '<code>$1</code>');
1928
- html = html.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>');
1929
- html = html.replace(/__([^_\n]+)__/g, '<strong>$1</strong>');
1930
- html = html.replace(/\*([^*\n]+)\*/g, '<em>$1</em>');
1931
- html = html.replace(/_([^_\n]+)_/g, '<em>$1</em>');
1932
- return html.replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noreferrer">$1</a>');
2005
+ // The slot markers are private-use characters; any the text itself holds are shown as the replacement character,
2006
+ // so no text can forge a slot.
2007
+ const source = String(value ?? '').replace(/[]/g, '�');
2008
+ const out = [];
2009
+ let last = 0;
2010
+ // Code spans first: nothing inside one is a link, an emphasis or a directive. A span opens on a whole run of
2011
+ // backticks and closes on the next whole run of exactly that length on the same line; a run with no partner is text.
2012
+ // Linear in the text: each run's partner (the next run of its length) is found in one backward pass, and each run's
2013
+ // line in one forward pass, so a long answer full of short spans renders as fast as a short one.
2014
+ const runs = [...source.matchAll(/`+/g)];
2015
+ const partner = new Array(runs.length).fill(-1);
2016
+ const nextOfLength = new Map();
2017
+ for (let i = runs.length - 1; i >= 0; i -= 1) {
2018
+ partner[i] = nextOfLength.get(runs[i][0].length) ?? -1;
2019
+ nextOfLength.set(runs[i][0].length, i);
2020
+ }
2021
+ const line = new Array(runs.length);
2022
+ for (let i = 0, at = 0, count = 0; i < runs.length; i += 1) {
2023
+ for (; at < runs[i].index; at += 1) if (source.charCodeAt(at) === 10) count += 1;
2024
+ line[i] = count;
2025
+ }
2026
+ for (let i = 0; i < runs.length; i += 1) {
2027
+ const open = runs[i];
2028
+ const j = partner[i];
2029
+ if (open.index < last || j < 0 || line[j] !== line[i]) continue;
2030
+ const close = runs[j];
2031
+ const inner = source.slice(open.index + open[0].length, close.index);
2032
+ out.push(markdownText(source.slice(last, open.index)), `<code>${escapeMarkdownHtml(inner.replace(/^ (.*) $/, '$1'))}</code>`);
2033
+ last = close.index + close[0].length;
2034
+ i = j;
2035
+ }
2036
+ out.push(markdownText(source.slice(last)));
2037
+ return out.join('');
1933
2038
  }
1934
2039
 
1935
2040
  function markdownHtml(value, depth = 0) {
@@ -2043,6 +2148,306 @@
2043
2148
  .trim();
2044
2149
  }
2045
2150
 
2151
+ /* ---- #2437: the sources an answer cited ------------------------------------------------------------------------------
2152
+ * FloLess writes a `citation` event for each floless_cite call; every label, identity and read state in it is FloLess's
2153
+ * own. An answer's turn folds them by anchor (a later source for an anchor replaces it); resolved sources are numbered
2154
+ * in the order they were first cited, and the number is the same on the marker in the text and on its chip. A chip says
2155
+ * what is guaranteed, in words: found, read by the AI, and never "checked" — nothing here checks a claim.
2156
+ */
2157
+ const CITATION_READ = {
2158
+ 'whole-sheet': 'yes, the whole sheet', tiles: 'yes, enlarged in 9 tiles', yes: 'yes', no: 'no', unknown: 'not recorded',
2159
+ };
2160
+
2161
+ function citationIndex(turnId) {
2162
+ const byAnchor = new Map();
2163
+ const order = [];
2164
+ for (const event of state.events) {
2165
+ if (event.type !== 'citation' || !turnId || event.turnId !== turnId) continue;
2166
+ const entries = Array.isArray(event.payload?.entries) ? event.payload.entries : [];
2167
+ entries.forEach((entry, index) => {
2168
+ if (!entry || typeof entry.anchor !== 'string' || !CITE_ANCHOR.test(entry.anchor)) return;
2169
+ if (!byAnchor.has(entry.anchor)) order.push(entry.anchor);
2170
+ // The conversation and owner are taken now, from what is being rendered: a chip clicked later opens THIS
2171
+ // conversation's source even while the app is between conversations (QA #2437: after Open in Knowledge).
2172
+ byAnchor.set(entry.anchor, { anchor: entry.anchor, entry, citationId: event.eventId, index, number: 0,
2173
+ chatId: state.chat?.chatId ?? null, owner: ownerQuery() });
2174
+ });
2175
+ }
2176
+ let n = 0;
2177
+ for (const anchor of order) { const row = byAnchor.get(anchor); row.number = row.entry.status === 'resolved' ? ++n : 0; }
2178
+ return { byAnchor, order };
2179
+ }
2180
+
2181
+ function citationProvenance(read) {
2182
+ return `Found: yes · Read by AI: ${CITATION_READ[read] || CITATION_READ.no} · Checked: no`;
2183
+ }
2184
+
2185
+ function citationUrl(row, what, extra = '') {
2186
+ if (!row.chatId) return null;
2187
+ return `/api/chat/conversations/${encodeURIComponent(row.chatId)}/citations/${encodeURIComponent(row.citationId)}/${row.index}/${what}?${row.owner}${extra}`;
2188
+ }
2189
+
2190
+ /** An answer's text, with its source markers made from FloLess's record of what it cited. */
2191
+ function renderAnswerBody(body, text, turnId) {
2192
+ inlineSlots = [];
2193
+ let slots = [];
2194
+ try { body.innerHTML = markdownHtml(text); }
2195
+ finally { slots = inlineSlots; inlineSlots = null; }
2196
+ if (slots.length) fillInlineSlots(body, slots, turnId);
2197
+ }
2198
+
2199
+ /** The markers an answer's directives asked for, built from FloLess's own record of what was cited. */
2200
+ function fillInlineSlots(body, slots, turnId) {
2201
+ const index = citationIndex(turnId);
2202
+ for (const slot of body.querySelectorAll('[data-inline-slot]')) {
2203
+ const spec = slots[Number(slot.dataset.inlineSlot)];
2204
+ if (!spec) { slot.remove(); continue; }
2205
+ if (spec.kind === 'assume') {
2206
+ const tag = document.createElement('span'); tag.className = 'ai-chat-assume';
2207
+ tag.textContent = 'Assumption';
2208
+ tag.dataset.tip = `The AI marked this as an assumption: ${spec.text}`;
2209
+ slot.replaceWith(tag);
2210
+ continue;
2211
+ }
2212
+ const row = index.byAnchor.get(spec.anchor) ?? null;
2213
+ const resolved = row?.entry.status === 'resolved';
2214
+ const marker = button(resolved ? String(row.number) : '?', 'shell.chat-cite-anchor', `ai-chat-cite${resolved ? '' : ' unresolved'}`);
2215
+ marker.dataset.turnId = turnId || '';
2216
+ marker.dataset.anchor = spec.anchor;
2217
+ const label = resolved ? row.entry.label : 'no source';
2218
+ // No citation for this anchor on this page is "none recorded", not "none found": the AI may have given none, or the
2219
+ // record has not reached this page yet.
2220
+ const missing = row ? 'No source was found for this claim' : 'No source is recorded for this claim';
2221
+ marker.dataset.commandInstanceLabel = label;
2222
+ marker.setAttribute('aria-label', resolved ? `Source ${row.number}: ${label}` : missing);
2223
+ marker.dataset.tip = resolved ? `${label} · ${citationProvenance(row.entry.read)}` : missing;
2224
+ marker.addEventListener('click', () => {
2225
+ const chip = [...ui.feed.querySelectorAll('.ai-chat-source')].find((node) => node.dataset.turnId === turnId && node.dataset.anchor === spec.anchor);
2226
+ if (!chip) { announce(resolved ? 'Its source is listed under the answer.' : 'The AI gave no source for this claim.'); return; }
2227
+ chip.scrollIntoView({ block: 'nearest' });
2228
+ chip.classList.remove('answer-jump'); void chip.offsetWidth; chip.classList.add('answer-jump');
2229
+ (chip.querySelector('button') ?? chip).focus({ preventScroll: true });
2230
+ });
2231
+ slot.replaceWith(marker);
2232
+ }
2233
+ }
2234
+
2235
+ /** One chip: the sheet or page, what FloLess can vouch for, and (unresolved) the person's two ways on. */
2236
+ function citationChip(turnId, row) {
2237
+ const chip = document.createElement('span');
2238
+ chip.className = 'ai-chat-attachment ai-chat-source';
2239
+ chip.dataset.turnId = turnId || '';
2240
+ chip.dataset.anchor = row.anchor;
2241
+ const number = document.createElement('span'); number.className = 'ai-chat-source-n';
2242
+ number.textContent = row.number ? String(row.number) : '?';
2243
+ chip.append(number);
2244
+ const entry = row.entry;
2245
+ if (entry.status !== 'resolved') {
2246
+ chip.classList.add('unresolved');
2247
+ const why = document.createElement('span'); why.className = 'ai-chat-source-why';
2248
+ why.textContent = `No source: ${entry.reason}`;
2249
+ const ask = button('Ask for the source', 'shell.chat-cite-ask', 'ai-chat-source-action');
2250
+ ask.dataset.tip = 'Puts a question in the message box asking where this comes from. Nothing is sent until you press Send';
2251
+ ask.addEventListener('click', () => addToMessageBox(`${unsourcedClaim(turnId, row.anchor)}: which sheet or Knowledge page does it come from? Cite it, or say plainly that it is an assumption.`));
2252
+ const assume = button('Go on with this as an assumption', 'shell.chat-cite-assume', 'ai-chat-source-action');
2253
+ assume.dataset.tip = 'Puts a message in the message box asking the AI to carry on with it as a labelled assumption. Nothing is sent until you press Send';
2254
+ assume.addEventListener('click', () => addToMessageBox(`${unsourcedClaim(turnId, row.anchor)}: go on with it as an assumption, and label it as an assumption wherever you use it.`));
2255
+ chip.append(why, ask, assume);
2256
+ return chip;
2257
+ }
2258
+ if (entry.kind === 'sheet') {
2259
+ const thumb = document.createElement('img'); thumb.alt = ''; thumb.loading = 'lazy';
2260
+ // A preview is only the picture the AI was shown (never a render): a tiles look or a changed picture has none.
2261
+ const preview = citationUrl(row, 'image', '&thumb=1');
2262
+ if (preview) {
2263
+ thumb.src = preview;
2264
+ thumb.addEventListener('error', () => thumb.remove(), { once: true });
2265
+ chip.append(thumb);
2266
+ }
2267
+ }
2268
+ const open = button(entry.label, 'shell.chat-cite-open', 'ai-chat-answer-open ai-chat-source-open');
2269
+ open.dataset.commandInstanceLabel = entry.label;
2270
+ open.setAttribute('aria-label', `Open ${entry.label}`);
2271
+ open.dataset.tip = citationProvenance(entry.read);
2272
+ open.addEventListener('click', () => openCitedSource(row, turnId));
2273
+ const marks = document.createElement('span'); marks.className = 'ai-chat-source-marks';
2274
+ marks.textContent = entry.read === 'no' ? 'FOUND' : 'FOUND · READ BY AI';
2275
+ chip.append(open, marks);
2276
+ return chip;
2277
+ }
2278
+
2279
+ /** The Sources row of one answer, shown once, under the answer, after its last citation. */
2280
+ function renderCitationSources(event) {
2281
+ const last = state.events.filter((candidate) => candidate.type === 'citation' && candidate.turnId === event.turnId).at(-1);
2282
+ if (last !== event) return null;
2283
+ const index = citationIndex(event.turnId);
2284
+ if (!index.order.length) return null;
2285
+ return citationRow(index.order.map((anchor) => citationChip(event.turnId, index.byAnchor.get(anchor))));
2286
+ }
2287
+
2288
+ /** #2436: a Knowledge citation written before #2437 — its pages as chips; whether the AI read them was never recorded. */
2289
+ function renderLegacyKnowledgeCitation(event) {
2290
+ const pages = Array.isArray(event.payload?.pages) ? event.payload.pages.filter((page) => page && typeof page.slug === 'string') : [];
2291
+ if (!pages.length) return null;
2292
+ return citationRow(pages.map((page, i) => {
2293
+ const label = typeof page.title === 'string' && page.title ? page.title : page.slug;
2294
+ const chip = document.createElement('span'); chip.className = 'ai-chat-attachment ai-chat-source';
2295
+ const number = Object.assign(document.createElement('span'), { className: 'ai-chat-source-n', textContent: String(i + 1) });
2296
+ const open = button(label, 'shell.chat-cite-open-knowledge', 'ai-chat-answer-open ai-chat-source-open');
2297
+ open.dataset.commandInstanceLabel = label;
2298
+ open.setAttribute('aria-label', `Open ${label}`);
2299
+ open.dataset.tip = citationProvenance('unknown');
2300
+ open.addEventListener('click', () => {
2301
+ if (window.flolessWorkspaces?.openKnowledgePage) window.flolessWorkspaces.openKnowledgePage(event.payload.projectId, page.slug, event.payload.generationId);
2302
+ else announce('Knowledge is not available on this page.');
2303
+ });
2304
+ const marks = Object.assign(document.createElement('span'), { className: 'ai-chat-source-marks', textContent: 'FOUND' });
2305
+ chip.append(number, open, marks);
2306
+ return chip;
2307
+ }));
2308
+ }
2309
+
2310
+ function citationRow(chips) {
2311
+ const wrap = document.createElement('div'); wrap.className = 'ai-chat-sources';
2312
+ const head = document.createElement('span'); head.className = 'ai-chat-sources-head';
2313
+ head.textContent = 'Sources the AI gave for this answer';
2314
+ head.dataset.tip = 'FloLess found each source and says whether the AI was shown it. It does not check that a source supports the claim.';
2315
+ const list = document.createElement('div'); list.className = 'ai-chat-sources-list';
2316
+ list.append(...chips);
2317
+ wrap.append(head, list);
2318
+ return wrap;
2319
+ }
2320
+
2321
+ /**
2322
+ * Which claim a "no source" chip is about, in words the AI can find: the answer it is in (by its time) and the text
2323
+ * just before its "?" marker. Several "?" claims, or a chip under an older answer, each name their own.
2324
+ */
2325
+ function unsourcedClaim(turnId, anchor) {
2326
+ const marker = [...ui.feed.querySelectorAll('button.ai-chat-cite')].find((node) => node.dataset.turnId === (turnId || '') && node.dataset.anchor === anchor);
2327
+ // The answer is found by its turn even when the AI put no marker after the claim (it is not obliged to).
2328
+ const answer = marker?.closest('.ai-chat-message')
2329
+ ?? [...ui.feed.querySelectorAll('.ai-chat-message.assistant')].filter((node) => node.dataset.turnId === turnId).at(-1);
2330
+ const when = answer?.querySelector('time')?.textContent?.trim();
2331
+ const block = marker?.closest('p, li, h1, h2, h3, blockquote');
2332
+ let before = '';
2333
+ if (block && marker) {
2334
+ // The block's text up to the marker, read in document order; other markers and tags add no words.
2335
+ const parts = [];
2336
+ const walk = (node) => {
2337
+ if (node === marker) return true;
2338
+ if (node.nodeType === 3) parts.push(node.textContent);
2339
+ else if (!(node.matches?.('button.ai-chat-cite, .ai-chat-assume'))) for (const child of node.childNodes) if (walk(child)) return true;
2340
+ return false;
2341
+ };
2342
+ walk(block);
2343
+ before = parts.join('').replace(/\s+/g, ' ').trim();
2344
+ }
2345
+ const words = [...before];
2346
+ const claim = words.length > 90 ? `…${words.slice(-90).join('').trimStart()}` : before;
2347
+ const where = when ? `in your answer of ${when}` : 'in your answer';
2348
+ return claim ? `For this claim ${where}, which has no source: “${claim}”` : `For the claim with no source ${where}`;
2349
+ }
2350
+
2351
+ /** Never overwrites what the person is writing: the text goes after it. */
2352
+ function addToMessageBox(text) {
2353
+ const held = ui.input.value.trim();
2354
+ putInMessageBox(held ? `${ui.input.value.replace(/\s+$/, '')}\n\n${text}` : text);
2355
+ }
2356
+
2357
+ /** The cited sheet or page, in a themed dialog over the app; it shows only what the server re-checked just now. */
2358
+ /**
2359
+ * The chip's open button as it is NOW: the feed repaints, so the node that was clicked may be gone; the live one is
2360
+ * found again by its answer and anchor, for focus to return to.
2361
+ */
2362
+ function liveCitationOpener(turnId, anchor) {
2363
+ const chip = [...ui.feed.querySelectorAll('.ai-chat-source')].find((node) => node.dataset.turnId === (turnId || '') && node.dataset.anchor === anchor);
2364
+ return chip?.querySelector('.ai-chat-source-open') ?? null;
2365
+ }
2366
+
2367
+ async function openCitedSource(row, turnId) {
2368
+ const entry = row.entry;
2369
+ const dialog = document.createElement('dialog'); dialog.className = 'ai-chat-source-viewer';
2370
+ dialog.setAttribute('aria-label', entry.label);
2371
+ const head = document.createElement('div'); head.className = 'ai-chat-source-viewer-head';
2372
+ const title = Object.assign(document.createElement('strong'), { textContent: entry.label });
2373
+ const close = button('Close', 'shell.chat-cite-close', 'ai-chat-source-viewer-close');
2374
+ // Closing is done here, not left to the dialog's own `close` event, which an embedding browser may never fire: the
2375
+ // viewer is removed, its picture released and focus handed back to the chip, once, whichever way it closes.
2376
+ let picture = null;
2377
+ let finished = false;
2378
+ const finish = () => {
2379
+ if (finished) return;
2380
+ finished = true;
2381
+ if (dialog.open) dialog.close();
2382
+ dialog.remove();
2383
+ if (picture) URL.revokeObjectURL(picture);
2384
+ liveCitationOpener(turnId, row.anchor)?.focus({ preventScroll: true });
2385
+ };
2386
+ close.addEventListener('click', finish);
2387
+ dialog.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.preventDefault(); finish(); } });
2388
+ dialog.addEventListener('close', finish);
2389
+ head.append(title, close);
2390
+ const note = Object.assign(document.createElement('span'), { className: 'ai-chat-source-viewer-note', textContent: citationProvenance(entry.read) });
2391
+ const body = document.createElement('div'); body.className = 'ai-chat-source-viewer-body';
2392
+ const status = Object.assign(document.createElement('p'), { className: 'ai-chat-source-viewer-status', textContent: 'Opening…' });
2393
+ status.setAttribute('role', 'status');
2394
+ body.append(status);
2395
+ dialog.append(head, note, body);
2396
+ document.body.append(dialog);
2397
+ dialog.showModal();
2398
+ const refused = async (response) => {
2399
+ if (response.status === 404) return 'FloLess no longer holds this source, or its project is no longer part of this conversation.';
2400
+ if (response.status === 410) return 'This Knowledge page has changed since the answer, so FloLess does not show it as the page the answer cited.';
2401
+ // 503: FloLess could not check it just now; anything else is said as "try again", never as "gone".
2402
+ const said = await response.json().catch(() => null);
2403
+ return typeof said?.message === 'string' && said.message ? said.message : 'FloLess could not open this source right now. Try again in a moment.';
2404
+ };
2405
+ const SHOWN = {
2406
+ 'as-seen': 'The sheet picture the AI was shown.',
2407
+ 'from-source:tiles': 'The whole sheet, rendered from its source drawing. The AI saw this sheet enlarged in tiles.',
2408
+ 'from-source:changed': 'Rendered from the source drawing: the sheet picture FloLess holds has changed since the AI looked at it.',
2409
+ 'from-source:missing': 'Rendered from the source drawing: FloLess no longer holds the sheet picture the AI was shown.',
2410
+ 'from-source:unchecked': 'Rendered from the source drawing: FloLess could not check the stored sheet picture just now.',
2411
+ };
2412
+ try {
2413
+ if (!citationUrl(row, 'page')) {
2414
+ status.textContent = 'Open this conversation again to open its sources.';
2415
+ return;
2416
+ }
2417
+ if (entry.kind === 'sheet') {
2418
+ const response = await fetch(citationUrl(row, 'image'), { credentials: 'same-origin', cache: 'no-store' });
2419
+ if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
2420
+ const shown = response.headers.get('X-FloLess-Shown') || 'as-seen';
2421
+ const bytes = await response.blob();
2422
+ // Checked after every wait: a viewer closed meanwhile creates nothing it would never release.
2423
+ if (finished) return;
2424
+ picture = URL.createObjectURL(bytes);
2425
+ const image = Object.assign(document.createElement('img'), { src: picture, alt: `${entry.label}${shown === 'as-seen' ? '' : ', rendered from the source drawing'}` });
2426
+ status.textContent = SHOWN[shown] || SHOWN['as-seen'];
2427
+ body.append(image);
2428
+ return;
2429
+ }
2430
+ const response = await fetch(citationUrl(row, 'page'), { credentials: 'same-origin', cache: 'no-store' });
2431
+ if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
2432
+ const { page } = await response.json();
2433
+ if (finished) return;
2434
+ status.textContent = 'The Knowledge page as it was when the answer cited it.';
2435
+ const article = document.createElement('div'); article.className = 'ai-chat-message-body ai-chat-source-viewer-page';
2436
+ article.innerHTML = markdownHtml(page.body);
2437
+ const knowledge = button('Open in Knowledge', 'shell.chat-cite-open-knowledge', 'ai-chat-source-viewer-knowledge');
2438
+ knowledge.addEventListener('click', () => {
2439
+ finish();
2440
+ if (window.flolessWorkspaces?.openKnowledgePage) window.flolessWorkspaces.openKnowledgePage(page.projectId, page.slug, page.generationId);
2441
+ else announce('Knowledge is not available on this page.');
2442
+ });
2443
+ body.append(article);
2444
+ dialog.append(knowledge);
2445
+ } catch (error) {
2446
+ console.error('[chat] a cited source could not be opened', error);
2447
+ if (!finished) status.textContent = 'FloLess could not open this source right now. Try again in a moment.';
2448
+ }
2449
+ }
2450
+
2046
2451
  function openChatAttachment(attachment) {
2047
2452
  return request(`/api/chat/conversations/${encodeURIComponent(state.chat.chatId)}/attachments/${encodeURIComponent(attachment.attachmentId)}/open`, {
2048
2453
  method: 'POST', body: JSON.stringify({ owner: state.scope.owner }),
@@ -2099,7 +2504,9 @@
2099
2504
  head.append(who, time); item.append(head);
2100
2505
  if (role === 'assistant' || visibleText) {
2101
2506
  const body = document.createElement('div'); body.className = 'ai-chat-message-body';
2102
- body.innerHTML = markdownHtml(visibleText);
2507
+ // #2437: only an answer's own directives become source markers; the person's words stay literal.
2508
+ if (role === 'assistant') renderAnswerBody(body, visibleText, event.turnId);
2509
+ else body.innerHTML = markdownHtml(visibleText);
2103
2510
  item.append(body);
2104
2511
  }
2105
2512
  if (role === 'user' && Array.isArray(event.payload?.attachmentIds)) {
@@ -2120,6 +2527,13 @@
2120
2527
  line.textContent = about;
2121
2528
  item.append(line);
2122
2529
  }
2530
+ const mentioned = role === 'user' && event.payload?.mentions ? mentionsLine(event.payload.mentions) : '';
2531
+ if (mentioned) {
2532
+ const line = document.createElement('span'); line.className = 'ai-chat-message-subjects ai-chat-message-mentions';
2533
+ line.textContent = mentioned.text;
2534
+ line.setAttribute('aria-label', mentioned.spoken);
2535
+ item.append(line);
2536
+ }
2123
2537
  if (role === 'user' && (event.payload?.followup || event.payload?.deliveryState)) {
2124
2538
  const delivery = followupDelivery(event);
2125
2539
  const deliveryReceipt = [...state.events].reverse().find((candidate) => candidate.type === 'followup-status'
@@ -2861,7 +3275,20 @@
2861
3275
  const actionCards = new Map();
2862
3276
  const ACTION_CARDS_KEPT = 200;
2863
3277
  const ACTION_CONFIRM_VERBS = { 'workflows.run': 'Run it', 'routines.run': 'Run it', 'projects.archive': 'Archive it',
2864
- 'projects.unarchive': 'Bring it back', 'workflows.stop': 'Stop it' };
3278
+ 'projects.unarchive': 'Bring it back', 'workflows.stop': 'Stop it',
3279
+ // #2290: the button says the consequence, never a reversible-sounding verb for something that is not.
3280
+ 'app.stop': 'Stop FloLess', 'workflows.delete': 'Delete it', 'requests.clear': 'Delete it', 'requests.clear-all': 'Delete them',
3281
+ 'routines.delete': 'Delete it', 'templates.delete': 'Delete it', 'requests.discard-read': 'Discard it', 'requests.keep-read': 'Keep it',
3282
+ 'workflows.fork': 'Fork it', 'workflows.copy': 'Copy it', 'workflows.adopt': 'Make it mine', 'workflows.restore': 'Restore it',
3283
+ 'workflows.apply-update': 'Update it', 'workflows.freeze-step': 'Freeze it', 'workflows.unfreeze-step': 'Unfreeze it',
3284
+ 'workflows.rename-installed': 'Rename it', 'workflows.reinstall-approved-tool': 'Reinstall it', 'workflows.run-live': 'Start it',
3285
+ 'requests.run': 'Start it', 'requests.desktop-launch': 'Open the app', 'routines.create': 'Create it',
3286
+ 'routines.create-for-agent': 'Create it', 'routines.update': 'Save changes',
3287
+ // #2363: what each button does on the window's side of the card, so none of them says a bare "Do it".
3288
+ 'models.start-import': 'Choose the file', 'tekla.start-upload': 'Choose the source', 'models.retry-import': 'Try it again',
3289
+ 'models.cancel-import': 'Cancel it', 'tekla.cancel-import': 'Cancel it', 'parser-setup.start-fresh': 'Open the review',
3290
+ 'models.retry-revit-setup': 'Try setup again', 'models.retry-tekla-setup': 'Try setup again',
3291
+ 'workspace-root.review-retirement': 'Open the review', 'workspace-root.confirm-retirement': 'Record it' };
2865
3292
  const ACTION_EYEBROWS = { write: 'Suggested change', destructive: 'Needs your OK', 'human-only': 'Your decision' };
2866
3293
  const ACTION_FINAL = new Set(['done', 'failed', 'cancelled', 'declined', 'expired', 'superseded', 'unknown']);
2867
3294
 
@@ -2874,8 +3301,44 @@
2874
3301
  }
2875
3302
  const fromServer = latest ? { state: latest.state, result: latest.result || null, supersededBy: latest.supersededBy || null, next: latest.next || null } : null;
2876
3303
  // A click's own answer is newer than the journal until the journal catches up; a final journal state always wins.
2877
- if (entry?.local && !(fromServer && ACTION_FINAL.has(fromServer.state))) return entry.local;
2878
- return fromServer || { state: 'proposed', result: null, supersededBy: null };
3304
+ if (fromServer && ACTION_FINAL.has(fromServer.state)) return fromServer;
3305
+ // #2266: the stored proposal, read once when the card was painted unfinished. A journal write that failed leaves the
3306
+ // card saying "Running…" over a stored "done"; the stored state is newer when it is further along.
3307
+ if (entry?.stored && ACTION_FINAL.has(entry.stored.state)) return entry.stored;
3308
+ if (entry?.local) return entry.local;
3309
+ const journal = fromServer || { state: 'proposed', result: null, supersededBy: null };
3310
+ if (entry?.stored && actionStateRank(entry.stored.state) > actionStateRank(journal.state)) return entry.stored;
3311
+ return journal;
3312
+ }
3313
+
3314
+ /** How far along a card's state is: waiting, then running, then any final state. */
3315
+ function actionStateRank(value) { return value === 'proposed' ? 0 : value === 'executing' ? 1 : 2; }
3316
+
3317
+ /**
3318
+ * #2266: read a card's proposal from FloLess once, when it is painted unfinished (a chat opened or reloaded), and
3319
+ * repaint it if the stored state is further along than the conversation recorded. A failed read leaves the card as
3320
+ * the conversation has it; nothing is retried until the chat is opened again.
3321
+ */
3322
+ async function syncActionProposal(proposalId) {
3323
+ try {
3324
+ const path = `/api/actions/proposals/${encodeURIComponent(proposalId)}`;
3325
+ await globalThis.flolessStartupAdmission?.admit(path);
3326
+ const response = await fetch(path, { credentials: 'same-origin' });
3327
+ // FloLess no longer has it: nothing newer to show. Anything else that is not an answer is tried again (below).
3328
+ if (response.status === 404) return;
3329
+ const body = response.ok ? await response.json().catch(() => null) : null;
3330
+ const p = body?.ok === true ? body.proposal : null;
3331
+ if (!p || typeof p.state !== 'string') throw new Error(`the stored proposal could not be read (${response.status})`);
3332
+ const entry = actionCards.get(proposalId);
3333
+ if (!entry) return;
3334
+ entry.stored = { state: p.state, result: p.result || null, supersededBy: p.supersededBy || null, next: p.next || null };
3335
+ repaintActionCards();
3336
+ } catch (error) {
3337
+ // FloLess could not be reached: the conversation's own record stays on the card, and the next paint asks again.
3338
+ const entry = actionCards.get(proposalId);
3339
+ if (entry) entry.synced = false;
3340
+ console.warn('[floless] a suggested action card could not be checked against FloLess', error);
3341
+ }
2879
3342
  }
2880
3343
 
2881
3344
  function renderActionProposal(event) {
@@ -2888,6 +3351,8 @@
2888
3351
  while (actionCards.size > ACTION_CARDS_KEPT) actionCards.delete(actionCards.keys().next().value);
2889
3352
  }
2890
3353
  const current = actionProposalState(proposalId);
3354
+ // #2266: an unfinished card asks FloLess once whether it has moved on (see syncActionProposal).
3355
+ if (!entry.synced && !ACTION_FINAL.has(current.state)) { entry.synced = true; void syncActionProposal(proposalId); }
2891
3356
  const signature = JSON.stringify([event.eventId, current.state, current.result?.message || null, current.supersededBy, current.next || null, entry.busy, entry.error]);
2892
3357
  if (entry.node && entry.signature === signature) return entry.node;
2893
3358
  entry.node = paintActionProposal(event, payload, proposalId, entry, current);
@@ -2917,10 +3382,24 @@
2917
3382
  return control;
2918
3383
  }
2919
3384
 
3385
+ /**
3386
+ * Show one connection in its project's model editor, selected and framed (#2450). Resolves the editor's
3387
+ * own outcome (see `openConnection` in workspaces.js), or null when the shell cannot do it here. Throws
3388
+ * a sentence written for the person (`plain`) when the editor was never reached.
3389
+ */
3390
+ async function openConnectionInModel(projectId, jointId, extra = {}) {
3391
+ if (typeof window.flolessWorkspaces?.openConnection !== 'function') return null;
3392
+ // #2450: `extra` asks the editor to open its "Raise an RFI" dialog too, with one check first.
3393
+ return await window.flolessWorkspaces.openConnection({ projectId, jointId,
3394
+ ...(extra.raiseRfi === true ? { raiseRfi: true } : {}), ...(typeof extra.checkId === 'string' && extra.checkId ? { checkId: extra.checkId } : {}) });
3395
+ }
3396
+
2920
3397
  /** Open the screen a human-only action names, or the one showing what a finished action made. Nothing runs. */
2921
3398
  async function openActionScreen(screen) {
2922
3399
  if (screen?.view === 'page' && screen.pageHome && screen.pageId && typeof window.flolessPages?.open === 'function') {
2923
- return await window.flolessPages.open(screen.pageHome, screen.pageId);
3400
+ // The exact version a finished action made, when it says one: a later version must not stand in for it.
3401
+ const version = Number.isInteger(screen.pageVersion) && screen.pageVersion > 0 ? screen.pageVersion : undefined;
3402
+ return await window.flolessPages.open(screen.pageHome, screen.pageId, version);
2924
3403
  }
2925
3404
  if (screen?.view === 'chat' && screen.chatId && screen.owner) {
2926
3405
  await openConversation(screen.chatId, { owner: screen.owner });
@@ -2932,15 +3411,106 @@
2932
3411
  if (screen?.view === 'workflow' && screen.workflowId && typeof window.flolessBridge?.openApp === 'function') {
2933
3412
  await window.flolessBridge.openApp(screen.workflowId); return true;
2934
3413
  }
3414
+ if (screen?.view === 'requests' && screen.requestId && typeof window.flolessBridge?.openRequest === 'function') {
3415
+ await window.flolessBridge.openRequest(screen.requestId); return true;
3416
+ }
3417
+ // #2450: one connection, selected and framed in the project's model editor. Like every screen here it
3418
+ // answers only whether it opened; the readiness card reads the editor's full outcome itself.
3419
+ if (screen?.view === 'connection' && screen.projectId && screen.jointId) {
3420
+ const outcome = await openConnectionInModel(screen.projectId, screen.jointId);
3421
+ return outcome?.ok === true || outcome?.superseded === true;
3422
+ }
3423
+ if (screen?.view === 'project' && screen.step === 'drawings' && screen.projectId && typeof window.flolessWorkspaces?.openDrawingsStep === 'function') {
3424
+ await window.flolessWorkspaces.openDrawingsStep(screen.projectId); return true;
3425
+ }
2935
3426
  if (screen?.view === 'project' && screen.projectId && typeof window.flolessWorkspaces?.openChatOwner === 'function') {
2936
3427
  await window.flolessWorkspaces.openChatOwner({ kind: 'project', projectId: screen.projectId }); return true;
2937
3428
  }
2938
3429
  if (['workspaces', 'workflows'].includes(screen?.view) && typeof window.flolessWorkspaces?.setMode === 'function') {
2939
3430
  await window.flolessWorkspaces.setMode(screen.view); return true;
2940
3431
  }
3432
+ // Automatic tool updates: the dialog where the person reads the wording and chooses (it opens nothing else, runs nothing).
3433
+ if (screen?.view === 'tool-update-policy' && typeof window.openToolUpdatePolicy === 'function') {
3434
+ window.openToolUpdatePolicy(); return true;
3435
+ }
3436
+ // Requests, at the request the screen names.
3437
+ if (screen?.view === 'requests' && typeof window.flolessBridge?.openRequest === 'function') {
3438
+ await window.flolessBridge.openRequest(screen.requestId || null); return true;
3439
+ }
2941
3440
  return false;
2942
3441
  }
2943
3442
 
3443
+ /** Take a confirmed step FloLess's own window must take (#2290). Returns a plain failure sentence, or '' when it went. */
3444
+ async function runBrowserStep(step) {
3445
+ if (step?.flow === 'stop-app') {
3446
+ // The menu's own Stop FloLess: it asks about anything not saved, then closes FloLess and shows the stopped screen.
3447
+ if (typeof window.flolessLeaveGuard?.stopApp !== 'function') return 'FloLess couldn’t start Stop from here. Use Stop FloLess in the ≡ menu.';
3448
+ try {
3449
+ // It resolves false when nothing was stopped (you cancelled, or a stop is already under way): never "Done" over that.
3450
+ if ((await window.flolessLeaveGuard.stopApp()) === false) return 'FloLess was not stopped: you cancelled, or a stop is already under way. Use Stop FloLess in the ≡ menu when you are ready.';
3451
+ } catch {
3452
+ return 'FloLess could not be stopped from here. Use Stop FloLess in the ≡ menu.';
3453
+ }
3454
+ return '';
3455
+ }
3456
+ if (step?.flow === 'desktop-launch') {
3457
+ if (!step.requestId) return 'FloLess could not tell which request to open in the desktop app. Open it from Requests.';
3458
+ try {
3459
+ const response = await fetch(`/api/requests/${encodeURIComponent(step.requestId)}/desktop-handoff/launch`, {
3460
+ method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' },
3461
+ body: JSON.stringify({ provider: step.provider, attemptId: step.attemptId }),
3462
+ });
3463
+ if (response.ok) return '';
3464
+ // The route's own words are not always plain English; the person gets one fixed sentence and Requests shows the detail.
3465
+ return 'The desktop app was not opened. Try it from Requests.';
3466
+ } catch {
3467
+ return 'FloLess could not be reached to open the desktop app. Check that it is still running.';
3468
+ }
3469
+ }
3470
+ if (step?.flow === 'model-source') {
3471
+ // #2363: the project's own Source step presses its own Replace / Try again / Cancel control, so the real call
3472
+ // runs with this window's editor session. It answers a plain sentence when it could not, or when the person must act.
3473
+ if (typeof window.flolessWorkspaces?.modelSourceStep !== 'function') return 'FloLess could not open the project from here. Open it from Workspaces and use its Source step.';
3474
+ try { return String((await window.flolessWorkspaces.modelSourceStep(step)) || ''); }
3475
+ catch { return 'FloLess could not open the project’s Source step from here. Open it from Workspaces.'; }
3476
+ }
3477
+ if (step?.flow === 'knowledge-pick') {
3478
+ // #2399 slice 0b: the project's Knowledge step opens its own file picker; what the person picks there is added.
3479
+ if (typeof window.flolessWorkspaces?.knowledgePickStep !== 'function') return 'FloLess could not open the project from here. Open it from Workspaces and use its Knowledge step.';
3480
+ try { return String((await window.flolessWorkspaces.knowledgePickStep(step)) || ''); }
3481
+ catch { return 'FloLess could not open the project’s Knowledge step from here. Open it from Workspaces.'; }
3482
+ }
3483
+ if (step?.flow === 'parser-setup') {
3484
+ if (typeof window.flolessParserSetupRecovery?.open !== 'function') return 'FloLess could not open the setup review from here. Use the setup card on the Workspaces screen.';
3485
+ try { const said = await window.flolessParserSetupRecovery.open(step.appId); return typeof said === 'string' ? said : ''; }
3486
+ catch { return 'FloLess could not open the setup review from here. Use the setup card on the Workspaces screen.'; }
3487
+ }
3488
+ if (step?.flow === 'workspace-root') {
3489
+ if (typeof window.flolessWorkspaceRootReview !== 'function') return 'FloLess could not open the saved directories from here. Use the Workspace directory button on the Workspaces screen.';
3490
+ try { return String((await window.flolessWorkspaceRootReview(step)) || ''); }
3491
+ catch { return 'FloLess could not open the saved directories from here. Use the Workspace directory button on the Workspaces screen.'; }
3492
+ }
3493
+ return 'FloLess did not recognise the step this card asked its window to take, so it did nothing. Try it from the screen instead.';
3494
+ }
3495
+ /**
3496
+ * Tell FloLess how a step this window took for a confirmed card went: done, or not done with the sentence shown here.
3497
+ * Until it is told, the card stays running (a restart marks it "not known"), so a failed report only leaves it
3498
+ * honest, never "done". Returns the settled proposal, or null when the report did not land.
3499
+ */
3500
+ async function reportBrowserStep(proposalId, failed) {
3501
+ try {
3502
+ const response = await fetch(`/api/actions/proposals/${encodeURIComponent(proposalId)}/step`, {
3503
+ method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' },
3504
+ body: JSON.stringify(failed ? { done: false, note: String(failed) } : { done: true }),
3505
+ });
3506
+ const body = await response.json().catch(() => null);
3507
+ return response.ok && body?.ok === true ? body.proposal || null : null;
3508
+ } catch { return null; }
3509
+ }
3510
+ // The terminal-request dialog takes the same steps for a request a terminal made (terminal-requests.js).
3511
+ window.flolessRunBrowserStep = runBrowserStep;
3512
+ window.flolessReportBrowserStep = reportBrowserStep;
3513
+
2944
3514
  async function sendActionProposal(proposalId, verb) {
2945
3515
  const response = await fetch(`/api/actions/proposals/${encodeURIComponent(proposalId)}/${verb}`, {
2946
3516
  method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, body: '{}',
@@ -2962,6 +3532,17 @@
2962
3532
  if (ok) {
2963
3533
  entry.local = { state: body.proposal?.state || (verb === 'decline' ? 'declined' : 'executing'), result: body.proposal?.result || null, supersededBy: null };
2964
3534
  announce(verb === 'confirm' ? `${title}: started.` : verb === 'decline' ? `Not now: ${title}.` : `Asked ${title} to stop.`);
3535
+ // #2290: a step only this window may take (its route checks the window's own origin) is taken here, now that the
3536
+ // person confirmed it: the same flow the menu or the Requests button runs.
3537
+ if (verb === 'confirm' && event.payload?.browserStep) {
3538
+ const failed = await runBrowserStep(event.payload.browserStep);
3539
+ if (failed) entry.error = failed;
3540
+ // The record says how the step went, so neither the card nor the AI calls it done when it was not. A Stop FloLess
3541
+ // that went ahead is settled by the server when it accepts the stop: this window's requests are already stopped.
3542
+ const stopped = event.payload.browserStep.flow === 'stop-app' && !failed;
3543
+ const settled = stopped ? null : await reportBrowserStep(proposalId, failed);
3544
+ if (settled) entry.local = { state: settled.state || entry.local.state, result: settled.result || null, supersededBy: null };
3545
+ }
2965
3546
  } else if (body.fresh) {
2966
3547
  // The target changed or the offer ended: the old card says so, and a fresh card shows the current state.
2967
3548
  entry.local = { state: body.proposal?.state || 'superseded', result: null, supersededBy: body.fresh.id };
@@ -3018,7 +3599,8 @@
3018
3599
  head.className = 'ai-chat-filter-card-head';
3019
3600
  const eyebrow = document.createElement('span');
3020
3601
  eyebrow.className = 'guide-move-eyebrow';
3021
- eyebrow.textContent = ACTION_EYEBROWS[risk];
3602
+ // A request that has been answered no longer "needs your OK": the eyebrow says where it ended up.
3603
+ eyebrow.textContent = { executing: actionId === 'workflows.run' || actionId === 'routines.run' ? 'Running' : 'Working', done: 'Finished', failed: 'Could not finish', unknown: 'Outcome unknown' }[current.state] || ACTION_EYEBROWS[risk];
3022
3604
  const strong = document.createElement('strong');
3023
3605
  strong.id = titleId;
3024
3606
  strong.textContent = title;
@@ -3047,7 +3629,8 @@
3047
3629
 
3048
3630
  if (current.state === 'done') {
3049
3631
  card.classList.add('is-done');
3050
- status.textContent = current.next ? 'Done. Its result is ready to view.' : String(payload.doneNote || 'Done.');
3632
+ // A step this window took after the confirm (#2290) can still fail here; that is said, never "Done." over it.
3633
+ status.textContent = entry.error || (current.next ? 'Done. Its result is ready to view.' : String(payload.doneNote || 'Done.'));
3051
3634
  if (current.next) {
3052
3635
  // What the finished action made (a run's report): opening it only shows it, it runs nothing again.
3053
3636
  const actions = document.createElement('div');
@@ -3068,7 +3651,13 @@
3068
3651
  }
3069
3652
  if (current.state === 'failed') {
3070
3653
  card.classList.add('is-failed');
3071
- status.textContent = `${current.result?.message || 'It did not complete.'} You can ask the AI to suggest it again.`;
3654
+ // A route's refusal can be a bare fragment: show it as a sentence, with the next step after it.
3655
+ const refusal = String(current.result?.message || '').trim();
3656
+ const sentence = refusal ? refusal.charAt(0).toUpperCase() + refusal.slice(1) + (/[.!?…]$/.test(refusal) ? '' : '.') : '';
3657
+ // A step this window could not take already says what to do instead (open the review, try it from Requests).
3658
+ status.textContent = current.result?.code === 'step-not-done' && sentence
3659
+ ? sentence
3660
+ : `${sentence || 'It did not complete.'} You can ask the AI to suggest it again.`;
3072
3661
  card.append(status);
3073
3662
  return card;
3074
3663
  }
@@ -3131,7 +3720,7 @@
3131
3720
  later.dataset.tip = 'Sets this suggestion aside. Nothing runs.';
3132
3721
  later.disabled = Boolean(entry.busy);
3133
3722
  later.addEventListener('click', () => { void actOnProposal(event, proposalId, 'decline'); });
3134
- const confirm = actionButton(entry.busy === 'confirm' ? 'Starting…' : (ACTION_CONFIRM_VERBS[actionId] || 'Do it'), 'shell.chat-action-confirm', proposalId, summaryText, 'ai-chat-filter-apply');
3723
+ const confirm = actionButton(entry.busy === 'confirm' ? 'Working…' : (ACTION_CONFIRM_VERBS[actionId] || 'Do it'), 'shell.chat-action-confirm', proposalId, summaryText, 'ai-chat-filter-apply');
3135
3724
  confirm.dataset.tip = risk === 'destructive' ? 'Runs it now, for real. FloLess checks first that nothing changed since this was suggested.'
3136
3725
  : 'Makes this change now. FloLess checks first that nothing changed since this was suggested.';
3137
3726
  confirm.disabled = Boolean(entry.busy);
@@ -3140,16 +3729,671 @@
3140
3729
  actions.append(later, confirm);
3141
3730
  const meta = document.createElement('p');
3142
3731
  meta.className = 'ai-chat-filter-note ai-chat-action-meta';
3143
- meta.textContent = payload.revision === 'bound' ? 'Uses the approved version as it is now; if it changes first, you will be asked again.'
3732
+ meta.textContent = payload.revision === 'bound' ? 'Checked against how it is now; if it changes first, you will be asked again.'
3144
3733
  : 'Acts on things as they are when you confirm.';
3145
3734
  status.textContent = entry.error;
3146
3735
  card.append(actions, meta, status);
3147
3736
  return card;
3148
3737
  }
3149
3738
 
3739
+ /**
3740
+ * #2262: a Page the AI saved from this conversation — a receipt the person will want to find again, so a card, not a
3741
+ * line. Title, version, the AI-made label the viewer also shows, and Open. When the AI was asked to change a Page it
3742
+ * did not make, that Page was left as it was and this is a new one: the card says so and can open the original.
3743
+ */
3744
+ function renderPageCard(event) {
3745
+ const card = event.payload.card;
3746
+ const title = String(card.title || 'Untitled Page');
3747
+ const version = Number.isInteger(card.version) && card.version > 0 ? card.version : 1;
3748
+ const node = document.createElement('section');
3749
+ node.className = 'ai-chat-filter-card ai-chat-action-card ai-chat-page-card is-done';
3750
+ node.dataset.eventId = event.eventId;
3751
+ node.dataset.eventSequence = String(event.sequence);
3752
+ node.setAttribute('role', 'group');
3753
+ node.setAttribute('aria-label', `Page: ${title}, version ${version}${card.aiMade === false ? '' : ', made by AI'}`);
3754
+ const head = document.createElement('div');
3755
+ head.className = 'ai-chat-filter-card-head';
3756
+ const named = document.createElement('div');
3757
+ named.className = 'ai-chat-action-named';
3758
+ const eyebrow = document.createElement('span');
3759
+ eyebrow.className = 'guide-move-eyebrow';
3760
+ eyebrow.textContent = 'Page';
3761
+ const strong = document.createElement('strong');
3762
+ strong.textContent = title;
3763
+ named.append(eyebrow, strong);
3764
+ head.append(named);
3765
+ if (card.aiMade !== false) {
3766
+ const badge = document.createElement('span');
3767
+ badge.className = 'pg-ai-badge';
3768
+ badge.textContent = 'AI-made';
3769
+ // A Page the chat only SHOWED (#2389) may have been made elsewhere: the tip must not claim this conversation made it.
3770
+ badge.dataset.tip = card.shown ? 'Made by AI. Check it before you rely on it or share it.' : 'Made by AI in this conversation. Check it before you rely on it or share it.';
3771
+ badge.tabIndex = 0;
3772
+ head.append(badge);
3773
+ }
3774
+ const line = document.createElement('p');
3775
+ line.className = 'ai-chat-action-line ai-chat-page-ver';
3776
+ line.textContent = card.shown ? `Version ${version} · shown here` : card.based ? 'Version 1 · a new Page' : version > 1 ? `Version ${version} · added to this Page` : 'Version 1';
3777
+ node.append(head, line);
3778
+ if (card.shown && typeof card.note === 'string' && card.note) {
3779
+ // FloLess's own sentence when the version asked for isn't kept, so the latest is shown instead.
3780
+ const shownNote = document.createElement('p');
3781
+ shownNote.className = 'ai-chat-action-line ai-chat-page-based';
3782
+ shownNote.textContent = card.note;
3783
+ node.append(shownNote);
3784
+ }
3785
+ const basedOn = card.basedOn && card.basedOn.home && card.basedOn.pageId ? card.basedOn : null;
3786
+ if (card.based) {
3787
+ const note = document.createElement('p');
3788
+ note.className = 'ai-chat-action-line ai-chat-page-based';
3789
+ // FloLess's own sentence for what happened (who made the original, or why it could not be used), when it sent one.
3790
+ note.textContent = typeof card.note === 'string' && card.note ? card.note
3791
+ : basedOn ? `Based on “${basedOn.title}”, which was left as it is.` : 'The Page the AI was asked to change was left as it is; this is a new Page.';
3792
+ node.append(note);
3793
+ }
3794
+ const actions = document.createElement('div');
3795
+ actions.className = 'ai-chat-guide-actions';
3796
+ const status = document.createElement('p');
3797
+ status.className = 'ai-chat-filter-note ai-chat-action-status';
3798
+ status.setAttribute('role', 'status');
3799
+ // A Page that cannot be opened says so on its own card, with what to do, rather than a click that does nothing.
3800
+ const openPage = async (screen) => {
3801
+ status.textContent = '';
3802
+ let opened = false;
3803
+ try { opened = await openActionScreen(screen); } catch { opened = false; }
3804
+ if (!opened) status.textContent = 'FloLess couldn’t open that Page. Find it in the Pages list and open it from there.';
3805
+ };
3806
+ const open = button('Open', `shell.chat-page-open#${card.pageId}-v${version}`, 'ai-chat-page-open');
3807
+ open.dataset.commandInstanceLabel = `${title}, version ${version}`;
3808
+ open.setAttribute('aria-label', `Open ${title}, version ${version}`);
3809
+ open.dataset.tip = 'Opens this version in the Page viewer';
3810
+ open.addEventListener('click', () => { void openPage({ view: 'page', pageHome: card.home, pageId: card.pageId, pageVersion: version }); });
3811
+ actions.append(open);
3812
+ if (basedOn) {
3813
+ const original = button('Open the original', `shell.chat-page-open-original#${event.eventId}`);
3814
+ original.dataset.commandInstanceLabel = basedOn.title;
3815
+ original.setAttribute('aria-label', `Open the original, ${basedOn.title}`);
3816
+ original.addEventListener('click', () => { void openPage({ view: 'page', pageHome: basedOn.home, pageId: basedOn.pageId }); });
3817
+ actions.append(original);
3818
+ }
3819
+ node.append(actions, status);
3820
+ return node;
3821
+ }
3822
+
3823
+ /* ---- #2439: connection readiness ------------------------------------------------------------------------------------
3824
+ * What FloLess measured and recorded for each connection, drawn as the action returned it. It certifies nothing: there
3825
+ * is no "ready" state, a check outside its limit says by how much in words, a check FloLess could not make says so, and
3826
+ * sign-off stays the person's. The three choices only fill the message box.
3827
+ */
3828
+ /** The card's note that a built connection had no checks to measure: shown, but not a question to raise. Worded as connection-readiness.ts writes it. */
3829
+ const READINESS_NOTHING_MEASURED = 'No checks were measured for this connection';
3830
+ const READINESS_REVIEW = {
3831
+ 'signed-off': 'You accepted this imported connection as drawn. That is not a fabrication check.',
3832
+ 'needs-review': 'This imported connection has changed since FloLess recorded its placement. Review it before you sign it off.',
3833
+ untracked: 'This imported connection is not watched for review, so FloLess cannot record a sign-off for it. Place it again in the model to watch it.',
3834
+ 'clean-not-signed-off': 'This imported connection is not signed off yet.',
3835
+ 'not-available': 'FloLess has no sign-off for this kind of connection yet.',
3836
+ unavailable: 'FloLess could not read the sign-offs just now, so it cannot say whether this connection is signed off.',
3837
+ };
3838
+ /** Only these states have a sign-off waiting for the person; the others would refuse it or have nothing to sign. */
3839
+ const READINESS_SIGNABLE = new Set(['needs-review', 'clean-not-signed-off']);
3840
+
3841
+ /**
3842
+ * Millimetres to one decimal, with more digits when one decimal would hide a small, real difference. Below a millionth
3843
+ * of a millimetre (the finest tolerance FloLess measures to) a value is arithmetic noise and reads as 0.0.
3844
+ */
3845
+ function readinessMm(value) {
3846
+ if (!Number.isFinite(value)) return '—';
3847
+ if (Math.abs(value) < 1e-6) return '0.0 mm';
3848
+ const rounded = Math.round(value * 10) / 10;
3849
+ return `${rounded !== 0 ? rounded.toFixed(1) : String(Number(value.toPrecision(2)))} mm`;
3850
+ }
3851
+
3852
+ function readinessCount(n, word) {
3853
+ return `${n} ${word}${n === 1 ? '' : 's'}`;
3854
+ }
3855
+
3856
+ /**
3857
+ * Whether the tolerance decided this result: the measurement misses the limit taken strictly, by more than the
3858
+ * arithmetic noise `readinessMm` reads as zero, and passes only because of the tolerance.
3859
+ */
3860
+ function readinessToleranceDecided(fact) {
3861
+ if (fact.verdict !== 'within' || !Number.isFinite(fact.actualMm) || !Number.isFinite(fact.limitMm)) return false;
3862
+ const diff = fact.actualMm - fact.limitMm;
3863
+ if (Math.abs(diff) < 1e-6) return false;
3864
+ return fact.relation === 'at-least' ? diff < 0 : fact.relation === 'at-most' ? diff > 0 : true;
3865
+ }
3866
+
3867
+ /** The limit, and its tolerance wherever the tolerance explains the result: outside it, decided by it, or big enough to matter. */
3868
+ function readinessLimit(fact) {
3869
+ const relation = fact.relation === 'at-least' ? 'at least ' : fact.relation === 'at-most' ? 'at most ' : '';
3870
+ const telling = fact.verdict === 'outside' || readinessToleranceDecided(fact) || fact.toleranceMm >= 0.05;
3871
+ const tolerance = Number.isFinite(fact.toleranceMm) && fact.toleranceMm > 0 && telling ? ` (±${readinessMm(fact.toleranceMm)})` : '';
3872
+ return `${relation}${readinessMm(fact.limitMm)}${tolerance}`;
3873
+ }
3874
+
3875
+ /** A connection has two welds, two edges, several bolts: number the repeats so each row is its own check. */
3876
+ function readinessLabels(facts) {
3877
+ const total = new Map();
3878
+ for (const fact of facts) total.set(fact.label, (total.get(fact.label) || 0) + 1);
3879
+ const seen = new Map();
3880
+ return facts.map((fact) => {
3881
+ if (total.get(fact.label) < 2) return fact.label;
3882
+ seen.set(fact.label, (seen.get(fact.label) || 0) + 1);
3883
+ return `${fact.label} ${seen.get(fact.label)}`;
3884
+ });
3885
+ }
3886
+
3887
+ /** The result of one check, in words: never a colour or a tick alone. */
3888
+ function readinessResult(fact) {
3889
+ if (fact.verdict === 'unmeasured') return 'Not measured';
3890
+ if (fact.verdict === 'within') return 'Within limit';
3891
+ const off = Math.abs((fact.actualMm ?? 0) - (fact.limitMm ?? 0));
3892
+ if (fact.relation === 'at-least') return `Short by ${readinessMm(off)}`;
3893
+ if (fact.relation === 'at-most') return `Over by ${readinessMm(off)}`;
3894
+ return `Off by ${readinessMm(off)}`;
3895
+ }
3896
+
3897
+ /** The small dashed tag on a check that rests on a holding assumption: dashed is this card's "assumed", never a pass. */
3898
+ function readinessAssumedTag(assumption) {
3899
+ const tag = Object.assign(document.createElement('span'), { className: 'ai-chat-assume ai-chat-readiness-assumed', textContent: 'Assumed' });
3900
+ const words = String(assumption.statement || '');
3901
+ tag.dataset.tip = `You confirmed: “${words}${/[.!?]$/.test(words) ? '' : '.'}” The result is still the measured one`;
3902
+ tag.tabIndex = 0;
3903
+ tag.dataset.assumptionId = String(assumption.id || '');
3904
+ tag.setAttribute('aria-label', `Assumed: ${assumption.statement}`);
3905
+ return tag;
3906
+ }
3907
+
3908
+ const READINESS_STALE = {
3909
+ 'connection-changed': 'No longer applies. This connection changed after you confirmed it.',
3910
+ 'check-gone': 'No longer applies. The check it was about is not on this connection any more.',
3911
+ 'connection-gone': 'No longer applies. This connection is not in the model any more.',
3912
+ };
3913
+
3914
+ function readinessDate(iso) {
3915
+ const date = new Date(iso);
3916
+ return Number.isFinite(date.getTime()) ? date.toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' }) : 'an earlier date';
3917
+ }
3918
+
3919
+ function readinessTime(iso) {
3920
+ const date = new Date(iso);
3921
+ return Number.isFinite(date.getTime()) ? date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }) : '';
3922
+ }
3923
+
3924
+ /**
3925
+ * #2449: the assumptions a person confirmed on this connection, as this answer read them. A holding one carries the
3926
+ * dashed edge; one that no longer applies says why, in words, and carries no weight. The person can withdraw each here.
3927
+ */
3928
+ function readinessAssumptions(row, card, assumptions) {
3929
+ if (!assumptions.length && !row.assumptionsHeldBack) return null;
3930
+ const wrap = document.createElement('div'); wrap.className = 'ai-chat-readiness-list ai-chat-readiness-assumptions';
3931
+ wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-sub', textContent: 'Assumptions you confirmed' }));
3932
+ const at = card.readAt ? readinessTime(card.readAt) : '';
3933
+ if (at) wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-asread', textContent: `As read at ${at}. Ask again to see them now.` }));
3934
+ const list = document.createElement('ul');
3935
+ list.setAttribute('aria-label', `Assumptions you confirmed for ${row.kindLabel || row.kind} ${row.jointId}`);
3936
+ for (const a of assumptions) {
3937
+ const item = document.createElement('li');
3938
+ item.className = `ai-chat-readiness-assumption is-${a.state === 'holds' ? 'holding' : 'stale'}`;
3939
+ item.dataset.assumptionId = String(a.id || '');
3940
+ if (a.state !== 'holds') item.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-assumption-state', textContent: READINESS_STALE[a.staleReason] || READINESS_STALE['connection-changed'] }));
3941
+ item.append(Object.assign(document.createElement('q'), { className: 'ai-chat-readiness-assumption-words', textContent: String(a.statement || '') }),
3942
+ Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-assumption-meta', textContent: `About: ${a.readingText}` }),
3943
+ Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-assumption-meta',
3944
+ textContent: `You confirmed this on ${readinessDate(a.confirmedAt)}.${a.proposedBy === 'ai' ? ' The AI wrote the words.' : ''}` }));
3945
+ if (card.projectId) {
3946
+ const withdraw = button('Withdraw', 'shell.chat-readiness-withdraw-assumption', 'ai-chat-source-action');
3947
+ withdraw.setAttribute('aria-label', `Withdraw assumption: ${a.statement}`);
3948
+ withdraw.dataset.commandInstanceLabel = `${row.jointId}: ${a.statement}`;
3949
+ withdraw.dataset.tip = 'Removes this assumption. The check then reads as the plain check again';
3950
+ withdraw.addEventListener('click', () => withdrawReadinessAssumption(card.projectId, row.jointId, a.id, withdraw));
3951
+ const actions = document.createElement('div'); actions.className = 'ai-chat-readiness-actions';
3952
+ actions.append(withdraw);
3953
+ item.append(actions);
3954
+ }
3955
+ list.append(item);
3956
+ }
3957
+ wrap.append(list);
3958
+ if (row.assumptionsHeldBack) wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-sub', textContent: `${readinessCount(row.assumptionsHeldBack, 'more assumption')} on this connection not shown here. Ask about it alone to see them.` }));
3959
+ return wrap;
3960
+ }
3961
+
3962
+ /**
3963
+ * Withdraw one assumption: a person's click in this window. Success replaces the button with a receipt, which takes the
3964
+ * focus; a failure keeps the button (and the focus on it) and says why underneath.
3965
+ */
3966
+ async function withdrawReadinessAssumption(projectId, jointId, assumptionId, control) {
3967
+ if (control.getAttribute('aria-disabled') === 'true') return;
3968
+ control.setAttribute('aria-disabled', 'true');
3969
+ control.textContent = 'Withdrawing…';
3970
+ const item = control.closest('li');
3971
+ const row = control.closest('.ai-chat-readiness-row');
3972
+ item?.querySelector('.ai-chat-readiness-receipt')?.remove();
3973
+ let answer;
3974
+ try {
3975
+ answer = await request(`/api/projects/${encodeURIComponent(projectId)}/connections/${encodeURIComponent(jointId)}/assumptions/${encodeURIComponent(assumptionId)}/withdraw`, { method: 'POST' });
3976
+ } catch (error) {
3977
+ control.removeAttribute('aria-disabled');
3978
+ control.textContent = 'Withdraw';
3979
+ // What happened, why, and what to do next: only a reason that can pass is followed by "try again".
3980
+ const text = error?.code === 'project-not-found'
3981
+ ? 'Not withdrawn: this project is no longer in FloLess, so there is nothing to withdraw here.'
3982
+ : `Not withdrawn: ${String(error?.message || 'FloLess could not reach this project just now').replace(/[.\s]+$/, '')}. Nothing was changed. Try again in a moment.`;
3983
+ const note = Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-receipt is-failed', textContent: text });
3984
+ note.setAttribute('role', 'alert');
3985
+ control.parentElement?.after(note);
3986
+ return;
3987
+ }
3988
+ // Already gone (another tab, or recorded again under a new id) is said as such, never as this click's doing.
3989
+ const receipt = answer?.changed === false
3990
+ ? 'It was already withdrawn. Nothing changed. Ask again to see the connection as it is now.'
3991
+ : 'Withdrawn. Ask again to see the connection as it is now.';
3992
+ const note = Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-receipt', textContent: receipt, tabIndex: -1 });
3993
+ note.setAttribute('role', 'status');
3994
+ const wasHolding = item?.classList.contains('is-holding');
3995
+ control.replaceWith(note);
3996
+ item?.classList.add('is-withdrawn');
3997
+ // Nothing on this card rests on it any more: its tags go with it, and the counts stop including it.
3998
+ for (const tag of row ? row.querySelectorAll('.ai-chat-readiness-assumed') : []) if (tag.dataset.assumptionId === String(assumptionId)) tag.remove();
3999
+ if (wasHolding) {
4000
+ readinessUncount(row?.querySelector('.ai-chat-readiness-status'), ' · ');
4001
+ readinessUncount(row?.closest('.ai-chat-readiness-card')?.querySelector('.ai-chat-filter-card-head .ai-chat-filter-state'), ' · ');
4002
+ }
4003
+ note.focus({ preventScroll: true });
4004
+ }
4005
+
4006
+ /** One fewer "N on an assumption" in a count line, the part dropped at zero (a person withdrew one on this card). */
4007
+ function readinessUncount(node, separator) {
4008
+ if (!node) return;
4009
+ const parts = node.textContent.split(separator);
4010
+ const next = parts.flatMap((part) => {
4011
+ const m = /^(\d+) on an assumption$/.exec(part);
4012
+ if (!m) return [part];
4013
+ const n = Number(m[1]) - 1;
4014
+ return n > 0 ? [`${n} on an assumption`] : [];
4015
+ });
4016
+ node.textContent = next.length ? next.join(separator) : 'Nothing measured is outside a limit';
4017
+ }
4018
+
4019
+ /** The holding assumption a person confirmed on one line of the answer, if any. */
4020
+ function readinessHolding(assumptions, kind, text) {
4021
+ return assumptions.find((a) => a.state === 'holds' && a.covers?.kind === kind && a.covers.text === text) || null;
4022
+ }
4023
+
4024
+ /** A list whose lines may rest on an assumption: each such line keeps its words and gains the dashed tag. */
4025
+ function readinessAssumedList(title, entries) {
4026
+ const node = readinessList(title, entries.map(([text]) => text));
4027
+ if (!node) return null;
4028
+ const items = node.querySelectorAll('li');
4029
+ entries.forEach(([, on], index) => { if (on && items[index]) items[index].append(' ', readinessAssumedTag(on)); });
4030
+ return node;
4031
+ }
4032
+
4033
+ function readinessList(title, items) {
4034
+ if (!items.length) return null;
4035
+ const wrap = document.createElement('div'); wrap.className = 'ai-chat-readiness-list';
4036
+ const head = Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-sub', textContent: title });
4037
+ const list = document.createElement('ul');
4038
+ for (const item of items) list.append(Object.assign(document.createElement('li'), { textContent: item }));
4039
+ wrap.append(head, list);
4040
+ return wrap;
4041
+ }
4042
+
4043
+ /*
4044
+ * #2451: where on the drawings each member, and the detail a member's size came from, were read. Each place opens the
4045
+ * source page cropped to it. The tag says who drew the area; nothing here says the connection fits.
4046
+ */
4047
+ const EVIDENCE_ORIGIN = {
4048
+ 'member-line': { tag: 'line framed by FloLess', note: (e) => `FloLess outlined this member's line on page ${e.page} of ${e.sheet}. This shows where it was read, not that the connection fits.` },
4049
+ 'reader-detail': { tag: 'area recorded by the drawing reader', note: (e) => `The drawing reader recorded this area on page ${e.page} of ${e.sheet}. This shows where a size was read, not that the connection fits.` },
4050
+ };
4051
+
4052
+ function readinessEvidence(row, card) {
4053
+ const places = (Array.isArray(row.drawingEvidence) ? row.drawingEvidence : []).filter((e) => e && EVIDENCE_ORIGIN[e.origin]);
4054
+ const gaps = Array.isArray(row.drawingEvidenceGaps) ? row.drawingEvidenceGaps.map(String) : [];
4055
+ if (!places.length && !gaps.length) return null;
4056
+ const wrap = document.createElement('div'); wrap.className = 'ai-chat-readiness-list ai-chat-readiness-evidence';
4057
+ wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-sub', textContent: 'Where on the drawings' }),
4058
+ Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-asread', textContent: 'Shows where each member and size was read. It does not show that the connection fits.' }));
4059
+ const list = document.createElement('ul');
4060
+ for (const place of places) {
4061
+ const item = document.createElement('li');
4062
+ const open = button('', 'shell.chat-readiness-open-evidence', 'ai-chat-readiness-place');
4063
+ open.dataset.commandInstanceLabel = String(place.where || place.label);
4064
+ open.setAttribute('aria-label', `${place.label}, ${EVIDENCE_ORIGIN[place.origin].tag}: opens the drawing`);
4065
+ open.dataset.tip = `Opens sheet ${place.sheet} with this area outlined`;
4066
+ open.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-place-sheet', textContent: String(place.sheet) }),
4067
+ Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-place-label', textContent: String(place.label) }),
4068
+ Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-place-origin', textContent: EVIDENCE_ORIGIN[place.origin].tag }));
4069
+ open.addEventListener('click', () => openReadinessEvidence(place, row, card, open));
4070
+ item.append(open);
4071
+ list.append(item);
4072
+ }
4073
+ for (const line of gaps) list.append(Object.assign(document.createElement('li'), { className: 'ai-chat-readiness-place-gap', textContent: line }));
4074
+ wrap.append(list);
4075
+ const more = [[Number(row.drawingEvidenceHeldBack) || 0, 'more place', 'on the drawings'], [Number(row.drawingEvidenceGapsHeldBack) || 0, 'more note', 'about places not shown']]
4076
+ .filter(([n]) => n > 0).map(([n, word, rest]) => `${readinessCount(n, word)} ${rest} not listed here.`);
4077
+ if (more.length) wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-asread', textContent: more.join(' ') }));
4078
+ return wrap;
4079
+ }
4080
+
4081
+ /** The crop of the page around a place: the area and some room around it, never smaller than a fifth of the page. */
4082
+ function evidenceCrop(place) {
4083
+ const [px0, py0, px1, py1] = place.pageBounds;
4084
+ const [rx0, ry0, rx1, ry1] = place.region;
4085
+ const grow = (lo, hi, min, max) => {
4086
+ const pad = Math.max((hi - lo) * 0.15, (max - min) * 0.01);
4087
+ let a = lo - pad, b = hi + pad;
4088
+ const least = (max - min) * 0.2;
4089
+ if (b - a < least) { const mid = (a + b) / 2; a = mid - least / 2; b = mid + least / 2; }
4090
+ if (a < min) { b += min - a; a = min; }
4091
+ if (b > max) { a -= b - max; b = max; }
4092
+ return [Math.max(min, a), Math.min(max, b)];
4093
+ };
4094
+ const [cx0, cx1] = grow(rx0, rx1, px0, px1);
4095
+ const [cy0, cy1] = grow(ry0, ry1, py0, py1);
4096
+ return { x0: cx0, y0: cy0, w: cx1 - cx0, h: cy1 - cy0, pageW: px1 - px0, pageH: py1 - py0, px0, py0 };
4097
+ }
4098
+
4099
+ /** The place's page in the cited-source viewer, cropped to the place, with the whole sheet a press away. */
4100
+ async function openReadinessEvidence(place, row, card, opener) {
4101
+ const title = String(place.title || place.label);
4102
+ const dialog = document.createElement('dialog'); dialog.className = 'ai-chat-source-viewer ai-chat-evidence-viewer';
4103
+ dialog.setAttribute('aria-label', title);
4104
+ const head = document.createElement('div'); head.className = 'ai-chat-source-viewer-head';
4105
+ const close = button('Close', 'shell.chat-readiness-evidence-close', 'ai-chat-source-viewer-close');
4106
+ let picture = null;
4107
+ let finished = false;
4108
+ const finish = () => {
4109
+ if (finished) return;
4110
+ finished = true;
4111
+ if (dialog.open) dialog.close();
4112
+ dialog.remove();
4113
+ if (picture) URL.revokeObjectURL(picture);
4114
+ if (opener?.isConnected) opener.focus({ preventScroll: true });
4115
+ };
4116
+ close.addEventListener('click', finish);
4117
+ dialog.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.preventDefault(); finish(); } });
4118
+ dialog.addEventListener('close', finish);
4119
+ head.append(Object.assign(document.createElement('strong'), { textContent: title }), close);
4120
+ const note = Object.assign(document.createElement('span'), { className: 'ai-chat-source-viewer-note', textContent: EVIDENCE_ORIGIN[place.origin].note(place) });
4121
+ const views = document.createElement('div'); views.className = 'ai-chat-evidence-views'; views.setAttribute('role', 'group'); views.setAttribute('aria-label', 'How much of the sheet to show');
4122
+ const area = button('This area', 'shell.chat-readiness-evidence-view', 'ai-chat-evidence-view');
4123
+ const whole = button('Whole sheet', 'shell.chat-readiness-evidence-view', 'ai-chat-evidence-view');
4124
+ area.dataset.commandInstanceLabel = 'this area'; whole.dataset.commandInstanceLabel = 'the whole sheet';
4125
+ views.append(area, whole);
4126
+ const body = document.createElement('div'); body.className = 'ai-chat-source-viewer-body';
4127
+ const status = Object.assign(document.createElement('p'), { className: 'ai-chat-source-viewer-status', textContent: 'Loading the drawing…' });
4128
+ status.setAttribute('role', 'status');
4129
+ const crop = evidenceCrop(place);
4130
+ const frame = document.createElement('div'); frame.className = 'ai-chat-evidence-frame';
4131
+ const show = (all) => {
4132
+ area.setAttribute('aria-pressed', String(!all)); whole.setAttribute('aria-pressed', String(all));
4133
+ frame.dataset.view = all ? 'sheet' : 'area';
4134
+ const c = all ? { x0: crop.px0, y0: crop.py0, w: crop.pageW, h: crop.pageH } : crop;
4135
+ // Shaped like the crop and never taller than most of the window: narrowed, not squashed, so the picture stays true.
4136
+ frame.style.aspectRatio = `${c.w} / ${c.h}`;
4137
+ frame.style.width = `min(100%, calc(62vh * ${c.w / c.h}))`;
4138
+ const image = frame.querySelector('img');
4139
+ if (image) Object.assign(image.style, { width: `${(crop.pageW / c.w) * 100}%`, left: `${(-(c.x0 - crop.px0) / c.w) * 100}%`, top: `${(-(c.y0 - crop.py0) / c.h) * 100}%` });
4140
+ };
4141
+ area.addEventListener('click', () => show(false));
4142
+ whole.addEventListener('click', () => show(true));
4143
+ show(false);
4144
+ body.append(status, frame);
4145
+ dialog.append(head, note, views, body);
4146
+ document.body.append(dialog);
4147
+ dialog.showModal();
4148
+ close.focus({ preventScroll: true });
4149
+ // A place that changed or is gone says so and offers the way on: the card asked for again, never sent for the person.
4150
+ const offerAgain = (why) => {
4151
+ if (finished) return;
4152
+ status.textContent = why;
4153
+ frame.remove(); views.remove();
4154
+ const again = button('Ask for the readiness card again', 'shell.chat-readiness-evidence-again', 'ai-chat-source-viewer-knowledge');
4155
+ again.dataset.tip = 'Puts the request in the message box. Nothing is sent until you press Send';
4156
+ again.addEventListener('click', () => {
4157
+ finish();
4158
+ addToMessageBox(`Show the readiness of connection ${row.jointId} again.`);
4159
+ ui.input.focus?.();
4160
+ });
4161
+ dialog.append(again);
4162
+ };
4163
+ try {
4164
+ const url = `/api/projects/${encodeURIComponent(card.projectId)}/connections/${encodeURIComponent(row.jointId)}/evidence/drawing?key=${encodeURIComponent(place.key)}&digest=${encodeURIComponent(place.digest)}`;
4165
+ const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store' });
4166
+ if (finished) return;
4167
+ if (!response.ok) {
4168
+ const said = await response.json().catch(() => null);
4169
+ offerAgain(typeof said?.error === 'string' && said.error ? said.error : 'FloLess could not open this drawing just now. Try again in a moment.');
4170
+ return;
4171
+ }
4172
+ const bytes = await response.blob();
4173
+ if (finished) return;
4174
+ picture = URL.createObjectURL(bytes);
4175
+ const image = Object.assign(document.createElement('img'), { src: picture, alt: `${title}, page ${place.page}, with the area outlined` });
4176
+ frame.append(image);
4177
+ show(false);
4178
+ status.textContent = `${place.sheet} · page ${place.page}`;
4179
+ } catch (error) {
4180
+ console.error('[chat] a drawing place could not be opened', error);
4181
+ offerAgain('FloLess could not open this drawing just now. Try again in a moment.');
4182
+ }
4183
+ }
4184
+
4185
+ /*
4186
+ * The feed is rebuilt on every streamed word and every 5 s poll (#2163). An action's card never changes once it is
4187
+ * recorded, so the node painted for an event is handed back as long as the event is the same one: the person's place
4188
+ * in the card's own scroll area and a focused button survive the rebuild. Bounded, oldest first.
4189
+ */
4190
+ const readinessNodes = new Map();
4191
+ function renderReadinessCard(event) {
4192
+ const kept = readinessNodes.get(event.eventId);
4193
+ if (kept && kept.sequence === event.sequence) return kept.node;
4194
+ const node = paintReadinessCard(event);
4195
+ readinessNodes.delete(event.eventId);
4196
+ readinessNodes.set(event.eventId, { sequence: event.sequence, node });
4197
+ while (readinessNodes.size > 40) readinessNodes.delete(readinessNodes.keys().next().value);
4198
+ return node;
4199
+ }
4200
+
4201
+ function paintReadinessCard(event) {
4202
+ const card = event.payload.card;
4203
+ const rows = Array.isArray(card.rows) ? card.rows : [];
4204
+ const node = document.createElement('section');
4205
+ node.className = 'ai-chat-filter-card ai-chat-action-card ai-chat-readiness-card';
4206
+ node.dataset.eventId = event.eventId;
4207
+ node.dataset.eventSequence = String(event.sequence);
4208
+ node.setAttribute('role', 'group');
4209
+ node.setAttribute('aria-label', 'Connection readiness');
4210
+ const sum = (key) => rows.reduce((total, row) => total + (Number(row.summary?.[key]) || 0), 0);
4211
+ const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
4212
+ // The counts are of the connections shown, and say so: with some held back they are not the project's totals.
4213
+ head.append(Object.assign(document.createElement('strong'), { textContent: 'Connection readiness' }),
4214
+ Object.assign(document.createElement('span'), { className: 'ai-chat-filter-state',
4215
+ textContent: `${rows.length} of ${readinessCount(card.total ?? rows.length, 'connection')} shown · in these: ${sum('outside')} outside a limit · ${sum('unmeasured')} not measured · ${readinessCount(sum('issues'), 'build issue')} · ${readinessCount(sum('openRfis'), 'open RFI')}${sum('onAssumption') ? ` · ${sum('onAssumption')} on an assumption` : ''}` }));
4216
+ const limits = Object.assign(document.createElement('p'), { className: 'ai-chat-readiness-limits',
4217
+ textContent: 'These are the checks FloLess measured. They do not certify a connection for fabrication.' });
4218
+ const body = document.createElement('div'); body.className = 'ai-chat-readiness-body'; body.tabIndex = 0;
4219
+ body.setAttribute('aria-label', 'Connections and their checks');
4220
+ for (const row of rows) body.append(readinessRow(row, card));
4221
+ node.append(head, limits, body);
4222
+ const notes = [];
4223
+ // The card names at most a few of each; the rest are counted, never dropped.
4224
+ const andMore = (list, more) => `${list.join(', ')}${more ? `, and ${more} more` : ''}`;
4225
+ const missing = Array.isArray(card.notFound?.jointIds) ? card.notFound.jointIds : [];
4226
+ const missingCount = missing.length + (Number(card.notFound?.jointIdsHeldBack) || 0);
4227
+ if (missing.length) notes.push(`${missingCount === 1 ? 'This connection is' : 'These connections are'} not in the model, so nothing is said about ${missingCount === 1 ? 'it' : 'them'}: ${andMore(missing, Number(card.notFound.jointIdsHeldBack) || 0)}.`);
4228
+ const otherKind = Array.isArray(card.notFound?.otherKind) ? card.notFound.otherKind : [];
4229
+ if (otherKind.length) notes.push(`Not of the kind "${card.notFound.askedKind || ''}" you asked about, so not shown: ${andMore(otherKind.map((row) => `${row.jointId} (${row.kind})`), Number(card.notFound.otherKindHeldBack) || 0)}.`);
4230
+ if (card.notFound?.kind) notes.push(`The model has no connections of the kind "${card.notFound.kind}", so nothing is said about that kind.`);
4231
+ if (card.reviewUnavailable) notes.push(card.reviewUnavailable);
4232
+ if (card.assumptionsUnavailable) notes.push(card.assumptionsUnavailable);
4233
+ if (card.drawingEvidenceUnavailable) notes.push(card.drawingEvidenceUnavailable);
4234
+ if (card.rfisUnavailable) notes.push(card.rfisUnavailable);
4235
+ if (card.heldBack?.rows) notes.push(`${card.heldBack.rows} more connections are not shown${card.heldBack.needingAttention ? `, and ${card.heldBack.needingAttention} of them need attention` : ''}. Ask about one kind or one connection to see them.`);
4236
+ for (const line of Array.isArray(card.unattached) ? card.unattached : []) notes.push(String(line));
4237
+ if (card.unattachedHeldBack) notes.push(`${readinessCount(card.unattachedHeldBack, 'more build failure')} that name no connection are not listed here.`);
4238
+ if (notes.length) node.append(readinessList('Also', notes));
4239
+ const foot = document.createElement('div'); foot.className = 'ai-chat-readiness-foot';
4240
+ foot.append(Object.assign(document.createElement('span'), { textContent: 'The AI does not mark this checked. Sign-off is yours.' }));
4241
+ node.append(foot);
4242
+ return node;
4243
+ }
4244
+
4245
+ function readinessRow(row, card) {
4246
+ const wrap = document.createElement('div'); wrap.className = 'ai-chat-readiness-row';
4247
+ wrap.dataset.jointId = String(row.jointId || '');
4248
+ const title = document.createElement('div'); title.className = 'ai-chat-readiness-title';
4249
+ title.append(Object.assign(document.createElement('strong'), { textContent: `${row.kindLabel || row.kind} · ${row.place}` }),
4250
+ Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-id', textContent: String(row.jointId || '') }));
4251
+ wrap.append(title);
4252
+ // One line per connection a detailer can scan down: what holds it back, in counts, worst first. Never "ready":
4253
+ // with nothing counted it says only that nothing measured is outside a limit.
4254
+ const s = row.summary || {};
4255
+ const holding = [[s.outside, 'outside a limit'], [s.issues, 'build issue'], [s.unmeasured, 'not measured'], [s.openRfis, 'open RFI'], [s.onAssumption, 'on an assumption']]
4256
+ .filter(([n]) => Number(n) > 0).map(([n, word]) => word === 'outside a limit' || word === 'not measured' || word === 'on an assumption' ? `${n} ${word}` : readinessCount(Number(n), word));
4257
+ wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-status',
4258
+ textContent: holding.length ? holding.join(' · ') : 'Nothing measured is outside a limit' }));
4259
+ const facts = Array.isArray(row.facts) ? row.facts : [];
4260
+ const assumptions = Array.isArray(row.assumptions) ? row.assumptions : [];
4261
+ if (facts.length) {
4262
+ const scroll = document.createElement('div'); scroll.className = 'ai-chat-readiness-table';
4263
+ const table = document.createElement('table');
4264
+ const headRow = document.createElement('tr');
4265
+ for (const label of ['Check', 'Measured', 'Limit', 'Result']) headRow.append(Object.assign(document.createElement('th'), { textContent: label, scope: 'col' }));
4266
+ const thead = document.createElement('thead');
4267
+ const tbody = document.createElement('tbody');
4268
+ thead.append(headRow);
4269
+ table.append(thead, tbody);
4270
+ const labels = readinessLabels(facts);
4271
+ for (const [index, fact] of facts.entries()) {
4272
+ const tr = document.createElement('tr');
4273
+ if (fact.verdict !== 'within') tr.className = `is-${fact.verdict}`;
4274
+ const result = Object.assign(document.createElement('td'), { textContent: readinessResult(fact) });
4275
+ // #2449: a check resting on a holding assumption keeps its result; the tag says only what it rests on.
4276
+ const on = fact.assumptionId ? assumptions.find((a) => a.id === fact.assumptionId) : null;
4277
+ if (on) result.append(' ', readinessAssumedTag(on));
4278
+ // #2450: a check that already has an RFI says which, so the card and the RFI stay linked.
4279
+ const filed = (Array.isArray(row.checkRfis) ? row.checkRfis : []).find((c) => c.checkId === fact.id);
4280
+ if (filed) result.append(' ', Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-rfi', textContent: `${filed.rfiId} · ${filed.status}` }));
4281
+ tr.append(Object.assign(document.createElement('td'), { textContent: labels[index] }),
4282
+ Object.assign(document.createElement('td'), { textContent: readinessMm(fact.actualMm) }),
4283
+ Object.assign(document.createElement('td'), { textContent: readinessLimit(fact) }),
4284
+ result);
4285
+ tbody.append(tr);
4286
+ }
4287
+ scroll.append(table);
4288
+ wrap.append(scroll);
4289
+ if (row.factsHeldBack) wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-sub', textContent: `${readinessCount(row.factsHeldBack, 'more check')} not shown here.` }));
4290
+ }
4291
+ const assumed = readinessAssumptions(row, card, assumptions);
4292
+ if (assumed) wrap.append(assumed);
4293
+ for (const part of [
4294
+ readinessAssumedList('Not measured', (row.unmeasured || []).map((line) => [String(line), readinessHolding(assumptions, 'unmeasured', String(line))])),
4295
+ readinessAssumedList('Build issues', (row.issues || []).map((issue) => [String(issue.text), issue.assumptionId ? assumptions.find((a) => a.id === issue.assumptionId) : null])),
4296
+ readinessList('RFIs on this connection', (row.rfis || []).map((rfi) => `${rfi.rfiId} · ${rfi.status} · ${rfi.question}`)),
4297
+ readinessList('RFIs on its members', (row.relatedRfis || []).map((rfi) => `${rfi.rfiId} · ${rfi.status} · ${rfi.question}`)),
4298
+ readinessList('Drawing references for these members', (row.drawingReferences || []).map((ref) => `${ref.member}, end ${Number(ref.end) + 1}: detail ${ref.detail}`)),
4299
+ card.projectId ? readinessEvidence(row, card) : null,
4300
+ ]) if (part) wrap.append(part);
4301
+ if (row.itemsHeldBack) wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-sub', textContent: `${readinessCount(row.itemsHeldBack, 'more item')} about this connection not shown here. Ask about it alone to see them.` }));
4302
+ wrap.append(Object.assign(document.createElement('p'), { className: 'ai-chat-readiness-review', textContent: READINESS_REVIEW[row.review] || READINESS_REVIEW['not-available'] }));
4303
+ const attention = (row.summary?.outside || 0) + (row.summary?.unmeasured || 0) + (row.summary?.issues || 0);
4304
+ const actions = document.createElement('div'); actions.className = 'ai-chat-readiness-actions';
4305
+ // What holds this connection back, in the card's own words: failing checks, then build issues, then what was not measured.
4306
+ const failing = [
4307
+ ...facts.filter((fact) => fact.verdict !== 'within').map((fact) => `${fact.label} (${fact.id}) measured ${readinessMm(fact.actualMm)} against ${readinessMm(fact.limitMm)}`),
4308
+ ...(row.issues || []).map((issue) => String(issue.text)),
4309
+ ...(row.unmeasured || []).map(String),
4310
+ ];
4311
+ const about = `${row.kindLabel || row.kind} ${row.jointId} at ${row.place}`;
4312
+ if (card.projectId) {
4313
+ const open = button('Open in the model', 'shell.chat-readiness-open-model', 'ai-chat-source-action');
4314
+ open.dataset.commandInstanceLabel = about;
4315
+ open.setAttribute('aria-label', `Open in the model: ${about}`);
4316
+ open.dataset.tip = 'Shows this connection in the model, selected and framed';
4317
+ open.addEventListener('click', async () => {
4318
+ // The line here says what happened, never more than the editor did: it waits for the editor's own
4319
+ // outcome. A refusal carries the editor's sentence; success and the fallback stay short.
4320
+ const unreachable = 'FloLess could not open the model from here. Open the project from Workspaces, then try again.';
4321
+ let said;
4322
+ try {
4323
+ const outcome = await openConnectionInModel(card.projectId, String(row.jointId || ''));
4324
+ if (outcome?.superseded) return; // a later click reports for itself
4325
+ said = !outcome ? unreachable
4326
+ : outcome.ok !== true ? (outcome.said || `Connection ${row.jointId} was not shown. Open the Model step, then press Open in the model again.`)
4327
+ : outcome.fallback === 'main-member' ? `FloLess could not build connection ${row.jointId}, so its main member is selected in the model instead.`
4328
+ : `Showing connection ${row.jointId} in the model.`;
4329
+ } catch (error) {
4330
+ // Only a sentence written for the person is shown as is; anything else gets the plain fallback,
4331
+ // and its cause goes to the console for a bug report.
4332
+ if (error?.plain !== true) console.error('[chat] Open in the model failed', error);
4333
+ said = error?.plain === true && error.message ? error.message : unreachable;
4334
+ }
4335
+ announce(said);
4336
+ });
4337
+ actions.append(open);
4338
+ }
4339
+ // What the model raises a question about, the way the server's question list counts it: a check outside
4340
+ // its limit or not measured, a build error, a connection that could not be built. A warning, and the
4341
+ // plain note that nothing was measured, are shown on the card but are not questions — offering
4342
+ // "Raise an RFI" for them would open a dialog with nothing to file.
4343
+ const raisableIssues = (row.issues || []).filter((issue) => issue.severity !== 'warning');
4344
+ const raisable = facts.some((fact) => fact.verdict !== 'within') || raisableIssues.length > 0
4345
+ || (row.unmeasured || []).some((line) => String(line) !== READINESS_NOTHING_MEASURED);
4346
+ if (raisable) {
4347
+ // #2450: the editor shows the connection and its questions as FloLess wrote them; the person files one there.
4348
+ const rfi = button('Raise an RFI', 'shell.chat-readiness-ask-rfi', 'ai-chat-source-action');
4349
+ rfi.dataset.commandInstanceLabel = about;
4350
+ rfi.setAttribute('aria-label', `Raise an RFI: ${about}`);
4351
+ rfi.dataset.tip = 'Opens this connection in the model so you can review the question and file the RFI yourself';
4352
+ const firstCheck = facts.find((fact) => fact.verdict !== 'within')?.id || raisableIssues[0]?.code || '';
4353
+ rfi.addEventListener('click', async () => {
4354
+ const unreachable = 'FloLess could not open the model from here. Open the project from Workspaces, then try again.';
4355
+ let said;
4356
+ try {
4357
+ const outcome = await openConnectionInModel(card.projectId, String(row.jointId || ''), { raiseRfi: true, ...(firstCheck ? { checkId: firstCheck } : {}) });
4358
+ if (outcome?.superseded) return; // a later click reports for itself
4359
+ // Said only when the editor really opened the questions; otherwise its own reason, or the plain fallback.
4360
+ said = !outcome ? unreachable
4361
+ : outcome.raised === true ? `The questions for connection ${row.jointId} are open in the model. Review one there and file it.`
4362
+ : outcome.raiseSaid || outcome.said || `The questions for connection ${row.jointId} could not be opened in the model. Open the Model step, then press Raise an RFI again.`;
4363
+ } catch (error) {
4364
+ if (error?.plain !== true) console.error('[chat] Raise an RFI failed', error);
4365
+ said = error?.plain === true && error.message ? error.message : unreachable;
4366
+ }
4367
+ announce(said);
4368
+ });
4369
+ const assume = button('Ask the AI to propose an assumption', 'shell.chat-readiness-assume', 'ai-chat-source-action');
4370
+ assume.dataset.commandInstanceLabel = about;
4371
+ assume.setAttribute('aria-label', `Ask the AI to propose an assumption: ${about}`);
4372
+ assume.dataset.tip = 'Puts a request in the message box. Nothing is sent until you press Send. The AI then shows the assumption on a card, and only your Confirm records it';
4373
+ assume.addEventListener('click', () => addToMessageBox(`For ${about}: propose an assumption I can go on with for ${failing.length ? failing.join('; ') : 'what FloLess could not check'}, on a card for me to confirm. Name each check exactly as the readiness card does.`));
4374
+ actions.append(rfi, assume);
4375
+ }
4376
+ if (READINESS_SIGNABLE.has(row.review) && card.projectId) {
4377
+ const sign = button('Open to sign off', 'shell.chat-readiness-sign-off', 'ai-chat-source-action');
4378
+ sign.dataset.commandInstanceLabel = about;
4379
+ sign.setAttribute('aria-label', `Open to sign off: ${about}`);
4380
+ sign.dataset.tip = 'Opens the project, where you sign off an imported connection yourself. The AI cannot';
4381
+ sign.addEventListener('click', async () => {
4382
+ let opened = false;
4383
+ try { opened = await openActionScreen({ view: 'project', projectId: card.projectId }); } catch { opened = false; }
4384
+ announce(opened ? `Sign off connection ${row.jointId} in the model's connections.` : 'FloLess could not open the project from here. Open it from Workspaces.');
4385
+ });
4386
+ actions.append(sign);
4387
+ }
4388
+ if (actions.childElementCount) wrap.append(actions);
4389
+ return wrap;
4390
+ }
4391
+
3150
4392
  /** One line per action the AI ran itself from this conversation: what it was, and how it ended. */
3151
4393
  function renderActionRow(event) {
3152
4394
  const payload = event.payload || {};
4395
+ if (payload.outcome === 'ok' && payload.card?.kind === 'page' && payload.card.home && payload.card.pageId) return renderPageCard(event);
4396
+ if (payload.outcome === 'ok' && payload.card?.kind === 'connection-readiness') return renderReadinessCard(event);
3153
4397
  const row = document.createElement('div');
3154
4398
  const outcome = payload.outcome === 'ok' ? 'ok' : payload.outcome === 'cancelled' ? 'stopped' : 'failed';
3155
4399
  row.className = `ai-chat-action-row is-${outcome}`;
@@ -3161,7 +4405,8 @@
3161
4405
  glyph.textContent = outcome === 'ok' ? '✓' : outcome === 'stopped' ? '■' : '!';
3162
4406
  const verb = document.createElement('span');
3163
4407
  verb.className = 'ai-chat-action-row-verb';
3164
- verb.textContent = payload.risk === 'read' ? 'Read' : 'Changed';
4408
+ // "Changed" only when the change happened (#2326): a write that ended not done or stopped changed nothing.
4409
+ verb.textContent = payload.risk === 'read' ? 'Read' : outcome === 'ok' ? 'Changed' : 'Tried';
3165
4410
  const title = document.createElement('span');
3166
4411
  title.className = 'ai-chat-action-row-title';
3167
4412
  title.textContent = String(payload.title || payload.actionId || 'A FloLess action');
@@ -3262,6 +4507,728 @@
3262
4507
  return item;
3263
4508
  }
3264
4509
 
4510
+ /*
4511
+ * #2399 PR C2 — THE ASSISTANT'S CARDS in a project, workflow or workspace chat (`next-move` events with
4512
+ * `payload.assistant`; the Guide's own cards stay in web/guide.js). The server owns everything a card is: its class
4513
+ * (blocking / resume / idea, with FloLess's own `fact` line), whose it is, and what a click does. The browser draws it,
4514
+ * names its buttons, and sends only the card id. A card is hidden until the server says how it stands now
4515
+ * (`/api/assistant/cards/state`), so a reload never shows a card already used or set aside as new, and never shows
4516
+ * another account's card. Nothing here sends a message: a follow-up only goes into the message box.
4517
+ */
4518
+ const assistantCardEntries = new Map();
4519
+ const ASSISTANT_CARDS_KEPT = 300;
4520
+ const ASSISTANT_FALLBACK_ERROR = 'FloLess couldn’t do that just now. Try again in a moment.';
4521
+ // A click whose refusal means the card can't be used any more: the card folds to a dimmed line that says why.
4522
+ const ASSISTANT_GONE_CODES = new Set(['assistant-card-target-changed', 'assistant-card-action-gone', 'assistant-card-action-changed',
4523
+ 'assistant-card-project-changed', 'assistant-card-chat-gone', 'assistant-card-missing', 'assistant-card-not-shown', 'assistant-card-scope',
4524
+ 'assistant-card-policy', 'assistant-card-input', 'assistant-quiet', 'assistant-card-instructor']);
4525
+ const assistantStateWanted = new Set();
4526
+ let assistantStateTimer = null;
4527
+ // Bumped when every drawn card is asked again (another account may have signed in): an answer to an older ask is dropped.
4528
+ let assistantStateGeneration = 0;
4529
+ // The one card showing "FloLess had to reset your suggestion settings" (shown once, until the person chooses).
4530
+ let assistantRecoveredCard = '';
4531
+
4532
+ function assistantNode(tag, className, text) {
4533
+ const node = document.createElement(tag);
4534
+ if (className) node.className = className;
4535
+ if (text !== undefined) node.textContent = text;
4536
+ return node;
4537
+ }
4538
+
4539
+ /** "check-connections" → "Check connections". */
4540
+ function assistantPatternLabel(pattern) {
4541
+ const words = String(pattern || '').split('-').filter(Boolean).join(' ');
4542
+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : 'a follow-up';
4543
+ }
4544
+
4545
+ /** What a card says and what its main button is called, by kind (and an action's risk). Never an action's input. */
4546
+ function assistantCardText(move) {
4547
+ const guideText = window.flolessGuide?.moveText?.(move);
4548
+ switch (move?.kind) {
4549
+ case 'action': {
4550
+ const title = String(move.title || 'A FloLess action');
4551
+ if (move.risk === 'read') return { title, action: 'Show it', note: 'Reads only. Nothing changes.' };
4552
+ if (move.risk === 'human-only') return { title, action: 'Open…', note: 'Only you can do this.' };
4553
+ return { title, action: 'Review…', note: 'Opens a request for your OK below. Nothing runs yet.' };
4554
+ }
4555
+ case 'follow-up':
4556
+ return { title: `Ask next: ${assistantPatternLabel(move.pattern)}`, action: 'Put in message box',
4557
+ note: 'Nothing is sent until you press Send. It goes with this chat’s Access when you do.' };
4558
+ case 'create-workflow':
4559
+ return { title: guideText?.title || `Build a workflow: ${move.name || ''}`, action: 'Build it', detail: move.purpose,
4560
+ note: 'Opens New workflow with its name filled in. Nothing is built until you confirm there.' };
4561
+ default:
4562
+ return guideText ? { ...guideText, note: 'Nothing happens until you confirm in the next step.' } : null;
4563
+ }
4564
+ }
4565
+
4566
+ /** What the message box should do with a follow-up's prompt: fill an empty box, leave one that has it, or ask. */
4567
+ function followUpComposeAction(current, prompt) {
4568
+ const held = String(current || '');
4569
+ if (!held.trim()) return 'fill';
4570
+ if (held.includes(prompt)) return 'focus';
4571
+ return 'choose';
4572
+ }
4573
+
4574
+ /** Put text in the message box as the person's own draft, and give them the box with the caret at its end. Never sends. */
4575
+ function putInMessageBox(text) {
4576
+ ui.input.value = text;
4577
+ autosize();
4578
+ saveDraftSoon();
4579
+ updateSendState();
4580
+ ui.input.focus({ preventScroll: true });
4581
+ const end = ui.input.value.length;
4582
+ try { ui.input.setSelectionRange(end, end); } catch { /* a box that takes no selection still has the text */ }
4583
+ }
4584
+
4585
+ function assistantEntry(event) {
4586
+ const payload = event.payload || {};
4587
+ const cardId = String(payload.cardId || event.eventId || '');
4588
+ let entry = assistantCardEntries.get(cardId);
4589
+ if (!entry) {
4590
+ entry = { cardId, event, node: null, signature: '', server: null, busy: '', error: '', fold: null, result: null, compose: null, recovered: false, focus: '' };
4591
+ assistantCardEntries.set(cardId, entry);
4592
+ while (assistantCardEntries.size > ASSISTANT_CARDS_KEPT) {
4593
+ const oldest = assistantCardEntries.keys().next().value;
4594
+ const gone = assistantCardEntries.get(oldest);
4595
+ assistantCardEntries.delete(oldest);
4596
+ // A forgotten card is no longer asked again when the account changes, so nothing it showed may stay up:
4597
+ // its node is emptied and hidden. Drawing the conversation again draws it afresh, checked like a new one.
4598
+ if (gone?.node) { gone.node.replaceChildren(); gone.node.hidden = true; }
4599
+ }
4600
+ }
4601
+ entry.event = event;
4602
+ return entry;
4603
+ }
4604
+
4605
+ /** Ask the server how cards stand, a few at a time (every card drawn in one repaint goes in one request). */
4606
+ function wantAssistantState(cardId) {
4607
+ assistantStateWanted.add(cardId);
4608
+ if (assistantStateTimer) return;
4609
+ assistantStateTimer = setTimeout(() => { assistantStateTimer = null; void readAssistantStates(); }, 0);
4610
+ }
4611
+
4612
+ async function readAssistantStates() {
4613
+ const ids = [...assistantStateWanted].slice(0, 100);
4614
+ for (const id of ids) assistantStateWanted.delete(id);
4615
+ if (!ids.length) return;
4616
+ const generation = assistantStateGeneration;
4617
+ try {
4618
+ const body = await request('/api/assistant/cards/state', { method: 'POST', body: JSON.stringify({ cardIds: ids }) });
4619
+ // Asked again meanwhile: this answer may be for the account before, and the newer ask covers these cards.
4620
+ if (generation !== assistantStateGeneration) return;
4621
+ const answered = new Set();
4622
+ for (const row of Array.isArray(body?.cards) ? body.cards : []) {
4623
+ const entry = assistantCardEntries.get(row?.cardId);
4624
+ if (!entry) continue;
4625
+ answered.add(row.cardId);
4626
+ entry.server = row;
4627
+ entry.stateError = '';
4628
+ if (row.state === 'used' && row.outcome === 'read' && row.result) entry.result = row.result;
4629
+ repaintAssistantCard(entry);
4630
+ }
4631
+ // An id the server did not answer (not a card id) is a card FloLess does not have.
4632
+ for (const id of ids) {
4633
+ const entry = assistantCardEntries.get(id);
4634
+ if (entry && !answered.has(id)) { entry.server = { cardId: id, state: 'missing' }; repaintAssistantCard(entry); }
4635
+ }
4636
+ } catch (error) {
4637
+ if (generation !== assistantStateGeneration) return;
4638
+ // Not known yet. The card is never drawn hidden for good: the AI has said a card is shown, so the person sees that
4639
+ // FloLess couldn't check it, with Retry — and nothing of the card itself (it may belong to another account).
4640
+ console.warn('[assistant] could not read how the suggestion cards stand:', error);
4641
+ for (const id of ids) {
4642
+ const entry = assistantCardEntries.get(id);
4643
+ if (!entry) continue;
4644
+ // A card already drawn is forgotten too: what it showed may have been for the account before.
4645
+ entry.server = null;
4646
+ entry.result = null;
4647
+ entry.stateError = 'FloLess couldn’t check this suggestion just now.';
4648
+ repaintAssistantCard(entry);
4649
+ }
4650
+ }
4651
+ if (assistantStateWanted.size) wantAssistantState([...assistantStateWanted][0]);
4652
+ }
4653
+
4654
+ /** Every card drawn on this page, asked about again (the account or the window may have changed meanwhile). */
4655
+ function rereadAssistantStates() {
4656
+ assistantStateGeneration++;
4657
+ for (const entry of assistantCardEntries.values()) { entry.stateError = ''; wantAssistantState(entry.cardId); }
4658
+ }
4659
+
4660
+ function renderAssistantCard(event) {
4661
+ const entry = assistantEntry(event);
4662
+ // A failed check waits for Retry (or the window coming back) rather than asking again on every repaint.
4663
+ if (!entry.server && !entry.stateError) wantAssistantState(entry.cardId);
4664
+ const signature = JSON.stringify([entry.server, entry.stateError || '', entry.busy, entry.error, entry.fold, entry.result, entry.compose, entry.recovered,
4665
+ entry.cardId === assistantRecoveredCard]);
4666
+ if (entry.node && entry.signature === signature) return entry.node;
4667
+ entry.node = paintAssistantCard(entry);
4668
+ entry.signature = signature;
4669
+ return entry.node;
4670
+ }
4671
+
4672
+ function repaintAssistantCard(entry) {
4673
+ const old = entry.node;
4674
+ const hadFocus = Boolean(old && old.contains(document.activeElement));
4675
+ const focusId = entry.focus || (hadFocus ? document.activeElement?.dataset?.commandId : '');
4676
+ entry.signature = '';
4677
+ const next = renderAssistantCard(entry.event);
4678
+ if (old && old !== next && old.isConnected) old.replaceWith(next);
4679
+ if (focusId === 'status') { entry.focus = ''; focusAssistantStatus(entry); return; }
4680
+ if (focusId || hadFocus) {
4681
+ const target = (focusId && [...next.querySelectorAll('button')].find((b) => b.dataset.commandId === focusId && !b.disabled))
4682
+ || next.querySelector('button:not([disabled])') || next.querySelector('[role="status"]');
4683
+ target?.focus({ preventScroll: true });
4684
+ }
4685
+ entry.focus = '';
4686
+ }
4687
+
4688
+ /** A button of this card. Its Instructor instance is the card's title. */
4689
+ function assistantButton(label, commandId, title, className = '') {
4690
+ const control = button(label, commandId, className);
4691
+ control.dataset.commandInstanceLabel = title;
4692
+ return control;
4693
+ }
4694
+
4695
+ function paintAssistantCard(entry) {
4696
+ const payload = entry.event.payload || {};
4697
+ const move = payload.move || {};
4698
+ const text = assistantCardText(move) || { title: 'A suggestion', action: 'Open', note: '' };
4699
+ const card = assistantNode('section', 'ai-chat-filter-card ai-chat-action-card assistant-card');
4700
+ card.dataset.eventId = entry.event.eventId;
4701
+ card.dataset.cardId = entry.cardId;
4702
+ card.setAttribute('role', 'group');
4703
+ const titleId = `assistant-card-title-${entry.cardId}`;
4704
+ card.setAttribute('aria-labelledby', titleId);
4705
+ const server = entry.server;
4706
+ // Not known yet: drawn hidden, so another account's card or one already used never flashes up as new.
4707
+ if (!server && entry.stateError) {
4708
+ // The check failed: say so where the card would be, with Retry, and show nothing of the card itself.
4709
+ card.classList.add('is-collapsed');
4710
+ const line = assistantNode('p', 'ai-chat-action-line', entry.stateError);
4711
+ const retry = button('Retry', 'shell.assistant-card-retry');
4712
+ retry.dataset.commandInstanceLabel = 'this suggestion';
4713
+ retry.dataset.tip = 'Checks this suggestion again.';
4714
+ retry.addEventListener('click', () => { entry.stateError = ''; repaintAssistantCard(entry); });
4715
+ card.append(line, retry);
4716
+ return card;
4717
+ }
4718
+ if (!server) { card.hidden = true; return card; }
4719
+
4720
+ const status = assistantNode('p', 'ai-chat-filter-note ai-chat-action-status assistant-card-status');
4721
+ status.setAttribute('role', 'status');
4722
+ status.tabIndex = -1;
4723
+ status.textContent = entry.error;
4724
+ const fold = (line, { undo = false, dim = false, again = false } = {}) => {
4725
+ card.classList.add('is-collapsed');
4726
+ if (dim) card.classList.add('is-gone');
4727
+ const row = assistantNode('div', 'assistant-card-line');
4728
+ const words = assistantNode('p', 'ai-chat-action-line', line);
4729
+ words.id = titleId;
4730
+ row.append(words);
4731
+ if (undo) {
4732
+ const back = assistantButton('Undo', 'shell.assistant-card-undo', text.title);
4733
+ back.dataset.tip = 'Shows this suggestion again.';
4734
+ back.disabled = Boolean(entry.busy);
4735
+ back.addEventListener('click', () => { void bringBackAssistantCard(entry, text.title); });
4736
+ row.append(back);
4737
+ }
4738
+ if (again) {
4739
+ // The request this card made is its own card below; this finds it again (and puts it back if it went missing).
4740
+ const show = assistantButton(entry.busy === 'use' ? 'Checking…' : 'Show the request', `shell.assistant-card-use#${move.kind || 'action'}`, text.title);
4741
+ show.dataset.tip = 'Shows the request for your OK again. Nothing runs from this card.';
4742
+ show.disabled = Boolean(entry.busy);
4743
+ show.addEventListener('click', () => { void useAssistantCard(entry, text); });
4744
+ row.append(show);
4745
+ }
4746
+ card.append(row, status);
4747
+ return card;
4748
+ };
4749
+
4750
+ if (server.state === 'other-account') return fold('This suggestion belongs to another account.', { dim: true });
4751
+ if (server.state === 'missing') return fold(`No longer applies: ${text.title}. FloLess no longer has this suggestion.`, { dim: true });
4752
+ if (entry.fold?.gone) return fold(`No longer applies: ${text.title}. ${entry.fold.reason}`, { dim: true });
4753
+ if (server.state === 'dismissed') {
4754
+ const returns = server.dismissed?.returns ? new Date(server.dismissed.returns) : null;
4755
+ const day = returns && !Number.isNaN(returns.getTime()) ? returns.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) : '';
4756
+ return fold(server.dismissed?.how === 'never' ? `Won’t suggest again: ${text.title}.`
4757
+ : day ? `Not now: ${text.title}. Back on ${day}.` : `Not now: ${text.title}.`, { undo: true });
4758
+ }
4759
+ // Folded only when this window put it there: after a reload the card is offered again (its button replays it).
4760
+ if (server.state === 'used' && server.outcome === 'compose' && entry.fold?.composed) return fold(`Put in message box: ${text.title}`);
4761
+ if (server.state === 'used' && server.outcome === 'proposal') return fold(`Sent for your OK below: ${text.title}`, { again: true });
4762
+ if (server.state === 'used' && (server.outcome === 'open' || server.outcome === 'screen') && entry.fold?.opened !== false) {
4763
+ return fold(`Opened: ${text.title}`);
4764
+ }
4765
+
4766
+ // The server re-checks the reason on every click: its answer wins over the card as first drawn (a failed workflow
4767
+ // that has since run fine is no longer a "Next step", and its old fact must not stay on the card).
4768
+ const cardClass = server.cardClass ?? payload.cardClass;
4769
+ const fact = 'fact' in server ? server.fact : payload.fact;
4770
+ const blocking = cardClass === 'blocking' || cardClass === 'resume';
4771
+ if (!blocking) card.classList.add('is-idea');
4772
+ const head = assistantNode('div', 'ai-chat-filter-card-head');
4773
+ const named = assistantNode('div', 'ai-chat-action-named');
4774
+ const strong = assistantNode('strong', '', text.title);
4775
+ strong.id = titleId;
4776
+ named.append(assistantNode('span', 'guide-move-eyebrow', blocking ? 'Next step' : 'Suggested'), strong);
4777
+ head.append(named);
4778
+ card.append(head);
4779
+ if (blocking && typeof fact === 'string' && fact.trim()) card.append(assistantNode('p', 'ai-chat-filter-note assistant-card-fact', fact.trim()));
4780
+ // The catalog summary only when it says more than the title (some actions repeat their title as their summary).
4781
+ if (move.kind === 'action' && move.summary && String(move.summary).trim() !== String(text.title).trim()) card.append(assistantNode('p', 'ai-chat-action-summary', String(move.summary)));
4782
+ if (text.detail) card.append(assistantNode('p', 'ai-chat-filter-why', String(text.detail)));
4783
+ if (move.kind === 'follow-up') card.append(assistantNode('blockquote', 'assistant-card-prompt', String(move.prompt || '')));
4784
+ const why = typeof payload.why === 'string' ? payload.why.trim() : '';
4785
+ if (why) card.append(assistantNode('p', 'ai-chat-filter-why ai-chat-action-why assistant-card-why', `Why: ${why}`));
4786
+ if (entry.result) card.append(paintAssistantResult(entry.result));
4787
+ if (server.state === 'used' && server.message && !entry.result) status.textContent = entry.error || String(server.message);
4788
+
4789
+ if (entry.compose) {
4790
+ // The person is writing something else: never overwrite it without asking.
4791
+ const choice = assistantNode('div', 'assistant-card-compose');
4792
+ choice.append(assistantNode('p', 'ai-chat-filter-note', 'You’re writing a message.'));
4793
+ const row = assistantNode('div', 'ai-chat-filter-actions');
4794
+ const replace = assistantButton('Replace it', 'shell.assistant-card-compose-replace', text.title);
4795
+ replace.dataset.tip = 'Replaces what is in the message box with this message. Nothing is sent.';
4796
+ replace.addEventListener('click', () => { composeAssistantFollowUp(entry, text.title, 'replace'); });
4797
+ const append = assistantButton('Add below it', 'shell.assistant-card-compose-append', text.title, 'ai-chat-filter-apply');
4798
+ append.dataset.tip = 'Adds this message below what you are writing. Nothing is sent.';
4799
+ append.addEventListener('click', () => { composeAssistantFollowUp(entry, text.title, 'append'); });
4800
+ row.append(replace, append);
4801
+ choice.append(row);
4802
+ card.append(choice, status);
4803
+ return card;
4804
+ }
4805
+
4806
+ const actions = assistantNode('div', 'ai-chat-filter-actions');
4807
+ const later = assistantButton('Not now', 'shell.assistant-card-not-now', text.title);
4808
+ later.dataset.tip = 'Hides this for 7 days. Undo on this card brings it back, or ask the AI in any chat to bring it back.';
4809
+ later.addEventListener('click', () => { void dismissAssistantCard(entry, text.title, 'not-now'); });
4810
+ const never = assistantButton('Don’t suggest again', 'shell.assistant-card-never', text.title);
4811
+ never.dataset.tip = 'Stops this suggestion for your account. Undo on this card brings it back, or ask the AI in any chat to bring it back.';
4812
+ never.addEventListener('click', () => { void dismissAssistantCard(entry, text.title, 'never'); });
4813
+ const use = assistantButton(entry.busy === 'use' ? 'Checking…' : text.action, `shell.assistant-card-use#${move.kind || 'open'}`, text.title, 'ai-chat-filter-apply');
4814
+ use.dataset.tip = move.kind === 'follow-up' ? 'Puts this message in the message box. Nothing is sent.'
4815
+ : move.kind === 'action' && move.risk === 'read' ? 'Shows the result here. Nothing changes.'
4816
+ : move.kind === 'action' && move.risk !== 'human-only' ? 'Opens a request below for your OK. Nothing runs from this card.'
4817
+ : 'Opens the place to do this. Nothing happens until you confirm there.';
4818
+ if (entry.busy === 'use') use.setAttribute('aria-busy', 'true');
4819
+ use.addEventListener('click', () => { void useAssistantCard(entry, text); });
4820
+ for (const control of [later, never, use]) control.disabled = Boolean(entry.busy);
4821
+ if (entry.busy) card.setAttribute('aria-busy', 'true');
4822
+ actions.append(later, never, use);
4823
+ card.append(actions);
4824
+ if (text.note) card.append(assistantNode('p', 'ai-chat-filter-note', text.note));
4825
+ if (entry.recovered && entry.cardId === assistantRecoveredCard) {
4826
+ const line = assistantNode('div', 'assistant-card-recovered');
4827
+ line.append(assistantNode('p', 'ai-chat-filter-note', 'FloLess had to reset your suggestion settings. Suggestions are paused until you choose.'));
4828
+ const choose = assistantButton('Choose…', 'shell.assistant-recovered-choose', 'Suggest next steps');
4829
+ choose.dataset.tip = 'Opens Suggest next steps in this chat’s settings.';
4830
+ choose.addEventListener('click', () => { void chooseAssistantMode(); });
4831
+ line.append(choose);
4832
+ card.append(line);
4833
+ }
4834
+ card.append(status);
4835
+ return card;
4836
+ }
4837
+
4838
+ /**
4839
+ * A read result as plain rows: each top-level field with a readable name ("runId" → "Run id") and a plain value
4840
+ * (Yes/No, a date as written, "—" for none). Nested lists and objects are counted ("12 items", "details"), and
4841
+ * `rows.hidden` says some detail was left out.
4842
+ */
4843
+ function assistantResultRows(data) {
4844
+ const rows = [];
4845
+ rows.hidden = false;
4846
+ const clip = (value, max) => { const s = String(value); if (s.length <= max) return s; rows.hidden = true; return `${s.slice(0, max - 1)}… (shortened)`; };
4847
+ if (typeof data === 'string') { if (data.trim()) rows.push(['Result', clip(data.trim(), 400)]); return rows; }
4848
+ if (!data || typeof data !== 'object' || Array.isArray(data)) {
4849
+ if (Array.isArray(data)) { rows.push(['Items', `${data.length}`]); rows.hidden = data.length > 0; }
4850
+ else if (data !== undefined && data !== null) rows.push(['Result', String(data)]);
4851
+ return rows;
4852
+ }
4853
+ const label = (key) => {
4854
+ const words = String(key).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').trim().toLowerCase();
4855
+ return words.charAt(0).toUpperCase() + words.slice(1);
4856
+ };
4857
+ for (const [key, value] of Object.entries(data)) {
4858
+ // A route's own `ok: true` only repeats that the read worked; any other `ok` is data and is shown.
4859
+ if (key === 'ok' && value === true) continue;
4860
+ if (rows.length >= 12) { rows.hidden = true; break; }
4861
+ if (value === null || value === undefined) rows.push([label(key), '—']);
4862
+ else if (typeof value === 'boolean') rows.push([label(key), value ? 'Yes' : 'No']);
4863
+ else if (typeof value === 'number' || typeof value === 'string') rows.push([label(key), clip(value, 200)]);
4864
+ else if (Array.isArray(value)) { rows.push([label(key), value.length === 1 ? '1 item' : `${value.length} items`]); if (value.length) rows.hidden = true; }
4865
+ else { rows.push([label(key), 'details']); rows.hidden = true; }
4866
+ }
4867
+ return rows;
4868
+ }
4869
+
4870
+ /** Every field of a read result, nested lists and objects included, as plain rows; values in full. */
4871
+ function assistantResultTree(data, depth) {
4872
+ const label = (key) => {
4873
+ const words = String(key).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').trim().toLowerCase();
4874
+ return words.charAt(0).toUpperCase() + words.slice(1);
4875
+ };
4876
+ const plain = (value) => value === null || value === undefined ? '—' : typeof value === 'boolean' ? (value ? 'Yes' : 'No') : String(value);
4877
+ if (data === null || typeof data !== 'object') return assistantNode('span', '', plain(data));
4878
+ const list = document.createElement('dl');
4879
+ list.className = 'assistant-card-result-list';
4880
+ // Only the route's own top-level `ok: true` is left out (it repeats that the read worked); any other `ok` is data.
4881
+ const entries = Array.isArray(data) ? data.map((value, i) => [`${i + 1}`, value])
4882
+ : Object.entries(data).filter(([key, value]) => depth > 0 || key !== 'ok' || value !== true);
4883
+ if (!entries.length) return assistantNode('span', '', Array.isArray(data) ? 'None' : '—');
4884
+ for (const [key, value] of entries) {
4885
+ const dd = document.createElement('dd');
4886
+ // Every level is laid out: the result is the server's own bounded JSON, so nothing is cut here.
4887
+ if (value !== null && typeof value === 'object') dd.append(assistantResultTree(value, depth + 1));
4888
+ else dd.textContent = plain(value);
4889
+ list.append(assistantNode('dt', '', Array.isArray(data) ? key : label(key)), dd);
4890
+ }
4891
+ return list;
4892
+ }
4893
+
4894
+ /** A read's result, kept by the server: shown in plain rows in a bounded themed scroller. */
4895
+ function paintAssistantResult(result) {
4896
+ const wrap = assistantNode('div', 'assistant-card-result');
4897
+ if (!result.ok) {
4898
+ wrap.append(assistantNode('p', 'ai-chat-filter-note', String(result.message || 'It did not complete.')));
4899
+ return wrap;
4900
+ }
4901
+ // Plain words, never raw data: a person reads this card. Top-level facts become "Field: value" rows; anything
4902
+ // nested is counted, not dumped — the AI in this chat can explain the details if the person asks.
4903
+ const body = assistantNode('div', 'assistant-card-result-body');
4904
+ body.tabIndex = 0;
4905
+ body.setAttribute('role', 'group');
4906
+ body.setAttribute('aria-label', 'Result');
4907
+ const rows = assistantResultRows(result.data);
4908
+ if (!rows.length) body.append(assistantNode('p', 'assistant-card-result-empty', 'Nothing to show.'));
4909
+ else {
4910
+ const list = document.createElement('dl');
4911
+ list.className = 'assistant-card-result-list';
4912
+ for (const [label, value] of rows) list.append(assistantNode('dt', '', label), assistantNode('dd', '', value));
4913
+ body.append(list);
4914
+ }
4915
+ wrap.append(body);
4916
+ if (rows.hidden) {
4917
+ // Everything the read returned, laid out in plain nested rows (never raw data), on request.
4918
+ const more = button('Show all details', 'shell.assistant-card-result-details', 'assistant-card-result-more');
4919
+ more.setAttribute('aria-expanded', 'false');
4920
+ more.dataset.tip = 'Shows everything this read returned, in full.';
4921
+ const full = assistantNode('div', 'assistant-card-result-body assistant-card-result-full');
4922
+ full.tabIndex = 0;
4923
+ full.setAttribute('role', 'group');
4924
+ full.setAttribute('aria-label', 'All details');
4925
+ full.hidden = true;
4926
+ full.append(assistantResultTree(result.data, 0));
4927
+ more.addEventListener('click', () => {
4928
+ const open = full.hidden;
4929
+ full.hidden = !open;
4930
+ more.setAttribute('aria-expanded', String(open));
4931
+ more.textContent = open ? 'Hide details' : 'Show all details';
4932
+ });
4933
+ wrap.append(more, full);
4934
+ }
4935
+ if (result.truncated && result.message) wrap.append(assistantNode('p', 'ai-chat-filter-note', String(result.message)));
4936
+ return wrap;
4937
+ }
4938
+
4939
+ /** A refusal from a card route: a plain sentence on the card, a fold when the card can't be used any more. */
4940
+ function assistantRefused(entry, error) {
4941
+ const code = error?.code || '';
4942
+ const message = typeof error?.message === 'string' && error.message && error.status ? error.message : ASSISTANT_FALLBACK_ERROR;
4943
+ if (code === 'assistant-card-other-account') { entry.server = { cardId: entry.cardId, state: 'other-account' }; return; }
4944
+ if (code === 'assistant-card-dismissed') { entry.server = null; wantAssistantState(entry.cardId); return; }
4945
+ if (ASSISTANT_GONE_CODES.has(code)) { entry.fold = { gone: true, reason: message }; return; }
4946
+ if (code === 'assistant-settings-recovered' && (!assistantRecoveredCard || !assistantCardEntries.has(assistantRecoveredCard))) {
4947
+ assistantRecoveredCard = entry.cardId; entry.recovered = true;
4948
+ }
4949
+ entry.error = message;
4950
+ }
4951
+
4952
+ async function useAssistantCard(entry, text) {
4953
+ if (entry.busy) return;
4954
+ const chatId = entry.event.chatId;
4955
+ entry.busy = 'use'; entry.error = '';
4956
+ repaintAssistantCard(entry);
4957
+ let answer = null;
4958
+ try {
4959
+ const body = await request(`/api/assistant/cards/${encodeURIComponent(entry.cardId)}/use`, { method: 'POST', body: '{}' });
4960
+ answer = body?.card || null;
4961
+ } catch (error) {
4962
+ assistantRefused(entry, error);
4963
+ }
4964
+ entry.busy = '';
4965
+ if (!answer) { entry.focus = 'status'; repaintAssistantCard(entry); return; }
4966
+ entry.server = { ...(entry.server || {}), cardId: entry.cardId, state: 'used', outcome: answer.outcome,
4967
+ ...(typeof answer.cardClass === 'string' ? { cardClass: answer.cardClass } : {}),
4968
+ // An answer without a fact clears the one the card was drawn with: it no longer holds.
4969
+ ...(typeof answer.cardClass === 'string' ? { fact: typeof answer.fact === 'string' ? answer.fact : null } : {}) };
4970
+ const title = text.title;
4971
+ if (answer.outcome === 'read') {
4972
+ entry.result = answer.result || { ok: false, message: 'FloLess kept no result for this.' };
4973
+ repaintAssistantCard(entry);
4974
+ announce(entry.result.ok ? `${title}: shown on the card.` : `${title}: it did not complete.`);
4975
+ return;
4976
+ }
4977
+ if (answer.outcome === 'indeterminate') {
4978
+ entry.error = answer.message || ASSISTANT_FALLBACK_ERROR;
4979
+ entry.focus = 'status'; repaintAssistantCard(entry); return;
4980
+ }
4981
+ if (answer.outcome === 'compose') {
4982
+ // The conversation may have changed while FloLess answered: the message box now belongs to another chat.
4983
+ if (state.chat?.chatId !== chatId || !ui.input || ui.input.disabled) {
4984
+ entry.server = { ...entry.server, state: 'shown' };
4985
+ entry.error = 'Open this conversation, then press Put in message box again. Nothing was sent.';
4986
+ entry.focus = 'status'; repaintAssistantCard(entry); return;
4987
+ }
4988
+ const prompt = String(answer.prompt || entry.event.payload?.move?.prompt || '');
4989
+ const action = followUpComposeAction(ui.input.value, prompt);
4990
+ if (action === 'choose') {
4991
+ entry.server = { ...entry.server, state: 'shown' };
4992
+ entry.compose = { prompt };
4993
+ entry.focus = 'shell.assistant-card-compose-append';
4994
+ repaintAssistantCard(entry);
4995
+ return;
4996
+ }
4997
+ entry.fold = { composed: true };
4998
+ repaintAssistantCard(entry);
4999
+ // After the repaint, so the keyboard ends in the message box, never back on the card.
5000
+ if (action === 'fill') putInMessageBox(prompt);
5001
+ else ui.input.focus({ preventScroll: true });
5002
+ announce(`Put in message box: ${title}. Press Send when you are ready.`);
5003
+ return;
5004
+ }
5005
+ if (answer.outcome === 'proposal') {
5006
+ repaintAssistantCard(entry);
5007
+ announce(`Sent for your OK below: ${title}.`);
5008
+ // The request arrives as its own card; if it never does, say so here (pressing Show the request asks again).
5009
+ const missing = () => { entry.error = 'FloLess couldn’t show the request just now. Press Show the request to try again.'; entry.focus = 'status'; repaintAssistantCard(entry); };
5010
+ if (answer.proposalId) focusProposalConfirm(answer.proposalId, missing); else missing();
5011
+ return;
5012
+ }
5013
+ // Open the place: a human-only action's screen, or the flow for a tool, workflow, agent, routine or page.
5014
+ let opened = false;
5015
+ try {
5016
+ if (answer.outcome === 'screen') opened = await openActionScreen(answer.screen);
5017
+ else if (answer.move?.kind === 'create-workflow' && typeof window.flolessBridge?.newWorkflow === 'function') {
5018
+ opened = true;
5019
+ void window.flolessBridge.newWorkflow({ name: answer.move.name });
5020
+ } else if (answer.move) opened = Boolean(await window.flolessGuide?.openFlow?.(answer.move));
5021
+ } catch (error) {
5022
+ console.warn('[assistant] a suggestion could not open its place:', error);
5023
+ opened = false;
5024
+ }
5025
+ if (!opened) {
5026
+ entry.fold = { opened: false };
5027
+ entry.error = 'FloLess couldn’t open that from here. Open it from the ≡ menu instead.';
5028
+ entry.focus = 'status'; repaintAssistantCard(entry); return;
5029
+ }
5030
+ entry.fold = null;
5031
+ repaintAssistantCard(entry);
5032
+ announce(`Opened: ${title}.`);
5033
+ }
5034
+
5035
+ /** The follow-up into a box that holds something else, as the person chose: below it, or instead of it. Never sends. */
5036
+ function composeAssistantFollowUp(entry, title, how) {
5037
+ const prompt = entry.compose?.prompt || '';
5038
+ if (!prompt) return;
5039
+ if (state.chat?.chatId !== entry.event.chatId || !ui.input || ui.input.disabled) {
5040
+ entry.error = 'Open this conversation to put the message in its message box. Nothing was sent.';
5041
+ repaintAssistantCard(entry); return;
5042
+ }
5043
+ const held = ui.input.value;
5044
+ entry.compose = null;
5045
+ entry.fold = { composed: true };
5046
+ entry.server = { ...(entry.server || {}), cardId: entry.cardId, state: 'used', outcome: 'compose' };
5047
+ repaintAssistantCard(entry);
5048
+ // After the repaint, so the caret ends in the message box.
5049
+ putInMessageBox(how === 'replace' || !held.trim() ? prompt : held.includes(prompt) ? held : `${held.replace(/\s+$/, '')}\n\n${prompt}`);
5050
+ announce(`Put in message box: ${title}. Press Send when you are ready.`);
5051
+ }
5052
+
5053
+ async function dismissAssistantCard(entry, title, how) {
5054
+ if (entry.busy) return;
5055
+ entry.busy = how; entry.error = '';
5056
+ repaintAssistantCard(entry);
5057
+ try {
5058
+ const body = await request(`/api/assistant/cards/${encodeURIComponent(entry.cardId)}/${how}`, { method: 'POST', body: '{}' });
5059
+ entry.server = { ...(entry.server || {}), cardId: entry.cardId, state: 'dismissed',
5060
+ dismissed: { how, ...(body?.suggestion?.until ? { returns: body.suggestion.until } : {}) } };
5061
+ entry.focus = 'shell.assistant-card-undo';
5062
+ announce(how === 'never' ? `Won’t suggest again: ${title}.` : `Not now: ${title}.`);
5063
+ } catch (error) {
5064
+ assistantRefused(entry, error);
5065
+ entry.focus = 'status';
5066
+ } finally {
5067
+ entry.busy = '';
5068
+ repaintAssistantCard(entry);
5069
+ }
5070
+ }
5071
+
5072
+ async function bringBackAssistantCard(entry, title) {
5073
+ if (entry.busy) return;
5074
+ entry.busy = 'undo'; entry.error = '';
5075
+ repaintAssistantCard(entry);
5076
+ try {
5077
+ const body = await request(`/api/assistant/cards/${encodeURIComponent(entry.cardId)}/bring-back`, { method: 'POST', body: '{}' });
5078
+ const status = body?.card?.status === 'used' ? 'used' : 'shown';
5079
+ entry.server = { ...(entry.server || {}), cardId: entry.cardId, state: status };
5080
+ delete entry.server.dismissed;
5081
+ entry.focus = `shell.assistant-card-use#${entry.event.payload?.move?.kind || 'open'}`;
5082
+ announce(`Brought back: ${title}.`);
5083
+ } catch (error) {
5084
+ assistantRefused(entry, error);
5085
+ entry.focus = 'status';
5086
+ } finally {
5087
+ entry.busy = '';
5088
+ repaintAssistantCard(entry);
5089
+ }
5090
+ }
5091
+
5092
+ function focusAssistantStatus(entry) {
5093
+ const status = entry.node?.querySelector('.assistant-card-status');
5094
+ if (status?.textContent) status.focus({ preventScroll: true });
5095
+ }
5096
+
5097
+ /** The request a card made arrives as its own card below (an event): its Confirm gets the keyboard once it is drawn. */
5098
+ function focusProposalConfirm(proposalId, onMissing = () => {}, tries = 40) {
5099
+ const proposal = ui.feed?.querySelector(`.ai-chat-action-card[data-proposal-id="${CSS.escape(proposalId)}"]`);
5100
+ if (proposal) {
5101
+ // Its Confirm (or a person-only step's Open); a request already answered has neither, so its own line.
5102
+ const target = proposal.querySelector('[data-command-id^="shell.chat-action-confirm"]:not([disabled])')
5103
+ || proposal.querySelector('[data-command-id^="shell.chat-action-open"]') || proposal.querySelector('.ai-chat-action-status');
5104
+ if (target && !target.hasAttribute('tabindex') && target.tagName === 'P') target.tabIndex = -1;
5105
+ (target || proposal).focus?.({ preventScroll: false });
5106
+ return;
5107
+ }
5108
+ if (tries > 0) setTimeout(() => focusProposalConfirm(proposalId, onMissing, tries - 1), 125);
5109
+ else onMissing();
5110
+ }
5111
+
5112
+ /** The recovered line's Choose…: the chat's settings, open at Suggest next steps. */
5113
+ async function chooseAssistantMode() {
5114
+ if (ui.settings?.hidden) ui.settingsToggle?.click();
5115
+ await assistantMode.refresh();
5116
+ if (ui.suggest && !ui.suggest.disabled) openPicker('suggest', ui.suggest, assistantMode.choices());
5117
+ }
5118
+
5119
+ /*
5120
+ * #2478: what FloLess recorded while the AI answered (objects it linked or named, sheets it looked at, a change it
5121
+ * made to the model view) folds under the answer into one quiet line, the way AI apps show their working. The line
5122
+ * says what happened: a change is named in words with anything still to be said about it, and only reads are
5123
+ * counted. Anything that went wrong, anything still running, anything that asks the person, and the answer's sources
5124
+ * never fold. Each fold is one node, kept while its conversation is open and reused across repaints, so whether it
5125
+ * is open and its focus survive streaming.
5126
+ */
5127
+ const receiptFolds = new Map();
5128
+ let receiptFoldsChat = null;
5129
+ let receiptFoldIds = 0;
5130
+ const EVIDENCE_COUNTS = { sheet: 'sheets', 'sheet-tiles': 'sheets', 'attachment-image': 'attachments', 'attachment-pdf': 'attachments' };
5131
+
5132
+ /** One receipt's part of its answer's fold line, or null when it must stay in sight. */
5133
+ function foldableReceipt(event) {
5134
+ const payload = event?.payload || {};
5135
+ if (event?.type === 'chat-subjects') {
5136
+ const count = Array.isArray(payload.items) ? payload.items.length : 0;
5137
+ return count ? { count: payload.role === 'answer' ? 'named' : 'linked', n: count } : null;
5138
+ }
5139
+ if (event?.type === 'evidence-read') return payload.outcome === 'read' ? { count: EVIDENCE_COUNTS[payload.kind] || 'items', n: 1 } : null;
5140
+ if (event?.type === 'view-command') {
5141
+ // Only a change the editor confirmed folds, named by its own words and every caveat FloLess wrote beside it. A
5142
+ // change still running, not confirmed or not fully done stays in sight, and so does one recorded before FloLess
5143
+ // wrote its caveats separately: what it left unsaid cannot be told apart from a change that had none.
5144
+ let update = null;
5145
+ for (const item of state.events) if (item.type === 'view-command-update' && item.payload?.commandId === payload.commandId) update = item;
5146
+ const done = update?.payload;
5147
+ if (done?.status !== 'applied' || typeof done.action !== 'string' || !done.action || !Array.isArray(done.caveats)) return null;
5148
+ const caveats = done.caveats.filter((caveat) => typeof caveat === 'string' && caveat);
5149
+ return { change: caveats.length ? `${done.action} (${caveats.join('; ')})` : done.action };
5150
+ }
5151
+ return null;
5152
+ }
5153
+
5154
+ /** The fold line's words: each change in its own words, then what was read, counted. */
5155
+ function receiptFoldSummary(parts) {
5156
+ const changes = [];
5157
+ const totals = { linked: 0, named: 0, sheets: 0, attachments: 0, items: 0 };
5158
+ for (const part of parts) {
5159
+ if (part.change) changes.push(part.change);
5160
+ else if (part.count in totals) totals[part.count] += part.n;
5161
+ }
5162
+ const counted = (n, one, many) => `${n} ${n === 1 ? one : many}`;
5163
+ const looked = [totals.sheets && counted(totals.sheets, 'sheet', 'sheets'), totals.attachments && counted(totals.attachments, 'attachment', 'attachments'),
5164
+ totals.items && counted(totals.items, 'other item', 'other items')].filter(Boolean);
5165
+ const line = [
5166
+ ...changes,
5167
+ totals.linked && `linked ${counted(totals.linked, 'object', 'objects')}`,
5168
+ totals.named && `named ${counted(totals.named, 'object', 'objects')}`,
5169
+ looked.length && `looked at ${looked.length > 1 ? `${looked.slice(0, -1).join(', ')} and ${looked.at(-1)}` : looked[0]}`,
5170
+ ].filter(Boolean).join(' · ');
5171
+ return line.charAt(0).toUpperCase() + line.slice(1);
5172
+ }
5173
+
5174
+ /**
5175
+ * An answer's held receipts, as the feed shows them, in the order they were written: each unbroken stretch of
5176
+ * foldable receipts becomes one line, and anything that stays in sight keeps its own place between them, so an open
5177
+ * fold reads in event order. A stretch only grows (receipts are added at the end, and one that was still running can
5178
+ * become foldable later and join its neighbours), so it reuses the fold of the earliest receipt in it that already
5179
+ * had one: a fold the person opened stays the same fold, still open, as its stretch grows.
5180
+ */
5181
+ function receiptFold(links) {
5182
+ const parts = links.map((link) => (link.event ? foldableReceipt(link.event) : null));
5183
+ if (!parts.some(Boolean)) return links.map((link) => link.node);
5184
+ const chatId = state.chat?.chatId || '';
5185
+ if (receiptFoldsChat !== chatId) { receiptFolds.clear(); receiptFoldsChat = chatId; }
5186
+ const shown = [];
5187
+ for (let start = 0; start < links.length;) {
5188
+ if (!parts[start]) { shown.push(links[start].node); start += 1; continue; }
5189
+ let end = start;
5190
+ while (end < links.length && parts[end]) end += 1;
5191
+ const stretch = links.slice(start, end);
5192
+ let fold = null;
5193
+ for (const link of stretch) if ((fold = receiptFolds.get(link.event.eventId))) break;
5194
+ if (!fold) fold = newReceiptFold(stretch[0].event.eventId);
5195
+ const summary = receiptFoldSummary(parts.slice(start, end));
5196
+ fold.text.textContent = summary;
5197
+ fold.toggle.dataset.commandInstanceLabel = summary;
5198
+ fold.body.replaceChildren(...stretch.map((link) => link.node));
5199
+ shown.push(fold.root);
5200
+ start = end;
5201
+ }
5202
+ return shown;
5203
+ }
5204
+
5205
+ /** One fold line, closed, kept under the event id of the receipt it starts at. */
5206
+ function newReceiptFold(key) {
5207
+ const root = document.createElement('div'); root.className = 'ai-chat-fold';
5208
+ const toggle = button('', 'shell.chat-answer-record', 'ai-chat-fold-toggle');
5209
+ const chevron = Object.assign(document.createElement('span'), { className: 'ai-chat-fold-chevron', textContent: '›' });
5210
+ chevron.setAttribute('aria-hidden', 'true');
5211
+ const text = Object.assign(document.createElement('span'), { className: 'ai-chat-fold-text' });
5212
+ toggle.append(chevron, text);
5213
+ const body = document.createElement('div'); body.className = 'ai-chat-fold-body';
5214
+ body.id = `ai-chat-fold-${++receiptFoldIds}`;
5215
+ body.setAttribute('role', 'group');
5216
+ body.setAttribute('aria-label', 'What FloLess recorded for this answer');
5217
+ toggle.setAttribute('aria-controls', body.id);
5218
+ root.append(toggle, body);
5219
+ const fold = { root, toggle, text, body, open: false };
5220
+ const paint = () => {
5221
+ toggle.setAttribute('aria-expanded', String(fold.open));
5222
+ toggle.dataset.tip = fold.open ? 'Hide what FloLess recorded' : 'Show what FloLess recorded while the AI answered';
5223
+ root.classList.toggle('is-open', fold.open);
5224
+ body.hidden = !fold.open;
5225
+ };
5226
+ toggle.addEventListener('click', () => { fold.open = !fold.open; paint(); });
5227
+ paint();
5228
+ receiptFolds.set(key, fold);
5229
+ return fold;
5230
+ }
5231
+
3265
5232
  function renderEvent(event) {
3266
5233
  if (event.type === 'user-message' && event.payload?.source === 'request' && event.payload?.filterAi) return renderFilterQuestion(event);
3267
5234
  if (event.type === 'user-message' && event.payload?.source === 'request') return renderRequestCard(event);
@@ -3281,6 +5248,8 @@
3281
5248
  if (event.type === 'connection-proposal-update') return null;
3282
5249
  if (event.type === 'connection-check') return renderConnectionCheck(event);
3283
5250
  // #2046: a next move the Guide suggested; web/guide.js paints it and owns its button.
5251
+ // #2399 PR C2: a next step the assistant suggested in a project, workflow or workspace chat; this file paints it.
5252
+ if (event.type === 'next-move' && event.payload?.assistant === true) return renderAssistantCard(event);
3284
5253
  if (event.type === 'next-move') return window.flolessGuide?.renderNextMove?.(event) || null;
3285
5254
  // #2185: what came of a card's button repaints that card; it is never a line of its own.
3286
5255
  if (event.type === 'next-move-update') { window.flolessGuide?.applyMoveUpdate?.(event); return null; }
@@ -3305,13 +5274,13 @@
3305
5274
  if (event.type === 'height-question') return renderHeightQuestion(event);
3306
5275
  if (event.type === 'setup-question') return renderSetupQuestion(event);
3307
5276
  const item = document.createElement('div');
3308
- item.className = `ai-chat-event ${event.type === 'error' ? 'error' : ''}${event.type === 'knowledge-citation' ? ' knowledge' : ''}`;
5277
+ item.className = `ai-chat-event ${event.type === 'error' ? 'error' : ''}`;
3309
5278
  item.dataset.eventSequence = String(event.sequence);
3310
5279
  item.dataset.eventId = event.eventId;
3311
5280
  const label = document.createElement('strong');
3312
5281
  const labels = {
3313
5282
  attachment: 'Attachment', tool: 'AI action', error: 'Error', interrupted: 'Stopped', usage: 'AI usage',
3314
- compaction: 'Conversation summary updated', 'knowledge-citation': 'Knowledge cited', state: 'Status', request: 'Request',
5283
+ compaction: 'Conversation summary updated', state: 'Status', request: 'Request',
3315
5284
  };
3316
5285
  const payload = event.payload || {};
3317
5286
  if (event.type === 'chat-subjects') {
@@ -3355,7 +5324,6 @@
3355
5324
  const statusLabels = { started: 'started', completed: 'completed', failed: 'failed', denied: 'not allowed' };
3356
5325
  detail = [toolLabels[payload.tool] || 'AI action', statusLabels[payload.status] || payload.status].filter(Boolean).join(' · ');
3357
5326
  }
3358
- if (!detail && event.type === 'knowledge-citation') detail = Array.isArray(payload.pageSlugs) ? payload.pageSlugs.join(', ') : '';
3359
5327
  if (!detail && event.type === 'interrupted') detail = 'The AI response was interrupted.';
3360
5328
  if (!detail && event.type === 'usage') {
3361
5329
  detail = 'Usage updated';
@@ -3460,7 +5428,9 @@
3460
5428
  if (!snapshot) return '';
3461
5429
  if (snapshot.state === 'unknown' || typeof snapshot.value !== 'number') return 'In the model when asked: no height.';
3462
5430
  const value = heightInModelValue(snapshot.value, units);
3463
- const tail = snapshot.state === 'assumed' ? ' (placed, not from the drawings)' : snapshot.state === 'answered' ? ' (your earlier answer)' : '';
5431
+ const tail = snapshot.state === 'assumed' ? ' (placed, not from the drawings)' : snapshot.state === 'answered' ? ' (your earlier answer)'
5432
+ // #2521: chosen by the AI in a Quick model build. Said plainly, so the person never takes it for a drawn height.
5433
+ : snapshot.state === 'decided' ? ' (chosen by the AI in the Quick model, not from the drawings or you)' : '';
3464
5434
  return `In the model when asked: ${value}${tail}.`;
3465
5435
  };
3466
5436
  const HEIGHT_PROPOSED_TEXT = 'Proposed in the review; the model changes only if you accept it there.';
@@ -5177,7 +7147,11 @@
5177
7147
  caret = { start: focusedNode.selectionStart, end: focusedNode.selectionEnd, direction: focusedNode.selectionDirection || 'none' };
5178
7148
  }
5179
7149
  } catch { caret = null; } // a checkbox or radio has no caret, and some engines throw on reading it
5180
- for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows')) list.keptScrollTop = list.scrollTop;
7150
+ // A reused card node is detached and re-attached here, and a detached element forgets its scroll: the height
7151
+ // card's lists, and the readiness card's own scroll area and table (#2439), are noted and put back below.
7152
+ for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows, .ai-chat-readiness-body, .ai-chat-readiness-table')) {
7153
+ list.keptScrollTop = list.scrollTop; list.keptScrollLeft = list.scrollLeft;
7154
+ }
5181
7155
  ui.feed.replaceChildren();
5182
7156
  if (!state.events.length) {
5183
7157
  ui.feed.append(emptyFeedNotice());
@@ -5192,15 +7166,20 @@
5192
7166
  ui.feed.append(renderMessage(assistant.event, 'assistant', rendered.text, rendered.streaming));
5193
7167
  assistant = null;
5194
7168
  };
5195
- const flushLinks = () => { if (links.length) { ui.feed.append(...links.map((link) => link.node)); links = []; } };
7169
+ const flushLinks = () => { if (links.length) { ui.feed.append(...receiptFold(links)); links = []; } };
5196
7170
  for (const event of state.events) {
5197
7171
  if (links.length && event.turnId !== links[0].turnId) { flushAssistant(); flushLinks(); }
5198
7172
  if (event.type === 'assistant-message' && event.payload?.delta) {
5199
7173
  // Codex keeps a stable item id while Claude's SDK may assign one per stream packet.
5200
- // Consecutive deltas in the same turn are one visible answer; a tool or other event
5201
- // flushes the block, so genuinely separate assistant items remain separate.
7174
+ // Same-turn deltas stay in one visible answer. Tools separate progress paragraphs;
7175
+ // conversation events that render their own prose still flush the block below.
5202
7176
  if (assistant && assistant.event.turnId === event.turnId) {
5203
7177
  assistant.event = event;
7178
+ // A tool separates progress paragraphs, whereas adjacent provider packets may split a word.
7179
+ if (assistant.afterTool && payloadText(event)) {
7180
+ if (assistant.text && !/\n\s*$/.test(assistant.text) && !/^\s*\n/.test(payloadText(event))) assistant.text += '\n\n';
7181
+ assistant.afterTool = false;
7182
+ }
5204
7183
  assistant.text += payloadText(event);
5205
7184
  } else {
5206
7185
  flushAssistant();
@@ -5208,6 +7187,8 @@
5208
7187
  }
5209
7188
  continue;
5210
7189
  }
7190
+ if (assistant && event.turnId === assistant.event.turnId && event.type === 'tool'
7191
+ && !event.payload?.plain && !['agent', 'guide', 'instructor'].includes(event.payload?.tool)) assistant.afterTool = true;
5211
7192
  // Something FloLess itself refused during the answer (a file change it declined, a connector it turned away,
5212
7193
  // #1890 PR 2b / #1907), written for the person: held and shown under the answer, like the receipts below.
5213
7194
  if (event.type === 'tool' && event.payload?.plain === true && !['agent', 'guide', 'instructor'].includes(event.payload?.tool)
@@ -5236,17 +7217,26 @@
5236
7217
  if (event.type === 'action-proposal-update') continue;
5237
7218
  if (event.type === 'action-proposal' || event.type === 'action-call') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
5238
7219
  // #2255: a model view change is written mid-answer while the tool waits, so it is held under the answer too.
5239
- if (event.type === 'view-command') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
5240
- if (['tool', 'usage', 'knowledge-citation', 'attachment', 'compaction', 'state'].includes(event.type)) continue;
7220
+ if (event.type === 'view-command') { links.push({ turnId: event.turnId, node: renderEvent(event), event }); continue; }
7221
+ // #2437 / #2436: an answer's sources are held under it, like the receipts below; one row per answer.
7222
+ if (event.type === 'citation' || event.type === 'knowledge-citation') {
7223
+ const node = event.type === 'citation' ? renderCitationSources(event) : renderLegacyKnowledgeCitation(event);
7224
+ if (node) links.push({ turnId: event.turnId, node });
7225
+ continue;
7226
+ }
7227
+ if (['tool', 'usage', 'attachment', 'compaction', 'state'].includes(event.type)) continue;
5241
7228
  // FloLess's own receipts (object links #1653; evidence looks and suggestion cards #1859) are written mid-answer while a tool runs:
5242
7229
  // held and shown under the answer, so they never cut one answer into fragments.
5243
- if (event.type === 'chat-subjects' || event.type === 'evidence-read' || event.type === 'filter-proposal') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
7230
+ if (event.type === 'chat-subjects' || event.type === 'evidence-read' || event.type === 'filter-proposal') { links.push({ turnId: event.turnId, node: renderEvent(event), event }); continue; }
5244
7231
  flushAssistant();
5245
7232
  const node = renderEvent(event);
5246
7233
  if (node) ui.feed.append(node);
5247
7234
  }
5248
7235
  flushAssistant();
5249
7236
  flushLinks();
7237
+ // #2399: an Instructor answer the person keeps talking to offers to continue with tools, under its latest reply.
7238
+ const continueRow = renderInstructorContinue();
7239
+ if (continueRow) ui.feed.append(continueRow);
5250
7240
  // A provider can send text before it finishes tools, usage, or its terminal turn signal.
5251
7241
  // Keep this fixed activity row visible for the full durable turn so an intermittent stream
5252
7242
  // never looks like a failed response. Recovery deliberately has no live indicator.
@@ -5260,8 +7250,9 @@
5260
7250
  if (refocused && caret) {
5261
7251
  try { refocused.setSelectionRange(caret.start, caret.end, caret.direction); } catch { /* no caret on this control */ }
5262
7252
  }
5263
- for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows')) {
7253
+ for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows, .ai-chat-readiness-body, .ai-chat-readiness-table')) {
5264
7254
  if (typeof list.keptScrollTop === 'number' && list.scrollTop !== list.keptScrollTop) list.scrollTop = list.keptScrollTop;
7255
+ if (typeof list.keptScrollLeft === 'number' && list.scrollLeft !== list.keptScrollLeft) list.scrollLeft = list.keptScrollLeft;
5265
7256
  }
5266
7257
  // Removing a focused control makes the browser lay out the half-built feed, which clamps its scroll near the top.
5267
7258
  // Scrolled up, the reader stays where they were.
@@ -5284,6 +7275,7 @@
5284
7275
  // a new user is never told to "sign in first" with nowhere to do it.
5285
7276
  function emptyFeedNotice() {
5286
7277
  const empty = document.createElement('div'); empty.className = 'ai-chat-empty';
7278
+ if (typeof chatLandingScene === 'function') chatLandingScene(empty, `chat:${state.chat?.chatId || ''}`);
5287
7279
  const strong = document.createElement('strong');
5288
7280
  const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy';
5289
7281
  const provider = state.chat?.provider;
@@ -5318,10 +7310,12 @@
5318
7310
  : 'You can write your first message now. Send becomes available when setup finishes.';
5319
7311
  empty.append(strong, copy);
5320
7312
  } else {
5321
- strong.textContent = `${label} needs attention`;
5322
- copy.textContent = capabilityMessage(provider, state.capability?.reason);
7313
+ // A FloLess sign-in or subscription refusal is about FloLess, not the AI app: say so, and offer no AI-app sign-in.
7314
+ const accountAccess = Boolean(state.capability?.accountAccess);
7315
+ strong.textContent = accountAccess ? 'FloLess account needs attention' : `${label} needs attention`;
7316
+ copy.textContent = capabilityMessage(provider, state.capability?.reason, accountAccess);
5323
7317
  empty.append(strong, copy);
5324
- if (signInNeeded(state.capability?.reason)) empty.append(emptySignInButton(label, false));
7318
+ if (!accountAccess && signInNeeded(state.capability?.reason)) empty.append(emptySignInButton(label, false));
5325
7319
  }
5326
7320
  return empty;
5327
7321
  }
@@ -5489,6 +7483,12 @@
5489
7483
  const commandAt = approval.protectedCommand === true && !connector ? approval.summary.indexOf('\nCommand: ') : -1;
5490
7484
  if (commandAt >= 0) {
5491
7485
  copy.textContent = approval.summary.slice(0, commandAt);
7486
+ // #2224 item 1: why it asks although actions may be approved for this request or conversation.
7487
+ const why = document.createElement('p');
7488
+ why.className = 'ai-chat-approval-note';
7489
+ why.textContent = 'This command names, or could match, a workflow’s approved lock, record or conversations, so FloLess '
7490
+ + 'asks every time, even when actions are approved for this request or conversation.';
7491
+ nodes.push(why);
5492
7492
  const block = document.createElement('pre');
5493
7493
  block.className = 'ai-chat-approval-cmd';
5494
7494
  block.tabIndex = 0;
@@ -6051,7 +8051,12 @@
6051
8051
  const create = approval.create && typeof approval.create === 'object' ? approval.create : null;
6052
8052
  const check = approval.connectionCheck && typeof approval.connectionCheck === 'object' ? approval.connectionCheck : null;
6053
8053
  const connector = approval.connector && typeof approval.connector === 'object' ? approval.connector : null;
6054
- const base = { requestRevision, decision: 'allow-chat', warning: '' };
8054
+ // #2196 follow-up: a command that names, or could match, a workflow's records is outside every grant. Its card keeps
8055
+ // the full set of choices (owner ruling 7), and the wider ones say plainly that they approve THIS command once and
8056
+ // cover other actions only.
8057
+ const protectedCommand = approval.protectedCommand === true
8058
+ ? { protectedNote: ' This command is approved once: a command that names or could match a workflow’s records still asks every time.' } : {};
8059
+ const base = { requestRevision, decision: 'allow-chat', warning: '', ...protectedCommand };
6055
8060
  const PROTECTED_NOTE = ' A workflow’s own records (its .lock, settings and conversations) always ask.';
6056
8061
  if (change) {
6057
8062
  if (change.refused || change.busy) return null;
@@ -6496,9 +8501,274 @@
6496
8501
  return true;
6497
8502
  }
6498
8503
 
8504
+ /* ---- #2438: @-mentions ------------------------------------------------------------------------------------------------
8505
+ * Typing @ in a project conversation lists the project's members (by the marks its drawings gave them) and its sheets;
8506
+ * a pick becomes a chip above the message box and goes with the next message as identity only — the server resolves it
8507
+ * and says to the AI what it is. Two members sharing a mark are two rows, each saying how to tell it apart. The list
8508
+ * shares the slash list's box and placement; the message box keeps focus throughout (aria-activedescendant).
8509
+ */
8510
+ function currentMentions() {
8511
+ return state.mentions?.[state.chat?.chatId] || [];
8512
+ }
8513
+ /** Each conversation keeps its own picks: switching away and back finds them where they were. */
8514
+ function setMentions(items) { if (state.chat?.chatId) state.mentions = { ...state.mentions, [state.chat.chatId]: items }; }
8515
+ function mentionKey(pick) {
8516
+ return pick.kind === 'member' ? JSON.stringify(['member', pick.id, pick.mark]) : JSON.stringify(['sheet', pick.sheet, pick.pageId, pick.sourceHash]);
8517
+ }
8518
+
8519
+ /**
8520
+ * What tells one ref from another of the same name: its profile, the views it was read on, its id; a sheet's page.
8521
+ * `all` lists every view (the tooltip); the row shows two and counts the rest, so it never wraps into a paragraph.
8522
+ */
8523
+ function refDetail(ref, all = false) {
8524
+ if (ref.kind === 'sheet') return [`Sheet${ref.pageNumber ? `, page ${ref.pageNumber}` : ''}`, `source ${String(ref.sourceHash).slice(0, 8)}`].join(' · ');
8525
+ const named = (ref.views || []).map((view) => (view.title ? `${view.sheet} ${view.title}` : view.sheet));
8526
+ const shown = all ? named : named.slice(0, 2);
8527
+ const views = shown.join(', ') + (named.length > shown.length ? ` +${named.length - shown.length} more` : '');
8528
+ return [ref.mark ? null : 'No mark', ref.profile, views ? `on ${views}` : null, `id ${ref.id}`].filter(Boolean).join(' · ');
8529
+ }
8530
+ function mentionOf(ref) {
8531
+ const pick = ref.kind === 'member'
8532
+ ? { kind: 'member', id: ref.id, mark: ref.mark ?? null }
8533
+ : { kind: 'sheet', sheet: ref.sheet, pageId: ref.pageId, sourceHash: ref.sourceHash };
8534
+ const label = ref.kind === 'member' ? (ref.mark || ref.id) : ref.sheet;
8535
+ return { key: mentionKey(pick), pick, label, tip: `${ref.kind === 'member' ? 'Member' : 'Sheet'} ${label} · ${refDetail(ref, true)}` };
8536
+ }
8537
+
8538
+ /** Why a mention did not resolve, in a few words, by what it is. */
8539
+ function mentionNotFound(mention) {
8540
+ if (mention.reason === 'not-found') return mention.kind === 'sheet' ? 'not in this project' : 'not in the model';
8541
+ if (mention.reason === 'unreadable') return 'could not be checked';
8542
+ if (mention.reason === 'no-model') return 'no model yet';
8543
+ if (mention.reason === 'not-steel') return 'not checked, not a steel project';
8544
+ return 'not found';
8545
+ }
8546
+
8547
+ /**
8548
+ * The line under a sent message naming what was mentioned, and what FloLess could not find or check: `text` to show,
8549
+ * `spoken` with each reason as a sentence, so a reason is never heard as part of a mark.
8550
+ */
8551
+ function mentionsLine(mentions) {
8552
+ if (!Array.isArray(mentions) || !mentions.length) return '';
8553
+ const listed = mentions.slice(0, 6);
8554
+ const name = (m) => m.label || m.mark || m.id || m.sheet;
8555
+ const more = mentions.length > listed.length ? ` and ${mentions.length - listed.length} more` : '';
8556
+ const text = `Mentioned: ${listed.map((m) => `${name(m)}${m.resolved === false ? ` (${mentionNotFound(m)})` : ''}`).join(', ')}${more}`;
8557
+ const spoken = `Mentioned: ${listed.map(name).join(', ')}${more}.`
8558
+ + listed.filter((m) => m.resolved === false).map((m) => ` ${name(m)}: ${mentionNotFound(m)}.`).join('');
8559
+ return { text, spoken };
8560
+ }
8561
+
8562
+ function paintMentionChips() {
8563
+ const items = currentMentions();
8564
+ for (const item of items) {
8565
+ const chip = document.createElement('span'); chip.className = 'ai-chat-attachment ai-chat-mention';
8566
+ chip.dataset.mentionKey = item.key;
8567
+ const label = button(`@${item.label}`, 'shell.chat-mention', 'ai-chat-subjects-label');
8568
+ label.dataset.commandInstanceLabel = item.label;
8569
+ label.dataset.tip = `${item.tip}. Goes with your next message.`;
8570
+ label.setAttribute('aria-label', `${item.tip}, mentioned in your next message`);
8571
+ label.addEventListener('click', () => announce(label.dataset.tip));
8572
+ const remove = button('×', `shell.chat-mention-remove#${item.key}`);
8573
+ remove.dataset.commandInstanceLabel = item.label;
8574
+ remove.setAttribute('aria-label', `Leave ${item.label} out of your next message`);
8575
+ remove.dataset.tip = 'Leave out of the next message';
8576
+ remove.addEventListener('click', () => {
8577
+ setMentions(currentMentions().filter((m) => m.key !== item.key));
8578
+ paintAttachments(); updateSendState(); ui.input.focus();
8579
+ announce(`${item.label} will not go with your next message.`);
8580
+ });
8581
+ chip.append(label, remove);
8582
+ ui.attachments.append(chip);
8583
+ }
8584
+ return items.length > 0;
8585
+ }
8586
+
8587
+ /** The @token the caret sits at the end of, or null. A selection, or a caret elsewhere, is no token. */
8588
+ function mentionToken() {
8589
+ if (state.scope?.owner?.kind !== 'project' || !state.chat) return null;
8590
+ const { selectionStart, selectionEnd, value } = ui.input;
8591
+ if (selectionStart !== selectionEnd) return null;
8592
+ const match = value.slice(0, selectionStart).match(/(?:^|\s)@([^\s@]{0,80})$/u);
8593
+ if (!match) return null;
8594
+ return { start: selectionStart - match[1].length - 1, end: selectionStart, query: match[1] };
8595
+ }
8596
+
8597
+ function closeMentionMenu() {
8598
+ const menu = state.mentionMenu;
8599
+ if (!menu) return;
8600
+ clearTimeout(menu.timer);
8601
+ state.mentionMenu = null;
8602
+ ui.skills.hidden = true; ui.skills.replaceChildren(); ui.skills.classList.remove('is-mentions');
8603
+ ui.skills.removeAttribute('aria-label');
8604
+ ui.input.setAttribute('aria-expanded', 'false'); ui.input.removeAttribute('aria-activedescendant');
8605
+ }
8606
+
8607
+ /** Opens, follows or closes the @ list for where the caret is; true while the list owns the shared box. */
8608
+ function paintMentionMenu() {
8609
+ const token = mentionToken();
8610
+ if (!token) { state.mentionDismissed = null; closeMentionMenu(); return false; }
8611
+ // Dismissed for this @word in THIS conversation only: another conversation's word at the same place opens its own list.
8612
+ if (state.mentionDismissed?.chatId === state.chat.chatId && state.mentionDismissed.start === token.start) { closeMentionMenu(); return false; }
8613
+ let menu = state.mentionMenu;
8614
+ if (!menu || menu.start !== token.start || menu.chatId !== state.chat.chatId) {
8615
+ closeMentionMenu();
8616
+ menu = { start: token.start, chatId: state.chat.chatId, query: null, status: 'loading', refs: [], heldBack: 0, note: '', active: -1, seq: 0, timer: null };
8617
+ state.mentionMenu = menu;
8618
+ }
8619
+ // A new word keeps the rows already shown until its answer comes, so the list does not flash on each letter.
8620
+ if (menu.query !== token.query) {
8621
+ menu.query = token.query;
8622
+ if (menu.status !== 'options') { menu.status = 'loading'; menu.active = -1; }
8623
+ // Rows for an earlier word stay in sight but cannot be picked until this word's answer comes.
8624
+ menu.stale = true;
8625
+ fetchMentionRefs(menu);
8626
+ }
8627
+ renderMentionMenu();
8628
+ return true;
8629
+ }
8630
+
8631
+ function fetchMentionRefs(menu) {
8632
+ clearTimeout(menu.timer);
8633
+ const seq = ++menu.seq;
8634
+ const projectId = state.scope?.owner?.projectId;
8635
+ menu.timer = setTimeout(async () => {
8636
+ let body = null;
8637
+ try { body = await request(`/api/projects/${encodeURIComponent(projectId)}/refs?q=${encodeURIComponent(menu.query)}`); }
8638
+ catch { body = null; }
8639
+ // A newer keystroke, a closed list or another conversation: this answer is for a question nobody is asking now.
8640
+ if (state.mentionMenu !== menu || menu.seq !== seq) return;
8641
+ menu.stale = false;
8642
+ if (!body) { menu.status = 'error'; menu.active = 0; }
8643
+ else if (body.status && body.status !== 'ok') { menu.status = 'note'; menu.note = String(body.note || ''); menu.active = -1; }
8644
+ else {
8645
+ // The row that was active stays active if it is still listed.
8646
+ const was = menu.status === 'options' && menu.refs[menu.active] ? mentionOf(menu.refs[menu.active]).key : null;
8647
+ menu.refs = Array.isArray(body.refs) ? body.refs : [];
8648
+ menu.heldBack = Number(body.heldBack) || 0;
8649
+ menu.status = menu.refs.length ? 'options' : 'empty';
8650
+ const kept = was ? menu.refs.findIndex((ref) => mentionOf(ref).key === was) : -1;
8651
+ menu.active = menu.refs.length ? Math.max(0, kept) : -1;
8652
+ }
8653
+ renderMentionMenu();
8654
+ announce(menu.status === 'options' ? `${menu.refs.length + menu.heldBack} ${menu.refs.length + menu.heldBack === 1 ? 'match' : 'matches'}`
8655
+ : menu.status === 'empty' ? 'No matches' : menu.status === 'error' ? 'FloLess could not list members and sheets' : menu.note);
8656
+ }, 150);
8657
+ }
8658
+
8659
+ function renderMentionMenu() {
8660
+ const menu = state.mentionMenu;
8661
+ if (!menu) return;
8662
+ ui.skills.replaceChildren();
8663
+ ui.skills.classList.add('is-mentions');
8664
+ ui.skills.setAttribute('aria-label', 'Members and sheets you can mention');
8665
+ const status = (text) => {
8666
+ const row = document.createElement('div'); row.className = 'ai-chat-mention-status'; row.setAttribute('role', 'option');
8667
+ row.setAttribute('aria-disabled', 'true'); row.textContent = text; ui.skills.append(row);
8668
+ };
8669
+ let activeId = '';
8670
+ if (menu.status === 'loading') status('Looking for members and sheets…');
8671
+ else if (menu.status === 'note') status(menu.note);
8672
+ else if (menu.status === 'empty') {
8673
+ status(menu.query ? `Nothing in this project is named “${menu.query}”. Type it in your message instead.`
8674
+ : 'This project has no members or sheets to mention yet.');
8675
+ } else if (menu.status === 'error') {
8676
+ status('FloLess could not list this project’s members and sheets just now.');
8677
+ const retry = button('Try again', 'shell.chat-mention-retry', 'ai-chat-choice');
8678
+ retry.id = 'chat-mention-retry'; retry.setAttribute('role', 'option'); retry.setAttribute('aria-selected', 'true');
8679
+ retry.addEventListener('pointerdown', (event) => event.preventDefault());
8680
+ retry.addEventListener('click', () => { menu.status = 'loading'; fetchMentionRefs(menu); renderMentionMenu(); ui.input.focus(); });
8681
+ ui.skills.append(retry);
8682
+ activeId = retry.id;
8683
+ } else {
8684
+ menu.refs.forEach((ref, index) => {
8685
+ const item = mentionOf(ref);
8686
+ const row = button('', `shell.chat-mention-pick#${item.key}`, 'ai-chat-choice ai-chat-mention-option');
8687
+ row.id = `chat-mention-option-${index}`; row.tabIndex = -1;
8688
+ row.setAttribute('role', 'option'); row.setAttribute('aria-selected', String(index === menu.active));
8689
+ row.dataset.commandInstanceLabel = item.label;
8690
+ row.dataset.tip = item.tip;
8691
+ const name = document.createElement('span'); name.className = 'ai-chat-mention-name'; name.textContent = item.label;
8692
+ const meta = document.createElement('small'); meta.className = 'ai-chat-skill-origin'; meta.textContent = refDetail(ref);
8693
+ row.append(name, meta);
8694
+ row.addEventListener('pointerdown', (event) => event.preventDefault()); // the message box keeps focus
8695
+ row.addEventListener('click', () => pickMention(ref));
8696
+ ui.skills.append(row);
8697
+ if (index === menu.active) activeId = row.id;
8698
+ });
8699
+ if (menu.heldBack) status(`${menu.heldBack} more match. Type more of the name to narrow the list.`);
8700
+ }
8701
+ ui.skills.hidden = false;
8702
+ ui.input.setAttribute('aria-controls', ui.skills.id);
8703
+ ui.input.setAttribute('aria-autocomplete', 'list');
8704
+ ui.input.setAttribute('aria-expanded', 'true');
8705
+ if (activeId) {
8706
+ ui.input.setAttribute('aria-activedescendant', activeId);
8707
+ document.getElementById(activeId)?.scrollIntoView?.({ block: 'nearest' });
8708
+ } else ui.input.removeAttribute('aria-activedescendant');
8709
+ placeSkills();
8710
+ }
8711
+
8712
+ function pickMention(ref) {
8713
+ // Rows for an earlier word are in sight but not pickable, by key or by click, until this word is answered.
8714
+ if (state.mentionMenu?.stale) { announce('Still looking. Pick again when the list updates.'); return; }
8715
+ const token = mentionToken();
8716
+ const item = mentionOf(ref);
8717
+ // The @word becomes the plain name, so the message still reads as a sentence; the chip carries which one it is.
8718
+ if (token) ui.input.setRangeText(`${item.label} `, token.start, token.end, 'end');
8719
+ if (!currentMentions().some((m) => m.key === item.key)) setMentions([...currentMentions(), item]);
8720
+ state.mentionDismissed = null;
8721
+ closeMentionMenu();
8722
+ autosize(); saveDraftSoon(); paintAttachments(); updateSendState(); ui.input.focus();
8723
+ announce(`${item.label} will go with your next message. Remove it from the list above the message box.`);
8724
+ }
8725
+
8726
+ /**
8727
+ * A refused message's mentions go back to their own conversation, before any picked there since (never over them),
8728
+ * and are painted at once if that conversation is the one on screen: the next Send must never carry a chip nobody sees.
8729
+ * Nothing is ever dropped here: the box may hold more than one message carries, and Send takes them in turn.
8730
+ */
8731
+ function restoreRefusedMentions(chatId, items) {
8732
+ const since = state.mentions?.[chatId] || [];
8733
+ state.mentions = { ...state.mentions, [chatId]: [...items, ...since.filter((item) => !items.some((m) => m.key === item.key))] };
8734
+ if (state.chat?.chatId === chatId) { paintAttachments(); updateSendState(); }
8735
+ }
8736
+
8737
+ /** The keys the open @ list takes; everything else, and everything while it is closed, is the message box's. */
8738
+ function handleMentionKey(event) {
8739
+ const menu = state.mentionMenu;
8740
+ if (!menu || ui.skills.hidden || event.isComposing || event.ctrlKey || event.altKey || event.metaKey) return false;
8741
+ // A select-all, a click elsewhere or a caret moved by the mouse leaves no token: the list is stale, and steps aside.
8742
+ if (mentionToken()?.start !== menu.start) { closeMentionMenu(); return false; }
8743
+ const count = menu.status === 'options' ? menu.refs.length : 0;
8744
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
8745
+ event.preventDefault();
8746
+ if (count) { menu.active = (menu.active + (event.key === 'ArrowDown' ? 1 : -1) + count) % count; renderMentionMenu(); }
8747
+ return true;
8748
+ }
8749
+ if ((event.key === 'Enter' && !event.shiftKey) || (event.key === 'Tab' && !event.shiftKey)) {
8750
+ // Never sends while the list is open: picks the active row, retries, or waits.
8751
+ event.preventDefault();
8752
+ if (menu.stale) { /* still answering this word: nothing to pick yet, and nothing is sent */ }
8753
+ else if (menu.status === 'options' && menu.active >= 0) pickMention(menu.refs[menu.active]);
8754
+ else if (menu.status === 'error') { menu.status = 'loading'; fetchMentionRefs(menu); renderMentionMenu(); }
8755
+ // Nothing to pick: the list steps aside, the word stays as typed, and the next Enter sends.
8756
+ else if (menu.status === 'empty' || menu.status === 'note') { state.mentionDismissed = { chatId: menu.chatId, start: menu.start }; closeMentionMenu(); }
8757
+ return true;
8758
+ }
8759
+ if (event.key === 'Escape') {
8760
+ event.preventDefault();
8761
+ state.mentionDismissed = { chatId: menu.chatId, start: menu.start };
8762
+ closeMentionMenu();
8763
+ return true;
8764
+ }
8765
+ return false;
8766
+ }
8767
+
6499
8768
  function paintAttachments() {
6500
8769
  ui.attachments.replaceChildren();
6501
- const pill = paintSubjectsPill();
8770
+ if (state.mentionMenu && state.mentionMenu.chatId !== state.chat?.chatId) closeMentionMenu();
8771
+ const pill = paintSubjectsPill() | paintMentionChips();
6502
8772
  // paintAttachControl, not the two lines #1653 had here: it says the same thing but asks the
6503
8773
  // SURFACE what may be attached, so the Drawing Filter reads “Attach a picture” (#1681).
6504
8774
  paintAttachControl();
@@ -6535,7 +8805,7 @@
6535
8805
  });
6536
8806
  chip.append(name, remove); ui.attachments.append(chip);
6537
8807
  }
6538
- ui.attachments.hidden = state.attachments.length === 0 && !pill;
8808
+ ui.attachments.hidden = state.attachments.length === 0 && !pill; // the pill includes any mention chips (#2438)
6539
8809
  placeSkills();
6540
8810
  }
6541
8811
 
@@ -6691,8 +8961,64 @@
6691
8961
  }
6692
8962
  }
6693
8963
 
8964
+ /**
8965
+ * #2399: "Suggest next steps" — the signed-in account's mode, shared by every chat and the ≡ menu (one
8966
+ * `floless:assistant-mode` event keeps them in step). Not this conversation's setting, so it never goes through
8967
+ * saveSettings. The Guide is exempt and says so.
8968
+ */
8969
+ const SUGGEST_LABELS = { on: 'On', quiet: 'Quiet', off: 'Off' };
8970
+ // Short tags: the picker's meta column is sized for tags (it never wraps). The full meaning is in the row's tooltip.
8971
+ const SUGGEST_META = { on: 'Problems, unfinished, ideas', quiet: 'Problems and unfinished', off: 'No cards' };
8972
+ const assistantMode = window.flolessAssistantMode || (window.flolessAssistantMode = (() => {
8973
+ let current = null; // { mode, recovered } once read
8974
+ let reading = null;
8975
+ const publish = () => window.dispatchEvent(new CustomEvent('floless:assistant-mode', { detail: current }));
8976
+ return {
8977
+ get value() { return current; },
8978
+ async refresh() {
8979
+ reading ??= request('/api/assistant/preference').then((body) => { current = { mode: body.mode, recovered: body.recovered === true }; publish(); })
8980
+ .catch((error) => { console.warn('[assistant] the suggestion setting could not be read:', error); })
8981
+ .finally(() => { reading = null; });
8982
+ return reading;
8983
+ },
8984
+ async set(mode) {
8985
+ try {
8986
+ const body = await request('/api/assistant/preference', { method: 'PUT', body: JSON.stringify({ mode }) });
8987
+ current = { mode: body.mode, recovered: body.recovered === true }; publish();
8988
+ announce(`Suggest next steps: ${SUGGEST_LABELS[body.mode] || body.mode}.`);
8989
+ } catch (error) {
8990
+ announce(error?.message || 'FloLess couldn’t save that just now. Try again in a moment.');
8991
+ }
8992
+ },
8993
+ choices() {
8994
+ return ['on', 'quiet', 'off'].map((mode) => ({
8995
+ id: `suggest:${mode}`, label: SUGGEST_LABELS[mode], meta: SUGGEST_META[mode],
8996
+ selected: current?.mode === mode && !current?.recovered, onPick: () => this.set(mode),
8997
+ }));
8998
+ },
8999
+ };
9000
+ })());
9001
+
9002
+ function paintSuggestSetting() {
9003
+ if (!ui.suggest) return;
9004
+ const value = ui.suggest.querySelector('strong');
9005
+ const guideChat = state.chat?.initiator?.kind === 'guide';
9006
+ const current = assistantMode.value;
9007
+ const text = guideChat ? 'Guide: always on'
9008
+ : current?.recovered ? 'Paused: choose'
9009
+ : current ? SUGGEST_LABELS[current.mode] || 'On' : 'On';
9010
+ if (value.textContent !== text) value.textContent = text;
9011
+ ui.suggest.disabled = guideChat;
9012
+ ui.suggest.dataset.tip = guideChat
9013
+ ? 'The Guide always suggests next steps; close it to stop. This setting is for your project, workflow and workspace chats.'
9014
+ : current?.recovered
9015
+ ? 'FloLess had to reset your suggestion settings. Suggestions are paused until you choose.'
9016
+ : 'Your account, in every project, workflow and workspace chat. On: problems to fix, unfinished work and ideas. Quiet: only problems and unfinished work. Off: no cards; the AI still knows where the project stands. The Guide always suggests; close it to stop.';
9017
+ }
9018
+
6694
9019
  function paintSettings() {
6695
9020
  if (ui.scopeControls) paintScopeControl();
9021
+ paintSuggestSetting();
6696
9022
  const chat = state.chat;
6697
9023
  ui.settingsToggle.disabled = !chat;
6698
9024
  const answer = capabilityAnswer(state.capability);
@@ -6736,7 +9062,10 @@
6736
9062
  ? `${bindings.length} FloLess account${bindings.length === 1 ? '' : 's'}`
6737
9063
  : 'Not using one';
6738
9064
  const frozen = !chat || Boolean(chat.activeTurn) || !state.capability?.available;
6739
- ui.model.disabled = frozen; ui.effort.disabled = frozen; ui.permission.disabled = frozen;
9065
+ // #2336: Access and the connectors switch do not depend on the provider's model list, so a provider check that failed
9066
+ // or is slow never locks them (only a running reply does). Model and effort need the list.
9067
+ const settled = !chat || Boolean(chat.activeTurn);
9068
+ ui.model.disabled = frozen; ui.effort.disabled = frozen; ui.permission.disabled = settled;
6740
9069
  ui.integrations.disabled = frozen || Boolean(chat?.nativeSessionId) || instructorChat;
6741
9070
  const integrationBlocked = instructorChat
6742
9071
  ? 'An Instructor answer uses no tools, so it cannot use a connected account. Start a new chat to use one.'
@@ -6744,12 +9073,12 @@
6744
9073
  ? 'Connected accounts are fixed after the first message. Start a new chat to use another account.'
6745
9074
  : !chat ? 'Open a conversation first.'
6746
9075
  : chat.activeTurn ? 'Connected accounts cannot change during an active turn.'
6747
- : !state.capability?.available ? capabilityMessage(chat.provider, state.capability?.reason)
9076
+ : !state.capability?.available ? capabilityMessage(chat.provider, state.capability?.reason, state.capability?.accountAccess)
6748
9077
  : '';
6749
9078
  ui.integrations.dataset.tip = integrationBlocked || 'Choose which connected account this chat can use';
6750
9079
  if (integrationBlocked) ui.integrations.dataset.blockedReason = integrationBlocked;
6751
9080
  else delete ui.integrations.dataset.blockedReason;
6752
- paintOwnConnectorsSetting(chat, frozen);
9081
+ paintOwnConnectorsSetting(chat, settled);
6753
9082
  paintDesktopStatus();
6754
9083
  }
6755
9084
 
@@ -6766,8 +9095,7 @@
6766
9095
  const blocked = !chat ? 'Open a conversation first.'
6767
9096
  : usesAccount ? 'This chat uses a FloLess connected account, so your own connectors stay off.'
6768
9097
  : chat.activeTurn ? 'Wait for the current AI reply to finish before changing this.'
6769
- : !state.capability?.available ? capabilityMessage(chat.provider, state.capability?.reason)
6770
- : frozen ? 'This setting cannot change right now.' : '';
9098
+ : frozen ? 'This setting cannot change right now.' : '';
6771
9099
  control.disabled = Boolean(blocked);
6772
9100
  control.dataset.tip = blocked || `Lets the AI use the connectors you added to ${provider}, such as Google Drive. Each call still asks you first. Off in every new chat.`;
6773
9101
  if (blocked) control.dataset.blockedReason = blocked; else delete control.dataset.blockedReason;
@@ -6851,6 +9179,7 @@
6851
9179
  ui.stop.hidden = !active || Boolean(chat.activeTurn?.local);
6852
9180
  ui.send.hidden = false;
6853
9181
  paintSettings(); paintRecovery(); paintApproval(); paintRuntime(); paintAttachments(); paintEvents(); paintHistory(); updateSendState();
9182
+ applyPendingSettings();
6854
9183
  }
6855
9184
 
6856
9185
  function draftForChat(chat) {
@@ -7031,10 +9360,82 @@
7031
9360
  void writeChatDraft(chatId, state.scope.owner, '').catch(error => report(error, 'Draft was not saved'));
7032
9361
  }
7033
9362
 
9363
+ function closedChatSession() {
9364
+ return Object.assign(new Error('Chat page is closed.'), { code: 'chat-page-closed' });
9365
+ }
9366
+
9367
+ function showSessionRecoveryHint(operation) {
9368
+ const prior = state.sessionRecoveryHint;
9369
+ if (!prior || prior.operation !== operation || !sameScope(prior.scope, prior.generation)) {
9370
+ state.sessionRecoveryHint = { operation, scope: state.scope, generation: state.scopeGeneration, announced: false,
9371
+ message: 'FloLess is finishing project recovery. Chat will open automatically when it’s ready. If this continues, open Workspaces and choose Review folders.' };
9372
+ }
9373
+ clearReport();
9374
+ }
9375
+
9376
+ function clearSessionRecoveryHint(operation) {
9377
+ const notice = state.sessionRecoveryHint;
9378
+ if (!notice || notice.operation !== operation) return;
9379
+ state.sessionRecoveryHint = null;
9380
+ if (!sameScope(notice.scope, notice.generation)) return;
9381
+ if (ui.status.textContent === notice.message) ui.status.textContent = '';
9382
+ if (ui.hint.textContent === notice.message) clearReport();
9383
+ }
9384
+
9385
+ function disposeChatSession() {
9386
+ state.sessionDisposed = true; state.sessionLifecycle += 1; state.sessionReady = false;
9387
+ state.sessionOperation?.cancel();
9388
+ state.sessionOperation = null;
9389
+ }
9390
+
9391
+ function restoreChatSession() {
9392
+ state.sessionDisposed = false; state.sessionLifecycle += 1; state.sessionReady = false;
9393
+ void loadScope(state.scope);
9394
+ }
9395
+
7034
9396
  async function ensureSession() {
7035
- if (state.sessionReady) return;
7036
- await request('/api/chat/session');
7037
- state.sessionReady = true;
9397
+ if (state.sessionDisposed) throw closedChatSession();
9398
+ if (state.sessionOperation) {
9399
+ if (state.sessionOperation.waiting) showSessionRecoveryHint(state.sessionOperation);
9400
+ return state.sessionOperation.promise;
9401
+ }
9402
+ // Readiness is server-owned. Recheck even a cached cookie after a server restart.
9403
+ const operation = { generation: state.sessionLifecycle, waiting: false, timer: null, promise: null, cancel: null };
9404
+ let cancel;
9405
+ const cancelled = new Promise((_, reject) => { cancel = () => reject(closedChatSession()); });
9406
+ operation.cancel = () => { clearTimeout(operation.timer); cancel(); };
9407
+ const current = () => {
9408
+ if (state.sessionDisposed || operation.generation !== state.sessionLifecycle) throw closedChatSession();
9409
+ };
9410
+ state.sessionOperation = operation;
9411
+ operation.promise = Promise.resolve().then(async () => {
9412
+ try {
9413
+ for (;;) {
9414
+ current();
9415
+ const session = await Promise.race([request('/api/chat/session'), cancelled]);
9416
+ current();
9417
+ if (session?.ready === true) {
9418
+ state.sessionReady = true;
9419
+ clearSessionRecoveryHint(operation);
9420
+ return;
9421
+ }
9422
+ if (session?.ready !== false) throw plainError('FloLess could not open Chat just now. Try again in a moment.');
9423
+ state.sessionReady = false; operation.waiting = true;
9424
+ showSessionRecoveryHint(operation);
9425
+ await Promise.race([new Promise((resolve) => { operation.timer = setTimeout(resolve, 1000); }), cancelled]);
9426
+ operation.timer = null;
9427
+ current();
9428
+ }
9429
+ } catch (error) {
9430
+ if (operation.generation === state.sessionLifecycle) state.sessionReady = false;
9431
+ clearSessionRecoveryHint(operation);
9432
+ throw error;
9433
+ } finally {
9434
+ clearTimeout(operation.timer);
9435
+ if (state.sessionOperation === operation) state.sessionOperation = null;
9436
+ }
9437
+ });
9438
+ return operation.promise;
7038
9439
  }
7039
9440
 
7040
9441
  function sessionNeedsRenewal(error) {
@@ -7048,7 +9449,10 @@
7048
9449
  // Claude or Codex as "not ready".
7049
9450
  return await request(`/api/chat/providers/${chat.provider}?${ownerQuery()}&chatId=${encodeURIComponent(chat.chatId)}`);
7050
9451
  } catch (error) {
7051
- return { provider: chat.provider, available: false, models: [], skills: [], reason: errorMessage(error), readFailed: true };
9452
+ // A FloLess sign-in or subscription refusal is not the AI app's sign-in: kept apart so the readiness copy
9453
+ // shows it as written and never offers a Claude or Codex sign-in for it.
9454
+ const accountAccess = Boolean(window.flolessBridge?.accountAccessText?.(error));
9455
+ return { provider: chat.provider, available: false, models: [], skills: [], reason: errorMessage(error), readFailed: true, accountAccess };
7052
9456
  }
7053
9457
  }
7054
9458
 
@@ -7081,6 +9485,7 @@
7081
9485
  if (!sessionNeedsRenewal(error)) throw error;
7082
9486
  state.sessionReady = false;
7083
9487
  await ensureSession();
9488
+ if (!sameChat(snapshot)) return;
7084
9489
  chat = await request(path);
7085
9490
  }
7086
9491
  if (!sameChat(snapshot)) return;
@@ -7122,7 +9527,7 @@
7122
9527
  const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy'; copy.textContent = listed
7123
9528
  ? `Loading “${listed.title}”…`
7124
9529
  : 'Loading the selected conversation…';
7125
- loading.append(strong, copy); ui.feed.append(loading);
9530
+ loading.append(strong, copy); if (typeof chatLandingScene === 'function') chatLandingScene(loading, `chat:${chatId}`); ui.feed.append(loading);
7126
9531
  paintHistory(); paintSettings(); paintRecovery();
7127
9532
  }
7128
9533
 
@@ -7305,6 +9710,7 @@
7305
9710
  setBusy(true);
7306
9711
  try {
7307
9712
  await ensureSession();
9713
+ if (generation !== state.scopeGeneration) return;
7308
9714
  const result = await request(`/api/chat/conversations?${ownerQuery(scope.owner)}`);
7309
9715
  if (generation !== state.scopeGeneration) return;
7310
9716
  state.chats = result.chats || [];
@@ -7558,7 +9964,7 @@
7558
9964
 
7559
9965
  function closePicker() {
7560
9966
  state.picker = null; state.pickerOpener = null; ui.picker.hidden = true; ui.picker.replaceChildren();
7561
- for (const control of [ui.model, ui.effort, ui.permission, ui.integrations]) control.setAttribute('aria-expanded', 'false');
9967
+ for (const control of [ui.model, ui.effort, ui.permission, ui.suggest, ui.integrations]) control?.setAttribute('aria-expanded', 'false');
7562
9968
  }
7563
9969
 
7564
9970
  function closePickerOnEscape(event) {
@@ -7581,7 +9987,8 @@
7581
9987
  const label = document.createElement('span'); label.textContent = choice.label;
7582
9988
  row.append(label);
7583
9989
  if (choice.meta) { const meta = document.createElement('small'); meta.textContent = choice.meta; row.append(meta); }
7584
- row.addEventListener('click', async () => { closePicker(); await saveSettings(choice.patch); anchor.focus(); });
9990
+ // A choice that is not this conversation's own setting (#2399: the account's suggestion mode) saves itself.
9991
+ row.addEventListener('click', async () => { closePicker(); if (choice.onPick) await choice.onPick(); else await saveSettings(choice.patch); anchor.focus(); });
7585
9992
  ui.picker.append(row);
7586
9993
  }
7587
9994
  ui.picker.hidden = false; anchor.setAttribute('aria-expanded', 'true');
@@ -7589,6 +9996,30 @@
7589
9996
  selected?.focus();
7590
9997
  }
7591
9998
 
9999
+ /**
10000
+ * #2399: "Continue with tools" under an answer-only (Instructor) chat's latest reply, once the person has typed a
10001
+ * follow-up — the moment a no-tools answer starts to get in their way. FloLess draws it, never the AI (that chat has
10002
+ * no tools). It opens the existing confirmation (confirmInstructorRelease) with the least widening, Read only; the
10003
+ * Access row stays the place for anything wider. Hidden while a reply is running.
10004
+ */
10005
+ function renderInstructorContinue() {
10006
+ const chat = state.chat;
10007
+ if (!isInstructorAnswer(chat) || turnIsVisiblyActive()) return null;
10008
+ const asked = state.events.filter((event) => event.type === 'user-message').length;
10009
+ const answered = state.events.some((event) => event.type === 'assistant-message');
10010
+ if (asked < 2 || !answered) return null;
10011
+ const row = document.createElement('div');
10012
+ row.className = 'ai-chat-request-actions ai-chat-instructor-continue';
10013
+ const note = document.createElement('span');
10014
+ note.className = 'ai-chat-instructor-continue-note';
10015
+ note.textContent = 'This chat answers without tools.';
10016
+ const go = button('Continue with tools…', 'shell.chat-instructor-continue');
10017
+ go.dataset.tip = 'Lets the AI read files and use tools in this chat. FloLess asks first.';
10018
+ go.addEventListener('click', () => { void saveSettings({ permissionProfile: 'read-only' }).finally(() => { if (go.isConnected) go.focus(); }); });
10019
+ row.append(note, go);
10020
+ return row;
10021
+ }
10022
+
7592
10023
  /** #2059: an Instructor-started conversation the person has not widened: its AI answers with no tools. */
7593
10024
  function isInstructorAnswer(chat) {
7594
10025
  // The server's rule (chatIsInstructorAnswer): durable facts only, never the stored settings.
@@ -7654,7 +10085,8 @@
7654
10085
  // #2059: giving an Instructor answer tools asks first; the server refuses it without this confirmation.
7655
10086
  let release = false;
7656
10087
  if (widensInstructorAnswer(patch)) {
7657
- if (!await confirmInstructorRelease(patch)) return;
10088
+ // A confirmed change that had to wait for a running reply (#2336) was confirmed already: it is not asked again.
10089
+ if (!options.releaseConfirmed && !await confirmInstructorRelease(patch)) return;
7658
10090
  if (!sameChat(snapshot)) return;
7659
10091
  // The settings may have moved on while the question was open: apply the choice to what is current now.
7660
10092
  snapshot = captureChat();
@@ -7685,7 +10117,46 @@
7685
10117
  // The transcript line the server wrote is shown now, not on the next poll.
7686
10118
  void refreshConversation(snapshot.chatId, false);
7687
10119
  } else if (options.announce !== false) announce('Chat settings updated.');
7688
- } catch (error) { if (sameChat(snapshot)) report(error, 'Could not update settings'); }
10120
+ } catch (error) {
10121
+ if (!sameChat(snapshot)) return;
10122
+ // #2336: a reply is still running, so the change cannot be stored yet. Nothing is refused: say so, keep the control on
10123
+ // the level that is really in force, and apply the choice by itself the moment the reply finishes (paintConversation).
10124
+ if (error?.code === 'chat-turn-active') {
10125
+ const earlier = state.pendingSettings?.chatId === snapshot.chatId ? state.pendingSettings : null;
10126
+ state.pendingSettings = { chatId: snapshot.chatId, patch: { ...(earlier?.patch || {}), ...patch }, releaseConfirmed: release || earlier?.releaseConfirmed === true };
10127
+ report(error, '', { 'chat-turn-active': pendingSettingsSentence(patch) });
10128
+ return;
10129
+ }
10130
+ report(error, 'Could not update settings', settingsSaveMessages(error));
10131
+ }
10132
+ }
10133
+
10134
+ /** #2336: said when a settings choice has to wait for the running reply; it applies by itself afterwards. */
10135
+ function pendingSettingsSentence(patch) {
10136
+ const what = 'permissionProfile' in patch ? `Access to ${permissionLabel(patch.permissionProfile)}`
10137
+ : 'useOwnConnectors' in patch ? (patch.useOwnConnectors === true ? 'your connectors to on' : 'your connectors to off')
10138
+ : 'model' in patch ? 'the model' : 'effort';
10139
+ return `The AI is still replying, so ${what} will change as soon as this reply finishes. Nothing else to do.`;
10140
+ }
10141
+
10142
+ /** #2336: the sentences for a settings change that could not be stored (the shared sentences say "Stop the response", which is wrong here). */
10143
+ function settingsSaveMessages(error) {
10144
+ const code = String(error && error.code || '');
10145
+ if (code === 'chat-turn-active') return { 'chat-turn-active': 'The AI is still replying. Try this change again when the reply has finished.' };
10146
+ if (code === 'chat-provider-unavailable') {
10147
+ return { 'chat-provider-unavailable': `${capabilityMessage(state.chat?.provider, error?.message)} The model and effort can’t be changed until then; Access and connectors still can.` };
10148
+ }
10149
+ return null;
10150
+ }
10151
+
10152
+ /** #2336: applies a choice that waited for a running reply, once that reply is over and only to the chat it was made in. */
10153
+ function applyPendingSettings() {
10154
+ const pending = state.pendingSettings;
10155
+ if (!pending) return;
10156
+ if (state.chat?.chatId !== pending.chatId) { state.pendingSettings = null; return; }
10157
+ if (state.chat.activeTurn || state.chat.archivedAt) return;
10158
+ state.pendingSettings = null;
10159
+ void saveSettings(pending.patch, { releaseConfirmed: pending.releaseConfirmed === true });
7689
10160
  }
7690
10161
 
7691
10162
  function modelChoices() {
@@ -7905,7 +10376,8 @@
7905
10376
  }
7906
10377
  }
7907
10378
  ui.send.disabled = state.loading || state.followupSubmitting || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen
7908
- || (!ui.input.value.trim() && state.attachments.length === 0) || settingUp;
10379
+ || (!ui.input.value.trim() && state.attachments.length === 0
10380
+ && !(state.mentions?.[state.chat?.chatId]?.length)) || settingUp;
7909
10381
  if (moving) ui.send.disabled = true;
7910
10382
  // The paperclip is the same on every surface, the Drawing Filter included (#1681, #1859): a message
7911
10383
  // there carries the filter's context AND whatever the person attached, under the general rules only.
@@ -8661,6 +11133,13 @@
8661
11133
  }
8662
11134
  const snapshot = captureChat();
8663
11135
  if (!snapshot) return given ? givenNotSent() : undefined;
11136
+ // #2438: what the person mentioned rides with the box's message too, decided at the click. Inline, not the helpers:
11137
+ // several harnesses run this function on its own.
11138
+ const liveMentions = () => (state.mentions?.[state.chat?.chatId] || []);
11139
+ // One message carries at most 20 (the server's limit); any more stay in the box, as chips, for the next message.
11140
+ const mentionItems = given ? [] : liveMentions().slice(0, 20);
11141
+ const mentionsField = mentionItems.length ? { mentions: mentionItems.map((item) => item.pick) } : {};
11142
+ const mentionsKey = (items) => items.map((item) => item.key).join('\n');
8664
11143
  // Bind a carried-over Tekla library first; a refused binding keeps the message unsent.
8665
11144
  if (!(await bindPendingTeklaRead(snapshot))) return given ? givenNotSent('Wait for the Tekla library change to finish, then send your answer again.') : undefined;
8666
11145
  const text = given ? given.text : ui.input.value.trim();
@@ -8668,20 +11147,22 @@
8668
11147
  const chatId = snapshot.chatId;
8669
11148
  const attachmentIds = (given ? given.attachments : state.attachments).map((item) => item.attachmentId);
8670
11149
  // #2061: the message as it was asked about, should the project turn out to be busy (see askIfProjectBusy).
8671
- const busyMessage = { chatId, text, attachmentIds, subjectsField, filterField: filterContext.field };
11150
+ const busyMessage = { chatId, text, attachmentIds, subjectsField, filterField: filterContext.field, mentionsField };
8672
11151
  // The busy-project question and its wait send what is in the box; an answer written elsewhere is told the refusal instead.
8673
11152
  const askedBusy = !sendOverride && !given && await projectBusyBeforeSend(snapshot, busyMessage);
8674
11153
  if (askedBusy || !sameChat(snapshot)) return given ? givenNotSent() : undefined;
8675
11154
  // Edited while FloLess checked — or already sent by an earlier click, which empties the box — nothing is sent over
8676
11155
  // the box's text now; it stays for the next Send.
8677
- if (!given && (ui.input.value.trim() !== text || JSON.stringify(state.attachments.map((item) => item.attachmentId)) !== JSON.stringify(attachmentIds))) return;
11156
+ if (!given && (ui.input.value.trim() !== text || JSON.stringify(state.attachments.map((item) => item.attachmentId)) !== JSON.stringify(attachmentIds)
11157
+ || mentionsKey(liveMentions().slice(0, 20)) !== mentionsKey(mentionItems))) return;
8678
11158
  const clientSubmissionId = crypto.randomUUID();
8679
11159
  const previousChat = state.chat;
8680
11160
  const previousAttachments = state.attachments;
8681
11161
  const optimisticEvent = {
8682
11162
  eventId: `local:${clientSubmissionId}`, sequence: Math.max(0, ...state.events.map((event) => Number(event.sequence) || 0)) + .5,
8683
11163
  chatId, turnId: clientSubmissionId, clientSubmissionId, providerItemId: null, type: 'user-message',
8684
- payload: { text, attachmentIds, ...subjectsField }, createdAt: new Date().toISOString(), optimistic: true,
11164
+ payload: { text, attachmentIds, ...subjectsField, ...(mentionItems.length ? { mentions: mentionItems.map((m) => ({ ...m.pick, label: m.label, resolved: true })) } : {}) },
11165
+ createdAt: new Date().toISOString(), optimistic: true,
8685
11166
  };
8686
11167
  if (!given) {
8687
11168
  clearTimeout(state.draftTimer);
@@ -8691,8 +11172,10 @@
8691
11172
  state.pendingSubmissionId = clientSubmissionId;
8692
11173
  state.events.push(optimisticEvent);
8693
11174
  state.chat = { ...previousChat, draft: given ? previousChat.draft : '', state: 'starting', activeTurn: { turnId: clientSubmissionId, local: true } };
8694
- if (!given) { ui.input.value = ''; autosize(); state.attachments = []; paintAttachments(); }
8695
- setBusy(true); paintConversation(); announce('Message sent.');
11175
+ if (!given) { ui.input.value = ''; autosize(); state.attachments = []; if (mentionItems.length) state.mentions = { ...state.mentions, [chatId]: liveMentions().slice(20) }; paintAttachments(); }
11176
+ setBusy(true); paintConversation();
11177
+ const mentionsLeft = given ? 0 : liveMentions().length;
11178
+ 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.');
8696
11179
  try {
8697
11180
  // A debounced save already in flight must finish before the server clears
8698
11181
  // the draft while admitting this message.
@@ -8702,7 +11185,7 @@
8702
11185
  // The server alone appends this context to the provider copy. The submitted text and
8703
11186
  // durable transcript must remain exactly what the user typed.
8704
11187
  owner: snapshot.scope.owner, clientSubmissionId, text, displayText: text, uiContext, attachmentIds,
8705
- modifying: previousChat.settings.permissionProfile !== 'read-only', ...subjectsField, ...filterContext.field,
11188
+ modifying: previousChat.settings.permissionProfile !== 'read-only', ...subjectsField, ...mentionsField, ...filterContext.field,
8706
11189
  // #2061: the person chose "Send my message now" over a request that was waiting first.
8707
11190
  ...(sendOverride ? { overrideWaiting: true } : {}),
8708
11191
  // #2223 Revision 7: a message written on a card leaves the box's saved draft as it is.
@@ -8733,7 +11216,11 @@
8733
11216
  } catch (error) {
8734
11217
  if (!sameChat(snapshot)) {
8735
11218
  if (given) return givenNotSent();
8736
- if (initialTurnDefinitelyRefused(error)) await restoreBackgroundDraft(snapshot, text, clientSubmissionId);
11219
+ if (initialTurnDefinitelyRefused(error)) {
11220
+ await restoreBackgroundDraft(snapshot, text, clientSubmissionId);
11221
+ // #2438: the mentions go back to their own conversation with the words.
11222
+ if (mentionItems.length) restoreRefusedMentions(chatId, mentionItems);
11223
+ }
8737
11224
  return;
8738
11225
  }
8739
11226
  state.pendingSubmissionId = null;
@@ -8741,6 +11228,7 @@
8741
11228
  state.chat = previousChat;
8742
11229
  if (given) { paintConversation(); return givenNotSent(givenRefusal(error)); }
8743
11230
  state.attachments = previousAttachments;
11231
+ if (mentionItems.length) restoreRefusedMentions(chatId, mentionItems);
8744
11232
  ui.input.value = text; autosize(); paintAttachments(); saveDraftSoon(); paintConversation();
8745
11233
  // #2061: the project is busy — ask (wait / open it / stop it) instead of only saying it failed. Nothing was sent.
8746
11234
  if (!askIfProjectBusy(error, busyMessage)) report(error, 'Message was not sent');
@@ -8761,14 +11249,15 @@
8761
11249
  const KNOWLEDGE_STUCK_REMEDY = 'If organizing has stopped, restart FloLess — that clears an organize that already finished. If it still shows as organizing after that, open a terminal outside FloLess (Claude Code or Codex) and ask it to check and recover the stuck knowledge organize for this project, then send again.';
8762
11250
 
8763
11251
  /** What a message means beyond its words: the selected objects and the open Drawing Filter's context. */
8764
- function projectWaitContext(subjectsField, filterField) {
8765
- try { return JSON.stringify({ subjects: subjectsField?.subjects ?? null, filter: filterField ?? {} }); }
11252
+ function projectWaitContext(subjectsField, filterField, mentionsField) {
11253
+ try { return JSON.stringify({ subjects: subjectsField?.subjects ?? null, filter: filterField ?? {}, mentions: mentionsField?.mentions ?? null }); }
8766
11254
  catch { return ''; }
8767
11255
  }
8768
11256
 
8769
11257
  function currentProjectWaitContext() {
8770
11258
  const subjects = subjectsPayload(composerSelection());
8771
- return projectWaitContext(subjects ? { subjects } : {}, filterContextForSend().field);
11259
+ const mentioned = (state.mentions?.[state.chat?.chatId] || []).slice(0, 20);
11260
+ return projectWaitContext(subjects ? { subjects } : {}, filterContextForSend().field, mentioned.length ? { mentions: mentioned.map((item) => item.pick) } : {});
8772
11261
  }
8773
11262
 
8774
11263
  function holderTitle(holder) {
@@ -8792,7 +11281,7 @@
8792
11281
  /** The pending-message record the wait compares against before it sends by itself. */
8793
11282
  function busyMessageRecord(message) {
8794
11283
  return { chatId: message.chatId, text: message.text, attachmentIds: JSON.stringify(message.attachmentIds),
8795
- context: projectWaitContext(message.subjectsField, message.filterField) };
11284
+ context: projectWaitContext(message.subjectsField, message.filterField, message.mentionsField) };
8796
11285
  }
8797
11286
 
8798
11287
  /**
@@ -9062,7 +11551,7 @@
9062
11551
  * usable, which already rules out recovery, an unconfirmed message, an upload and a provider still
9063
11552
  * being set up. Otherwise the original notice is shown and the draft stays for the user to decide.
9064
11553
  */
9065
- async function resendAfterTurnEnded({ snapshot, text, attachmentIds, error, given }) {
11554
+ async function resendAfterTurnEnded({ snapshot, text, attachmentIds, mentionsKey = '', error, given }) {
9066
11555
  state.followupSubmitting = true;
9067
11556
  updateSendState();
9068
11557
  try { await refreshConversation(snapshot.chatId); }
@@ -9073,7 +11562,8 @@
9073
11562
  if (given) return !turnIsVisiblyActive() && !givenMessageBlocked();
9074
11563
  if (!turnIsVisiblyActive() && !ui.send.disabled
9075
11564
  && ui.input.value.trim() === text
9076
- && JSON.stringify(state.attachments.map((item) => item.attachmentId)) === JSON.stringify(attachmentIds)) return true;
11565
+ && JSON.stringify(state.attachments.map((item) => item.attachmentId)) === JSON.stringify(attachmentIds)
11566
+ && (state.mentions?.[state.chat?.chatId] || []).slice(0, 20).map((item) => item.key).join('\n') === mentionsKey) return true;
9077
11567
  report(error, '');
9078
11568
  return false;
9079
11569
  }
@@ -9093,7 +11583,10 @@
9093
11583
  if (!snapshot) return notSent();
9094
11584
  const text = given ? given.text : ui.input.value.trim();
9095
11585
  const attachmentIds = (given ? given.attachments : state.attachments).map((item) => item.attachmentId);
9096
- if (!text && !attachmentIds.length) return notSent();
11586
+ // #2438: a follow-up carries what the person mentioned, into the running reply or the next one.
11587
+ // At most 20 go with it (the server's limit); any more stay as chips for the next message.
11588
+ const mentionItems = given ? [] : (state.mentions?.[state.chat?.chatId] || []).slice(0, 20);
11589
+ if (!text && !attachmentIds.length && !mentionItems.length) return notSent();
9097
11590
  if (new TextEncoder().encode(text).length > 128 * 1024) {
9098
11591
  if (given) return notSent(errorMessage({ code: 'chat-message-too-long' }));
9099
11592
  report({ code: 'chat-message-too-long' }, 'Message was not sent');
@@ -9110,7 +11603,8 @@
9110
11603
  sequence: Math.max(0, ...state.events.map((event) => Number(event.sequence) || 0)) + .5,
9111
11604
  chatId: snapshot.chatId, turnId: state.chat.activeTurn.turnId, clientSubmissionId,
9112
11605
  providerItemId: null, type: 'user-message',
9113
- payload: { text, attachmentIds, followup: true, deliveryState: 'pending' },
11606
+ payload: { text, attachmentIds, followup: true, deliveryState: 'pending',
11607
+ ...(mentionItems.length ? { mentions: mentionItems.map((m) => ({ ...m.pick, label: m.label, resolved: true })) } : {}) },
9114
11608
  createdAt: new Date().toISOString(), optimistic: true,
9115
11609
  };
9116
11610
  if (!given) {
@@ -9121,14 +11615,14 @@
9121
11615
  state.followupSubmitting = true;
9122
11616
  if (!given) state.chat.draft = '';
9123
11617
  state.events.push(optimisticEvent);
9124
- if (!given) { ui.input.value = ''; autosize(); state.attachments = []; paintAttachments(); }
11618
+ if (!given) { ui.input.value = ''; autosize(); state.attachments = []; if (mentionItems.length) state.mentions = { ...state.mentions, [snapshot.chatId]: (state.mentions?.[snapshot.chatId] || []).slice(20) }; paintAttachments(); }
9125
11619
  paintEvents({ forceBottom: true }); updateSendState();
9126
11620
  try {
9127
11621
  await state.draftWrites.get(snapshot.chatId)?.catch(() => {});
9128
11622
  const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/followups`, {
9129
11623
  method: 'POST', body: JSON.stringify({
9130
11624
  owner: snapshot.scope.owner, clientSubmissionId, text,
9131
- uiContext: currentFloLessContext(), attachmentIds, ...filterContext.field,
11625
+ uiContext: currentFloLessContext(), attachmentIds, ...(mentionItems.length ? { mentions: mentionItems.map((item) => item.pick) } : {}), ...filterContext.field,
9132
11626
  ...(given ? { keepDraft: true } : {}), // #2223 Revision 7: see sendTurn
9133
11627
  }),
9134
11628
  });
@@ -9140,19 +11634,24 @@
9140
11634
  state.chat = result.chat;
9141
11635
  // The server kept the saved draft (keepDraft); the box's own words, newer than any save, stay in the box and its record.
9142
11636
  if (given) { keepComposerDraft(); outcome = { sent: true }; }
9143
- announce(result.followup?.deliveryState === 'queued-next'
11637
+ // #2438: as for a new message, mentions past the 20 one message carries stay above the box, and that is said.
11638
+ const mentionsLeft = given || !mentionItems.length ? 0 : (state.mentions?.[snapshot.chatId] || []).length;
11639
+ const leftNote = mentionsLeft ? ` ${mentionsLeft} more ${mentionsLeft === 1 ? 'mention stays' : 'mentions stay'} above the box for your next message: one message carries up to 20.` : '';
11640
+ announce((result.followup?.deliveryState === 'queued-next'
9144
11641
  ? 'Message queued for the next AI response.'
9145
11642
  : result.followup?.deliveryState === 'accepted'
9146
11643
  ? 'Follow-up sent to AI.'
9147
11644
  : result.followup?.deliveryState === 'not-sent'
9148
11645
  ? (result.followup?.deliveryFailure?.reason || 'FloLess could not finish saving this message. Use Retry sending if you still want to send it.')
9149
- : 'Follow-up saved. Waiting for AI.');
11646
+ : 'Follow-up saved. Waiting for AI.') + leftNote);
9150
11647
  paintConversation();
9151
11648
  } catch (error) {
9152
11649
  if (!sameChat(snapshot)) {
9153
11650
  if (given && followupDefinitelyRefused(error)) return notSent();
9154
- if (followupDefinitelyRefused(error)) await restoreBackgroundDraft(snapshot, text, clientSubmissionId);
9155
- else {
11651
+ if (followupDefinitelyRefused(error)) {
11652
+ await restoreBackgroundDraft(snapshot, text, clientSubmissionId);
11653
+ if (mentionItems.length) restoreRefusedMentions(snapshot.chatId, mentionItems);
11654
+ } else {
9156
11655
  optimisticEvent.payload.deliveryState = 'unknown';
9157
11656
  state.unknownFollowups.set(snapshot.chatId, { submissionId: clientSubmissionId, text, event: optimisticEvent });
9158
11657
  // The user may have selected A → B → A while this request was in flight.
@@ -9183,6 +11682,8 @@
9183
11682
  // message, and restore chips only when the server definitely refused it.
9184
11683
  if (!given) {
9185
11684
  state.attachments = definitiveRefusal ? previousAttachments : [];
11685
+ // Definitely refused: the mentions come back with the words. Uncertain: they stay with the message that may have gone.
11686
+ if (definitiveRefusal && mentionItems.length) restoreRefusedMentions(snapshot.chatId, mentionItems);
9186
11687
  ui.input.value = text; autosize(); paintAttachments();
9187
11688
  if (definitiveRefusal) saveDraftSoon();
9188
11689
  else state.localDraft = { chatId: snapshot.chatId, text };
@@ -9191,7 +11692,7 @@
9191
11692
  // The response ended before this arrived (#1616). sendTurn resends it as a new turn, and
9192
11693
  // shows this refusal only if it cannot.
9193
11694
  if (definitiveRefusal && error?.code === 'chat-followup-refused' && error?.reason === 'chat-turn-stale') {
9194
- outcome = { outcome: 'turn-ended', snapshot, text, attachmentIds, error, given };
11695
+ outcome = { outcome: 'turn-ended', snapshot, text, attachmentIds, mentionsKey: mentionItems.map((item) => item.key).join('\n'), error, given };
9195
11696
  } else if (given) {
9196
11697
  outcome = notSent(definitiveRefusal ? givenRefusal(error)
9197
11698
  : 'FloLess couldn’t confirm your answer reached the AI. Check the conversation before you answer again.');
@@ -10246,28 +12747,63 @@
10246
12747
  }
10247
12748
 
10248
12749
  function closeScopePicker(restoreFocus = false) {
12750
+ state.scopeRead = null;
10249
12751
  state.scopePickerOpen = false; state.scopeChoice = null;
10250
12752
  if (ui.scopePicker) { ui.scopePicker.hidden = true; ui.scopePicker.replaceChildren(); }
10251
12753
  ui.scopeToggle?.setAttribute('aria-expanded', 'false');
10252
12754
  if (restoreFocus) ui.scopeToggle?.focus();
10253
12755
  }
10254
12756
 
12757
+ function paintScopePickerNotice(message, retry = false) {
12758
+ const host = ui.scopePicker;
12759
+ const hadFocus = host.contains(document.activeElement);
12760
+ host.replaceChildren();
12761
+ const head = document.createElement('div'); head.className = 'ai-chat-scope-head';
12762
+ const heading = document.createElement('strong'); heading.textContent = 'Conversation scope';
12763
+ const close = button('×', 'shell.chat-scope-close', 'ai-chat-scope-close');
12764
+ close.setAttribute('aria-label', 'Close conversation scope'); close.dataset.tip = 'Close conversation scope';
12765
+ close.addEventListener('click', () => closeScopePicker(true));
12766
+ head.append(heading, close); host.append(head);
12767
+ const note = document.createElement('p'); note.className = 'ai-chat-scope-note';
12768
+ note.setAttribute('role', 'status'); note.textContent = message; host.append(note);
12769
+ if (retry) {
12770
+ const again = button('Try again', 'shell.chat-scope-retry', 'ai-chat-scope-action');
12771
+ again.addEventListener('click', () => { closeScopePicker(); void openScopePicker(); });
12772
+ host.append(again);
12773
+ }
12774
+ if (hadFocus) close.focus();
12775
+ }
12776
+
10255
12777
  async function openScopePicker() {
10256
12778
  if (state.scopePickerOpen) { closeScopePicker(true); return; }
10257
12779
  const snapshot = captureChat();
10258
12780
  if (!snapshot || state.chat.archivedAt) return;
10259
12781
  closePicker(); state.scopeChoice = null; state.scopePickerOpen = true; state.scopeViewChatId = snapshot.chatId;
12782
+ state.scopeView = null;
12783
+ const read = {}; state.scopeRead = read;
12784
+ // A selection refresh can advance selectionGeneration without changing this conversation. Scope belongs to
12785
+ // the conversation and owner, not that transient generation; each opening still owns its reply.
12786
+ const current = () => {
12787
+ if (state.scopeRead !== read || !state.scopePickerOpen) return false;
12788
+ if (!sameScope(snapshot.scope, snapshot.generation) || state.chat?.chatId !== snapshot.chatId) {
12789
+ closeScopePicker(); return false;
12790
+ }
12791
+ return true;
12792
+ };
10260
12793
  ui.scopePicker.hidden = false; ui.scopeToggle.setAttribute('aria-expanded', 'true');
10261
- ui.scopePicker.textContent = 'Loading conversation scope…';
12794
+ paintScopePickerNotice('Loading conversation scope…');
10262
12795
  try {
10263
- const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/scope?${ownerQuery(snapshot.scope.owner)}`);
10264
- if (!sameChat(snapshot) || !state.scopePickerOpen) return;
12796
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/scope?${ownerQuery(snapshot.scope.owner)}`, { timeoutMs: 15000 });
12797
+ if (!current()) return;
12798
+ const hadFocus = document.activeElement === ui.scopeToggle || ui.scopePicker.contains(document.activeElement);
10265
12799
  state.scopeView = result; state.scopeViewChatId = snapshot.chatId;
10266
12800
  state.chat = { ...state.chat, scopeExtensions: result.scope.extensions.map((entry) => entry.target), scopeRevision: result.scope.revision, changeAllowance: result.changeAllowance };
10267
12801
  paintScopePicker(); paintScopeControl();
10268
- ui.scopePicker.querySelector('button')?.focus();
12802
+ if (hadFocus) ui.scopePicker.querySelector('button')?.focus();
10269
12803
  } catch (error) {
10270
- if (sameChat(snapshot) && state.scopePickerOpen) { closeScopePicker(true); report(error, 'Could not load conversation scope'); }
12804
+ if (current()) paintScopePickerNotice(error?.code === 'local-timeout'
12805
+ ? 'Conversation scope took too long to load. Try again.'
12806
+ : 'Conversation scope could not be loaded. Try again.', true);
10271
12807
  }
10272
12808
  }
10273
12809
 
@@ -10935,11 +13471,33 @@
10935
13471
  ui.settings.hidden = !open;
10936
13472
  ui.settingsToggle.setAttribute('aria-expanded', String(open));
10937
13473
  closePicker();
13474
+ // #2399: the account's suggestion mode may have changed in another tab or the ≡ menu.
13475
+ if (open) void assistantMode.refresh();
10938
13476
  });
10939
13477
  ui.model.addEventListener('click', () => openPicker('model', ui.model, modelChoices()));
10940
13478
  ui.switchAccount.addEventListener('click', () => { void switchAccount(); });
10941
13479
  ui.effort.addEventListener('click', () => openPicker('effort', ui.effort, effortChoices()));
10942
13480
  ui.permission.addEventListener('click', () => openPicker('permission', ui.permission, permissionChoices()));
13481
+ ui.suggest?.addEventListener('click', async () => {
13482
+ if (state.picker === 'suggest') { closePicker(); return; }
13483
+ await assistantMode.refresh();
13484
+ openPicker('suggest', ui.suggest, assistantMode.choices());
13485
+ });
13486
+ window.addEventListener('floless:assistant-mode', (event) => {
13487
+ paintSuggestSetting();
13488
+ // #2399 PR C2: the setting was read again (settings opened, or the ≡ menu): the cards drawn here are asked again how
13489
+ // they stand too — another account may have signed in since they were drawn.
13490
+ rereadAssistantStates();
13491
+ // #2399 PR C2: once the person chooses a mode again, the "suggestions are paused" line on a card goes.
13492
+ if (assistantRecoveredCard && event.detail && !event.detail.recovered) {
13493
+ const entry = assistantCardEntries.get(assistantRecoveredCard);
13494
+ assistantRecoveredCard = '';
13495
+ if (entry) { entry.recovered = false; entry.error = ''; repaintAssistantCard(entry); }
13496
+ }
13497
+ });
13498
+ // #2399 PR C2: the window coming back may mean another account signed in, or a card used in another window: every
13499
+ // assistant card drawn here asks again how it stands.
13500
+ document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') rereadAssistantStates(); });
10943
13501
  // #2046: the Guide's own controls (web/guide.js does the work and says what happened).
10944
13502
  el('chat-guide-off')?.addEventListener('click', () => { void window.flolessGuide?.turnOff?.(); });
10945
13503
  el('chat-guide-delete')?.addEventListener('click', () => { void window.flolessGuide?.deleteHistory?.(); });
@@ -10967,8 +13525,17 @@
10967
13525
  ui.reconcile.addEventListener('click', reconcile);
10968
13526
  ui.attach.addEventListener('click', () => ui.file.click());
10969
13527
  ui.file.addEventListener('change', () => attachFiles(ui.file.files));
10970
- ui.input.addEventListener('input', () => { autosize(); saveDraftSoon(); paintSkills(); updateSendState(); });
13528
+ ui.input.addEventListener('input', () => { autosize(); saveDraftSoon(); if (!paintMentionMenu()) paintSkills(); updateSendState(); });
13529
+ // #2438: the @ list follows the caret, and closes when the caret leaves its token or the box loses focus.
13530
+ ui.input.addEventListener('click', () => { if (state.mentionMenu || mentionToken()) paintMentionMenu(); });
13531
+ ui.input.addEventListener('keyup', (event) => {
13532
+ if (['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key) && (state.mentionMenu || mentionToken())) paintMentionMenu();
13533
+ });
13534
+ ui.input.addEventListener('select', () => { if (state.mentionMenu || mentionToken()) paintMentionMenu(); });
13535
+ ui.input.addEventListener('blur', () => closeMentionMenu());
13536
+ ui.skills.addEventListener('pointerdown', (event) => { if (state.mentionMenu) event.preventDefault(); });
10971
13537
  ui.input.addEventListener('keydown', (event) => {
13538
+ if (handleMentionKey(event)) return;
10972
13539
  if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { event.preventDefault(); sendTurn(); }
10973
13540
  else if (event.key === 'Escape') { ui.skills.hidden = true; closePicker(); }
10974
13541
  });
@@ -11028,7 +13595,8 @@
11028
13595
  }
11029
13596
 
11030
13597
  state.refreshTimer = setInterval(pollChatsTick, 5000);
11031
- window.addEventListener('pagehide', () => { closeSource(); contextObserver.disconnect(); activityResizeObserver.disconnect(); clearInterval(state.refreshTimer); clearTimeout(state.draftTimer); });
13598
+ window.addEventListener('pagehide', () => { disposeChatSession(); closeSource(); contextObserver.disconnect(); activityResizeObserver.disconnect(); clearInterval(state.refreshTimer); clearTimeout(state.draftTimer); });
13599
+ window.addEventListener('pageshow', (event) => { if (event.persisted) restoreChatSession(); });
11032
13600
  // A new selection is a new decision: a pill left out for the old one comes back for it.
11033
13601
  window.addEventListener('floless:model-selection', () => {
11034
13602
  let selection = null;
@@ -11045,6 +13613,8 @@
11045
13613
  currentProvider: () => state.chat?.provider ?? null,
11046
13614
  // The project this panel's conversations belong to; an object card offers Show in chat only for it (#1653).
11047
13615
  scopeProjectId: () => (state.scope?.owner?.kind === 'project' ? state.scope.owner.projectId : null),
13616
+ // The Knowledge step's "Ask AI to index" (#2399 slice 0b): the person's own draft in the message box; never sent.
13617
+ fillMessageBox: (text) => putInMessageBox(String(text || '')),
11048
13618
  // The New project dialog's AI choice (#1605) words each provider's sign-in the way this
11049
13619
  // panel's own chooser does, so the two ways into a conversation read the same.
11050
13620
  providerAccountLabel,