@floless/app 0.158.0 → 0.160.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 (43) hide show
  1. package/dist/floless-server.cjs +140655 -117708
  2. package/dist/schemas/drawing-check.profile.v1.schema.json +33 -1
  3. package/dist/schemas/steel.model.v2.schema.json +1 -0
  4. package/dist/skills/floless-app-actions/SKILL.md +23 -5
  5. package/dist/skills/floless-app-bridge/SKILL.md +5 -3
  6. package/dist/skills/floless-app-onboarding/SKILL.md +69 -5
  7. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +8 -6
  8. package/dist/skills/floless-app-queue/SKILL.md +3 -1
  9. package/dist/skills/floless-app-rfi/SKILL.md +29 -1
  10. package/dist/skills/floless-app-steel-model/SKILL.md +11 -5
  11. package/dist/skills/floless-app-steel-takeoff/SKILL.md +28 -8
  12. package/dist/skills/floless-app-workflows/SKILL.md +6 -3
  13. package/dist/web/agents.js +12 -5
  14. package/dist/web/app.css +266 -159
  15. package/dist/web/app.js +23 -51
  16. package/dist/web/aware.js +533 -546
  17. package/dist/web/chat-question-card.js +24 -1
  18. package/dist/web/chat.css +170 -48
  19. package/dist/web/chat.js +1406 -208
  20. package/dist/web/commands-shell.js +1104 -177
  21. package/dist/web/commands-steel.js +2 -0
  22. package/dist/web/drawing-check-editor.html +10 -0
  23. package/dist/web/drawing-check-editor.js +44 -0
  24. package/dist/web/guide.js +12 -2
  25. package/dist/web/index.html +62 -48
  26. package/dist/web/instructor.js +33 -12
  27. package/dist/web/pages.js +186 -31
  28. package/dist/web/panels.js +19 -1
  29. package/dist/web/project-access.js +67 -8
  30. package/dist/web/project-modules.js +474 -0
  31. package/dist/web/project-rfis.js +715 -0
  32. package/dist/web/project-workflows.js +506 -0
  33. package/dist/web/run-history.js +198 -0
  34. package/dist/web/run-page-view.js +12 -2
  35. package/dist/web/steel-3d-core.js +75 -1
  36. package/dist/web/steel-3d-view.js +8 -38
  37. package/dist/web/steel-editor.html +263 -59
  38. package/dist/web/steel-model-v2-projection.js +7 -0
  39. package/dist/web/workspace-root-recovery.js +119 -0
  40. package/dist/web/workspaces.js +493 -161
  41. package/launch-starting-page.mjs +5 -2
  42. package/launch.mjs +136 -78
  43. package/package.json +6 -1
package/dist/web/chat.js CHANGED
@@ -33,7 +33,7 @@
33
33
  connectors: el('chat-connectors'),
34
34
  changeAllowance: el('chat-change-allowance'),
35
35
  scopeControls: el('chat-scope-controls'), scopeToggle: el('chat-scope-toggle'),
36
- scopePicker: el('chat-scope-picker'), scopeDisclosure: el('chat-scope-disclosure'), accessExplanation: el('chat-access-explanation'),
36
+ scopePicker: el('chat-scope-picker'), accessChip: el('chat-access-chip'), accessMenu: el('chat-access-menu'),
37
37
  checkAllowance: el('chat-check-allowance'),
38
38
  grants: el('chat-grants'),
39
39
  workspaceUnits: el('chat-units'),
@@ -41,11 +41,21 @@
41
41
  moveSecondary: el('chat-move-secondary'), moveDismiss: el('chat-move-dismiss'),
42
42
  };
43
43
 
44
+ // The hint line under the message box only takes room when it says something about this moment. Its idle text
45
+ // ("Enter to send …") is kept for screen readers but not drawn. Watched rather than set at each of the many places
46
+ // that write the hint, so a new writer can never leave an error hidden behind the idle class.
47
+ function markIdleHint() {
48
+ ui.hint?.classList.toggle('is-idle', /^Enter to send /.test(ui.hint.textContent || ''));
49
+ }
50
+ if (ui.hint && typeof MutationObserver === 'function') {
51
+ new MutationObserver(markIdleHint).observe(ui.hint, { childList: true, characterData: true, subtree: true });
52
+ markIdleHint();
53
+ }
54
+
44
55
  const state = {
45
56
  // #2438: the picks waiting to go with the next message (per conversation), and the open @ list.
46
- mentions: {}, mentionMenu: null, mentionDismissed: null,
57
+ mentions: {}, mentionMenu: null, mentionDismissed: null, sourcePicker: null,
47
58
  scopeView: null, scopeViewChatId: null, scopeChoice: null, scopeEditing: false, scopePickerOpen: false,
48
- accessExplanationExpanded: readAccessExplanationPreference(),
49
59
  // signInPending is keyed by provider: a wait started in one conversation must not paint an
50
60
  // unrelated conversation's button as Waiting for sign-in… for the next two minutes.
51
61
  // #1798: the chat owner's display units as the server last answered them (null = not known yet), and the
@@ -74,7 +84,6 @@
74
84
  reportHold: null,
75
85
  // Only this exact report announcement may be removed when its composer reason ends (#1704).
76
86
  reportLiveMessage: null,
77
- pendingSettings: null,
78
87
  // A Tekla model library carried over from a Graft receipt but not yet bound to its chat. It is
79
88
  // browser-only until Send: opening, editing or removing it never calls the binding route.
80
89
  // pendingTeklaLibrary waits for the provider chooser to create the chat it belongs to.
@@ -95,10 +104,23 @@
95
104
  keepApprovalTrayDecisionVisible(ui.approvalTray);
96
105
  // #2223: a card opening above the message box shrinks the conversation. A reader who was at its end stays at its end,
97
106
  // so the AI's reply to their answer is in sight; one who scrolled up stays where they were.
107
+ // The feed moving up, away from its end, is the reader leaving the end, however few pixels it has moved yet: a smooth
108
+ // scroll starts with one or two, and a repaint or resize in between used to pull it back down (owner, 2026-10-23:
109
+ // "bouncing up and down" while the AI worked). The feed's own movement covers wheel, keys, scrollbar and touch alike, and
110
+ // never a list scrolling inside a card. A clamp (a card closing, the end shrinking) leaves it AT the end, so it is not a
111
+ // leave. They follow again once back at the very end. paintEvents reads the same flag.
112
+ // Movement is counted net of content that shrank (scroll anchoring moves scrollTop by exactly that much), and tiny
113
+ // upward steps (a precision touchpad's fractions of a pixel) add up against the same starting point until they count.
98
114
  function keepFeedFollowing(feed) {
99
115
  let atEnd = true;
116
+ let fromTop = feed.scrollTop, fromHeight = feed.scrollHeight;
100
117
  feed.addEventListener('scroll', () => {
101
- atEnd = feed.scrollHeight - feed.scrollTop - feed.clientHeight < 56;
118
+ const distance = feed.scrollHeight - feed.scrollTop - feed.clientHeight;
119
+ const movedUp = (fromTop - feed.scrollTop) - (fromHeight - feed.scrollHeight);
120
+ if (movedUp > 0.5 && distance > 0.5) state.feedLeftEnd = true;
121
+ else if (distance < 2) state.feedLeftEnd = false;
122
+ if (!(movedUp > 0 && movedUp <= 0.5)) { fromTop = feed.scrollTop; fromHeight = feed.scrollHeight; }
123
+ atEnd = !state.feedLeftEnd && distance < 56;
102
124
  });
103
125
  new ResizeObserver(() => {
104
126
  if (atEnd && !state.answerJump) feed.scrollTop = feed.scrollHeight;
@@ -567,7 +589,10 @@
567
589
  : 'Enter to send · Shift+Enter for a new line';
568
590
  if (turnIsVisiblyActive() && !state.followupUnknownId && !hasUnknownFollowup()
569
591
  && state.imageLimitChatId !== state.chat?.chatId) {
570
- ui.hint.textContent = 'AI is working · send a follow-up without stopping';
592
+ // #2651: after the person changed Access during this reply, a message sent now waits for the next turn.
593
+ const nextAccess = accessChangedDuringReply(state.chat);
594
+ if (nextAccess) ui.hint.textContent = `AI is working · your next message uses ${nextAccess.next}`;
595
+ else ui.hint.textContent = 'AI is working · send a follow-up without stopping';
571
596
  ui.hint.classList.remove('working');
572
597
  ui.hint.removeAttribute('aria-label');
573
598
  } else {
@@ -621,6 +646,7 @@
621
646
  const workspaceSurface = {
622
647
  drawings: 'drawing-filter', model: 'project-model', exports: 'project-exports',
623
648
  history: 'project-history', knowledge: 'project-knowledge', pages: 'project-pages',
649
+ workflows: 'project-workflows', // #2470 R6.2
624
650
  }[selectedStep || ''] || 'project-list';
625
651
  const workspaceProjectOpen = document.getElementById('ws-project')?.hidden === false;
626
652
  const dashboardVisible = document.getElementById('dashboard')?.hidden === false;
@@ -666,6 +692,7 @@
666
692
  case 'project-history': return shellText('ws-history');
667
693
  case 'project-knowledge': return shellText('ws-knowledge');
668
694
  case 'project-pages': return shellText('ws-pages');
695
+ case 'project-workflows': return shellText('ws-workflows');
669
696
  case 'project-list': return shellText('ws-landing');
670
697
  case 'workflow-list': return shellText('wf-landing');
671
698
  case 'agent-list': case 'agent-page': return shellText('agents-surface');
@@ -681,7 +708,7 @@
681
708
  function floLessContextLabel(context = currentFloLessContext()) {
682
709
  const labels = {
683
710
  'drawing-filter': 'Drawing Filter', 'project-model': 'project model', 'project-exports': 'project exports',
684
- 'project-history': 'project history', 'project-knowledge': 'project Knowledge', 'project-pages': 'project Pages', 'project-list': 'project list',
711
+ 'project-history': 'project history', 'project-knowledge': 'project Knowledge', 'project-pages': 'project Pages', 'project-workflows': 'project Workflows', 'project-list': 'project list',
685
712
  'workflow-canvas': 'workflow canvas', dashboard: 'dashboard', report: 'report', '3d-report': '3D report',
686
713
  'model-editor': 'model editor', 'workflow-list': 'workflow list', 'agent-list': 'list of agents', 'agent-page': 'agent page',
687
714
  };
@@ -859,6 +886,66 @@
859
886
  return node;
860
887
  }
861
888
 
889
+ /*
890
+ * #2582: the two source viewers (a cited source, a readiness place) open over a backdrop of their own, never as a
891
+ * native modal <dialog>. showModal() lifts a dialog into the browser's top layer and makes the rest of the page inert,
892
+ * the Instructor included: `?` explained a viewer's control in a band nobody could see, and "see all" opened a command
893
+ * sheet nobody could click. Like the Page viewer, the backdrop sits under the band and the sheet (app.css), Tab stays
894
+ * in the viewer, and a press on the backdrop itself closes it. The rest of the app is made inert as a modal would make
895
+ * it, all but the band and its Ask menu, so the sheet takes a person to the viewer's own control and never to the same
896
+ * command on a chip behind it. Returns what puts it all back; the caller's `close` must call it.
897
+ */
898
+ function showChatViewer(dialog, close) {
899
+ const backdrop = document.createElement('div');
900
+ backdrop.className = 'modal-backdrop show ai-chat-viewer-backdrop';
901
+ // The Instructor's command sheet may open over this viewer, as over the Page viewer: its controls are built at run time.
902
+ backdrop.dataset.commandSheetOver = '';
903
+ dialog.setAttribute('aria-modal', 'true');
904
+ backdrop.append(dialog);
905
+ // What was inert already stays so when the viewer closes: put back, never cleared.
906
+ const covered = [...document.querySelectorAll('#app > *')].filter((node) => node.id !== 'instructor' && node.id !== 'ix-ask-menu')
907
+ .map((node) => [node, node.inert]);
908
+ for (const [node] of covered) node.inert = true;
909
+ document.body.append(backdrop);
910
+ dialog.show();
911
+ let pressedBackdrop = false;
912
+ backdrop.addEventListener('mousedown', (event) => { pressedBackdrop = event.target === backdrop; });
913
+ backdrop.addEventListener('click', (event) => {
914
+ const hit = pressedBackdrop && event.target === backdrop;
915
+ pressedBackdrop = false;
916
+ if (hit) close();
917
+ });
918
+ // On the document, in capture, not on the dialog: a click on the picture or the title leaves focus on <body>, and a
919
+ // shown (not modal) dialog has no Escape of its own, so a dialog-level listener would never hear the key. The viewer
920
+ // takes Escape and Tab from wherever focus is (the viewer, the band, a toast, the page itself), except while
921
+ // something above it owns the keys: another dialog (the command sheet, or a form the band's Ask menu opens) or the
922
+ // Ask menu itself, open or holding focus. Tab goes round the viewer's controls and then the band's, so "see all" and
923
+ // Ask stay reachable from the keyboard.
924
+ const forThisViewer = (event) => {
925
+ if ([...document.querySelectorAll('.modal-backdrop.show')].some((node) => node !== backdrop)) return false;
926
+ const askMenu = document.getElementById('ix-ask-menu');
927
+ return !(askMenu && (!askMenu.hidden || askMenu.contains(event.target)));
928
+ };
929
+ const onKey = (event) => {
930
+ if ((event.key !== 'Escape' && event.key !== 'Tab') || !forThisViewer(event)) return;
931
+ event.preventDefault();
932
+ if (event.key === 'Escape') { event.stopPropagation(); close(); return; }
933
+ const reachable = (node) => !node.disabled && !node.closest('[inert]') && node.getClientRects().length;
934
+ const band = document.getElementById('instructor');
935
+ const focusables = [...dialog.querySelectorAll('button, a[href], [tabindex="0"]'), ...(band?.querySelectorAll('button, a[href], [tabindex="0"]') ?? [])].filter(reachable);
936
+ if (!focusables.length) return;
937
+ const at = focusables.indexOf(document.activeElement);
938
+ const step = event.shiftKey ? -1 : 1;
939
+ focusables[at < 0 ? (event.shiftKey ? focusables.length - 1 : 0) : (at + step + focusables.length) % focusables.length].focus();
940
+ };
941
+ document.addEventListener('keydown', onKey, true);
942
+ return () => {
943
+ document.removeEventListener('keydown', onKey, true);
944
+ backdrop.remove();
945
+ for (const [node, wasInert] of covered) node.inert = wasInert;
946
+ };
947
+ }
948
+
862
949
  // The composer's disclosure line. Derived from state in ONE place and called from every render
863
950
  // entry point, rather than switched on where the chooser is built and off in each of the paths
864
951
  // that leave it: a guarantee assembled from N call sites is only as good as the one someone
@@ -2177,42 +2264,148 @@
2177
2264
  chatId: state.chat?.chatId ?? null, owner: ownerQuery(), ownerObject: state.scope?.owner ?? null });
2178
2265
  });
2179
2266
  }
2267
+ for (const record of citationAssumptions(turnId)) { const row = byAnchor.get(record.anchor); if (row) row.assumption = record; }
2268
+ // #2643: the sources the person chose. The latest is the claim's current one while the AI has given it none; the
2269
+ // earlier ones are its history. A chosen source is numbered like a cited one: the "?" becomes a number.
2270
+ for (const [anchor, made] of citationChoices(turnId)) {
2271
+ const row = byAnchor.get(anchor);
2272
+ if (!row) continue;
2273
+ row.choices = made;
2274
+ if (row.entry.status !== 'resolved') row.choice = made[made.length - 1];
2275
+ }
2180
2276
  let n = 0;
2181
- for (const anchor of order) { const row = byAnchor.get(anchor); row.number = row.entry.status === 'resolved' ? ++n : 0; }
2277
+ for (const anchor of order) { const row = byAnchor.get(anchor); row.number = row.entry.status === 'resolved' || row.choice ? ++n : 0; }
2182
2278
  return { byAnchor, order };
2183
2279
  }
2184
2280
 
2281
+ /**
2282
+ * #2643: the sources the person chose for this answer's claims, by anchor, in the order made — the server's validity
2283
+ * rule (`validCitationChoices`): every field the route writes, through the same checks, and the citation it names is
2284
+ * this turn's and holds the anchor. An invalid row is skipped, so it can never stand in for the person's choice.
2285
+ */
2286
+ function citationChoices(turnId) {
2287
+ const out = new Map();
2288
+ if (!turnId) return out;
2289
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
2290
+ for (const event of state.events) {
2291
+ if (event.type !== 'citation-choice') continue;
2292
+ const p = event.payload || {};
2293
+ if (p.turnId !== turnId || typeof p.turnId !== 'string' || !uuid.test(p.turnId) || typeof p.citationId !== 'string' || !uuid.test(p.citationId)
2294
+ || typeof p.anchor !== 'string' || !CITE_ANCHOR.test(p.anchor) || !(p.claim === null || citeText(p.claim, 300))
2295
+ || !citeText(p.chosenBy, 200) || !citeText(p.chosenAt, 40) || Number.isNaN(Date.parse(p.chosenAt)) || p.via !== 'chip') continue;
2296
+ const source = chosenSourceOf(p.source);
2297
+ if (!source) continue;
2298
+ const cited = state.events.find((row) => row.type === 'citation' && row.eventId === p.citationId);
2299
+ if (!cited || cited.turnId !== turnId || !(cited.payload?.entries ?? []).some((entry) => entry?.anchor === p.anchor)) continue;
2300
+ const made = out.get(p.anchor) ?? [];
2301
+ made.push({ eventId: event.eventId, anchor: p.anchor, chosenBy: p.chosenBy, chosenAt: p.chosenAt, source });
2302
+ out.set(p.anchor, made);
2303
+ }
2304
+ return out;
2305
+ }
2306
+
2307
+ function citeText(x, max) { return typeof x === 'string' && x.length > 0 && x.length <= max && !/[\u0000-\u001F\u007F]/.test(x); }
2308
+
2309
+ /** A chosen source as the server stores it (`normalizeChosenSource`): a sheet with the picture digest kept at choosing, or a member. */
2310
+ function chosenSourceOf(value) {
2311
+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some((key) => !['kind', 'label', 'ref'].includes(key))) return null;
2312
+ const r = value.ref;
2313
+ if (!r || typeof r !== 'object' || Array.isArray(r) || !citeText(value.label, 160) || !citeText(r.projectId, 200) || !citeText(r.projectUuid, 200)) return null;
2314
+ const hex = /^[0-9a-f]{64}$/;
2315
+ if (value.kind === 'sheet') {
2316
+ if (Object.keys(r).some((key) => !['projectId', 'projectUuid', 'appId', 'pageId', 'sourceHash', 'sheet', 'pageNumber', 'representation', 'imageDigests'].includes(key))
2317
+ || !citeText(r.appId, 100) || !citeText(r.pageId, 200) || typeof r.sourceHash !== 'string' || !hex.test(r.sourceHash) || !citeText(r.sheet, 200)
2318
+ || !(r.pageNumber === null || (Number.isSafeInteger(r.pageNumber) && r.pageNumber >= 1)) || r.representation !== 'sheet'
2319
+ || !Array.isArray(r.imageDigests) || r.imageDigests.length !== 1 || typeof r.imageDigests[0] !== 'string' || !hex.test(r.imageDigests[0])) return null;
2320
+ return { kind: 'sheet', label: value.label, ref: r };
2321
+ }
2322
+ if (value.kind === 'member') {
2323
+ const views = r.views;
2324
+ if (Object.keys(r).some((key) => !['projectId', 'projectUuid', 'memberId', 'mark', 'profile', 'modelEtag', 'views'].includes(key))
2325
+ || !citeText(r.memberId, 200) || !(r.mark === null || citeText(r.mark, 120)) || !(r.profile === null || citeText(r.profile, 120)) || !citeText(r.modelEtag, 200)
2326
+ || !Array.isArray(views) || views.length > 4 || views.some((v) => !v || typeof v !== 'object' || Array.isArray(v)
2327
+ || Object.keys(v).some((key) => key !== 'sheet' && key !== 'title') || !citeText(v.sheet, 120) || !(v.title === null || citeText(v.title, 120)))) return null;
2328
+ return { kind: 'member', label: value.label, ref: r };
2329
+ }
2330
+ return null;
2331
+ }
2332
+
2333
+ /** The chosen source as a chip opens it: its own record (the choice event, index 0), labelled as chosen, never as read. */
2334
+ function chosenViewRow(row, choice) {
2335
+ return { ...row, citationId: choice.eventId, index: 0, entry: { ...choice.source, status: 'resolved', chosen: choice } };
2336
+ }
2337
+
2338
+ /**
2339
+ * #2642: the person's "go on with this as an assumption" on this answer's claims — the server's validity rule
2340
+ * (`liveCitationAssumptions`): the citation it names is this turn's and holds the anchor; the first record per claim wins.
2341
+ */
2342
+ function citationAssumptions(turnId) {
2343
+ const out = new Map();
2344
+ if (!turnId) return [];
2345
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
2346
+ const text = (x, max) => typeof x === 'string' && x.length > 0 && x.length <= max && !/[\u0000-\u001F\u007F]/.test(x);
2347
+ for (const event of state.events) {
2348
+ if (event.type !== 'citation-assumption') continue;
2349
+ const p = event.payload || {};
2350
+ // Every check `normalizeCitationAssumption` makes: a row the server would not tell the AI about is never shown as one.
2351
+ if (p.turnId !== turnId || typeof p.turnId !== 'string' || !uuid.test(p.turnId) || typeof p.citationId !== 'string' || !uuid.test(p.citationId)
2352
+ || typeof p.anchor !== 'string' || !CITE_ANCHOR.test(p.anchor) || out.has(p.anchor) || !(p.claim === null || text(p.claim, 300))
2353
+ || !text(p.assumedBy, 200) || !text(p.assumedAt, 40) || Number.isNaN(Date.parse(p.assumedAt)) || p.via !== 'chip') continue;
2354
+ const cited = state.events.find((row) => row.type === 'citation' && row.eventId === p.citationId);
2355
+ if (!cited || cited.turnId !== turnId || !(cited.payload?.entries ?? []).some((entry) => entry?.anchor === p.anchor)) continue;
2356
+ out.set(p.anchor, { anchor: p.anchor, assumedBy: p.assumedBy, assumedAt: p.assumedAt });
2357
+ }
2358
+ return [...out.values()];
2359
+ }
2360
+
2361
+ /** Who and when, in words: an account id is "you" (FloLess holds no display name), a date is "23 Oct 2026". */
2362
+ function assumedWho(record) {
2363
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-/i.test(record.assumedBy) || record.assumedBy === 'You' ? 'you' : record.assumedBy;
2364
+ }
2365
+ function assumedWhen(record) {
2366
+ return new Date(record.assumedAt).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
2367
+ }
2368
+
2185
2369
  /**
2186
2370
  * #2471: what "Read by AI" says, by kind — each kind has its own receipts. A member counts only by its @-mention line in
2187
2371
  * the person's message; a file only by a look that showed it, and one that merely went with the question says so.
2188
2372
  */
