@floless/app 0.153.0 → 0.155.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 (53) hide show
  1. package/dist/floless-server.cjs +51767 -38222
  2. package/dist/schemas/revit.model.v1.schema.json +5 -0
  3. package/dist/schemas/steel.model.v2.schema.json +19 -5
  4. package/dist/skills/floless-app-new-workflow/SKILL.md +8 -2
  5. package/dist/skills/floless-app-onboarding/SKILL.md +31 -19
  6. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +20 -11
  7. package/dist/skills/floless-app-queue/SKILL.md +23 -4
  8. package/dist/skills/floless-app-steel-model/SKILL.md +23 -2
  9. package/dist/skills/floless-app-steel-takeoff/SKILL.md +158 -65
  10. package/dist/skills/floless-app-workflows/SKILL.md +23 -5
  11. package/dist/skills/floless-app-workflows/references/blender-exec.md +183 -0
  12. package/dist/skills/floless-app-workflows/references/dev-server-and-run-trace.md +27 -12
  13. package/dist/templates/blender-construction-sequence.flo +96 -0
  14. package/dist/web/agents.js +33 -13
  15. package/dist/web/app.css +331 -34
  16. package/dist/web/app.js +12 -1
  17. package/dist/web/aware.js +1167 -137
  18. package/dist/web/chat-question-card.js +477 -0
  19. package/dist/web/chat.css +237 -25
  20. package/dist/web/chat.js +2156 -889
  21. package/dist/web/commands-shell.js +578 -21
  22. package/dist/web/commands-steel.js +105 -4
  23. package/dist/web/guide.js +217 -16
  24. package/dist/web/index.html +104 -10
  25. package/dist/web/instructor.js +10 -9
  26. package/dist/web/left-pane.js +43 -6
  27. package/dist/web/media-player.js +234 -0
  28. package/dist/web/model-editor-contract.js +2 -0
  29. package/dist/web/model-editor-revit-adapter.js +1 -0
  30. package/dist/web/model-editor-steel-adapter.js +89 -1
  31. package/dist/web/model-panel-bridge.js +16 -2
  32. package/dist/web/model-view-query.js +590 -0
  33. package/dist/web/model-viewport-revit-adapter.js +15 -1
  34. package/dist/web/model-viewport-toolbar.js +5 -2
  35. package/dist/web/pages.js +592 -0
  36. package/dist/web/panels.js +2 -1
  37. package/dist/web/revit-editor.js +182 -16
  38. package/dist/web/run-progress.js +193 -0
  39. package/dist/web/run-strip.js +173 -0
  40. package/dist/web/steel-3d-core.js +70 -0
  41. package/dist/web/steel-editor.html +2751 -219
  42. package/dist/web/steel-frames-core.js +958 -0
  43. package/dist/web/steel-last-seen.js +315 -0
  44. package/dist/web/steel-marks-core.js +530 -0
  45. package/dist/web/steel-model-slim.js +95 -0
  46. package/dist/web/steel-model-v2-client-validation.js +14 -2
  47. package/dist/web/steel-model-v2-commands.js +258 -27
  48. package/dist/web/steel-model-v2-projection.js +78 -18
  49. package/dist/web/steel-read-confidence.js +11 -2
  50. package/dist/web/tekla-structural-grid-adapter.js +7 -1
  51. package/dist/web/tool-updates.js +141 -33
  52. package/dist/web/workspaces.js +446 -30
  53. package/package.json +3 -2
package/dist/web/chat.js CHANGED
@@ -33,8 +33,9 @@
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'),
36
+ scopePicker: el('chat-scope-picker'), scopeDisclosure: el('chat-scope-disclosure'), accessExplanation: el('chat-access-explanation'),
37
37
  checkAllowance: el('chat-check-allowance'),
38
+ grants: el('chat-grants'),
38
39
  workspaceUnits: el('chat-units'),
39
40
  moveNotice: el('chat-move-notice'), moveCopy: el('chat-move-copy'), movePrimary: el('chat-move-primary'),
40
41
  moveSecondary: el('chat-move-secondary'), moveDismiss: el('chat-move-dismiss'),
@@ -42,6 +43,7 @@
42
43
 
43
44
  const state = {
44
45
  scopeView: null, scopeViewChatId: null, scopeChoice: null, scopeEditing: false, scopePickerOpen: false,
46
+ accessExplanationExpanded: readAccessExplanationPreference(),
45
47
  // signInPending is keyed by provider: a wait started in one conversation must not paint an
46
48
  // unrelated conversation's button as Waiting for sign-in… for the next two minutes.
47
49
  // #1798: the chat owner's display units as the server last answered them (null = not known yet), and the
@@ -53,8 +55,8 @@
53
55
  source: null, eventReconnectTimer: null, eventReconnectAttempt: 0, eventReconnectChatId: null, attachments: [], imageLimitChatId: null, followupSubmitting: false, followupUnknownId: null, resolvingFollowupIds: new Set(), retryingFollowupIds: new Set(), integrations: null, historyOpen: false, historyOpenings: 0, historyFilter: 'all', archivedHistoryOpen: false,
54
56
  instructorAnswers: [], historyLoading: false, historyRequestGeneration: 0, picker: null, loading: false,
55
57
  draftTimer: null, localDraft: null, backgroundDrafts: new Map(), draftWrites: new Map(), draftVersions: new Map(), unknownFollowups: new Map(), refreshTimer: null, scopeGeneration: 0, selectionGeneration: 0, openInGeneration: 0, choosingProvider: false,
56
- answerJump: null, answerJumpTimer: null, scopeInitialized: false, renaming: null, historyRename: null, pendingSubmissionId: null, recoveryMessage: null, recoveryCanEnd: false,
57
- stream: null, liveStatusTurnId: null, liveFlo: null, decidingApprovalIds: new Set(), revokingApprovalTurns: new Set(), uploadingChatIds: new Set(),
58
+ answerJump: null, answerJumpTimer: null, scopeInitialized: false, renaming: null, historyRename: null, pendingSubmissionId: null, recoveryMessage: null, recoveryCanEnd: false, recoveryTurnId: null,
59
+ stream: null, liveStatusTurnId: null, liveFlo: null, decidingApprovalIds: new Set(), revokingApprovalTurns: new Set(), uploadingChatIds: new Set(), pendingStops: new Map(),
58
60
  // #1653 stage 4: this chat owner's (project or workflow, #1890) questions linked to live Tekla parts, the card's open lists, and the receipt showing it.
59
61
  teklaLinks: { ownerKey: '', state: 'idle', links: [], partial: false, inflight: false, again: false }, teklaHistoryUi: {}, teklaHistoryHost: null,
60
62
  // Latched so the 5 s account poll logs an outage once instead of twelve times a minute; cleared
@@ -87,6 +89,18 @@
87
89
  }).observe(tray);
88
90
  }
89
91
  keepApprovalTrayDecisionVisible(ui.approvalTray);
92
+ // #2223: a card opening above the message box shrinks the conversation. A reader who was at its end stays at its end,
93
+ // so the AI's reply to their answer is in sight; one who scrolled up stays where they were.
94
+ function keepFeedFollowing(feed) {
95
+ let atEnd = true;
96
+ feed.addEventListener('scroll', () => {
97
+ atEnd = feed.scrollHeight - feed.scrollTop - feed.clientHeight < 56;
98
+ });
99
+ new ResizeObserver(() => {
100
+ if (atEnd && !state.answerJump) feed.scrollTop = feed.scrollHeight;
101
+ }).observe(feed);
102
+ }
103
+ keepFeedFollowing(ui.feed);
90
104
  // #2037: safest to widest; Auto is the default for a project or workflow conversation.
91
105
  const permissionLabels = {
92
106
  'read-only': 'Read only', auto: 'Auto', 'workspace-write': 'Working folder write', 'full-access': 'Full access',
@@ -102,8 +116,8 @@
102
116
  // The server's own sentence is more accurate than anything we can substitute: it names WHICH
103
117
  // runtime problem happened and WHICH command to run by hand. errorMessage() would flatten it.
104
118
  const SERVER_WORDED_SIGN_IN_CODES = new Set(['runtime-unavailable', 'launch-failed', 'launch-unsafe', 'sign-in-active', 'sign-out-failed']);
105
- const requestTypeLabels = { 'drawing-intake': 'Initial drawing read', 'initial-drawing-read': 'Initial drawing read', 'tweak-contract': 'Workflow change', guide: 'Question' };
106
- const requestStatusLabels = { pending: 'Queued', queued: 'Queued', running: 'Running', ready: 'Ready', completed: 'Complete', failed: 'Failed', stopped: 'Stopped', finished: 'Finished', 'left-queue': 'Left the queue' };
119
+ const requestTypeLabels = { 'drawing-intake': 'Initial drawing read', 'initial-drawing-read': 'Initial drawing read', 'tweak-contract': 'Workflow change', guide: 'Question', 'new-workflow': 'Build a workflow' };
120
+ const requestStatusLabels = { pending: 'Queued', queued: 'Queued', running: 'Running', ready: 'Ready', completed: 'Complete', failed: 'Failed', stopped: 'Stopped', finished: 'Finished', 'left-queue': 'Left the queue', dismissed: 'Dismissed', expired: 'Expired', settled: 'Done' };
107
121
  // Pictures and PDFs upload as the browser names them. Any other file is a DATA file (#1853): its
108
122
  // bytes decide whether FloLess can read it (sniffDataFile), never its name or declared type.
109
123
  const allowedTypes = new Set(['image/png', 'image/jpeg', 'image/webp', 'application/pdf']);
@@ -240,7 +254,6 @@
240
254
  // #2059: an Instructor answer uses no tools until the person confirms a wider Access.
241
255
  'chat-instructor-answer-access': 'This chat is an Instructor answer, so the AI uses no tools. Confirm the Access change to turn it into an ordinary chat.',
242
256
  'chat-instructor-answer-accounts': 'An Instructor answer uses no tools, so it cannot use a connected account. Start a new chat to use one.',
243
- 'chat-guide-read-only': 'The Guide only reads, so its Access stays Read only. To let the AI change things, use a regular conversation.',
244
257
  // Damage the user can act on, unlike the refusals below it: the conversation history lists this
245
258
  // same record as a row offering Discard, so the sentence sends them there (#1629). Without an
246
259
  // entry here the code fell through to the generic "could not complete this chat action", which
@@ -287,8 +300,14 @@
287
300
  'request-chat-not-ready': 'This request is still being prepared. Wait a moment, then try again.',
288
301
  'chat-knowledge-unscoped': 'Knowledge is available only inside a project conversation. Open a project and try again.',
289
302
  'chat-knowledge-page-missing': 'That Knowledge page is no longer available in this project. Refresh the conversation.',
290
- 'approval-explicit-only': 'This read needs its own approval. Choose Approve once or Deny.',
291
- 'approval-not-chat-allowable': 'This can only be approved once. Choose Approve once or Deny.',
303
+ 'approval-explicit-only': 'This request needs its own approval. Choose Approve once or Deny.',
304
+ 'approval-not-chat-allowable': 'That choice does not fit this request. Choose again.',
305
+ 'approval-not-session-allowable': 'That choice does not fit this request. Choose again.',
306
+ 'request-grant-changed': 'What is allowed for this request changed. Choose again.',
307
+ 'session-approval-changed': 'Auto-approval for this conversation changed. Choose again.',
308
+ 'approval-grants-changed': 'What is allowed for this chat changed. Choose again.',
309
+ 'integration-read-allowance-changed': 'The connection checks allowed for this chat changed. Choose again.',
310
+ 'change-allowance-changed': 'The changes allowed for this chat changed. Choose again.',
292
311
  'tekla-allowance-changed': 'The Tekla read permission for this chat changed. Choose again.',
293
312
  'connector-allowance-changed': 'The connectors allowed for this chat changed. Choose again.',
294
313
  };
@@ -833,6 +852,7 @@
833
852
  paintChangeAllowance();
834
853
  paintScopeControl();
835
854
  paintCheckAllowance();
855
+ paintApprovalGrants();
836
856
  }
837
857
 
838
858
  function providerChooser() {
@@ -2188,7 +2208,12 @@
2188
2208
  label.textContent = requestTypeLabels[payload.requestType] || String(payload.requestType || 'Request').replace(/-/g, ' ');
2189
2209
  const status = document.createElement('span'); status.className = 'ai-chat-request-status';
2190
2210
  status.textContent = requestStatusLabels[payload.requestStatus] || String(payload.requestStatus || 'pending').replace(/-/g, ' ');
2191
- head.append(label, status);
2211
+ // #2185: always-visible ✕ - hides the card, and on a request that is still waiting also sets the request aside (with Undo).
2212
+ const hide = document.createElement('button'); hide.type = 'button'; hide.className = 'ai-chat-request-dismiss'; hide.textContent = '×';
2213
+ hide.dataset.commandId = `shell.chat-request-dismiss#${payload.requestId || 'linked request'}`;
2214
+ hide.setAttribute('aria-label', 'Dismiss this request');
2215
+ status.setAttribute('role', 'status');
2216
+ head.append(label, status, hide);
2192
2217
  const body = document.createElement('p'); body.textContent = payloadText(event);
2193
2218
  item.append(head, body);
2194
2219
  if (Array.isArray(payload.sourceNames) && payload.sourceNames.length) {
@@ -2203,9 +2228,209 @@
2203
2228
  open.dataset.tip = 'Open the linked request and its detailed progress';
2204
2229
  open.addEventListener('click', () => window.flolessBridge?.openRequest?.(payload.requestId));
2205
2230
  actions.append(open); item.append(actions);
2231
+ // Its live state replaces the frozen copy above as soon as it is known (and again whenever Requests changes).
2232
+ initRequestCard(item, event);
2206
2233
  return item;
2207
2234
  }
2208
2235
 
2236
+ /*
2237
+ * #2185 - the request card tells the truth about its request, now. The frozen copy in the event says "Queued" for ever; the
2238
+ * server's projection says Waiting for the AI / The AI is working / The AI has a question / Done / Dismissed / Expired.
2239
+ * ✕ is always there: on a request that is only waiting it sets the request aside (Undo puts it back); when the AI is
2240
+ * working on it the card ASKS - stop that work and dismiss, or keep it. On one that is already done it hides the card.
2241
+ */
2242
+ const REQUEST_CARD_WORDS = { dismissed: 'Dismissed', expired: 'Expired', settled: 'Done' };
2243
+ const REQUEST_CARD_HIDDEN_KEY = 'floless:chat-hidden-request-cards';
2244
+ state.requestCards = state.requestCards || new Map();
2245
+ state.requestCardsAt = state.requestCardsAt || 0;
2246
+
2247
+ function hiddenRequestCards() {
2248
+ try {
2249
+ const parsed = JSON.parse(localStorage.getItem(REQUEST_CARD_HIDDEN_KEY) || '[]');
2250
+ return new Set(Array.isArray(parsed) ? parsed.filter((id) => typeof id === 'string') : []);
2251
+ } catch { return new Set(); }
2252
+ }
2253
+ function rememberHiddenRequestCard(eventId, hidden) {
2254
+ const ids = hiddenRequestCards();
2255
+ if (hidden) ids.add(eventId); else ids.delete(eventId);
2256
+ try { localStorage.setItem(REQUEST_CARD_HIDDEN_KEY, JSON.stringify([...ids].slice(-300))); } catch { /* private mode: it shows again next time */ }
2257
+ }
2258
+
2259
+ /** The word for a request's live state, or '' when nothing live is known yet (the frozen word stays). */
2260
+ function requestCardWord(live) {
2261
+ if (!live) return '';
2262
+ if (live.found === false) return 'Done';
2263
+ if (live.lifecycle?.state) return REQUEST_CARD_WORDS[live.lifecycle.state] || '';
2264
+ return live.attention?.label || '';
2265
+ }
2266
+
2267
+ function paintRequestCard(item) {
2268
+ const requestId = item.dataset.requestId;
2269
+ const live = state.requestCards.get(requestId);
2270
+ const word = requestCardWord(live);
2271
+ const status = item.querySelector('.ai-chat-request-status');
2272
+ if (status && word) status.textContent = word;
2273
+ const set = live?.found !== false ? live?.lifecycle?.state || null : null;
2274
+ item.dataset.requestState = live ? (live.found === false ? 'gone' : set || 'waiting') : 'unknown';
2275
+ item.dataset.attention = live?.attention?.state || '';
2276
+ item.classList.toggle('ai-chat-request-aside', set === 'dismissed' || set === 'expired');
2277
+ // A request I dismissed from here can be taken back from here.
2278
+ let undo = item.querySelector('.ai-chat-request-undo');
2279
+ if (set === 'dismissed' || set === 'expired') {
2280
+ if (!undo) {
2281
+ undo = button('Undo', `shell.chat-request-undo#${requestId || 'linked request'}`, 'ai-chat-request-undo');
2282
+ undo.dataset.tip = 'Put this request back in Requests, exactly as it was';
2283
+ undo.addEventListener('click', () => { void restoreRequestFromCard(item); });
2284
+ item.querySelector('.ai-chat-request-actions')?.prepend(undo);
2285
+ }
2286
+ } else if (undo) undo.remove();
2287
+ const hideButton = item.querySelector('.ai-chat-request-dismiss');
2288
+ if (hideButton) {
2289
+ const finished = live && (live.found === false || set);
2290
+ hideButton.dataset.tip = finished ? 'Hide this card from the chat' : 'Dismiss this request. It stays in Requests → Done, and you can undo it';
2291
+ hideButton.setAttribute('aria-label', finished ? 'Hide this card' : 'Dismiss this request');
2292
+ }
2293
+ }
2294
+
2295
+ function initRequestCard(item, event) {
2296
+ item.dataset.cardEventId = event.eventId;
2297
+ if (hiddenRequestCards().has(event.eventId)) item.hidden = true;
2298
+ const hide = item.querySelector('.ai-chat-request-dismiss');
2299
+ hide?.addEventListener('click', () => { void dismissRequestFromCard(item, event.eventId); });
2300
+ paintRequestCard(item);
2301
+ queueMicrotask(() => { void refreshRequestCards(); });
2302
+ }
2303
+
2304
+ async function refreshRequestCards({ force = false } = {}) {
2305
+ if (!ui.feed) return;
2306
+ const cards = [...ui.feed.querySelectorAll('.ai-chat-request-card[data-request-id]')].filter((card) => card.dataset.requestId);
2307
+ if (!cards.length) return;
2308
+ if (!force && Date.now() - state.requestCardsAt < 2500) return;
2309
+ state.requestCardsAt = Date.now();
2310
+ const ids = [...new Set(cards.map((card) => card.dataset.requestId))].slice(0, 40);
2311
+ let statuses;
2312
+ try { statuses = (await request(`/api/requests/status?ids=${ids.map(encodeURIComponent).join(',')}`, { timeoutMs: 10000 })).statuses; }
2313
+ catch { return; /* the card keeps what it last knew; the next poll tries again */ }
2314
+ if (!Array.isArray(statuses)) return;
2315
+ for (const live of statuses) if (live?.id) state.requestCards.set(live.id, live);
2316
+ for (const card of ui.feed.querySelectorAll('.ai-chat-request-card[data-request-id]')) paintRequestCard(card);
2317
+ }
2318
+
2319
+ async function lifecycleCall(requestId, action) {
2320
+ const response = await fetch(`/api/requests/${encodeURIComponent(requestId)}/${action}`, {
2321
+ method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, body: '{}',
2322
+ });
2323
+ const body = await response.json().catch(() => ({}));
2324
+ return { ok: response.ok && body.ok !== false, status: response.status, body };
2325
+ }
2326
+
2327
+ async function dismissRequestFromCard(item, eventId) {
2328
+ const requestId = item.dataset.requestId;
2329
+ if (!requestId) return;
2330
+ const live = state.requestCards.get(requestId);
2331
+ // Already done, set aside or gone: ✕ only hides this card from this chat.
2332
+ if (live && (live.found === false || live.lifecycle)) {
2333
+ rememberHiddenRequestCard(eventId, true);
2334
+ item.hidden = true;
2335
+ return;
2336
+ }
2337
+ const hide = item.querySelector('.ai-chat-request-dismiss');
2338
+ if (hide) hide.disabled = true;
2339
+ item.querySelector('.ai-chat-request-note')?.remove(); // a new try replaces the last failure's note
2340
+ try {
2341
+ const done = await lifecycleCall(requestId, 'dismiss');
2342
+ if (done.ok) {
2343
+ state.requestCards.set(requestId, { id: requestId, found: true, lifecycle: { state: 'dismissed' }, attention: { state: 'not-now', code: 'dismissed', label: 'Dismissed' } });
2344
+ paintRequestCard(item);
2345
+ item.querySelector('.ai-chat-request-undo')?.focus();
2346
+ announce('Request dismissed. Undo is on the card.');
2347
+ return;
2348
+ }
2349
+ if (done.body?.code === 'request-held' && done.body.hold) { askStopThenDismiss(item, done.body.hold); return; }
2350
+ if (done.status === 404 || done.body?.code === 'request-already-set-aside') { void refreshRequestCards({ force: true }); return; }
2351
+ cardNotice(item, done.body?.error || 'FloLess couldn’t dismiss that request. It is still in Requests; try ✕ again.');
2352
+ } catch {
2353
+ cardNotice(item, 'FloLess couldn’t reach the server, so the request was not dismissed. Try ✕ again in a moment.');
2354
+ } finally {
2355
+ if (hide) hide.disabled = false;
2356
+ }
2357
+ }
2358
+
2359
+ /** A failure said where the person is looking (on the card) as well as to a screen reader: never only one of the two. */
2360
+ function cardNotice(item, text) {
2361
+ item.querySelector('.ai-chat-request-note')?.remove();
2362
+ const note = document.createElement('p');
2363
+ note.className = 'ai-chat-request-note'; note.setAttribute('role', 'status'); note.textContent = text;
2364
+ item.append(note);
2365
+ announce(text);
2366
+ }
2367
+
2368
+ /** The AI is working on it: ask - stop that work and dismiss, or keep the request. Nothing happened yet. */
2369
+ function askStopThenDismiss(item, hold) {
2370
+ item.querySelector('.ai-chat-request-ask')?.remove();
2371
+ const ask = document.createElement('div'); ask.className = 'ai-chat-request-ask'; ask.setAttribute('role', 'group'); ask.setAttribute('aria-label', 'This request is being worked on');
2372
+ // Escape means Keep it: the safe default.
2373
+ ask.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.stopPropagation(); ask.remove(); item.querySelector('.ai-chat-request-dismiss')?.focus(); } });
2374
+ const why = document.createElement('p'); why.textContent = `${hold.why || 'The AI is working on this request.'} Nothing was changed.`;
2375
+ const row = document.createElement('div'); row.className = 'ai-chat-request-ask-actions';
2376
+ const keep = button('Keep it', `shell.chat-request-keep#${item.dataset.requestId || 'linked request'}`);
2377
+ keep.addEventListener('click', () => { ask.remove(); item.querySelector('.ai-chat-request-dismiss')?.focus(); });
2378
+ row.append(keep);
2379
+ const stop = hold.stop;
2380
+ if (stop) {
2381
+ const go = button('Stop it and dismiss', `shell.chat-request-stop-dismiss#${item.dataset.requestId || 'linked request'}`, 'danger');
2382
+ go.addEventListener('click', async () => {
2383
+ go.disabled = true; keep.disabled = true;
2384
+ let stopped = true; // a stale stop means the work had already ended or changed: never claimed as "stopped"
2385
+ try {
2386
+ if (stop.kind === 'chat') {
2387
+ await request(`/api/chat/conversations/${encodeURIComponent(stop.chatId)}/stop`, { method: 'POST',
2388
+ body: JSON.stringify({ owner: stop.owner, expectTurnId: stop.turnId || undefined }) });
2389
+ } else if (stop.kind === 'wait') {
2390
+ await request(`/api/requests/${encodeURIComponent(stop.requestId)}/run/stop`, { method: 'POST', body: JSON.stringify({ waitId: stop.waitId }) });
2391
+ } else {
2392
+ await request(`/api/requests/${encodeURIComponent(stop.requestId)}/run/stop`, { method: 'POST', body: JSON.stringify(stop.leaseId ? { expectLeaseId: stop.leaseId } : {}) });
2393
+ }
2394
+ } catch (error) {
2395
+ if (error?.code !== 'stop-stale') { why.textContent = 'FloLess couldn’t stop that work, so the request was not dismissed.'; go.disabled = false; keep.disabled = false; return; }
2396
+ stopped = false;
2397
+ }
2398
+ const again = await lifecycleCall(item.dataset.requestId, 'dismiss').catch(() => null);
2399
+ if (again?.ok) {
2400
+ ask.remove();
2401
+ state.requestCards.set(item.dataset.requestId, { id: item.dataset.requestId, found: true, lifecycle: { state: 'dismissed' }, attention: { state: 'not-now', code: 'dismissed', label: 'Dismissed' } });
2402
+ paintRequestCard(item);
2403
+ item.querySelector('.ai-chat-request-undo')?.focus();
2404
+ } else {
2405
+ // A stop that went through is said, so the person does not think the AI is still working; a stale one is not claimed.
2406
+ why.textContent = again?.body?.code === 'request-held'
2407
+ ? (stopped ? 'The work was stopped and is still winding down. Try again in a moment.' : 'Something is still working on this request. Try again in a moment.')
2408
+ : `${stopped ? 'The work was stopped, but the request' : 'The request'} couldn’t be set aside. It is still in Requests; try again.`;
2409
+ go.disabled = false; keep.disabled = false;
2410
+ }
2411
+ });
2412
+ row.append(go);
2413
+ }
2414
+ ask.append(why, row);
2415
+ item.append(ask);
2416
+ keep.focus();
2417
+ }
2418
+
2419
+ async function restoreRequestFromCard(item) {
2420
+ const requestId = item.dataset.requestId;
2421
+ const undo = item.querySelector('.ai-chat-request-undo');
2422
+ if (undo) undo.disabled = true;
2423
+ item.querySelector('.ai-chat-request-note')?.remove();
2424
+ try {
2425
+ const done = await lifecycleCall(requestId, 'restore');
2426
+ 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; }
2427
+ rememberHiddenRequestCard(item.dataset.cardEventId, false);
2428
+ await refreshRequestCards({ force: true });
2429
+ } catch {
2430
+ cardNotice(item, 'FloLess couldn’t reach the server, so the request was not put back. Try Undo again in a moment.');
2431
+ } finally { if (undo) undo.disabled = false; }
2432
+ }
2433
+
2209
2434
  // #1907: the plain name of one of the person's connectors — the same rule the server words its cards with.
2210
2435
  function connectorLabel(connector) {
2211
2436
  // A Claude.ai connector is named "claude.ai <Name>"; the prefix names the channel, not the connector.
@@ -2223,7 +2448,7 @@
2223
2448
  item.dataset.eventSequence = String(event.sequence);
2224
2449
  item.dataset.eventId = event.eventId;
2225
2450
  const label = document.createElement('strong');
2226
- label.textContent = 'Allowed for this chat';
2451
+ label.textContent = autoReceiptLabel(event);
2227
2452
  const connector = event.payload.connector;
2228
2453
  const tool = typeof connector.tool === 'string' ? connector.tool : 'a tool';
2229
2454
  item.append(label, document.createTextNode(` · ${connectorLabel(connector)} ran ${tool}`));
@@ -2236,14 +2461,16 @@
2236
2461
  // #2037: a Codex auto-review decision is a receipt, not a failure: approved is information, held back is a notice.
2237
2462
  const review = event.payload?.tool === 'auto-review' ? event.payload.decision : null;
2238
2463
  // #2035: a step declined because nobody was watching a scheduled run is a notice the person reads later, not an error.
2239
- const unattended = event.payload?.tool === 'unattended-decline';
2464
+ const unattended = event.payload?.tool === 'unattended-decline' || event.payload?.tool === 'unattended-question';
2240
2465
  // #2058: an account command Codex ran without asking FloLess already ran; its line says the result is unchecked.
2241
2466
  const unchecked = event.payload?.tool === 'unchecked-command';
2242
2467
  item.className = review === 'approved' ? 'ai-chat-event auto-review' : review || unattended || unchecked ? 'ai-chat-event auto-review held' : 'ai-chat-event error';
2243
2468
  item.dataset.eventSequence = String(event.sequence);
2244
2469
  item.dataset.eventId = event.eventId;
2245
2470
  const label = document.createElement('strong');
2246
- label.textContent = review === 'approved' ? 'Auto-approved' : review ? 'Held back' : unattended ? 'Declined' : unchecked ? 'Not checked' : 'Not done';
2471
+ // #2223: a question the AI asked while nobody was watching went unanswered, not declined.
2472
+ label.textContent = review === 'approved' ? 'Auto-approved' : review ? 'Held back'
2473
+ : unattended ? (event.payload?.tool === 'unattended-question' ? 'Not asked' : 'Declined') : unchecked ? 'Not checked' : 'Not done';
2247
2474
  item.append(label, document.createTextNode(` · ${event.payload.message}`));
2248
2475
  return item;
2249
2476
  }
@@ -2260,6 +2487,27 @@
2260
2487
  return item;
2261
2488
  }
2262
2489
 
2490
+ /** The receipt label of an action a grant approved without a card: which grant (this reply, or this conversation). */
2491
+ function autoReceiptLabel(event) {
2492
+ return event.payload?.scope === 'request' ? 'Allowed for this request' : 'Allowed for this conversation';
2493
+ }
2494
+
2495
+ /** Epic #2185 Slice A: every other action a grant approved automatically leaves one line saying what covered it. */
2496
+ function renderAutoReceipt(event) {
2497
+ const item = document.createElement('div');
2498
+ item.className = 'ai-chat-event connector';
2499
+ item.dataset.eventSequence = String(event.sequence);
2500
+ item.dataset.eventId = event.eventId;
2501
+ const label = document.createElement('strong');
2502
+ label.textContent = autoReceiptLabel(event);
2503
+ const payload = event.payload || {};
2504
+ const what = payload.scopeAdd ? `Added ${payload.scopeAdd.target?.kind || 'project'} “${payload.scopeAdd.label}” to this chat`
2505
+ : payload.create ? `Created the workflow “${payload.create.name}”`
2506
+ : String(payload.summary || payload.grantLabel || 'An action').slice(0, 200);
2507
+ item.append(label, document.createTextNode(` · ${what}${payload.grantLabel && !payload.scopeAdd && !payload.create ? ` (${payload.grantLabel})` : ''}`));
2508
+ return item;
2509
+ }
2510
+
2263
2511
  function renderChangeReceipt(event) {
2264
2512
  const item = document.createElement('div');
2265
2513
  item.className = 'ai-chat-event connector';
@@ -2272,7 +2520,7 @@
2272
2520
  item.append(label, document.createTextNode(' · FloLess could not confirm this change could still go ahead. Ask the AI to check the current files and scope, then try again.'));
2273
2521
  return item;
2274
2522
  }
2275
- label.textContent = event.payload.coveredBy === 'create' ? 'Part of creating the workflow' : 'Allowed for this chat';
2523
+ label.textContent = event.payload.coveredBy === 'create' ? 'Part of creating the workflow' : autoReceiptLabel(event);
2276
2524
  // The receipt records the approval FloLess gave; whether the file was then written is the AI's own reply to report.
2277
2525
  const owners = Array.isArray(change?.owners) ? change.owners : [];
2278
2526
  const paths = owners.flatMap((owner) => owner.paths || []);
@@ -2291,19 +2539,27 @@
2291
2539
  */
2292
2540
  const connectionCards = new Map();
2293
2541
  const CONNECTION_CARDS_KEPT = 200;
2294
- const connectionLive = { services: null, loading: false, loadedAt: 0, error: '' };
2542
+ const connectionLive = { services: null, loading: false, loadedAt: 0, error: '', again: false };
2295
2543
  const connectionsApi = () => window.flolessConnections || null;
2296
2544
 
2297
- /** Re-reads what is connected (and the latest checks) when the copy on screen is older than `maxAgeMs`. */
2298
- function refreshConnectionLive(maxAgeMs = 15000) {
2545
+ /**
2546
+ * Re-reads what is connected (and the latest checks) when the copy on screen is older than `maxAgeMs`.
2547
+ * `force` (#2185: the server said a connection, credential, install or account choice just changed) cannot be skipped
2548
+ * because a read is already running: that read may have started before the change, so one more runs right after it.
2549
+ */
2550
+ function refreshConnectionLive(maxAgeMs = 15000, force = false) {
2299
2551
  const api = connectionsApi();
2300
- if (!api || connectionLive.loading) return;
2301
- if (connectionLive.loadedAt && Date.now() - connectionLive.loadedAt < maxAgeMs) return;
2552
+ if (!api) return;
2553
+ if (connectionLive.loading) { if (force) connectionLive.again = true; return; }
2554
+ if (!force && connectionLive.loadedAt && Date.now() - connectionLive.loadedAt < maxAgeMs) return;
2302
2555
  connectionLive.loading = true;
2303
2556
  Promise.all([api.loadServices(), api.loadReceipts()])
2304
2557
  .then(([services]) => { connectionLive.services = services; connectionLive.error = ''; })
2305
2558
  .catch((error) => { connectionLive.error = api.sentenceOf(error); })
2306
- .finally(() => { connectionLive.loading = false; connectionLive.loadedAt = Date.now(); repaintConnectionCards(); });
2559
+ .finally(() => {
2560
+ connectionLive.loading = false; connectionLive.loadedAt = Date.now(); repaintConnectionCards();
2561
+ if (connectionLive.again) { connectionLive.again = false; refreshConnectionLive(0, true); }
2562
+ });
2307
2563
  }
2308
2564
 
2309
2565
  function repaintConnectionCards() {
@@ -2314,12 +2570,20 @@
2314
2570
  if (next !== old) {
2315
2571
  const focused = old.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
2316
2572
  old.replaceWith(next);
2317
- if (focused) [...next.querySelectorAll('[data-command-id]')].find((node) => node.dataset.commandId === focused && !node.disabled)?.focus({ preventScroll: true });
2573
+ if (focused) {
2574
+ const same = [...next.querySelectorAll('[data-command-id]')].find((node) => node.dataset.commandId === focused && !node.disabled);
2575
+ // The control under the keyboard is gone (a card that finished loses its Not now): keep the keyboard on the card.
2576
+ if (same) same.focus({ preventScroll: true });
2577
+ else { next.tabIndex = -1; next.focus({ preventScroll: true }); }
2578
+ }
2318
2579
  }
2319
2580
  }
2320
2581
  }
2321
2582
 
2322
2583
  window.addEventListener('focus', () => { if (ui.feed?.querySelector('.ai-chat-connection-card[data-proposal-id]')) refreshConnectionLive(0); });
2584
+ // #2185: Integrations is a modal, so coming back from it never refocuses the window. The server says when something
2585
+ // was connected, a credential changed or an account was chosen, and the cards tick themselves off.
2586
+ window.addEventListener('floless:connections-changed', () => { if (ui.feed?.querySelector('.ai-chat-connection-card[data-proposal-id]')) refreshConnectionLive(0, true); });
2323
2587
 
2324
2588
  /**
2325
2589
  * Did the person answer Not now to this target? Dismissal is per target. The newest Not now / Show again in the
@@ -2445,6 +2709,7 @@
2445
2709
  };
2446
2710
  const services = connectionLive.services;
2447
2711
  let keyCode = null;
2712
+ let connected = false;
2448
2713
  if (payload.targetKind === 'host') {
2449
2714
  if (payload.checkAgent && api) {
2450
2715
  actions.append(check(null, {}));
@@ -2523,6 +2788,15 @@
2523
2788
  stateLine.textContent = `FloLess couldn’t read which account it uses for ${name}. Open Integrations to choose it again.`;
2524
2789
  actions.append(integrations('Open Integrations', 'shell.chat-connection-change-account', `Opens Integrations at ${name}.`, true));
2525
2790
  } else if (service.choice?.source === 'floless') {
2791
+ // #2185: connected and an account chosen is the finished state: say what was connected, to which account, and stop asking.
2792
+ connected = true;
2793
+ const accountLabel = service.choice.alias ? service.choice.alias : 'main account';
2794
+ card.classList.add('is-connected');
2795
+ const tick = document.createElement('span'); tick.setAttribute('aria-hidden', 'true'); tick.textContent = '✓ ';
2796
+ title.replaceChildren(tick, document.createTextNode(`${name} connected · ${accountLabel}`));
2797
+ // The card was asking a moment ago and now is not: say so once to a screen reader (an old card drawn already done stays quiet).
2798
+ if (entry.seenOpen && !entry.announcedConnected) announce(`${name} connected, using ${accountLabel}.`);
2799
+ entry.announcedConnected = true;
2526
2800
  stateLine.textContent = `FloLess uses ${service.choice.alias ? service.choice.alias : 'the default account'} for ${name}.`;
2527
2801
  // The card checks the CHOSEN account at the choice it was painted on: the server refuses a card that is out of date.
2528
2802
  if (payload.checkAgent && alias !== undefined) {
@@ -2542,7 +2816,8 @@
2542
2816
  notNow.dataset.tip = `Sets this suggestion aside. The AI won’t suggest ${name} again in this chat unless you choose Show again.`;
2543
2817
  notNow.disabled = entry.busy;
2544
2818
  notNow.addEventListener('click', () => { void setConnectionDismissed(event, true); });
2545
- actions.append(notNow);
2819
+ // Nothing is left to set aside once it is connected (#2185); Change account is still there.
2820
+ if (!connected) { actions.append(notNow); entry.seenOpen = true; }
2546
2821
  card.append(stateLine, ...(keyCode ? [keyCode] : []), actions, confirmHost, receiptHost, said, error);
2547
2822
  return card;
2548
2823
  }
@@ -2579,6 +2854,331 @@
2579
2854
  }
2580
2855
  }
2581
2856
 
2857
+ // ── #2247: FloLess actions the AI ran or suggested ────────────────────────────────────────────────────────────
2858
+ // A proposal card asks the person to confirm one action (a real run, a change suggested from a Guide or Read only
2859
+ // chat), or — for something only a person does — opens the screen where they do it. Nothing runs from the AI's
2860
+ // side: Confirm is the person's click, and the server re-checks that the approved version is still the one shown.
2861
+ const actionCards = new Map();
2862
+ const ACTION_CARDS_KEPT = 200;
2863
+ const ACTION_CONFIRM_VERBS = { 'workflows.run': 'Run it', 'routines.run': 'Run it', 'projects.archive': 'Archive it',
2864
+ 'projects.unarchive': 'Bring it back', 'workflows.stop': 'Stop it' };
2865
+ const ACTION_EYEBROWS = { write: 'Suggested change', destructive: 'Needs your OK', 'human-only': 'Your decision' };
2866
+ const ACTION_FINAL = new Set(['done', 'failed', 'cancelled', 'declined', 'expired', 'superseded', 'unknown']);
2867
+
2868
+ /** The newest state the conversation records for a proposal: its card event, then its updates, then this tab's own answer. */
2869
+ function actionProposalState(proposalId) {
2870
+ const entry = actionCards.get(proposalId);
2871
+ let latest = null;
2872
+ for (const event of state.events) {
2873
+ if (event.type === 'action-proposal-update' && event.payload?.proposalId === proposalId) latest = event.payload;
2874
+ }
2875
+ const fromServer = latest ? { state: latest.state, result: latest.result || null, supersededBy: latest.supersededBy || null, next: latest.next || null } : null;
2876
+ // A click's own answer is newer than the journal until the journal catches up; a final journal state always wins.
2877
+ if (entry?.local && !(fromServer && ACTION_FINAL.has(fromServer.state))) return entry.local;
2878
+ return fromServer || { state: 'proposed', result: null, supersededBy: null };
2879
+ }
2880
+
2881
+ function renderActionProposal(event) {
2882
+ const payload = event.payload || {};
2883
+ const proposalId = String(payload.proposalId || event.eventId || '');
2884
+ let entry = actionCards.get(proposalId);
2885
+ if (!entry) {
2886
+ entry = { node: null, signature: '', busy: '', error: '', local: null };
2887
+ actionCards.set(proposalId, entry);
2888
+ while (actionCards.size > ACTION_CARDS_KEPT) actionCards.delete(actionCards.keys().next().value);
2889
+ }
2890
+ const current = actionProposalState(proposalId);
2891
+ const signature = JSON.stringify([event.eventId, current.state, current.result?.message || null, current.supersededBy, current.next || null, entry.busy, entry.error]);
2892
+ if (entry.node && entry.signature === signature) return entry.node;
2893
+ entry.node = paintActionProposal(event, payload, proposalId, entry, current);
2894
+ entry.signature = signature;
2895
+ return entry.node;
2896
+ }
2897
+
2898
+ function repaintActionCards(focusProposal) {
2899
+ for (const old of ui.feed?.querySelectorAll('.ai-chat-action-card[data-proposal-id]') || []) {
2900
+ const event = state.events.find((known) => known.eventId === old.dataset.eventId);
2901
+ if (!event) continue;
2902
+ const next = renderActionProposal(event);
2903
+ if (next !== old) old.replaceWith(next);
2904
+ }
2905
+ if (focusProposal) {
2906
+ const card = ui.feed?.querySelector(`.ai-chat-action-card[data-proposal-id="${CSS.escape(focusProposal)}"]`);
2907
+ const target = card?.querySelector('[data-command-id^="shell.chat-action-stop"]') || card?.querySelector('.ai-chat-action-status');
2908
+ target?.focus({ preventScroll: true });
2909
+ }
2910
+ }
2911
+
2912
+ /** A card button. Its Instructor instance is the proposal (two cards for one action never share a carrier), and it
2913
+ * is narrated by what the card asks, e.g. "Run dummy-report with its default inputs". */
2914
+ function actionButton(label, commandId, proposalId, summary, className = '') {
2915
+ const control = button(label, `${commandId}#${proposalId}`, className);
2916
+ control.dataset.commandInstanceLabel = summary;
2917
+ return control;
2918
+ }
2919
+
2920
+ /** Open the screen a human-only action names, or the one showing what a finished action made. Nothing runs. */
2921
+ async function openActionScreen(screen) {
2922
+ if (screen?.view === 'page' && screen.pageHome && screen.pageId && typeof window.flolessPages?.open === 'function') {
2923
+ return await window.flolessPages.open(screen.pageHome, screen.pageId);
2924
+ }
2925
+ if (screen?.view === 'chat' && screen.chatId && screen.owner) {
2926
+ await openConversation(screen.chatId, { owner: screen.owner });
2927
+ return state.chat?.chatId === screen.chatId;
2928
+ }
2929
+ if (screen?.view === 'workflow-report' && screen.workflowId && typeof window.flolessBridge?.openAppReport === 'function') {
2930
+ await window.flolessBridge.openAppReport(screen.workflowId, screen.runId || null); return true;
2931
+ }
2932
+ if (screen?.view === 'workflow' && screen.workflowId && typeof window.flolessBridge?.openApp === 'function') {
2933
+ await window.flolessBridge.openApp(screen.workflowId); return true;
2934
+ }
2935
+ if (screen?.view === 'project' && screen.projectId && typeof window.flolessWorkspaces?.openChatOwner === 'function') {
2936
+ await window.flolessWorkspaces.openChatOwner({ kind: 'project', projectId: screen.projectId }); return true;
2937
+ }
2938
+ if (['workspaces', 'workflows'].includes(screen?.view) && typeof window.flolessWorkspaces?.setMode === 'function') {
2939
+ await window.flolessWorkspaces.setMode(screen.view); return true;
2940
+ }
2941
+ return false;
2942
+ }
2943
+
2944
+ async function sendActionProposal(proposalId, verb) {
2945
+ const response = await fetch(`/api/actions/proposals/${encodeURIComponent(proposalId)}/${verb}`, {
2946
+ method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, body: '{}',
2947
+ });
2948
+ let body = null;
2949
+ try { body = await response.json(); } catch { body = null; }
2950
+ return { ok: response.ok && body?.ok === true, body: body || {} };
2951
+ }
2952
+
2953
+ async function actOnProposal(event, proposalId, verb) {
2954
+ const entry = actionCards.get(proposalId);
2955
+ if (!entry || entry.busy) return;
2956
+ const title = String(event.payload?.title || 'the action');
2957
+ entry.busy = verb; entry.error = '';
2958
+ repaintActionCards();
2959
+ let focus = proposalId;
2960
+ try {
2961
+ const { ok, body } = await sendActionProposal(proposalId, verb);
2962
+ if (ok) {
2963
+ entry.local = { state: body.proposal?.state || (verb === 'decline' ? 'declined' : 'executing'), result: body.proposal?.result || null, supersededBy: null };
2964
+ announce(verb === 'confirm' ? `${title}: started.` : verb === 'decline' ? `Not now: ${title}.` : `Asked ${title} to stop.`);
2965
+ } else if (body.fresh) {
2966
+ // The target changed or the offer ended: the old card says so, and a fresh card shows the current state.
2967
+ entry.local = { state: body.proposal?.state || 'superseded', result: null, supersededBy: body.fresh.id };
2968
+ announce(body.error || 'It changed after it was suggested. A new card shows the current state.');
2969
+ } else {
2970
+ if (body.proposal?.state) entry.local = { state: body.proposal.state, result: body.proposal.result || null, supersededBy: body.proposal.supersededBy || null };
2971
+ entry.error = body.error || 'FloLess could not do that just now. Try again in a moment.';
2972
+ }
2973
+ } catch {
2974
+ entry.error = 'FloLess could not be reached. Check that it is still running, then try again.';
2975
+ } finally {
2976
+ entry.busy = '';
2977
+ repaintActionCards(focus);
2978
+ }
2979
+ }
2980
+
2981
+ function paintActionProposal(event, payload, proposalId, entry, current) {
2982
+ const actionId = String(payload.actionId || 'action');
2983
+ const title = String(payload.title || 'A FloLess action');
2984
+ const summaryText = String(payload.summary || title);
2985
+ const risk = ['write', 'destructive', 'human-only'].includes(payload.risk) ? payload.risk : 'write';
2986
+ const card = document.createElement('section');
2987
+ card.className = `ai-chat-filter-card ai-chat-action-card risk-${risk}`;
2988
+ card.dataset.eventId = event.eventId;
2989
+ card.dataset.eventSequence = String(event.sequence);
2990
+ card.dataset.proposalId = proposalId;
2991
+ card.dataset.state = current.state;
2992
+ card.setAttribute('role', 'group');
2993
+ const status = document.createElement('p');
2994
+ status.className = 'ai-chat-filter-note ai-chat-action-status';
2995
+ status.setAttribute('role', 'status');
2996
+ status.tabIndex = -1;
2997
+ const titleId = `chat-action-title-${proposalId}`;
2998
+ card.setAttribute('aria-labelledby', titleId);
2999
+
3000
+ // Finished, set aside or replaced: one quiet line that says honestly what happened.
3001
+ const collapsed = {
3002
+ declined: `Not now: ${title}`,
3003
+ expired: `Offer ended: ${title}. Ask again if you still want it.`,
3004
+ superseded: `Replaced by a newer suggestion: ${title}`,
3005
+ cancelled: `Stopped: ${title}. Work already sent to the host may remain.`,
3006
+ }[current.state];
3007
+ if (collapsed) {
3008
+ card.classList.add('is-collapsed');
3009
+ const line = document.createElement('p');
3010
+ line.className = 'ai-chat-action-line';
3011
+ line.id = titleId;
3012
+ line.textContent = collapsed;
3013
+ card.append(line);
3014
+ return card;
3015
+ }
3016
+
3017
+ const head = document.createElement('div');
3018
+ head.className = 'ai-chat-filter-card-head';
3019
+ const eyebrow = document.createElement('span');
3020
+ eyebrow.className = 'guide-move-eyebrow';
3021
+ eyebrow.textContent = ACTION_EYEBROWS[risk];
3022
+ const strong = document.createElement('strong');
3023
+ strong.id = titleId;
3024
+ strong.textContent = title;
3025
+ const named = document.createElement('div');
3026
+ named.className = 'ai-chat-action-named';
3027
+ named.append(eyebrow, strong);
3028
+ head.append(named);
3029
+ const badgeText = { executing: 'Running', done: 'Done', failed: 'Not done', unknown: 'Unknown' }[current.state];
3030
+ if (badgeText) {
3031
+ const badge = document.createElement('span');
3032
+ badge.className = 'ai-chat-filter-state';
3033
+ badge.textContent = badgeText;
3034
+ head.append(badge);
3035
+ }
3036
+ card.append(head);
3037
+ if (payload.changedNote) {
3038
+ const changed = document.createElement('p');
3039
+ changed.className = 'ai-chat-filter-note ai-chat-action-changed';
3040
+ changed.textContent = String(payload.changedNote);
3041
+ card.append(changed);
3042
+ }
3043
+ const summary = document.createElement('p');
3044
+ summary.className = 'ai-chat-action-summary';
3045
+ summary.textContent = summaryText;
3046
+ card.append(summary);
3047
+
3048
+ if (current.state === 'done') {
3049
+ card.classList.add('is-done');
3050
+ status.textContent = current.next ? 'Done. Its result is ready to view.' : String(payload.doneNote || 'Done.');
3051
+ if (current.next) {
3052
+ // What the finished action made (a run's report): opening it only shows it, it runs nothing again.
3053
+ const actions = document.createElement('div');
3054
+ actions.className = 'ai-chat-filter-actions';
3055
+ const view = actionButton(String(current.next.label || 'View result'), 'shell.chat-action-view', proposalId, summaryText);
3056
+ view.dataset.tip = 'Opens what this made. Nothing runs again.';
3057
+ view.addEventListener('click', async () => {
3058
+ entry.error = '';
3059
+ try { if (!(await openActionScreen(current.next))) entry.error = 'FloLess couldn’t open that from here. Open the workflow from Workflows instead.'; }
3060
+ catch (error) { entry.error = error?.message || 'FloLess couldn’t open that from here.'; }
3061
+ if (entry.error) status.textContent = entry.error;
3062
+ });
3063
+ actions.append(view);
3064
+ card.append(actions);
3065
+ }
3066
+ card.append(status);
3067
+ return card;
3068
+ }
3069
+ if (current.state === 'failed') {
3070
+ card.classList.add('is-failed');
3071
+ status.textContent = `${current.result?.message || 'It did not complete.'} You can ask the AI to suggest it again.`;
3072
+ card.append(status);
3073
+ return card;
3074
+ }
3075
+ if (current.state === 'unknown') {
3076
+ status.textContent = 'FloLess restarted while this was running, so how it ended is not known. Check the result, and ask the AI to suggest it again if you still want it.';
3077
+ card.append(status);
3078
+ return card;
3079
+ }
3080
+ if (payload.riskReason) {
3081
+ const reason = document.createElement('p');
3082
+ reason.className = 'ai-chat-filter-note ai-chat-action-reason';
3083
+ reason.textContent = String(payload.riskReason);
3084
+ card.append(reason);
3085
+ }
3086
+ if (payload.why) {
3087
+ const why = document.createElement('p');
3088
+ why.className = 'ai-chat-filter-why ai-chat-action-why';
3089
+ why.textContent = `Why: ${String(payload.why)}`;
3090
+ card.append(why);
3091
+ }
3092
+ const actions = document.createElement('div');
3093
+ actions.className = 'ai-chat-filter-actions';
3094
+ if (current.state === 'executing') {
3095
+ status.textContent = actionId === 'workflows.run' || actionId === 'routines.run' ? 'Running…' : 'Working…';
3096
+ if (actionId === 'workflows.run') {
3097
+ const stop = actionButton('Stop', 'shell.chat-action-stop', proposalId, summaryText);
3098
+ stop.dataset.tip = 'Asks the run to stop. Work already sent to the host may remain.';
3099
+ stop.disabled = Boolean(entry.busy);
3100
+ stop.addEventListener('click', () => { void actOnProposal(event, proposalId, 'cancel'); });
3101
+ actions.append(stop);
3102
+ }
3103
+ card.append(actions, status);
3104
+ return card;
3105
+ }
3106
+ if (risk === 'human-only') {
3107
+ const screen = payload.screen || {};
3108
+ const open = actionButton(String(screen.label || 'Open it'), 'shell.chat-action-open', proposalId, summaryText, 'ai-chat-filter-apply');
3109
+ open.dataset.tip = 'Opens the screen where you do this yourself. Nothing runs from this card.';
3110
+ open.addEventListener('click', async () => {
3111
+ entry.error = '';
3112
+ try { if (!(await openActionScreen(screen))) entry.error = screen.view === 'chat'
3113
+ ? 'FloLess couldn’t open that conversation. Find it in AI Chat history and try again.'
3114
+ : 'FloLess couldn’t open that from here. Open it from Workflows or Workspaces instead.'; }
3115
+ catch (error) { entry.error = error?.message || 'FloLess couldn’t open that from here.'; }
3116
+ if (entry.error) { status.textContent = entry.error; }
3117
+ });
3118
+ const later = actionButton('Not now', 'shell.chat-action-not-now', proposalId, summaryText);
3119
+ later.dataset.tip = 'Sets this suggestion aside. Nothing changes.';
3120
+ later.disabled = Boolean(entry.busy);
3121
+ later.addEventListener('click', () => { void actOnProposal(event, proposalId, 'decline'); });
3122
+ actions.append(later, open);
3123
+ const note = document.createElement('p');
3124
+ note.className = 'ai-chat-filter-note';
3125
+ note.textContent = 'Only you can do this. Nothing runs from here.';
3126
+ status.textContent = entry.error;
3127
+ card.append(actions, note, status);
3128
+ return card;
3129
+ }
3130
+ const later = actionButton('Not now', 'shell.chat-action-not-now', proposalId, summaryText);
3131
+ later.dataset.tip = 'Sets this suggestion aside. Nothing runs.';
3132
+ later.disabled = Boolean(entry.busy);
3133
+ later.addEventListener('click', () => { void actOnProposal(event, proposalId, 'decline'); });
3134
+ const confirm = actionButton(entry.busy === 'confirm' ? 'Starting…' : (ACTION_CONFIRM_VERBS[actionId] || 'Do it'), 'shell.chat-action-confirm', proposalId, summaryText, 'ai-chat-filter-apply');
3135
+ confirm.dataset.tip = risk === 'destructive' ? 'Runs it now, for real. FloLess checks first that nothing changed since this was suggested.'
3136
+ : 'Makes this change now. FloLess checks first that nothing changed since this was suggested.';
3137
+ confirm.disabled = Boolean(entry.busy);
3138
+ if (entry.busy === 'confirm') confirm.setAttribute('aria-busy', 'true');
3139
+ confirm.addEventListener('click', () => { void actOnProposal(event, proposalId, 'confirm'); });
3140
+ actions.append(later, confirm);
3141
+ const meta = document.createElement('p');
3142
+ meta.className = 'ai-chat-filter-note ai-chat-action-meta';
3143
+ meta.textContent = payload.revision === 'bound' ? 'Uses the approved version as it is now; if it changes first, you will be asked again.'
3144
+ : 'Acts on things as they are when you confirm.';
3145
+ status.textContent = entry.error;
3146
+ card.append(actions, meta, status);
3147
+ return card;
3148
+ }
3149
+
3150
+ /** One line per action the AI ran itself from this conversation: what it was, and how it ended. */
3151
+ function renderActionRow(event) {
3152
+ const payload = event.payload || {};
3153
+ const row = document.createElement('div');
3154
+ const outcome = payload.outcome === 'ok' ? 'ok' : payload.outcome === 'cancelled' ? 'stopped' : 'failed';
3155
+ row.className = `ai-chat-action-row is-${outcome}`;
3156
+ row.dataset.eventId = event.eventId;
3157
+ row.dataset.eventSequence = String(event.sequence);
3158
+ const glyph = document.createElement('span');
3159
+ glyph.className = 'ai-chat-action-row-glyph';
3160
+ glyph.setAttribute('aria-hidden', 'true');
3161
+ glyph.textContent = outcome === 'ok' ? '✓' : outcome === 'stopped' ? '■' : '!';
3162
+ const verb = document.createElement('span');
3163
+ verb.className = 'ai-chat-action-row-verb';
3164
+ verb.textContent = payload.risk === 'read' ? 'Read' : 'Changed';
3165
+ const title = document.createElement('span');
3166
+ title.className = 'ai-chat-action-row-title';
3167
+ title.textContent = String(payload.title || payload.actionId || 'A FloLess action');
3168
+ const state = document.createElement('span');
3169
+ state.className = 'ai-chat-filter-state';
3170
+ state.textContent = outcome === 'ok' ? 'Done' : outcome === 'stopped' ? 'Stopped' : 'Not done';
3171
+ row.append(glyph, verb, title, state);
3172
+ if (outcome === 'failed' && payload.message) {
3173
+ const reason = document.createElement('span');
3174
+ reason.className = 'ai-chat-action-row-reason';
3175
+ reason.textContent = String(payload.message);
3176
+ row.append(reason);
3177
+ }
3178
+ row.setAttribute('aria-label', `${verb.textContent}: ${title.textContent}, ${state.textContent.toLowerCase()}${outcome === 'failed' && payload.message ? `. ${payload.message}` : ''}`);
3179
+ return row;
3180
+ }
3181
+
2582
3182
  /** The result of a check the person approved in chat: the same receipt Discover and Integrations show. */
2583
3183
  function renderConnectionCheck(event) {
2584
3184
  const payload = event.payload || {};
@@ -2634,7 +3234,7 @@
2634
3234
  item.dataset.eventSequence = String(event.sequence);
2635
3235
  item.dataset.eventId = event.eventId;
2636
3236
  const label = document.createElement('strong');
2637
- label.textContent = 'Allowed for this chat';
3237
+ label.textContent = autoReceiptLabel(event);
2638
3238
  const name = String(event.payload.connectionCheck?.name || event.payload.connectionCheck?.agent || 'a connection');
2639
3239
  item.append(label, document.createTextNode(` · checked ${name}`));
2640
3240
  return item;
@@ -2669,20 +3269,36 @@
2669
3269
  if (event.type === 'user-message') return withFilterNotShared(renderMessage(event, 'user', payloadText(event)), event);
2670
3270
  if (event.type === 'filter-proposal') return renderServerProposal(event);
2671
3271
  if (event.type === 'filter-proposal-update') return null;
3272
+ // #2247: a FloLess action the AI suggested (a card) or ran (a line); an update only repaints its card.
3273
+ if (event.type === 'action-proposal') return renderActionProposal(event);
3274
+ if (event.type === 'action-proposal-update') return null;
3275
+ if (event.type === 'action-call') return renderActionRow(event);
3276
+ // #2255: a change the AI made to the model view; its outcome repaints the same line.
3277
+ if (event.type === 'view-command') return renderViewCommand(event);
3278
+ if (event.type === 'view-command-update') return null;
2672
3279
  // #1900: a connection the AI suggested, the result of a check it asked for, and a check run under "Allow for this chat".
2673
3280
  if (event.type === 'connection-proposal') return renderConnectionProposal(event);
2674
3281
  if (event.type === 'connection-proposal-update') return null;
2675
3282
  if (event.type === 'connection-check') return renderConnectionCheck(event);
2676
3283
  // #2046: a next move the Guide suggested; web/guide.js paints it and owns its button.
2677
3284
  if (event.type === 'next-move') return window.flolessGuide?.renderNextMove?.(event) || null;
3285
+ // #2185: what came of a card's button repaints that card; it is never a line of its own.
3286
+ if (event.type === 'next-move-update') { window.flolessGuide?.applyMoveUpdate?.(event); return null; }
2678
3287
  if (event.type === 'approval-decided' && event.payload?.automatic === true && event.payload?.connectionCheck) return renderConnectionCheckAllowed(event);
3288
+ // #2223 Revision 6: a question whose words already streamed carries only its card (above the message box): no empty bubble.
3289
+ if (event.type === 'assistant-message' && event.payload?.asyncQuestion && !payloadText(event)) return null;
2679
3290
  if (event.type === 'assistant-message') return renderMessage(event, 'assistant', payloadText(event), Boolean(event.payload?.delta));
2680
3291
  // #1907: a connector call that ran under "Allow for this chat" leaves a visible receipt; every other decision is audit only.
2681
3292
  if (event.type === 'approval-decided' && event.payload?.automatic === true && event.payload?.connector) return renderConnectorReceipt(event);
2682
3293
  // #1890 PR 2b: a workspace change that ran under "Allow for this chat", or one FloLess stopped at the last check.
2683
3294
  if (event.type === 'approval-decided' && event.payload?.change && (event.payload?.automatic === true || event.payload?.reason)) return renderChangeReceipt(event);
2684
3295
  // #1890 PR 3a: a decided workflow create stays visible as one line, so a reload never shows it as pending.
2685
- if (event.type === 'approval-decided' && event.payload?.create) return renderCreateReceipt(event);
3296
+ if (event.type === 'approval-decided' && event.payload?.create && !(event.payload?.automatic === true && event.payload?.decision === 'allow')) return renderCreateReceipt(event);
3297
+ // A Tekla read already leaves its own result card, so it gets no second line here.
3298
+ if (event.type === 'approval-decided' && event.payload?.automatic === true && !event.payload?.unattended && event.payload?.decision === 'allow'
3299
+ && !String(event.payload?.tool || '').startsWith('floless_tekla_')) return renderAutoReceipt(event);
3300
+ // #2223: how a question card closed: the person's answer, or why it never reached the AI.
3301
+ if (event.type === 'approval-decided' && event.payload?.kind === 'question') return renderQuestionAnswered(event);
2686
3302
  if (event.type === 'approval-requested' || event.type === 'approval-decided' || event.type === 'state' || event.type === 'followup-status') return null;
2687
3303
  if (event.type === 'tool' && ['agent', 'guide', 'instructor'].includes(event.payload?.tool) && typeof event.payload?.message === 'string') return renderAgentRunLine(event);
2688
3304
  if (event.type === 'tekla-read') return renderTeklaReadEvent(event);
@@ -2794,7 +3410,7 @@
2794
3410
  * Typed text is not in the signature on purpose: it lives in the field and in `drafts`, and a keystroke is not a
2795
3411
  * reason to rebuild. Everything else a card paints from belongs in it.
2796
3412
  */
2797
- const CARD_SIGNATURE_SKIP = new Set(['node', 'nodeSig', 'drafts', 'bulkDraft', 'rowsScroll', 'bodyScroll', 'reloadPending', 'loading']);
3413
+ const CARD_SIGNATURE_SKIP = new Set(['node', 'nodeSig', 'drafts', 'bulkDraft', 'rowsScroll', 'bodyScroll', 'reloadPending', 'loading', 'slotNode', 'slotDrafts', 'slotSig']);
2798
3414
  function cardSignature(entry, eventId, sequence) {
2799
3415
  settleNotSent(entry);
2800
3416
  const sources = [];
@@ -2882,7 +3498,7 @@
2882
3498
 
2883
3499
  function repaintHeightCard(entry) {
2884
3500
  const old = ui.feed?.querySelector(`[data-height-question="${CSS.escape(entry.key)}"]`);
2885
- if (!old) return;
3501
+ if (!old) { drawingSlotRepaint(); return; }
2886
3502
  const focused = old.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
2887
3503
  const caret = focused ? textCaret(document.activeElement) : null;
2888
3504
  const next = rememberCard(entry, paintHeightCard(entry, old.dataset.eventId, old.dataset.eventSequence), old.dataset.eventId, old.dataset.eventSequence);
@@ -2936,209 +3552,10 @@
2936
3552
  }
2937
3553
 
2938
3554
  function paintHeightCard(entry, eventId, sequence) {
2939
- const view = entry.view;
2940
- const card = document.createElement('section');
2941
- card.className = 'ai-chat-filter-card ai-chat-height-card';
2942
- card.dataset.heightQuestion = entry.key;
2943
- card.dataset.eventId = eventId || '';
2944
- card.dataset.eventSequence = sequence || '';
2945
- card.setAttribute('aria-label', view?.n ? `Confirm member heights, question ${view.n}` : 'Confirm member heights');
2946
- const rows = view ? view.ends : [];
2947
- const live = rows.filter((row) => row.status !== 'superseded');
2948
- // A picture-only answer ("see snap") is answered by the person but waits on the READ, which only looks
2949
- // once told; it counts here so Tell the read is offered (E2E #1906).
2950
- const answered = live.filter((row) => row.answer && (row.status === 'confirmed' || row.status === 'typed' || row.status === 'evidence'));
2951
- const open = Boolean(view?.open);
2952
- const allAnswered = live.length > 0 && answered.length === live.length;
2953
- card.dataset.state = !view ? (entry.finished ? 'closed' : 'loading') : !open ? 'closed' : allAnswered ? 'answered' : 'open';
2954
-
2955
- const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
2956
- const title = document.createElement('strong'); title.textContent = 'Confirm member heights';
2957
- const chip = document.createElement('span'); chip.className = 'ai-chat-filter-state';
2958
- chip.textContent = !view ? (entry.finished ? 'closed' : 'loading') : !open ? 'closed' : allAnswered ? 'answered' : 'needs you';
2959
- head.append(title, chip);
2960
- card.append(head);
2961
-
2962
- const note = document.createElement('p'); note.className = 'ai-chat-filter-note';
2963
- note.textContent = !view
2964
- ? (entry.finished ? CARD_FINISHED_TEXT : entry.loadError || 'Loading the heights this read is asking about…')
2965
- : open
2966
- ? (rows.some((row) => row.inModel)
2967
- // #1903: never say "straight into the model" about a member already in it — that answer is proposed.
2968
- // Neutral about the drawings: an existing member's end may well be drawn, and the person is being
2969
- // asked whether it still holds (code review).
2970
- ? 'Only you can answer these heights — the AI can’t fill this in. For a new member, what you confirm or type goes straight into the model; for one already in the model, it is proposed in the review.'
2971
- : 'The drawings don’t settle these heights. Only you can answer — the AI can’t fill this in. What you confirm or type goes straight into the model.')
2972
- : 'This read is no longer waiting for an answer.';
2973
- card.append(note);
2974
- if (!view) {
2975
- if (entry.loadError) {
2976
- const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
2977
- const retry = heightActionButton('Try again', `shell.chat-height-retry#${entry.questionId}`, 'this height question', '');
2978
- retry.addEventListener('click', () => { entry.loadError = ''; repaintHeightCard(entry); loadHeightQuestion(entry); });
2979
- actions.append(retry); card.append(actions);
2980
- }
2981
- return card;
2982
- }
2983
-
2984
- const questionLabel = `height question ${view.n}`;
2985
- const count = document.createElement('p'); count.className = 'ai-chat-height-count'; count.setAttribute('aria-live', 'polite');
2986
- count.textContent = `${answered.length} of ${live.length} answered`;
2987
- card.append(count);
2988
-
2989
- // #1906: rows the read grouped ("W10x33 column bases") sit under a header that selects them together.
2990
- const selectable = (row) => open && row.status !== 'superseded' && !(row.answer && (row.status === 'confirmed' || row.status === 'typed') && !entry.changing.has(heightEndKey(row)));
2991
- for (const key of [...entry.selected]) if (!rows.some((row) => heightEndKey(row) === key && selectable(row))) entry.selected.delete(key);
2992
- const list = document.createElement('ol'); list.className = 'ai-chat-height-rows';
2993
- list.setAttribute('role', 'region'); list.setAttribute('aria-label', 'Heights to confirm'); list.tabIndex = 0;
2994
- list.dataset.commandId = `shell.chat-height-rows#${entry.questionId}`;
2995
- list.dataset.commandInstanceLabel = questionLabel;
2996
- const groups = [];
2997
- for (const row of rows) {
2998
- const name = row.group || '';
2999
- let group = groups.find((g) => g.name === name);
3000
- if (!group) { group = { name, rows: [] }; groups.push(group); }
3001
- group.rows.push(row);
3002
- }
3003
- for (const group of groups) {
3004
- if (group.name) list.append(paintHeightGroup(entry, group, selectable));
3005
- for (const row of group.rows) list.append(paintHeightRow(entry, row, open, selectable(row)));
3006
- }
3007
- card.append(list);
3008
- // The feed repaints on every streamed word; a person scrolled halfway down a long card stays there.
3009
- list.addEventListener('scroll', () => { entry.rowsScroll = list.scrollTop; }, { passive: true });
3010
- if (entry.rowsScroll) requestAnimationFrame(() => { if (list.isConnected) list.scrollTop = entry.rowsScroll; });
3011
-
3012
- if (open && entry.selected.size) card.append(paintHeightBulk(entry, rows, questionLabel));
3013
-
3014
- const error = document.createElement('p'); error.className = 'ai-chat-height-error'; error.setAttribute('role', 'alert');
3015
- error.textContent = entry.cardError || '';
3016
- card.append(error);
3017
-
3018
- const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
3019
- const confirmable = live.filter((row) => !row.answer && row.proposed);
3020
- if (open && !allAnswered && !entry.selected.size && confirmable.length >= 2 && confirmable.length === live.filter((row) => !row.answer).length) {
3021
- const all = heightActionButton(`Confirm all ${confirmable.length}`, `shell.chat-height-confirm-all#${entry.questionId}`, questionLabel, '',
3022
- entry.busy ? 'A height is still being saved — wait for it to finish' : null);
3023
- all.addEventListener('click', () => {
3024
- if (all.getAttribute('aria-disabled') === 'true') return;
3025
- submitHeightAnswers(entry, confirmable.map((row) => ({ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value })), null);
3026
- });
3027
- actions.append(all);
3028
- }
3029
- if (open && allAnswered) {
3030
- const done = document.createElement('p'); done.className = 'ai-chat-height-done';
3031
- // No paint-time state about the composer: it changes without this card repainting, so anything
3032
- // painted here about it would go stale. The click decides (owner ruling 2026-10-02).
3033
- done.textContent = 'All answered. Tell the read puts the message in the box so you can add to it; Send to the read sends it now.';
3034
- card.append(done);
3035
- const tell = heightActionButton('Tell the read', `shell.chat-height-tell-read#${entry.questionId}`, questionLabel, 'ai-chat-filter-apply', null);
3036
- tell.addEventListener('click', () => tellReadHeightsAnswered(entry));
3037
- const send = heightActionButton('Send to the read', `shell.chat-height-send-read#${entry.questionId}`, questionLabel, '', null);
3038
- send.addEventListener('click', () => { void sendToReadAnswered(entry, heightTellText(entry), repaintHeightCard); });
3039
- actions.append(tell, send);
3040
- }
3041
- actions.hidden = !actions.childNodes.length;
3042
- card.append(actions);
3043
- return card;
3044
- }
3045
-
3046
- /** A themed checkbox (the native box never shows, in either theme). */
3047
- function themedCheck(commandId, instance, checked, ariaLabel, disabledReason, onChange) {
3048
- const box = document.createElement('input');
3049
- box.type = 'checkbox'; box.className = 'ai-chat-check';
3050
- box.dataset.commandId = commandId; box.dataset.commandInstanceLabel = instance;
3051
- box.checked = checked;
3052
- box.setAttribute('aria-label', ariaLabel);
3053
- if (disabledReason) { box.disabled = true; box.dataset.blockedReason = disabledReason; }
3054
- box.addEventListener('change', () => onChange(box.checked));
3055
- return box;
3555
+ return paintDrawingHistory('height', entry, eventId, sequence);
3056
3556
  }
3057
3557
 
3058
- function paintHeightGroup(entry, group, selectable) {
3059
- const header = document.createElement('li'); header.className = 'ai-chat-height-group';
3060
- const name = document.createElement('span'); name.className = 'ai-chat-height-group-name'; name.textContent = group.name; name.dataset.tip = group.name;
3061
- const tally = document.createElement('span'); tally.className = 'ai-chat-height-meta'; tally.textContent = `${group.rows.length} ${group.rows.length === 1 ? 'end' : 'ends'}`;
3062
- header.append(name, tally);
3063
- const open = group.rows.filter(selectable);
3064
- if (open.length) {
3065
- const all = open.every((row) => entry.selected.has(heightEndKey(row)));
3066
- const toggle = heightActionButton(all ? 'Clear group' : 'Select group', `shell.chat-height-select-group#${entry.questionId} ${group.name}`, group.name, 'ai-chat-height-change',
3067
- entry.busy ? 'A height is still being saved — wait for it to finish' : null);
3068
- toggle.setAttribute('aria-label', `${all ? 'Clear' : 'Select'} every open end in ${group.name}`);
3069
- toggle.addEventListener('click', () => {
3070
- if (toggle.getAttribute('aria-disabled') === 'true') return;
3071
- for (const row of open) { if (all) entry.selected.delete(heightEndKey(row)); else entry.selected.add(heightEndKey(row)); }
3072
- repaintHeightCard(entry);
3073
- });
3074
- header.append(toggle);
3075
- }
3076
- return header;
3077
- }
3078
-
3079
- /** The bulk bar (#1906): one height and one source for every ticked end, pinned under the rows. */
3080
- function paintHeightBulk(entry, rows, questionLabel) {
3081
- const chosen = rows.filter((row) => entry.selected.has(heightEndKey(row)));
3082
- const n = chosen.length;
3083
- const busyReason = entry.busy ? 'A height is still being saved — wait for it to finish' : null;
3084
- const bar = document.createElement('div'); bar.className = 'ai-chat-height-bulk';
3085
- const top = document.createElement('div'); top.className = 'ai-chat-height-bulk-top';
3086
- const tally = document.createElement('span'); tally.setAttribute('aria-live', 'polite'); tally.setAttribute('aria-atomic', 'true');
3087
- tally.textContent = `${n} selected`;
3088
- const clear = heightActionButton('Clear', `shell.chat-height-bulk-clear#${entry.questionId}`, questionLabel, 'ai-chat-height-change', null);
3089
- clear.setAttribute('aria-label', 'Clear the selection');
3090
- clear.addEventListener('click', () => { entry.selected.clear(); repaintHeightCard(entry); });
3091
- top.append(tally, clear);
3092
- bar.append(top);
3093
- const shared = chosen.every((row) => row.proposed && chosen[0].proposed && row.proposed.value === chosen[0].proposed.value);
3094
- if (shared && chosen[0]?.proposed) {
3095
- // Offered only when every ticked end has the SAME proposal — never shown disabled (design review).
3096
- const line = document.createElement('div'); line.className = 'ai-chat-height-proposal';
3097
- const value = document.createElement('span'); value.textContent = `Proposed ${chosen[0].proposed.asRead}`;
3098
- const confirm = heightActionButton(`Confirm proposed for ${n}`, `shell.chat-height-bulk-confirm#${entry.questionId}`, questionLabel, 'ai-chat-filter-apply', busyReason);
3099
- confirm.addEventListener('click', () => {
3100
- if (confirm.getAttribute('aria-disabled') === 'true') return;
3101
- submitHeightAnswers(entry, chosen.map((row) => ({ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value })), null, `hb:${entry.questionId}`);
3102
- });
3103
- line.append(value, confirm);
3104
- bar.append(line);
3105
- }
3106
- const field = document.createElement('div'); field.className = 'ai-chat-height-field';
3107
- const input = document.createElement('input');
3108
- input.type = 'text'; input.className = 'ai-chat-height-input'; input.autocomplete = 'off'; input.spellcheck = false;
3109
- input.dataset.commandId = `shell.chat-height-bulk-input#${entry.questionId}`; input.dataset.commandInstanceLabel = questionLabel;
3110
- input.placeholder = entry.view?.units === 'mm' ? 'one height for all, e.g. 4870 mm' : 'one height for all, e.g. 16\'-6"';
3111
- input.setAttribute('aria-label', `One height for the ${n} selected ends`);
3112
- input.value = entry.bulkDraft || '';
3113
- input.addEventListener('input', () => { entry.bulkDraft = input.value; entry.cardError = ''; });
3114
- if (busyReason) { input.readOnly = true; input.setAttribute('aria-disabled', 'true'); input.dataset.blockedReason = busyReason; }
3115
- const use = heightActionButton(`Use for ${n}`, `shell.chat-height-bulk-use#${entry.questionId}`, questionLabel, shared ? '' : 'ai-chat-filter-apply', busyReason);
3116
- use.setAttribute('aria-label', `Use the typed height for the ${n} selected ends`);
3117
- const submit = () => {
3118
- if (use.getAttribute('aria-disabled') === 'true') return;
3119
- const typed = input.value.trim();
3120
- if (!typed) {
3121
- // #2167: no height, but a note or a picture, is an honest answer: "I don't know it, look here".
3122
- if (hasAnswerSource(`hb:${entry.questionId}`)) {
3123
- submitHeightAnswers(entry, chosen.map((row) => ({ memberId: row.memberId, end: row.end, action: 'evidence' })), null, `hb:${entry.questionId}`);
3124
- return;
3125
- }
3126
- entry.cardError = NO_HEIGHT_NO_SOURCE; repaintHeightCard(entry); return;
3127
- }
3128
- submitHeightAnswers(entry, chosen.map((row) => ({ memberId: row.memberId, end: row.end, action: 'type', typed })), null, `hb:${entry.questionId}`);
3129
- };
3130
- input.addEventListener('keydown', (event) => { if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); submit(); } });
3131
- use.addEventListener('click', submit);
3132
- field.append(input, use);
3133
- bar.append(field);
3134
- bar.append(paintAnswerSource(`hb:${entry.questionId}`, {
3135
- requestId: entry.requestId, chatId: entry.chatId, repaint: () => repaintHeightCard(entry), label: `the ${n} selected ends`, instance: questionLabel,
3136
- idFor: (what, extra) => `shell.chat-answer-${what}#${entry.questionId} bulk${extra ? ` ${extra}` : ''}`, busyReason, allowPictureOnly: false,
3137
- }));
3138
- return bar;
3139
- }
3140
-
3141
- function paintHeightRow(entry, row, open, selectable) {
3558
+ function paintHeightRow(entry, row, open) {
3142
3559
  const key = heightEndKey(row);
3143
3560
  const item = document.createElement('li'); item.className = 'ai-chat-height-row';
3144
3561
  item.dataset.status = row.status;
@@ -3146,11 +3563,6 @@
3146
3563
  const idFor = (what) => `shell.chat-height-${what}#${entry.questionId} ${row.memberId} ${row.endWord}`;
3147
3564
  const sourceIdFor = (what, extra) => `shell.chat-answer-${what}#${entry.questionId} ${row.memberId} ${row.endWord}${extra ? ` ${extra}` : ''}`;
3148
3565
  const labelLine = document.createElement('div'); labelLine.className = 'ai-chat-height-labelline';
3149
- if (selectable) {
3150
- labelLine.append(themedCheck(idFor('select'), instance, entry.selected.has(key), `Select ${row.label} to answer several ends at once`,
3151
- entry.busy ? 'A height is still being saved — wait for it to finish' : null,
3152
- (checked) => { if (checked) entry.selected.add(key); else entry.selected.delete(key); repaintHeightCard(entry); }));
3153
- }
3154
3566
  const label = document.createElement('div'); label.className = 'ai-chat-height-label'; label.textContent = row.label;
3155
3567
  label.dataset.tip = row.label;
3156
3568
  labelLine.append(label);
@@ -3186,11 +3598,8 @@
3186
3598
  change.setAttribute('aria-label', picture ? `Answer the height for ${row.label} yourself instead` : `Change the height for ${row.label}`);
3187
3599
  change.addEventListener('click', () => {
3188
3600
  if (change.getAttribute('aria-disabled') === 'true') return;
3189
- entry.changing.add(key);
3190
3601
  if (!entry.drafts.has(key) && row.answer.how === 'typed') entry.drafts.set(key, row.answer.typed);
3191
- repaintHeightCard(entry);
3192
- const card = ui.feed.querySelector(`[data-height-question="${CSS.escape(entry.key)}"]`);
3193
- if (card) focusHeightControl(card, idFor('input'));
3602
+ reopenDrawingItem('height', entry, key);
3194
3603
  });
3195
3604
  done.append(change);
3196
3605
  }
@@ -3204,61 +3613,6 @@
3204
3613
  item.append(none);
3205
3614
  return item;
3206
3615
  }