2189
2373
  function citationReadWords(entry) {
2190
2374
  if (entry.kind === 'member') return entry.read === 'mentioned' ? 'yes, its @-mention was in your message' : 'not recorded';
2375
+ // #2701: FloLess keeps the AI's request to read a file of the project folder, never what came back, so it is not "yes".
2376
+ if (entry.kind === 'project-file') return entry.read === 'requested' ? 'not confirmed, the AI asked to read it but FloLess has no record of what came back' : 'not recorded';
2191
2377
  if (entry.kind === 'attachment') {
2192
2378
  if (entry.read === 'looked') {
2193
2379
  const pages = Array.isArray(entry.ref?.pagesLooked) ? entry.ref.pagesLooked : [];
2194
2380
  return pages.length ? `yes, ${pages.length === 1 ? 'page' : 'pages'} ${pages.join(', ')}` : 'yes';
2195
2381
  }
2196
- // In the message itself: a data file as its text, checked against the attached file and cut at 16,000 characters.
2197
- if (entry.read === 'in-message') return 'yes, its text was in your message (up to the first 16,000 characters)';
2382
+ // In the message itself, checked against the attached file: a picture as its bytes (#2580), a data file as its text
2383
+ // cut at 16,000 characters.
2384
+ if (entry.read === 'in-message') {
2385
+ return String(entry.ref?.mediaType || '').startsWith('image/') ? 'yes, the picture was in your message'
2386
+ : 'yes, its text was in your message (up to the first 16,000 characters)';
2387
+ }
2198
2388
  return entry.read === 'sent' ? 'not recorded, it went with your question' : 'not recorded';
2199
2389
  }
2200
2390
  return CITATION_READ[entry.read] || CITATION_READ.no;
2201
2391
  }
2202
2392
 
2203
2393
  function citationProvenance(entry) {
2394
+ // #2643: a source the person chose says who chose it, and claims no AI read: the choice records none.
2395
+ if (entry.chosen) return `Found: yes · Chosen by ${assumedWho({ assumedBy: entry.chosen.chosenBy })}, ${assumedWhen({ assumedAt: entry.chosen.chosenAt })} · Read by AI: this choice records none · Checked: no`;
2204
2396
  return `Found: yes · Read by AI: ${citationReadWords(entry)} · Checked: no`;
2205
2397
  }
2206
2398
 
2207
2399
  /** The chip's tag, in words: never a colour or a tick. */
2208
2400
  function citationMarks(entry) {
2401
+ if (entry.chosen) return `FOUND · CHOSEN BY ${assumedWho({ assumedBy: entry.chosen.chosenBy }).toUpperCase()}`;
2209
2402
  if (entry.kind === 'attachment' && entry.read === 'sent') return 'FOUND · SENT WITH QUESTION';
2210
2403
  return ['whole-sheet', 'tiles', 'yes', 'mentioned', 'looked', 'in-message'].includes(entry.read) ? 'FOUND · READ BY AI' : 'FOUND';
2211
2404
  }
2212
2405
 
2213
2406
  /** A member is named with its profile, which is what tells it from a member with a like mark. */
2214
2407
  function citationLabel(entry) {
2215
- return entry.kind === 'member' && entry.status === 'resolved' && entry.ref?.profile ? `${entry.label} · ${entry.ref.profile}` : entry.label;
2408
+ return entry.kind === 'member' && (entry.status === 'resolved' || entry.chosen) && entry.ref?.profile ? `${entry.label} · ${entry.ref.profile}` : entry.label;
2216
2409
  }
2217
2410
 
2218
2411
  function citationUrl(row, what, extra = '') {
@@ -2244,24 +2437,51 @@
2244
2437
  }
2245
2438
  const row = index.byAnchor.get(spec.anchor) ?? null;
2246
2439
  const resolved = row?.entry.status === 'resolved';
2247
- const marker = button(resolved ? String(row.number) : '?', 'shell.chat-cite-anchor', `ai-chat-cite${resolved ? '' : ' unresolved'}`);
2440
+ // #2643: a source the person chose numbers the claim like a cited one, and says who chose it.
2441
+ const chosen = !resolved && row?.choice ? row.choice : null;
2442
+ const sourced = resolved || !!chosen;
2443
+ const marker = button(sourced ? String(row.number) : '?', 'shell.chat-cite-anchor', `ai-chat-cite${sourced ? '' : ' unresolved'}`);
2248
2444
  marker.dataset.turnId = turnId || '';
2249
2445
  marker.dataset.anchor = spec.anchor;
2250
- const label = resolved ? citationLabel(row.entry) : 'no source';
2446
+ const assumed = !sourced && row?.assumption ? row.assumption : null;
2447
+ const label = resolved ? citationLabel(row.entry) : chosen ? citationLabel(chosenViewRow(row, chosen).entry) : assumed ? 'assumption, no source' : 'no source';
2251
2448
  // No citation for this anchor on this page is "none recorded", not "none found": the AI may have given none, or the
2252
2449
  // record has not reached this page yet.
2253
- const missing = row ? 'No source was found for this claim' : 'No source is recorded for this claim';
2450
+ const missing = assumed ? `No source. Assumed by ${assumedWho(assumed)} on ${assumedWhen(assumed)}`
2451
+ : row ? 'No source was found for this claim' : 'No source is recorded for this claim';
2452
+ if (assumed) marker.classList.add('assumed');
2453
+ if (chosen) marker.classList.add('chosen');
2254
2454
  marker.dataset.commandInstanceLabel = label;
2255
- marker.setAttribute('aria-label', resolved ? `Source ${row.number}: ${label}` : missing);
2256
- marker.dataset.tip = resolved ? `${label} · ${citationProvenance(row.entry)}` : missing;
2455
+ const chosenTip = chosen ? `Source chosen by ${assumedWho({ assumedBy: chosen.chosenBy })}: ${label}. No AI read is recorded for this choice, and nothing checked the claim` : '';
2456
+ marker.setAttribute('aria-label', resolved ? `Source ${row.number}: ${label}` : chosen ? `Source ${row.number}: ${chosenTip}` : missing);
2457
+ marker.dataset.tip = resolved ? `${label} · ${citationProvenance(row.entry)}` : chosen ? chosenTip : missing;
2257
2458
  marker.addEventListener('click', () => {
2258
2459
  const chip = [...ui.feed.querySelectorAll('.ai-chat-source')].find((node) => node.dataset.turnId === turnId && node.dataset.anchor === spec.anchor);
2259
- if (!chip) { announce(resolved ? 'Its source is listed under the answer.' : 'The AI gave no source for this claim.'); return; }
2460
+ if (!chip) { announce(sourced ? 'Its source is listed under the answer.' : 'The AI gave no source for this claim.'); return; }
2260
2461
  chip.scrollIntoView({ block: 'nearest' });
2261
2462
  chip.classList.remove('answer-jump'); void chip.offsetWidth; chip.classList.add('answer-jump');
2262
2463
  (chip.querySelector('button') ?? chip).focus({ preventScroll: true });
2263
2464
  });
2264
2465
  slot.replaceWith(marker);
2466
+ if (assumed) {
2467
+ // The person's decision, beside the "?" that stays: it is still not a source. A solid edge tells it from the AI's own tag.
2468
+ const tag = document.createElement('span'); tag.className = 'ai-chat-assume by-person';
2469
+ tag.textContent = 'Assumption';
2470
+ tag.dataset.tip = `${assumedWho(assumed) === 'you' ? 'You' : assumedWho(assumed)} chose to go on with this as an assumption (${assumedWhen(assumed)}). It has no source.`;
2471
+ marker.after(tag);
2472
+ }
2473
+ }
2474
+ // The AI often marks the same claim with its own Assumption tag just after the "?": one tag then says both, rather
2475
+ // than two identical words side by side. It takes the person's edge, and its tip names both authors.
2476
+ for (const mine of body.querySelectorAll('.ai-chat-assume.by-person')) {
2477
+ // Only the tag right beside it, with nothing but spaces between: an AI tag on another claim further on is not
2478
+ // the person's decision, and must never be shown as one.
2479
+ let theirs = mine.nextSibling;
2480
+ while (theirs && theirs.nodeType === 3 && !theirs.textContent.trim()) theirs = theirs.nextSibling;
2481
+ if (!theirs?.matches?.('.ai-chat-assume:not(.by-person)')) continue;
2482
+ theirs.classList.add('by-person');
2483
+ theirs.dataset.tip = `${mine.dataset.tip} ${theirs.dataset.tip}`;
2484
+ mine.remove();
2265
2485
  }
2266
2486
  }
2267
2487
 
@@ -2274,18 +2494,39 @@
2274
2494
  const number = document.createElement('span'); number.className = 'ai-chat-source-n';
2275
2495
  number.textContent = row.number ? String(row.number) : '?';
2276
2496
  chip.append(number);
2497
+ if (row.entry.status !== 'resolved' && row.choice) return chosenChip(chip, turnId, row);
2277
2498
  const entry = row.entry;
2278
2499
  if (entry.status !== 'resolved') {
2279
- chip.classList.add('unresolved');
2280
2500
  const why = document.createElement('span'); why.className = 'ai-chat-source-why';
2281
- why.textContent = `No source: ${entry.reason}`;
2282
2501
  const ask = button('Ask for the source', 'shell.chat-cite-ask', 'ai-chat-source-action');
2283
2502
  ask.dataset.tip = 'Puts a question in the message box asking where this comes from. Nothing is sent until you press Send';
2284
- ask.addEventListener('click', () => addToMessageBox(`${unsourcedClaim(turnId, row.anchor)}: which sheet, model member, attached file or Knowledge page does it come from? Cite it, or say plainly that it is an assumption.`));
2503
+ ask.addEventListener('click', () => addToMessageBox(`${unsourcedClaim(turnId, row.anchor)}: which sheet, model member, attached file, project file or Knowledge page does it come from? Cite it, or say plainly that it is an assumption.`));
2504
+ // #2643: the person names the source themself: a sheet or model member of a project in this conversation.
2505
+ const choose = button('Choose a source…', 'shell.chat-cite-choose', 'ai-chat-source-action');
2506
+ choose.dataset.tip = 'Pick the sheet or model member this claim comes from. It is recorded as chosen by you, with the date; nothing checks the claim';
2507
+ choose.setAttribute('aria-haspopup', 'dialog');
2508
+ choose.addEventListener('click', () => openSourcePicker(row, turnId, null));
2509
+ if (row.assumption) {
2510
+ // #2642: the person's recorded decision. Still "?" — an assumption is not a source, and nothing was checked.
2511
+ chip.classList.add('assumed');
2512
+ number.setAttribute('aria-label', 'Assumption, no source');
2513
+ why.textContent = `Assumed by ${assumedWho(row.assumption)}, ${assumedWhen(row.assumption)}, no source.`;
2514
+ const marks = document.createElement('span'); marks.className = 'ai-chat-source-marks';
2515
+ marks.textContent = 'ASSUMPTION';
2516
+ marks.dataset.tip = 'Your decision to go on without a source. Nothing was found or checked for this claim. The AI is reminded of it with each message you send';
2517
+ chip.append(why, marks, sourceActions(ask, choose));
2518
+ return chip;
2519
+ }
2520
+ chip.classList.add('unresolved');
2521
+ // What was cited, in the AI's own words, so the person knows which source FloLess could not match.
2522
+ const cited = document.createElement('span'); cited.className = 'ai-chat-source-cited';
2523
+ cited.textContent = entry.label;
2524
+ cited.dataset.tip = 'What the AI cited';
2525
+ why.textContent = `No source: ${entry.reason}`;
2285
2526
  const assume = button('Go on with this as an assumption', 'shell.chat-cite-assume', 'ai-chat-source-action');
2286
- 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';
2287
- 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.`));
2288
- chip.append(why, ask, assume);
2527
+ assume.dataset.tip = 'Records that you chose to go on without a source, with your name and the date. The claim is labelled Assumption, and the AI is told with your next message. Nothing is sent now';
2528
+ assume.addEventListener('click', () => assumeClaim(row, turnId, chip, assume));
2529
+ chip.append(cited, why, sourceActions(ask, choose, assume));
2289
2530
  return chip;
2290
2531
  }
2291
2532
  if (entry.kind === 'sheet') {
@@ -2307,9 +2548,338 @@
2307
2548
  const marks = document.createElement('span'); marks.className = 'ai-chat-source-marks';
2308
2549
  marks.textContent = citationMarks(entry);
2309
2550
  chip.append(open, marks);
2551
+ // A source cited after the person went on without one, or chose one: their decision stays visible, and the source
2552
+ // is still unchecked.
2553
+ const before = [row.assumption ? `Earlier assumed by ${assumedWho(row.assumption)}, ${assumedWhen(row.assumption)}` : '',
2554
+ row.choices?.length ? `Earlier ${assumedWho({ assumedBy: row.choices.at(-1).chosenBy }) === 'you' ? 'you' : assumedWho({ assumedBy: row.choices.at(-1).chosenBy })} chose ${row.choices.at(-1).source.label}` : '']
2555
+ .filter(Boolean);
2556
+ if (before.length) {
2557
+ const earlier = document.createElement('span'); earlier.className = 'ai-chat-source-note';
2558
+ earlier.textContent = before.join(' · ');
2559
+ chip.append(earlier);
2560
+ }
2561
+ return chip;
2562
+ }
2563
+
2564
+ /** The person's ways on from a claim with no source, in one row that wraps between buttons, never inside one. */
2565
+ function sourceActions(...buttons) {
2566
+ const actions = document.createElement('span'); actions.className = 'ai-chat-source-actions';
2567
+ actions.append(...buttons);
2568
+ return actions;
2569
+ }
2570
+
2571
+ /**
2572
+ * #2643: a claim whose source the person chose. Numbered like a cited source, opening the source the server resolved
2573
+ * and recorded; its tag says who chose it and never that the AI read it. "Change…" picks another (the record keeps both).
2574
+ */
2575
+ function chosenChip(chip, turnId, row) {
2576
+ const view = chosenViewRow(row, row.choice);
2577
+ const entry = view.entry;
2578
+ chip.classList.add('chosen');
2579
+ if (entry.kind === 'sheet') {
2580
+ const thumb = document.createElement('img'); thumb.alt = ''; thumb.loading = 'lazy';
2581
+ // Only the picture FloLess held when it was chosen, byte for byte (never a render); a changed picture has none.
2582
+ const preview = citationUrl(view, 'image', '&thumb=1');
2583
+ if (preview) {
2584
+ thumb.src = preview;
2585
+ thumb.addEventListener('error', () => thumb.remove(), { once: true });
2586
+ chip.append(thumb);
2587
+ }
2588
+ }
2589
+ const label = citationLabel(entry);
2590
+ const open = button(label, 'shell.chat-cite-open-chosen', 'ai-chat-answer-open ai-chat-source-open');
2591
+ open.dataset.commandInstanceLabel = label;
2592
+ open.setAttribute('aria-label', `Open ${label}`);
2593
+ open.dataset.tip = citationProvenance(entry);
2594
+ open.addEventListener('click', () => openCitedSource(view, turnId));
2595
+ const marks = document.createElement('span'); marks.className = 'ai-chat-source-marks';
2596
+ marks.textContent = citationMarks(entry);
2597
+ marks.dataset.tip = 'A person picked this source. No AI read is recorded for this choice, and nothing checked the claim';
2598
+ const change = button('Change…', 'shell.chat-cite-change', 'ai-chat-source-action quiet');
2599
+ change.setAttribute('aria-label', 'Change the source for this claim');
2600
+ change.setAttribute('aria-haspopup', 'dialog');
2601
+ change.dataset.tip = 'Pick a different sheet or model member. The earlier choice stays in the record';
2602
+ change.addEventListener('click', () => openSourcePicker(row, turnId, row.choice.eventId));
2603
+ chip.append(open, marks, change);
2604
+ const earlier = row.choices.length > 1 ? row.choices[row.choices.length - 2] : null;
2605
+ const before = [row.assumption ? `Earlier assumed by ${assumedWho(row.assumption)}, ${assumedWhen(row.assumption)}` : '',
2606
+ earlier ? `Changed from ${earlier.source.label}` : ''].filter(Boolean);
2607
+ if (before.length) {
2608
+ const note = document.createElement('span'); note.className = 'ai-chat-source-note';
2609
+ note.textContent = before.join(' · ');
2610
+ chip.append(note);
2611
+ }
2310
2612
  return chip;
2311
2613
  }
2312
2614
 
2615
+ /**
2616
+ * #2642: record the person's "go on with this as an assumption". Nothing goes in the message box and nothing is sent;
2617
+ * the server writes it with the signed-in account and the date. The conversation is the one the chip was painted for:
2618
+ * a reply that lands after the person moved to another conversation changes nothing on screen.
2619
+ */
2620
+ async function assumeClaim(row, turnId, chip, assume) {
2621
+ if (assume.getAttribute('aria-busy') === 'true' || !row.chatId) return;
2622
+ chip.querySelector('.ai-chat-source-note')?.remove();
2623
+ // Busy, not disabled: a disabled button drops the keyboard focus to the page.
2624
+ assume.setAttribute('aria-busy', 'true'); assume.setAttribute('aria-disabled', 'true');
2625
+ assume.textContent = 'Saving…';
2626
+ const claim = unsourcedClaimWords(turnId, row.anchor);
2627
+ let saved = null; let problem = '';
2628
+ try {
2629
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(row.chatId)}/citations/${encodeURIComponent(row.citationId)}/assume`, {
2630
+ method: 'POST', body: JSON.stringify({ owner: row.ownerObject, turnId, anchor: row.anchor, claim: claim || null }),
2631
+ });
2632
+ saved = result?.event ?? null;
2633
+ } catch (error) {
2634
+ // The server's own sentence when it says why nothing was recorded; anything else is a plain "try again".
2635
+ problem = ['chat-cite-assume-stale', 'chat-cite-assume-unknown', 'chat-cite-assume-unreadable'].includes(error?.code)
2636
+ ? String(error.message) : 'Could not save your choice. Try again.';
2637
+ }
2638
+ if (state.chat?.chatId !== row.chatId) return;
2639
+ if (saved && !state.events.some((known) => known.eventId === saved.eventId)) state.events.push(saved);
2640
+ if (saved) {
2641
+ paintEvents();
2642
+ const after = [...ui.feed.querySelectorAll('.ai-chat-source')].find((node) => node.dataset.turnId === (turnId || '') && node.dataset.anchor === row.anchor);
2643
+ after?.querySelector('[data-command-id="shell.chat-cite-ask"]')?.focus({ preventScroll: true });
2644
+ const record = citationIndex(turnId).byAnchor.get(row.anchor)?.assumption;
2645
+ announce(record ? `Marked as an assumption by ${assumedWho(record)}, ${assumedWhen(record)}. No source.` : 'Your choice was saved.');
2646
+ return;
2647
+ }
2648
+ assume.removeAttribute('aria-busy'); assume.removeAttribute('aria-disabled');
2649
+ assume.textContent = 'Go on with this as an assumption';
2650
+ const note = document.createElement('span'); note.className = 'ai-chat-source-note warn'; note.setAttribute('role', 'status');
2651
+ note.textContent = problem;
2652
+ chip.append(note);
2653
+ }
2654
+
2655
+ /**
2656
+ * #2643: "Choose a source…" — the @ list's sources (the project's sheets and model members, the same rows and the same
2657
+ * read), in a small dialog under the claim's chip. Not the message box's @ list: nothing goes in the message. The pick is
2658
+ * sent by identity with a request id made when it is picked (a retry sends the same one); the server resolves the source
2659
+ * from the project's own records. Everything the save needs is taken now, from the chip as painted: a reply that lands
2660
+ * after the person moved on (another conversation, the list closed) changes nothing on screen.
2661
+ */
2662
+ function openSourcePicker(row, turnId, replaces) {
2663
+ closeSourcePicker(false);
2664
+ if (!row.chatId) { announce('Open this conversation again to choose a source.'); return; }
2665
+ const command = replaces ? 'shell.chat-cite-change' : 'shell.chat-cite-choose';
2666
+ const picker = { row, turnId, replaces, command, chatId: row.chatId, projects: null, projectId: null, query: '', refs: [], heldBack: 0,
2667
+ status: 'loading', note: '', active: -1, seq: 0, timer: null, saving: null, problem: '', pending: null };
2668
+ state.sourcePicker = picker;
2669
+ const dialog = document.createElement('div'); dialog.className = 'ai-chat-source-picker';
2670
+ dialog.setAttribute('role', 'dialog'); dialog.setAttribute('aria-label', 'Choose a source');
2671
+ const head = Object.assign(document.createElement('p'), { className: 'ai-chat-source-picker-head', textContent: 'Choose the source for this claim' });
2672
+ const projects = document.createElement('div'); projects.className = 'ai-chat-source-picker-projects'; projects.hidden = true;
2673
+ const input = document.createElement('input');
2674
+ input.type = 'search'; input.className = 'ai-chat-source-picker-input'; input.placeholder = 'Search sheets and model members';
2675
+ input.setAttribute('role', 'combobox'); input.setAttribute('aria-autocomplete', 'list'); input.setAttribute('aria-expanded', 'true');
2676
+ input.setAttribute('aria-label', 'Search sheets and model members'); input.autocomplete = 'off'; input.spellcheck = false;
2677
+ const list = document.createElement('div'); list.className = 'ai-chat-source-picker-list'; list.id = 'chat-source-picker-list';
2678
+ list.setAttribute('role', 'listbox'); list.setAttribute('aria-label', 'Sheets and model members');
2679
+ input.setAttribute('aria-controls', list.id);
2680
+ const foot = document.createElement('p'); foot.className = 'ai-chat-source-picker-foot'; foot.setAttribute('role', 'status');
2681
+ const limit = Object.assign(document.createElement('p'), { className: 'ai-chat-source-picker-limit',
2682
+ textContent: 'Sheets and model members only. For a Knowledge page or an attached file, use Ask for the source.' });
2683
+ dialog.append(head, projects, input, list, foot, limit);
2684
+ picker.dialog = dialog; picker.input = input; picker.list = list; picker.foot = foot; picker.projectRow = projects;
2685
+ (ui.feed.closest('.ai-chat-shell') || document.body).append(dialog);
2686
+ input.addEventListener('input', () => { picker.query = input.value; searchSources(picker); });
2687
+ input.addEventListener('keydown', (event) => sourcePickerKey(picker, event));
2688
+ dialog.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.preventDefault(); event.stopPropagation(); closeSourcePicker(true); } });
2689
+ // A click elsewhere closes it and leaves the focus where the person clicked.
2690
+ picker.outside = (event) => { if (!dialog.contains(event.target)) closeSourcePicker(false); };
2691
+ picker.place = () => placeSourcePicker(picker);
2692
+ document.addEventListener('pointerdown', picker.outside, true);
2693
+ ui.feed.addEventListener('scroll', picker.place, { passive: true });
2694
+ window.addEventListener('resize', picker.place);
2695
+ paintSourcePicker(picker);
2696
+ input.focus({ preventScroll: true });
2697
+ loadSourceProjects(picker);
2698
+ }
2699
+
2700
+ function closeSourcePicker(refocus) {
2701
+ const picker = state.sourcePicker;
2702
+ if (!picker) return;
2703
+ state.sourcePicker = null;
2704
+ clearTimeout(picker.timer);
2705
+ document.removeEventListener('pointerdown', picker.outside, true);
2706
+ ui.feed.removeEventListener('scroll', picker.place);
2707
+ window.removeEventListener('resize', picker.place);
2708
+ picker.dialog.remove();
2709
+ if (refocus) {
2710
+ const chip = sourceChip(picker.turnId, picker.row.anchor);
2711
+ [...(chip?.querySelectorAll('button') ?? [])].find((control) => control.dataset.commandId === picker.command)?.focus({ preventScroll: true });
2712
+ }
2713
+ }
2714
+
2715
+ function sourceChip(turnId, anchor) {
2716
+ return [...ui.feed.querySelectorAll('.ai-chat-source')].find((node) => node.dataset.turnId === (turnId || '') && node.dataset.anchor === anchor) ?? null;
2717
+ }
2718
+
2719
+ /** Under the claim's chip as it is now (the feed repaints), above it when there is no room below; inside the window. */
2720
+ function placeSourcePicker(picker) {
2721
+ const chip = sourceChip(picker.turnId, picker.row.anchor);
2722
+ if (!chip) { closeSourcePicker(false); return; }
2723
+ const at = chip.getBoundingClientRect();
2724
+ const box = picker.dialog;
2725
+ const width = Math.min(360, window.innerWidth - 32);
2726
+ box.style.width = `${width}px`;
2727
+ box.style.left = `${Math.round(Math.max(16, Math.min(at.left, window.innerWidth - width - 16)))}px`;
2728
+ const height = box.offsetHeight;
2729
+ const below = at.bottom + 4;
2730
+ box.style.top = `${Math.round(below + height <= window.innerHeight - 8 ? below : Math.max(8, at.top - height - 4))}px`;
2731
+ }
2732
+
2733
+ async function loadSourceProjects(picker) {
2734
+ let projects = null;
2735
+ try {
2736
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(picker.chatId)}/scope?${picker.row.owner}`, { timeoutMs: 15000 });
2737
+ projects = Array.isArray(result?.scope?.projects) ? result.scope.projects : [];
2738
+ } catch { projects = null; }
2739
+ if (state.sourcePicker !== picker || state.chat?.chatId !== picker.chatId) return;
2740
+ if (!projects) { picker.status = 'error'; picker.note = 'FloLess could not read which projects are in this conversation.'; paintSourcePicker(picker); return; }
2741
+ picker.projects = projects;
2742
+ if (!projects.length) {
2743
+ picker.status = 'note';
2744
+ picker.note = 'This conversation has no project, so there are no sheets or model members to choose from. Ask for the source instead.';
2745
+ paintSourcePicker(picker);
2746
+ return;
2747
+ }
2748
+ picker.projectId = projects[0].projectId;
2749
+ searchSources(picker, 0);
2750
+ }
2751
+
2752
+ function searchSources(picker, delay = 150) {
2753
+ if (!picker.projectId) return;
2754
+ clearTimeout(picker.timer);
2755
+ const seq = ++picker.seq;
2756
+ picker.stale = true;
2757
+ picker.timer = setTimeout(async () => {
2758
+ let body = null;
2759
+ try { body = await request(`/api/projects/${encodeURIComponent(picker.projectId)}/refs?q=${encodeURIComponent(picker.query)}&kinds=sheet,member`); }
2760
+ catch { body = null; }
2761
+ // A newer search, a closed list or another conversation: this answer is for a question nobody is asking now.
2762
+ if (state.sourcePicker !== picker || picker.seq !== seq || state.chat?.chatId !== picker.chatId) return;
2763
+ picker.stale = false;
2764
+ if (!body) { picker.status = 'error'; picker.note = 'FloLess could not list this project’s sheets and members just now.'; }
2765
+ else if (body.status && body.status !== 'ok') { picker.status = 'note'; picker.note = String(body.note || ''); }
2766
+ else {
2767
+ picker.refs = Array.isArray(body.refs) ? body.refs : [];
2768
+ picker.heldBack = Number(body.heldBack) || 0;
2769
+ picker.status = picker.refs.length ? 'options' : 'empty';
2770
+ }
2771
+ picker.active = picker.status === 'options' ? 0 : -1;
2772
+ paintSourcePicker(picker);
2773
+ announce(picker.status === 'options' ? `${picker.refs.length + picker.heldBack} ${picker.refs.length + picker.heldBack === 1 ? 'match' : 'matches'}`
2774
+ : picker.status === 'empty' ? 'No matches' : picker.note);
2775
+ }, delay);
2776
+ }
2777
+
2778
+ function paintSourcePicker(picker) {
2779
+ const { list, foot, input, projectRow } = picker;
2780
+ projectRow.replaceChildren();
2781
+ projectRow.hidden = !(picker.projects?.length > 1);
2782
+ for (const project of picker.projects?.length > 1 ? picker.projects : []) {
2783
+ const pick = button(project.label || 'Project', `shell.chat-cite-choose-project#${project.projectId}`, 'ai-chat-source-picker-project');
2784
+ pick.setAttribute('aria-pressed', String(project.projectId === picker.projectId));
2785
+ pick.addEventListener('click', () => { picker.projectId = project.projectId; picker.status = 'loading'; paintSourcePicker(picker); searchSources(picker, 0); input.focus(); });
2786
+ projectRow.append(pick);
2787
+ }
2788
+ list.replaceChildren();
2789
+ const status = (text) => {
2790
+ const line = Object.assign(document.createElement('div'), { className: 'ai-chat-mention-status', textContent: text });
2791
+ line.setAttribute('role', 'option'); line.setAttribute('aria-disabled', 'true');
2792
+ list.append(line);
2793
+ };
2794
+ let activeId = '';
2795
+ if (picker.status === 'loading') status('Loading the project’s sheets and members…');
2796
+ else if (picker.status === 'note') status(picker.note);
2797
+ else if (picker.status === 'empty') status(picker.query ? `Nothing matches “${picker.query}”.` : 'This project has no sheets or model members yet.');
2798
+ else if (picker.status === 'error') {
2799
+ status(picker.note);
2800
+ const retry = button('Try again', 'shell.chat-cite-choose-retry', 'ai-chat-choice');
2801
+ retry.setAttribute('role', 'option');
2802
+ retry.addEventListener('click', () => { picker.status = 'loading'; paintSourcePicker(picker); if (picker.projects) searchSources(picker, 0); else loadSourceProjects(picker); });
2803
+ list.append(retry);
2804
+ } else {
2805
+ picker.refs.forEach((ref, index) => {
2806
+ const item = mentionOf(ref);
2807
+ const option = button('', `shell.chat-cite-choose-pick#${item.key}`, 'ai-chat-choice ai-chat-mention-option');
2808
+ option.id = `chat-source-option-${index}`; option.tabIndex = -1;
2809
+ option.setAttribute('role', 'option'); option.setAttribute('aria-selected', String(index === picker.active));
2810
+ option.dataset.commandInstanceLabel = item.label;
2811
+ option.dataset.tip = item.tip;
2812
+ const busy = picker.saving?.key === item.key;
2813
+ if (picker.saving) option.setAttribute('aria-disabled', 'true');
2814
+ if (busy) option.setAttribute('aria-busy', 'true');
2815
+ const name = Object.assign(document.createElement('span'), { className: 'ai-chat-mention-name', textContent: `${ref.kind === 'sheet' ? 'Sheet' : 'Member'} ${item.label}` });
2816
+ const meta = Object.assign(document.createElement('small'), { className: 'ai-chat-skill-origin', textContent: refDetail(ref) });
2817
+ option.append(name, meta);
2818
+ option.addEventListener('pointerdown', (event) => event.preventDefault()); // the search box keeps focus
2819
+ option.addEventListener('click', () => chooseSource(picker, ref));
2820
+ list.append(option);
2821
+ if (index === picker.active) activeId = option.id;
2822
+ });
2823
+ if (picker.heldBack) status(`${picker.heldBack} more match. Type more of the name to narrow the list.`);
2824
+ }
2825
+ if (activeId) { input.setAttribute('aria-activedescendant', activeId); document.getElementById(activeId)?.scrollIntoView?.({ block: 'nearest' }); }
2826
+ else input.removeAttribute('aria-activedescendant');
2827
+ foot.textContent = picker.saving ? 'Saving your choice…' : picker.problem;
2828
+ foot.classList.toggle('warn', !picker.saving && !!picker.problem);
2829
+ placeSourcePicker(picker);
2830
+ }
2831
+
2832
+ function sourcePickerKey(picker, event) {
2833
+ if (event.isComposing) return;
2834
+ const count = picker.status === 'options' ? picker.refs.length : 0;
2835
+ if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
2836
+ event.preventDefault();
2837
+ if (count) { picker.active = (picker.active + (event.key === 'ArrowDown' ? 1 : -1) + count) % count; paintSourcePicker(picker); }
2838
+ } else if (event.key === 'Enter') {
2839
+ event.preventDefault();
2840
+ if (count && picker.refs[picker.active]) chooseSource(picker, picker.refs[picker.active]);
2841
+ }
2842
+ }
2843
+
2844
+ /** Records the pick. A failure keeps the list open with the server's sentence; the claim stays as it was. */
2845
+ async function chooseSource(picker, ref) {
2846
+ if (picker.saving) return;
2847
+ if (picker.stale) { announce('Still looking. Pick again when the list updates.'); return; }
2848
+ const item = mentionOf(ref);
2849
+ // The same pick again after a failure is the same decision, so it keeps its request id; another pick is a new one.
2850
+ // The same sheet identity can be in two projects, so the project is part of what was picked.
2851
+ const decision = JSON.stringify([picker.projectId, item.key]);
2852
+ if (picker.pending?.key !== decision) picker.pending = { key: decision, requestId: crypto.randomUUID() };
2853
+ picker.saving = { key: item.key }; picker.problem = '';
2854
+ paintSourcePicker(picker);
2855
+ const { row, turnId } = picker;
2856
+ let saved = null; let problem = '';
2857
+ try {
2858
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(row.chatId)}/citations/${encodeURIComponent(row.citationId)}/choose`, {
2859
+ method: 'POST', body: JSON.stringify({ owner: row.ownerObject, turnId, anchor: row.anchor, claim: unsourcedClaimWords(turnId, row.anchor) || null,
2860
+ projectId: picker.projectId, pick: item.pick, requestId: picker.pending.requestId, replaces: picker.replaces }),
2861
+ });
2862
+ saved = result?.event ?? null;
2863
+ } catch (error) {
2864
+ problem = String(error?.code || '').startsWith('chat-cite-choose-') && error.message ? String(error.message) : 'Could not save your choice. Try again.';
2865
+ }
2866
+ // Another conversation, or a list the person closed or replaced meanwhile: this reply moves nothing on screen and
2867
+ // takes no focus. A saved choice still reaches the page through the conversation's own event stream.
2868
+ if (state.chat?.chatId !== row.chatId || state.sourcePicker !== picker) return;
2869
+ if (saved && !state.events.some((known) => known.eventId === saved.eventId)) state.events.push(saved);
2870
+ if (saved) {
2871
+ closeSourcePicker(false);
2872
+ paintEvents();
2873
+ liveCitationOpener(turnId, row.anchor)?.focus({ preventScroll: true });
2874
+ const current = citationIndex(turnId).byAnchor.get(row.anchor)?.choice;
2875
+ announce(current ? `Source ${current.source.label} recorded as chosen by ${assumedWho({ assumedBy: current.chosenBy })}.` : 'Your choice was saved.');
2876
+ return;
2877
+ }
2878
+ picker.saving = null; picker.problem = `Couldn't record your choice: ${problem} The claim is still as it was.`;
2879
+ paintSourcePicker(picker);
2880
+ picker.input.focus({ preventScroll: true });
2881
+ }
2882
+
2313
2883
  /** The Sources row of one answer, shown once, under the answer, after its last citation. */
2314
2884
  function renderCitationSources(event) {
2315
2885
  const last = state.events.filter((candidate) => candidate.type === 'citation' && candidate.turnId === event.turnId).at(-1);
@@ -2344,8 +2914,12 @@
2344
2914
  function citationRow(chips) {
2345
2915
  const wrap = document.createElement('div'); wrap.className = 'ai-chat-sources';
2346
2916
  const head = document.createElement('span'); head.className = 'ai-chat-sources-head';
2347
- head.textContent = 'Sources the AI gave for this answer';
2348
- 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.';
2917
+ // #2643: a source a person chose is not one the AI gave, so a row holding one says neither.
2918
+ const chosen = chips.some((chip) => chip.classList.contains('chosen'));
2919
+ head.textContent = chosen ? 'Sources for this answer' : 'Sources the AI gave for this answer';
2920
+ head.dataset.tip = chosen
2921
+ ? 'FloLess found each source. It says whether the AI was shown one it cited, and marks one a person chose as chosen. It does not check that a source supports the claim.'
2922
+ : 'FloLess found each source and says whether the AI was shown it. It does not check that a source supports the claim.';
2349
2923
  const list = document.createElement('div'); list.className = 'ai-chat-sources-list';
2350
2924
  list.append(...chips);
2351
2925
  wrap.append(head, list);
@@ -2362,6 +2936,14 @@
2362
2936
  const answer = marker?.closest('.ai-chat-message')
2363
2937
  ?? [...ui.feed.querySelectorAll('.ai-chat-message.assistant')].filter((node) => node.dataset.turnId === turnId).at(-1);
2364
2938
  const when = answer?.querySelector('time')?.textContent?.trim();
2939
+ const claim = unsourcedClaimWords(turnId, anchor);
2940
+ const where = when ? `in your answer of ${when}` : 'in your answer';
2941
+ return claim ? `For this claim ${where}, which has no source: “${claim}”` : `For the claim with no source ${where}`;
2942
+ }
2943
+
2944
+ /** The words just before a claim's "?" marker (the last 90 characters), or '' when the answer shows no marker for it. */
2945
+ function unsourcedClaimWords(turnId, anchor) {
2946
+ const marker = [...ui.feed.querySelectorAll('button.ai-chat-cite')].find((node) => node.dataset.turnId === (turnId || '') && node.dataset.anchor === anchor);
2365
2947
  const block = marker?.closest('p, li, h1, h2, h3, blockquote');
2366
2948
  let before = '';
2367
2949
  if (block && marker) {
@@ -2377,9 +2959,7 @@
2377
2959
  before = parts.join('').replace(/\s+/g, ' ').trim();
2378
2960
  }
2379
2961
  const words = [...before];
2380
- const claim = words.length > 90 ? `…${words.slice(-90).join('').trimStart()}` : before;
2381
- const where = when ? `in your answer of ${when}` : 'in your answer';
2382
- return claim ? `For this claim ${where}, which has no source: “${claim}”` : `For the claim with no source ${where}`;
2962
+ return words.length > 90 ? `…${words.slice(-90).join('').trimStart()}` : before;
2383
2963
  }
2384
2964
 
2385
2965
  /** Never overwrites what the person is writing: the text goes after it. */
@@ -2413,12 +2993,11 @@
2413
2993
  if (finished) return;
2414
2994
  finished = true;
2415
2995
  if (dialog.open) dialog.close();
2416
- dialog.remove();
2996
+ hide();
2417
2997
  if (picture) URL.revokeObjectURL(picture);
2418
2998
  liveCitationOpener(turnId, row.anchor)?.focus({ preventScroll: true });
2419
2999
  };
2420
3000
  close.addEventListener('click', finish);
2421
- dialog.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.preventDefault(); finish(); } });
2422
3001
  dialog.addEventListener('close', finish);
2423
3002
  head.append(title, close);
2424
3003
  const note = Object.assign(document.createElement('span'), { className: 'ai-chat-source-viewer-note', textContent: citationProvenance(entry) });
@@ -2427,8 +3006,8 @@
2427
3006
  status.setAttribute('role', 'status');
2428
3007
  body.append(status);
2429
3008
  dialog.append(head, note, body);
2430
- document.body.append(dialog);
2431
- dialog.showModal();
3009
+ const hide = showChatViewer(dialog, finish);
3010
+ close.focus({ preventScroll: true });
2432
3011
  const refused = async (response) => {
2433
3012
  if (response.status === 404) return 'FloLess no longer holds this source, or its project is no longer part of this conversation.';
2434
3013
  if (response.status === 410) {
@@ -2441,7 +3020,13 @@
2441
3020
  const said = await response.json().catch(() => null);
2442
3021
  return typeof said?.message === 'string' && said.message ? said.message : 'FloLess could not open this source right now. Try again in a moment.';
2443
3022
  };
2444
- const SHOWN = {
3023
+ // #2643: a chosen sheet's picture is the one FloLess held when the person chose it; the AI was not shown it by that.
3024
+ const SHOWN = entry.chosen ? {
3025
+ 'as-seen': 'The sheet picture FloLess held when you chose it.',
3026
+ 'from-source:changed': 'Rendered from the source drawing: the sheet picture FloLess holds has changed since you chose it.',
3027
+ 'from-source:missing': 'Rendered from the source drawing: FloLess no longer holds the sheet picture it held when you chose it.',
3028
+ 'from-source:unchecked': 'Rendered from the source drawing: FloLess could not check the stored sheet picture just now.',
3029
+ } : {
2445
3030
  'as-seen': 'The sheet picture the AI was shown.',
2446
3031
  'from-source:tiles': 'The whole sheet, rendered from its source drawing. The AI saw this sheet enlarged in tiles.',
2447
3032
  'from-source:changed': 'Rendered from the source drawing: the sheet picture FloLess holds has changed since the AI looked at it.',
@@ -2467,6 +3052,24 @@
2467
3052
  return;
2468
3053
  }
2469
3054
  if (entry.kind === 'member') { await showCitedMember(row, { dialog, body, status, finish, refused, done: () => finished }); return; }
3055
+ if (entry.kind === 'project-file') {
3056
+ // #2701: a file of the project's folder, checked now against the size and digest it was cited with.
3057
+ const response = await fetch(citationUrl(row, 'project-file'), { credentials: 'same-origin', cache: 'no-store' });
3058
+ if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
3059
+ const { file } = await response.json();
3060
+ if (finished) return;
3061
+ if (!file) { status.textContent = 'FloLess could not open this source right now. Try again in a moment.'; return; }
3062
+ if (file.state === 'refused') status.textContent = `FloLess does not open ${file.path} as the cited file: ${file.reason}.`;
3063
+ else if (file.state === 'gone') status.textContent = `${file.path} is no longer in the project folder.`;
3064
+ else if (file.state === 'changed') status.textContent = `${file.path} has changed since the answer cited it, so FloLess does not show it as the cited file.`;
3065
+ else if (typeof file.text === 'string') {
3066
+ status.textContent = `${file.path} in the project folder, as it was cited${file.truncated ? '. Showing the start of the file' : ''}.`;
3067
+ const pre = Object.assign(document.createElement('pre'), { className: 'ai-chat-source-viewer-text', tabIndex: 0, textContent: file.text });
3068
+ pre.setAttribute('aria-label', `Text of ${entry.label}`);
3069
+ body.append(pre);
3070
+ } else status.textContent = `${file.path} in the project folder, as it was cited (${Number(file.bytes).toLocaleString()} bytes). FloLess does not show this kind of file here.`;
3071
+ return;
3072
+ }
2470
3073
  if (entry.kind === 'attachment') {
2471
3074
  const response = await fetch(citationUrl(row, 'attachment'), { credentials: 'same-origin', cache: 'no-store' });
2472
3075
  if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
@@ -2556,11 +3159,15 @@
2556
3159
  fact('Mark', member.mark ?? 'No mark');
2557
3160
  fact('Profile', member.profile ?? 'Not recorded');
2558
3161
  const views = Array.isArray(member.views) ? member.views : [];
2559
- fact('Read on', views.length ? views.map((v) => (v.title ? `${v.sheet} (${v.title})` : v.sheet)).join(', ') : 'No sheet recorded');
2560
- body.insertBefore(Object.assign(document.createElement('p'), { className: 'ai-chat-source-viewer-sub', textContent: 'As the answer cited it' }), status);
3162
+ // #2643: a member the person chose is described as it was when chosen, never as the answer citing it. "Read on" is
3163
+ // the drawings the model's read found it on; for a chosen member it says "On sheets", so no read is put near the AI.
3164
+ const chosen = !!row.entry?.chosen;
3165
+ fact(chosen ? 'On sheets' : 'Read on', views.length ? views.map((v) => (v.title ? `${v.sheet} (${v.title})` : v.sheet)).join(', ') : 'No sheet recorded');
3166
+ body.insertBefore(Object.assign(document.createElement('p'), { className: 'ai-chat-source-viewer-sub', textContent: chosen ? 'As it was when you chose it' : 'As the answer cited it' }), status);
2561
3167
  body.insertBefore(facts, status);
2562
- status.textContent = member.model === 'same' ? 'The model is the same version as when the answer cited it.'
2563
- : member.model === 'changed' ? 'The model has changed since this answer; the member is still in it. Its size or position may differ from what the answer described.'
3168
+ status.textContent = member.model === 'same' ? (chosen ? 'The model is the same version as when you chose this member.' : 'The model is the same version as when the answer cited it.')
3169
+ : member.model === 'changed' ? (chosen ? 'The model has changed since you chose this member; the member is still in it. Its size or position may differ from when you chose it.'
3170
+ : 'The model has changed since this answer; the member is still in it. Its size or position may differ from what the answer described.')
2564
3171
  : member.model === 'no-model' ? 'This project has no steel model FloLess can show now, so the member cannot be shown in it.'
2565
3172
  : 'This member is no longer in the model.';
2566
3173
  if (member.model === 'gone' || member.model === 'no-model') return;
@@ -2767,12 +3374,10 @@
2767
3374
  label.textContent = requestTypeLabels[payload.requestType] || String(payload.requestType || 'Request').replace(/-/g, ' ');
2768
3375
  const status = document.createElement('span'); status.className = 'ai-chat-request-status';
2769
3376
  status.textContent = requestStatusLabels[payload.requestStatus] || String(payload.requestStatus || 'pending').replace(/-/g, ' ');
2770
- // #2185: always-visible ✕ - hides the card, and on a request that is still waiting also sets the request aside (with Undo).
2771
- const hide = document.createElement('button'); hide.type = 'button'; hide.className = 'ai-chat-request-dismiss'; hide.textContent = '×';
2772
- hide.dataset.commandId = `shell.chat-request-dismiss#${payload.requestId || 'linked request'}`;
2773
- hide.setAttribute('aria-label', 'Dismiss this request');
2774
3377
  status.setAttribute('role', 'status');
2775
- head.append(label, status, hide);
3378
+ // #2678: the card's chevron (on its shell, like every other card in the conversation) only folds it; setting the request aside
3379
+ // is Dismiss, named, below. It used to be the ×, which made hiding a waiting request also turn it down.
3380
+ head.append(label, status);
2776
3381
  const body = document.createElement('p'); body.textContent = payloadText(event);
2777
3382
  item.append(head, body);
2778
3383
  if (Array.isArray(payload.sourceNames) && payload.sourceNames.length) {
@@ -2783,10 +3388,13 @@
2783
3388
  item.append(sources);
2784
3389
  }
2785
3390
  const actions = document.createElement('div'); actions.className = 'ai-chat-request-actions';
3391
+ const dismiss = button('Dismiss', `shell.chat-request-dismiss#${payload.requestId || 'linked request'}`, 'ai-chat-request-dismiss');
3392
+ dismiss.dataset.tip = 'Set this request aside. It stays in Requests → Done, and you can undo it';
3393
+ dismiss.setAttribute('aria-label', 'Dismiss this request');
2786
3394
  const open = button('Open Requests', `shell.requests-open#${payload.requestId || 'linked request'}`);
2787
3395
  open.dataset.tip = 'Open the linked request and its detailed progress';
2788
3396
  open.addEventListener('click', () => window.flolessBridge?.openRequest?.(payload.requestId));
2789
- actions.append(open); item.append(actions);
3397
+ actions.append(dismiss, open); item.append(actions);
2790
3398
  // Its live state replaces the frozen copy above as soon as it is known (and again whenever Requests changes).
2791
3399
  initRequestCard(item, event);
2792
3400
  return item;
@@ -2795,8 +3403,9 @@
2795
3403
  /*
2796
3404
  * #2185 - the request card tells the truth about its request, now. The frozen copy in the event says "Queued" for ever; the
2797
3405
  * server's projection says Waiting for the AI / The AI is working / The AI has a question / Done / Dismissed / Expired.
2798
- * ✕ is always there: on a request that is only waiting it sets the request aside (Undo puts it back); when the AI is
2799
- * working on it the card ASKS - stop that work and dismiss, or keep it. On one that is already done it hides the card.
3406
+ * Dismiss is there until the request is finished: on a request that is only waiting it sets the request aside (Undo puts
3407
+ * it back); when the AI is working on it the card ASKS - stop that work and dismiss, or keep it. (#2678: hiding the card is
3408
+ * its chevron on the shell, and decides nothing.)
2800
3409
  */
2801
3410
  const REQUEST_CARD_WORDS = { dismissed: 'Dismissed', expired: 'Expired', settled: 'Done' };
2802
3411
  const REQUEST_CARD_HIDDEN_KEY = 'floless:chat-hidden-request-cards';
@@ -2809,10 +3418,11 @@
2809
3418
  return new Set(Array.isArray(parsed) ? parsed.filter((id) => typeof id === 'string') : []);
2810
3419
  } catch { return new Set(); }
2811
3420
  }
2812
- function rememberHiddenRequestCard(eventId, hidden) {
3421
+ /** #2678: a card opened again drops the hide #2185's × remembered for it (nothing is written for any other card). */
3422
+ function forgetHiddenRequestCard(eventId) {
2813
3423
  const ids = hiddenRequestCards();
2814
- if (hidden) ids.add(eventId); else ids.delete(eventId);
2815
- try { localStorage.setItem(REQUEST_CARD_HIDDEN_KEY, JSON.stringify([...ids].slice(-300))); } catch { /* private mode: it shows again next time */ }
3424
+ if (!ids.delete(eventId)) return;
3425
+ try { localStorage.setItem(REQUEST_CARD_HIDDEN_KEY, JSON.stringify([...ids])); } catch { /* private mode: it starts folded again next time */ }
2816
3426
  }
2817
3427
 
2818
3428
  /** The word for a request's live state, or '' when nothing live is known yet (the frozen word stays). */
@@ -2843,26 +3453,27 @@
2843
3453
  item.querySelector('.ai-chat-request-actions')?.prepend(undo);
2844
3454
  }
2845
3455
  } else if (undo) undo.remove();