3207
- const busyReason = entry.busy ? 'A height is still being saved — wait for it to finish' : null;
3208
- if (row.proposed) {
3209
- const proposal = document.createElement('div'); proposal.className = 'ai-chat-height-proposal';
3210
- const value = document.createElement('span'); value.textContent = `Proposed ${row.proposed.asRead}`;
3211
- const confirm = heightActionButton('Confirm', idFor('confirm'), instance, 'ai-chat-filter-apply', busyReason);
3212
- confirm.setAttribute('aria-label', `Confirm ${row.proposed.asRead} for ${row.label}`);
3213
- confirm.addEventListener('click', () => {
3214
- if (confirm.getAttribute('aria-disabled') === 'true') return;
3215
- submitHeightAnswers(entry, [{ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value }], key);
3216
- });
3217
- proposal.append(value, confirm);
3218
- item.append(proposal);
3219
- if (row.fromEvidence) {
3220
- // #1906 "see snap": the proposal is the READ's reading of the person's picture, said as such.
3221
- const tag = document.createElement('div'); tag.className = 'ai-chat-setup-evidence';
3222
- const t = document.createElement('span'); t.className = 'ai-chat-setup-tag';
3223
- t.textContent = !row.inherited?.length ? 'THE READ’S READING OF YOUR NOTE' : 'THE READ’S READING OF YOUR PICTURE';
3224
- tag.append(t, document.createTextNode(' Check it before you confirm.'));
3225
- item.append(tag);
3226
- }
3227
- }
3228
- const field = document.createElement('div'); field.className = 'ai-chat-height-field';
3229
- const input = document.createElement('input');
3230
- input.type = 'text'; input.className = 'ai-chat-height-input'; input.autocomplete = 'off'; input.spellcheck = false;
3231
- input.dataset.commandId = idFor('input');
3232
- input.dataset.commandInstanceLabel = instance;
3233
- input.placeholder = entry.view?.units === 'mm' ? 'e.g. 4870 mm' : 'e.g. 15\'-11 3/4"';
3234
- input.setAttribute('aria-label', `${row.proposed ? 'Or type the height' : 'Type the height'} for ${row.label}`);
3235
- input.value = entry.drafts.get(key) || '';
3236
- input.addEventListener('input', () => { entry.drafts.set(key, input.value); entry.rowErrors.delete(key); });
3237
- if (busyReason) { input.readOnly = true; input.setAttribute('aria-disabled', 'true'); input.dataset.blockedReason = busyReason; }
3238
- const use = heightActionButton('Use', idFor('use'), instance, row.proposed ? '' : 'ai-chat-filter-apply', busyReason);
3239
- use.setAttribute('aria-label', `Use the typed height for ${row.label}`);
3240
- const submitTyped = () => {
3241
- if (use.getAttribute('aria-disabled') === 'true') return;
3242
- const typed = input.value.trim();
3243
- if (!typed) {
3244
- // #2167: a note or a picture without a height is an answer too; the AI works the height out from it.
3245
- if (hasAnswerSource(`h:${entry.questionId}:${key}`)) { submitHeightAnswers(entry, [{ memberId: row.memberId, end: row.end, action: 'evidence' }], key); return; }
3246
- entry.rowErrors.set(key, NO_HEIGHT_NO_SOURCE); repaintHeightCard(entry); return;
3247
- }
3248
- submitHeightAnswers(entry, [{ memberId: row.memberId, end: row.end, action: 'type', typed }], key);
3249
- };
3250
- input.addEventListener('keydown', (event) => { if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); submitTyped(); } });
3251
- use.addEventListener('click', submitTyped);
3252
- field.append(input, use);
3253
- item.append(field);
3254
- item.append(paintAnswerSource(`h:${entry.questionId}:${key}`, {
3255
- requestId: entry.requestId, chatId: entry.chatId, repaint: () => repaintHeightCard(entry), label: row.label, instance,
3256
- idFor: sourceIdFor, inherited: row.inherited, busyReason, allowPictureOnly: true,
3257
- onPictureOnly: () => submitHeightAnswers(entry, [{ memberId: row.memberId, end: row.end, action: 'evidence' }], key),
3258
- }));
3259
- const rowError = document.createElement('p'); rowError.className = 'ai-chat-height-error'; rowError.setAttribute('role', 'alert');
3260
- rowError.textContent = entry.rowErrors.get(key) || '';
3261
- item.append(rowError);
3262
3616
  return item;
3263
3617
  }
3264
3618
 
@@ -3267,7 +3621,13 @@
3267
3621
  * several ends are answered at once (`sharedScope`).
3268
3622
  */
3269
3623
  async function submitHeightAnswers(entry, answers, rowKey, sharedScope) {
3270
- if (entry.busy) return;
3624
+ if (entry.busy) return false;
3625
+ const ownedSlot = drawingEntryCurrent(entry) && ui.approvalTray?.querySelector('.ai-chat-drawing-step')?.dataset.drawingStep;
3626
+ const ownedNode = ownedSlot ? ui.approvalTray.querySelector('.ai-chat-drawing-step') : null;
3627
+ const pendingFocusId = ownedNode?.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
3628
+ const failedField = ownedNode && ([...ownedNode.querySelectorAll('input')].find((field) => field.dataset.commandId === ownedNode.lastDrawingField) || ownedNode.querySelector('.ai-chat-ask-other-input'));
3629
+ const failedFieldId = failedField?.dataset.commandId, failedCaret = failedField ? textCaret(failedField) : null;
3630
+ let saved = false;
3271
3631
  const scopeOf = (answer) => sharedScope || `h:${entry.questionId}:${heightEndKey(answer)}`;
3272
3632
  const withSource = answers.map((answer) => ({ ...answer, ...answerSourcePayload(scopeOf(answer)) }));
3273
3633
  entry.busy = true; entry.cardError = ''; if (rowKey) entry.rowErrors.delete(rowKey);
@@ -3276,11 +3636,40 @@
3276
3636
  const result = await request(`/api/chat/height-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}/answers`, {
3277
3637
  method: 'POST', body: JSON.stringify({ chatId: entry.chatId, answers: withSource }),
3278
3638
  });
3639
+ const keptPictures = new Set([
3640
+ ...withSource.flatMap((answer) => answer.evidence || []),
3641
+ ...[entry.view, result.question].flatMap((view) => (view?.ends || []).flatMap((row) => [...row.answer?.evidence || [], ...row.inherited || []])).map((ref) => ref.attachmentId),
3642
+ ]);
3279
3643
  entry.view = result.question;
3644
+ saved = true;
3280
3645
  for (const answer of answers) {
3281
3646
  const key = heightEndKey(answer);
3282
3647
  entry.changing.delete(key); entry.drafts.delete(key); entry.selected.delete(key);
3648
+ if (entry.activeItem === key) { entry.activeItem = null; entry.reopenedAt = 0; }
3283
3649
  clearAnswerSource(scopeOf(answer));
3650
+ if (sharedScope) {
3651
+ const rowScope = `h:${entry.questionId}:${key}`, source = answerSources.get(rowScope);
3652
+ if (source) {
3653
+ source.note = '';
3654
+ for (const file of [...source.files]) {
3655
+ if (keptPictures.has(file.attachmentId)) {
3656
+ source.files = source.files.filter((held) => held !== file);
3657
+ if (file.url) URL.revokeObjectURL(file.url);
3658
+ continue;
3659
+ }
3660
+ await removeAnswerFile(rowScope, {
3661
+ requestId: entry.requestId, chatId: entry.chatId, repaint: () => repaintHeightCard(entry),
3662
+ removeFile: async (unused) => {
3663
+ try { await request(evidenceUrl(entry.requestId, unused.attachmentId), { method: 'DELETE', body: JSON.stringify({ chatId: entry.chatId }) }); }
3664
+ catch (error) { if (error?.code !== 'answer-evidence-cited') throw error; }
3665
+ },
3666
+ }, file);
3667
+ if (source.files.includes(file)) file.cleanupPending = true;
3668
+ }
3669
+ if (!source.files.length) clearAnswerSource(rowScope);
3670
+ else { source.open = true; source.error = `Unused pictures could not be removed: ${source.files.filter((file) => file.cleanupPending).map((file) => file.fileName).join(', ')}. Remove these pictures to retry.`; }
3671
+ }
3672
+ }
3284
3673
  }
3285
3674
  if (sharedScope) entry.bulkDraft = '';
3286
3675
  } catch (error) {
@@ -3295,8 +3684,14 @@
3295
3684
  entry.busy = false;
3296
3685
  repaintHeightCard(entry);
3297
3686
  settlePendingReload(entry, loadHeightQuestion);
3298
- focusNextHeightControl(entry);
3687
+ const currentSlot = ui.approvalTray?.querySelector('.ai-chat-drawing-step');
3688
+ if (ownedSlot && drawingEntryCurrent(entry) && ownedSlot === currentSlot?.dataset.drawingStep
3689
+ && pendingFocusId && currentSlot.contains(document.activeElement) && document.activeElement.dataset.commandId === pendingFocusId) {
3690
+ if (saved) focusNextHeightControl(entry);
3691
+ else if (failedFieldId) focusHeightControl(currentSlot, failedFieldId, failedCaret);
3692
+ }
3299
3693
  }
3694
+ return saved;
3300
3695
  }
3301
3696
 
3302
3697
  // After an answer, keyboard focus moves to the next row still waiting, or to Tell the read.
@@ -3402,14 +3797,25 @@
3402
3797
  ctx.repaint(); return;
3403
3798
  }
3404
3799
  for (const file of incoming) {
3800
+ if (answerSources.get(scope) !== source) break;
3405
3801
  source.uploading += 1; ctx.repaint();
3406
3802
  try {
3407
3803
  const data = await fileBase64(file);
3408
- const result = await request(`/api/chat/answer-evidence/${encodeURIComponent(ctx.requestId)}`, {
3804
+ // #2223: the AI's question card keeps its files through its own person-only route (`ctx.upload`).
3805
+ const result = ctx.upload ? await ctx.upload(file, data) : await request(`/api/chat/answer-evidence/${encodeURIComponent(ctx.requestId)}`, {
3409
3806
  method: 'POST', timeoutMs: 120000,
3410
3807
  body: JSON.stringify({ chatId: ctx.chatId, fileName: file.name || 'screenshot.png', mediaType: file.type, data }),
3411
3808
  });
3412
3809
  const ref = result.evidence;
3810
+ if (answerSources.get(scope) !== source) {
3811
+ if (ctx.removeFile) {
3812
+ try { await ctx.removeFile(ref); }
3813
+ catch (error) {
3814
+ if (error?.code !== 'answer-evidence-unknown') console.warn('[chat] a closed question\u2019s unused picture could not be released', ref.attachmentId, error?.message);
3815
+ }
3816
+ }
3817
+ continue;
3818
+ }
3413
3819
  source.files.push({ ...ref, url: file.type.startsWith('image/') ? URL.createObjectURL(file) : '' });
3414
3820
  } catch (error) {
3415
3821
  source.error = error?.message || `FloLess could not attach “${file.name}”. Try again.`;
@@ -3424,16 +3830,18 @@
3424
3830
  const drop = () => {
3425
3831
  source.files = source.files.filter((row) => row.attachmentId !== file.attachmentId);
3426
3832
  if (file.url) URL.revokeObjectURL(file.url);
3427
- source.error = '';
3833
+ const unused = source.files.filter((held) => held.cleanupPending);
3834
+ source.error = unused.length ? `Unused pictures could not be removed: ${unused.map((held) => held.fileName).join(', ')}. Remove these pictures to retry.` : '';
3428
3835
  };
3429
3836
  try {
3430
- await request(evidenceUrl(ctx.requestId, file.attachmentId), { method: 'DELETE', body: JSON.stringify({ chatId: ctx.chatId }) });
3837
+ if (ctx.removeFile) await ctx.removeFile(file);
3838
+ else await request(evidenceUrl(ctx.requestId, file.attachmentId), { method: 'DELETE', body: JSON.stringify({ chatId: ctx.chatId }) });
3431
3839
  drop();
3432
3840
  } catch (error) {
3433
3841
  // Already gone on the server (review #1906): the chip goes too, or it would ride on every later
3434
3842
  // answer and be refused each time, with the paperclip stuck at the file limit.
3435
3843
  if (error?.code === 'answer-evidence-unknown') drop();
3436
- else source.error = error?.message || 'FloLess could not remove that file. Try again.';
3844
+ else source.error = file.cleanupPending ? `Unused pictures could not be removed: ${source.files.filter((held) => held.cleanupPending).map((held) => held.fileName).join(', ')}. Remove these pictures to retry.` : error?.message || 'FloLess could not remove that file. Try again.';
3437
3845
  }
3438
3846
  ctx.repaint();
3439
3847
  }
@@ -3515,7 +3923,7 @@
3515
3923
  kept.append(lead, ...ctx.inherited.map((ref) => answerPictureChip(ctx.requestId, ref, ctx.idFor('picture-open', ref.attachmentId), ctx.instance)));
3516
3924
  wrap.append(kept);
3517
3925
  }
3518
- const hasDraft = source.open || source.note || source.files.length || source.uploading;
3926
+ const hasDraft = ctx.alwaysOpen || source.open || source.note || source.files.length || source.uploading;
3519
3927
  if (!hasDraft) {
3520
3928
  const add = button('+ Add source', ctx.idFor('source'), 'ai-chat-answer-add');
3521
3929
  add.dataset.commandInstanceLabel = ctx.instance;
@@ -3523,7 +3931,7 @@
3523
3931
  add.dataset.tip = 'Say where your answer comes from: a note like “per 7/S-502”, or a screenshot or PDF';
3524
3932
  add.addEventListener('click', () => {
3525
3933
  source.open = true; ctx.repaint();
3526
- [...(ui.feed?.querySelectorAll('[data-command-id]') || [])].find((node) => node.dataset.commandId === ctx.idFor('note'))?.focus({ preventScroll: true });
3934
+ [...(ui.approvalTray?.querySelectorAll('[data-command-id]') || []), ...(ui.feed?.querySelectorAll('[data-command-id]') || [])].find((node) => node.dataset.commandId === ctx.idFor('note'))?.focus({ preventScroll: true });
3527
3935
  });
3528
3936
  wrap.append(add);
3529
3937
  return wrap;
@@ -3536,7 +3944,8 @@
3536
3944
  note.dataset.commandId = ctx.idFor('note'); note.dataset.commandInstanceLabel = ctx.instance;
3537
3945
  note.setAttribute('aria-label', `Source note for ${ctx.label}`);
3538
3946
  note.value = source.note;
3539
- note.addEventListener('input', () => { source.note = note.value; });
3947
+ if (ctx.busyReason) { note.readOnly = true; note.setAttribute('aria-disabled', 'true'); note.dataset.blockedReason = ctx.busyReason; note.dataset.tip = ctx.busyReason; }
3948
+ note.addEventListener('input', () => { source.note = note.value; ctx.onDraftChange?.(); });
3540
3949
  const clip = document.createElement('button');
3541
3950
  clip.type = 'button'; clip.className = 'ai-chat-answer-clip';
3542
3951
  clip.dataset.commandId = ctx.idFor('attach'); clip.dataset.commandInstanceLabel = ctx.instance;
@@ -3550,16 +3959,16 @@
3550
3959
  picker.type = 'file'; picker.multiple = true; picker.hidden = true; picker.accept = 'image/png,image/jpeg,image/webp,application/pdf';
3551
3960
  picker.dataset.commandId = ctx.idFor('attach-input'); picker.dataset.commandInstanceLabel = ctx.instance;
3552
3961
  picker.addEventListener('change', () => { const files = [...picker.files]; picker.value = ''; attachAnswerFiles(scope, ctx, files); });
3553
- clip.addEventListener('click', () => picker.click());
3962
+ clip.addEventListener('click', () => { if (clip.getAttribute('aria-disabled') !== 'true') picker.click(); });
3554
3963
  if (ctx.busyReason || source.files.length >= MAX_ANSWER_FILES) {
3555
3964
  const why = ctx.busyReason || `An answer can carry at most ${MAX_ANSWER_FILES} files`;
3556
3965
  clip.setAttribute('aria-disabled', 'true'); clip.dataset.blockedReason = why; clip.dataset.tip = why;
3557
- clip.onclick = (event) => event.stopImmediatePropagation();
3558
3966
  }
3559
3967
  line.append(note, clip, picker);
3560
3968
  box.append(line);
3561
3969
  // Paste and drop, like the composer: a screenshot pasted while this box has focus attaches to the answer.
3562
3970
  box.addEventListener('paste', (event) => {
3971
+ if (ctx.busyReason) return;
3563
3972
  const files = [...(event.clipboardData?.files || [])];
3564
3973
  if (files.length) { event.preventDefault(); attachAnswerFiles(scope, ctx, files); }
3565
3974
  });
@@ -3567,6 +3976,7 @@
3567
3976
  box.addEventListener('dragleave', () => box.classList.remove('drop'));
3568
3977
  box.addEventListener('drop', (event) => {
3569
3978
  box.classList.remove('drop');
3979
+ if (ctx.busyReason) return;
3570
3980
  const files = [...(event.dataTransfer?.files || [])];
3571
3981
  if (files.length) { event.preventDefault(); attachAnswerFiles(scope, ctx, files); }
3572
3982
  });
@@ -3575,12 +3985,13 @@
3575
3985
  for (const file of source.files) {
3576
3986
  const chip = document.createElement('span'); chip.className = 'ai-chat-attachment';
3577
3987
  if (file.url) { const img = document.createElement('img'); img.alt = ''; img.src = file.url; chip.append(img); }
3578
- const name = document.createElement('span'); name.textContent = file.fileName;
3988
+ const name = document.createElement('span'); name.textContent = file.cleanupPending ? `Removal pending: ${file.fileName}` : file.fileName;
3579
3989
  const remove = button('×', ctx.idFor('picture-remove', file.attachmentId));
3580
3990
  remove.dataset.commandInstanceLabel = file.fileName;
3581
- remove.setAttribute('aria-label', `Remove ${file.fileName} from this answer`);
3582
- remove.dataset.tip = 'Remove from this answer';
3583
- remove.addEventListener('click', () => removeAnswerFile(scope, ctx, file));
3991
+ remove.setAttribute('aria-label', file.cleanupPending ? `Retry removing unused picture ${file.fileName}` : `Remove ${file.fileName} from this answer`);
3992
+ remove.dataset.tip = file.cleanupPending ? 'Retry removing this unused picture' : 'Remove from this answer';
3993
+ if (ctx.busyReason) { remove.setAttribute('aria-disabled', 'true'); remove.dataset.blockedReason = ctx.busyReason; remove.dataset.tip = ctx.busyReason; }
3994
+ remove.addEventListener('click', () => { if (!ctx.busyReason) removeAnswerFile(scope, ctx, file); });
3584
3995
  chip.append(name, remove); chips.append(chip);
3585
3996
  }
3586
3997
  if (source.uploading) {
@@ -3600,7 +4011,8 @@
3600
4011
  box.append(only);
3601
4012
  }
3602
4013
  const error = document.createElement('p'); error.className = 'ai-chat-height-error'; error.setAttribute('role', 'alert');
3603
- error.textContent = source.error || '';
4014
+ const unused = source.files.filter((file) => file.cleanupPending);
4015
+ error.textContent = source.error || (unused.length ? `Unused pictures could not be removed: ${unused.map((file) => file.fileName).join(', ')}. Remove these pictures to retry.` : '');
3604
4016
  box.append(error);
3605
4017
  wrap.append(box);
3606
4018
  return wrap;
@@ -3687,6 +4099,325 @@
3687
4099
  * use exactly what is settled here, and asks again on a new card if anything conflicts.
3688
4100
  */
3689
4101
  const setupCards = new Map();
4102
+
4103
+ /** Drawing answers share the question slot; their server-owned records remain in the transcript. */
4104
+ function drawingRows(kind, entry) { return kind === 'setup' ? entry.view?.items || [] : entry.view?.ends || []; }
4105
+ function drawingRowKey(kind, row) { return kind === 'setup' ? row.key : heightEndKey(row); }
4106
+ function drawingRowOpen(kind, entry, row) {
4107
+ if (!entry.view?.open || row.status === 'superseded' || row.frozen) return false;
4108
+ const key = drawingRowKey(kind, row);
4109
+ if (entry.changing.has(key)) return true;
4110
+ return kind === 'setup' ? row.status === 'open' : !row.answer;
4111
+ }
4112
+ function drawingEntryCurrent(entry) { return entry.chatId === state.chat?.chatId; }
4113
+ function drawingSlotRepaint() {
4114
+ paintDrawingQuestionSlot();
4115
+ }
4116
+ function reopenDrawingItem(kind, entry, key) {
4117
+ const row = drawingRows(kind, entry).find((row) => drawingRowKey(kind, row) === key);
4118
+ if (entry.busy || !entry.view?.open || !row || row.frozen || row.status === 'superseded') return;
4119
+ entry.changing.add(key); entry.activeItem = key; entry.finishActive = false; entry.reopenedAt = (state.drawingActivationOrder = (state.drawingActivationOrder || 0) + 1);
4120
+ 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; }
4121
+ entry.slotPhase = 'row';
4122
+ (kind === 'setup' ? repaintSetupCard : repaintHeightCard)(entry);
4123
+ drawingSlotRepaint();
4124
+ }
4125
+ function paintDrawingHistory(kind, entry, eventId, sequence) {
4126
+ entry.eventId = eventId || entry.eventId || ''; entry.sequence = Number(sequence || entry.sequence || 0);
4127
+ const card = document.createElement('section');
4128
+ card.className = `ai-chat-filter-card ai-chat-height-card${kind === 'setup' ? ' ai-chat-setup-card' : ''}`;
4129
+ card.dataset[kind === 'setup' ? 'setupQuestion' : 'heightQuestion'] = entry.key;
4130
+ card.dataset.eventId = eventId || ''; card.dataset.eventSequence = sequence || '';
4131
+ const title = kind === 'setup' ? 'Read setup' : 'Confirm member heights';
4132
+ card.setAttribute('aria-label', entry.view?.n ? `${title}, question ${entry.view.n}` : title);
4133
+ const rows = drawingRows(kind, entry), live = rows.filter((row) => row.status !== 'superseded');
4134
+ const answered = live.filter((row) => row.answer);
4135
+ const settled = kind === 'setup' ? live.filter(setupSettled).length : live.filter((row) => row.status === 'confirmed' || row.status === 'typed').length;
4136
+ const allAnswered = live.length > 0 && answered.length === live.length;
4137
+ card.dataset.state = !entry.view ? (entry.finished ? 'closed' : 'loading') : !entry.view.open ? 'closed'
4138
+ : allAnswered ? (settled === live.length ? 'answered' : 'waiting-for-read') : 'open';
4139
+ const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
4140
+ const heading = document.createElement('strong'); heading.textContent = title;
4141
+ const chip = document.createElement('span'); chip.className = 'ai-chat-filter-state'; chip.textContent = card.dataset.state;
4142
+ head.append(heading, chip); card.append(head);
4143
+ if (!entry.view) {
4144
+ const note = document.createElement('p'); note.className = 'ai-chat-filter-note';
4145
+ note.textContent = entry.finished ? CARD_FINISHED_TEXT : entry.loadError || `Loading ${kind === 'setup' ? 'the read setup' : 'the heights this read is asking about'}…`;
4146
+ card.append(note);
4147
+ if (entry.loadError) {
4148
+ const retry = heightActionButton('Try again', `shell.chat-${kind}-retry#${entry.questionId}`, title, '');
4149
+ retry.addEventListener('click', () => { entry.loadError = ''; (kind === 'setup' ? loadSetupQuestion : loadHeightQuestion)(entry); }); card.append(retry);
4150
+ }
4151
+ } else {
4152
+ const count = document.createElement('p'); count.className = 'ai-chat-height-count'; count.setAttribute('aria-live', 'polite');
4153
+ count.textContent = `${kind === 'setup' ? settled : answered.length} of ${live.length} ${kind === 'setup' ? 'settled' : 'answered'}`; card.append(count);
4154
+ if (kind === 'height' && entry.view.open) {
4155
+ const note = document.createElement('p'); note.className = 'ai-chat-filter-note';
4156
+ note.textContent = rows.some((row) => row.inModel)
4157
+ ? 'Only you can answer these heights. For a new member, what you confirm or type goes straight into the model; for one already in the model, it is proposed in the review.'
4158
+ : 'Only you can answer these heights. What you confirm or type goes straight into the model.';
4159
+ card.append(note);
4160
+ }
4161
+ if (entry.view.open && allAnswered) {
4162
+ const next = heightActionButton('Tell / send to the read', `shell.chat-${kind}-next-step#${entry.questionId}`, `${kind === 'setup' ? 'setup' : 'height'} question ${entry.view.n}`, 'ai-chat-height-change', entry.busy ? 'An answer is still being saved — wait for it to finish' : null);
4163
+ next.dataset.tip = 'Choose whether to put the message in the box or send it now';
4164
+ next.addEventListener('click', () => {
4165
+ if (entry.busy) return;
4166
+ for (const other of [...setupCards.values(), ...heightCards.values()]) other.finishActive = false;
4167
+ entry.finishActive = true; entry.reopenedAt = (state.drawingActivationOrder = (state.drawingActivationOrder || 0) + 1); drawingSlotRepaint();
4168
+ });
4169
+ card.append(next);
4170
+ }
4171
+ const list = document.createElement('ol'); list.className = 'ai-chat-height-rows';
4172
+ for (const row of rows) {
4173
+ const key = drawingRowKey(kind, row);
4174
+ let item;
4175
+ if (row.answer || row.status === 'superseded' || row.frozen) {
4176
+ // Existing answer/source renderers retain pictures, provenance and recovery wording. There is only one place to answer.
4177
+ const changing = entry.changing.has(key); entry.changing.delete(key);
4178
+ item = kind === 'setup' ? paintSetupRow(entry, row, Boolean(entry.view.open)) : paintHeightRow(entry, row, Boolean(entry.view.open), false);
4179
+ if (changing) entry.changing.add(key);
4180
+ } else {
4181
+ item = document.createElement('li'); item.className = 'ai-chat-height-row'; item.dataset.status = row.status; item.dataset.key = key;
4182
+ const label = document.createElement('span'); label.textContent = row.label || (row.kind === 'origin' ? 'Model origin' : viewName(row)); item.append(label);
4183
+ if (entry.view.open) {
4184
+ const answer = heightActionButton('Answer', `shell.chat-${kind}-change#${entry.questionId} ${key}`, label.textContent, 'ai-chat-height-change', null);
4185
+ answer.addEventListener('click', () => reopenDrawingItem(kind, entry, key)); item.append(answer);
4186
+ }
4187
+ }
4188
+ list.append(item);
4189
+ }
4190
+ card.append(list);
4191
+ }
4192
+ const unused = kind === 'height' ? drawingRows(kind, entry).filter((row) => answerSources.get(`h:${entry.questionId}:${heightEndKey(row)}`)?.files.some((file) => file.cleanupPending)) : [];
4193
+ const cleanup = unused.length ? `Your heights were saved. Some unused pictures could not be removed. Choose Change for each listed end, then Remove on its unused pictures: ${unused.map((row) => `${row.label} · ${row.memberId} · ${heightEndWord(row)}`).join('; ')}. You do not need to submit the heights again.` : '';
4194
+ const error = document.createElement('p'); error.className = 'ai-chat-height-error'; error.setAttribute('role', 'alert'); error.textContent = [entry.cardError, cleanup].filter(Boolean).join(' '); card.append(error);
4195
+ drawingSlotRepaint();
4196
+ return card;
4197
+ }
4198
+ function drawingSource(kind, entry, scope, label, idFor, row, onDraftChange) {
4199
+ return paintAnswerSource(scope, { requestId: entry.requestId, chatId: entry.chatId, repaint: () => { (kind === 'setup' ? repaintSetupCard : repaintHeightCard)(entry); drawingSlotRepaint(); },
4200
+ removeFile: (file) => request(`/api/chat/answer-evidence/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(file.attachmentId)}`, { method: 'DELETE', body: JSON.stringify({ chatId: entry.chatId }) }),
4201
+ label, instance: label, idFor, inherited: row?.inherited, busyReason: entry.busy ? 'An answer is still being saved — wait for it to finish' : null,
4202
+ allowPictureOnly: false, onDraftChange, alwaysOpen: Boolean(entry.slotDrafts?.get(entry.slotQuestionKey)?.rows[0]?.otherOpen) });
4203
+ }
4204
+ function drawingStep(kind, entry) {
4205
+ const open = drawingRows(kind, entry).filter((row) => drawingRowOpen(kind, entry, row));
4206
+ const row = open.find((row) => drawingRowKey(kind, row) === entry.activeItem) || open[0];
4207
+ if (!row) {
4208
+ const live = drawingRows(kind, entry).filter((row) => row.status !== 'superseded');
4209
+ if (!entry.view?.open || !live.length || !live.every((row) => row.answer)) return null;
4210
+ 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,
4211
+ hint: 'Tell the read puts a message in the box. Send to the read sends it now.',
4212
+ 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' }] },
4213
+ commit: async (answer) => { const text = kind === 'setup' ? setupTellText(entry) : heightTellText(entry); const repaint = kind === 'setup' ? repaintSetupCard : repaintHeightCard;
4214
+ if (answer.choices[0] === 0) tellReadAnswered(entry, text, repaint); else await sendToReadAnswered(entry, text, repaint); return false; } };
4215
+ }
4216
+ if (kind === 'height' && open.length > 1 && entry.slotPhase !== 'row') return drawingHeightBatch(entry, open);
4217
+ const key = drawingRowKey(kind, row), scope = `${kind === 'setup' ? 's' : 'h'}:${entry.questionId}:${key}`;
4218
+ const label = row.label || (row.kind === 'origin' ? 'the model origin' : viewName(row));
4219
+ const q = { id: key, header: kind === 'setup' ? 'Read setup' : 'Height', question: label, options: [], recommended: null, context: [] };
4220
+ const live = drawingRows(kind, entry).filter((item) => item.status !== 'superseded');
4221
+ q.progress = { index: live.indexOf(row), total: live.length };
4222
+ const choices = [];
4223
+ if (kind === 'height') {
4224
+ if (row.inModel) {
4225
+ q.context.push(
4226
+ `${row.inModel.profile || ''} · ${row.memberId} · ${heightEndWord(row)}. ${heightInModelText(row.inModel, entry.view.units)} ${HEIGHT_PROPOSED_TEXT}`
4227
+ );
4228
+ }
4229
+ else q.context.push(`${row.memberId} · ${heightEndWord(row)}. Only you can answer. What you confirm or type goes straight into the model.`);
4230
+ if (row.proposed) { q.options.push({ shown: `Confirm ${row.proposed.asRead}`, description: 'Use the value proposed for this member end' }); choices.push({ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value }); q.recommended = 0; }
4231
+ if (row.fromEvidence) q.context.push(row.inherited?.length ? 'The read’s reading of your picture. Check it before you confirm.' : 'The read’s reading of your note. Check it before you confirm.');
4232
+ } else if (row.kind === 'origin') {
4233
+ q.question = 'Which grid crossing is the model’s origin (0, 0)?'; q.layout = 'grid'; q.confirmSelection = true;
4234
+ row.choices.forEach((choice, index) => { q.options.push({ shown: originText(choice), description: 'A straight grid crossing in the model', confirmLabel: `Confirm ${originText(choice)} as the model origin`, tag: row.proposed === index ? 'THE READ SUGGESTS' : '' }); choices.push({ key, action: 'confirm', choice: `c${index}`, shown: originText(choice) }); });
4235
+ row.offGrid.forEach((point, index) => { const target = row.choices[point.same]; q.options.push({ shown: point.as, description: 'Not a straight grid line; check the read’s mapping', confirmLabel: `Confirm ${originText(target)} as the model origin`, statement: `${point.as} is not a straight grid line in the model. The read says it is the same point as ${originText(target)} (${point.why}). This is the read’s claim; FloLess has not checked it.` }); choices.push({ key, action: 'confirm', choice: `o${index}`, shown: originText(target) }); });
4236
+ q.recommended = Number.isInteger(row.proposed) ? row.proposed : null;
4237
+ if (row.fromEvidence) q.context.push('The read’s reading of your picture. Check it before you confirm.');
4238
+ } else {
4239
+ if (row.clue) q.context.push(row.clue);
4240
+ if (row.noSingleLevel) q.context.push(`No single level on the drawings: ${row.noSingleLevel.why}`);
4241
+ row.proposals.forEach((proposal) => { q.options.push({ shown: row.kind === 'scale' ? `${proposal.pageFit ? 'Use for this plan' : 'Confirm'}: ${proposal.standard} · ${proposal.mmPerPx} mm per drawing point` : `Confirm ${proposal.asRead}`,
4242
+ description: row.kind === 'scale' ? proposal.evidence : levelEvidence(proposal), tag: (row.kind === 'scale' ? scaleTag : levelTag)[proposal.source] || 'PROPOSED' }); choices.push({ key, action: 'confirm', choice: proposal.id, shown: row.kind === 'scale' ? proposal.mmPerPx : proposal.value }); });
4243
+ }
4244
+ if (kind === 'setup' && row.kind !== 'scale') { q.options.push({ shown: row.kind === 'origin' ? 'None of these' : 'No single level', description: 'Tell the read what to use instead', requiresNote: { placeholder: 'Add a short reason', max: MAX_ANSWER_NOTE } }); choices.push({ key, action: 'none' }); }
4245
+ if (kind === 'setup') { const banner = setupConflictBanner(row); if (banner) q.context.push(banner.textContent); }
4246
+ const controlKey = kind === 'height' ? `${row.memberId} ${row.endWord}` : key;
4247
+ const idFor = (what, extra) => `shell.chat-answer-${what}#${entry.questionId} ${controlKey}${extra === undefined ? '' : ` ${extra}`}`;
4248
+ const previous = live.slice(0, live.indexOf(row)).filter((item) => !item.frozen).at(-1);
4249
+ const backToMode = kind === 'height' && !previous && open.length > 1;
4250
+ return { key, question: q, scope, row, label, actions: choices, backToMode,
4251
+ back: previous ? () => reopenDrawingItem(kind, entry, drawingRowKey(kind, previous)) : backToMode ? () => { entry.slotPhase = null; entry.activeItem = null; entry.slotSig = null; drawingSlotRepaint(); } : null,
4252
+ source: (_index, onDraftChange) => drawingSource(kind, entry, scope, label, idFor, row, onDraftChange),
4253
+ validate: (_step, draft) => {
4254
+ const answer = draft.rows[0]; if (answer.choices.length) return '';
4255
+ if (answer.other.trim()) return '';
4256
+ if (kind === 'height' && hasAnswerSource(scope)) return '';
4257
+ return answerSource(scope).files.length ? '' : kind === 'setup' ? 'Type a value, or attach a picture first.' : NO_HEIGHT_NO_SOURCE;
4258
+ },
4259
+ commit: async (answer) => {
4260
+ let payload;
4261
+ if (answer.choices.length) { payload = { ...choices[answer.choices[0]] }; if (payload.action === 'none') payload.note = answer.reason; }
4262
+ else if (answer.other) payload = kind === 'setup' ? { key, action: 'type', typed: answer.other } : { memberId: row.memberId, end: row.end, action: 'type', typed: answer.other };
4263
+ else payload = kind === 'setup' ? { key, action: 'evidence' } : { memberId: row.memberId, end: row.end, action: 'evidence' };
4264
+ return kind === 'setup' ? submitSetupAnswers(entry, [payload], key) : submitHeightAnswers(entry, [payload], key);
4265
+ } };
4266
+ }
4267
+ function drawingHeightBatch(entry, rows) {
4268
+ const base = { header: 'Heights', allowOther: false, id: 'batch', recommended: null };
4269
+ if (!entry.slotPhase) {
4270
+ const confirmable = rows.every((row) => !row.answer && row.proposed);
4271
+ const scope = `hb:${entry.questionId}`, label = `all ${rows.length} proposed member ends`;
4272
+ const idFor = (what, extra) => `shell.chat-answer-${what}#${entry.questionId} bulk${extra === undefined ? '' : ` ${extra}`}`;
4273
+ const inherited = [...new Map(rows.flatMap((row) => row.inherited || []).map((ref) => [ref.attachmentId, ref])).values()];
4274
+ const options = [];
4275
+ if (confirmable) options.push({ shown: `Confirm all ${rows.length} proposed heights`, description: 'Save the values listed above, one for each member end' });
4276
+ options.push({ shown: 'Answer several together', description: 'Choose ends from any group and give them one value or source' }, { shown: 'Answer one by one', description: 'Answer each member end separately' });
4277
+ return { key: 'batch-intro', scope: confirmable ? scope : null, label,
4278
+ source: confirmable ? (_index, onDraftChange) => drawingSource('height', entry, scope, label, idFor, { inherited }, onDraftChange) : null,
4279
+ question: { ...base, question: 'How would you like to answer these heights?', options, recommended: confirmable ? 0 : null,
4280
+ hint: confirmable ? 'Confirm all saves these values. The other choices only choose how to answer.' : 'Choose how to answer; no heights are saved yet.',
4281
+ context: [...rows.map((row) => `${row.label} · ${row.inModel?.profile ? `${row.inModel.profile} · ` : ''}${row.memberId} · ${heightEndWord(row)}.${row.proposed ? ` Proposed: ${row.proposed.asRead} (${row.proposed.value} mm).` : ''} ${row.inModel ? `${heightInModelText(row.inModel, entry.view.units)} ${HEIGHT_PROPOSED_TEXT}` : 'What you confirm or type goes straight into the model.'}${row.fromEvidence ? ` The read’s reading of your ${row.inherited?.length ? 'picture' : 'note'}. Check it before you confirm.` : ''}`), ...(confirmable ? [`Optional source for all ${rows.length} heights. Each end keeps its own proposed value.`] : [])] }, commit: async (answer) => {
4282
+ if (confirmable && answer.choices[0] === 0) return submitHeightAnswers(entry, rows.map((row) => ({ memberId: row.memberId, end: row.end, action: 'confirm', shown: row.proposed.value })), null, hasAnswerSource(scope) ? scope : null);
4283
+ entry.slotPhase = answer.choices[0] === options.length - 1 ? 'row' : 'select'; return true;
4284
+ } };
4285
+ }
4286
+ if (entry.slotPhase === 'select') {
4287
+ const groups = new Map();
4288
+ for (const row of rows) { const members = groups.get(row.group) || []; members.push(row); groups.set(row.group, members); }
4289
+ const ordered = [...groups.values()].flat();
4290
+ return { key: 'batch-select', rows: ordered, question: { ...base, allowClear: true, hint: 'Select ends, then Submit. No heights are saved yet.', question: 'Which member ends should share one answer?', multiSelect: true, options: ordered.map((row) => ({ shown: row.label, group: row.group, description: `${row.memberId} · ${heightEndWord(row)}` })) },
4291
+ initial: ordered.map((row, index) => entry.selected.size ? entry.selected.has(heightEndKey(row)) ? index : -1 : index).filter((index) => index >= 0),
4292
+ back: () => { entry.slotPhase = null; entry.slotSig = null; drawingSlotRepaint(); },
4293
+ commit: async (answer) => { entry.selected = new Set(answer.choices.map((index) => heightEndKey(ordered[index]))); entry.slotPhase = 'value'; return true; } };
4294
+ }
4295
+ const chosen = rows.filter((row) => entry.selected.has(heightEndKey(row)));
4296
+ if (!chosen.length) { entry.slotPhase = 'select'; return drawingHeightBatch(entry, rows); }
4297
+ const shared = chosen.every((row) => row.proposed && row.proposed.value === chosen[0].proposed?.value);
4298
+ const scope = `hb:${entry.questionId}`, label = `${chosen.length} selected member ends`, idFor = (what, extra) => `shell.chat-answer-${what}#${entry.questionId} bulk${extra === undefined ? '' : ` ${extra}`}`;
4299
+ const inherited = [...new Map(chosen.flatMap((row) => row.inherited || []).map((ref) => [ref.attachmentId, ref])).values()];
4300
+ const context = chosen.filter((row) => row.inModel).map((row) => `${row.label}: ${row.inModel.profile || ''}. ${heightInModelText(row.inModel, entry.view.units)} ${HEIGHT_PROPOSED_TEXT}`);
4301
+ if (chosen.some((row) => row.fromEvidence)) context.push(inherited.length ? 'The read’s reading of your picture. Check it before you confirm.' : 'The read’s reading of your note. Check it before you confirm.');
4302
+ return { key: 'batch-value', scope, label, back: () => { entry.slotPhase = 'select'; entry.slotSig = null; drawingSlotRepaint(); },
4303
+ question: { ...base, allowOther: true, context, question: `What height should the ${chosen.length} selected ends use?`,
4304
+ options: shared ? [{ shown: `Confirm ${chosen[0].proposed.asRead} for ${chosen.length}`, description: 'Every selected end has this same proposed value' }] : [], recommended: shared ? 0 : null },
4305
+ source: (_index, onDraftChange) => drawingSource('height', entry, scope, label, idFor, { inherited }, onDraftChange), validate: (_step, draft) => draft.rows[0].choices.length || draft.rows[0].other.trim() || hasAnswerSource(scope) ? '' : NO_HEIGHT_NO_SOURCE,
4306
+ commit: async (answer) => { const answers = chosen.map((row) => ({ memberId: row.memberId, end: row.end, ...(answer.choices.length ? { action: 'confirm', shown: row.proposed.value } : answer.other ? { action: 'type', typed: answer.other } : { action: 'evidence' }) }));
4307
+ const saved = await submitHeightAnswers(entry, answers, null, scope);
4308
+ if (saved) { entry.slotPhase = null; entry.slotDrafts?.delete('batch-value'); entry.slotDrafts?.delete('batch-select'); }
4309
+ return saved; } };
4310
+ }
4311
+ function paintDrawingQuestionSlot() {
4312
+ const tray = ui.approvalTray; if (!tray || !window.FlolessQuestionCard) return false;
4313
+ const showing = tray.querySelector('.ai-chat-drawing-step');
4314
+ const heldFocus = showing?.contains(document.activeElement) ? document.activeElement : null;
4315
+ if (state.chat?.pendingApproval || tray.querySelector('.ai-chat-approval:not(.ai-chat-approval-scope):not(.ai-chat-drawing-step)')) { showing?.remove(); return false; }
4316
+ const entries = [...setupCards.values()].map((entry) => ({ kind: 'setup', entry })).concat([...heightCards.values()].map((entry) => ({ kind: 'height', entry })))
4317
+ .filter(({ entry }) => drawingEntryCurrent(entry) && entry.view?.open && !entry.reloadPending && !entry.loading)
4318
+ .sort((a, b) => ((b.entry.finishActive || b.entry.changing.has(b.entry.activeItem)) ? b.entry.reopenedAt || 0 : 0)
4319
+ - ((a.entry.finishActive || a.entry.changing.has(a.entry.activeItem)) ? a.entry.reopenedAt || 0 : 0) || a.entry.sequence - b.entry.sequence);
4320
+ const candidates = entries.map(({ kind, entry }) => ({ kind, entry, step: drawingStep(kind, entry) })).filter(({ step }) => step);
4321
+ const units = drawingUnitsCandidate(); if (units) candidates.push(units);
4322
+ let chosen = candidates.find(({ entry, step }) => entry.finishActive && step.key === 'finish') || candidates.find(({ step }) => step.key !== 'finish') || candidates[0];
4323
+ if (heldFocus && personIsTyping()) {
4324
+ const current = candidates.find(({ entry, step }) => `${entry.chatId}/${entry.key}/${step.key}` === showing.dataset.drawingStep);
4325
+ const activated = chosen?.entry.finishActive || (chosen?.entry.reopenedAt || 0) > (current?.entry.reopenedAt || 0);
4326
+ if (current && !activated) chosen = current;
4327
+ }
4328
+ if (!chosen) { showing?.remove(); return false; }
4329
+ const { kind, entry, step } = chosen, key = `${entry.chatId}/${entry.key}/${step.key}`;
4330
+ if (showing && showing.dataset.drawingStep !== key) showing.remove();
4331
+ entry.slotDrafts ??= new Map();
4332
+ let draft = entry.slotDrafts.get(step.key);
4333
+ if (!draft) {
4334
+ draft = window.FlolessQuestionCard.createDraft([step.question]);
4335
+ if (step.initial) draft.rows[0].choices = step.initial;
4336
+ if (step.row?.answer?.how === 'typed' && entry.changing.has(step.key)) { draft.rows[0].otherOpen = true; draft.rows[0].other = step.row.answer.typed; }
4337
+ entry.slotDrafts.set(step.key, draft);
4338
+ }
4339
+ const choiceSignature = JSON.stringify(step.question.options);
4340
+ if (draft.choiceSignature && draft.choiceSignature !== choiceSignature) draft.rows[0].choices = [];
4341
+ draft.choiceSignature = choiceSignature;
4342
+ const source = step.scope ? answerSource(step.scope) : null;
4343
+ entry.slotQuestionKey = step.key;
4344
+ const sig = JSON.stringify([key, entry.view, entry.busy, entry.cardError, [...entry.rowErrors], [...entry.changing], [...entry.selected || []], entry.slotPhase,
4345
+ // Typing refreshes Submit availability/carrier in place; note text must not invalidate the live field on a poll.
4346
+ source && [source.open, source.files.map((file) => file.attachmentId), source.uploading, source.error], draft.pending, draft.rows[0].choices, draft.rows[0].otherOpen]);
4347
+ const node = entry.slotNode || document.createElement('section'); entry.slotNode = node;
4348
+ if (node.isConnected && entry.slotSig === sig) return true;
4349
+ const editingSelections = [...node.querySelectorAll('input[data-command-id]')].map((field) => ({ id: field.dataset.commandId, caret: textCaret(field) })).filter(({ caret }) => caret);
4350
+ const focused = node.contains(document.activeElement) ? document.activeElement : heldFocus;
4351
+ const focusId = focused?.dataset.commandId, caret = focused ? textCaret(focused) : null;
4352
+ const freshStep = node.dataset.drawingStep !== key;
4353
+ const sameStepScroll = freshStep ? null : tray.scrollTop;
4354
+ if (freshStep) { delete node.dataset.armedAt; node.lastDrawingField = null; }
4355
+ if (!node.drawingFieldFocus) {
4356
+ node.drawingFieldFocus = (event) => { if (event.target.tagName === 'INPUT' && (event.target.type === 'text' || !event.target.type)) node.lastDrawingField = event.target.dataset.commandId; };
4357
+ node.addEventListener('focusin', node.drawingFieldFocus);
4358
+ }
4359
+ node.className = 'ai-chat-approval ai-chat-ask-card ai-chat-drawing-step'; node.dataset.drawingStep = key;
4360
+ if (!node.isConnected) tray.append(node);
4361
+ window.FlolessQuestionCard.paint(node, { id: encodeURIComponent(key), questions: [step.question], draft, mode: 'per-step', busy: entry.busy ? 'Saving your answer…' : '', error: entry.rowErrors.get(step.key) || entry.cardError,
4362
+ source: step.source, back: step.back, validate: step.validate, files: source ? { list: () => source.files, uploading: () => source.uploading, error: () => source.error,
4363
+ attach: (_index, files) => attachAnswerFiles(step.scope, { requestId: entry.requestId, chatId: entry.chatId, repaint: drawingSlotRepaint,
4364
+ removeFile: (file) => request(`/api/chat/answer-evidence/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(file.attachmentId)}`, { method: 'DELETE', body: JSON.stringify({ chatId: entry.chatId }) }) }, files),
4365
+ remove: (_index, file) => removeAnswerFile(step.scope, { requestId: entry.requestId, chatId: entry.chatId, repaint: drawingSlotRepaint }, file) } : null,
4366
+ carrier: (what, _index, extra) => drawingCarrier(kind, entry, step, draft, what, extra),
4367
+ repaint: () => { entry.slotSig = null; drawingSlotRepaint(); }, commitStep: async (_index, answer) => { const saved = await step.commit(answer); entry.slotSig = null; return saved; },
4368
+ });
4369
+ entry.slotSig = sig;
4370
+ // Rebuilding the same question temporarily shrinks the tray and clamps its scroll position.
4371
+ if (sameStepScroll !== null) tray.scrollTop = sameStepScroll;
4372
+ for (const { id, caret } of editingSelections) {
4373
+ const field = [...node.querySelectorAll('input[data-command-id]')].find((control) => control.dataset.commandId === id);
4374
+ field?.setSelectionRange?.(Math.min(caret.start, field.value.length), Math.min(caret.end, field.value.length), caret.direction);
4375
+ }
4376
+ if (focusId) {
4377
+ focusHeightControl(node, focusId, caret);
4378
+ if (![...node.querySelectorAll('[data-command-id]')].some((control) => control.dataset.commandId === focusId)) window.FlolessQuestionCard.focusCursor(node);
4379
+ } else if (freshStep && !personIsTyping()) window.FlolessQuestionCard.focusCursor(node);
4380
+ return true;
4381
+ }
4382
+ function drawingCarrier(kind, entry, step, draft, what, extra) {
4383
+ const prefix = kind === 'setup' ? 'shell.chat-setup' : 'shell.chat-height';
4384
+ const rowKey = step.row && kind === 'height' ? `${step.row.memberId} ${step.row.endWord}` : step.key;
4385
+ let name = what, suffix = rowKey, instance = step.label || step.question.header;
4386
+ if (kind === 'units') return { id: `shell.chat-units-choose#${extra === 0 ? 'ft-in' : 'mm'}`, instance: extra === 0 ? 'feet and inches' : 'metric (mm)' };
4387
+ if (step.key === 'finish') name = extra === 0 ? 'tell-read' : 'send-read';
4388
+ else if (what === 'option') {
4389
+ if (step.key === 'batch-intro') { name = extra === 0 && step.question.recommended === 0 ? 'confirm-all' : 'mode'; if (name === 'mode') suffix += ` ${extra}`; }
4390
+ else if (step.key === 'batch-select') { name = 'select'; const row = step.rows[extra]; suffix = `${row.memberId} ${row.endWord}`; instance = row.label; }
4391
+ else if (step.key === 'batch-value') name = 'bulk-confirm';
4392
+ else if (step.row?.kind === 'origin' && step.actions[extra]?.action === 'confirm') { name = 'origin-choice'; suffix += ` ${step.actions[extra].choice}`; instance = step.question.options[extra].shown; }
4393
+ else if (step.actions?.[extra]?.action === 'none') name = 'none';
4394
+ else { name = 'confirm'; if (step.actions?.[extra]?.choice) suffix += ` ${step.actions[extra].choice}`; }
4395
+ } else if (what === 'group') { name = 'select-group'; const groups = [...new Set(step.rows.map((row) => row.group).filter(Boolean))]; suffix = groups[extra]; instance = suffix; }
4396
+ else if (what === 'other-input') name = step.key === 'batch-value' ? 'bulk-input' : 'input';
4397
+ else if (what === 'reason') name = 'none-note';
4398
+ else if (what === 'clear') name = 'bulk-clear';
4399
+ else if (what === 'back' && (step.key.startsWith('batch-') || step.backToMode)) name = 'bulk-back';
4400
+ else if (what === 'send') {
4401
+ if (step.key === 'batch-select') name = 'bulk-next';
4402
+ else if (step.key === 'batch-value') name = !draft.rows[0].choices.length && !draft.rows[0].other.trim() && hasAnswerSource(step.scope) ? 'bulk-evidence' : 'bulk-use';
4403
+ else if (step.actions?.[draft.rows[0].choices[0]]?.action === 'none') name = 'none-save';
4404
+ else if (!draft.rows[0].choices.length && !draft.rows[0].other.trim() && hasAnswerSource(step.scope)) name = 'evidence';
4405
+ else name = step.row?.kind === 'origin' && !draft.rows[0].otherOpen ? 'origin-confirm' : 'use';
4406
+ }
4407
+ return { id: `${prefix}-${name}#${entry.questionId} ${suffix}`, instance };
4408
+ }
4409
+ function drawingUnitsCandidate() {
4410
+ const chat = state.chat;
4411
+ if (state.scope?.owner?.kind !== 'workspace' || !chat || chat.archivedAt || (chat.workspaceUnits?.chosen && !state.workspaceUnitsEditing)) return null;
4412
+ state.workspaceUnitsQuestions ??= new Map();
4413
+ let entry = state.workspaceUnitsQuestions.get(chat.chatId);
4414
+ if (!entry) { entry = { key: `units/${chat.chatId}`, chatId: chat.chatId, questionId: chat.chatId, view: { open: true }, rowErrors: new Map(), changing: new Set(), selected: new Set() }; state.workspaceUnitsQuestions.set(chat.chatId, entry); }
4415
+ const values = ['ft-in', 'mm'], suggested = values.indexOf(chat.workspaceUnits?.suggested);
4416
+ const step = { key: 'units', question: { id: 'units', header: 'Units', question: 'Which units should AI use here?', allowOther: false,
4417
+ options: [{ shown: 'Feet and inches', description: 'Show lengths in feet and inches' }, { shown: 'Metric (mm)', description: 'Show lengths in millimetres' }], recommended: suggested < 0 ? null : suggested },
4418
+ commit: async (answer) => Boolean(await chooseWorkspaceUnits(values[answer.choices[0]])) };
4419
+ return { kind: 'units', entry, step };
4420
+ }
3690
4421
  const SETUP_STALE = new Set(['setup-question-changed', 'height-question-closed', 'setup-question-superseded', 'setup-answer-frozen']);
3691
4422
  const SETUP_SECTIONS = [['scale', 'Drawing scale'], ['origin', 'Model origin'], ['level', 'Plan levels']];
3692
4423
 
@@ -3715,7 +4446,7 @@
3715
4446
 
3716
4447
  function repaintSetupCard(entry) {
3717
4448
  const old = ui.feed?.querySelector(`[data-setup-question="${CSS.escape(entry.key)}"]`);
3718
- if (!old) return;
4449
+ if (!old) { drawingSlotRepaint(); return; }
3719
4450
  const focused = old.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
3720
4451
  const caret = focused ? textCaret(document.activeElement) : null;
3721
4452
  const next = rememberCard(entry, paintSetupCard(entry, old.dataset.eventId, old.dataset.eventSequence), old.dataset.eventId, old.dataset.eventSequence);
@@ -3754,113 +4485,10 @@
3754
4485
  }
3755
4486
 
3756
4487
  function paintSetupCard(entry, eventId, sequence) {
3757
- const view = entry.view;
3758
- const card = document.createElement('section');
3759
- card.className = 'ai-chat-filter-card ai-chat-height-card ai-chat-setup-card';
3760
- card.dataset.setupQuestion = entry.key;
3761
- card.dataset.eventId = eventId || '';
3762
- card.dataset.eventSequence = sequence || '';
3763
- card.setAttribute('aria-label', view?.n ? `Read setup, question ${view.n}` : 'Read setup');
3764
- const rows = view ? view.items : [];
3765
- const live = rows.filter(setupLive);
3766
- const settled = live.filter(setupSettled);
3767
- const open = Boolean(view?.open);
3768
- const allSettled = live.length > 0 && settled.length === live.length;
3769
- // Every row the person can answer is answered, but some wait on the READ (a picture to read, or new
3770
- // choices to offer): the person still has to tell it, or the read never looks (E2E #1906).
3771
- const waitsOnRead = (row) => row.status === 'picture' || row.status === 'needs-new-choices';
3772
- const allAnswered = !allSettled && live.length > 0 && live.every((row) => setupSettled(row) || waitsOnRead(row));
3773
- card.dataset.state = !view ? (entry.finished ? 'closed' : 'loading') : !open ? 'closed' : allSettled ? 'answered' : allAnswered ? 'waiting-for-read' : 'open';
3774
-
3775
- const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
3776
- const title = document.createElement('strong'); title.textContent = 'Read setup';
3777
- const chip = document.createElement('span'); chip.className = 'ai-chat-filter-state';
3778
- chip.textContent = !view ? (entry.finished ? 'closed' : 'loading') : !open ? 'closed' : allSettled ? 'settled' : allAnswered ? 'with the read' : 'needs you';
3779
- head.append(title, chip);
3780
- card.append(head);
3781
- const note = document.createElement('p'); note.className = 'ai-chat-filter-note';
3782
- note.textContent = !view
3783
- ? (entry.finished ? CARD_FINISHED_TEXT : entry.loadError || 'Loading the read setup…')
3784
- : open
3785
- ? 'These shape the whole model: each plan’s drawing scale, the model origin and each plan’s level. Only you can answer, and the read uses exactly what you settle here. If something conflicts, it asks you again here.'
3786
- : 'This read is no longer waiting for an answer.';
3787
- card.append(note);
3788
- if (!view) {
3789
- if (entry.loadError) {
3790
- const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
3791
- const retry = heightActionButton('Try again', `shell.chat-setup-retry#${entry.questionId}`, 'the read setup', '');
3792
- retry.addEventListener('click', () => { entry.loadError = ''; repaintSetupCard(entry); loadSetupQuestion(entry); });
3793
- actions.append(retry); card.append(actions);
3794
- }
3795
- return card;
3796
- }
3797
- const questionLabel = `setup question ${view.n}`;
3798
- const count = document.createElement('p'); count.className = 'ai-chat-height-count'; count.setAttribute('aria-live', 'polite'); count.setAttribute('aria-atomic', 'true');
3799
- count.textContent = `${settled.length} of ${live.length} settled`;
3800
- card.append(count);
3801
-
3802
- const body = document.createElement('div'); body.className = 'ai-chat-height-rows ai-chat-setup-body';
3803
- body.setAttribute('role', 'region'); body.setAttribute('aria-label', 'Read setup questions'); body.tabIndex = 0;
3804
- body.dataset.commandId = `shell.chat-setup-body#${entry.questionId}`;
3805
- body.dataset.commandInstanceLabel = questionLabel;
3806
- for (const [kind, name] of SETUP_SECTIONS) {
3807
- const items = rows.filter((row) => row.kind === kind);
3808
- if (!items.length) continue;
3809
- body.append(paintSetupSection(entry, kind, name, items, open));
3810
- }
3811
- card.append(body);
3812
- body.addEventListener('scroll', () => { entry.bodyScroll = body.scrollTop; }, { passive: true });
3813
- if (entry.bodyScroll) requestAnimationFrame(() => { if (body.isConnected) body.scrollTop = entry.bodyScroll; });
3814
-
3815
- const error = document.createElement('p'); error.className = 'ai-chat-height-error'; error.setAttribute('role', 'alert');
3816
- error.textContent = entry.cardError || '';
3817
- card.append(error);
3818
- const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
3819
- if (open && (allSettled || allAnswered)) {
3820
- const done = document.createElement('p'); done.className = 'ai-chat-height-done';
3821
- done.textContent = allSettled
3822
- ? 'All settled. Tell the read puts the message in the box so you can add to it; Send to the read sends it now.'
3823
- : 'All answered. Tell the read puts the message in the box so you can add to it; Send to the read sends it now. The read then looks at what you sent and asks you to confirm its reading here.';
3824
- card.append(done);
3825
- const tell = heightActionButton('Tell the read', `shell.chat-setup-tell-read#${entry.questionId}`, questionLabel, 'ai-chat-filter-apply', null);
3826
- tell.addEventListener('click', () => tellReadAnswered(entry, setupTellText(entry), repaintSetupCard));
3827
- const send = heightActionButton('Send to the read', `shell.chat-setup-send-read#${entry.questionId}`, questionLabel, '', null);
3828
- send.addEventListener('click', () => { void sendToReadAnswered(entry, setupTellText(entry), repaintSetupCard); });
3829
- actions.append(tell, send);
3830
- }
3831
- actions.hidden = !actions.childNodes.length;
3832
- card.append(actions);
3833
- return card;
4488
+ return paintDrawingHistory('setup', entry, eventId, sequence);
3834
4489
  }
3835
4490
 
3836
- function paintSetupSection(entry, kind, name, items, open) {
3837
- const section = document.createElement('div'); section.className = 'ai-chat-setup-section';
3838
- const live = items.filter(setupLive);
3839
- const settled = live.filter(setupSettled).length;
3840
- // The first section with something open starts expanded; a settled one collapses to one line.
3841
- const expanded = entry.expanded.has(kind) ? entry.expanded.get(kind) : (settled < live.length || !open);
3842
- const toggle = document.createElement('button');
3843
- toggle.type = 'button'; toggle.className = 'ai-chat-setup-section-head';
3844
- toggle.dataset.commandId = `shell.chat-setup-section#${entry.questionId} ${kind}`;
3845
- toggle.dataset.commandInstanceLabel = name;
3846
- toggle.setAttribute('aria-expanded', String(expanded));
3847
- const label = document.createElement('span'); label.textContent = name;
3848
- const tally = document.createElement('span'); tally.className = 'ai-chat-filter-state';
3849
- tally.textContent = settled === live.length ? '✓ settled' : `${settled}/${live.length}`;
3850
- toggle.append(label, tally);
3851
- toggle.addEventListener('click', () => { entry.expanded.set(kind, !expanded); repaintSetupCard(entry); });
3852
- section.append(toggle);
3853
- if (!expanded) {
3854
- const summary = document.createElement('p'); summary.className = 'ai-chat-setup-summary';
3855
- summary.textContent = live.map((row) => `${row.kind === 'origin' ? 'Origin' : row.view.sheet} ${setupAnswerText(row) || 'open'}`).join(' · ');
3856
- section.append(summary);
3857
- return section;
3858
- }
3859
- const list = document.createElement('ol'); list.className = 'ai-chat-setup-list';
3860
- for (const row of items) list.append(paintSetupRow(entry, row, open));
3861
- section.append(list);
3862
- return section;
3863
- }
4491
+
3864
4492
 
3865
4493
  function setupConflictBanner(row) {
3866
4494
  if (!row.conflict) return null;
@@ -3910,10 +4538,7 @@
3910
4538
  change.setAttribute('aria-label', `Change your answer for ${instance}`);
3911
4539
  change.addEventListener('click', () => {
3912
4540
  if (change.getAttribute('aria-disabled') === 'true') return;
3913
- entry.changing.add(row.key);
3914
- // A "none" answer's note is the person's REASON, not a source: it is not put in the source box.
3915
- if (row.answer.note && row.answer.how !== 'none') { const source = answerSource(`s:${entry.questionId}:${row.key}`); source.open = true; source.note = source.note || row.answer.note; }
3916
- repaintSetupCard(entry);
4541
+ reopenDrawingItem('setup', entry, row.key);
3917
4542
  });
3918
4543
  done.append(change);
3919
4544
  }
@@ -3931,7 +4556,7 @@
3931
4556
  if (open) {
3932
4557
  const change = heightActionButton('Answer now', idFor('change'), instance, 'ai-chat-height-change', null);
3933
4558
  change.setAttribute('aria-label', `Answer ${instance} yourself instead`);
3934
- change.addEventListener('click', () => { entry.changing.add(row.key); repaintSetupCard(entry); });
4559
+ change.addEventListener('click', () => reopenDrawingItem('setup', entry, row.key));
3935
4560
  wait.append(change);
3936
4561
  }
3937
4562
  item.append(wait);
@@ -3945,73 +4570,14 @@
3945
4570
  return item;
3946
4571
  }
3947
4572
  if (row.frozen) { const frozen = document.createElement('p'); frozen.className = 'ai-chat-setup-frozen'; frozen.textContent = row.frozen; item.append(frozen); return item; }
3948
- const busyReason = entry.busy ? 'An answer is still being saved — wait for it to finish' : null;
3949
- const scope = `s:${entry.questionId}:${row.key}`;
3950
- if (row.kind === 'scale') paintScaleControls(entry, row, item, instance, idFor, busyReason, scope);
3951
- else if (row.kind === 'level') paintLevelControls(entry, row, item, instance, idFor, busyReason, scope);
3952
- else paintOriginControls(entry, row, item, instance, idFor, busyReason, scope);
3953
- item.append(paintAnswerSource(scope, {
3954
- requestId: entry.requestId, chatId: entry.chatId, repaint: () => repaintSetupCard(entry), label: instance, instance,
3955
- idFor: sourceIdFor, inherited: row.inherited, busyReason, allowPictureOnly: true,
3956
- onPictureOnly: () => submitSetupAnswers(entry, [{ key: row.key, action: 'evidence' }], row.key),
3957
- }));
3958
- const rowError = document.createElement('p'); rowError.className = 'ai-chat-height-error'; rowError.setAttribute('role', 'alert');
3959
- rowError.textContent = entry.rowErrors.get(row.key) || '';
3960
- item.append(rowError);
3961
4573
  return item;
3962
4574
  }
3963
4575
 
3964
- function setupProposal(valueText, tag, evidence, confirm) {
3965
- const box = document.createElement('div'); box.className = 'ai-chat-setup-proposal';
3966
- const line = document.createElement('div'); line.className = 'ai-chat-height-proposal';
3967
- const value = document.createElement('span'); value.textContent = valueText;
3968
- line.append(value, confirm);
3969
- const source = document.createElement('div'); source.className = 'ai-chat-setup-evidence';
3970
- const label = document.createElement('span'); label.className = 'ai-chat-setup-tag'; label.textContent = tag;
3971
- source.append(label, document.createTextNode(` ${evidence}`));
3972
- source.dataset.tip = `${tag}: ${evidence}`;
3973
- box.append(line, source);
3974
- return box;
3975
- }
3976
4576
 
3977
- function setupTypedField(entry, row, item, instance, idFor, busyReason, placeholder, ariaWhat, primary) {
3978
- const field = document.createElement('div'); field.className = 'ai-chat-height-field';
3979
- const input = document.createElement('input');
3980
- input.type = 'text'; input.className = 'ai-chat-height-input'; input.autocomplete = 'off'; input.spellcheck = false;
3981
- input.dataset.commandId = idFor('input'); input.dataset.commandInstanceLabel = instance;
3982
- input.placeholder = placeholder;
3983
- input.setAttribute('aria-label', `${ariaWhat} for ${instance}`);
3984
- input.value = entry.drafts.get(row.key) || '';
3985
- input.addEventListener('input', () => { entry.drafts.set(row.key, input.value); entry.rowErrors.delete(row.key); if (row.kind === 'origin' && input.value) entry.originPick = null; });
3986
- if (busyReason) { input.readOnly = true; input.setAttribute('aria-disabled', 'true'); input.dataset.blockedReason = busyReason; }
3987
- const use = heightActionButton('Use', idFor('use'), instance, primary ? 'ai-chat-filter-apply' : '', busyReason);
3988
- use.setAttribute('aria-label', `Use what you typed for ${instance}`);
3989
- const submit = () => {
3990
- if (use.getAttribute('aria-disabled') === 'true') return;
3991
- const typed = input.value.trim();
3992
- if (!typed) { entry.rowErrors.set(row.key, 'Type an answer first.'); repaintSetupCard(entry); return; }
3993
- submitSetupAnswers(entry, [{ key: row.key, action: 'type', typed }], row.key);
3994
- };
3995
- input.addEventListener('keydown', (event) => { if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); submit(); } });
3996
- use.addEventListener('click', submit);
3997
- field.append(input, use);
3998
- item.append(field);
3999
- }
4000
-
4001
- function paintScaleControls(entry, row, item, instance, idFor, busyReason, scope) {
4002
- if (row.clue) { const clue = document.createElement('p'); clue.className = 'ai-chat-setup-why'; clue.textContent = row.clue; item.append(clue); }
4003
- for (const proposal of row.proposals) {
4004
- const confirm = heightActionButton(proposal.pageFit ? 'Use for this plan' : 'Confirm', idFor('confirm', proposal.id), instance, 'ai-chat-filter-apply', busyReason);
4005
- confirm.setAttribute('aria-label', `${proposal.pageFit ? 'Use' : 'Confirm'} ${proposal.standard} for ${instance}`);
4006
- confirm.addEventListener('click', () => {
4007
- if (confirm.getAttribute('aria-disabled') === 'true') return;
4008
- submitSetupAnswers(entry, [{ key: row.key, action: 'confirm', choice: proposal.id, shown: proposal.mmPerPx }], row.key);
4009
- });
4010
- // The Confirm records mmPerPx, so the exact number is shown beside the standard (Codex review #1906).
4011
- item.append(setupProposal(`${proposal.standard} · ${scaleNumber(proposal.mmPerPx)} mm per drawing point`, scaleTag[proposal.source] || 'PROPOSED', proposal.evidence, confirm));
4012
- }
4013
- setupTypedField(entry, row, item, instance, idFor, busyReason, 'or type a scale, e.g. 1/4" = 1\'-0" or 1:100', 'Type the scale', !row.proposals.length);
4014
- }
4577
+
4578
+
4579
+
4580
+
4015
4581
 
4016
4582
  const scaleNumber = (mmPerPx) => String(Number(Number(mmPerPx).toFixed(6)));
4017
4583
 