2846
- const hideButton = item.querySelector('.ai-chat-request-dismiss');
2847
- if (hideButton) {
2848
- const finished = live && (live.found === false || set);
2849
- hideButton.dataset.tip = finished ? 'Hide this card from the chat' : 'Dismiss this request. It stays in Requests → Done, and you can undo it';
2850
- hideButton.setAttribute('aria-label', finished ? 'Hide this card' : 'Dismiss this request');
2851
- }
3456
+ // Nothing is left to set aside once the request is finished, dismissed or gone; its card still folds (its chevron).
3457
+ const finished = Boolean(live && (live.found === false || set));
3458
+ const dismiss = item.querySelector('.ai-chat-request-dismiss');
3459
+ if (dismiss) dismiss.hidden = finished;
3460
+ // #2678: what a hidden card's line says still waits: the person (the server's "needs you", except a request only waiting
3461
+ // for the AI to start it), or the AI. The line says the card's own live word either way.
3462
+ if (finished) item.dataset.waits = 'done';
3463
+ else item.dataset.waits = live?.attention?.state === 'needs-you' && live.attention.code !== 'waiting-to-start' ? 'you' : 'ai';
2852
3464
  }
2853
3465
 
2854
3466
  function initRequestCard(item, event) {
2855
3467
  item.dataset.cardEventId = event.eventId;
2856
- if (hiddenRequestCards().has(event.eventId)) item.hidden = true;
2857
- const hide = item.querySelector('.ai-chat-request-dismiss');
2858
- hide?.addEventListener('click', () => { void dismissRequestFromCard(item, event.eventId); });
3468
+ item.querySelector('.ai-chat-request-dismiss')?.addEventListener('click', () => { void dismissRequestFromCard(item); });
2859
3469
  paintRequestCard(item);
2860
3470
  queueMicrotask(() => { void refreshRequestCards(); });
2861
3471
  }
2862
3472
 
2863
3473
  async function refreshRequestCards({ force = false } = {}) {
2864
3474
  if (!ui.feed) return;
2865
- const cards = [...ui.feed.querySelectorAll('.ai-chat-request-card[data-request-id]')].filter((card) => card.dataset.requestId);
3475
+ // #2678: a hidden card's one line carries its request too, so the request is still polled and the line stays current.
3476
+ const cards = [...ui.feed.querySelectorAll('.ai-chat-request-card[data-request-id], .ai-chat-feed-hidden[data-request-id]')].filter((card) => card.dataset.requestId);
2866
3477
  if (!cards.length) return;
2867
3478
  if (!force && Date.now() - state.requestCardsAt < 2500) return;
2868
3479
  state.requestCardsAt = Date.now();
@@ -2872,6 +3483,7 @@
2872
3483
  catch { return; /* the card keeps what it last knew; the next poll tries again */ }
2873
3484
  if (!Array.isArray(statuses)) return;
2874
3485
  for (const live of statuses) if (live?.id) state.requestCards.set(live.id, live);
3486
+ // A hidden card's line reads these on the conversation's next repaint (the chat poll, every 5 s).
2875
3487
  for (const card of ui.feed.querySelectorAll('.ai-chat-request-card[data-request-id]')) paintRequestCard(card);
2876
3488
  }
2877
3489
 
@@ -2883,18 +3495,23 @@
2883
3495
  return { ok: response.ok && body.ok !== false, status: response.status, body };
2884
3496
  }
2885
3497
 
2886
- async function dismissRequestFromCard(item, eventId) {
3498
+ async function dismissRequestFromCard(item) {
2887
3499
  const requestId = item.dataset.requestId;
2888
3500
  if (!requestId) return;
3501
+ // #2678: the person's own click holds the card open (its Undo, its ask, its note stay in front of them), counted from
3502
+ // the click so a collapse while it is answered still wins.
3503
+ openFeedCard(item.dataset.cardEventId);
2889
3504
  const live = state.requestCards.get(requestId);
2890
- // Already done, set aside or gone: ✕ only hides this card from this chat.
3505
+ // Finished, set aside or gone since the card was drawn: nothing to dismiss. The card catches up (Dismiss goes), says so,
3506
+ // and keeps the keyboard on the card's other button.
2891
3507
  if (live && (live.found === false || live.lifecycle)) {
2892
- rememberHiddenRequestCard(eventId, true);
2893
- item.hidden = true;
3508
+ paintRequestCard(item);
3509
+ item.querySelector('.ai-chat-request-actions button:not([hidden])')?.focus();
3510
+ announce('This request is already finished, so there is nothing to dismiss.');
2894
3511
  return;
2895
3512
  }
2896
- const hide = item.querySelector('.ai-chat-request-dismiss');
2897
- if (hide) hide.disabled = true;
3513
+ const dismiss = item.querySelector('.ai-chat-request-dismiss');
3514
+ if (dismiss) dismiss.disabled = true;
2898
3515
  item.querySelector('.ai-chat-request-note')?.remove(); // a new try replaces the last failure's note
2899
3516
  try {
2900
3517
  const done = await lifecycleCall(requestId, 'dismiss');
@@ -2907,11 +3524,11 @@
2907
3524
  }
2908
3525
  if (done.body?.code === 'request-held' && done.body.hold) { askStopThenDismiss(item, done.body.hold); return; }
2909
3526
  if (done.status === 404 || done.body?.code === 'request-already-set-aside') { void refreshRequestCards({ force: true }); return; }
2910
- cardNotice(item, done.body?.error || 'FloLess couldn’t dismiss that request. It is still in Requests; try ✕ again.');
3527
+ cardNotice(item, done.body?.error || 'FloLess couldn’t dismiss that request. It is still in Requests; try Dismiss again.');
2911
3528
  } catch {
2912
- cardNotice(item, 'FloLess couldn’t reach the server, so the request was not dismissed. Try ✕ again in a moment.');
3529
+ cardNotice(item, 'FloLess couldn’t reach the server, so the request was not dismissed. Try Dismiss again in a moment.');
2913
3530
  } finally {
2914
- if (hide) hide.disabled = false;
3531
+ if (dismiss) dismiss.disabled = false;
2915
3532
  }
2916
3533
  }
2917
3534
 
@@ -2940,6 +3557,7 @@
2940
3557
  const go = button('Stop it and dismiss', `shell.chat-request-stop-dismiss#${item.dataset.requestId || 'linked request'}`, 'danger');
2941
3558
  go.addEventListener('click', async () => {
2942
3559
  go.disabled = true; keep.disabled = true;
3560
+ openFeedCard(item.dataset.cardEventId); // #2678: as Dismiss: the Undo it offers stays in front of them
2943
3561
  let stopped = true; // a stale stop means the work had already ended or changed: never claimed as "stopped"
2944
3562
  try {
2945
3563
  if (stop.kind === 'chat') {
@@ -2983,7 +3601,7 @@
2983
3601
  try {
2984
3602
  const done = await lifecycleCall(requestId, 'restore');
2985
3603
  if (!done.ok) { cardNotice(item, done.body?.error || 'FloLess couldn’t put that request back. It is still in Requests → Done; try Undo again.'); return; }
2986
- rememberHiddenRequestCard(item.dataset.cardEventId, false);
3604
+ forgetHiddenRequestCard(item.dataset.cardEventId);
2987
3605
  await refreshRequestCards({ force: true });
2988
3606
  } catch {
2989
3607
  cardNotice(item, 'FloLess couldn’t reach the server, so the request was not put back. Try Undo again in a moment.');
@@ -3020,7 +3638,7 @@
3020
3638
  // #2037: a Codex auto-review decision is a receipt, not a failure: approved is information, held back is a notice.
3021
3639
  const review = event.payload?.tool === 'auto-review' ? event.payload.decision : null;
3022
3640
  // #2035: a step declined because nobody was watching a scheduled run is a notice the person reads later, not an error.
3023
- const unattended = event.payload?.tool === 'unattended-decline' || event.payload?.tool === 'unattended-question';
3641
+ const unattended = event.payload?.tool === 'unattended-decline' || event.payload?.tool === 'unattended-question' || event.payload?.tool === 'approval-dropped';
3024
3642
  // #2058: an account command Codex ran without asking FloLess already ran; its line says the result is unchecked.
3025
3643
  const unchecked = event.payload?.tool === 'unchecked-command';
3026
3644
  item.className = review === 'approved' ? 'ai-chat-event auto-review' : review || unattended || unchecked ? 'ai-chat-event auto-review held' : 'ai-chat-event error';
@@ -3029,7 +3647,7 @@
3029
3647
  const label = document.createElement('strong');
3030
3648
  // #2223: a question the AI asked while nobody was watching went unanswered, not declined.
3031
3649
  label.textContent = review === 'approved' ? 'Auto-approved' : review ? 'Held back'
3032
- : unattended ? (event.payload?.tool === 'unattended-question' ? 'Not asked' : 'Declined') : unchecked ? 'Not checked' : 'Not done';
3650
+ : unattended ? (event.payload?.tool === 'unattended-question' ? 'Not asked' : event.payload?.tool === 'approval-dropped' ? 'Not answered' : 'Declined') : unchecked ? 'Not checked' : 'Not done';
3033
3651
  item.append(label, document.createTextNode(` · ${event.payload.message}`));
3034
3652
  return item;
3035
3653
  }
@@ -3376,7 +3994,9 @@
3376
3994
  notNow.disabled = entry.busy;
3377
3995
  notNow.addEventListener('click', () => { void setConnectionDismissed(event, true); });
3378
3996
  // Nothing is left to set aside once it is connected (#2185); Change account is still there.
3379
- if (!connected) { actions.append(notNow); entry.seenOpen = true; }
3997
+ // #2678: not connected yet, it waits for the person; a hidden card's line says the card's own sentence about where it is.
3998
+ if (!connected) { actions.append(notNow); entry.seenOpen = true; card.dataset.waits = 'you'; card.dataset.waitsSays = stateLine.textContent; }
3999
+ else card.dataset.waits = 'done';
3380
4000
  card.append(stateLine, ...(keyCode ? [keyCode] : []), actions, confirmHost, receiptHost, said, error);
3381
4001
  return card;
3382
4002
  }
@@ -3762,6 +4382,13 @@
3762
4382
  // A request that has been answered no longer "needs your OK": the eyebrow says where it ended up.
3763
4383
  // #2427: a step that left the last click to the person is theirs to finish, not a failure and not yet done.
3764
4384
  const handedOver = current.state === 'done' && current.result?.code === 'step-handed-over';
4385
+ // #2678: what a hidden card's line says still waits: the person's choice, their last click, a result to check, or the
4386
+ // work running. The line's words follow the card's, never the kind's when they would not be true.
4387
+ const waitsSays = handedOver ? 'The last step is yours. Expand it to finish.'
4388
+ : { failed: 'Could not finish. Expand it to see why.', unknown: 'Outcome unknown. Expand it to check the result.' }[current.state];
4389
+ if (current.state === 'proposed' || waitsSays) card.dataset.waits = 'you';
4390
+ else card.dataset.waits = current.state === 'executing' ? 'ai' : 'done';
4391
+ if (waitsSays) card.dataset.waitsSays = waitsSays;
3765
4392
  eyebrow.textContent = handedOver ? 'Waiting for you'
3766
4393
  : { executing: actionId === 'workflows.run' || actionId === 'routines.run' ? 'Running' : 'Working', done: 'Finished', failed: 'Could not finish', unknown: 'Outcome unknown' }[current.state] || ACTION_EYEBROWS[risk];
3767
4394
  const strong = document.createElement('strong');
@@ -4295,12 +4922,11 @@
4295
4922
  if (finished) return;
4296
4923
  finished = true;
4297
4924
  if (dialog.open) dialog.close();
4298
- dialog.remove();
4925
+ hide();
4299
4926
  if (picture) URL.revokeObjectURL(picture);
4300
4927
  if (opener?.isConnected) opener.focus({ preventScroll: true });
4301
4928
  };
4302
4929
  close.addEventListener('click', finish);
4303
- dialog.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.preventDefault(); finish(); } });
4304
4930
  dialog.addEventListener('close', finish);
4305
4931
  head.append(Object.assign(document.createElement('strong'), { textContent: title }), close);
4306
4932
  const note = Object.assign(document.createElement('span'), { className: 'ai-chat-source-viewer-note', textContent: EVIDENCE_ORIGIN[place.origin].note(place) });
@@ -4329,8 +4955,7 @@
4329
4955
  show(false);
4330
4956
  body.append(status, frame);
4331
4957
  dialog.append(head, note, views, body);
4332
- document.body.append(dialog);
4333
- dialog.showModal();
4958
+ const hide = showChatViewer(dialog, finish);
4334
4959
  close.focus({ preventScroll: true });
4335
4960
  // A place that changed or is gone says so and offers the way on: the card asked for again, never sent for the person.
4336
4961
  const offerAgain = (why) => {
@@ -4404,7 +5029,13 @@
4404
5029
  const body = document.createElement('div'); body.className = 'ai-chat-readiness-body'; body.tabIndex = 0;
4405
5030
  body.setAttribute('aria-label', 'Connections and their checks');
4406
5031
  for (const row of rows) body.append(readinessRow(row, card));
4407
- node.append(head, limits, body);
5032
+ node.append(head, limits);
5033
+ // #2521 row 5: measured on a Quick model (or one whose AI decisions could not be read): said with the card, which
5034
+ // outlives the project screen, in the server's own words.
5035
+ const quick = card.quick && (card.quick.state === 'quick' || card.quick.state === 'unknown') && typeof card.quick.label === 'string' ? card.quick : null;
5036
+ if (quick) node.append(Object.assign(document.createElement('p'), { className: 'ai-chat-readiness-limits ai-chat-readiness-quick',
5037
+ textContent: `The model measured here: ${quick.label}. ${quick.tip || ''}`.trim() }));
5038
+ node.append(body);
4408
5039
  const notes = [];
4409
5040
  // The card names at most a few of each; the rest are counted, never dropped.
4410
5041
  const andMore = (list, more) => `${list.join(', ')}${more ? `, and ${more} more` : ''}`;
@@ -4744,6 +5375,9 @@
4744
5375
  case 'create-workflow':
4745
5376
  return { title: guideText?.title || `Build a workflow: ${move.name || ''}`, action: 'Build it', detail: move.purpose,
4746
5377
  note: 'Opens New workflow with its name filled in. Nothing is built until you confirm there.' };
5378
+ // An Open card only shows a page: there is no next step to confirm.
5379
+ case 'open':
5380
+ return guideText ? { ...guideText, note: 'This only opens the page. Nothing changes.' } : null;
4747
5381
  default:
4748
5382
  return guideText ? { ...guideText, note: 'Nothing happens until you confirm in the next step.' } : null;
4749
5383
  }
@@ -4955,6 +5589,14 @@
4955
5589
  const fact = 'fact' in server ? server.fact : payload.fact;
4956
5590
  const blocking = cardClass === 'blocking' || cardClass === 'resume';
4957
5591
  if (!blocking) card.classList.add('is-idea');
5592
+ // #2678: only a read whose result came back is settled (it folds by itself). A failed or unknown outcome, or a card
5593
+ // offered again, is the person's to look at; its line says which.
5594
+ const read = server.state === 'used' ? entry.result : null;
5595
+ card.dataset.waits = read?.ok ? 'done' : 'you';
5596
+ const waitsSays = read ? (read.ok ? 'Done. Expand it to see the result.' : 'Did not complete. Expand it to see why.')
5597
+ : server.state === 'used' && server.outcome === 'indeterminate' ? 'Outcome unknown. Expand it to check the result.'
5598
+ : entry.error ? 'Could not finish. Expand it to see why.' : '';
5599
+ if (waitsSays) card.dataset.waitsSays = waitsSays;
4958
5600
  const head = assistantNode('div', 'ai-chat-filter-card-head');
4959
5601
  const named = assistantNode('div', 'ai-chat-action-named');
4960
5602
  const strong = assistantNode('strong', '', text.title);
@@ -5000,7 +5642,8 @@
5000
5642
  use.dataset.tip = move.kind === 'follow-up' ? 'Puts this message in the message box. Nothing is sent.'
5001
5643
  : move.kind === 'action' && move.risk === 'read' ? 'Shows the result here. Nothing changes.'
5002
5644
  : move.kind === 'action' && move.risk !== 'human-only' ? 'Opens a request below for your OK. Nothing runs from this card.'
5003
- : 'Opens the place to do this. Nothing happens until you confirm there.';
5645
+ : move.kind === 'open' ? `${text.action}. Nothing changes.`
5646
+ : 'Opens the place to do this. Nothing happens until you confirm there.';
5004
5647
  if (entry.busy === 'use') use.setAttribute('aria-busy', 'true');
5005
5648
  use.addEventListener('click', () => { void useAssistantCard(entry, text); });
5006
5649
  for (const control of [later, never, use]) control.disabled = Boolean(entry.busy);