@@ -4022,143 +4588,47 @@
4022
4588
  return 'Read from the picture you sent. Check it before you confirm.';
4023
4589
  }
4024
4590
 
4025
- function paintLevelControls(entry, row, item, instance, idFor, busyReason, scope) {
4026
- if (row.noSingleLevel) { const why = document.createElement('p'); why.className = 'ai-chat-setup-why'; why.textContent = `No single level on the drawings: ${row.noSingleLevel.why}`; item.append(why); }
4027
- const units = entry.view?.units;
4028
- for (const proposal of row.proposals) {
4029
- const confirm = heightActionButton('Confirm', idFor('confirm', proposal.id), instance, 'ai-chat-filter-apply', busyReason);
4030
- confirm.setAttribute('aria-label', `Confirm ${proposal.asRead} for ${instance}`);
4031
- confirm.addEventListener('click', () => {
4032
- if (confirm.getAttribute('aria-disabled') === 'true') return;
4033
- submitSetupAnswers(entry, [{ key: row.key, action: 'confirm', choice: proposal.id, shown: proposal.value }], row.key);
4034
- });
4035
- item.append(setupProposal(proposal.asRead, levelTag[proposal.source] || 'PROPOSED', levelEvidence(proposal), confirm));
4036
- }
4037
- setupTypedField(entry, row, item, instance, idFor, busyReason, units === 'mm' ? 'or type a level, e.g. 4870 mm' : 'or type a level, e.g. 16\'-6"', 'Type the level', !row.proposals.length);
4038
- paintNoneControl(entry, row, item, instance, idFor, busyReason, 'No single level', 'Short note (required), e.g. 1\'-6" TOF west, 0\'-0" east', 'Save: no single level');
4039
- }
4040
4591
 
4041
- function paintNoneControl(entry, row, item, instance, idFor, busyReason, label, placeholder, saveLabel) {
4042
- if (!entry.noneOpen.has(row.key)) {
4043
- const none = heightActionButton(label, idFor('none'), instance, 'ai-chat-setup-secondary', busyReason);
4044
- none.setAttribute('aria-label', `${label} for ${instance}`);
4045
- none.addEventListener('click', () => {
4046
- if (none.getAttribute('aria-disabled') === 'true') return;
4047
- entry.noneOpen.add(row.key); repaintSetupCard(entry);
4048
- const card = ui.feed.querySelector(`[data-setup-question="${CSS.escape(entry.key)}"]`);
4049
- if (card) focusHeightControl(card, idFor('none-note'));
4050
- });
4051
- item.append(none);
4052
- return;
4053
- }
4054
- const field = document.createElement('div'); field.className = 'ai-chat-height-field';
4055
- const note = document.createElement('input');
4056
- note.type = 'text'; note.className = 'ai-chat-height-input'; note.maxLength = 160; note.autocomplete = 'off';
4057
- note.dataset.commandId = idFor('none-note'); note.dataset.commandInstanceLabel = instance;
4058
- note.placeholder = placeholder;
4059
- note.setAttribute('aria-label', `Why: ${label.toLowerCase()} for ${instance}`);
4060
- note.required = true;
4061
- const noteKey = `${row.key}\u0000none`;
4062
- note.value = entry.drafts.get(noteKey) || '';
4063
- note.addEventListener('input', () => { entry.drafts.set(noteKey, note.value); entry.rowErrors.delete(row.key); });
4064
- const save = heightActionButton(saveLabel, idFor('none-save'), instance, '', busyReason);
4065
- const submit = () => {
4066
- if (save.getAttribute('aria-disabled') === 'true') return;
4067
- const text = note.value.trim();
4068
- if (!text) { entry.rowErrors.set(row.key, 'Add a short note first, so the read knows what to do instead.'); repaintSetupCard(entry); return; }
4069
- submitSetupAnswers(entry, [{ key: row.key, action: 'none', note: text }], row.key);
4070
- };
4071
- note.addEventListener('keydown', (event) => { if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); submit(); } });
4072
- save.addEventListener('click', submit);
4073
- field.append(note, save);
4074
- item.append(field);
4075
- }
4076
-
4077
- function paintOriginControls(entry, row, item, instance, idFor, busyReason, scope) {
4078
- const group = document.createElement('fieldset'); group.className = 'ai-chat-setup-origin';
4079
- group.setAttribute('role', 'radiogroup');
4080
- const legend = document.createElement('legend'); legend.textContent = 'Which grid crossing is the model’s origin (0, 0)?';
4081
- group.append(legend);
4082
- const radio = (choiceId, text, tag) => {
4083
- const label = document.createElement('label'); label.className = 'ai-chat-setup-choice';
4084
- const input = document.createElement('input');
4085
- input.type = 'radio'; input.name = `origin-${entry.questionId}`; input.value = choiceId;
4086
- input.dataset.commandId = idFor('origin-choice', choiceId); input.dataset.commandInstanceLabel = text;
4087
- input.checked = entry.originPick === choiceId;
4088
- if (busyReason) { input.disabled = true; }
4089
- input.addEventListener('change', () => { entry.originPick = choiceId; entry.drafts.delete(row.key); entry.rowErrors.delete(row.key); repaintSetupCard(entry); });
4090
- const name = document.createElement('span'); name.className = 'ai-chat-setup-choice-name'; name.textContent = text;
4091
- label.append(input, name);
4092
- if (tag) { const t = document.createElement('span'); t.className = 'ai-chat-setup-tag'; t.textContent = tag; label.append(t); }
4093
- return label;
4094
- };
4095
- const straight = document.createElement('div'); straight.className = 'ai-chat-setup-choices';
4096
- row.choices.forEach((choice, i) => straight.append(radio(`c${i}`, originText(choice), row.proposed === i ? (row.fromEvidence ? 'THE READ’S READING OF YOUR PICTURE' : 'THE READ SUGGESTS') : '')));
4097
- group.append(straight);
4098
- if (row.offGrid.length) {
4099
- const also = document.createElement('fieldset'); also.className = 'ai-chat-setup-also';
4100
- const legend2 = document.createElement('legend'); legend2.textContent = 'Also on the drawing (not straight grid lines)';
4101
- also.append(legend2);
4102
- row.offGrid.forEach((point, i) => also.append(radio(`o${i}`, point.as, '')));
4103
- group.append(also);
4104
- }
4105
- item.append(group);
4106
- const pick = entry.originPick;
4107
- let target = null;
4108
- if (pick && pick.startsWith('c')) target = row.choices[Number(pick.slice(1))] || null;
4109
- let statement = null;
4110
- if (pick && pick.startsWith('o')) {
4111
- const point = row.offGrid[Number(pick.slice(1))];
4112
- target = point ? row.choices[point.same] : null;
4113
- if (point && target) {
4114
- // Said BEFORE the confirm, and the confirm itself names the straight intersection that lands.
4115
- statement = document.createElement('div'); statement.className = 'ai-chat-setup-statement';
4116
- statement.setAttribute('role', 'status');
4117
- statement.id = `setup-statement-${entry.questionId}`;
4118
- statement.textContent = `${point.as} is not a straight grid line in the model, so it cannot be the origin. The read says it is the same point as ${originText(target)} (${point.why}). This is the read’s claim; FloLess has not checked it.`;
4119
- item.append(statement);
4120
- }
4121
- }
4122
- const confirmLabel = target ? `Confirm ${originText(target)} as the model origin` : 'Confirm the model origin';
4123
- const confirm = heightActionButton(confirmLabel, idFor('origin-confirm'), instance, 'ai-chat-filter-apply', busyReason || (target ? null : 'Pick a point first'));
4124
- if (statement) confirm.setAttribute('aria-describedby', statement.id);
4125
- confirm.addEventListener('click', () => {
4126
- if (confirm.getAttribute('aria-disabled') === 'true' || !target) return;
4127
- submitSetupAnswers(entry, [{ key: row.key, action: 'confirm', choice: pick, shown: originText(target) }], row.key);
4128
- });
4129
- const actions = document.createElement('div'); actions.className = 'ai-chat-height-proposal';
4130
- actions.append(confirm);
4131
- item.append(actions);
4132
- setupTypedField(entry, row, item, instance, idFor, busyReason, 'or type a point, e.g. K/1.1', 'Type the grid point', false);
4133
- paintNoneControl(entry, row, item, instance, idFor, busyReason, 'None of these', 'Short note (required), e.g. use the corner at C/0.5', 'Save: none of these');
4134
- }
4592
+
4593
+
4594
+
4595
+
4135
4596
 
4136
4597
  async function submitSetupAnswers(entry, answers, rowKey) {
4137
- if (entry.busy) return;
4598
+ if (entry.busy) return false;
4599
+ const ownedSlot = drawingEntryCurrent(entry) && ui.approvalTray?.querySelector('.ai-chat-drawing-step')?.dataset.drawingStep;
4600
+ const ownedNode = ownedSlot ? ui.approvalTray.querySelector('.ai-chat-drawing-step') : null;
4601
+ const pendingFocusId = ownedNode?.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
4602
+ const failedField = ownedNode && ([...ownedNode.querySelectorAll('input')].find((field) => field.dataset.commandId === ownedNode.lastDrawingField) || ownedNode.querySelector('.ai-chat-ask-other-input'));
4603
+ const failedFieldId = failedField?.dataset.commandId, failedCaret = failedField ? textCaret(failedField) : null;
4604
+ let saved = false;
4138
4605
  const withSource = answers.map((answer) => withAnswerSource(answer, answerSourcePayload(`s:${entry.questionId}:${answer.key}`)));
4139
- const tooLong = withSource.find((answer) => answer.note && answer.note.length > MAX_ANSWER_NOTE);
4140
- if (tooLong) {
4141
- entry.rowErrors.set(rowKey, `Your reason and your source note together are longer than ${MAX_ANSWER_NOTE} characters. Shorten one of them.`);
4142
- repaintSetupCard(entry); return;
4143
- }
4144
- if (withSource.some((answer) => answer.action === 'evidence' && !answer.evidence?.length)) {
4145
- entry.rowErrors.set(rowKey, 'Attach a picture first.'); repaintSetupCard(entry); return;
4146
- }
4147
- entry.busy = true; entry.cardError = ''; if (rowKey) entry.rowErrors.delete(rowKey);
4148
- repaintSetupCard(entry);
4149
4606
  try {
4607
+ const tooLong = withSource.find((answer) => answer.note && answer.note.length > MAX_ANSWER_NOTE);
4608
+ if (tooLong) {
4609
+ entry.rowErrors.set(rowKey, `Your reason and your source note together are longer than ${MAX_ANSWER_NOTE} characters. Shorten one of them.`);
4610
+ return false;
4611
+ }
4612
+ if (withSource.some((answer) => answer.action === 'evidence' && !answer.evidence?.length)) {
4613
+ entry.rowErrors.set(rowKey, 'Attach a picture first.'); return false;
4614
+ }
4615
+ entry.busy = true; entry.cardError = ''; if (rowKey) entry.rowErrors.delete(rowKey);
4616
+ repaintSetupCard(entry);
4150
4617
  const result = await request(`/api/chat/setup-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}/answers`, {
4151
4618
  method: 'POST', body: JSON.stringify({ chatId: entry.chatId, answers: withSource }),
4152
4619
  });
4153
4620
  entry.view = result.question;
4621
+ saved = true;
4154
4622
  for (const answer of answers) {
4155
4623
  entry.changing.delete(answer.key); entry.drafts.delete(answer.key); entry.drafts.delete(`${answer.key}\u0000none`);
4624
+ if (entry.activeItem === answer.key) { entry.activeItem = null; entry.reopenedAt = 0; }
4156
4625
  entry.noneOpen.delete(answer.key);
4157
4626
  if (answer.key === 'origin') entry.originPick = null;
4158
4627
  clearAnswerSource(`s:${entry.questionId}:${answer.key}`);
4159
4628
  }
4160
4629
  } catch (error) {
4161
4630
  let message = heightErrorText(error, 'FloLess could not save this answer. Try again.');
4631
+ 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.';
4162
4632
  if (error?.code === 'answer-evidence-unknown') message = dropStaleAnswerFiles(answers.map((answer) => `s:${entry.questionId}:${answer.key}`), entry);
4163
4633
  if (SETUP_STALE.has(error?.code)) { entry.cardError = message; entry.view = null; loadSetupQuestion(entry); }
4164
4634
  else if (rowKey) entry.rowErrors.set(rowKey, message);
@@ -4167,8 +4637,14 @@
4167
4637
  entry.busy = false;
4168
4638
  repaintSetupCard(entry);
4169
4639
  settlePendingReload(entry, loadSetupQuestion);
4170
- focusNextSetupControl(entry);
4640
+ const currentSlot = ui.approvalTray?.querySelector('.ai-chat-drawing-step');
4641
+ if (ownedSlot && drawingEntryCurrent(entry) && ownedSlot === currentSlot?.dataset.drawingStep
4642
+ && pendingFocusId && currentSlot.contains(document.activeElement) && document.activeElement.dataset.commandId === pendingFocusId) {
4643
+ if (saved) focusNextSetupControl(entry);
4644
+ else if (failedFieldId) focusHeightControl(currentSlot, failedFieldId, failedCaret);
4645
+ }
4171
4646
  }
4647
+ return saved;
4172
4648
  }
4173
4649
 
4174
4650
  // After an answer, keyboard focus moves to the next row still open, or to Tell the read.
@@ -4750,10 +5226,17 @@
4750
5226
  ui.feed.append(renderAgentRunLine(event));
4751
5227
  continue;
4752
5228
  }
4753
- if (event.type === 'connection-proposal-update') continue;
5229
+ if (event.type === 'connection-proposal-update' || event.type === 'view-command-update') continue;
4754
5230
  if (event.type === 'connection-proposal' || event.type === 'connection-check') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
4755
5231
  // #2046: the Guide's next-move cards are held under the answer they were suggested in, like the cards above.
4756
5232
  if (event.type === 'next-move') { const node = renderEvent(event); if (node) links.push({ turnId: event.turnId, node }); continue; }
5233
+ if (event.type === 'next-move-update') { renderEvent(event); continue; }
5234
+ // #2247: an action suggestion or an action the AI ran is held under the answer, like the cards above; an update
5235
+ // only changes its card (which reads it when it repaints).
5236
+ if (event.type === 'action-proposal-update') continue;
5237
+ if (event.type === 'action-proposal' || event.type === 'action-call') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
5238
+ // #2255: a model view change is written mid-answer while the tool waits, so it is held under the answer too.
5239
+ if (event.type === 'view-command') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
4757
5240
  if (['tool', 'usage', 'knowledge-citation', 'attachment', 'compaction', 'state'].includes(event.type)) continue;
4758
5241
  // FloLess's own receipts (object links #1653; evidence looks and suggestion cards #1859) are written mid-answer while a tool runs:
4759
5242
  // held and shown under the answer, so they never cut one answer into fragments.
@@ -4873,26 +5356,47 @@
4873
5356
  }
4874
5357
 
4875
5358
  function paintApproval() {
5359
+ clearSettledQuestionDrafts(state.events, state.chat);
4876
5360
  paintApprovalScope();
4877
5361
  const existing = shell.querySelector('.ai-chat-approval:not(.ai-chat-approval-scope)');
4878
5362
  const approval = state.chat?.pendingApproval;
4879
5363
  const deciding = Boolean(approval && state.decidingApprovalIds.has(approval.approvalId));
4880
5364
  shell.dataset.approvalPending = String(Boolean(approval) && !deciding);
5365
+ // #2223 Revision 6: a question Codex asked without waiting, while no approval holds the slot — a blocking question or an
5366
+ // action the AI is waiting on always goes first, and this one shows once it has settled. The chat is waiting on the person.
5367
+ const asking = approval ? null : openAsyncQuestion(state.events, state.chat);
5368
+ if (asking) shell.dataset.approvalPending = 'true';
4881
5369
  document.dispatchEvent(new CustomEvent('floless:chat-indicator'));
4882
- if (!approval || deciding) { existing?.remove(); return; }
4883
- // Keep the same buttons during polling so keyboard focus and pointer clicks survive. A Tekla card
4884
- // also carries the permission view it offers "Allow for this chat" on, so a change repaints it.
5370
+ if (asking && window.FlolessQuestionCard) {
5371
+ if (existing?.dataset.approvalId === asking.approvalId && existing.classList.contains('ai-chat-ask-card')) return;
5372
+ existing?.remove();
5373
+ paintQuestionCard(asking, null);
5374
+ return;
5375
+ }
5376
+ if (!approval || deciding) {
5377
+ if (existing && !existing.classList.contains('ai-chat-drawing-step')) existing.remove();
5378
+ if (!paintDrawingQuestionSlot()) existing?.remove();
5379
+ return;
5380
+ }
5381
+ // #2223: the AI is asking the person. Its card keeps the person's draft across repaints, so a card already showing this
5382
+ // question repaints only from its own changes (a choice, a file, sending), never from a poll.
5383
+ if (approval.kind === 'question' && approval.question && window.FlolessQuestionCard) {
5384
+ if (existing?.dataset.approvalId === approval.approvalId && existing.classList.contains('ai-chat-ask-card')) return;
5385
+ existing?.remove();
5386
+ paintQuestionCard(approval, null);
5387
+ return;
5388
+ }
5389
+ // Keep the same buttons during polling so keyboard focus and pointer clicks survive. A card also carries the
5390
+ // permission views its wider choices are offered on (epic #2185 Slice A), so a change to any of them repaints it.
4885
5391
  const teklaBinding = teklaAllowableApproval(approval) ? currentTeklaBinding(state.chat) : null;
4886
5392
  // #1890 PR 2b: a workspace conversation's file change, with the projects/workflows it touches.
4887
5393
  const change = approval.change && typeof approval.change === 'object' ? approval.change : null;
4888
- // #1907: a call to one of the person's connectors FloLess could identify may be allowed for the whole chat.
4889
- const connector = approval.connector?.verified ? approval.connector : null;
4890
- // #1900: a connection check the AI asked for; "Allow for this chat" only when the server says it may be.
5394
+ // #1907: a call to one of the person's connectors.
5395
+ const connector = approval.connector && typeof approval.connector === 'object' ? approval.connector : null;
5396
+ // #1900: a connection check the AI asked for.
4891
5397
  const connectionCheck = approval.connectionCheck && typeof approval.connectionCheck === 'object' ? approval.connectionCheck : null;
4892
- const allowanceRevision = connectionCheck ? String(state.chat?.integrationReadAllowance?.revision ?? 0)
4893
- : change ? String(state.chat?.changeAllowance?.revision ?? 0)
4894
- : teklaBinding ? String(teklaAllowanceRevision(teklaBinding))
4895
- : connector ? String(state.chat?.connectorAllowance?.revision ?? 0) : '';
5398
+ const offer = approvalOffer(approval);
5399
+ const allowanceRevision = offer ? offerStamp(offer) : '';
4896
5400
  if (existing?.dataset.approvalId === approval.approvalId && (existing.dataset.allowanceRevision || '') === allowanceRevision) return;
4897
5401
  // A permission change repaints the same approval: keep keyboard focus on the same control.
4898
5402
  const refocus = existing?.dataset.approvalId === approval.approvalId && existing.contains(document.activeElement)
@@ -4906,7 +5410,7 @@
4906
5410
  card.classList.add('has-flo'); card.append(flo);
4907
5411
  floAvatar(flo, { size: 28, mood: 'yourcall', hat: true });
4908
5412
  }
4909
- if (teklaBinding || connector || change || connectionCheck) card.dataset.allowanceRevision = allowanceRevision;
5413
+ card.dataset.allowanceRevision = allowanceRevision;
4910
5414
  // #1890 PR 3a: the AI asking to create a workflow, with where it would go.
4911
5415
  const create = approval.create && typeof approval.create === 'object' ? approval.create : null;
4912
5416
  if (approval.scopeAdd) {
@@ -4919,10 +5423,9 @@
4919
5423
  card.setAttribute('aria-labelledby', heading.id);
4920
5424
  const copy = document.createElement('p');
4921
5425
  const readOnly = state.chat?.settings?.permissionProfile === 'read-only';
4922
- const writeProfile = state.chat?.owner?.kind === 'workspace' ? 'Make changes (asks first)' : 'Working folder write';
4923
5426
  copy.textContent = readOnly
4924
5427
  ? 'The AI’s file tools cannot change files while Read only is on. Commands keep their own approvals and may authorize file changes.'
4925
- + (scope.allowsFileChanges ? ` If you choose ${writeProfile}, file changes here will also be allowed without asking.` : '')
5428
+ + (scope.allowsFileChanges ? ' If you choose Working folder write, file changes here will also be allowed without asking.' : '')
4926
5429
  : scope.allowsFileChanges ? 'File changes here will also be allowed without asking. Commands and tools keep their own approvals.'
4927
5430
  : 'Adds this folder to the conversation. Your current file approval setting stays unchanged.';
4928
5431
  const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
@@ -4930,119 +5433,402 @@
4930
5433
  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');
4931
5434
  deny.addEventListener('click', () => decideApproval('deny'));
4932
5435
  allow.addEventListener('click', () => decideApproval('allow'));
4933
- actions.append(deny, allow); card.append(heading, copy, actions);
5436
+ actions.append(deny, allow); card.append(heading, copy, actions, ...widerChoices(approval, offer));
4934
5437
  ui.approvalTray.append(card);
4935
5438
  if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
4936
5439
  ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
4937
5440
  return;
4938
5441
  }
4939
- if (create) {
4940
- paintCreateCard(card, approval, create);
4941
- ui.approvalTray.append(card);
4942
- if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
4943
- ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
4944
- return;
5442
+ if (create) {
5443
+ paintCreateCard(card, approval, create, offer);
5444
+ ui.approvalTray.append(card);
5445
+ if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
5446
+ ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
5447
+ return;
5448
+ }
5449
+ if (change) {
5450
+ paintChangeCard(card, approval, change, offer);
5451
+ ui.approvalTray.append(card);
5452
+ if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
5453
+ ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
5454
+ return;
5455
+ }
5456
+ const heading = document.createElement('strong'); heading.textContent = 'Approval needed';
5457
+ const copy = document.createElement('p'); copy.textContent = approval.summary;
5458
+ const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
5459
+ const deny = button('Deny', 'shell.chat-approval-deny');
5460
+ const allow = button('Approve once', 'shell.chat-approval-allow', 'allow');
5461
+ deny.addEventListener('click', () => decideApproval('deny'));
5462
+ allow.addEventListener('click', () => decideApproval('allow'));
5463
+ if (connectionCheck) {
5464
+ paintConnectionCheckApproval(card, approval, connectionCheck, { heading, copy, actions, deny, allow }, offer);
5465
+ ui.approvalTray.append(card);
5466
+ if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
5467
+ // A new question: Deny is the safe default, unless the person is typing a message.
5468
+ else if (existing?.dataset.approvalId !== approval.approvalId && !(document.activeElement === ui.input && ui.input.value)) deny.focus({ preventScroll: true });
5469
+ ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
5470
+ return;
5471
+ }
5472
+ actions.append(deny, allow);
5473
+ const nodes = [heading, copy];
5474
+ if (connector) {
5475
+ card.dataset.explicitOnly = 'true';
5476
+ // The warning is the part that decides it: on its own line, not at the end of the question.
5477
+ const split = approval.summary.indexOf(' FloLess cannot check');
5478
+ const warning = document.createElement('p');
5479
+ warning.className = 'ai-chat-approval-warning';
5480
+ if (split > 0) {
5481
+ copy.textContent = approval.summary.slice(0, split);
5482
+ warning.textContent = approval.summary.slice(split + 1);
5483
+ }
5484
+ if (warning.textContent) nodes.push(warning);
5485
+ } else if (offer && offer.kind !== 'tool') card.dataset.explicitOnly = 'true';
5486
+ // #2196: a command naming a workflow's protected files arrives flagged, as "<one-line reason>\nCommand: <command>"
5487
+ // (the server keeps the reason to one line, so the first marker is the separator). The command goes in its own
5488
+ // block, exactly as it will run (spacing kept, long tokens wrapped, a long one scrolls). Nothing else is split.
5489
+ const commandAt = approval.protectedCommand === true && !connector ? approval.summary.indexOf('\nCommand: ') : -1;
5490
+ if (commandAt >= 0) {
5491
+ copy.textContent = approval.summary.slice(0, commandAt);
5492
+ const block = document.createElement('pre');
5493
+ block.className = 'ai-chat-approval-cmd';
5494
+ block.tabIndex = 0;
5495
+ block.setAttribute('aria-label', 'Command that will run');
5496
+ const code = document.createElement('code');
5497
+ code.textContent = approval.summary.slice(commandAt + '\nCommand: '.length);
5498
+ block.append(code);
5499
+ nodes.push(block);
5500
+ }
5501
+ card.append(...nodes, actions, ...widerChoices(approval, offer));
5502
+ ui.approvalTray.append(card);
5503
+ if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
5504
+ // When a request-wide grant notice is also present, keep the decision nearest the composer.
5505
+ ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
5506
+ }
5507
+
5508
+ /*
5509
+ * #2223 — the AI's question card (web/chat-question-card.js), above the message box. The draft lives here, by approval
5510
+ * id, so a repaint, a reconnect or a refused send never loses what the person chose or typed (R12, Revision 2). Sending
5511
+ * shows "Sending…" on the card instead of removing it: only the server's answer closes it.
5512
+ */
5513
+ const questionDrafts = new Map();
5514
+ const questionScope = (approvalId, index) => `ask:${approvalId}:${index}`;
5515
+
5516
+ function questionEntry(approval) {
5517
+ let entry = questionDrafts.get(approval.approvalId);
5518
+ if (!entry) {
5519
+ entry = { chatId: state.chat?.chatId, async: Boolean(approval.async), draft: window.FlolessQuestionCard.createDraft(approval.question.questions), busy: '', error: '' };
5520
+ questionDrafts.set(approval.approvalId, entry);
5521
+ }
5522
+ return entry;
5523
+ }
5524
+
5525
+ /** Forget closed questions and their previews, keeping a still-open card even behind another approval. */
5526
+ function clearSettledQuestionDrafts(events, chat) {
5527
+ if (!chat) return;
5528
+ const observed = Array.isArray(events) ? events : [];
5529
+ for (const [id, entry] of questionDrafts) {
5530
+ if (entry.chatId !== chat.chatId) continue;
5531
+ // An older or partial snapshot may omit a live card. Only its recorded settlement is proof it closed.
5532
+ const askedAt = entry.async ? observed.findIndex((event) => event.eventId === id && event.type === 'assistant-message' && event.payload?.asyncQuestion) : -1;
5533
+ const settled = entry.async
5534
+ ? askedAt >= 0 && observed.slice(askedAt + 1).some((event) => (event.type === 'user-message' && !event.optimistic) || (event.type === 'assistant-message' && event.payload?.asyncQuestion))
5535
+ : observed.some((event) => event.type === 'approval-decided' && event.payload?.kind === 'question' && event.payload.approvalId === id);
5536
+ if (!chat.archivedAt && !settled) continue;
5537
+ questionDrafts.delete(id);
5538
+ for (let index = 0; index < entry.draft.rows.length; index += 1) clearAnswerSource(questionScope(id, index));
5539
+ }
5540
+ }
5541
+
5542
+ function questionCardNode(approvalId) {
5543
+ return [...ui.approvalTray.querySelectorAll('.ai-chat-ask-card')].find((node) => node.dataset.approvalId === approvalId) || null;
5544
+ }
5545
+
5546
+ /** The Other… box's files, through the Drawing Filter answer source's machinery (types, sizes, three per answer). */
5547
+ function questionFiles(approval) {
5548
+ const snapshot = captureChat();
5549
+ const base = () => `/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/questions/${encodeURIComponent(approval.approvalId)}/files`;
5550
+ const repaint = () => { const card = questionCardNode(approval.approvalId); if (card && sameChat(snapshot)) paintQuestionCard(approval, card); };
5551
+ const ctx = {
5552
+ chatId: snapshot?.chatId, requestId: null, repaint,
5553
+ upload: (file, data) => request(base(), { method: 'POST', timeoutMs: 120000,
5554
+ body: JSON.stringify({ owner: snapshot.scope.owner, fileName: file.name || 'screenshot.png', mediaType: file.type, data }) }),
5555
+ removeFile: (file) => request(`${base()}/${encodeURIComponent(file.attachmentId)}`, { method: 'DELETE', body: JSON.stringify({ owner: snapshot.scope.owner }) }),
5556
+ };
5557
+ return {
5558
+ max: MAX_ANSWER_FILES,
5559
+ list: (index) => answerSource(questionScope(approval.approvalId, index)).files,
5560
+ uploading: (index) => answerSource(questionScope(approval.approvalId, index)).uploading,
5561
+ error: (index) => answerSource(questionScope(approval.approvalId, index)).error,
5562
+ attach: (index, files) => { if (snapshot) void attachAnswerFiles(questionScope(approval.approvalId, index), ctx, files); },
5563
+ remove: (index, file) => { if (snapshot) void removeAnswerFile(questionScope(approval.approvalId, index), ctx, file); },
5564
+ };
5565
+ }
5566
+
5567
+ function paintQuestionCard(approval, existing) {
5568
+ const entry = questionEntry(approval);
5569
+ const fresh = !existing;
5570
+ const card = existing || document.createElement('section');
5571
+ if (fresh) {
5572
+ card.className = 'ai-chat-approval ai-chat-ask-card';
5573
+ card.dataset.approvalId = approval.approvalId;
5574
+ if (approval.async) card.dataset.askAsync = 'true';
5575
+ // #2079: Flo, hat on, faces the person: the AI is asking, and the person decides.
5576
+ if (typeof floAvatar === 'function') {
5577
+ const flo = document.createElement('span'); flo.className = 'ai-chat-approval-flo';
5578
+ card.classList.add('has-flo'); card.append(flo);
5579
+ floAvatar(flo, { size: 28, mood: 'yourcall', hat: true });
5580
+ }
5581
+ ui.approvalTray.append(card);
5582
+ }
5583
+ // A repaint keeps keyboard focus (and the caret in the answer box) on the same control.
5584
+ const focused = !fresh && card.contains(document.activeElement) ? document.activeElement : null;
5585
+ const refocus = focused?.dataset?.commandId || null;
5586
+ let caret = null;
5587
+ try { if (focused && typeof focused.selectionStart === 'number') caret = [focused.selectionStart, focused.selectionEnd]; } catch { caret = null; }
5588
+ window.FlolessQuestionCard.paint(card, {
5589
+ id: approval.approvalId, questions: approval.question.questions, draft: entry.draft, busy: entry.busy, error: entry.error,
5590
+ // #2223 Revision 6: an async question's answer is the person's next message, its files that message's files.
5591
+ // Operator ruling 2026-10-12 (review round 4): an async question's answer is the person's next message, so its files
5592
+ // go with a message from the box, whose paperclip attaches them; its Other… box takes words only.
5593
+ files: approval.async ? null : questionFiles(approval),
5594
+ ...(approval.async ? { otherHint: 'Type your own answer, or write it in the message box below to attach a file' } : {}),
5595
+ repaint: () => paintQuestionCard(approval, card),
5596
+ submit: () => { void (approval.async ? submitAsyncQuestion(approval) : submitQuestion(approval)); },
5597
+ });
5598
+ const target = refocus ? [...card.querySelectorAll('[data-command-id]')].find((node) => node.dataset.commandId === refocus) : null;
5599
+ if (target) {
5600
+ target.focus({ preventScroll: true });
5601
+ if (caret) { try { target.setSelectionRange(caret[0], caret[1]); } catch { /* no caret on this control */ } }
5602
+ } else if (focused || (fresh && !personIsTyping())) {
5603
+ // A new question: the recommended answer has focus, unless the person is typing a message.
5604
+ window.FlolessQuestionCard.focusCursor(card);
5605
+ if (fresh && !card.contains(document.activeElement)) focusQuestionWhenShown(card);
5606
+ }
5607
+ // A new card opens at its top, where the question and the recommended answer are: scrolled to its end, a card taller
5608
+ // than the tray hid both (UX review). A repaint keeps the control in use in sight; the actions row sticks anyway.
5609
+ const tray = ui.approvalTray;
5610
+ if (fresh) tray.scrollTop += card.getBoundingClientRect().top - tray.getBoundingClientRect().top;
5611
+ // In the Other… box that is the whole box, so a file just attached shows its chip (E2E 2026-10-12: it landed out of sight).
5612
+ else if (card.contains(document.activeElement)) {
5613
+ (document.activeElement.closest('.ai-chat-ask-other') || document.activeElement).scrollIntoView?.({ block: 'nearest' });
5614
+ }
5615
+ }
5616
+
5617
+ /**
5618
+ * A question that arrives while AI Chat is collapsed (or the page is reloaded with the chat closed) cannot take focus
5619
+ * — a hidden element refuses it — so the number keys would do nothing once the person opens the chat (E2E 2026-10-12).
5620
+ * It takes focus the first time it is shown, unless the person is typing somewhere by then.
5621
+ */
5622
+ /**
5623
+ * Someone is writing: words in the message box, or any other text field (a chat being renamed, a search). A new question
5624
+ * card never takes focus from them, or the next digit they type would choose an answer (code review 2026-10-12). An empty
5625
+ * message box is where the person just sent from, so the card may take focus from it.
5626
+ */
5627
+ function personIsTyping() {
5628
+ const active = document.activeElement;
5629
+ if (!active || active === document.body) return false;
5630
+ if (active === ui.input) return Boolean(ui.input.value);
5631
+ return Boolean(active.isContentEditable) || /^(INPUT|TEXTAREA|SELECT)$/.test(active.tagName);
5632
+ }
5633
+
5634
+ function focusQuestionWhenShown(card) {
5635
+ const Observer = window.IntersectionObserver;
5636
+ if (typeof Observer !== 'function') return;
5637
+ const watch = new Observer((entries) => {
5638
+ if (!entries.some((entry) => entry.isIntersecting)) return;
5639
+ watch.disconnect();
5640
+ if (card.isConnected && !personIsTyping()) window.FlolessQuestionCard.focusCursor(card);
5641
+ });
5642
+ watch.observe(card);
5643
+ }
5644
+
5645
+ async function submitQuestion(approval) {
5646
+ const entry = questionEntry(approval);
5647
+ const snapshot = captureChat();
5648
+ if (!snapshot || entry.busy) return;
5649
+ const questions = approval.question.questions;
5650
+ const repaint = () => { const card = questionCardNode(approval.approvalId); if (card) paintQuestionCard(approval, card); };
5651
+ if (questions.some((_, index) => answerSource(questionScope(approval.approvalId, index)).uploading)) {
5652
+ entry.error = 'A file is still attaching. Wait for it to finish, then send.';
5653
+ repaint(); return;
5654
+ }
5655
+ const answers = window.FlolessQuestionCard.answersFor(questions, entry.draft, (index) => answerSource(questionScope(approval.approvalId, index)).files);
5656
+ entry.busy = 'Sending…'; entry.error = '';
5657
+ repaint();
5658
+ announce('Sending your answer to the AI…');
5659
+ try {
5660
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/approvals/${encodeURIComponent(approval.approvalId)}`, {
5661
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, decision: 'answer', answers }),
5662
+ });
5663
+ const outcome = result?.outcome;
5664
+ // The files now belong to the answer (or to a card that closed): forget the drafts and the chips' previews. The
5665
+ // card's state is settled even when the person has moved to another chat (code review 2026-10-12: returning first
5666
+ // left it saying "Sending…" for good); only what is painted and said waits for this chat.
5667
+ questionDrafts.delete(approval.approvalId);
5668
+ questions.forEach((_, index) => clearAnswerSource(questionScope(approval.approvalId, index)));
5669
+ if (!sameChat(snapshot)) return;
5670
+ // Code review 2026-10-12: the AI stopped before the answer reached it, so the person's own words go back in the
5671
+ // message box (after anything already there) to send once it can take them; the conversation's record keeps them too.
5672
+ const kept = outcome?.outcome === 'lost' && typeof outcome.otherText === 'string' && outcome.otherText ? outcome.otherText : '';
5673
+ if (kept) {
5674
+ const words = ui.input.value.trim();
5675
+ ui.input.value = words ? `${words}\n\n${kept}` : kept;
5676
+ ui.input.dispatchEvent(new Event('input', { bubbles: true }));
5677
+ }
5678
+ announce(outcome?.delivered ? 'Your answer was handed to the AI.'
5679
+ : `${outcome?.message || 'The question closed before your answer reached the AI.'}${kept ? ' Your words are back in the message box.' : ''}`);
5680
+ await refreshConversation(snapshot.chatId, false);
5681
+ } catch (error) {
5682
+ entry.busy = '';
5683
+ // The server says what happened in words; anything else (FloLess unreachable) gets a sentence of its own.
5684
+ entry.error = error?.code && error?.message ? error.message
5685
+ : 'FloLess could not send your answer just now. Make sure FloLess is still running, then send it again.';
5686
+ if (error?.code === 'answer-evidence-unknown') {
5687
+ for (const [index] of questions.entries()) {
5688
+ const source = answerSources.get(questionScope(approval.approvalId, index));
5689
+ if (!source) continue;
5690
+ for (const file of source.files) if (file.url) URL.revokeObjectURL(file.url);
5691
+ source.files = [];
5692
+ }
5693
+ }
5694
+ if (!sameChat(snapshot)) return;
5695
+ repaint();
5696
+ announce(entry.error);
5697
+ await refreshConversation(snapshot.chatId, false);
5698
+ }
5699
+ }
5700
+
5701
+ /**
5702
+ * #2223: the conversation's record of a question card: the question, ✓ the person's answer, the files they attached —
5703
+ * or, when the card closed without their answer reaching the AI, the plain sentence the server wrote.
5704
+ */
5705
+ function renderQuestionAnswered(event) {
5706
+ const payload = event.payload || {};
5707
+ const answered = payload.outcome === 'answered';
5708
+ const item = document.createElement('div');
5709
+ item.className = `ai-chat-event ai-chat-ask-answered${answered ? '' : ' is-unanswered'}`;
5710
+ item.dataset.eventSequence = String(event.sequence);
5711
+ item.dataset.eventId = event.eventId;
5712
+ const rows = Array.isArray(payload.answers) ? payload.answers : [];
5713
+ const filesOf = (row) => (Array.isArray(row?.files) ? row.files.filter((file) => file && typeof file.attachmentId === 'string') : []);
5714
+ const gave = (row) => Boolean(typeof row?.answer === 'string' && row.answer) || filesOf(row).length > 0;
5715
+ // Code review 2026-10-12: an answer that did not reach the AI, or may not have, keeps what the person gave; the note
5716
+ // below says what became of it. Only a delivered answer carries the tick.
5717
+ const kept = !answered && rows.some(gave);
5718
+ const label = document.createElement('strong');
5719
+ label.textContent = answered ? 'You answered' : kept ? 'Your answer' : 'Not answered';
5720
+ item.append(label);
5721
+ for (const row of rows) {
5722
+ const line = document.createElement('div'); line.className = 'ai-chat-ask-answered-row';
5723
+ const asked = document.createElement('span'); asked.className = 'ai-chat-ask-answered-q';
5724
+ asked.textContent = typeof row?.question === 'string' ? row.question : '';
5725
+ line.append(asked);
5726
+ const files = answered || kept ? filesOf(row) : [];
5727
+ if (answered || (kept && gave(row))) {
5728
+ const reply = document.createElement('span'); reply.className = 'ai-chat-ask-answered-a';
5729
+ if (answered) {
5730
+ const tick = document.createElement('span'); tick.className = 'ai-chat-ask-tick'; tick.setAttribute('aria-hidden', 'true'); tick.textContent = '✓';
5731
+ reply.append(tick);
5732
+ }
5733
+ reply.append(document.createTextNode(typeof row?.answer === 'string' && row.answer ? row.answer : files.length ? 'See the attached file' : 'Answered'));
5734
+ line.append(reply);
5735
+ }
5736
+ if (files.length) {
5737
+ const chips = document.createElement('div'); chips.className = 'ai-chat-message-attachments ai-chat-ask-answered-files';
5738
+ chips.append(...files.map((file) => renderChatAttachment({ attachmentId: file.attachmentId, fileName: String(file.fileName || 'file'),
5739
+ mediaType: String(file.mediaType || '') })));
5740
+ line.append(chips);
5741
+ }
5742
+ item.append(line);
5743
+ }
5744
+ if (!answered && typeof payload.message === 'string' && payload.message) {
5745
+ const note = document.createElement('p'); note.className = 'ai-chat-ask-answered-note'; note.textContent = payload.message;
5746
+ item.append(note);
4945
5747
  }
4946
- if (change) {
4947
- paintChangeCard(card, approval, change, Number(allowanceRevision));
4948
- ui.approvalTray.append(card);
4949
- if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
4950
- ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
4951
- return;
5748
+ return item;
5749
+ }
5750
+
5751
+ /*
5752
+ * #2223 Revision 6 — Codex's async question (measured 2026-10-12, codex-cli 0.162.1). Codex can ask without waiting: the
5753
+ * question rides on the assistant message that asks it (`asyncQuestion`, shaped by the server like any card), the reply
5754
+ * goes on, and Codex's own app sends the person's answer as their next message. So the question stays open until the
5755
+ * person's next message: the latest such message with no message of the person's after it, in a conversation that is not
5756
+ * archived. A message still on its way (optimistic) does not close it, so a send that fails leaves the card as it was;
5757
+ * the message the person types in the box instead is an answer too, and closes it the same way. Reading the
5758
+ * conversation again (a reload) finds it again: it is all in the stored events.
5759
+ */
5760
+ function openAsyncQuestion(events, chat) {
5761
+ if (!chat || chat.archivedAt || !Array.isArray(events)) return null;
5762
+ for (let index = events.length - 1; index >= 0; index -= 1) {
5763
+ const event = events[index];
5764
+ if (event?.type === 'user-message' && !event.optimistic) return null;
5765
+ const set = event?.type === 'assistant-message' ? event.payload?.asyncQuestion : null;
5766
+ if (!set) continue;
5767
+ // The latest question decides: one the card cannot show is no card, never an older one in its place.
5768
+ const shown = Array.isArray(set.questions) && set.questions.length > 0 && set.questions.every((question) => question
5769
+ && typeof question.id === 'string' && typeof question.question === 'string' && Array.isArray(question.options)
5770
+ && question.options.every((option) => option && typeof option.label === 'string' && typeof option.shown === 'string'));
5771
+ return shown ? { approvalId: event.eventId, async: true, question: { questions: set.questions } } : null;
4952
5772
  }
4953
- const heading = document.createElement('strong'); heading.textContent = 'Approval needed';
4954
- const copy = document.createElement('p'); copy.textContent = approval.summary;
4955
- const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
4956
- const deny = button('Deny', 'shell.chat-approval-deny');
4957
- const allow = button('Approve once', 'shell.chat-approval-allow', 'allow');
4958
- // A Tekla read is never covered by a request-wide grant; it may instead be allowed for the whole chat (below).
4959
- const explicitOnly = approvalIsExplicitOnly(approval) || Boolean(connectionCheck);
4960
- const allowRequest = explicitOnly ? null : button('Approve for this request', 'shell.chat-approval-request', 'allow');
4961
- // #2162: the same coverage as "Approve for this request", held for the rest of the conversation. Never on a card
4962
- // that must ask every time (the same test that hides the request grant), nor in the Guide, which only reads.
4963
- const allowSession = explicitOnly || state.chat?.initiator?.kind === 'guide' ? null
4964
- : button('Approve for this conversation', 'shell.chat-approval-session', 'allow');
4965
- const scope = document.createElement('span');
4966
- scope.className = 'sr-only';
4967
- scope.id = `chat-approval-request-help-${approval.approvalId}`;
4968
- deny.addEventListener('click', () => decideApproval('deny'));
4969
- allow.addEventListener('click', () => decideApproval('allow'));
4970
- if (allowRequest) {
4971
- scope.textContent = 'Approve access actions until this response finishes. Your permission setting stays unchanged. Review checkpoints still ask every time, and Tekla reads ask unless you allow them for this chat.';
4972
- allowRequest.dataset.tip = scope.textContent;
4973
- allowRequest.setAttribute('aria-describedby', scope.id);
4974
- allowRequest.addEventListener('click', () => decideApproval('allow-request'));
4975
- actions.append(deny, allow, allowRequest); card.append(heading, copy, actions, scope);
4976
- if (allowSession) {
4977
- const sessionScope = document.createElement('span');
4978
- sessionScope.className = 'sr-only';
4979
- sessionScope.id = `chat-approval-session-help-${approval.approvalId}`;
4980
- sessionScope.textContent = 'Approve access actions for the rest of this conversation, not only this response, until you press Revoke. Your permission setting stays unchanged. Review checkpoints, Tekla reads and connector calls still ask, and so do file changes in a workspace conversation. Revoke it above the message box.';
4981
- allowSession.dataset.tip = sessionScope.textContent;
4982
- allowSession.setAttribute('aria-describedby', sessionScope.id);
4983
- allowSession.addEventListener('click', () => decideApproval('allow-session'));
4984
- actions.append(allowSession); card.append(sessionScope);
4985
- }
4986
- } else if (connectionCheck) {
4987
- paintConnectionCheckApproval(card, approval, connectionCheck, { heading, copy, actions, deny, allow }, Number(allowanceRevision));
4988
- ui.approvalTray.append(card);
4989
- if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
4990
- // A new question: Deny is the safe default, unless the person is typing a message.
4991
- else if (existing?.dataset.approvalId !== approval.approvalId && !(document.activeElement === ui.input && ui.input.value)) deny.focus({ preventScroll: true });
4992
- ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
5773
+ return null;
5774
+ }
5775
+
5776
+ /**
5777
+ * The answer as the message Codex's own app would send: the chosen answer's own label (as the AI wrote it), or the
5778
+ * person's words; with several questions, one line each, "<question>: <answer>".
5779
+ */
5780
+ function asyncAnswerMessage(questions, draft) {
5781
+ const answers = questions.map((question, index) => {
5782
+ const row = draft.rows[index];
5783
+ const parts = [...row.choices].sort((a, b) => a - b).map((choice) => question.options[choice]?.shown).filter(Boolean);
5784
+ const own = row.otherOpen ? row.other.trim() : '';
5785
+ if (own) parts.push(own);
5786
+ return parts.join(', ');
5787
+ });
5788
+ return questions.length === 1 ? answers[0]
5789
+ : questions.map((question, index) => `${question.question.replace(/\s+/g, ' ').trim()}: ${answers[index]}`).join('\n');
5790
+ }
5791
+
5792
+
5793
+ /**
5794
+ * Sending an async question's answer: an ordinary message through the chat's own send (a new turn, or a follow-up while
5795
+ * the reply still runs). The card shows "Sending…" and closes when that message is in the conversation; one that did not
5796
+ * go keeps the card and the draft, and says why on the card.
5797
+ */
5798
+ async function submitAsyncQuestion(approval) {
5799
+ const entry = questionEntry(approval);
5800
+ const snapshot = captureChat();
5801
+ if (!snapshot || entry.busy) return;
5802
+ const questions = approval.question.questions;
5803
+ const repaint = () => { const card = questionCardNode(approval.approvalId); if (card) paintQuestionCard(approval, card); };
5804
+ const text = asyncAnswerMessage(questions, entry.draft);
5805
+ entry.busy = 'Sending…'; entry.error = '';
5806
+ repaint();
5807
+ let result;
5808
+ try { result = await sendTurn({ message: { text, attachments: [] } }); }
5809
+ catch (error) { result = { sent: false, message: errorMessage(error) }; }
5810
+ // Settled whichever chat is open now; only painting and announcing wait for this one (code review 2026-10-12).
5811
+ entry.busy = '';
5812
+ if (result?.sent === true) {
5813
+ questionDrafts.delete(approval.approvalId);
5814
+ if (sameChat(snapshot)) paintApproval();
4993
5815
  return;
4994
- } else if (connector) {
4995
- card.dataset.explicitOnly = 'true';
4996
- // The warning is the part that decides it: on its own line, not at the end of the question.
4997
- const split = approval.summary.indexOf(' FloLess cannot check');
4998
- const warning = document.createElement('p');
4999
- warning.className = 'ai-chat-approval-warning';
5000
- if (split > 0) {
5001
- copy.textContent = approval.summary.slice(0, split);
5002
- warning.textContent = approval.summary.slice(split + 1);
5003
- }
5004
- const who = connectorLabel(connector);
5005
- const allowChat = button(`Allow ${who} for this chat`, `shell.chat-connector-allow-chat#${connectorKey(connector)}`, 'allow');
5006
- allowChat.dataset.commandInstanceLabel = who;
5007
- const help = document.createElement('span');
5008
- help.className = 'sr-only';
5009
- help.id = `chat-approval-connector-scope-help-${approval.approvalId}`;
5010
- help.textContent = `Let ${who} run whenever Chat asks in this conversation, without asking you each time. Each run is shown in the chat. Revoke it above the message box.`;
5011
- allowChat.dataset.tip = help.textContent;
5012
- allowChat.setAttribute('aria-describedby', help.id);
5013
- allowChat.addEventListener('click', () => decideApproval('allow-chat', Number(allowanceRevision)));
5014
- actions.append(deny, allow, allowChat); card.append(heading, copy, ...(warning.textContent ? [warning] : []), actions, help);
5015
- } else if (teklaBinding) {
5016
- // A Tekla read may instead be allowed for the whole chat, covering every read the chat is bound for.
5017
- card.dataset.explicitOnly = 'true';
5018
- const allowChat = button('Allow for this chat', 'shell.chat-tekla-allow-chat', 'allow');
5019
- const help = document.createElement('span');
5020
- help.className = 'sr-only';
5021
- help.id = `chat-approval-tekla-scope-help-${approval.approvalId}`;
5022
- help.textContent = `Let Chat read ${teklaReadsCopy(teklaBinding.operations, ' and ')} whenever it asks in this conversation, without asking you each time. FloLess still checks Tekla live and shows every result. Revoke it from the Tekla box above the message.`;
5023
- allowChat.dataset.tip = help.textContent;
5024
- allowChat.setAttribute('aria-describedby', help.id);
5025
- allowChat.addEventListener('click', () => decideApproval('allow-chat', Number(allowanceRevision)));
5026
- actions.append(deny, allow, allowChat); card.append(heading, copy, actions, help);
5027
- } else {
5028
- card.dataset.explicitOnly = 'true';
5029
- actions.append(deny, allow); card.append(heading, copy, actions);
5030
5816
  }
5031
- ui.approvalTray.append(card);
5032
- if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
5033
- // When a request-wide grant notice is also present, keep the decision nearest the composer.
5034
- ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
5817
+ entry.error = result?.message || 'Your answer was not sent. Send it again.';
5818
+ if (!sameChat(snapshot)) return;
5819
+ repaint();
5820
+ announce(entry.error);
5035
5821
  }