@@ -5138,6 +5781,9 @@
5138
5781
  async function useAssistantCard(entry, text) {
5139
5782
  if (entry.busy) return;
5140
5783
  const chatId = entry.event.chatId;
5784
+ // #2678: the person's own click holds the card open (a read's result is shown on it), counted from the click so a
5785
+ // collapse while it is answered still wins.
5786
+ openFeedCard(entry.event.eventId);
5141
5787
  entry.busy = 'use'; entry.error = '';
5142
5788
  repaintAssistantCard(entry);
5143
5789
  let answer = null;
@@ -5282,6 +5928,9 @@
5282
5928
 
5283
5929
  /** The request a card made arrives as its own card below (an event): its Confirm gets the keyboard once it is drawn. */
5284
5930
  function focusProposalConfirm(proposalId, onMissing = () => {}, tries = 40) {
5931
+ // #2678: Show the request is the person asking for the proposal card: a folded one opens, and stays open.
5932
+ const asked = state.events.find((event) => event.type === 'action-proposal' && String(event.payload?.proposalId || event.eventId) === proposalId);
5933
+ if (asked) { openFeedCard(asked.eventId); paintEvents(); }
5285
5934
  const proposal = ui.feed?.querySelector(`.ai-chat-action-card[data-proposal-id="${CSS.escape(proposalId)}"]`);
5286
5935
  if (proposal) {
5287
5936
  // Its Confirm (or a person-only step's Open); a request already answered has neither, so its own line.
@@ -5415,6 +6064,180 @@
5415
6064
  return fold;
5416
6065
  }
5417
6066
 
6067
+ /*
6068
+ * #2678 — EVERY CARD IN THE CONVERSATION FOLDS TO ONE LINE. Owner, 2026-10-23: "Any card should have that functionality",
6069
+ * once the cards above the message box could (#2684). Its chevron (or Esc) folds a card to one line that says what it was
6070
+ * and what still waits; the line's chevron opens it again with nothing lost, showing where it stands now. Owner,
6071
+ * 2026-10-24: a card arrives open, and once it is answered or settled it folds by itself ("follow what Claude does"),
6072
+ * still one click from open; so does one still waiting for the person once they send a message after it ("someone
6073
+ * answered it into the general chat box ... this card should also disappear"), the drawing card's rule (#2684). A card
6074
+ * the person opens stays open (one still waiting, until they send another message). Nothing leaves the conversation: the
6075
+ * line says what happened, or what still waits. Folding applies, answers, dismisses or declines nothing: a suggestion
6076
+ * stays unapplied, a request keeps whatever state it is in. The chevron sits on a shell kept per card rather than in the
6077
+ * card, because several cards repaint themselves in place (replaceWith, the Guide's replaceChildren) and would drop it.
6078
+ * A one-line row (a receipt, a notice, a line the AI ran) and an ordinary message have none: folding one line to another
6079
+ * saves nothing (UX review; #2684 left the one-line auto-approval strip alone for the same reason). A fold by hand is not
6080
+ * remembered: a reload shows every card as it arrives (open, or folded by itself once settled), as above the message
6081
+ * box, except a request card #2185's × hid for good (below).
6082
+ * A card says what waits with data-waits, set by its own renderer: "you" (the person's choice or answer), "ai" (the AI
6083
+ * or the read still works) or "done" (answered or settled: it folds by itself); data-waits-says, when set, is what its
6084
+ * line says about it instead of the kind's words. A card with no mark (a result, a card still loading) stays as it is.
6085
+ */
6086
+ // Cards the person folded by hand (and #2185's hidden requests, below), until they open them.
6087
+ const hiddenFeedCards = new Set();
6088
+ // Cards the person opened, each with the messages there were then (folded again by hand: hiddenFeedCards). Their choice
6089
+ // wins over folding by itself, until they send another message.
6090
+ const openedFeedCards = new Map();
6091
+ // Cards folded because the person wrote in the message box after them.
6092
+ const movedPastFeedCards = new Set();
6093
+ // #2185's × hid a finished request card for good, remembered in this browser: those cards start folded instead, until opened.
6094
+ for (const id of hiddenRequestCards()) hiddenFeedCards.add(id);
6095
+ const feedCardShells = new Map();
6096
+ const feedCardLines = new Map();
6097
+ let feedCardsChat = null;
6098
+
6099
+ /**
6100
+ * What a feed card is, for its chevron and its line: { label, name, waits, working } (waits: what its line says while the
6101
+ * person's choice is open; working: while the AI's side works), or null for an event whose node never hides.
6102
+ */
6103
+ function feedCardKind(event) {
6104
+ const payload = event?.payload || {};
6105
+ const choice = 'It waits for your choice.';
6106
+ switch (event?.type) {
6107
+ case 'filter-proposal': return { label: 'Drawing Filter', name: 'the Drawing Filter suggestion', waits: `Not applied yet. ${choice}` };
6108
+ case 'user-message':
6109
+ if (payload.source !== 'request') return null;
6110
+ return payload.filterAi ? { label: 'Drawing Filter', name: 'your Drawing Filter question' } : { label: 'Request', name: 'the request card' };
6111
+ case 'assistant-message':
6112
+ return payload.filterAi && !payload.delta ? { label: 'Drawing Filter', name: 'the Drawing Filter answer', waits: `Not applied yet. ${choice}` } : null;
6113
+ case 'action-proposal': return { label: 'Action', name: 'the suggested action', waits: `Not run yet. ${choice}` };
6114
+ case 'action-call': return { label: 'Result', name: 'the result the AI showed' };
6115
+ case 'connection-proposal': return { label: 'Connection', name: 'the connection suggestion', waits: choice };
6116
+ case 'connection-check': return { label: 'Connection', name: 'the connection check' };
6117
+ case 'next-move': return { label: 'Next step', name: 'the suggested next step', waits: choice };
6118
+ case 'tekla-read': return { label: 'Model read', name: 'the model read' };
6119
+ case 'height-question': return { label: 'Heights', name: 'the height question', waits: 'Still waiting for your answer.', working: 'Your answers are with the read.' };
6120
+ case 'setup-question': return { label: 'Read setup', name: 'the read setup question', waits: 'Still waiting for your answer.', working: 'Your answers are with the read.' };
6121
+ default: return null;
6122
+ }
6123
+ }
6124
+
6125
+ const feedCardRow = (node) => node.matches('.ai-chat-event, .ai-chat-action-row');
6126
+ /**
6127
+ * The person wrote in the message box after this card (and after they last opened it): they moved on, so a card that
6128
+ * waits for them folds, still saying it waits. Only a message FloLess says was not sent does not count (#2684's rule).
6129
+ */
6130
+ function feedCardAnsweredInChat(event, id) {
6131
+ const seen = openedFeedCards.get(id);
6132
+ return state.events.some((other) => other.type === 'user-message' && !other.payload?.source && Number(other.sequence) > Number(event.sequence)
6133
+ && !seen?.has(messageId(other)) && !((other.payload?.followup || other.payload?.deliveryState) && followupDelivery(other) === 'not-sent'));
6134
+ }
6135
+ /** The element that says what waits on a card: the card itself, or the suggestion card inside an answer. */
6136
+ const feedCardMark = (node) => (node.matches('[data-waits]') ? node : node.querySelector('[data-waits]'));
6137
+ /** A card already folded to one quiet line of its own (set aside, Not now, used): nothing to fold (its chevron is hidden by CSS). */
6138
+ const feedCardFolded = (card) => Boolean(card?.matches('.is-collapsed, .is-dismissed') || card?.querySelector(':scope > .ai-chat-connection-collapsed'));
6139
+ /**
6140
+ * What the line says: the card's name or title, cut at a word, then what waits (the card's own words, else its kind's)
6141
+ * or the state word the card shows ("Applied", "Done", "Dismissed"). A request says its own live word either way.
6142
+ */
6143
+ function feedCardSentence(node, kind, mark) {
6144
+ const words = String((node.matches('.ai-chat-request-card') ? node.querySelector('p')?.textContent
6145
+ : node.getAttribute('aria-label') || node.querySelector('strong, .ai-chat-message-body, p')?.textContent) || node.textContent || '')
6146
+ .replace(/\s+/g, ' ').trim();
6147
+ const cut = (text, max) => (text.length > max ? `${text.slice(0, max).replace(/\s+\S*$/, '').replace(/[\s·,;:.-]+$/, '')}…` : text);
6148
+ const title = cut(words, 70);
6149
+ // A state word, cut too: the readiness card's chip is a whole summary.
6150
+ const shown = cut(node.querySelector('.ai-chat-request-status, .ai-chat-filter-state, .guide-move-eyebrow')?.textContent.trim() || '', 48);
6151
+ const waits = mark?.dataset.waits || '';
6152
+ const tail = mark?.dataset.waitsSays || (waits === 'you' && kind.waits) || (waits === 'ai' && kind.working)
6153
+ || (shown && `${shown.charAt(0).toUpperCase()}${shown.slice(1)}`);
6154
+ return { sentence: [title, tail].filter(Boolean).join(' · '), full: words };
6155
+ }
6156
+
6157
+ /** A feed card in its shell (with its chevron), or the one line it leaves while folded. Any other node comes back as it was. */
6158
+ function feedCard(node, event) {
6159
+ const kind = node && event?.eventId ? feedCardKind(event) : null;
6160
+ // A card its renderer keeps hidden (an assistant card whose state is still loading) shows nothing, so it gets no chevron.
6161
+ if (!kind || feedCardRow(node) || node.hidden) return node;
6162
+ const chatId = state.chat?.chatId || '';
6163
+ if (feedCardsChat !== chatId) { feedCardShells.clear(); feedCardLines.clear(); feedCardsChat = chatId; }
6164
+ const id = event.eventId;
6165
+ const mark = feedCardMark(node);
6166
+ const waits = mark?.dataset.waits || '';
6167
+ // Answered or settled folds by itself, unless the person opened it; so does one waiting for them once they write in the
6168
+ // message box. A card already one quiet line of its own stays as it is.
6169
+ // Once a message folds it, it stays folded while that message counts, whatever the card turns into meanwhile (its line
6170
+ // follows); a message refused or not sent stops counting, and the card is back.
6171
+ const movedPast = (waits === 'you' || movedPastFeedCards.has(id)) && feedCardAnsweredInChat(event, id);
6172
+ if (movedPast) movedPastFeedCards.add(id);
6173
+ const byItself = !feedCardFolded(node) && ((waits === 'done' && !openedFeedCards.has(id)) || movedPast);
6174
+ if (hiddenFeedCards.has(id) || byItself) {
6175
+ const { sentence, full } = feedCardSentence(node, kind, mark);
6176
+ // Amber while the person's choice waits, blue while the AI or the read still works, quiet once it is finished.
6177
+ const line = paintHiddenLine(feedCardLines.get(id), null, {
6178
+ className: `ai-chat-feed-hidden${waits === 'you' ? ' is-decision' : waits === 'ai' ? ' is-open' : ''}`, label: kind.label, sentence,
6179
+ commandId: `shell.chat-feed-card-show#${id}`, instance: kind.name, tip: full.length > 70 ? full : '', show: () => showFeedCard(id, kind),
6180
+ });
6181
+ // It opens a card that is no longer in the page, so it controls nothing: the state is in its name instead.
6182
+ line.removeAttribute('aria-expanded');
6183
+ line.setAttribute('aria-label', `Expand ${kind.name}. ${sentence}`);
6184
+ // A request's line follows its live state, which the request cards poll for (refreshRequestCards).
6185
+ if (node.matches('.ai-chat-request-card')) line.dataset.requestId = node.dataset.requestId || ''; else delete line.dataset.requestId;
6186
+ feedCardLines.set(id, line);
6187
+ return line;
6188
+ }
6189
+ let shell = feedCardShells.get(id);
6190
+ if (!shell) {
6191
+ shell = document.createElement('div');
6192
+ shell.className = 'ai-chat-feed-card';
6193
+ // The chevron of an open card (the receipt fold's own, turned down); the folded line's points right (paintHiddenLine).
6194
+ const hide = button('›', `shell.chat-feed-card-hide#${id}`, 'ai-chat-card-hide');
6195
+ // A double click is one hide: its second click would land on the line that took the card's place and show it again.
6196
+ hide.addEventListener('click', (click) => { if (!(click.detail > 1)) hideFeedCard(id); });
6197
+ shell.addEventListener('keydown', (key) => {
6198
+ if (!window.FlolessQuestionCard?.escapeHides(key) || feedCardFolded(shell.firstElementChild)) return;
6199
+ key.preventDefault(); key.stopPropagation(); hideFeedCard(id);
6200
+ });
6201
+ shell.hideButton = hide;
6202
+ shell.feedCardId = id;
6203
+ feedCardShells.set(id, shell);
6204
+ }
6205
+ const hide = shell.hideButton;
6206
+ hide.dataset.commandInstanceLabel = kind.name;
6207
+ hide.setAttribute('aria-label', `Collapse ${kind.name}`);
6208
+ hide.dataset.tip = waits === 'you' ? 'Collapse to one line. Nothing is applied or answered, and it keeps waiting for you.' : 'Collapse to one line. Expand it any time.';
6209
+ if (shell.firstChild !== node || shell.lastChild !== hide) shell.replaceChildren(node, hide);
6210
+ return shell;
6211
+ }
6212
+ /** Keyboard into a card: on the control `commandId` names, else its first usable control, else the card itself. */
6213
+ function focusFeedCard(card, commandId = null) {
6214
+ const controls = [...card.querySelectorAll('button, a[href], input, select, textarea, [tabindex="0"]')].filter((node) => !node.disabled && !node.closest('[hidden]'));
6215
+ const target = (commandId && controls.find((node) => node.dataset.commandId === commandId)) || controls[0] || card;
6216
+ if (target === card && !card.hasAttribute('tabindex')) card.tabIndex = -1;
6217
+ target.focus({ preventScroll: true });
6218
+ return target;
6219
+ }
6220
+ function hideFeedCard(eventId) {
6221
+ hiddenFeedCards.add(eventId); openedFeedCards.delete(eventId);
6222
+ paintEvents();
6223
+ feedCardLines.get(eventId)?.focus({ preventScroll: true });
6224
+ }
6225
+ /** The person opens a card: it stays open until they fold it (one still waiting, until their next message). */
6226
+ function openFeedCard(eventId) {
6227
+ hiddenFeedCards.delete(eventId); movedPastFeedCards.delete(eventId); openedFeedCards.set(eventId, drawingMessageIds());
6228
+ forgetHiddenRequestCard(eventId); // a card #2185's × hid for good stays open after a reload too, once opened
6229
+ }
6230
+ function showFeedCard(eventId, kind) {
6231
+ openFeedCard(eventId);
6232
+ paintEvents();
6233
+ const card = feedCardShells.get(eventId)?.firstElementChild;
6234
+ if (!card || card.classList.contains('ai-chat-card-hide')) return;
6235
+ // The keyboard lands on the card's first control (or the card), and a screen reader hears which card came back.
6236
+ focusFeedCard(card);
6237
+ card.scrollIntoView?.({ block: 'nearest' });
6238
+ announce(`${kind.label} card expanded.`);
6239
+ }
6240
+
5418
6241
  function renderEvent(event) {
5419
6242
  if (event.type === 'user-message' && event.payload?.source === 'request' && event.payload?.filterAi) return renderFilterQuestion(event);
5420
6243
  if (event.type === 'user-message' && event.payload?.source === 'request') return renderRequestCard(event);
@@ -5432,6 +6255,8 @@
5432
6255
  // #1900: a connection the AI suggested, the result of a check it asked for, and a check run under "Allow for this chat".
5433
6256
  if (event.type === 'connection-proposal') return renderConnectionProposal(event);
5434
6257
  if (event.type === 'connection-proposal-update') return null;
6258
+ // #2642/#2643: the person's assumption or chosen source on an unsourced claim is shown on that claim's chip and in its text, never as a row.
6259
+ if (event.type === 'citation-assumption' || event.type === 'citation-choice') return null;
5435
6260
  if (event.type === 'connection-check') return renderConnectionCheck(event);
5436
6261
  // #2046: a next move the Guide suggested; web/guide.js paints it and owns its button.
5437
6262
  // #2399 PR C2: a next step the assistant suggested in a project, workflow or workspace chat; this file paints it.
@@ -5778,6 +6603,8 @@
5778
6603
  */
5779
6604
  async function submitHeightAnswers(entry, answers, rowKey, sharedScope) {
5780
6605
  if (entry.busy) return false;
6606
+ // The messages there are as the person answers on the card, in its own chat (see drawingMessagesSeen).
6607
+ const seenAtAnswer = drawingEntryCurrent(entry) ? drawingMessageIds() : null;
5781
6608
  const ownedSlot = drawingEntryCurrent(entry) && ui.approvalTray?.querySelector('.ai-chat-drawing-step')?.dataset.drawingStep;
5782
6609
  const ownedNode = ownedSlot ? ui.approvalTray.querySelector('.ai-chat-drawing-step') : null;
5783
6610
  const pendingFocusId = ownedNode?.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
@@ -5797,7 +6624,8 @@
5797
6624
  ...[entry.view, result.question].flatMap((view) => (view?.ends || []).flatMap((row) => [...row.answer?.evidence || [], ...row.inherited || []])).map((ref) => ref.attachmentId),
5798
6625
  ]);
5799
6626
  entry.view = result.question;
5800
- saved = true;
6627
+ // Answering on the card means the person is on it: a message sent while its save kept failing does not fold it now.
6628
+ saved = true; entry.saveFailed = false; if (seenAtAnswer) drawingMessagesSeen(entry.chatId, seenAtAnswer);
5801
6629
  for (const answer of answers) {
5802
6630
  const key = heightEndKey(answer);
5803
6631
  entry.changing.delete(key); entry.drafts.delete(key); entry.selected.delete(key);
@@ -5831,6 +6659,8 @@
5831
6659
  } catch (error) {
5832
6660
  let message = heightErrorText(error, 'FloLess could not save this height. Try again.');
5833
6661
  if (error?.code === 'answer-evidence-unknown') message = dropStaleAnswerFiles([...new Set(answers.map(scopeOf))], entry);
6662
+ // A failed save, apart from the card's other notices: the hidden line says so and the card never hides by itself.
6663
+ entry.saveFailed = true;
5834
6664
  // Dropped, not kept: a reload that fails must show its own error and Try again, which only an
5835
6665
  // empty card does — an old view would hide both behind rows that are out of date.
5836
6666
  if (HEIGHT_STALE.has(error?.code)) { entry.cardError = message; entry.view = null; loadHeightQuestion(entry); }
@@ -6269,9 +7099,116 @@
6269
7099
  function drawingSlotRepaint() {
6270
7100
  paintDrawingQuestionSlot();
6271
7101
  }
7102
+ /*
7103
+ * Owner, 2026-10-23: "if card stays and I answer into the main chat, this card doesn't disappear. And it just taking half
7104
+ * of the screen." The question slot HIDES to one line above the message box: by hand (× or Esc on the card), and by itself
7105
+ * once the person sends a message after the card was posted or last shown. Every waiting drawing card hides together, so
7106
+ * hiding one never brings up the next; a card posted later arrives open. Nothing is dropped: drafts and answers stay, the
7107
+ * line says what still waits for the person, Show (or Answer / Change on the transcript card) brings it back, and a card
7108
+ * whose last answer did not save never hides by itself. A reload forgets a hide by hand; one after a message holds.
7109
+ * The workspace units question shares the slot and hides by hand only ("Any card should have that functionality").
7110
+ */
7111
+ const drawingHidden = new Map();
7112
+ let drawingHiddenLine = null;
7113
+ function lastEventSequence() { return Math.max(0, ...state.events.map((event) => Number(event.sequence) || 0)); }
7114
+ function messageId(event) { return event.clientSubmissionId || event.eventId; }
7115
+ function drawingMessageIds() { return new Set(state.events.filter((event) => event.type === 'user-message').map(messageId)); }
7116
+ function drawingCardHidden(entry) {
7117
+ const hidden = drawingHidden.get(entry.chatId) || { at: 0, byHand: false, shown: null };
7118
+ if (entry.key.startsWith('units/')) return hidden.byHand;
7119
+ if (hidden.at && entry.sequence <= hidden.at) return true;
7120
+ if (entry.saveFailed) return false;
7121
+ // Moved on the moment they send, while a follow-up still waits for the AI (E2E: an AI held on an approval kept one
7122
+ // "Sending to AI"); only a message FloLess says was not sent brings the card back.
7123
+ return state.events.some((event) => Number(event.sequence) > entry.sequence && event.type === 'user-message' && !event.payload?.source
7124
+ && !hidden.shown?.has(messageId(event))
7125
+ && !((event.payload?.followup || event.payload?.deliveryState) && followupDelivery(event) === 'not-sent'));
7126
+ }
7127
+ /**
7128
+ * Messages put behind the card, by identity. A sequence would not hold: a message sent a moment before carries a
7129
+ * stand-in sequence until the server confirms it with a higher one (Codex review). Show puts every message so far
7130
+ * behind it and clears a hide by hand; an answer adds the messages there were when it was given, in its own chat, and
7131
+ * keeps a hide by hand (Codex review round 2: taken when the save ENDED, a message sent meanwhile, or another chat's
7132
+ * messages after a switch, counted as seen).
7133
+ */
7134
+ function drawingMessagesSeen(chatId, ids, keep = true) {
7135
+ const current = keep ? drawingHidden.get(chatId) : null;
7136
+ drawingHidden.set(chatId, { at: current?.at || 0, byHand: Boolean(current?.byHand), shown: new Set([...(current?.shown || []), ...ids]) });
7137
+ }
7138
+ function showDrawingSlot(chatId) { drawingMessagesSeen(chatId, drawingMessageIds(), false); }
7139
+ function hideDrawingByHand(chatId) {
7140
+ drawingHidden.set(chatId, { at: lastEventSequence(), byHand: true, shown: null });
7141
+ // Removed first, so the line knows the person hid it and can take the focus the card had.
7142
+ ui.approvalTray?.querySelector('.ai-chat-drawing-step')?.remove();
7143
+ paintDrawingQuestionSlot();
7144
+ drawingHiddenLine?.focus({ preventScroll: true });
7145
+ }
7146
+ function showDrawingByHand(chatId) {
7147
+ showDrawingSlot(chatId);
7148
+ // The Enter or Space that pressed Show must not also choose an answer on the card it opens.
7149
+ for (const entry of [...setupCards.values(), ...heightCards.values(), ...(state.workspaceUnitsQuestions?.values() || [])]) {
7150
+ if (entry.slotNode) delete entry.slotNode.dataset.armedAt;
7151
+ }
7152
+ paintDrawingQuestionSlot();
7153
+ const card = ui.approvalTray?.querySelector('.ai-chat-drawing-step.ai-chat-ask-card');
7154
+ if (card) card.dataset.reshown = 'true'; // no arrival pulse for a card brought back (kept across its repaints)
7155
+ if (card && !(card.lastDrawingField && focusHeightControl(card, card.lastDrawingField, null))) window.FlolessQuestionCard.focusCursor(card);
7156
+ }
7157
+ function paintDrawingHiddenLine(tray, showing, hidden) {
7158
+ const names = { height: 'Heights', setup: 'Read setup', units: 'Units' };
7159
+ const waiting = { height: 0, setup: 0, units: 0 };
7160
+ for (const { kind, entry } of hidden) waiting[kind] += drawingRows(kind, entry).filter((row) => drawingRowOpen(kind, entry, row)).length;
7161
+ const kinds = [...new Set(hidden.map(({ kind }) => kind))], reads = kinds.filter((kind) => kind !== 'units');
7162
+ const asked = reads.filter((kind) => waiting[kind]);
7163
+ const count = (n, kind) => (kind === 'setup' ? `${n} ${n === 1 ? 'question still needs' : 'questions still need'}` : `${n} ${n === 1 ? 'end still needs' : 'ends still need'}`);
7164
+ const sentence = [
7165
+ hidden.some(({ entry }) => entry.saveFailed) ? 'Your last answer did not save.' : '',
7166
+ !reads.length ? '' : !asked.length ? 'Answers recorded. Tell the read what to look at next.'
7167
+ : reads.length === 1 ? `${count(waiting[asked[0]], asked[0])} your answer.`
7168
+ : `${asked.map((kind) => `${names[kind]} (${waiting[kind]})`).join(' and ')} still ${asked.length === 1 && waiting[asked[0]] === 1 ? 'needs' : 'need'} your answer.`,
7169
+ kinds.includes('units') ? 'Choose the units AI uses here.' : '',
7170
+ hidden.some(({ entry }) => [...(entry.slotDrafts?.values() || [])].some((draft) => draft.rows[0].other.trim())) ? 'Your typing is kept.' : '',
7171
+ ].filter(Boolean).join(' ');
7172
+ const { entry } = hidden[0], key = `hidden/${entry.chatId}`;
7173
+ if (showing && showing.dataset.drawingStep !== key) showing.remove();
7174
+ drawingHiddenLine = paintHiddenLine(drawingHiddenLine, tray, {
7175
+ className: 'ai-chat-drawing-step', label: kinds.length === 1 ? names[kinds[0]] : 'The read', sentence,
7176
+ commandId: reads.length ? `shell.chat-drawing-show#${entry.questionId}` : 'shell.chat-card-show#units',
7177
+ instance: `the ${kinds.map((kind) => names[kind].toLowerCase()).join(' and ')} question${kinds.length > 1 ? 's' : ''}`,
7178
+ show: () => showDrawingByHand(entry.chatId),
7179
+ });
7180
+ drawingHiddenLine.dataset.drawingStep = key;
7181
+ return true;
7182
+ }
7183
+ /**
7184
+ * The one line a hidden card leaves above the message box (or, with no tray, in the conversation, where paintEvents
7185
+ * places it): what still waits, and Show. One button, so it is one tab stop and one Instructor carrier. Above the message
7186
+ * box it is rebuilt only when what it says changes, so a repaint keeps the focus on it; in the conversation the feed is
7187
+ * rebuilt on every paint, the same button is reused, and paintEvents puts the focus back on it.
7188
+ */
7189
+ function paintHiddenLine(node, tray, { className, label, sentence, commandId, instance, show, tip = '' }) {
7190
+ node ||= document.createElement('button');
7191
+ const sig = JSON.stringify([className, label, sentence, commandId, tip]);
7192
+ // A double click is one expand: its second click would land on the card's own chevron where the line was (#2678).
7193
+ node.onclick = (click) => { if (!(click?.detail > 1)) show(); };
7194
+ if (node.isConnected && node.dataset.sig === sig) return node;
7195
+ node.type = 'button'; node.className = `ai-chat-hidden-line ${className}`; node.dataset.sig = sig;
7196
+ node.dataset.commandId = commandId; node.dataset.commandInstanceLabel = instance;
7197
+ if (tip) node.dataset.tip = tip; else delete node.dataset.tip;
7198
+ node.setAttribute('aria-expanded', 'false');
7199
+ const chip = document.createElement('span'); chip.className = 'ai-chat-ask-chip'; chip.textContent = label;
7200
+ const text = document.createElement('span'); text.className = 'ai-chat-hidden-line-text'; text.textContent = sentence;
7201
+ // Owner, 2026-10-24: an icon, not the word Show: the chevron of a fold that is closed (the same glyph as the receipt fold).
7202
+ const more = document.createElement('span'); more.className = 'ai-chat-hidden-line-toggle'; more.textContent = '›';
7203
+ more.setAttribute('aria-hidden', 'true');
7204
+ node.replaceChildren(chip, text, more);
7205
+ if (!node.isConnected && tray) tray.append(node);
7206
+ return node;
7207
+ }
6272
7208
  function reopenDrawingItem(kind, entry, key) {
6273
7209
  const row = drawingRows(kind, entry).find((row) => drawingRowKey(kind, row) === key);
6274
7210
  if (entry.busy || !entry.view?.open || !row || row.frozen || row.status === 'superseded') return;
7211
+ showDrawingSlot(entry.chatId);
6275
7212
  entry.changing.add(key); entry.activeItem = key; entry.finishActive = false; entry.reopenedAt = (state.drawingActivationOrder = (state.drawingActivationOrder || 0) + 1);
6276
7213
  if (row.answer?.note && row.answer.how !== 'none') { const source = answerSource(`${kind === 'setup' ? 's' : 'h'}:${entry.questionId}:${key}`); source.open = true; source.note ||= row.answer.note; }
6277
7214
  entry.slotPhase = 'row';
@@ -6292,6 +7229,9 @@
6292
7229
  const allAnswered = live.length > 0 && answered.length === live.length;
6293
7230
  card.dataset.state = !entry.view ? (entry.finished ? 'closed' : 'loading') : !entry.view.open ? 'closed'
6294
7231
  : allAnswered ? (settled === live.length ? 'answered' : 'waiting-for-read') : 'open';
7232
+ // #2678: a hidden card's line says what still waits: the person's answers, or the read.
7233
+ const waits = { open: 'you', 'waiting-for-read': 'ai', answered: 'done', closed: 'done' }[card.dataset.state];
7234
+ if (waits) card.dataset.waits = waits;
6295
7235
  const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
6296
7236
  const heading = document.createElement('strong'); heading.textContent = title;
6297
7237
  const chip = document.createElement('span'); chip.className = 'ai-chat-filter-state'; chip.textContent = card.dataset.state;
@@ -6320,6 +7260,7 @@
6320
7260
  next.addEventListener('click', () => {
6321
7261
  if (entry.busy) return;
6322
7262
  for (const other of [...setupCards.values(), ...heightCards.values()]) other.finishActive = false;
7263
+ showDrawingSlot(entry.chatId);
6323
7264
  entry.finishActive = true; entry.reopenedAt = (state.drawingActivationOrder = (state.drawingActivationOrder || 0) + 1); drawingSlotRepaint();
6324
7265
  });
6325
7266
  card.append(next);
@@ -6357,12 +7298,31 @@
6357
7298
  label, instance: label, idFor, inherited: row?.inherited, busyReason: entry.busy ? 'An answer is still being saved — wait for it to finish' : null,
6358
7299
  allowPictureOnly: false, onDraftChange, alwaysOpen: Boolean(entry.slotDrafts?.get(entry.slotQuestionKey)?.rows[0]?.otherOpen) });
6359
7300
  }
7301
+ /**
7302
+ * The card's last step ("Tell the read what to look at next") has nothing left to do once a message saying so went to
7303
+ * the read after the card's last answer (owner, 2026-10-23: the card stayed while the AI was already working on it).
7304
+ * Only a message that was sent counts: an ordinary one, or a follow-up the chat accepted or queued. Changing an answer
7305
+ * after that brings the step back, since the read has not been told about the change. The message must name THIS card
7306
+ * ("the second read setup card"), so telling one card never ends another's step.
7307
+ * ponytail: matched on the card's current wording; a later card renames "the read setup card" to "the first …",
7308
+ * which brings the step back on the earlier card. Harmless: it only offers the message again.
7309
+ */
7310
+ function drawingFinishTold(kind, entry, live) {
7311
+ const told = (kind === 'setup' ? setupTellText(entry) : heightTellText(entry)).replace(/\.$/, '');
7312
+ const lastAnswer = Math.max(0, ...live.map((row) => Date.parse(row.answer?.answeredAt || '') || 0));
7313
+ return state.events.some((event) => event.type === 'user-message' && !event.payload?.source
7314
+ && (Date.parse(event.createdAt || '') || 0) > lastAnswer
7315
+ && (!(event.payload?.followup || event.payload?.deliveryState) || ['accepted', 'queued-next'].includes(followupDelivery(event)))
7316
+ && String(event.payload?.text || '').includes(told));
7317
+ }
7318
+
6360
7319
  function drawingStep(kind, entry) {
6361
7320
  const open = drawingRows(kind, entry).filter((row) => drawingRowOpen(kind, entry, row));
6362
7321
  const row = open.find((row) => drawingRowKey(kind, row) === entry.activeItem) || open[0];
6363
7322
  if (!row) {
6364
7323
  const live = drawingRows(kind, entry).filter((row) => row.status !== 'superseded');
6365
7324
  if (!entry.view?.open || !live.length || !live.every((row) => row.answer)) return null;
7325
+ if (drawingFinishTold(kind, entry, live)) return null;
6366
7326
  return { key: 'finish', question: { id: 'finish', header: kind === 'setup' ? 'Read setup' : 'Heights', question: 'Your answers are recorded. Tell the read what to look at next.', allowOther: false,
6367
7327
  hint: 'Tell the read puts a message in the box. Send to the read sends it now.',
6368
7328
  options: [{ shown: 'Tell the read', description: 'Put the message in the box so you can add to it' }, { shown: 'Send to the read', description: 'Send it now, keeping your words and files' }] },
@@ -6468,19 +7428,23 @@
6468
7428
  const tray = ui.approvalTray; if (!tray || !window.FlolessQuestionCard) return false;
6469
7429
  const showing = tray.querySelector('.ai-chat-drawing-step');
6470
7430
  const heldFocus = showing?.contains(document.activeElement) ? document.activeElement : null;
6471
- if (state.chat?.pendingApproval || tray.querySelector('.ai-chat-approval:not(.ai-chat-approval-scope):not(.ai-chat-drawing-step)')) { showing?.remove(); return false; }
7431
+ // A hidden approval or AI question still holds the slot (Codex review round 3): its line is not an .ai-chat-approval.
7432
+ if (state.chat?.pendingApproval || tray.querySelector('.ai-chat-approval:not(.ai-chat-approval-scope):not(.ai-chat-drawing-step), .ai-chat-approval-hidden')) { showing?.remove(); return false; }
6472
7433
  const entries = [...setupCards.values()].map((entry) => ({ kind: 'setup', entry })).concat([...heightCards.values()].map((entry) => ({ kind: 'height', entry })))
6473
7434
  .filter(({ entry }) => drawingEntryCurrent(entry) && entry.view?.open && !entry.reloadPending && !entry.loading)
6474
7435
  .sort((a, b) => ((b.entry.finishActive || b.entry.changing.has(b.entry.activeItem)) ? b.entry.reopenedAt || 0 : 0)
6475
7436
  - ((a.entry.finishActive || a.entry.changing.has(a.entry.activeItem)) ? a.entry.reopenedAt || 0 : 0) || a.entry.sequence - b.entry.sequence);
6476
- const candidates = entries.map(({ kind, entry }) => ({ kind, entry, step: drawingStep(kind, entry) })).filter(({ step }) => step);
6477
- const units = drawingUnitsCandidate(); if (units) candidates.push(units);
7437
+ const waiting = entries.map(({ kind, entry }) => ({ kind, entry, step: drawingStep(kind, entry) })).filter(({ step }) => step);
7438
+ const hidden = waiting.filter(({ entry }) => drawingCardHidden(entry));
7439
+ const candidates = waiting.filter((candidate) => !hidden.includes(candidate));
7440
+ const units = drawingUnitsCandidate(); if (units) (drawingCardHidden(units.entry) ? hidden : candidates).push(units);
6478
7441
  let chosen = candidates.find(({ entry, step }) => entry.finishActive && step.key === 'finish') || candidates.find(({ step }) => step.key !== 'finish') || candidates[0];
6479
7442
  if (heldFocus && personIsTyping()) {
6480
7443
  const current = candidates.find(({ entry, step }) => `${entry.chatId}/${entry.key}/${step.key}` === showing.dataset.drawingStep);
6481
7444
  const activated = chosen?.entry.finishActive || (chosen?.entry.reopenedAt || 0) > (current?.entry.reopenedAt || 0);
6482
7445
  if (current && !activated) chosen = current;
6483
7446
  }
7447
+ if (!chosen && hidden.length) return paintDrawingHiddenLine(tray, showing, hidden);
6484
7448
  if (!chosen) { showing?.remove(); return false; }
6485
7449
  const { kind, entry, step } = chosen, key = `${entry.chatId}/${entry.key}/${step.key}`;
6486
7450
  if (showing && showing.dataset.drawingStep !== key) showing.remove();
@@ -6520,6 +7484,9 @@
6520
7484
  removeFile: (file) => request(`/api/chat/answer-evidence/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(file.attachmentId)}`, { method: 'DELETE', body: JSON.stringify({ chatId: entry.chatId }) }) }, files),
6521
7485
  remove: (_index, file) => removeAnswerFile(step.scope, { requestId: entry.requestId, chatId: entry.chatId, repaint: drawingSlotRepaint }, file) } : null,
6522
7486
  carrier: (what, _index, extra) => drawingCarrier(kind, entry, step, draft, what, extra),
7487
+ hide: { run: () => hideDrawingByHand(entry.chatId), ...(kind === 'units'
7488
+ ? { carrier: { id: 'shell.chat-card-hide#units', instance: 'the units question' }, tip: 'Collapse for now. Nothing is chosen for you.' }
7489
+ : { carrier: { id: `shell.chat-drawing-hide#${entry.questionId}`, instance: kind === 'setup' ? 'the read setup' : `height question ${entry.view.n}` } }) },
6523
7490
  repaint: () => { entry.slotSig = null; drawingSlotRepaint(); }, commitStep: async (_index, answer) => { const saved = await step.commit(answer); entry.slotSig = null; return saved; },
6524
7491
  });