5036
5822
 
5037
5823
  /**
5038
5824
  * #1900 — the card for a connection check the AI asked for. The server's summary is the whole question; the two
5039
5825
  * things that decide it (a tool FloLess has not reviewed, a key sent to an address) are pulled out onto their own
5040
- * lines. Never "Approve for this request": each check is approved once, or allowed for this chat when the server
5041
- * says that is safe (reviewed, no custom key, an identified account, a pinned tool).
5826
+ * lines. Like every card it offers the full set (epic #2185 Slice A); the conversation choice is the older allowance when
5827
+ * the server says that is safe (reviewed, no custom key, an identified account, a pinned tool), else exactly this plan.
5042
5828
  */
5043
5829
  const CONNECTION_UNREVIEWED_SENTENCE = 'This check comes from a tool FloLess has not reviewed.';
5044
5830
 
5045
- function paintConnectionCheckApproval(card, approval, check, parts, allowanceRevision) {
5831
+ function paintConnectionCheckApproval(card, approval, check, parts, offer) {
5046
5832
  const { heading, copy, actions, deny, allow } = parts;
5047
5833
  card.dataset.explicitOnly = 'true';
5048
5834
  card.classList.add('ai-chat-connection-approval');
@@ -5073,22 +5859,7 @@
5073
5859
  }
5074
5860
  // Deny and Approve once already answer through paintApproval's own listeners.
5075
5861
  actions.append(deny, allow);
5076
- const nodes = [heading, copy, ...extra, actions];
5077
- if (check.chatAllowable === true) {
5078
- const label = check.kind === 'host' ? `Allow checks of ${name} for this chat` : `Allow checks of ${name} with this account for this chat`;
5079
- const key = `${check.agent}${check.alias ? `.${check.alias}` : ''}`;
5080
- const allowChat = button(label, `shell.chat-connection-check-allow-chat#${key}`, 'allow');
5081
- allowChat.dataset.commandInstanceLabel = name;
5082
- const help = document.createElement('span');
5083
- help.className = 'sr-only';
5084
- help.id = `chat-approval-check-scope-help-${approval.approvalId}`;
5085
- help.textContent = `Let Chat check ${name}${check.kind === 'host' ? '' : ' with this account'} whenever it asks in this conversation, without asking you each time. Each check is shown in the chat. Revoke it above the message box.`;
5086
- allowChat.dataset.tip = help.textContent;
5087
- allowChat.setAttribute('aria-describedby', help.id);
5088
- allowChat.addEventListener('click', () => decideApproval('allow-chat', allowanceRevision));
5089
- actions.append(allowChat);
5090
- nodes.push(help);
5091
- }
5862
+ const nodes = [heading, copy, ...extra, actions, ...widerChoices(approval, offer)];
5092
5863
  card.append(...nodes);
5093
5864
  }
5094
5865
 
@@ -5114,7 +5885,7 @@
5114
5885
  }
5115
5886
 
5116
5887
  /** The card for a workspace conversation's file change: where it lands, then Deny / Approve once / Allow for this chat. */
5117
- function paintChangeCard(card, approval, change, allowanceRevision) {
5888
+ function paintChangeCard(card, approval, change, offer) {
5118
5889
  card.dataset.explicitOnly = 'true';
5119
5890
  card.classList.add('ai-chat-change');
5120
5891
  card.setAttribute('role', 'group');
@@ -5153,23 +5924,7 @@
5153
5924
  deny.addEventListener('click', () => decideApproval('deny'));
5154
5925
  allow.addEventListener('click', () => decideApproval('allow'));
5155
5926
  actions.append(deny, allow);
5156
- if (change.owners?.length) {
5157
- const label = 'Allow file changes for this chat';
5158
- const key = change.owners.map((owner) => owner.key).join('+');
5159
- const allowChat = button(label, `shell.chat-change-allow-chat#${key}`, 'allow');
5160
- allowChat.dataset.commandInstanceLabel = changeNames(change);
5161
- const help = document.createElement('span');
5162
- help.className = 'ai-chat-change-scope-help';
5163
- help.id = `chat-change-scope-help-${id}`;
5164
- help.textContent = 'Allows file changes in this conversation’s scope, including folders you add later, without asking you each time. Commands and tools still ask. Your home folder keeps its current permission setting. Revoke it above the message box.';
5165
- allowChat.dataset.tip = help.textContent;
5166
- allowChat.setAttribute('aria-describedby', help.id);
5167
- allowChat.addEventListener('click', () => decideApproval('allow-chat', allowanceRevision));
5168
- actions.append(allowChat);
5169
- card.append(heading, copy, changeOwnerList(change), actions, help);
5170
- return;
5171
- }
5172
- card.append(heading, copy, actions);
5927
+ card.append(heading, copy, ...(change.owners?.length ? [changeOwnerList(change)] : []), actions, ...widerChoices(approval, offer));
5173
5928
  }
5174
5929
 
5175
5930
  /** Why a workflow the AI asked to create can only be dismissed (#1890 PR 3a); the server says the same to the AI. */
@@ -5182,8 +5937,8 @@
5182
5937
  return create.destination?.kind === 'project' ? `in project ${create.destination.label}` : 'on its own, outside any project';
5183
5938
  }
5184
5939
 
5185
- /** The card for the AI asking to create a workflow: what and where, then Deny / Create workflow. Approve once only. */
5186
- function paintCreateCard(card, approval, create) {
5940
+ /** The card for the AI asking to create a workflow: what and where, then Deny / Create workflow, then the wider choices. */
5941
+ function paintCreateCard(card, approval, create, offer) {
5187
5942
  card.dataset.explicitOnly = 'true';
5188
5943
  card.classList.add('ai-chat-change', 'ai-chat-create');
5189
5944
  card.setAttribute('role', 'group');
@@ -5241,7 +5996,7 @@
5241
5996
  deny.addEventListener('click', () => decideApproval('deny'));
5242
5997
  allow.addEventListener('click', () => decideApproval('allow'));
5243
5998
  actions.append(deny, allow);
5244
- card.append(heading, copy, list, actions);
5999
+ card.append(heading, copy, list, actions, ...widerChoices(approval, offer));
5245
6000
  }
5246
6001
 
5247
6002
  /** Each project or workflow the change touches, with up to five of its files. */
@@ -5281,6 +6036,136 @@
5281
6036
  return list;
5282
6037
  }
5283
6038
 
6039
+ /*
6040
+ * Epic #2185 Slice A (owner ruling 7): EVERY approval card offers Deny, Approve once, Approve for this request and
6041
+ * Approve for this conversation. `approvalOffer` says, for the card on screen, exactly WHAT each wider choice covers (the
6042
+ * same fingerprint rules as server/chat-approval-grants.ts, worded for a person), where the conversation grant is kept
6043
+ * (so the right revision travels with the click) and which instructor command the button is. The server stays the
6044
+ * authority: it recomputes the fingerprint and refuses a click decided on an older view.
6045
+ */
6046
+ function approvalOffer(approval) {
6047
+ const chat = state.chat;
6048
+ if (!approval || !chat) return null;
6049
+ const requestRevision = chat.activeTurn?.requestGrantRevision ?? 0;
6050
+ const change = approval.change && typeof approval.change === 'object' ? approval.change : null;
6051
+ const create = approval.create && typeof approval.create === 'object' ? approval.create : null;
6052
+ const check = approval.connectionCheck && typeof approval.connectionCheck === 'object' ? approval.connectionCheck : null;
6053
+ const connector = approval.connector && typeof approval.connector === 'object' ? approval.connector : null;
6054
+ const base = { requestRevision, decision: 'allow-chat', warning: '' };
6055
+ const PROTECTED_NOTE = ' A workflow’s own records (its .lock, settings and conversations) always ask.';
6056
+ if (change) {
6057
+ if (change.refused || change.busy) return null;
6058
+ if (!change.owners?.length) {
6059
+ // Only the AI's own folder: no project or workflow to name, still a file change with its own fingerprint.
6060
+ if (!change.scratchPaths?.length) return null;
6061
+ return { ...base, kind: 'change', key: 'change:scratch', revision: chat.approvalGrants?.revision ?? 0,
6062
+ what: 'File changes in the AI’s own folder', protectedNote: PROTECTED_NOTE, commandId: 'shell.chat-approval-grant-chat', instance: 'file changes in its own folder' };
6063
+ }
6064
+ return { ...base, kind: 'change', key: 'change', revision: chat.changeAllowance?.revision ?? 0,
6065
+ what: 'File changes in this chat’s folders', conversationExtra: ', including folders you add later', protectedNote: PROTECTED_NOTE,
6066
+ commandId: `shell.chat-change-allow-chat#${change.owners.map((owner) => owner.key).join('+')}`, instance: changeNames(change) };
6067
+ }
6068
+ if (create) {
6069
+ if (create.refused || create.busy) return null;
6070
+ const inProject = create.destination?.kind === 'project';
6071
+ return { ...base, kind: 'create', key: inProject ? 'create:project' : 'create:standalone', revision: chat.approvalGrants?.revision ?? 0,
6072
+ what: inProject ? 'Creating workflows in a project, and drafting inside them' : 'Creating standalone workflows, and drafting inside them',
6073
+ commandId: 'shell.chat-approval-grant-chat', instance: inProject ? create.destination.label : 'standalone workflows' };
6074
+ }
6075
+ if (approval.scopeAdd) {
6076
+ const write = Boolean(approval.scopeAdd.allowsFileChanges || chat.changeAllowance?.allowedForChat
6077
+ || (chat.activeTurn?.requestGrants || []).some((grant) => grant.key === 'change'));
6078
+ return { ...base, kind: write ? 'scope-write' : 'scope-read', key: write ? 'scope:write' : 'scope:read', revision: chat.approvalGrants?.revision ?? 0,
6079
+ what: write ? 'Adding projects and workflows to this chat, together with file changes in them' : 'Adding projects and workflows to this chat for reading only',
6080
+ commandId: 'shell.chat-approval-grant-chat', instance: 'adding scope' };
6081
+ }
6082
+ if (connector) {
6083
+ const who = connectorLabel(connector);
6084
+ if (connector.verified) {
6085
+ return { ...base, kind: 'connector', key: `connector:${connectorKey(connector)}`, revision: chat.connectorAllowance?.revision ?? 0,
6086
+ what: `Calls to ${who}`, commandId: `shell.chat-connector-allow-chat#${connectorKey(connector)}`, instance: who };
6087
+ }
6088
+ return { ...base, kind: 'connector-unverified', key: 'connector:unverified', revision: chat.approvalGrants?.revision ?? 0,
6089
+ what: 'Any connector call FloLess cannot identify', commandId: 'shell.chat-approval-grant-chat', instance: 'unidentified connector calls',
6090
+ warning: 'FloLess cannot tell which connector this is, so this covers every call it cannot identify, not just this one.' };
6091
+ }
6092
+ if (check) {
6093
+ const name = String(check.name || check.agent || 'this tool');
6094
+ const allowable = check.chatAllowable === true && check.reviewed && !check.sendsCustomKey && (check.kind === 'host' || Boolean(check.lastStableId));
6095
+ const route = check.kind === 'account' && !check.lastStableId ? ' through this key (the account could not be identified)' : '';
6096
+ const key = `${check.agent}${check.alias ? `.${check.alias}` : ''}`;
6097
+ return allowable
6098
+ ? { ...base, kind: 'check', key: `check:${key}`, revision: chat.integrationReadAllowance?.revision ?? 0,
6099
+ what: `Exactly this check of ${name}`, conversationWhat: `Checks of ${name}${check.kind === 'host' ? '' : ' with this account'}`,
6100
+ commandId: `shell.chat-connection-check-allow-chat#${key}`, instance: name }
6101
+ : { ...base, kind: 'check', key: `check:${key}:exact`, revision: chat.approvalGrants?.revision ?? 0,
6102
+ what: `Exactly this check of ${name}${route}`, commandId: 'shell.chat-approval-grant-chat', instance: name };
6103
+ }
6104
+ if (!approvalIsExplicitOnly(approval)) {
6105
+ return { ...base, kind: 'tool', key: 'tool', decision: 'allow-session', revision: chat.sessionApprovalRevision ?? 0,
6106
+ what: 'All access actions', conversationExtra: '. Review checkpoints still ask every time', commandId: 'shell.chat-approval-session', instance: '' };
6107
+ }
6108
+ const binding = teklaAllowableApproval(approval) ? currentTeklaBinding(chat) : null;
6109
+ if (binding) {
6110
+ return { ...base, kind: 'tekla', key: 'tekla', revision: teklaAllowanceRevision(binding),
6111
+ what: `The Tekla reads this chat is set up for (${teklaReadsCopy(binding.operations, ' and ')})`, commandId: 'shell.chat-tekla-allow-chat', instance: '' };
6112
+ }
6113
+ const words = String(approval.summary || '').replace(/\s+/g, ' ').trim();
6114
+ return { ...base, kind: 'other', key: `other:${approval.tool || ''}`, revision: chat.approvalGrants?.revision ?? 0,
6115
+ what: `This exact request: “${words.length > 80 ? `${words.slice(0, 79)}…` : words}”`, commandId: 'shell.chat-approval-grant-chat', instance: approval.tool || 'this request' };
6116
+ }
6117
+
6118
+ /** What makes a painted card out of date: its kind, the views its wider choices decide on, and their wording. */
6119
+ function offerStamp(offer) {
6120
+ return [offer.kind, offer.key, offer.revision, offer.requestRevision, offer.decision, offer.what].join('|');
6121
+ }
6122
+
6123
+ /**
6124
+ * The two wider choices, each as one row: the button and, beside or under it, a line that says exactly what it covers.
6125
+ * The line is visible text (not a tooltip alone), and the button is described by it. Returns [] when the card can only
6126
+ * be denied.
6127
+ */
6128
+ function widerChoices(approval, offer) {
6129
+ if (!offer) return [];
6130
+ const group = document.createElement('div');
6131
+ group.className = 'ai-chat-approval-wide';
6132
+ group.setAttribute('role', 'group');
6133
+ const caption = document.createElement('span');
6134
+ caption.className = 'ai-chat-approval-wide-caption';
6135
+ caption.id = `chat-approval-wide-caption-${approval.approvalId}`;
6136
+ caption.textContent = 'Or allow more than this one action';
6137
+ group.setAttribute('aria-labelledby', caption.id);
6138
+ group.append(caption);
6139
+ const rows = [
6140
+ { which: 'request', label: 'Approve for this request', decision: 'allow-request', revision: offer.requestRevision, commandId: 'shell.chat-approval-request',
6141
+ text: `${offer.what}, until this reply ends.` },
6142
+ { which: 'conversation', label: 'Approve for this conversation', decision: offer.decision, revision: offer.revision, commandId: offer.commandId,
6143
+ text: `${offer.conversationWhat || offer.what}${offer.conversationExtra || ''}, for the rest of this conversation, until you revoke it above the message box.` },
6144
+ ];
6145
+ for (const row of rows) {
6146
+ const line = document.createElement('div');
6147
+ line.className = 'ai-chat-approval-wide-row';
6148
+ const choice = button(row.label, row.commandId);
6149
+ if (offer.instance && row.which === 'conversation') choice.dataset.commandInstanceLabel = offer.instance;
6150
+ const covers = document.createElement('span');
6151
+ covers.className = 'ai-chat-approval-covers';
6152
+ covers.id = `chat-approval-covers-${row.which}-${approval.approvalId}`;
6153
+ covers.textContent = `${row.text}${offer.protectedNote || ''}`;
6154
+ choice.dataset.tip = covers.textContent;
6155
+ choice.setAttribute('aria-describedby', covers.id);
6156
+ choice.addEventListener('click', () => decideApproval(row.decision, row.revision));
6157
+ line.append(choice, covers);
6158
+ group.append(line);
6159
+ }
6160
+ if (offer.warning) {
6161
+ const warning = document.createElement('p');
6162
+ warning.className = 'ai-chat-approval-warning';
6163
+ warning.textContent = offer.warning;
6164
+ group.append(warning);
6165
+ }
6166
+ return [group];
6167
+ }
6168
+
5284
6169
  function approvalIsExplicitOnly(approval) {
5285
6170
  if (!approval) return false;
5286
6171
  if (approval.explicitOnly === true) return true;
@@ -5314,7 +6199,7 @@
5314
6199
  const explanation = document.createElement('span');
5315
6200
  explanation.className = 'sr-only';
5316
6201
  explanation.id = `chat-approval-scope-help-${turn.turnId}`;
5317
- explanation.textContent = 'Your permission setting is unchanged. Review checkpoints still ask every time, and Tekla reads ask unless you allow them for this chat. Revoke asks before future access actions in this request; actions already approved may finish.';
6202
+ explanation.textContent = 'Your permission setting is unchanged. Review checkpoints still ask every time; other kinds of request have their own “Approve for this request” choices. Revoke asks before future access actions in this request; actions already approved may finish.';
5318
6203
  const revoke = button('Revoke', 'shell.chat-approval-revoke');
5319
6204
  revoke.dataset.tip = explanation.textContent;
5320
6205
  revoke.setAttribute('aria-describedby', explanation.id);
@@ -5343,7 +6228,7 @@
5343
6228
  const explanation = document.createElement('span');
5344
6229
  explanation.className = 'sr-only';
5345
6230
  explanation.id = `chat-approval-session-help-${session.approvalId}`;
5346
- explanation.textContent = 'Your permission setting is unchanged. Review checkpoints still ask every time, and Tekla reads, connector calls and file changes in a workspace conversation ask unless you allow them for this chat. Revoke asks before future access actions in this conversation; actions already approved may finish.';
6231
+ explanation.textContent = 'Your permission setting is unchanged. Review checkpoints still ask every time. Tekla reads, connector calls, file changes, scope additions and workflow creation have their own “Approve for this conversation” choices. Revoke asks before future access actions in this conversation; actions already approved may finish.';
5347
6232
  const revoke = button('Revoke', 'shell.chat-session-revoke');
5348
6233
  revoke.dataset.tip = explanation.textContent;
5349
6234
  revoke.setAttribute('aria-describedby', explanation.id);
@@ -5651,21 +6536,33 @@
5651
6536
  chip.append(name, remove); ui.attachments.append(chip);
5652
6537
  }
5653
6538
  ui.attachments.hidden = state.attachments.length === 0 && !pill;
6539
+ placeSkills();
5654
6540
  }
5655
6541
 
5656
6542
  function selectedModel() {
5657
6543
  if (!state.capability) return null;
5658
6544
  return state.capability.models.find((model) => model.id === state.chat?.settings.model)
6545
+ || coveringModel(state.capability.models, state.chat?.settings.model)
5659
6546
  || preferredModel(state.chat?.provider, state.capability.models)
5660
6547
  || state.capability.models.find((model) => model.isDefault)
5661
6548
  || state.capability.models[0] || null;
5662
6549
  }
5663
6550
 
6551
+ // #2232: a stored id the runtime stopped listing (`opus[1m]`, `claude-fable-5-1[1m]` before Claude Code 2.1.296) is the
6552
+ // offered row that runs the same model; the 1M variant is no longer offered, so its `[1m]` suffix is set aside.
6553
+ function coveringModel(models, stored) {
6554
+ const base = typeof stored === 'string' ? stored.replace(/\[1m\]$/i, '') : '';
6555
+ if (!base) return null;
6556
+ // The exact id first; then a named row running that model, never `default`, whose model changes between releases.
6557
+ return models.find((model) => model.id === base)
6558
+ || models.find((model) => model.id !== 'default' && model.resolvedModel === base) || null;
6559
+ }
6560
+
5664
6561
  // In order of preference; keep in step with PREFERRED_MODELS in server/chat-routes.ts. Without