6525
7492
  entry.slotSig = sig;
@@ -6752,6 +7719,7 @@
6752
7719
 
6753
7720
  async function submitSetupAnswers(entry, answers, rowKey) {
6754
7721
  if (entry.busy) return false;
7722
+ const seenAtAnswer = drawingEntryCurrent(entry) ? drawingMessageIds() : null;
6755
7723
  const ownedSlot = drawingEntryCurrent(entry) && ui.approvalTray?.querySelector('.ai-chat-drawing-step')?.dataset.drawingStep;
6756
7724
  const ownedNode = ownedSlot ? ui.approvalTray.querySelector('.ai-chat-drawing-step') : null;
6757
7725
  const pendingFocusId = ownedNode?.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
@@ -6774,7 +7742,7 @@
6774
7742
  method: 'POST', body: JSON.stringify({ chatId: entry.chatId, answers: withSource }),
6775
7743
  });
6776
7744
  entry.view = result.question;
6777
- saved = true;
7745
+ saved = true; entry.saveFailed = false; if (seenAtAnswer) drawingMessagesSeen(entry.chatId, seenAtAnswer);
6778
7746
  for (const answer of answers) {
6779
7747
  entry.changing.delete(answer.key); entry.drafts.delete(answer.key); entry.drafts.delete(`${answer.key}\u0000none`);
6780
7748
  if (entry.activeItem === answer.key) { entry.activeItem = null; entry.reopenedAt = 0; }
@@ -6786,6 +7754,7 @@
6786
7754
  let message = heightErrorText(error, 'FloLess could not save this answer. Try again.');
6787
7755
  if (error?.code === 'setup-answer-off-grid') message = 'This point isn’t a crossing of two straight grid lines. Choose the matching numbered off-grid option above, check the straight-grid crossing it maps to, then press Confirm.';
6788
7756
  if (error?.code === 'answer-evidence-unknown') message = dropStaleAnswerFiles(answers.map((answer) => `s:${entry.questionId}:${answer.key}`), entry);
7757
+ entry.saveFailed = true;
6789
7758
  if (SETUP_STALE.has(error?.code)) { entry.cardError = message; entry.view = null; loadSetupQuestion(entry); }
6790
7759
  else if (rowKey) entry.rowErrors.set(rowKey, message);
6791
7760
  else entry.cardError = message;
@@ -7293,8 +8262,8 @@
7293
8262
 
7294
8263
  function updateOffscreenActivity() {
7295
8264
  const liveDots = ui.feed.querySelector('.ai-chat-live-status');
7296
- // Showing the badge claims a row below the feed. Require enough room for that row before
7297
- // showing it, otherwise ResizeObserver could alternate between show and hide in a short pane.
8265
+ // The badge sits over the bottom of the feed (chat.css), so showing it never resizes the feed. A feed too short to
8266
+ // hold it over its content does not show it; the higher bar to show than to keep stops it flickering at that size.
7298
8267
  const minimumFeedHeight = ui.offscreenActivity.hidden ? 88 : 48;
7299
8268
  ui.offscreenActivity.hidden = !turnIsVisiblyActive() || state.historyOpen || !liveDots
7300
8269
  || ui.feed.clientHeight < minimumFeedHeight
@@ -7322,7 +8291,13 @@
7322
8291
  ? document.activeElement?.dataset?.commandId : null;
7323
8292
  // A card painted once and reused across repaints (a connection suggestion, #1900) keeps its own control focused.
7324
8293
  const focusedNode = ui.feed.contains(document.activeElement) ? document.activeElement : null;
7325
- const nearBottom = ui.feed.scrollHeight - ui.feed.scrollTop - ui.feed.clientHeight < 56;
8294
+ const chipNode = focusedNode?.closest?.('.ai-chat-source');
8295
+ // #2678: a card in its shell (kept per card) that this repaint rebuilds keeps the keyboard: on the same control, else the card.
8296
+ const focusedShell = focusedNode?.closest?.('.ai-chat-feed-card') || null;
8297
+ const focusedLine = focusedNode?.matches?.('.ai-chat-feed > .ai-chat-feed-hidden') ? String(focusedNode.dataset.commandId || '').replace('shell.chat-feed-card-show#', '') : '';
8298
+ const focusedChip = chipNode ? { turnId: chipNode.dataset.turnId, anchor: chipNode.dataset.anchor, command: focusedNode.dataset?.commandId || '' } : null;
8299
+ if (options.forceBottom) state.feedLeftEnd = false; // the person just sent: the end is where they are going
8300
+ const nearBottom = !state.feedLeftEnd && ui.feed.scrollHeight - ui.feed.scrollTop - ui.feed.clientHeight < 56;
7326
8301
  const scrollTop = ui.feed.scrollTop;
7327
8302
  // #2163 / #2166: the rebuild below forgets two things only a detach loses: the caret of the field being typed in
7328
8303
  // and each card list's scroll position. A card that did not change is the very same node (see `cardSignature`),
@@ -7354,7 +8329,11 @@
7354
8329
  };
7355
8330
  const flushLinks = () => { if (links.length) { ui.feed.append(...receiptFold(links)); links = []; } };
7356
8331
  for (const event of state.events) {
7357
- if (links.length && event.turnId !== links[0].turnId) { flushAssistant(); flushLinks(); }
8332
+ // #2642/#2643: the person's assumption or chosen source is painted on its claim's chip; it never starts or ends an answer group (it has no turn).
8333
+ if (event.type === 'citation-assumption' || event.type === 'citation-choice') continue;
8334
+ // A follow-up can share its provider turn with the preceding answer. Its question still
8335
+ // starts a new visible answer group, after that answer's text and held receipts (#2505).
8336
+ if (event.type === 'user-message' || (links.length && event.turnId !== links[0].turnId)) { flushAssistant(); flushLinks(); }
7358
8337
  if (event.type === 'assistant-message' && event.payload?.delta) {
7359
8338
  // Codex keeps a stable item id while Claude's SDK may assign one per stream packet.
7360
8339
  // Same-turn deltas stay in one visible answer. Tools separate progress paragraphs;
@@ -7394,14 +8373,14 @@
7394
8373
  continue;
7395
8374
  }
7396
8375
  if (event.type === 'connection-proposal-update' || event.type === 'view-command-update') continue;
7397
- if (event.type === 'connection-proposal' || event.type === 'connection-check') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
8376
+ if (event.type === 'connection-proposal' || event.type === 'connection-check') { links.push({ turnId: event.turnId, node: feedCard(renderEvent(event), event) }); continue; }
7398
8377
  // #2046: the Guide's next-move cards are held under the answer they were suggested in, like the cards above.
7399
- if (event.type === 'next-move') { const node = renderEvent(event); if (node) links.push({ turnId: event.turnId, node }); continue; }
8378
+ if (event.type === 'next-move') { const node = feedCard(renderEvent(event), event); if (node) links.push({ turnId: event.turnId, node }); continue; }
7400
8379
  if (event.type === 'next-move-update') { renderEvent(event); continue; }
7401
8380
  // #2247: an action suggestion or an action the AI ran is held under the answer, like the cards above; an update
7402
8381
  // only changes its card (which reads it when it repaints).
7403
8382
  if (event.type === 'action-proposal-update') continue;
7404
- if (event.type === 'action-proposal' || event.type === 'action-call') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
8383
+ if (event.type === 'action-proposal' || event.type === 'action-call') { links.push({ turnId: event.turnId, node: feedCard(renderEvent(event), event) }); continue; }
7405
8384
  // #2255: a model view change is written mid-answer while the tool waits, so it is held under the answer too.
7406
8385
  if (event.type === 'view-command') { links.push({ turnId: event.turnId, node: renderEvent(event), event }); continue; }
7407
8386
  // #2437 / #2436: an answer's sources are held under it, like the receipts below; one row per answer.
@@ -7413,9 +8392,11 @@
7413
8392
  if (['tool', 'usage', 'attachment', 'compaction', 'state'].includes(event.type)) continue;
7414
8393
  // FloLess's own receipts (object links #1653; evidence looks and suggestion cards #1859) are written mid-answer while a tool runs:
7415
8394
  // held and shown under the answer, so they never cut one answer into fragments.
7416
- if (event.type === 'chat-subjects' || event.type === 'evidence-read' || event.type === 'filter-proposal') { links.push({ turnId: event.turnId, node: renderEvent(event), event }); continue; }
8395
+ if (event.type === 'chat-subjects' || event.type === 'evidence-read' || event.type === 'filter-proposal') { links.push({ turnId: event.turnId, node: feedCard(renderEvent(event), event), event }); continue; }
7417
8396
  flushAssistant();
7418
- const node = renderEvent(event);
8397
+ // #2678: a card comes in its shell, with its chevron, or as the one line it left (an ordinary message or a one-line row comes
8398
+ // as it is).
8399
+ const node = feedCard(renderEvent(event), event);
7419
8400
  if (node) ui.feed.append(node);
7420
8401
  }
7421
8402
  flushAssistant();
@@ -7432,7 +8413,28 @@
7432
8413
  if (focusedNode?.isConnected && ui.feed.contains(focusedNode)) {
7433
8414
  if (document.activeElement !== focusedNode) focusedNode.focus({ preventScroll: true });
7434
8415
  refocused = focusedNode;
8416
+ } else if (focusedChip) {
8417
+ // #2642: a source chip is rebuilt on every repaint; the keyboard stays on the same claim's chip, on the same button
8418
+ // when it is still there (a recorded assumption leaves "Ask for the source", never a jump to the top of the feed).
8419
+ const chip = [...ui.feed.querySelectorAll('.ai-chat-source')].find((node) => node.dataset.turnId === focusedChip.turnId && node.dataset.anchor === focusedChip.anchor);
8420
+ refocused = [...(chip?.querySelectorAll('button') ?? [])].find((control) => control.dataset.commandId === focusedChip.command) ?? chip?.querySelector('button') ?? null;
8421
+ refocused?.focus({ preventScroll: true });
8422
+ } else if (focusedShell?.isConnected && ui.feed.contains(focusedShell) && focusedShell.firstElementChild !== focusedShell.hideButton) {
8423
+ refocused = focusFeedCard(focusedShell.firstElementChild, focusedCommand);
8424
+ } else if (focusedLine && feedCardShells.get(focusedLine)?.isConnected) {
8425
+ // #2678: the line had the keyboard and its card is back (a message that folded it was not sent): the card takes it.
8426
+ refocused = focusFeedCard(feedCardShells.get(focusedLine).firstElementChild);
8427
+ } else if (focusedShell && feedCardLines.get(focusedShell.feedCardId)?.isConnected) {
8428
+ // #2678: the card folded by itself (answered) under the keyboard: the keyboard stays with it, on its line.
8429
+ refocused = feedCardLines.get(focusedShell.feedCardId);
8430
+ refocused.focus({ preventScroll: true });
7435
8431
  } else refocused = restoreFeedFocus(focusedCommand);
8432
+ // #2643: an open "Choose a source…" list lives outside the feed, so a repaint keeps it (and what is typed in it); it
8433
+ // follows its claim's rebuilt chip, and closes with its conversation.
8434
+ if (state.sourcePicker) {
8435
+ if (state.sourcePicker.chatId !== state.chat?.chatId) closeSourcePicker(false);
8436
+ else placeSourcePicker(state.sourcePicker);
8437
+ }
7436
8438
  if (refocused && caret) {
7437
8439
  try { refocused.setSelectionRange(caret.start, caret.end, caret.direction); } catch { /* no caret on this control */ }
7438
8440
  }
@@ -7441,11 +8443,14 @@
7441
8443
  if (typeof list.keptScrollLeft === 'number' && list.scrollLeft !== list.keptScrollLeft) list.scrollLeft = list.keptScrollLeft;
7442
8444
  }
7443
8445
  // Removing a focused control makes the browser lay out the half-built feed, which clamps its scroll near the top.
7444
- // Scrolled up, the reader stays where they were.
8446
+ // Scrolled up, the reader stays where they were. At the end, they are put back there now, before any scroll event
8447
+ // can read that clamp as the reader moving up (keepFeedFollowing); the frame below settles late layout.
7445
8448
  if (!nearBottom) ui.feed.scrollTop = scrollTop;
8449
+ else if (!state.answerJump) ui.feed.scrollTop = ui.feed.scrollHeight;
7446
8450
  restoreAnswerJump();
7447
8451
  updateOffscreenActivity();