5665
- // GPT-6-Sol nothing is preferred, so the provider's own default row is shown and used.
6562
+ // GPT-6.1-Sol or GPT-6-Sol nothing is preferred, so the provider's own default row is shown and used.
5666
6563
  function preferredModel(provider, models) {
5667
6564
  if (!provider || !Array.isArray(models)) return null;
5668
- const patterns = provider === 'codex' ? [/gpt[- .]?6[- .]?sol/i] : [/opus[- .]?5\.5/i, /opus/i];
6565
+ const patterns = provider === 'codex' ? [/gpt[- .]?6\.1[- .]?sol/i, /gpt[- .]?6[- .]?sol/i] : [/opus[- .]?5\.5/i, /opus/i];
5669
6566
  for (const pattern of patterns) {
5670
6567
  const found = models.find((model) => pattern.test(`${model.id} ${model.label}`));
5671
6568
  if (found) return found;
@@ -5827,9 +6724,9 @@
5827
6724
  ui.permission.dataset.tip = instructorChat
5828
6725
  ? '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.'
5829
6726
  : permissionTip(chat?.settings.permissionProfile);
5830
- // #2046: the Guide always reads only; its Access is said, not chosen, beside its Turn off and Delete.
6727
+ // #2234: the Guide's Access is chosen like any conversation's (it starts Read only). Its own controls — the morning
6728
+ // briefing, set-aside suggestions, Turn off and Delete history — keep their cell, shown only in a Guide conversation.
5831
6729
  const guideChat = chat?.initiator?.kind === 'guide';
5832
- ui.permission.hidden = guideChat;
5833
6730
  if (ui.guideAccess) ui.guideAccess.hidden = !guideChat;
5834
6731
  // #2053: the Guide's morning briefing lives here too; web/guide.js paints it (only when something changed).
5835
6732
  if (guideChat) window.flolessGuide?.paintBriefing?.();
@@ -5915,13 +6812,21 @@
5915
6812
 
5916
6813
  function paintRecovery() {
5917
6814
  paintMoveNotice();
6815
+ // Recovery authority/explanations belong to one UUID turn, never to the shared panel.
6816
+ if (state.recoveryTurnId !== state.chat?.activeTurn?.turnId) {
6817
+ state.recoveryCanEnd = false;
6818
+ state.recoveryMessage = null;
6819
+ state.recoveryTurnId = null;
6820
+ }
5918
6821
  const recovery = state.chat?.state === 'recovery';
5919
6822
  ui.recovery.hidden = !recovery;
5920
6823
  ui.recoveryStop.hidden = !recovery;
5921
6824
  ui.recoveryStop.textContent = state.recoveryCanEnd ? 'End recovery' : 'Stop response';
6825
+ ui.recoveryStop.dataset.commandId = state.recoveryCanEnd ? 'shell.chat-end-recovery' : 'shell.chat-stop';
5922
6826
  ui.recoveryCopy.textContent = recovery
5923
6827
  ? (state.recoveryMessage || 'FloLess needs to check the last AI response before sending another message.')
5924
6828
  : '';
6829
+ paintStopState();
5925
6830
  }
5926
6831
 
5927
6832
  function paintConversation() {
@@ -5931,6 +6836,7 @@
5931
6836
  paintConnectorAllowance();
5932
6837
  paintChangeAllowance();
5933
6838
  paintCheckAllowance();
6839
+ paintApprovalGrants();
5934
6840
  const chat = state.chat;
5935
6841
  if (!chat) { providerChooser(); paintHistory(); return; }
5936
6842
  ui.historyToggle.disabled = false;
@@ -6037,6 +6943,9 @@
6037
6943
  if (event.type === 'chat-subjects') subjectLinksSaved(event.payload);
6038
6944
  // So does the Tekla questions card, once any selection receipt in this pane has shown one (#1653 stage 4).
6039
6945
  if (event.type === 'chat-subjects' && state.teklaHistoryHost) void loadTeklaLinks(true);
6946
+ // #2255: only an event new to this window is taken; one read from history never is.
6947
+ if (event.type === 'view-command') takeViewCommand(event);
6948
+ if (event.type === 'view-command-update' && typeof event.payload?.line === 'string') announce(`Model view. ${event.payload.line.replace(/ · /g, '. ')}`);
6040
6949
  state.events.sort((a, b) => a.sequence - b.sequence);
6041
6950
  state.chat.lastEventSequence = Math.max(state.chat.lastEventSequence || 0, event.sequence || 0);
6042
6951
  const listChat = state.chats.find((item) => item.chatId === chatId);
@@ -6067,6 +6976,8 @@
6067
6976
  if (notices[event.payload?.deliveryState]) announce(notices[event.payload.deliveryState]);
6068
6977
  }
6069
6978
  paintEvents(); paintUnread();
6979
+ // #2223 Revision 6: a message that asks a question without waiting opens its card; the person's next message closes it.
6980
+ if (event.type === 'user-message' || event.payload?.asyncQuestion) paintApproval();
6070
6981
  if (!document.hidden && !ui.feed.closest('[hidden]')) markRead();
6071
6982
  if (['approval-requested', 'approval-decided', 'error', 'interrupted', 'state', 'followup-status'].includes(event.type)
6072
6983
  || (event.type === 'user-message' && event.payload?.followup)) {
@@ -6174,6 +7085,7 @@
6174
7085
  }
6175
7086
  if (!sameChat(snapshot)) return;
6176
7087
  state.chat = chat;
7088
+ // #2223 Revision 6: a file on the open question card's answer goes with that answer, not with the box's next message.
6177
7089
  state.attachments = composerDrafts(chat);
6178
7090
  const index = state.chats.findIndex((item) => item.chatId === chatId);
6179
7091
  if (index >= 0) state.chats[index] = chat;
@@ -6455,7 +7367,7 @@
6455
7367
  const label = (value) => (value === 'mm' ? 'Metric (mm)' : 'ft-in');
6456
7368
  // Settings repaint on every chat event; rebuilding unchanged buttons would swap them out from under a click.
6457
7369
  const painted = `${chat.chatId}|${chosen}|${units.suggested ?? null}|${Boolean(state.workspaceUnitsEditing)}`;
6458
- if (!host.hidden && host.dataset.painted === painted) return;
7370
+ if (host.dataset.painted === painted) return;
6459
7371
  host.dataset.painted = painted;
6460
7372
  host.hidden = false;
6461
7373
  host.replaceChildren();
@@ -6470,48 +7382,16 @@
6470
7382
  change.setAttribute('aria-label', 'Change units');
6471
7383
  change.dataset.commandId = 'shell.chat-units-change';
6472
7384
  change.dataset.tip = 'Choose the units AI answers in, in this conversation';
6473
- change.addEventListener('click', () => { state.workspaceUnitsEditing = true; paintWorkspaceUnits(); host.querySelector('[role="radio"][aria-checked="true"], [role="radio"]')?.focus(); });
7385
+ change.addEventListener('click', () => { state.workspaceUnitsEditing = true; paintWorkspaceUnits();
7386
+ const entry = state.workspaceUnitsQuestions?.get(chat.chatId);
7387
+ if (entry?.slotNode?.isConnected) window.FlolessQuestionCard.focusCursor(entry.slotNode);
7388
+ });
6474
7389
  host.append(text, change);
6475
7390
  return;
6476
7391
  }
6477
- const question = document.createElement('span');
6478
- question.className = 'ai-chat-units-question';
6479
- question.id = 'chat-units-question';
6480
- question.textContent = 'Which units should AI use here?';
6481
- const group = document.createElement('div');
6482
- group.className = 'ai-chat-units-options';
6483
- group.setAttribute('role', 'radiogroup');
6484
- group.setAttribute('aria-labelledby', 'chat-units-question');
6485
- const suggested = units.suggested === 'mm' || units.suggested === 'ft-in' ? units.suggested : null;
6486
- const options = ['ft-in', 'mm'];
6487
- for (const value of options) {
6488
- const option = document.createElement('button');
6489
- option.type = 'button';
6490
- option.className = 'ai-chat-units-option';
6491
- option.setAttribute('role', 'radio');
6492
- const checked = chosen ? chosen === value : suggested === value;
6493
- option.setAttribute('aria-checked', String(Boolean(chosen && chosen === value)));
6494
- option.tabIndex = checked || (!chosen && !suggested && value === 'ft-in') ? 0 : -1;
6495
- option.dataset.commandId = `shell.chat-units-choose#${value}`;
6496
- option.dataset.commandInstanceLabel = label(value);
6497
- if (suggested === value && !chosen) option.classList.add('is-suggested');
6498
- option.textContent = label(value);
6499
- if (suggested === value && !chosen) {
6500
- const hint = document.createElement('span');
6501
- hint.className = 'ai-chat-units-hint';
6502
- hint.textContent = ' · last project';
6503
- option.append(hint);
6504
- }
6505
- option.addEventListener('click', () => { void chooseWorkspaceUnits(value); });
6506
- option.addEventListener('keydown', (event) => {
6507
- if (event.key !== 'ArrowRight' && event.key !== 'ArrowLeft' && event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return;
6508
- event.preventDefault();
6509
- const next = group.querySelectorAll('[role="radio"]')[value === 'ft-in' ? 1 : 0];
6510
- next?.focus();
6511
- });
6512
- group.append(option);
6513
- }
6514
- host.append(question, group);
7392
+ host.hidden = true;
7393
+ drawingSlotRepaint();
7394
+ return;
6515
7395
  }
6516
7396
 
6517
7397
  async function chooseWorkspaceUnits(value) {
@@ -6521,15 +7401,17 @@
6521
7401
  const updated = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/workspace-units`, {
6522
7402
  method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, units: value }),
6523
7403
  });
6524
- if (!sameChat(snapshot)) return;
7404
+ if (!sameChat(snapshot)) return updated.workspaceUnits;
6525
7405
  state.chat = { ...state.chat, workspaceUnits: updated.workspaceUnits };
6526
7406
  state.workspaceUnitsEditing = false;
6527
7407
  paintWorkspaceUnits();
6528
7408
  void refreshDisplayUnits();
6529
7409
  announce(`Units set to ${value === 'mm' ? 'metric (millimetres)' : 'feet and inches'}.`);
6530
7410
  ui.workspaceUnits?.querySelector('.ai-chat-units-change')?.focus();
7411
+ return updated.workspaceUnits;
6531
7412
  } catch (error) {
6532
7413
  report(error, 'Could not save the units for this conversation');
7414
+ return false;
6533
7415
  }
6534
7416
  }
6535
7417
 
@@ -6547,7 +7429,7 @@
6547
7429
  const chat = await request('/api/chat/conversations', {
6548
7430
  method: 'POST', body: JSON.stringify({
6549
7431
  owner, provider, title: 'New chat',
6550
- // #2037: no access level — the server starts a project or workflow conversation in Auto, the workspace in Read only.
7432
+ // #2037/#2234: no access level — the server starts every new conversation in Auto.
6551
7433
  settings: { model: null, effort: null },
6552
7434
  initiator: { kind: 'user' },
6553
7435
  ...(displayUnitsSuggestion ? { displayUnitsSuggestion } : {}),
@@ -6676,7 +7558,6 @@
6676
7558
 
6677
7559
  function closePicker() {
6678
7560
  state.picker = null; state.pickerOpener = null; ui.picker.hidden = true; ui.picker.replaceChildren();
6679
- ui.picker.removeAttribute('aria-describedby');
6680
7561
  for (const control of [ui.model, ui.effort, ui.permission, ui.integrations]) control.setAttribute('aria-expanded', 'false');
6681
7562
  }
6682
7563
 
@@ -6688,7 +7569,7 @@
6688
7569
  if (opener?.isConnected && !opener.disabled) opener.focus();
6689
7570
  }
6690
7571
 
6691
- function openPicker(kind, anchor, choices, note) {
7572
+ function openPicker(kind, anchor, choices) {
6692
7573
  if (anchor.disabled) return;
6693
7574
  if (state.picker === kind) { closePicker(); return; }
6694
7575
  toggleHistory(false); closePicker(); state.picker = kind; state.pickerOpener = anchor;
@@ -6703,11 +7584,6 @@
6703
7584
  row.addEventListener('click', async () => { closePicker(); await saveSettings(choice.patch); anchor.focus(); });
6704
7585
  ui.picker.append(row);
6705
7586
  }
6706
- // A quiet line after the choices says why one is missing; it is not an option, so the list is described by it.
6707
- if (note) {
6708
- const line = document.createElement('div'); line.className = 'ai-chat-picker-note'; line.id = 'chat-picker-note'; line.textContent = note;
6709
- ui.picker.append(line); ui.picker.setAttribute('aria-describedby', line.id);
6710
- }
6711
7587
  ui.picker.hidden = false; anchor.setAttribute('aria-expanded', 'true');
6712
7588
  const selected = ui.picker.querySelector('[aria-selected="true"]') || ui.picker.querySelector('button');
6713
7589
  selected?.focus();
@@ -6787,6 +7663,15 @@
6787
7663
  }
6788
7664
  const settings = { ...state.chat.settings, ...patch };
6789
7665
  if ('model' in patch && !('effort' in patch)) settings.effort = null;
7666
+ // A model the runtime stopped listing (an update renamed it) is saved as the row the picker shows for it, the one
7667
+ // running the same model where there is one (coveringModel), so changing Effort or Access is never refused.
7668
+ // Only against a list the provider actually returned: an empty one (the check failed) proves nothing about the model.
7669
+ if (!('model' in patch) && settings.model && state.capability?.available && state.capability.models.length
7670
+ && !state.capability.models.some((model) => model.id === settings.model)) {
7671
+ const shown = selectedModel();
7672
+ settings.model = shown?.id ?? null;
7673
+ if (!shown?.efforts?.includes(settings.effort)) settings.effort = null;
7674
+ }
6790
7675
  try {
6791
7676
  const chat = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/settings`, {
6792
7677
  method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, ...settings, ...(release ? { releaseInstructorAnswer: true } : {}) }),
@@ -6805,9 +7690,11 @@
6805
7690
 
6806
7691
  function modelChoices() {
6807
7692
  const models = state.capability?.models || [];
6808
- return models.map((model) => ({
7693
+ const shown = selectedModel()?.id;
7694
+ // #2232: an older model the provider's own picker no longer offers is listed only for a chat already on it.
7695
+ return models.filter((model) => !model.legacy || model.id === shown).map((model) => ({
6809
7696
  id: `model:${model.id}`, label: model.label, meta: model.detail || '',
6810
- selected: (state.chat.settings.model || selectedModel()?.id) === model.id, patch: { model: model.id },
7697
+ selected: shown === model.id, patch: { model: model.id },
6811
7698
  }));
6812
7699
  }
6813
7700
 
@@ -6817,9 +7704,8 @@
6817
7704
  selected: (state.chat.settings.effort || 'medium').toLowerCase() === effort.toLowerCase(), patch: { effort } }));
6818
7705
  }
6819
7706
 
6820
- /** #1890 PR 2b: in a workspace conversation, "Make changes" — every change outside the AI's own folder asks first. */
7707
+ /** #2234 (owner ruling 2026-10-12, one Access vocabulary everywhere): the same label in every conversation. */
6821
7708
  function permissionLabel(value) {
6822
- if (state.scope?.owner?.kind === 'workspace' && value === 'workspace-write') return 'Make changes (asks first)';
6823
7709
  return permissionLabels[value] || 'Read only';
6824
7710
  }
6825
7711
 
@@ -6833,7 +7719,7 @@
6833
7719
  return state.chat?.provider === 'claude' && selectedModel()?.autoMode === false ? 'model' : null;
6834
7720
  }
6835
7721
 
6836
- function permissionMeta(value, workspace) {
7722
+ function permissionMeta(value) {
6837
7723
  if (value === 'read-only') return 'Looks and answers. Changes nothing.';
6838
7724
  if (value === 'auto') {
6839
7725
  const why = autoUnavailable();
@@ -6841,36 +7727,39 @@
6841
7727
  if (why === 'accounts') return 'With a FloLess account selected, the AI asks you before steps that need approval.';
6842
7728
  return why ? 'Not available with this model. It asks before changes.' : 'Does safe work by itself. Checks risky steps first.';
6843
7729
  }
6844
- if (value === 'workspace-write') return workspace ? 'Asks before changing project files.' : 'Asks you whenever the AI needs approval.';
7730
+ if (value === 'workspace-write') return 'Asks you whenever the AI needs approval.';
6845
7731
  return 'Can change any file on this computer.';
6846
7732
  }
6847
7733
 
6848
7734
  function permissionTip(value) {
6849
- if (state.scope?.owner?.kind === 'workspace') return `Access: ${permissionLabel(value)}. Full access and Auto are offered only inside a project or workflow.`;
6850
7735
  const why = value === 'auto' ? autoUnavailable() : null;
6851
7736
  const label = why === 'connectors' ? 'Auto (asking first while your connectors are on)'
6852
7737
  : why === 'accounts' ? 'Auto (asking first while a FloLess account is selected)'
6853
7738
  : why ? 'Auto (asking first with this model)' : permissionLabel(value);
6854
- return `Access: ${label}. ${permissionMeta(value || 'read-only', false)}`;
7739
+ return `Access: ${label}. ${permissionMeta(value || 'read-only')}`;
6855
7740
  }
6856
7741
 
6857
7742
  function permissionChoices() {
6858
- // #1890 PR 2b: from the workspace, Full access is not offered — it would remove the approvals each change needs.
6859
- // #2037: nor Auto — Codex's auto review would approve a change around the claim its card makes.
6860
- const workspace = state.scope?.owner?.kind === 'workspace';
6861
- const offered = workspace
6862
- ? Object.keys(permissionLabels).filter((value) => value !== 'full-access' && value !== 'auto')
6863
- : Object.keys(permissionLabels);
6864
- return offered.map((value) => ({
6865
- id: `permission:${value}`, label: permissionLabel(value), meta: permissionMeta(value, workspace),
7743
+ // #2234 (owner ruling 2026-10-12): every conversation offers all four levels — the workspace's and the Guide's too.
7744
+ return Object.keys(permissionLabels).map((value) => ({
7745
+ id: `permission:${value}`, label: permissionLabel(value), meta: permissionMeta(value),
6866
7746
  // #2059: an Instructor answer has none of these yet ("No tools" is a state, not a choice).
6867
7747
  selected: !isInstructorAnswer(state.chat) && state.chat.settings.permissionProfile === value, patch: { permissionProfile: value },
6868
7748
  }));
6869
7749
  }
6870
7750
 
6871
- /** Why the workspace's Access list has no Auto or Full access; the same test permissionChoices uses to leave them out. */
6872
- function permissionPickerNote() {
6873
- return state.scope?.owner?.kind === 'workspace' ? 'Auto and Full access are offered inside a project or workflow.' : '';
7751
+ /**
7752
+ * #2234 (plan R2.3): said once, in the notes every conversation shares, wherever the AI may change files outside its
7753
+ * home folder without asking (Auto, Full access): such a change is not held back for a workflow run or other work on
7754
+ * the same files. Not said where Auto asks instead (autoUnavailable): there it would be untrue.
7755
+ */
7756
+ function unaskedChangesNote() {
7757
+ return 'If the AI changes something outside your home folder without asking, that change is not held back while a workflow run or other work is using the same files.';
7758
+ }
7759
+
7760
+ /** Full access in this conversation's Scope view. */
7761
+ function fullAccessScopeNote() {
7762
+ return `Full access is on. The AI can change files without asking. ${unaskedChangesNote()}`;
6874
7763
  }
6875
7764
 
6876
7765
  /** #2037: what Auto means in this conversation's Scope view; Codex's review may approve a change outside the folder. */
@@ -6880,8 +7769,8 @@
6880
7769
  if (why === 'accounts') return 'Auto: while a FloLess account is selected for this chat, the AI asks you — instead of its own review — before any step that needs approval, so that account stays its only way to reach the service. Scope does not limit file reads.';
6881
7770
  if (why) return 'Auto isn’t available with this model, so the AI asks before changes. File edits outside your home folder ask for approval. Scope does not limit file reads.';
6882
7771
  return state.chat?.provider === 'codex'
6883
- ? 'Auto: Codex’s built-in review checks each step. Safe changes go ahead; risky ones, like deleting, are held back. Its review may also approve a change outside your home folder on its own — each decision is noted in the conversation. Scope does not limit file reads.'
6884
- : 'Auto: Claude checks each step itself. Safe changes in your home folder go ahead; it asks you before touching anything outside it, and holds back risky steps like deleting. Scope does not limit file reads.';
7772
+ ? `Auto: Codex’s built-in review checks each step. Safe changes go ahead; risky ones, like deleting, are held back. Its review may also approve a change outside your home folder on its own — each decision is noted in the conversation. ${unaskedChangesNote()} Scope does not limit file reads.`
7773
+ : `Auto: Claude checks each step itself. Safe changes in your home folder go ahead. A file edit outside it asks you first; a command Claude’s check judges safe can run without asking, and risky steps like deleting are held back. ${unaskedChangesNote()} Scope does not limit file reads.`;
6885
7774
  }
6886
7775
 
6887
7776
  async function loadIntegrations() {
@@ -7033,6 +7922,7 @@
7033
7922
  else delete control.dataset.blockedReason;
7034
7923
  }
7035
7924
  ui.stop.hidden = !active || Boolean(state.chat?.activeTurn?.local);
7925
+ paintStopState();
7036
7926
  ui.send.hidden = false;
7037
7927
  // Session recovery must remain available even while provider capability discovery is loading
7038
7928
  // or has failed; it is the escape hatch for that exact state.
@@ -7175,8 +8065,29 @@
7175
8065
  ui.skills.append(row);
7176
8066
  }
7177
8067
  ui.skills.hidden = false;
8068
+ placeSkills();
7178
8069
  }
7179
8070
 
8071
+ // #2185: the open / list sits 4px above what is about to be sent (the attachments, right above the message box, or the
8072
+ // box itself), so it never cuts across a chip, and it is never taller than the room above that, so a short pane does not
8073
+ // clip its first options. chat.css keeps a fixed bottom and height only as the fallback before layout.
8074
+ function placeSkills() {
8075
+ const host = ui.skills.offsetParent;
8076
+ if (ui.skills.hidden || !host) return;
8077
+ const shell = host.getBoundingClientRect();
8078
+ const top = (ui.attachments.hidden ? ui.input : ui.attachments).getBoundingClientRect().top;
8079
+ ui.skills.style.bottom = `${Math.max(0, Math.round(shell.bottom - top + 4))}px`;
8080
+ ui.skills.style.maxHeight = `${Math.max(0, Math.round(Math.min(260, window.innerHeight * 0.4, top - shell.top - 8)))}px`;
8081
+ }
8082
+ // While the list is open, anything that moves its anchor moves the list: the composer (the chips, the box and the hint
8083
+ // or disclosure under it all live inside it) and the shell (the pane's own size).
8084
+ function watchSkillsPlacement() {
8085
+ if (typeof ResizeObserver !== 'function') return;
8086
+ const watch = new ResizeObserver(() => placeSkills());
8087
+ for (const node of [ui.composer, ui.skills.parentElement]) if (node) watch.observe(node);
8088
+ }
8089
+ watchSkillsPlacement();
8090
+
7180
8091
  // ── Drawing Filter context and suggestions ─────────────────────────────────────────────────────
7181
8092
  // ONE AI CHAT (#1859). With the Drawing Filter open, a message is an ordinary turn or follow-up; the
7182
8093
  // open filter only adds a snapshot of the sheet and its selection (`filterContextForSend`), and the AI
@@ -7424,6 +8335,97 @@
7424
8335
  return item;
7425
8336
  }
7426
8337
 
8338
+ /* -- #2255: the AI's changes to the model view ---------------------------------------------------------------------
8339
+ The tool waits on the server. A window showing that project's model, ready, claims the command (the server gives one
8340
+ window the claim), sends it to the editor, and settles it with the editor's report. One command at a time per chat,
8341
+ so the editor receives them in the order the AI asked. The line is FloLess's own, from the server's update. */
8342
+ const VIEW_LINE_WORKING = 'Changing the model view…';
8343
+ const VIEW_LINE_NO_RESULT = 'No result was recorded. The model view may or may not have changed, so check it on screen.';
8344
+ /** A model still opening gets this long to become ready before the window gives the command up (the server waits 15 s). */
8345
+ const VIEW_READY_WAIT_MS = 12000;
8346
+ /** The editor's own answer must arrive before the server stops waiting (10 s after the claim). */
8347
+ const VIEW_APPLY_WAIT_MS = 9000;
8348
+ const viewCommandChains = new Map();
8349
+
8350
+ function renderViewCommand(event) {
8351
+ const commandId = event.payload?.commandId;
8352
+ let update = null;
8353
+ for (const item of state.events) if (item.type === 'view-command-update' && item.payload?.commandId === commandId) update = item;
8354
+ // Working only while the reply that asked is still running; after a restart its turn is in recovery, not running.
8355
+ const working = !update && ['running', 'awaiting-approval'].includes(state.chat?.state) && state.chat?.activeTurn?.turnId === event.turnId;
8356
+ const status = update?.payload?.status || (working ? 'working' : 'no-result');
8357
+ const item = document.createElement('div');
8358
+ // Accent when it applied; amber when something was not done or cannot be confirmed; plain when the reply ended.
8359
+ const tone = status === 'applied' ? 'done' : status === 'working' ? 'working' : status === 'cancelled' ? 'ended' : 'held';
8360
+ item.className = `ai-chat-event view-command ${tone}`;
8361
+ item.dataset.eventSequence = String(event.sequence);
8362
+ item.dataset.eventId = event.eventId;
8363
+ item.dataset.viewStatus = status;
8364
+ const label = document.createElement('strong');
8365
+ label.textContent = 'Model view';
8366
+ const line = typeof update?.payload?.line === 'string' ? update.payload.line : working ? VIEW_LINE_WORKING : VIEW_LINE_NO_RESULT;
8367
+ item.append(label, document.createTextNode(` · ${line}`));
8368
+ return item;
8369
+ }
8370
+
8371
+ function takeViewCommand(event) {
8372
+ const snapshot = captureChat();
8373
+ const payload = event.payload || {};
8374
+ if (!snapshot || typeof payload.commandId !== 'string') return;
8375
+ if (state.events.some((item) => item.type === 'view-command-update' && item.payload?.commandId === payload.commandId)) return;
8376
+ const previous = viewCommandChains.get(snapshot.chatId) || Promise.resolve();
8377
+ const next = previous.then(() => runViewCommand(snapshot, payload))
8378
+ .catch((error) => console.warn('[chat] a model view request could not be handled', error));
8379
+ viewCommandChains.set(snapshot.chatId, next);
8380
+ void next.then(() => { if (viewCommandChains.get(snapshot.chatId) === next) viewCommandChains.delete(snapshot.chatId); });
8381
+ }
8382
+
8383
+ async function runViewCommand(snapshot, payload) {
8384
+ // A model that is still opening (or was just switched to) becomes ready in a moment: wait for it, briefly.
8385
+ const settled = () => state.events.some((item) => item.type === 'view-command-update' && item.payload?.commandId === payload.commandId);
8386
+ let target = window.flolessLeftPane?.viewTarget?.();
8387
+ for (const started = Date.now(); !target && Date.now() - started < VIEW_READY_WAIT_MS && sameChat(snapshot) && !settled();) {
8388
+ await new Promise((resolve) => setTimeout(resolve, 500));
8389
+ target = window.flolessLeftPane?.viewTarget?.();
8390
+ }
8391
+ // Not this project's model, or not ready here: another window may show it, and the server says so if none does.
8392
+ if (!target || target.projectId !== payload.projectId || target.source !== payload.source) return;
8393
+ const path = `/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/view-commands/${encodeURIComponent(payload.commandId)}`;
8394
+ const owner = snapshot.scope.owner;
8395
+ let claim;
8396
+ try { claim = await request(`${path}/claim`, { method: 'POST', body: JSON.stringify({ owner, target }) }); }
8397
+ catch (error) {
8398
+ // Another window took it, the reply ended, or this reply's changes go to another view: nothing for this one to do.
8399
+ // Anything else is kept in the console; the server still answers the AI when its wait ends.
8400
+ const expected = (error?.status === 409 && ['chat-view-command-taken', 'chat-view-command-ended', 'chat-view-command-other-view'].includes(error.code))
8401
+ || (error?.status === 404 && error.code === 'chat-view-command-missing');
8402
+ if (!expected) console.warn('[chat] a model view request could not be taken', { status: error?.status ?? null, code: error?.code ?? null, message: error?.message });
8403
+ return;
8404
+ }
8405
+ let body;
8406
+ try {
8407
+ const answer = await window.flolessLeftPane.applyView({ command: claim.command, target, timeoutMs: VIEW_APPLY_WAIT_MS });
8408
+ // Never asked (still loading): nothing changed. Asked and answered without a report: it may have changed something.
8409
+ body = answer?.ran === false ? { result: viewNotApplied('loading') } : answer?.ok && answer.result ? { result: answer.result } : { unconfirmed: true };
8410
+ } catch (error) {
8411
+ body = error?.dispatched === false ? { result: viewNotApplied('failed') } : { unconfirmed: true };
8412
+ }
8413
+ const settle = () => request(`${path}/settle`, { method: 'POST', body: JSON.stringify({ owner, claimToken: claim.claimToken, ...body }) });
8414
+ try { await settle(); }
8415
+ catch (error) {
8416
+ console.warn('[chat] what the model view did could not be recorded', { status: error?.status ?? null, code: error?.code ?? null });
8417
+ if (error?.status === 410 || error?.status === 400) return; // the server already ended it, and wrote its own line
8418
+ try { await settle(); }
8419
+ catch { announce('FloLess could not record what happened in the model view. Check the model on screen.'); }
8420
+ }
8421
+ }
8422
+
8423
+ /** A report for a change that never reached the editor: nothing changed. */
8424
+ function viewNotApplied(reason) {
8425
+ return { status: 'not-applied', reason, total: 0, matched: 0, selectionApplied: 0, selectedFinal: 0, notDrawable: 0, noField: 0, unchecked: 0,
8426
+ overCap: false, framed: false, display: null, skipped: [], assumptions: [], references: [], samples: [] };
8427
+ }
8428
+
7427
8429
  function renderFilterQuestion(event) {
7428
8430
  // A Drawing Filter question from before #1859: the person's own words, like any message. Nothing
7429
8431
  // waits on it any more; its answer, if one was published, is its own event.
@@ -7584,41 +8586,95 @@
7584
8586
  if (reason) state.filterNotShared.set(clientSubmissionId, reason);
7585
8587
  }
7586
8588
 
8589
+ /**
8590
+ * #2223 Revision 6: sendTurn's `message` is an answer written outside the message box (on an AI question card). It goes
8591
+ * through the same send, as a new turn or a follow-up to a running reply; the box, its files, its selection and its draft
8592
+ * stay exactly as they are, and the caller is told { sent, message } to say on the card, never a report under the box.
8593
+ * This is why the chat cannot take such a message right now, in words — Send's own reasons, less the two that are only
8594
+ * about the box (nothing typed in it, a file of its own still attaching); '' when it can. The conditions are written out
8595
+ * as updateSendState has them, because several harnesses run that function on its own.
8596
+ */
8597
+ function givenMessageBlocked() {
8598
+ const chat = state.chat;
8599
+ if (!chat || chat.archivedAt) return 'This conversation can’t take a message right now. Open it again, then send your answer.';
8600
+ if (state.loading || state.followupSubmitting || chat.activeTurn?.local) return 'FloLess is still sending your last message. Wait a moment, then send your answer again.';
8601
+ if (state.followupUnknownId || hasUnknownFollowup()) return 'FloLess could not confirm your last message reached the AI. Check it in the conversation, then send your answer.';
8602
+ if (chat.state === 'recovery') return 'This conversation is reconnecting to the AI. Send your answer once it is ready.';
8603
+ if (requestExecutionBlocked()) return 'Another AI Chat is changing this project or workflow. Wait for it to finish or stop it, then send your answer.';
8604
+ if (state.capability?.runtime && state.capability.runtime.state !== 'installed') return 'FloLess is still setting up the AI. Send your answer once it is ready.';
8605
+ if (chat.rehome && ['freezing', 'copying', 'publishing'].includes(chat.rehome.state) && state.scope?.owner?.kind === 'workspace') {
8606
+ return 'This conversation is moving into its workflow. Send your answer once it has moved.';
8607
+ }
8608
+ return '';
8609
+ }
8610
+
8611
+ /** An answer written outside the box that did not go: what the card is told, in words. */
8612
+ function givenNotSent(sentence) {
8613
+ return { sent: false, message: sentence || 'Your answer was not sent. Send it again.' };
8614
+ }
8615
+
8616
+ /**
8617
+ * What an answer written outside the box is told when the server would not take it. A busy project is asked about only
8618
+ * from the box (its question and wait send what is in the box), so the answer says where that choice is.
8619
+ */
8620
+ function givenRefusal(error) {
8621
+ return PROJECT_BUSY_CODES.has(String(error?.code || ''))
8622
+ ? 'Other work is using this project right now, so your answer was not sent. It is kept here: send it again once that work finishes, or type it in the message box below to choose what happens to that work.'
8623
+ : errorMessage(error);
8624
+ }
8625
+
8626
+ /**
8627
+ * #2223 Revision 6: the server empties a conversation's saved draft when it takes a message. A message written outside
8628
+ * the box (an answer on a question card) was not the box's words, so the box keeps them, saved again.
8629
+ */
8630
+ function keepComposerDraft() {
8631
+ if (!state.chat) return;
8632
+ state.chat.draft = ui.input.value;
8633
+ if (ui.input.value) saveDraftSoon();
8634
+ }
8635
+
7587
8636
  async function sendTurn(options) {
7588
8637
  // #2061: `override` — the person chose to send now over a background request that was waiting first.
7589
8638
  const sendOverride = options?.override === true;
7590
- if (!state.chat || ui.send.disabled) return;
8639
+ // #2223 Revision 6: `message` — an answer written outside the message box (see givenMessageBlocked).
8640
+ const given = options?.message || null;
8641
+ const blocked = given ? givenMessageBlocked() : '';
8642
+ if (blocked) return givenNotSent(blocked);
8643
+ if (!given && (!state.chat || ui.send.disabled)) return;
7591
8644
  // ONE AI CHAT (#1859, owner ruling 2026-10-01/02): the open Drawing Filter never changes where a message goes.
7592
8645
  // It is a turn, or a follow-up to a running reply (a drawing read included), exactly as anywhere else; the
7593
8646
  // filter only adds its context (`filterContextForSend`) and the AI may answer with a suggestion card.
7594
8647
  // Decided once, at the click, from what the pill showed: a follow-up that falls back to a new turn below
7595
8648
  // must not attach objects the person was never shown (#1653).
7596
- const subjects = subjectsPayload(composerSelection());
8649
+ const subjects = given ? null : subjectsPayload(composerSelection()); // the box's selection rides with the box's message
7597
8650
  const subjectsField = subjects ? { subjects } : {};
7598
8651
  const filterContext = filterContextForSend();
7599
8652
  if (turnIsVisiblyActive() && !state.chat.activeTurn?.local) {
7600
- const followup = await sendFollowup();
7601
- if (followup?.outcome !== 'turn-ended') return;
8653
+ const followup = await sendFollowup(given);
8654
+ if (followup?.outcome !== 'turn-ended') return given ? followup || givenNotSent() : undefined;
7602
8655
  // #1616: the response finished while this follow-up was on its way, so the server refused it
7603
8656
  // before saving anything. Re-read the conversation and, if it is now idle and the composer still
7604
8657
  // holds exactly that message, send it once as a new turn instead of asking for a second click.
7605
- if (!(await resendAfterTurnEnded(followup))) return;
8658
+ if (!(await resendAfterTurnEnded(followup))) {
8659
+ return given ? givenNotSent(givenMessageBlocked() || 'The AI’s reply ended while your answer was on its way, so it was not sent. Send it again.') : undefined;
8660
+ }
7606
8661
  }
7607
8662
  const snapshot = captureChat();
7608
- if (!snapshot) return;
8663
+ if (!snapshot) return given ? givenNotSent() : undefined;
7609
8664
  // Bind a carried-over Tekla library first; a refused binding keeps the message unsent.
7610
- if (!(await bindPendingTeklaRead(snapshot))) return;
7611
- const text = ui.input.value.trim();
8665
+ if (!(await bindPendingTeklaRead(snapshot))) return given ? givenNotSent('Wait for the Tekla library change to finish, then send your answer again.') : undefined;
8666
+ const text = given ? given.text : ui.input.value.trim();
7612
8667
  const uiContext = currentFloLessContext();
7613
8668
  const chatId = snapshot.chatId;
7614
- const attachmentIds = state.attachments.map((item) => item.attachmentId);
8669
+ const attachmentIds = (given ? given.attachments : state.attachments).map((item) => item.attachmentId);
7615
8670
  // #2061: the message as it was asked about, should the project turn out to be busy (see askIfProjectBusy).
7616
8671
  const busyMessage = { chatId, text, attachmentIds, subjectsField, filterField: filterContext.field };
7617
- const askedBusy = !sendOverride && await projectBusyBeforeSend(snapshot, busyMessage);
7618
- if (askedBusy || !sameChat(snapshot)) return;
8672
+ // The busy-project question and its wait send what is in the box; an answer written elsewhere is told the refusal instead.
8673
+ const askedBusy = !sendOverride && !given && await projectBusyBeforeSend(snapshot, busyMessage);
8674
+ if (askedBusy || !sameChat(snapshot)) return given ? givenNotSent() : undefined;
7619
8675
  // Edited while FloLess checked — or already sent by an earlier click, which empties the box — nothing is sent over
7620
8676
  // the box's text now; it stays for the next Send.
7621
- if (ui.input.value.trim() !== text || JSON.stringify(state.attachments.map((item) => item.attachmentId)) !== JSON.stringify(attachmentIds)) return;
8677
+ if (!given && (ui.input.value.trim() !== text || JSON.stringify(state.attachments.map((item) => item.attachmentId)) !== JSON.stringify(attachmentIds))) return;
7622
8678
  const clientSubmissionId = crypto.randomUUID();
7623
8679
  const previousChat = state.chat;
7624
8680
  const previousAttachments = state.attachments;
@@ -7627,13 +8683,15 @@
7627
8683
  chatId, turnId: clientSubmissionId, clientSubmissionId, providerItemId: null, type: 'user-message',
7628
8684
  payload: { text, attachmentIds, ...subjectsField }, createdAt: new Date().toISOString(), optimistic: true,
7629
8685
  };
7630
- clearTimeout(state.draftTimer);
7631
- state.localDraft = { chatId, text: '' };
7632
- state.backgroundDrafts.delete(chatId);
8686
+ if (!given) {
8687
+ clearTimeout(state.draftTimer);
8688
+ state.localDraft = { chatId, text: '' };
8689
+ state.backgroundDrafts.delete(chatId);
8690
+ }
7633
8691
  state.pendingSubmissionId = clientSubmissionId;
7634
8692
  state.events.push(optimisticEvent);
7635
- state.chat = { ...previousChat, draft: '', state: 'starting', activeTurn: { turnId: clientSubmissionId, local: true } };
7636
- ui.input.value = ''; autosize(); state.attachments = []; paintAttachments();
8693
+ state.chat = { ...previousChat, draft: given ? previousChat.draft : '', state: 'starting', activeTurn: { turnId: clientSubmissionId, local: true } };
8694
+ if (!given) { ui.input.value = ''; autosize(); state.attachments = []; paintAttachments(); }
7637
8695
  setBusy(true); paintConversation(); announce('Message sent.');
7638
8696
  try {
7639
8697
  // A debounced save already in flight must finish before the server clears
@@ -7647,30 +8705,41 @@
7647
8705
  modifying: previousChat.settings.permissionProfile !== 'read-only', ...subjectsField, ...filterContext.field,
7648
8706
  // #2061: the person chose "Send my message now" over a request that was waiting first.
7649
8707
  ...(sendOverride ? { overrideWaiting: true } : {}),
8708
+ // #2223 Revision 7: a message written on a card leaves the box's saved draft as it is.
8709
+ ...(given ? { keepDraft: true } : {}),
7650
8710
  }),
7651
8711
  });
7652
8712
  if (sameChat(snapshot)) endProjectBusy();
7653
8713
  if (!sameChat(snapshot)) {
7654
8714
  noteFilterContext(clientSubmissionId, filterContext, result?.filterContext);
7655
- return void subjectLinksSaved(subjects);
8715
+ subjectLinksSaved(subjects);
8716
+ // Code review 2026-10-12: a card's answer admitted after the person moved on was still sent; saying otherwise invited
8717
+ // a second copy. The server kept the box's saved draft (keepDraft), so there is nothing to put back.
8718
+ if (given) return { sent: true };
8719
+ return;
7656
8720
  }
7657
8721
  noteFilterContext(clientSubmissionId, filterContext, result?.filterContext);
7658
8722
  subjectLinksSaved(subjects);
7659
8723
  state.pendingSubmissionId = null;
7660
8724
  state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
7661
8725
  state.chat = result.chat;
8726
+ // The server kept the saved draft (keepDraft); the box's own words, newer than any save, stay in the box and its record.
8727
+ if (given) keepComposerDraft();
7662
8728
  for (const event of result.events || []) if (!state.events.some((item) => item.eventId === event.eventId)) state.events.push(event);
7663
8729
  paintConversation();
7664
8730
  // The server accepts a turn only from a ready provider, so a warning from an earlier check is stale.