7448
8452
  if (!state.answerJump && (nearBottom || options.forceBottom)) requestAnimationFrame(() => {
8453
+ if (state.feedLeftEnd || state.answerJump) return; // the reader moved up, or another conversation jumped to an answer
7449
8454
  ui.feed.scrollTop = ui.feed.scrollHeight;
7450
8455
  // A control that kept keyboard focus across the repaint (the questions card sits above the answer) stays in sight.
7451
8456
  if (ui.feed.contains(document.activeElement)) document.activeElement.scrollIntoView({ block: 'nearest' });
@@ -7535,10 +8540,66 @@
7535
8540
  return signIn;
7536
8541
  }
7537
8542
 
8543
+ /*
8544
+ * Owner, 2026-10-23: "Any card should have that functionality". An approval, a proposal or the AI's own question above the
8545
+ * message box hides to one line by hand (× or Esc), like a drawing read's card. Hiding answers, allows or denies nothing:
8546
+ * the AI keeps waiting, the chat keeps its "approval needed" mark, and the line says what waits. A reload shows it again.
8547
+ * ponytail: ids of settled approvals stay in the set; harmless, an id is never reused.
8548
+ */
8549
+ const hiddenApprovals = new Set();
8550
+ let approvalHiddenLine = null;
8551
+ function hideApprovalByHand(approvalId) {
8552
+ hiddenApprovals.add(approvalId);
8553
+ paintApproval();
8554
+ approvalHiddenLine?.focus({ preventScroll: true });
8555
+ }
8556
+ function showApprovalByHand(approvalId) {
8557
+ hiddenApprovals.delete(approvalId);
8558
+ paintApproval();
8559
+ const card = [...ui.approvalTray.querySelectorAll('.ai-chat-approval')].find((node) => node.dataset.approvalId === approvalId);
8560
+ if (card) card.dataset.reshown = 'true'; // its arrival pulse is for a card that is new, not one brought back
8561
+ // A question card puts focus on its recommended answer itself; a decision starts on Deny, the safe default.
8562
+ if (card && !card.contains(document.activeElement)) {
8563
+ (card.querySelector('[data-command-id="shell.chat-approval-deny"]') || card.querySelector('button:not(.ai-chat-card-hide)'))?.focus({ preventScroll: true });
8564
+ }
8565
+ }
8566
+ function paintApprovalHiddenLine(approval, existing) {
8567
+ if (existing && existing !== approvalHiddenLine) existing.remove();
8568
+ const question = approval.kind === 'question' || approval.async;
8569
+ const draft = questionDrafts.get(approval.approvalId)?.draft;
8570
+ const asked = approval.question?.questions?.[draft?.step || 0] || approval.question?.questions?.[0];
8571
+ // An async question is answered by the person's next message, so the line says what it asks (UX review), cut at a word.
8572
+ const words = String(asked?.question || '');
8573
+ const quoted = words.length > 90 ? `${words.slice(0, 90).replace(/\s+\S*$/, '')}…` : words;
8574
+ approvalHiddenLine = paintHiddenLine(approvalHiddenLine, ui.approvalTray, {
8575
+ className: `ai-chat-approval-hidden${question ? '' : ' is-decision'}`, label: question ? asked?.header || 'Question' : 'Approval',
8576
+ sentence: [approval.async ? `The AI asked “${quoted}”${/[.?!…]$/.test(quoted) ? '' : '.'} Your next message answers it.`
8577
+ : question ? 'The AI is waiting for your answer.' : 'The AI is waiting for your decision.',
8578
+ draft?.rows.some((row) => row.choices.length || row.other.trim()) ? 'What you chose or typed is kept.' : ''].filter(Boolean).join(' '),
8579
+ commandId: `shell.chat-card-show#${approval.approvalId}`, instance: question ? 'the AI’s question' : 'the approval',
8580
+ tip: approval.async && quoted !== words ? words : '', show: () => showApprovalByHand(approval.approvalId),
8581
+ });
8582
+ }
8583
+ /** The × on an approval or proposal card, and Esc anywhere inside it. */
8584
+ function approvalHideControl(card, approval) {
8585
+ const hide = button('›', `shell.chat-card-hide#${approval.approvalId}`, 'ai-chat-card-hide');
8586
+ hide.dataset.commandInstanceLabel = 'the approval';
8587
+ hide.setAttribute('aria-label', 'Collapse this approval for now');
8588
+ hide.dataset.tip = 'Collapse for now. The AI keeps waiting for your decision.';
8589
+ hide.addEventListener('click', () => hideApprovalByHand(approval.approvalId));
8590
+ card.addEventListener('keydown', (event) => {
8591
+ if (!window.FlolessQuestionCard?.escapeHides(event)) return;
8592
+ event.preventDefault(); event.stopPropagation(); hideApprovalByHand(approval.approvalId);
8593
+ });
8594
+ card.append(hide);
8595
+ }
8596
+
7538
8597
  function paintApproval() {
7539
8598
  clearSettledQuestionDrafts(state.events, state.chat);
7540
8599
  paintApprovalScope();
7541
- const existing = shell.querySelector('.ai-chat-approval:not(.ai-chat-approval-scope)');
8600
+ // A hidden drawing question's one line holds the slot like its card does, so an approval or question replaces it too.
8601
+ // Only the tray's own line: a card hidden in the conversation leaves one too (#2678), and it is not this slot's.
8602
+ const existing = shell.querySelector('.ai-chat-approval:not(.ai-chat-approval-scope), .ai-chat-approval-tray > .ai-chat-hidden-line');
7542
8603
  const approval = state.chat?.pendingApproval;
7543
8604
  const deciding = Boolean(approval && state.decidingApprovalIds.has(approval.approvalId));
7544
8605
  shell.dataset.approvalPending = String(Boolean(approval) && !deciding);
@@ -7547,6 +8608,8 @@
7547
8608
  const asking = approval ? null : openAsyncQuestion(state.events, state.chat);
7548
8609
  if (asking) shell.dataset.approvalPending = 'true';
7549
8610
  document.dispatchEvent(new CustomEvent('floless:chat-indicator'));
8611
+ const waiting = asking || (approval && !deciding ? approval : null);
8612
+ if (waiting && hiddenApprovals.has(waiting.approvalId)) { paintApprovalHiddenLine(waiting, existing); return; }
7550
8613
  if (asking && window.FlolessQuestionCard) {
7551
8614
  if (existing?.dataset.approvalId === asking.approvalId && existing.classList.contains('ai-chat-ask-card')) return;
7552
8615
  existing?.remove();
@@ -7590,6 +8653,7 @@
7590
8653
  card.classList.add('has-flo'); card.append(flo);
7591
8654
  floAvatar(flo, { size: 28, mood: 'yourcall', hat: true });
7592
8655
  }
8656
+ approvalHideControl(card, approval);
7593
8657
  card.dataset.allowanceRevision = allowanceRevision;
7594
8658
  // #1890 PR 3a: the AI asking to create a workflow, with where it would go.
7595
8659
  const create = approval.create && typeof approval.create === 'object' ? approval.create : null;
@@ -7613,7 +8677,7 @@
7613
8677
  const allow = button(scope.allowsFileChanges ? readOnly ? 'Add scope for later file changes' : 'Add scope and allow file changes' : 'Approve once', 'shell.chat-scope-add-approve', 'allow');
7614
8678
  deny.addEventListener('click', () => decideApproval('deny'));
7615
8679
  allow.addEventListener('click', () => decideApproval('allow'));
7616
- actions.append(deny, allow); card.append(heading, copy, actions, ...widerChoices(approval, offer));
8680
+ actions.append(deny, allow); card.append(heading, copy, actions, ...widerChoices(approval, offer, actions));
7617
8681
  ui.approvalTray.append(card);
7618
8682
  if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
7619
8683
  ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
@@ -7684,7 +8748,7 @@
7684
8748
  block.append(code);
7685
8749
  nodes.push(block);
7686
8750
  }
7687
- card.append(...nodes, actions, ...widerChoices(approval, offer));
8751
+ card.append(...nodes, actions, ...widerChoices(approval, offer, actions));
7688
8752
  ui.approvalTray.append(card);
7689
8753
  if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
7690
8754
  // When a request-wide grant notice is also present, keep the decision nearest the composer.
@@ -7779,6 +8843,8 @@
7779
8843
  files: approval.async ? null : questionFiles(approval),
7780
8844
  ...(approval.async ? { otherHint: 'Type your own answer, or write it in the message box below to attach a file' } : {}),
7781
8845
  repaint: () => paintQuestionCard(approval, card),
8846
+ hide: { run: () => hideApprovalByHand(approval.approvalId), carrier: { id: `shell.chat-card-hide#${approval.approvalId}`, instance: 'the AI’s question' },
8847
+ tip: approval.async ? 'Collapse for now. Your typing is kept.' : 'Collapse for now. The AI keeps waiting, and your typing is kept.' },
7782
8848
  submit: () => { void (approval.async ? submitAsyncQuestion(approval) : submitQuestion(approval)); },
7783
8849
  });
7784
8850
  const target = refocus ? [...card.querySelectorAll('[data-command-id]')].find((node) => node.dataset.commandId === refocus) : null;
@@ -8045,7 +9111,7 @@
8045
9111
  }
8046
9112
  // Deny and Approve once already answer through paintApproval's own listeners.
8047
9113
  actions.append(deny, allow);
8048
- const nodes = [heading, copy, ...extra, actions, ...widerChoices(approval, offer)];
9114
+ const nodes = [heading, copy, ...extra, actions, ...widerChoices(approval, offer, actions)];
8049
9115
  card.append(...nodes);
8050
9116
  }
8051
9117
 
@@ -8110,7 +9176,7 @@
8110
9176
  deny.addEventListener('click', () => decideApproval('deny'));
8111
9177
  allow.addEventListener('click', () => decideApproval('allow'));
8112
9178
  actions.append(deny, allow);
8113
- card.append(heading, copy, ...(change.owners?.length ? [changeOwnerList(change)] : []), actions, ...widerChoices(approval, offer));
9179
+ card.append(heading, copy, ...(change.owners?.length ? [changeOwnerList(change)] : []), actions, ...widerChoices(approval, offer, actions));
8114
9180
  }
8115
9181
 
8116
9182
  /** Why a workflow the AI asked to create can only be dismissed (#1890 PR 3a); the server says the same to the AI. */
@@ -8182,7 +9248,7 @@
8182
9248
  deny.addEventListener('click', () => decideApproval('deny'));
8183
9249
  allow.addEventListener('click', () => decideApproval('allow'));
8184
9250
  actions.append(deny, allow);
8185
- card.append(heading, copy, list, actions, ...widerChoices(approval, offer));
9251
+ card.append(heading, copy, list, actions, ...widerChoices(approval, offer, actions));
8186
9252
  }
8187
9253
 
8188
9254
  /** Each project or workflow the change touches, with up to five of its files. */
@@ -8312,21 +9378,13 @@
8312
9378
  }
8313
9379
 
8314
9380
  /**
8315
- * The two wider choices, each as one row: the button and, beside or under it, a line that says exactly what it covers.
8316
- * The line is visible text (not a tooltip alone), and the button is described by it. Returns [] when the card can only
8317
- * be denied.
9381
+ * The two wider choices join the card's one row of buttons, after Deny and Approve once (owner, 2026-10-23: "all button
9382
+ * should be inlined, move the text explanation to tooltip"). What each one covers is its themed tooltip, and a hidden
9383
+ * line the button is described by reads it to screen readers. Returns what still needs a line of its own: the warning
9384
+ * that a choice covers more than this one call.
8318
9385
  */
8319
- function widerChoices(approval, offer) {
9386
+ function widerChoices(approval, offer, actions) {
8320
9387
  if (!offer) return [];
8321
- const group = document.createElement('div');
8322
- group.className = 'ai-chat-approval-wide';
8323
- group.setAttribute('role', 'group');
8324
- const caption = document.createElement('span');
8325
- caption.className = 'ai-chat-approval-wide-caption';
8326
- caption.id = `chat-approval-wide-caption-${approval.approvalId}`;
8327
- caption.textContent = 'Or allow more than this one action';
8328
- group.setAttribute('aria-labelledby', caption.id);
8329
- group.append(caption);
8330
9388
  const rows = [
8331
9389
  { which: 'request', label: 'Approve for this request', decision: 'allow-request', revision: offer.requestRevision, commandId: 'shell.chat-approval-request',
8332
9390
  text: `${offer.what}, until this reply ends.` },
@@ -8334,27 +9392,22 @@
8334
9392
  text: `${offer.conversationWhat || offer.what}${offer.conversationExtra || ''}, for the rest of this conversation, until you revoke it above the message box.` },
8335
9393
  ];
8336
9394
  for (const row of rows) {
8337
- const line = document.createElement('div');
8338
- line.className = 'ai-chat-approval-wide-row';
8339
9395
  const choice = button(row.label, row.commandId);
8340
9396
  if (offer.instance && row.which === 'conversation') choice.dataset.commandInstanceLabel = offer.instance;
8341
9397
  const covers = document.createElement('span');
8342
- covers.className = 'ai-chat-approval-covers';
9398
+ covers.className = 'ai-chat-approval-covers sr-only';
8343
9399
  covers.id = `chat-approval-covers-${row.which}-${approval.approvalId}`;
8344
9400
  covers.textContent = `${row.text}${offer.protectedNote || ''}`;
8345
9401
  choice.dataset.tip = covers.textContent;
8346
9402
  choice.setAttribute('aria-describedby', covers.id);
8347
9403
  choice.addEventListener('click', () => decideApproval(row.decision, row.revision));
8348
- line.append(choice, covers);
8349
- group.append(line);
9404
+ actions.append(choice, covers);
8350
9405
  }
8351
- if (offer.warning) {
8352
- const warning = document.createElement('p');
8353
- warning.className = 'ai-chat-approval-warning';
8354
- warning.textContent = offer.warning;
8355
- group.append(warning);
8356
- }
8357
- return [group];
9406
+ if (!offer.warning) return [];
9407
+ const warning = document.createElement('p');
9408
+ warning.className = 'ai-chat-approval-warning';
9409
+ warning.textContent = offer.warning;
9410
+ return [warning];
8358
9411
  }
8359
9412
 
8360
9413
  function approvalIsExplicitOnly(approval) {
@@ -9235,7 +10288,7 @@
9235
10288
  ui.permission.querySelector('strong').textContent = instructorChat ? 'No tools' : permissionLabel(chat?.settings.permissionProfile);
9236
10289
  ui.permission.dataset.tip = instructorChat
9237
10290
  ? 'This chat answers an Instructor question, so the AI can’t read files, run commands, search the web or use your connectors. Choose an Access to turn it into an ordinary chat. FloLess asks first.'
9238
- : permissionTip(chat?.settings.permissionProfile);
10291
+ : accessTip(chat);
9239
10292
  // #2234: the Guide's Access is chosen like any conversation's (it starts Read only). Its own controls — the morning
9240
10293
  // briefing, set-aside suggestions, Turn off and Delete history — keep their cell, shown only in a Guide conversation.
9241
10294
  const guideChat = chat?.initiator?.kind === 'guide';
@@ -9249,9 +10302,10 @@
9249
10302
  : 'Not using one';
9250
10303
  const frozen = !chat || Boolean(chat.activeTurn) || !state.capability?.available;
9251
10304
  // #2336: Access and the connectors switch do not depend on the provider's model list, so a provider check that failed
9252
- // or is slow never locks them (only a running reply does). Model and effort need the list.
10305
+ // or is slow never locks them. Model and effort need the list. #2651: Access can change during a reply too (it applies
10306
+ // from the next message); the connectors switch still waits for the reply.
9253
10307
  const settled = !chat || Boolean(chat.activeTurn);
9254
- ui.model.disabled = frozen; ui.effort.disabled = frozen; ui.permission.disabled = settled;
10308
+ ui.model.disabled = frozen; ui.effort.disabled = frozen; ui.permission.disabled = !chat;
9255
10309
  ui.integrations.disabled = frozen || Boolean(chat?.nativeSessionId) || instructorChat;
9256
10310
  const integrationBlocked = instructorChat
9257
10311
  ? 'An Instructor answer uses no tools, so it cannot use a connected account. Start a new chat to use one.'
@@ -9365,7 +10419,6 @@
9365
10419
  ui.stop.hidden = !active || Boolean(chat.activeTurn?.local);
9366
10420
  ui.send.hidden = false;
9367
10421
  paintSettings(); paintRecovery(); paintApproval(); paintRuntime(); paintAttachments(); paintEvents(); paintHistory(); updateSendState();
9368
- applyPendingSettings();
9369
10422
  }
9370
10423
 
9371
10424
  function draftForChat(chat) {
@@ -9691,6 +10744,7 @@
9691
10744
  clearLiveStream(true);
9692
10745
  state.chat = null; state.events = []; state.capability = null; state.desktop = null;
9693
10746
  state.attachments = []; state.followupUnknownId = null; state.integrations = null;
10747
+ state.feedLeftEnd = false; // the feed is rebuilt from nothing: a conversation, re-opened or not, opens at its end
9694
10748
  updateOffscreenActivity();
9695
10749
  // The header switches to the next conversation now; the previous provider's setup card and composer
9696
10750
  // hint must not stay under it while that conversation opens.
@@ -9847,7 +10901,9 @@
9847
10901
  }
9848
10902
 