7665
8731
  if (!providerReady()) void loadCapability().then(() => { if (sameChat(snapshot)) { paintSettings(); updateSendState(); } });
8732
+ if (given) return { sent: true };
7666
8733
  } catch (error) {
7667
8734
  if (!sameChat(snapshot)) {
8735
+ if (given) return givenNotSent();
7668
8736
  if (initialTurnDefinitelyRefused(error)) await restoreBackgroundDraft(snapshot, text, clientSubmissionId);
7669
8737
  return;
7670
8738
  }
7671
8739
  state.pendingSubmissionId = null;
7672
8740
  state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
7673
8741
  state.chat = previousChat;
8742
+ if (given) { paintConversation(); return givenNotSent(givenRefusal(error)); }
7674
8743
  state.attachments = previousAttachments;
7675
8744
  ui.input.value = text; autosize(); paintAttachments(); saveDraftSoon(); paintConversation();
7676
8745
  // #2061: the project is busy — ask (wait / open it / stop it) instead of only saying it failed. Nothing was sent.
@@ -7993,13 +9062,15 @@
7993
9062
  * usable, which already rules out recovery, an unconfirmed message, an upload and a provider still
7994
9063
  * being set up. Otherwise the original notice is shown and the draft stays for the user to decide.
7995
9064
  */
7996
- async function resendAfterTurnEnded({ snapshot, text, attachmentIds, error }) {
9065
+ async function resendAfterTurnEnded({ snapshot, text, attachmentIds, error, given }) {
7997
9066
  state.followupSubmitting = true;
7998
9067
  updateSendState();
7999
9068
  try { await refreshConversation(snapshot.chatId); }
8000
9069
  finally { state.followupSubmitting = false; }
8001
9070
  if (!sameChat(snapshot)) return false;
8002
9071
  updateSendState();
9072
+ // #2223 Revision 6: an answer written outside the box is the same message whatever the box holds; its writer is told.
9073
+ if (given) return !turnIsVisiblyActive() && !givenMessageBlocked();
8003
9074
  if (!turnIsVisiblyActive() && !ui.send.disabled
8004
9075
  && ui.input.value.trim() === text
8005
9076
  && JSON.stringify(state.attachments.map((item) => item.attachmentId)) === JSON.stringify(attachmentIds)) return true;
@@ -8013,14 +9084,18 @@
8013
9084
  || sessionNeedsRenewal(error) || error?.status === 413;
8014
9085
  }
8015
9086
 
8016
- async function sendFollowup() {
8017
- if (!state.chat || !turnIsVisiblyActive() || state.followupSubmitting) return;
9087
+ async function sendFollowup(given = null) {
9088
+ // #2223 Revision 6: `given` is a message written outside the box (see sendTurn); the box stays as it is, and the result
9089
+ // says { sent, message } — or hands back a reply that ended first, as it does for the box.
9090
+ const notSent = (sentence) => (given ? givenNotSent(sentence) : undefined);
9091
+ if (!state.chat || !turnIsVisiblyActive() || state.followupSubmitting) return notSent();
8018
9092
  const snapshot = captureChat();
8019
- if (!snapshot) return;
8020
- const text = ui.input.value.trim();
8021
- const attachmentIds = state.attachments.map((item) => item.attachmentId);
8022
- if (!text && !attachmentIds.length) return;
9093
+ if (!snapshot) return notSent();
9094
+ const text = given ? given.text : ui.input.value.trim();
9095
+ const attachmentIds = (given ? given.attachments : state.attachments).map((item) => item.attachmentId);
9096
+ if (!text && !attachmentIds.length) return notSent();
8023
9097
  if (new TextEncoder().encode(text).length > 128 * 1024) {
9098
+ if (given) return notSent(errorMessage({ code: 'chat-message-too-long' }));
8024
9099
  report({ code: 'chat-message-too-long' }, 'Message was not sent');
8025
9100
  return;
8026
9101
  }
@@ -8038,13 +9113,15 @@
8038
9113
  payload: { text, attachmentIds, followup: true, deliveryState: 'pending' },
8039
9114
  createdAt: new Date().toISOString(), optimistic: true,
8040
9115
  };
8041
- clearTimeout(state.draftTimer);
8042
- state.localDraft = { chatId: snapshot.chatId, text: '' };
8043
- state.backgroundDrafts.delete(snapshot.chatId);
9116
+ if (!given) {
9117
+ clearTimeout(state.draftTimer);
9118
+ state.localDraft = { chatId: snapshot.chatId, text: '' };
9119
+ state.backgroundDrafts.delete(snapshot.chatId);
9120
+ }
8044
9121
  state.followupSubmitting = true;
8045
- state.chat.draft = '';
9122
+ if (!given) state.chat.draft = '';
8046
9123
  state.events.push(optimisticEvent);
8047
- ui.input.value = ''; autosize(); state.attachments = []; paintAttachments();
9124
+ if (!given) { ui.input.value = ''; autosize(); state.attachments = []; paintAttachments(); }
8048
9125
  paintEvents({ forceBottom: true }); updateSendState();
8049
9126
  try {
8050
9127
  await state.draftWrites.get(snapshot.chatId)?.catch(() => {});
@@ -8052,14 +9129,17 @@
8052
9129
  method: 'POST', body: JSON.stringify({
8053
9130
  owner: snapshot.scope.owner, clientSubmissionId, text,
8054
9131
  uiContext: currentFloLessContext(), attachmentIds, ...filterContext.field,
9132
+ ...(given ? { keepDraft: true } : {}), // #2223 Revision 7: see sendTurn
8055
9133
  }),
8056
9134
  });
8057
9135
  noteFilterContext(clientSubmissionId, filterContext, result?.filterContext);
8058
- if (!sameChat(snapshot)) return;
9136
+ if (!sameChat(snapshot)) return given ? { sent: true } : undefined;
8059
9137
  state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
8060
9138
  for (const event of result.events || []) if (!state.events.some((item) => item.eventId === event.eventId)) state.events.push(event);
8061
9139
  state.events.sort((a, b) => a.sequence - b.sequence);
8062
9140
  state.chat = result.chat;
9141
+ // The server kept the saved draft (keepDraft); the box's own words, newer than any save, stay in the box and its record.
9142
+ if (given) { keepComposerDraft(); outcome = { sent: true }; }
8063
9143
  announce(result.followup?.deliveryState === 'queued-next'
8064
9144
  ? 'Message queued for the next AI response.'
8065
9145
  : result.followup?.deliveryState === 'accepted'
@@ -8070,6 +9150,7 @@
8070
9150
  paintConversation();
8071
9151
  } catch (error) {
8072
9152
  if (!sameChat(snapshot)) {
9153
+ if (given && followupDefinitelyRefused(error)) return notSent();
8073
9154
  if (followupDefinitelyRefused(error)) await restoreBackgroundDraft(snapshot, text, clientSubmissionId);
8074
9155
  else {
8075
9156
  optimisticEvent.payload.deliveryState = 'unknown';
@@ -8081,13 +9162,13 @@
8081
9162
  paintEvents(); updateSendState();
8082
9163
  }
8083
9164
  }
8084
- return;
9165
+ return notSent();
8085
9166
  }
8086
9167
  if (state.events.some((event) => !event.optimistic && event.clientSubmissionId === clientSubmissionId
8087
9168
  && event.type === 'user-message')) {
8088
9169
  state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
8089
9170
  announce('Follow-up saved. Waiting for AI.'); paintEvents();
8090
- return;
9171
+ return given ? { sent: true } : undefined;
8091
9172
  }
8092
9173
  const definitiveRefusal = followupDefinitelyRefused(error);
8093
9174
  // A lost HTTP reply does not prove the provider missed the message. Keep the submission
@@ -8100,14 +9181,20 @@
8100
9181
  }
8101
9182
  // An uncertain request may already own these files. Keep them on its
8102
9183
  // message, and restore chips only when the server definitely refused it.
8103
- state.attachments = definitiveRefusal ? previousAttachments : [];
8104
- ui.input.value = text; autosize(); paintAttachments(); paintEvents();
8105
- if (definitiveRefusal) saveDraftSoon();
8106
- else state.localDraft = { chatId: snapshot.chatId, text };
9184
+ if (!given) {
9185
+ state.attachments = definitiveRefusal ? previousAttachments : [];
9186
+ ui.input.value = text; autosize(); paintAttachments();
9187
+ if (definitiveRefusal) saveDraftSoon();
9188
+ else state.localDraft = { chatId: snapshot.chatId, text };
9189
+ }
9190
+ paintEvents();
8107
9191
  // The response ended before this arrived (#1616). sendTurn resends it as a new turn, and
8108
9192
  // shows this refusal only if it cannot.
8109
9193
  if (definitiveRefusal && error?.code === 'chat-followup-refused' && error?.reason === 'chat-turn-stale') {
8110
- outcome = { outcome: 'turn-ended', snapshot, text, attachmentIds, error };
9194
+ outcome = { outcome: 'turn-ended', snapshot, text, attachmentIds, error, given };
9195
+ } else if (given) {
9196
+ outcome = notSent(definitiveRefusal ? givenRefusal(error)
9197
+ : 'FloLess couldn’t confirm your answer reached the AI. Check the conversation before you answer again.');
8111
9198
  } else failedDelivery = { error, prefix: definitiveRefusal ? '' : 'Could not confirm the follow-up' };
8112
9199
  } finally {
8113
9200
  state.followupSubmitting = false;
@@ -8212,17 +9299,43 @@
8212
9299
  }
8213
9300
  }
8214
9301
 
9302
+ function stopRequestKey(chat = state.chat, scope = state.scope) {
9303
+ return JSON.stringify([scopeKey(scope), chat?.chatId, chat?.activeTurn?.turnId]);
9304
+ }
9305
+
9306
+ // These carriers are shared by all conversations. Derive their state from the visible turn,
9307
+ // even when a request from a conversation the person has left is the one that just settled.
9308
+ function paintStopState() {
9309
+ const pending = state.chat && state.pendingStops.get(stopRequestKey());
9310
+ for (const control of [ui.stop, ui.recoveryStop]) {
9311
+ control.disabled = Boolean(pending);
9312
+ if (pending) {
9313
+ control.setAttribute('aria-busy', 'true');
9314
+ control.dataset.blockedReason = pending.kind === 'recovery'
9315
+ ? 'FloLess is ending recovery for this response. Wait for it to finish.'
9316
+ : 'FloLess is stopping this response. Wait for it to finish.';
9317
+ } else {
9318
+ control.removeAttribute('aria-busy');
9319
+ delete control.dataset.blockedReason;
9320
+ }
9321
+ }
9322
+ }
9323
+
8215
9324
  async function stopTurn() {
8216
9325
  if (!state.chat?.activeTurn) return;
8217
9326
  const snapshot = captureChat();
8218
9327
  if (!snapshot) return;
8219
9328
  const chatId = snapshot.chatId;
8220
9329
  const owner = snapshot.scope.owner;
9330
+ const turnId = state.chat.activeTurn.turnId;
9331
+ const key = stopRequestKey();
9332
+ if (state.pendingStops.has(key)) return;
9333
+ const pending = { kind: 'stop' };
9334
+ state.pendingStops.set(key, pending);
8221
9335
  const stop = () => request(`/api/chat/conversations/${encodeURIComponent(chatId)}/stop`, {
8222
- method: 'POST', body: JSON.stringify({ owner }),
9336
+ method: 'POST', body: JSON.stringify({ owner, expectTurnId: turnId }),
8223
9337
  });
8224
- ui.stop.disabled = true;
8225
- ui.recoveryStop.disabled = true;
9338
+ paintStopState();
8226
9339
  announce('Stopping the current response…');
8227
9340
  try {
8228
9341
  try { await stop(); }
@@ -8235,17 +9348,24 @@
8235
9348
  if (!sameChat(snapshot)) return;
8236
9349
  await refreshConversation(chatId, false);
8237
9350
  if (!sameChat(snapshot)) return;
9351
+ if (state.chat.activeTurn && state.chat.activeTurn.turnId !== turnId) return;
8238
9352
  announce('The current response was stopped.');
8239
9353
  } catch (error) {
8240
9354
  if (!sameChat(snapshot)) return;
9355
+ if (error?.code === 'stop-stale') { await refreshConversation(chatId, false); return; }
9356
+ if (state.chat.activeTurn && state.chat.activeTurn.turnId !== turnId) return;
8241
9357
  if (error?.code === 'chat-stop-uncertain') {
8242
9358
  state.recoveryCanEnd = true;
9359
+ state.recoveryTurnId = turnId;
8243
9360
  state.recoveryMessage = 'FloLess cannot stop this response remotely because the AI app no longer recognizes it. End recovery unlocks this chat; any late response will not appear here.';
8244
9361
  paintRecovery();
8245
9362
  announce('FloLess could not stop the response remotely. You can end its local recovery lock.');
8246
9363
  } else report(error, 'Could not stop the response');
8247
9364
  }
8248
- finally { if (sameChat(snapshot)) { ui.stop.disabled = false; ui.recoveryStop.disabled = false; } }
9365
+ finally {
9366
+ if (state.pendingStops.get(key) === pending) state.pendingStops.delete(key);
9367
+ paintStopState();
9368
+ }
8249
9369
  }
8250
9370
 
8251
9371
  async function refreshChatSession() {
@@ -8280,21 +9400,49 @@
8280
9400
  async function endRecovery() {
8281
9401
  const snapshot = captureChat();
8282
9402
  if (!snapshot) return;
8283
- ui.recoveryStop.disabled = true;
9403
+ const key = stopRequestKey();
9404
+ if (state.pendingStops.has(key)) return;
9405
+ const turnId = state.chat.activeTurn?.turnId;
9406
+ const pending = { kind: 'recovery' };
9407
+ state.pendingStops.set(key, pending);
9408
+ paintStopState();
8284
9409
  announce('Ending recovery for this response…');
8285
9410
  try {
8286
9411
  const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/end-recovery`, {
8287
- method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner }),
9412
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, expectTurnId: turnId }),
8288
9413
  });
8289
9414
  if (!sameChat(snapshot)) return;
9415
+ if (state.chat.activeTurn && state.chat.activeTurn.turnId !== turnId) return;
9416
+ // The visible row still belongs to the initiating response (or its terminal refresh).
9417
+ // Its End authority is obsolete even when the POST already carries a replacement response.
8290
9418
  state.recoveryCanEnd = false;
8291
9419
  state.recoveryMessage = null;
9420
+ state.recoveryTurnId = null;
9421
+ if (result.chat.activeTurn && result.chat.activeTurn.turnId !== turnId) {
9422
+ paintRecovery();
9423
+ return;
9424
+ }
9425
+ // A terminal SSE refresh may beat this acknowledgement. Clear this turn's recovery authority,
9426
+ // but keep that newer conversation row rather than replacing it with the older POST result.
9427
+ if (!state.chat.activeTurn) {
9428
+ paintRecovery();
9429
+ announce('Recovery ended. You can continue this chat. The AI may still be working; any late reply will not appear here.');
9430
+ return;
9431
+ }
8292
9432
  state.chat = result.chat;
8293
9433
  await refreshConversation(snapshot.chatId, false);
8294
9434
  if (!sameChat(snapshot)) return;
8295
- announce('This unconfirmed response was ended. You can continue this chat.');
8296
- } catch (error) { if (sameChat(snapshot)) report(error, 'Could not end recovery'); }
8297
- finally { if (sameChat(snapshot)) ui.recoveryStop.disabled = false; }
9435
+ if (state.chat.activeTurn && state.chat.activeTurn.turnId !== turnId) return;
9436
+ announce('Recovery ended. You can continue this chat. The AI may still be working; any late reply will not appear here.');
9437
+ } catch (error) {
9438
+ if (error.code === 'chat-recovery-stale') {
9439
+ if (sameChat(snapshot)) await refreshConversation(snapshot.chatId, false);
9440
+ } else if (sameChat(snapshot) && state.chat.activeTurn?.turnId === turnId) report(error, 'Could not end recovery');
9441
+ }
9442
+ finally {
9443
+ if (state.pendingStops.get(key) === pending) state.pendingStops.delete(key);
9444
+ paintStopState();
9445
+ }
8298
9446
  }
8299
9447
 
8300
9448
  async function reconcile() {
@@ -8309,6 +9457,7 @@
8309
9457
  ui.reconcile.textContent = 'Checking…';
8310
9458
  state.recoveryMessage = null;
8311
9459
  state.recoveryCanEnd = false;
9460
+ state.recoveryTurnId = state.chat.activeTurn?.turnId;
8312
9461
  ui.recoveryCopy.textContent = 'Checking the last AI response now. You can continue when FloLess confirms it is safe.';
8313
9462
  announce('Checking the last AI response…');
8314
9463
  try {
@@ -8353,6 +9502,7 @@
8353
9502
  const snapshot = captureChat();
8354
9503
  if (!snapshot) return;
8355
9504
  const approvalId = approval.approvalId;
9505
+ const offer = approvalOffer(approval);
8356
9506
  // The provider stays paused while this request reaches it, but the choice is already made.
8357
9507
  // Suppress any stale poll/SSE snapshot so the card disappears on the click itself instead of
8358
9508
  // looking like a frozen control until the provider acknowledges the decision.
@@ -8363,7 +9513,7 @@
8363
9513
  try {
8364
9514
  const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/approvals/${encodeURIComponent(approvalId)}`, {
8365
9515
  method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, decision,
8366
- ...(decision === 'allow-chat' ? { allowanceRevision } : {}) }),
9516
+ ...(allowanceRevision !== undefined ? { allowanceRevision } : {}) }),
8367
9517
  });
8368
9518
  if (!sameChat(snapshot)) return;
8369
9519
  // #1890 PR 2b: the server says what it actually did. A change it refused at its last check is announced with the
@@ -8373,12 +9523,9 @@
8373
9523
  announce(refusal ? refusal
8374
9524
  // The request ended before the choice reached the AI (it was stopped or withdrawn): claim nothing about it.
8375
9525
  : outcome?.delivered === false ? 'This request ended before your choice reached the AI.'
8376
- : decision === 'allow-request' ? 'Access auto-approval is on for this request.'
9526
+ : decision === 'allow-request' ? `Allowed until this reply ends: ${offer?.what || 'this kind of request'}.`
8377
9527
  : decision === 'allow-session' ? 'Access auto-approval is on for this conversation until you press Revoke, above the message box.'
8378
- : decision === 'allow-chat' && approval.change ? 'File changes in this conversation’s scope are allowed for this chat. Commands and tools still ask. Revoke above the message box.'
8379
- : decision === 'allow-chat' && approval.connectionCheck ? `Checks of ${approval.connectionCheck.name || 'this tool'} are allowed for this chat. Revoke them above the message box.`
8380
- : decision === 'allow-chat' && approval.connector ? `${connectorLabel(approval.connector)} is allowed for this chat. Revoke it above the message box.`
8381
- : decision === 'allow-chat' ? 'Tekla reads are allowed for this chat. Revoke them from the Tekla box above the message.'
9528
+ : decision === 'allow-chat' ? `Allowed for this conversation: ${offer?.conversationWhat || offer?.what || 'this kind of request'}. Revoke it above the message box.`
8382
9529
  : decision === 'allow' ? 'Approved once.' : 'Action denied.');
8383
9530
  await refreshConversation(snapshot.chatId, false);
8384
9531
  } catch (error) {
@@ -8760,6 +9907,8 @@
8760
9907
 
8761
9908
  function refreshActivity() {
8762
9909
  paintConversation();
9910
+ // Requests changed (or the list just polled): the request cards in the feed read their live state again.
9911
+ void refreshRequestCards({ force: true });
8763
9912
  }
8764
9913
 
8765
9914
  async function refreshIndex() {
@@ -8781,7 +9930,7 @@
8781
9930
 
8782
9931
  // Longer than the server's capability-check bound (CAPABILITY_PROBE_TIMEOUT_MS, 12 s) plus its locks.
8783
9932
  const REQUEST_START_TIMEOUT_MS = 30000;
8784
- async function startRequest(requestId, provider, mode = 'start') {
9933
+ async function startRequest(requestId, provider, mode = 'start', options = {}) {
8785
9934
  if (!state.scope?.owner) throw new Error('Open the Request’s project or workflow before starting its chat.');
8786
9935
  if (provider !== 'claude' && provider !== 'codex') throw new Error('Choose Claude or Codex for this chat.');
8787
9936
  const scope = state.scope;
@@ -8790,7 +9939,9 @@
8790
9939
  if (!sameScope(scope, generation)) {
8791
9940
  throw Object.assign(new Error('The project or workflow changed while FloLess was starting this request. Open it again and try once more.'), { code: 'request-chat-owner-mismatch' });
8792
9941
  }
8793
- const currentChatId = state.chat && state.chat.provider === provider && !state.chat.activeTurn
9942
+ // #2185: "Work on it" starts the request in its OWN conversation. Without `ownChat`, an idle open chat of the same AI is
9943
+ // reused (Discuss), which is how a request used to end up as a card in whatever chat happened to be open.
9944
+ const currentChatId = options?.ownChat !== true && state.chat && state.chat.provider === provider && !state.chat.activeTurn
8794
9945
  && !state.chat.archivedAt && state.chat.state !== 'recovery' ? state.chat.chatId : undefined;
8795
9946
  // Starting a Request waits for the AI's capability check (up to 12 s on the server, longer when
8796
9947
  // it first launches a copy FloLess has only just set up), so a shorter wait here reported
@@ -8798,7 +9949,7 @@
8798
9949
  // "Still opening…" after 4 s, so the longer wait is not a silent one.
8799
9950
  const result = await request(`/api/chat/requests/${encodeURIComponent(requestId)}/start`, {
8800
9951
  method: 'POST', timeoutMs: REQUEST_START_TIMEOUT_MS,
8801
- body: JSON.stringify({ provider, mode, chatId: currentChatId, expectedOwner: scope.owner }),
9952
+ body: JSON.stringify({ provider, mode, chatId: currentChatId, expectedOwner: scope.owner, ...(options?.restoreFirst === true ? { restoreFirst: true } : {}) }),
8802
9953
  });
8803
9954
  if (!sameScope(scope, generation)) {
8804
9955
  throw Object.assign(new Error('The project or workflow changed while FloLess was starting this request. Open it again and try once more.'), { code: 'request-chat-owner-mismatch' });
@@ -9033,6 +10184,17 @@
9033
10184
  }
9034
10185
  }
9035
10186
 
10187
+ // This is a browser presentation preference, never a conversation permission or approval.
10188
+ function readAccessExplanationPreference() {
10189
+ try { return localStorage.getItem('floless:chat-access-explanation') === 'expanded'; } catch { return false; }
10190
+ }
10191
+
10192
+ function toggleAccessExplanation() {
10193
+ state.accessExplanationExpanded = !state.accessExplanationExpanded;
10194
+ try { localStorage.setItem('floless:chat-access-explanation', state.accessExplanationExpanded ? 'expanded' : 'collapsed'); } catch { /* private mode: retain the choice for this page */ }
10195
+ paintScopeControl();
10196
+ }
10197
+
9036
10198
  function paintScopeControl() {
9037
10199
  if (!ui.scopeControls) return;
9038
10200
  const chat = state.chat;
@@ -9049,12 +10211,24 @@
9049
10211
  ui.scopeToggle.disabled = state.loading;
9050
10212
  if (ui.scopeToggle.disabled) ui.scopeToggle.dataset.blockedReason = 'The conversation is still loading.';
9051
10213
  else delete ui.scopeToggle.dataset.blockedReason;
9052
- const disclosure = chat.settings?.permissionProfile === 'read-only'
10214
+ const disclosure = isInstructorAnswer(chat)
10215
+ ? '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.'
10216
+ : chat.settings?.permissionProfile === 'read-only'
9053
10217
  ? 'Read only: the AI’s file tools cannot change files. Commands keep their own approvals and may authorize file changes.'
9054
- : chat.settings?.permissionProfile === 'full-access' ? 'Full access is on. The AI can change files without asking.'
10218
+ : chat.settings?.permissionProfile === 'full-access' ? fullAccessScopeNote()
9055
10219
  : chat.settings?.permissionProfile === 'auto' ? autoScopeNote()
9056
- : chat.changeAllowance?.allowedForChat ? 'File changes in scope, including folders you add later, are allowed for this chat.' : '';
10220
+ : chat.changeAllowance?.allowedForChat ? 'File changes in scope, including folders you add later, are allowed for this chat.' : permissionTip(chat.settings?.permissionProfile);
9057
10221
  if (ui.scopeDisclosure.textContent !== disclosure) ui.scopeDisclosure.textContent = disclosure;
10222
+ if (ui.accessExplanation) {
10223
+ const label = isInstructorAnswer(chat) ? 'No tools' : permissionLabel(chat.settings?.permissionProfile);
10224
+ ui.accessExplanation.querySelector('strong').textContent = label;
10225
+ ui.accessExplanation.setAttribute('aria-label', `Explain ${label} access`);
10226
+ ui.accessExplanation.setAttribute('aria-expanded', String(Boolean(state.accessExplanationExpanded)));
10227
+ ui.accessExplanation.dataset.tip = state.accessExplanationExpanded ? 'Explanation shown. Hide the access explanation.' : 'Explanation hidden. Show what this access level allows.';
10228
+ ui.accessExplanation.dataset.commandInstanceLabel = state.accessExplanationExpanded ? 'shown' : 'hidden';
10229
+ ui.accessExplanation.dataset.commandId = `shell.chat-access-explanation#${state.accessExplanationExpanded ? 'shown' : 'hidden'}`;
10230
+ ui.scopeDisclosure.hidden = !state.accessExplanationExpanded || !disclosure;
10231
+ }
9058
10232
  // Poll/SSE can change permissions or pause a reply while Scope stays open. Refresh only when
9059
10233
  // these states change, retaining its selected add choice and focus on an enabled control.
9060
10234
  const picker = ui.scopePicker;
@@ -9114,7 +10288,7 @@
9114
10288
  const note = document.createElement('p'); note.className = 'ai-chat-scope-note';
9115
10289
  note.textContent = readOnly ? 'The AI’s file tools cannot change files while Read only is on. Commands keep their own approvals and may authorize file changes. Scope adds folders and project data; it does not limit file reads.'
9116
10290
  + (globalAllowance ? ' Your saved file-change allowance does not override Read only.' : '')
9117
- : profile === 'full-access' ? 'Full access is on. The AI can change files without asking.'
10291
+ : profile === 'full-access' ? fullAccessScopeNote()
9118
10292
  : profile === 'auto' ? autoScopeNote()
9119
10293
  : globalAllowance ? 'File changes in this scope, including folders you add later, are allowed without asking. Commands and tools keep their own approvals. Scope does not limit file reads.'
9120
10294
  : 'File edits outside your home folder ask for approval unless you allow file changes for this chat. Scope adds folders and project data to this conversation; it does not limit file reads. Your home folder keeps its native provider permissions.';
@@ -9150,9 +10324,8 @@
9150
10324
  const choice = state.scopeChoice;
9151
10325
  const choiceKey = choice.target.kind === 'project' ? choice.target.projectId : choice.target.workflowId;
9152
10326
  const question = document.createElement('p'); question.className = 'ai-chat-scope-note';
9153
- const writeProfile = state.chat?.owner?.kind === 'workspace' ? 'Make changes (asks first)' : 'Working folder write';
9154
10327
  question.textContent = `Add ${choice.target.kind} “${choice.label}” to this conversation?${globalAllowance ? readOnly
9155
- ? ` If you choose ${writeProfile}, file changes here will also be allowed without asking.`
10328
+ ? ' If you choose Working folder write, file changes here will also be allowed without asking.'
9156
10329
  : ' File changes here will also be allowed without asking.' : ''}`;
9157
10330
  const add = button(globalAllowance ? readOnly ? 'Add scope for later file changes' : 'Add scope and allow file changes' : 'Add scope', `shell.chat-scope-add#${commandInstance(`${choice.target.kind}:${choiceKey}`)}`, 'ai-chat-scope-action');
9158
10331
  add.dataset.commandInstanceLabel = choice.label; add.disabled = state.scopeEditing || Boolean(state.chat?.activeTurn);
@@ -9216,6 +10389,74 @@
9216
10389
  }
9217
10390
  }
9218
10391
 
10392
+ // Epic #2185 Slice A: what the person allowed for the kinds of request that have no box of their own - for this reply
10393
+ // (kept in the server's memory, gone when the reply ends) and for this conversation - each with its own Revoke. The
10394
+ // older boxes (file changes, connectors, checks, Tekla, the access-action strips) keep painting theirs.
10395
+ function paintApprovalGrants() {
10396
+ const host = ui.grants;
10397
+ if (!host) return;
10398
+ const chat = state.chat;
10399
+ const live = chat && !chat.archivedAt;
10400
+ const turn = live && ['running', 'awaiting-approval'].includes(chat.state) ? chat.activeTurn : null;
10401
+ const request = turn && Array.isArray(turn.requestGrants) ? turn.requestGrants.filter((grant) => grant && grant.key) : [];
10402
+ const conversation = live && Array.isArray(chat.approvalGrants?.grants) ? chat.approvalGrants.grants : [];
10403
+ const painted = `${chat?.chatId || ''}|${turn?.turnId || ''}|${request.map((grant) => grant.key).join(',')}|${conversation.map((grant) => grant.key).join(',')}|${state.grantRevoking || ''}`;
10404
+ if (host.dataset.painted === painted) return;
10405
+ host.dataset.painted = painted;
10406
+ host.replaceChildren();
10407
+ host.hidden = !request.length && !conversation.length;
10408
+ if (host.hidden) return;
10409
+ const rows = [
10410
+ ...request.map((grant) => ({ ...grant, which: 'request', turnId: turn.turnId })),
10411
+ ...conversation.map((grant) => ({ ...grant, which: 'conversation' })),
10412
+ ];
10413
+ const title = document.createElement('span');
10414
+ title.className = 'ai-chat-connectors-title';
10415
+ title.textContent = 'Allowed without asking:';
10416
+ host.append(title);
10417
+ for (const grant of rows) {
10418
+ const id = `${grant.which}:${grant.key}`;
10419
+ const pill = document.createElement('span');
10420
+ pill.className = 'ai-chat-connector-pill';
10421
+ const name = document.createElement('span');
10422
+ name.textContent = `${grant.label} · ${grant.which === 'request' ? 'this reply' : 'this conversation'}`;
10423
+ const revoke = button('Revoke', grant.which === 'request' ? 'shell.chat-request-grant-revoke' : 'shell.chat-approval-grant-revoke', 'ai-chat-connector-revoke');
10424
+ revoke.dataset.commandInstanceLabel = grant.label;
10425
+ revoke.setAttribute('aria-label', `Revoke: ${grant.label}, ${grant.which === 'request' ? 'this reply' : 'this conversation'}`);
10426
+ revoke.dataset.tip = `${grant.label} will ask you again. Something already approved may finish.`;
10427
+ revoke.disabled = state.grantRevoking === id;
10428
+ revoke.addEventListener('click', () => { void revokeApprovalGrant(grant); });
10429
+ pill.append(name, revoke);
10430
+ host.append(pill);
10431
+ }
10432
+ }
10433
+
10434
+ async function revokeApprovalGrant(grant) {
10435
+ const snapshot = captureChat();
10436
+ if (!snapshot) return;
10437
+ const id = `${grant.which}:${grant.key}`;
10438
+ state.grantRevoking = id;
10439
+ paintApprovalGrants();
10440
+ try {
10441
+ await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/${grant.which === 'request' ? 'approval-scope' : 'approval-grants'}/revoke`, {
10442
+ method: 'POST', body: JSON.stringify(grant.which === 'request'
10443
+ ? { owner: snapshot.scope.owner, turnId: grant.turnId, key: grant.key }
10444
+ : { owner: snapshot.scope.owner, key: grant.key }),
10445
+ });
10446
+ if (!sameChat(snapshot)) return;
10447
+ announce(`${grant.label} will ask you again. Something already approved may finish.`);
10448
+ await refreshConversation(snapshot.chatId, false);
10449
+ } catch (error) {
10450
+ if (!sameChat(snapshot)) return;
10451
+ report(error, 'Could not revoke');
10452
+ await refreshConversation(snapshot.chatId, false);
10453
+ } finally {
10454
+ state.grantRevoking = null;
10455
+ if (sameChat(snapshot)) paintApprovalGrants();
10456
+ (ui.grants?.querySelector('.ai-chat-connector-revoke') || ui.input)?.focus();
10457
+ }
10458
+ }
10459
+
9219
10460
  // Legacy per-owner allowances remain removable when no conversation-wide file allowance covers them.
9220
10461
  function paintChangeAllowance() {
9221
10462
  const host = ui.changeAllowance;
@@ -9636,6 +10877,28 @@
9636
10877
  });
9637
10878
  }
9638
10879
 
10880
+ /**
10881
+ * #2185: build a workflow in its own conversation (a Guide card or ≡ New workflow), then land on it: the workflow opens
10882
+ * and its conversation, already working, is the one shown. The same build id always answers the same workflow.
10883
+ */
10884
+ async function startWorkflowBuild(buildId, payload) {
10885
+ await ensureSession();
10886
+ const result = await request(`/api/chat/workflow-builds/${encodeURIComponent(buildId)}/start`, {
10887
+ method: 'POST', timeoutMs: REQUEST_START_TIMEOUT_MS, body: JSON.stringify(payload),
10888
+ });
10889
+ window.flolessBridge?.revealAiChat?.();
10890
+ let opened = false;
10891
+ // No conversation (it was deleted and its Request has left the queue): the workflow itself opens.
10892
+ if (result.chat) {
10893
+ try { opened = await openMovedChat({ owner: { kind: 'workflow', workflowId: result.workflow.workflowId }, chatId: result.chat.chatId }); }
10894
+ catch (error) { console.warn('[chat] built a workflow but could not open its conversation:', error); }
10895
+ }
10896
+ // The AI's first reply is usually a question, so the person's next move is typing in this conversation.
10897
+ if (opened) ui.input.focus();
10898
+ else await window.flolessBridge?.openOwnedWorkflow?.(result.workflow.workflowId);
10899
+ return result;
10900
+ }
10901
+
9639
10902
  async function resumeProjectIntake(submissionId) {
9640
10903
  await ensureSession();
9641
10904
  return request(`/api/chat/project-intakes/${encodeURIComponent(submissionId)}/resume`, {
@@ -9676,7 +10939,7 @@
9676
10939
  ui.model.addEventListener('click', () => openPicker('model', ui.model, modelChoices()));
9677
10940
  ui.switchAccount.addEventListener('click', () => { void switchAccount(); });
9678
10941
  ui.effort.addEventListener('click', () => openPicker('effort', ui.effort, effortChoices()));
9679
- ui.permission.addEventListener('click', () => openPicker('permission', ui.permission, permissionChoices(), permissionPickerNote()));
10942
+ ui.permission.addEventListener('click', () => openPicker('permission', ui.permission, permissionChoices()));
9680
10943
  // #2046: the Guide's own controls (web/guide.js does the work and says what happened).
9681
10944
  el('chat-guide-off')?.addEventListener('click', () => { void window.flolessGuide?.turnOff?.(); });
9682
10945
  el('chat-guide-delete')?.addEventListener('click', () => { void window.flolessGuide?.deleteHistory?.(); });
@@ -9697,7 +10960,10 @@
9697
10960
  });
9698
10961
  document.getElementById('ws-frame-drawings')?.addEventListener('load', () => { paintFloLessContext(); refreshFilterCards(); updateSendState(); });
9699
10962
  ui.stop.addEventListener('click', stopTurn);
9700
- ui.recoveryStop.addEventListener('click', () => { void (state.recoveryCanEnd ? endRecovery() : stopTurn()); });
10963
+ ui.recoveryStop.addEventListener('click', () => {
10964
+ paintRecovery();
10965
+ void (state.recoveryCanEnd ? endRecovery() : stopTurn());
10966
+ });
9701
10967
  ui.reconcile.addEventListener('click', reconcile);
9702
10968
  ui.attach.addEventListener('click', () => ui.file.click());
9703
10969
  ui.file.addEventListener('change', () => attachFiles(ui.file.files));
@@ -9707,6 +10973,7 @@
9707
10973
  else if (event.key === 'Escape') { ui.skills.hidden = true; closePicker(); }
9708
10974
  });
9709
10975
  ui.scopeToggle?.addEventListener('click', () => { void openScopePicker(); });
10976
+ ui.accessExplanation?.addEventListener('click', toggleAccessExplanation);
9710
10977
  ui.scopePicker?.addEventListener('keydown', (event) => {
9711
10978
  if (event.key === 'Escape') { event.preventDefault(); closeScopePicker(true); }
9712
10979
  });
@@ -9771,7 +11038,7 @@
9771
11038
  });
9772
11039
  window.flolessChat = {
9773
11040
  refreshScope, refreshActivity, refreshIndex, startRequest, openConversation, openConversationIn, openDraft, openVerifiedTeklaDraft,
9774
- startProjectIntake, resumeProjectIntake,
11041
+ startProjectIntake, resumeProjectIntake, startWorkflowBuild,
9775
11042
  // The plain-English sentence for a refusal the chat routes named, so a Start outside this panel
9776
11043
  // (the upload modal, Requests) says what happened and what to do next instead of a generic toast (#1779).
9777
11044
  describeError: errorMessage,