9849
10903
  async function applyProviderDefaults(chatId) {
9850
- if (!state.chat || state.chat.chatId !== chatId || state.chat.nativeSessionId || !state.capability?.available) return;
10904
+ // #2651: not while a reply runs: the model and effort change only between replies, and that reply starts the provider
10905
+ // session on its own default anyway.
10906
+ if (!state.chat || state.chat.chatId !== chatId || state.chat.nativeSessionId || state.chat.activeTurn || !state.capability?.available) return;
9851
10907
  const defaults = preferredSettings(state.chat.provider, state.capability);
9852
10908
  if (!defaults?.model) return;
9853
10909
  const patch = {};
@@ -9947,11 +11003,19 @@
9947
11003
 
9948
11004
  // The units question of a workspace conversation (#1890): asked until the person answers, then a quiet line to change
9949
11005
  // it. Never blocks Send — an unanswered question tells the AI the units are not chosen yet, and it asks.
11006
+ // The units menu's open state and its outside-click listener belong to the chip they were made for: a repaint that
11007
+ // replaces the chip drops both, so a menu never comes back open without a way to close it.
11008
+ function dropUnitsMenu() {
11009
+ if (state.workspaceUnitsMenuAway) document.removeEventListener('pointerdown', state.workspaceUnitsMenuAway, true);
11010
+ state.workspaceUnitsMenuAway = null;
11011
+ state.workspaceUnitsMenuOpen = false;
11012
+ }
11013
+
9950
11014
  function paintWorkspaceUnits() {
9951
11015
  const host = ui.workspaceUnits;
9952
11016
  if (!host) return;
9953
11017
  const chat = state.chat;
9954
- if (state.scope?.owner?.kind !== 'workspace' || !chat || chat.archivedAt) { host.hidden = true; host.replaceChildren(); delete host.dataset.painted; return; }
11018
+ if (state.scope?.owner?.kind !== 'workspace' || !chat || chat.archivedAt) { dropUnitsMenu(); host.hidden = true; host.replaceChildren(); delete host.dataset.painted; return; }
9955
11019
  // The receipts' units follow the conversation's own (chosen, else suggested) — set here, where the chat is known.
9956
11020
  state.displayUnits = workspaceUnitsOf(chat);
9957
11021
  const units = chat.workspaceUnits || {};
@@ -9962,23 +11026,77 @@
9962
11026
  if (host.dataset.painted === painted) return;
9963
11027
  host.dataset.painted = painted;
9964
11028
  host.hidden = false;
11029
+ dropUnitsMenu();
9965
11030
  host.replaceChildren();
9966
11031
  if (chosen && !state.workspaceUnitsEditing) {
9967
- const text = document.createElement('span');
9968
- text.className = 'ai-chat-units-current';
9969
- text.textContent = `Units: ${label(chosen)}`;
9970
- const change = document.createElement('button');
9971
- change.type = 'button';
9972
- change.className = 'ai-chat-units-change';
9973
- change.textContent = 'Change';
9974
- change.setAttribute('aria-label', 'Change units');
9975
- change.dataset.commandId = 'shell.chat-units-change';
9976
- change.dataset.tip = 'Choose the units AI answers in, in this conversation';
9977
- change.addEventListener('click', () => { state.workspaceUnitsEditing = true; paintWorkspaceUnits();
9978
- const entry = state.workspaceUnitsQuestions?.get(chat.chatId);
9979
- if (entry?.slotNode?.isConnected) window.FlolessQuestionCard.focusCursor(entry.slotNode);
11032
+ // A toolbar chip ("ft-in ⌄"), whose two-item menu changes the units in place.
11033
+ const chip = document.createElement('button');
11034
+ chip.type = 'button';
11035
+ chip.className = 'ai-chat-units-chip ai-chat-units-change';
11036
+ chip.setAttribute('aria-label', `Units: ${label(chosen)}. Change units`);
11037
+ chip.setAttribute('aria-haspopup', 'menu');
11038
+ chip.setAttribute('aria-expanded', String(Boolean(state.workspaceUnitsMenuOpen)));
11039
+ chip.setAttribute('aria-controls', 'chat-units-menu');
11040
+ chip.dataset.commandId = 'shell.chat-units-change';
11041
+ chip.dataset.tip = `Units: ${label(chosen)}. Choose the units AI answers in, in this conversation`;
11042
+ chip.insertAdjacentHTML('afterbegin', '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M21.3 15.3a2.4 2.4 0 0 1 0 3.4l-2.6 2.6a2.4 2.4 0 0 1-3.4 0L2.7 8.7a2.41 2.41 0 0 1 0-3.4l2.6-2.6a2.41 2.41 0 0 1 3.4 0Z"/><path d="m14.5 12.5 2-2"/><path d="m11.5 9.5 2-2"/><path d="m8.5 6.5 2-2"/><path d="m17.5 15.5 2-2"/></svg>');
11043
+ const value = document.createElement('span');
11044
+ value.textContent = chosen === 'mm' ? 'mm' : 'ft-in';
11045
+ const chevron = document.createElement('span');
11046
+ chevron.className = 'ai-chat-access-chevron';
11047
+ chevron.setAttribute('aria-hidden', 'true');
11048
+ chevron.textContent = '⌄';
11049
+ chip.append(value, chevron);
11050
+ const menu = document.createElement('div');
11051
+ menu.className = 'ai-chat-units-menu';
11052
+ menu.id = 'chat-units-menu';
11053
+ menu.setAttribute('role', 'menu');
11054
+ menu.setAttribute('aria-label', 'Units');
11055
+ menu.hidden = !state.workspaceUnitsMenuOpen;
11056
+ const closeMenu = (focusChip) => {
11057
+ dropUnitsMenu();
11058
+ menu.hidden = true;
11059
+ chip.setAttribute('aria-expanded', 'false');
11060
+ if (focusChip) chip.focus();
11061
+ };
11062
+ for (const option of ['ft-in', 'mm']) {
11063
+ const item = document.createElement('button');
11064
+ item.type = 'button';
11065
+ item.setAttribute('role', 'menuitemradio');
11066
+ item.setAttribute('aria-checked', String(option === chosen));
11067
+ item.dataset.commandId = `shell.chat-units-choose#${option}`;
11068
+ item.dataset.commandInstanceLabel = option === 'mm' ? 'metric (mm)' : 'feet and inches';
11069
+ item.textContent = option === 'mm' ? 'Metric (mm)' : 'Feet and inches (ft-in)';
11070
+ item.addEventListener('click', () => { closeMenu(false); if (option !== chosen) void chooseWorkspaceUnits(option); else chip.focus(); });
11071
+ menu.append(item);
11072
+ }
11073
+ // Escape closes it from the chip or the menu; focus leaving both (Tab away) closes it too.
11074
+ chip.addEventListener('keydown', (event) => {
11075
+ if (event.key === 'Escape' && state.workspaceUnitsMenuOpen) { event.preventDefault(); closeMenu(true); }
11076
+ });
11077
+ // On the chip and menu (rebuilt each paint), never the long-lived host, so listeners never pile up.
11078
+ const leave = (event) => { if (state.workspaceUnitsMenuOpen && !chip.contains(event.relatedTarget) && !menu.contains(event.relatedTarget)) closeMenu(false); };
11079
+ chip.addEventListener('focusout', leave);
11080
+ menu.addEventListener('focusout', leave);
11081
+ menu.addEventListener('keydown', (event) => {
11082
+ const items = [...menu.querySelectorAll('button')];
11083
+ const at = items.indexOf(document.activeElement);
11084
+ if (event.key === 'Escape') { event.preventDefault(); closeMenu(true); }
11085
+ else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
11086
+ event.preventDefault();
11087
+ items[(at + (event.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length]?.focus();
11088
+ }
11089
+ });
11090
+ chip.addEventListener('click', () => {
11091
+ if (state.workspaceUnitsMenuOpen) { closeMenu(false); return; }
11092
+ state.workspaceUnitsMenuOpen = true;
11093
+ menu.hidden = false;
11094
+ chip.setAttribute('aria-expanded', 'true');
11095
+ state.workspaceUnitsMenuAway = (event) => { if (!host.contains(event.target)) closeMenu(false); };
11096
+ document.addEventListener('pointerdown', state.workspaceUnitsMenuAway, true);
11097
+ (menu.querySelector('[aria-checked="true"]') || menu.querySelector('button'))?.focus();
9980
11098
  });
9981
- host.append(text, change);
11099
+ host.append(chip, menu);
9982
11100
  return;
9983
11101
  }
9984
11102
  host.hidden = true;
@@ -10236,6 +11354,7 @@
10236
11354
  + (connectors
10237
11355
  ? `If you turn on your ${provider} connectors, it becomes an ordinary chat, and its next replies can use the tools its Access allows as well as your connectors (each call still asks you first).`
10238
11356
  : `If you change Access to ${chosen}, it becomes an ordinary chat, and its next replies can use the tools ${chosen} allows.`)
11357
+ + (state.chat?.activeTurn ? ' The reply that is running now stays on No tools.' : '')
10239
11358
  + ' Earlier answers stay as they were. You can’t switch it back to no tools: ask the Instructor again for that.';
10240
11359
  go.textContent = connectors ? 'Turn on connectors' : `Change to ${chosen}`;
10241
11360
  const done = (value) => {
@@ -10271,21 +11390,24 @@
10271
11390
  // #2059: giving an Instructor answer tools asks first; the server refuses it without this confirmation.
10272
11391
  let release = false;
10273
11392
  if (widensInstructorAnswer(patch)) {
10274
- // A confirmed change that had to wait for a running reply (#2336) was confirmed already: it is not asked again.
10275
- if (!options.releaseConfirmed && !await confirmInstructorRelease(patch)) return;
11393
+ if (!await confirmInstructorRelease(patch)) return;
10276
11394
  if (!sameChat(snapshot)) return;
10277
11395
  // The settings may have moved on while the question was open: apply the choice to what is current now.
10278
11396
  snapshot = captureChat();
10279
11397
  if (!snapshot) return;
10280
11398
  release = true;
10281
11399
  }
10282
- const settings = { ...state.chat.settings, ...patch };
11400
+ // #2651: a pick sends only what it changes; the server keeps the rest as it is NOW. This page's copy may be older: an
11401
+ // Access it carried back could undo a change made meanwhile (in another window, or by the AI's own card), and a model
11402
+ // it carried back would be a model change, which waits for a running reply.
11403
+ const settings = { ...patch };
10283
11404
  if ('model' in patch && !('effort' in patch)) settings.effort = null;
10284
11405
  // A model the runtime stopped listing (an update renamed it) is saved as the row the picker shows for it, the one
10285
- // running the same model where there is one (coveringModel), so changing Effort or Access is never refused.
11406
+ // running the same model where there is one (coveringModel), so changing Effort is never refused.
10286
11407
  // Only against a list the provider actually returned: an empty one (the check failed) proves nothing about the model.
10287
- if (!('model' in patch) && settings.model && state.capability?.available && state.capability.models.length
10288
- && !state.capability.models.some((model) => model.id === settings.model)) {
11408
+ const stored = state.chat.settings.model;
11409
+ if ('effort' in patch && !('model' in patch) && stored && state.capability?.available && state.capability.models.length
11410
+ && !state.capability.models.some((model) => model.id === stored)) {
10289
11411
  const shown = selectedModel();
10290
11412
  settings.model = shown?.id ?? null;
10291
11413
  if (!shown?.efforts?.includes(settings.effort)) settings.effort = null;
@@ -10297,34 +11419,22 @@
10297
11419
  if (!sameChat(snapshot)) return;
10298
11420
  state.chat = chat;
10299
11421
  paintConversation();
11422
+ // #2651: said once, here, never from a repaint. Decided by the saved record: a reply that ended meanwhile has no "next".
11423
+ const accessSaid = 'permissionProfile' in patch
11424
+ ? `Access changed to ${permissionLabel(chat.settings.permissionProfile)}.${chat.activeTurn ? ' It applies from your next message.' : ''}` : '';
10300
11425
  if (release) {
10301
11426
  announce(patch.useOwnConnectors === true && !('permissionProfile' in patch)
10302
- ? 'Connectors on. This is now an ordinary chat.' : `Access changed to ${permissionLabel(chat.settings.permissionProfile)}. This is now an ordinary chat.`);
11427
+ ? 'Connectors on. This is now an ordinary chat.' : `${accessSaid} This is now an ordinary chat.`);
10303
11428
  // The transcript line the server wrote is shown now, not on the next poll.
10304
11429
  void refreshConversation(snapshot.chatId, false);
10305
- } else if (options.announce !== false) announce('Chat settings updated.');
11430
+ } else if (options.announce !== false) announce(accessSaid || 'Chat settings updated.');
10306
11431
  } catch (error) {
10307
11432
  if (!sameChat(snapshot)) return;
10308
- // #2336: a reply is still running, so the change cannot be stored yet. Nothing is refused: say so, keep the control on
10309
- // the level that is really in force, and apply the choice by itself the moment the reply finishes (paintConversation).
10310
- if (error?.code === 'chat-turn-active') {
10311
- const earlier = state.pendingSettings?.chatId === snapshot.chatId ? state.pendingSettings : null;
10312
- state.pendingSettings = { chatId: snapshot.chatId, patch: { ...(earlier?.patch || {}), ...patch }, releaseConfirmed: release || earlier?.releaseConfirmed === true };
10313
- report(error, '', { 'chat-turn-active': pendingSettingsSentence(patch) });
10314
- return;
10315
- }
11433
+ // The control stays on the level that is really in force (state.chat was not replaced); the hint says why.
10316
11434
  report(error, 'Could not update settings', settingsSaveMessages(error));
10317
11435
  }
10318
11436
  }
10319
11437
 
10320
- /** #2336: said when a settings choice has to wait for the running reply; it applies by itself afterwards. */
10321
- function pendingSettingsSentence(patch) {
10322
- const what = 'permissionProfile' in patch ? `Access to ${permissionLabel(patch.permissionProfile)}`
10323
- : 'useOwnConnectors' in patch ? (patch.useOwnConnectors === true ? 'your connectors to on' : 'your connectors to off')
10324
- : 'model' in patch ? 'the model' : 'effort';
10325
- return `The AI is still replying, so ${what} will change as soon as this reply finishes. Nothing else to do.`;
10326
- }
10327
-
10328
11438
  /** #2336: the sentences for a settings change that could not be stored (the shared sentences say "Stop the response", which is wrong here). */
10329
11439
  function settingsSaveMessages(error) {
10330
11440
  const code = String(error && error.code || '');
@@ -10335,16 +11445,6 @@
10335
11445
  return null;
10336
11446
  }
10337
11447
 
10338
- /** #2336: applies a choice that waited for a running reply, once that reply is over and only to the chat it was made in. */
10339
- function applyPendingSettings() {
10340
- const pending = state.pendingSettings;
10341
- if (!pending) return;
10342
- if (state.chat?.chatId !== pending.chatId) { state.pendingSettings = null; return; }
10343
- if (state.chat.activeTurn || state.chat.archivedAt) return;
10344
- state.pendingSettings = null;
10345
- void saveSettings(pending.patch, { releaseConfirmed: pending.releaseConfirmed === true });
10346
- }
10347
-
10348
11448
  function modelChoices() {
10349
11449
  const models = state.capability?.models || [];
10350
11450
  const shown = selectedModel()?.id;
@@ -10396,6 +11496,26 @@
10396
11496
  return `Access: ${label}. ${permissionMeta(value || 'read-only')}`;
10397
11497
  }
10398
11498
 
11499
+ /**
11500
+ * #2651: while a reply runs after the person changed Access, the level the next message uses and the one the reply
11501
+ * keeps (from the record, so a reload, another window and the AI's own change all show it); otherwise null.
11502
+ */
11503
+ function accessChangedDuringReply(chat) {
11504
+ const turn = chat?.activeTurn;
11505
+ if (!turn || turn.local || (turn.accessRevision ?? 0) === (chat.accessRevision ?? 0)) return null;
11506
+ return {
11507
+ next: isInstructorAnswer(chat) ? 'No tools' : permissionLabel(chat.settings?.permissionProfile),
11508
+ kept: turn.answerOnly ? 'No tools' : turn.permissionProfile ? permissionLabel(turn.permissionProfile) : null,
11509
+ };
11510
+ }
11511
+
11512
+ /** #2651: the Access tooltip of the chip and the settings row; during a reply it says when a change applies. */
11513
+ function accessTip(chat) {
11514
+ const changed = accessChangedDuringReply(chat);
11515
+ if (changed) return `Access: ${changed.next}, from your next message. This reply keeps ${changed.kept || 'the Access it started with'}.`;
11516
+ return `${permissionTip(chat?.settings?.permissionProfile)}${chat?.activeTurn ? ' Changes apply from your next message.' : ''}`;
11517
+ }
11518
+
10399
11519
  function permissionChoices() {
10400
11520
  // #2234 (owner ruling 2026-10-12): every conversation offers all four levels — the workspace's and the Guide's too.
10401
11521
  return Object.keys(permissionLabels).map((value) => ({
@@ -10463,6 +11583,10 @@
10463
11583
 
10464
11584
  function integrationReason(row) {
10465
11585
  const code = typeof row?.reasonCode === 'string' ? row.reasonCode : '';
11586
+ // #2649: Google's file access is the Drive checkbox on its card; other services keep the general sentence.
11587
+ if (code === 'scope-missing' && row?.integration === 'google-workspace') {
11588
+ return 'This account was connected without permission to read these files. In Integrations, tick the Drive file list on Google Workspace and click Reconnect.';
11589
+ }
10466
11590
  if (Object.hasOwn(INTEGRATION_REASON_COPY, code)) return INTEGRATION_REASON_COPY[code];
10467
11591
  const raw = String(row?.reason || '');
10468
11592
  if (!raw) return 'This connected account is unavailable.';
@@ -10887,6 +12011,12 @@
10887
12011
  if (server.disposition === 'stale') info.note = server.reason || SERVER_PROPOSAL_NOTES.stale;
10888
12012
  }
10889
12013
  const disposition = info.known ? info.disposition : 'pending';
12014
+ // #2678: an undecided suggestion still waits for the person when its card is hidden (repainted in place, so it is cleared
12015
+ // too). One from an earlier view, or one that suggests no change, offers no buttons, so nothing waits on it.
12016
+ // Applied with nothing left to undo, kept, undone or out of date: settled, so the card folds by itself.
12017
+ if (info.known && disposition === 'pending' && hasChanges) card.dataset.waits = 'you';
12018
+ else if (info.known && (['kept', 'undone', 'stale'].includes(disposition) || (disposition === 'applied' && !info.undo))) card.dataset.waits = 'done';
12019
+ else delete card.dataset.waits;
10890
12020
  // An unknown record (reload, another window) claims no outcome, only that it predates this view.
10891
12021
  // "not saved" only while this suggestion's own Undo is live: Save and later edits retire it.
10892
12022
  const chip = card.querySelector('.ai-chat-filter-state');
@@ -11417,7 +12547,8 @@
11417
12547
  if (mentionItems.length) restoreRefusedMentions(chatId, mentionItems);
11418
12548
  ui.input.value = text; autosize(); paintAttachments(); saveDraftSoon(); paintConversation();
11419
12549
  // #2061: the project is busy — ask (wait / open it / stop it) instead of only saying it failed. Nothing was sent.
11420
- if (!askIfProjectBusy(error, busyMessage)) report(error, 'Message was not sent');
12550
+ // A provider refusal carries its reason (a check that timed out on a busy computer is not a sign-out).
12551
+ if (!askIfProjectBusy(error, busyMessage)) report(error, 'Message was not sent', { 'chat-provider-unavailable': capabilityMessage(state.chat?.provider, error?.message) });
11421
12552
  } finally { if (sameChat(snapshot)) { setBusy(false); updateSendState(); } }
11422
12553
  }
11423
12554
 
@@ -12871,50 +14002,96 @@
12871
14002
  }
12872
14003
  }
12873
14004
 
12874
- // This is a browser presentation preference, never a conversation permission or approval.
12875
- function readAccessExplanationPreference() {
12876
- try { return localStorage.getItem('floless:chat-access-explanation') === 'expanded'; } catch { return false; }
14005
+ /**
14006
+ * The composer's Access chip is a quick switch, like the AI terminals' own: the four levels, each with its one-line
14007
+ * note and a check on the current one. A pick saves through saveSettings, so it takes the same path as the settings
14008
+ * row (an Instructor answer still asks first). What a level means in full stays in this conversation's Scope view.
14009
+ */
14010
+ function openAccessMenu() {
14011
+ const chip = ui.accessChip, menu = ui.accessMenu;
14012
+ if (!chip || !menu || chip.disabled || !state.chat) return;
14013
+ if (!menu.hidden) { closeAccessMenu(); return; }
14014
+ closePicker(); closeScopePicker();
14015
+ const head = document.createElement('div'); head.className = 'ai-chat-access-menu-head'; head.id = 'chat-access-menu-head';
14016
+ head.textContent = accessMenuHead(state.chat);
14017
+ menu.replaceChildren(head);
14018
+ for (const choice of permissionChoices()) {
14019
+ const value = choice.patch.permissionProfile;
14020
+ const item = button('', `shell.chat-access-choose#${commandInstance(value)}`);
14021
+ item.dataset.commandInstanceLabel = choice.label; item.dataset.value = value;
14022
+ item.setAttribute('role', 'menuitemradio'); item.setAttribute('aria-checked', String(choice.selected));
14023
+ const label = document.createElement('strong'); label.textContent = choice.label;
14024
+ const meta = document.createElement('small'); meta.textContent = choice.meta;
14025
+ item.append(label, meta);
14026
+ item.addEventListener('click', () => {
14027
+ const current = item.getAttribute('aria-checked') === 'true';
14028
+ closeAccessMenu(true);
14029
+ if (!current) void saveSettings(choice.patch);
14030
+ });
14031
+ menu.append(item);
14032
+ }
14033
+ state.accessMenuChatId = state.chat.chatId;
14034
+ menu.hidden = false; chip.setAttribute('aria-expanded', 'true');
14035
+ (menu.querySelector('[aria-checked="true"]') || menu.querySelector('button'))?.focus();
12877
14036
  }
12878
14037
 
12879
- function toggleAccessExplanation() {
12880
- state.accessExplanationExpanded = !state.accessExplanationExpanded;
12881
- try { localStorage.setItem('floless:chat-access-explanation', state.accessExplanationExpanded ? 'expanded' : 'collapsed'); } catch { /* private mode: retain the choice for this page */ }
12882
- paintScopeControl();
14038
+ /** #2651: during a reply a pick applies from the next message, and the menu says so before the click. */
14039
+ function accessMenuHead(chat) { return chat?.activeTurn ? 'Access · from your next message' : 'Access · this chat'; }
14040
+
14041
+ function closeAccessMenu(focusChip = false) {
14042
+ if (!ui.accessMenu || ui.accessMenu.hidden) return;
14043
+ ui.accessMenu.hidden = true; ui.accessMenu.replaceChildren();
14044
+ ui.accessChip?.setAttribute('aria-expanded', 'false');
14045
+ if (focusChip) ui.accessChip?.focus();
12883
14046
  }
12884
14047
 
12885
14048
  function paintScopeControl() {
12886
14049
  if (!ui.scopeControls) return;
12887
14050
  const chat = state.chat;
12888
14051
  ui.scopeControls.hidden = !chat || Boolean(chat.archivedAt);
12889
- if (!chat) { closeScopePicker(); return; }
14052
+ if (!chat) { closeScopePicker(); closeAccessMenu(); return; }
12890
14053
  if (state.scopeViewChatId !== chat.chatId) { state.scopeView = null; closeScopePicker(); }
12891
14054
  if (state.scopeView && state.scopeView.scope.revision !== (chat.scopeRevision ?? 0)) {
12892
14055
  state.scopeView = null; closeScopePicker();
12893
14056
  }
12894
14057
  const count = Array.isArray(chat.scopeExtensions) ? chat.scopeExtensions.length : 0;
12895
14058
  const home = state.scopeView?.scope?.home?.label || state.scope?.label || 'Home';
12896
- ui.scopeToggle.textContent = `Scope · ${home}${count ? ` + ${count}` : ''}`;
12897
- ui.scopeToggle.dataset.tip = 'See the conversation’s home folder and add or remove other projects and workflows.';
14059
+ // A toolbar chip: a folder icon and the home (+ how many added); the word "Scope" is in its name and tooltip.
14060
+ const scopeText = `${home}${count ? ` + ${count}` : ''}`;
14061
+ const scopeLabel = ui.scopeToggle.querySelector('span') || document.createElement('span');
14062
+ if (!scopeLabel.isConnected) {
14063
+ ui.scopeToggle.replaceChildren();
14064
+ ui.scopeToggle.insertAdjacentHTML('afterbegin', '<svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/></svg>');
14065
+ ui.scopeToggle.append(scopeLabel);
14066
+ }
14067
+ scopeLabel.textContent = scopeText;
14068
+ ui.scopeToggle.setAttribute('aria-label', `Scope: ${scopeText}`);
14069
+ ui.scopeToggle.dataset.tip = `Scope: ${scopeText}. See the conversation’s home folder and add or remove other projects and workflows.`;
12898
14070
  ui.scopeToggle.disabled = state.loading;
12899
14071
  if (ui.scopeToggle.disabled) ui.scopeToggle.dataset.blockedReason = 'The conversation is still loading.';
12900
14072
  else delete ui.scopeToggle.dataset.blockedReason;
12901
- const disclosure = isInstructorAnswer(chat)
12902
- ? 'This chat answers an Instructor question, so the AI can’t read files, run commands, search the web or use your connectors. Choose an Access to turn it into an ordinary chat. FloLess asks first.'
12903
- : chat.settings?.permissionProfile === 'read-only'
12904
- ? 'Read only: the AI’s file tools cannot change files. Commands keep their own approvals and may authorize file changes.'
12905
- : chat.settings?.permissionProfile === 'full-access' ? fullAccessScopeNote()
12906
- : chat.settings?.permissionProfile === 'auto' ? autoScopeNote()
12907
- : chat.changeAllowance?.allowedForChat ? 'File changes in scope, including folders you add later, are allowed for this chat.' : permissionTip(chat.settings?.permissionProfile);
12908
- if (ui.scopeDisclosure.textContent !== disclosure) ui.scopeDisclosure.textContent = disclosure;
12909
- if (ui.accessExplanation) {
12910
- const label = isInstructorAnswer(chat) ? 'No tools' : permissionLabel(chat.settings?.permissionProfile);
12911
- ui.accessExplanation.querySelector('strong').textContent = label;
12912
- ui.accessExplanation.setAttribute('aria-label', `Explain ${label} access`);
12913
- ui.accessExplanation.setAttribute('aria-expanded', String(Boolean(state.accessExplanationExpanded)));
12914
- ui.accessExplanation.dataset.tip = state.accessExplanationExpanded ? 'Explanation shown. Hide the access explanation.' : 'Explanation hidden. Show what this access level allows.';
12915
- ui.accessExplanation.dataset.commandInstanceLabel = state.accessExplanationExpanded ? 'shown' : 'hidden';
12916
- ui.accessExplanation.dataset.commandId = `shell.chat-access-explanation#${state.accessExplanationExpanded ? 'shown' : 'hidden'}`;
12917
- ui.scopeDisclosure.hidden = !state.accessExplanationExpanded || !disclosure;
14073
+ if (ui.accessChip) {
14074
+ const instructor = isInstructorAnswer(chat);
14075
+ const label = instructor ? 'No tools' : permissionLabel(chat.settings?.permissionProfile);
14076
+ ui.accessChip.querySelector('strong').textContent = label;
14077
+ // #2651: Access can change at any time, a reply included: it shows the level the next message uses.
14078
+ const changed = accessChangedDuringReply(chat);
14079
+ ui.accessChip.setAttribute('aria-label', changed ? `Access: ${label} from your next message. Change access` : `Access: ${label}. Change access`);
14080
+ ui.accessChip.disabled = false;
14081
+ delete ui.accessChip.dataset.blockedReason;
14082
+ // One line, like the menu; what the level means in full is in this conversation's Scope view.
14083
+ ui.accessChip.dataset.tip = instructor
14084
+ ? 'This chat answers an Instructor question, so the AI can’t read files, run commands, search the web or use your connectors. Choose an Access to turn it into an ordinary chat. FloLess asks first.'
14085
+ : `${accessTip(chat)} Click to change.`;
14086
+ if (state.accessMenuChatId !== chat.chatId) closeAccessMenu();
14087
+ else if (!ui.accessMenu.hidden) {
14088
+ // A repaint moves the check and the head only; the items stay, so focus stays where it is.
14089
+ const head = ui.accessMenu.querySelector('#chat-access-menu-head');
14090
+ if (head && head.textContent !== accessMenuHead(chat)) head.textContent = accessMenuHead(chat);
14091
+ for (const item of ui.accessMenu.querySelectorAll('[role="menuitemradio"]')) {
14092
+ item.setAttribute('aria-checked', String(!isInstructorAnswer(chat) && item.dataset.value === chat.settings?.permissionProfile));
14093
+ }
14094
+ }
12918
14095
  }
12919
14096
  // Poll/SSE can change permissions or pause a reply while Scope stays open. Refresh only when
12920
14097
  // these states change, retaining its selected add choice and focus on an enabled control.
@@ -13592,10 +14769,14 @@
13592
14769
  ui.input.focus();
13593
14770
  }
13594
14771
 
14772
+ // An intake creates the project and saves its drawings before the first turn's own capability check and locks, so it
14773
+ // needs longer than REQUEST_START_TIMEOUT_MS; a retry with the same submission id never makes a second project.
14774
+ const PROJECT_INTAKE_TIMEOUT_MS = 120000;
13595
14775
  async function startProjectIntake(submissionId, payload) {
13596
14776
  await ensureSession();
14777
+ // A shorter wait read "could not create" about a project that was made, on a busy computer (#2470 R6.4 E2E).
13597
14778
  return request(`/api/chat/project-intakes/${encodeURIComponent(submissionId)}/start`, {
13598
- method: 'POST', body: JSON.stringify(payload),
14779
+ method: 'POST', timeoutMs: PROJECT_INTAKE_TIMEOUT_MS, body: JSON.stringify(payload),
13599
14780
  });
13600
14781
  }
13601
14782
 
@@ -13624,7 +14805,7 @@
13624
14805
  async function resumeProjectIntake(submissionId) {
13625
14806
  await ensureSession();
13626
14807
  return request(`/api/chat/project-intakes/${encodeURIComponent(submissionId)}/resume`, {
13627
- method: 'POST', body: '{}',
14808
+ method: 'POST', timeoutMs: PROJECT_INTAKE_TIMEOUT_MS, body: '{}',
13628
14809
  });
13629
14810
  }
13630
14811
 
@@ -13726,12 +14907,29 @@
13726
14907
  else if (event.key === 'Escape') { ui.skills.hidden = true; closePicker(); }
13727
14908
  });
13728
14909
  ui.scopeToggle?.addEventListener('click', () => { void openScopePicker(); });
13729
- ui.accessExplanation?.addEventListener('click', toggleAccessExplanation);
14910
+ ui.accessChip?.addEventListener('click', openAccessMenu);
14911
+ ui.accessChip?.addEventListener('keydown', (event) => {
14912
+ if (event.key === 'Escape' && !ui.accessMenu.hidden) { event.preventDefault(); event.stopPropagation(); closeAccessMenu(true); }
14913
+ });
14914
+ ui.accessMenu?.addEventListener('keydown', (event) => {
14915
+ const items = [...ui.accessMenu.querySelectorAll('button')];
14916
+ const at = items.indexOf(document.activeElement);
14917
+ // Keys the menu uses stop here: Home is also the canvas's fit-to-screen shortcut (web/app.js).
14918
+ if (['Escape', 'ArrowDown', 'ArrowUp', 'Home', 'End'].includes(event.key)) { event.preventDefault(); event.stopPropagation(); }
14919
+ if (event.key === 'Escape') closeAccessMenu(true);
14920
+ else if (event.key === 'ArrowDown' || event.key === 'ArrowUp') items[(at + (event.key === 'ArrowDown' ? 1 : items.length - 1)) % items.length]?.focus();
14921
+ else if (event.key === 'Home' || event.key === 'End') items[event.key === 'Home' ? 0 : items.length - 1]?.focus();
14922
+ });
14923
+ // Focus leaving both the chip and the menu (Tab away) closes it.
14924
+ for (const node of [ui.accessChip, ui.accessMenu]) node?.addEventListener('focusout', (event) => {
14925
+ if (!ui.accessMenu.hidden && !ui.accessChip.contains(event.relatedTarget) && !ui.accessMenu.contains(event.relatedTarget)) closeAccessMenu();
14926
+ });
13730
14927
  ui.scopePicker?.addEventListener('keydown', (event) => {
13731
14928
  if (event.key === 'Escape') { event.preventDefault(); closeScopePicker(true); }
13732
14929
  });
13733
14930
  document.addEventListener('pointerdown', (event) => {
13734
14931
  if (state.scopePickerOpen && !ui.scopeControls?.contains(event.target)) closeScopePicker();
14932
+ if (ui.accessMenu && !ui.accessMenu.hidden && !ui.accessMenu.contains(event.target) && !ui.accessChip.contains(event.target)) closeAccessMenu();
13735
14933
  });
13736
14934
  // Capture phase: the control's own handler runs after, so a sentence it reports is held afresh.
13737
14935
  shell.addEventListener('click', releaseReportOnControl, true);