@floless/app 0.153.0 → 0.154.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.
package/dist/web/chat.js CHANGED
@@ -35,6 +35,7 @@
35
35
  scopeControls: el('chat-scope-controls'), scopeToggle: el('chat-scope-toggle'),
36
36
  scopePicker: el('chat-scope-picker'), scopeDisclosure: el('chat-scope-disclosure'),
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'),
@@ -102,8 +103,8 @@
102
103
  // The server's own sentence is more accurate than anything we can substitute: it names WHICH
103
104
  // runtime problem happened and WHICH command to run by hand. errorMessage() would flatten it.
104
105
  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' };
106
+ const requestTypeLabels = { 'drawing-intake': 'Initial drawing read', 'initial-drawing-read': 'Initial drawing read', 'tweak-contract': 'Workflow change', guide: 'Question', 'new-workflow': 'Build a workflow' };
107
+ 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
108
  // Pictures and PDFs upload as the browser names them. Any other file is a DATA file (#1853): its
108
109
  // bytes decide whether FloLess can read it (sniffDataFile), never its name or declared type.
109
110
  const allowedTypes = new Set(['image/png', 'image/jpeg', 'image/webp', 'application/pdf']);
@@ -287,8 +288,14 @@
287
288
  'request-chat-not-ready': 'This request is still being prepared. Wait a moment, then try again.',
288
289
  'chat-knowledge-unscoped': 'Knowledge is available only inside a project conversation. Open a project and try again.',
289
290
  '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.',
291
+ 'approval-explicit-only': 'This request needs its own approval. Choose Approve once or Deny.',
292
+ 'approval-not-chat-allowable': 'That choice does not fit this request. Choose again.',
293
+ 'approval-not-session-allowable': 'That choice does not fit this request. Choose again.',
294
+ 'request-grant-changed': 'What is allowed for this request changed. Choose again.',
295
+ 'session-approval-changed': 'Auto-approval for this conversation changed. Choose again.',
296
+ 'approval-grants-changed': 'What is allowed for this chat changed. Choose again.',
297
+ 'integration-read-allowance-changed': 'The connection checks allowed for this chat changed. Choose again.',
298
+ 'change-allowance-changed': 'The changes allowed for this chat changed. Choose again.',
292
299
  'tekla-allowance-changed': 'The Tekla read permission for this chat changed. Choose again.',
293
300
  'connector-allowance-changed': 'The connectors allowed for this chat changed. Choose again.',
294
301
  };
@@ -833,6 +840,7 @@
833
840
  paintChangeAllowance();
834
841
  paintScopeControl();
835
842
  paintCheckAllowance();
843
+ paintApprovalGrants();
836
844
  }
837
845
 
838
846
  function providerChooser() {
@@ -2188,7 +2196,12 @@
2188
2196
  label.textContent = requestTypeLabels[payload.requestType] || String(payload.requestType || 'Request').replace(/-/g, ' ');
2189
2197
  const status = document.createElement('span'); status.className = 'ai-chat-request-status';
2190
2198
  status.textContent = requestStatusLabels[payload.requestStatus] || String(payload.requestStatus || 'pending').replace(/-/g, ' ');
2191
- head.append(label, status);
2199
+ // #2185: always-visible ✕ - hides the card, and on a request that is still waiting also sets the request aside (with Undo).
2200
+ const hide = document.createElement('button'); hide.type = 'button'; hide.className = 'ai-chat-request-dismiss'; hide.textContent = '×';
2201
+ hide.dataset.commandId = `shell.chat-request-dismiss#${payload.requestId || 'linked request'}`;
2202
+ hide.setAttribute('aria-label', 'Dismiss this request');
2203
+ status.setAttribute('role', 'status');
2204
+ head.append(label, status, hide);
2192
2205
  const body = document.createElement('p'); body.textContent = payloadText(event);
2193
2206
  item.append(head, body);
2194
2207
  if (Array.isArray(payload.sourceNames) && payload.sourceNames.length) {
@@ -2203,9 +2216,209 @@
2203
2216
  open.dataset.tip = 'Open the linked request and its detailed progress';
2204
2217
  open.addEventListener('click', () => window.flolessBridge?.openRequest?.(payload.requestId));
2205
2218
  actions.append(open); item.append(actions);
2219
+ // Its live state replaces the frozen copy above as soon as it is known (and again whenever Requests changes).
2220
+ initRequestCard(item, event);
2206
2221
  return item;
2207
2222
  }
2208
2223
 
2224
+ /*
2225
+ * #2185 - the request card tells the truth about its request, now. The frozen copy in the event says "Queued" for ever; the
2226
+ * server's projection says Waiting for the AI / The AI is working / The AI has a question / Done / Dismissed / Expired.
2227
+ * ✕ is always there: on a request that is only waiting it sets the request aside (Undo puts it back); when the AI is
2228
+ * working on it the card ASKS - stop that work and dismiss, or keep it. On one that is already done it hides the card.
2229
+ */
2230
+ const REQUEST_CARD_WORDS = { dismissed: 'Dismissed', expired: 'Expired', settled: 'Done' };
2231
+ const REQUEST_CARD_HIDDEN_KEY = 'floless:chat-hidden-request-cards';
2232
+ state.requestCards = state.requestCards || new Map();
2233
+ state.requestCardsAt = state.requestCardsAt || 0;
2234
+
2235
+ function hiddenRequestCards() {
2236
+ try {
2237
+ const parsed = JSON.parse(localStorage.getItem(REQUEST_CARD_HIDDEN_KEY) || '[]');
2238
+ return new Set(Array.isArray(parsed) ? parsed.filter((id) => typeof id === 'string') : []);
2239
+ } catch { return new Set(); }
2240
+ }
2241
+ function rememberHiddenRequestCard(eventId, hidden) {
2242
+ const ids = hiddenRequestCards();
2243
+ if (hidden) ids.add(eventId); else ids.delete(eventId);
2244
+ try { localStorage.setItem(REQUEST_CARD_HIDDEN_KEY, JSON.stringify([...ids].slice(-300))); } catch { /* private mode: it shows again next time */ }
2245
+ }
2246
+
2247
+ /** The word for a request's live state, or '' when nothing live is known yet (the frozen word stays). */
2248
+ function requestCardWord(live) {
2249
+ if (!live) return '';
2250
+ if (live.found === false) return 'Done';
2251
+ if (live.lifecycle?.state) return REQUEST_CARD_WORDS[live.lifecycle.state] || '';
2252
+ return live.attention?.label || '';
2253
+ }
2254
+
2255
+ function paintRequestCard(item) {
2256
+ const requestId = item.dataset.requestId;
2257
+ const live = state.requestCards.get(requestId);
2258
+ const word = requestCardWord(live);
2259
+ const status = item.querySelector('.ai-chat-request-status');
2260
+ if (status && word) status.textContent = word;
2261
+ const set = live?.found !== false ? live?.lifecycle?.state || null : null;
2262
+ item.dataset.requestState = live ? (live.found === false ? 'gone' : set || 'waiting') : 'unknown';
2263
+ item.dataset.attention = live?.attention?.state || '';
2264
+ item.classList.toggle('ai-chat-request-aside', set === 'dismissed' || set === 'expired');
2265
+ // A request I dismissed from here can be taken back from here.
2266
+ let undo = item.querySelector('.ai-chat-request-undo');
2267
+ if (set === 'dismissed' || set === 'expired') {
2268
+ if (!undo) {
2269
+ undo = button('Undo', `shell.chat-request-undo#${requestId || 'linked request'}`, 'ai-chat-request-undo');
2270
+ undo.dataset.tip = 'Put this request back in Requests, exactly as it was';
2271
+ undo.addEventListener('click', () => { void restoreRequestFromCard(item); });
2272
+ item.querySelector('.ai-chat-request-actions')?.prepend(undo);
2273
+ }
2274
+ } else if (undo) undo.remove();
2275
+ const hideButton = item.querySelector('.ai-chat-request-dismiss');
2276
+ if (hideButton) {
2277
+ const finished = live && (live.found === false || set);
2278
+ hideButton.dataset.tip = finished ? 'Hide this card from the chat' : 'Dismiss this request. It stays in Requests → Done, and you can undo it';
2279
+ hideButton.setAttribute('aria-label', finished ? 'Hide this card' : 'Dismiss this request');
2280
+ }
2281
+ }
2282
+
2283
+ function initRequestCard(item, event) {
2284
+ item.dataset.cardEventId = event.eventId;
2285
+ if (hiddenRequestCards().has(event.eventId)) item.hidden = true;
2286
+ const hide = item.querySelector('.ai-chat-request-dismiss');
2287
+ hide?.addEventListener('click', () => { void dismissRequestFromCard(item, event.eventId); });
2288
+ paintRequestCard(item);
2289
+ queueMicrotask(() => { void refreshRequestCards(); });
2290
+ }
2291
+
2292
+ async function refreshRequestCards({ force = false } = {}) {
2293
+ if (!ui.feed) return;
2294
+ const cards = [...ui.feed.querySelectorAll('.ai-chat-request-card[data-request-id]')].filter((card) => card.dataset.requestId);
2295
+ if (!cards.length) return;
2296
+ if (!force && Date.now() - state.requestCardsAt < 2500) return;
2297
+ state.requestCardsAt = Date.now();
2298
+ const ids = [...new Set(cards.map((card) => card.dataset.requestId))].slice(0, 40);
2299
+ let statuses;
2300
+ try { statuses = (await request(`/api/requests/status?ids=${ids.map(encodeURIComponent).join(',')}`, { timeoutMs: 10000 })).statuses; }
2301
+ catch { return; /* the card keeps what it last knew; the next poll tries again */ }
2302
+ if (!Array.isArray(statuses)) return;
2303
+ for (const live of statuses) if (live?.id) state.requestCards.set(live.id, live);
2304
+ for (const card of ui.feed.querySelectorAll('.ai-chat-request-card[data-request-id]')) paintRequestCard(card);
2305
+ }
2306
+
2307
+ async function lifecycleCall(requestId, action) {
2308
+ const response = await fetch(`/api/requests/${encodeURIComponent(requestId)}/${action}`, {
2309
+ method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' }, body: '{}',
2310
+ });
2311
+ const body = await response.json().catch(() => ({}));
2312
+ return { ok: response.ok && body.ok !== false, status: response.status, body };
2313
+ }
2314
+
2315
+ async function dismissRequestFromCard(item, eventId) {
2316
+ const requestId = item.dataset.requestId;
2317
+ if (!requestId) return;
2318
+ const live = state.requestCards.get(requestId);
2319
+ // Already done, set aside or gone: ✕ only hides this card from this chat.
2320
+ if (live && (live.found === false || live.lifecycle)) {
2321
+ rememberHiddenRequestCard(eventId, true);
2322
+ item.hidden = true;
2323
+ return;
2324
+ }
2325
+ const hide = item.querySelector('.ai-chat-request-dismiss');
2326
+ if (hide) hide.disabled = true;
2327
+ item.querySelector('.ai-chat-request-note')?.remove(); // a new try replaces the last failure's note
2328
+ try {
2329
+ const done = await lifecycleCall(requestId, 'dismiss');
2330
+ if (done.ok) {
2331
+ state.requestCards.set(requestId, { id: requestId, found: true, lifecycle: { state: 'dismissed' }, attention: { state: 'not-now', code: 'dismissed', label: 'Dismissed' } });
2332
+ paintRequestCard(item);
2333
+ item.querySelector('.ai-chat-request-undo')?.focus();
2334
+ announce('Request dismissed. Undo is on the card.');
2335
+ return;
2336
+ }
2337
+ if (done.body?.code === 'request-held' && done.body.hold) { askStopThenDismiss(item, done.body.hold); return; }
2338
+ if (done.status === 404 || done.body?.code === 'request-already-set-aside') { void refreshRequestCards({ force: true }); return; }
2339
+ cardNotice(item, done.body?.error || 'FloLess couldn’t dismiss that request. It is still in Requests; try ✕ again.');
2340
+ } catch {
2341
+ cardNotice(item, 'FloLess couldn’t reach the server, so the request was not dismissed. Try ✕ again in a moment.');
2342
+ } finally {
2343
+ if (hide) hide.disabled = false;
2344
+ }
2345
+ }
2346
+
2347
+ /** A failure said where the person is looking (on the card) as well as to a screen reader: never only one of the two. */
2348
+ function cardNotice(item, text) {
2349
+ item.querySelector('.ai-chat-request-note')?.remove();
2350
+ const note = document.createElement('p');
2351
+ note.className = 'ai-chat-request-note'; note.setAttribute('role', 'status'); note.textContent = text;
2352
+ item.append(note);
2353
+ announce(text);
2354
+ }
2355
+
2356
+ /** The AI is working on it: ask - stop that work and dismiss, or keep the request. Nothing happened yet. */
2357
+ function askStopThenDismiss(item, hold) {
2358
+ item.querySelector('.ai-chat-request-ask')?.remove();
2359
+ 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');
2360
+ // Escape means Keep it: the safe default.
2361
+ ask.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.stopPropagation(); ask.remove(); item.querySelector('.ai-chat-request-dismiss')?.focus(); } });
2362
+ const why = document.createElement('p'); why.textContent = `${hold.why || 'The AI is working on this request.'} Nothing was changed.`;
2363
+ const row = document.createElement('div'); row.className = 'ai-chat-request-ask-actions';
2364
+ const keep = button('Keep it', `shell.chat-request-keep#${item.dataset.requestId || 'linked request'}`);
2365
+ keep.addEventListener('click', () => { ask.remove(); item.querySelector('.ai-chat-request-dismiss')?.focus(); });
2366
+ row.append(keep);
2367
+ const stop = hold.stop;
2368
+ if (stop) {
2369
+ const go = button('Stop it and dismiss', `shell.chat-request-stop-dismiss#${item.dataset.requestId || 'linked request'}`, 'danger');
2370
+ go.addEventListener('click', async () => {
2371
+ go.disabled = true; keep.disabled = true;
2372
+ let stopped = true; // a stale stop means the work had already ended or changed: never claimed as "stopped"
2373
+ try {
2374
+ if (stop.kind === 'chat') {
2375
+ await request(`/api/chat/conversations/${encodeURIComponent(stop.chatId)}/stop`, { method: 'POST',
2376
+ body: JSON.stringify({ owner: stop.owner, expectTurnId: stop.turnId || undefined }) });
2377
+ } else if (stop.kind === 'wait') {
2378
+ await request(`/api/requests/${encodeURIComponent(stop.requestId)}/run/stop`, { method: 'POST', body: JSON.stringify({ waitId: stop.waitId }) });
2379
+ } else {
2380
+ await request(`/api/requests/${encodeURIComponent(stop.requestId)}/run/stop`, { method: 'POST', body: JSON.stringify(stop.leaseId ? { expectLeaseId: stop.leaseId } : {}) });
2381
+ }
2382
+ } catch (error) {
2383
+ 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; }
2384
+ stopped = false;
2385
+ }
2386
+ const again = await lifecycleCall(item.dataset.requestId, 'dismiss').catch(() => null);
2387
+ if (again?.ok) {
2388
+ ask.remove();
2389
+ state.requestCards.set(item.dataset.requestId, { id: item.dataset.requestId, found: true, lifecycle: { state: 'dismissed' }, attention: { state: 'not-now', code: 'dismissed', label: 'Dismissed' } });
2390
+ paintRequestCard(item);
2391
+ item.querySelector('.ai-chat-request-undo')?.focus();
2392
+ } else {
2393
+ // A stop that went through is said, so the person does not think the AI is still working; a stale one is not claimed.
2394
+ why.textContent = again?.body?.code === 'request-held'
2395
+ ? (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.')
2396
+ : `${stopped ? 'The work was stopped, but the request' : 'The request'} couldn’t be set aside. It is still in Requests; try again.`;
2397
+ go.disabled = false; keep.disabled = false;
2398
+ }
2399
+ });
2400
+ row.append(go);
2401
+ }
2402
+ ask.append(why, row);
2403
+ item.append(ask);
2404
+ keep.focus();
2405
+ }
2406
+
2407
+ async function restoreRequestFromCard(item) {
2408
+ const requestId = item.dataset.requestId;
2409
+ const undo = item.querySelector('.ai-chat-request-undo');
2410
+ if (undo) undo.disabled = true;
2411
+ item.querySelector('.ai-chat-request-note')?.remove();
2412
+ try {
2413
+ const done = await lifecycleCall(requestId, 'restore');
2414
+ 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; }
2415
+ rememberHiddenRequestCard(item.dataset.cardEventId, false);
2416
+ await refreshRequestCards({ force: true });
2417
+ } catch {
2418
+ cardNotice(item, 'FloLess couldn’t reach the server, so the request was not put back. Try Undo again in a moment.');
2419
+ } finally { if (undo) undo.disabled = false; }
2420
+ }
2421
+
2209
2422
  // #1907: the plain name of one of the person's connectors — the same rule the server words its cards with.
2210
2423
  function connectorLabel(connector) {
2211
2424
  // A Claude.ai connector is named "claude.ai <Name>"; the prefix names the channel, not the connector.
@@ -2223,7 +2436,7 @@
2223
2436
  item.dataset.eventSequence = String(event.sequence);
2224
2437
  item.dataset.eventId = event.eventId;
2225
2438
  const label = document.createElement('strong');
2226
- label.textContent = 'Allowed for this chat';
2439
+ label.textContent = autoReceiptLabel(event);
2227
2440
  const connector = event.payload.connector;
2228
2441
  const tool = typeof connector.tool === 'string' ? connector.tool : 'a tool';
2229
2442
  item.append(label, document.createTextNode(` · ${connectorLabel(connector)} ran ${tool}`));
@@ -2260,6 +2473,27 @@
2260
2473
  return item;
2261
2474
  }
2262
2475
 
2476
+ /** The receipt label of an action a grant approved without a card: which grant (this reply, or this conversation). */
2477
+ function autoReceiptLabel(event) {
2478
+ return event.payload?.scope === 'request' ? 'Allowed for this request' : 'Allowed for this conversation';
2479
+ }
2480
+
2481
+ /** Epic #2185 Slice A: every other action a grant approved automatically leaves one line saying what covered it. */
2482
+ function renderAutoReceipt(event) {
2483
+ const item = document.createElement('div');
2484
+ item.className = 'ai-chat-event connector';
2485
+ item.dataset.eventSequence = String(event.sequence);
2486
+ item.dataset.eventId = event.eventId;
2487
+ const label = document.createElement('strong');
2488
+ label.textContent = autoReceiptLabel(event);
2489
+ const payload = event.payload || {};
2490
+ const what = payload.scopeAdd ? `Added ${payload.scopeAdd.target?.kind || 'project'} “${payload.scopeAdd.label}” to this chat`
2491
+ : payload.create ? `Created the workflow “${payload.create.name}”`
2492
+ : String(payload.summary || payload.grantLabel || 'An action').slice(0, 200);
2493
+ item.append(label, document.createTextNode(` · ${what}${payload.grantLabel && !payload.scopeAdd && !payload.create ? ` (${payload.grantLabel})` : ''}`));
2494
+ return item;
2495
+ }
2496
+
2263
2497
  function renderChangeReceipt(event) {
2264
2498
  const item = document.createElement('div');
2265
2499
  item.className = 'ai-chat-event connector';
@@ -2272,7 +2506,7 @@
2272
2506
  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
2507
  return item;
2274
2508
  }
2275
- label.textContent = event.payload.coveredBy === 'create' ? 'Part of creating the workflow' : 'Allowed for this chat';
2509
+ label.textContent = event.payload.coveredBy === 'create' ? 'Part of creating the workflow' : autoReceiptLabel(event);
2276
2510
  // The receipt records the approval FloLess gave; whether the file was then written is the AI's own reply to report.
2277
2511
  const owners = Array.isArray(change?.owners) ? change.owners : [];
2278
2512
  const paths = owners.flatMap((owner) => owner.paths || []);
@@ -2291,19 +2525,27 @@
2291
2525
  */
2292
2526
  const connectionCards = new Map();
2293
2527
  const CONNECTION_CARDS_KEPT = 200;
2294
- const connectionLive = { services: null, loading: false, loadedAt: 0, error: '' };
2528
+ const connectionLive = { services: null, loading: false, loadedAt: 0, error: '', again: false };
2295
2529
  const connectionsApi = () => window.flolessConnections || null;
2296
2530
 
2297
- /** Re-reads what is connected (and the latest checks) when the copy on screen is older than `maxAgeMs`. */
2298
- function refreshConnectionLive(maxAgeMs = 15000) {
2531
+ /**
2532
+ * Re-reads what is connected (and the latest checks) when the copy on screen is older than `maxAgeMs`.
2533
+ * `force` (#2185: the server said a connection, credential, install or account choice just changed) cannot be skipped
2534
+ * because a read is already running: that read may have started before the change, so one more runs right after it.
2535
+ */
2536
+ function refreshConnectionLive(maxAgeMs = 15000, force = false) {
2299
2537
  const api = connectionsApi();
2300
- if (!api || connectionLive.loading) return;
2301
- if (connectionLive.loadedAt && Date.now() - connectionLive.loadedAt < maxAgeMs) return;
2538
+ if (!api) return;
2539
+ if (connectionLive.loading) { if (force) connectionLive.again = true; return; }
2540
+ if (!force && connectionLive.loadedAt && Date.now() - connectionLive.loadedAt < maxAgeMs) return;
2302
2541
  connectionLive.loading = true;
2303
2542
  Promise.all([api.loadServices(), api.loadReceipts()])
2304
2543
  .then(([services]) => { connectionLive.services = services; connectionLive.error = ''; })
2305
2544
  .catch((error) => { connectionLive.error = api.sentenceOf(error); })
2306
- .finally(() => { connectionLive.loading = false; connectionLive.loadedAt = Date.now(); repaintConnectionCards(); });
2545
+ .finally(() => {
2546
+ connectionLive.loading = false; connectionLive.loadedAt = Date.now(); repaintConnectionCards();
2547
+ if (connectionLive.again) { connectionLive.again = false; refreshConnectionLive(0, true); }
2548
+ });
2307
2549
  }
2308
2550
 
2309
2551
  function repaintConnectionCards() {
@@ -2314,12 +2556,20 @@
2314
2556
  if (next !== old) {
2315
2557
  const focused = old.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
2316
2558
  old.replaceWith(next);
2317
- if (focused) [...next.querySelectorAll('[data-command-id]')].find((node) => node.dataset.commandId === focused && !node.disabled)?.focus({ preventScroll: true });
2559
+ if (focused) {
2560
+ const same = [...next.querySelectorAll('[data-command-id]')].find((node) => node.dataset.commandId === focused && !node.disabled);
2561
+ // The control under the keyboard is gone (a card that finished loses its Not now): keep the keyboard on the card.
2562
+ if (same) same.focus({ preventScroll: true });
2563
+ else { next.tabIndex = -1; next.focus({ preventScroll: true }); }
2564
+ }
2318
2565
  }
2319
2566
  }
2320
2567
  }
2321
2568
 
2322
2569
  window.addEventListener('focus', () => { if (ui.feed?.querySelector('.ai-chat-connection-card[data-proposal-id]')) refreshConnectionLive(0); });
2570
+ // #2185: Integrations is a modal, so coming back from it never refocuses the window. The server says when something
2571
+ // was connected, a credential changed or an account was chosen, and the cards tick themselves off.
2572
+ window.addEventListener('floless:connections-changed', () => { if (ui.feed?.querySelector('.ai-chat-connection-card[data-proposal-id]')) refreshConnectionLive(0, true); });
2323
2573
 
2324
2574
  /**
2325
2575
  * Did the person answer Not now to this target? Dismissal is per target. The newest Not now / Show again in the
@@ -2445,6 +2695,7 @@
2445
2695
  };
2446
2696
  const services = connectionLive.services;
2447
2697
  let keyCode = null;
2698
+ let connected = false;
2448
2699
  if (payload.targetKind === 'host') {
2449
2700
  if (payload.checkAgent && api) {
2450
2701
  actions.append(check(null, {}));
@@ -2523,6 +2774,15 @@
2523
2774
  stateLine.textContent = `FloLess couldn’t read which account it uses for ${name}. Open Integrations to choose it again.`;
2524
2775
  actions.append(integrations('Open Integrations', 'shell.chat-connection-change-account', `Opens Integrations at ${name}.`, true));
2525
2776
  } else if (service.choice?.source === 'floless') {
2777
+ // #2185: connected and an account chosen is the finished state: say what was connected, to which account, and stop asking.
2778
+ connected = true;
2779
+ const accountLabel = service.choice.alias ? service.choice.alias : 'main account';
2780
+ card.classList.add('is-connected');
2781
+ const tick = document.createElement('span'); tick.setAttribute('aria-hidden', 'true'); tick.textContent = '✓ ';
2782
+ title.replaceChildren(tick, document.createTextNode(`${name} connected · ${accountLabel}`));
2783
+ // 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).
2784
+ if (entry.seenOpen && !entry.announcedConnected) announce(`${name} connected, using ${accountLabel}.`);
2785
+ entry.announcedConnected = true;
2526
2786
  stateLine.textContent = `FloLess uses ${service.choice.alias ? service.choice.alias : 'the default account'} for ${name}.`;
2527
2787
  // The card checks the CHOSEN account at the choice it was painted on: the server refuses a card that is out of date.
2528
2788
  if (payload.checkAgent && alias !== undefined) {
@@ -2542,7 +2802,8 @@
2542
2802
  notNow.dataset.tip = `Sets this suggestion aside. The AI won’t suggest ${name} again in this chat unless you choose Show again.`;
2543
2803
  notNow.disabled = entry.busy;
2544
2804
  notNow.addEventListener('click', () => { void setConnectionDismissed(event, true); });
2545
- actions.append(notNow);
2805
+ // Nothing is left to set aside once it is connected (#2185); Change account is still there.
2806
+ if (!connected) { actions.append(notNow); entry.seenOpen = true; }
2546
2807
  card.append(stateLine, ...(keyCode ? [keyCode] : []), actions, confirmHost, receiptHost, said, error);
2547
2808
  return card;
2548
2809
  }
@@ -2634,7 +2895,7 @@
2634
2895
  item.dataset.eventSequence = String(event.sequence);
2635
2896
  item.dataset.eventId = event.eventId;
2636
2897
  const label = document.createElement('strong');
2637
- label.textContent = 'Allowed for this chat';
2898
+ label.textContent = autoReceiptLabel(event);
2638
2899
  const name = String(event.payload.connectionCheck?.name || event.payload.connectionCheck?.agent || 'a connection');
2639
2900
  item.append(label, document.createTextNode(` · checked ${name}`));
2640
2901
  return item;
@@ -2675,6 +2936,8 @@
2675
2936
  if (event.type === 'connection-check') return renderConnectionCheck(event);
2676
2937
  // #2046: a next move the Guide suggested; web/guide.js paints it and owns its button.
2677
2938
  if (event.type === 'next-move') return window.flolessGuide?.renderNextMove?.(event) || null;
2939
+ // #2185: what came of a card's button repaints that card; it is never a line of its own.
2940
+ if (event.type === 'next-move-update') { window.flolessGuide?.applyMoveUpdate?.(event); return null; }
2678
2941
  if (event.type === 'approval-decided' && event.payload?.automatic === true && event.payload?.connectionCheck) return renderConnectionCheckAllowed(event);
2679
2942
  if (event.type === 'assistant-message') return renderMessage(event, 'assistant', payloadText(event), Boolean(event.payload?.delta));
2680
2943
  // #1907: a connector call that ran under "Allow for this chat" leaves a visible receipt; every other decision is audit only.
@@ -2682,7 +2945,10 @@
2682
2945
  // #1890 PR 2b: a workspace change that ran under "Allow for this chat", or one FloLess stopped at the last check.
2683
2946
  if (event.type === 'approval-decided' && event.payload?.change && (event.payload?.automatic === true || event.payload?.reason)) return renderChangeReceipt(event);
2684
2947
  // #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);
2948
+ if (event.type === 'approval-decided' && event.payload?.create && !(event.payload?.automatic === true && event.payload?.decision === 'allow')) return renderCreateReceipt(event);
2949
+ // A Tekla read already leaves its own result card, so it gets no second line here.
2950
+ if (event.type === 'approval-decided' && event.payload?.automatic === true && !event.payload?.unattended && event.payload?.decision === 'allow'
2951
+ && !String(event.payload?.tool || '').startsWith('floless_tekla_')) return renderAutoReceipt(event);
2686
2952
  if (event.type === 'approval-requested' || event.type === 'approval-decided' || event.type === 'state' || event.type === 'followup-status') return null;
2687
2953
  if (event.type === 'tool' && ['agent', 'guide', 'instructor'].includes(event.payload?.tool) && typeof event.payload?.message === 'string') return renderAgentRunLine(event);
2688
2954
  if (event.type === 'tekla-read') return renderTeklaReadEvent(event);
@@ -4754,6 +5020,7 @@
4754
5020
  if (event.type === 'connection-proposal' || event.type === 'connection-check') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
4755
5021
  // #2046: the Guide's next-move cards are held under the answer they were suggested in, like the cards above.
4756
5022
  if (event.type === 'next-move') { const node = renderEvent(event); if (node) links.push({ turnId: event.turnId, node }); continue; }
5023
+ if (event.type === 'next-move-update') { renderEvent(event); continue; }
4757
5024
  if (['tool', 'usage', 'knowledge-citation', 'attachment', 'compaction', 'state'].includes(event.type)) continue;
4758
5025
  // FloLess's own receipts (object links #1653; evidence looks and suggestion cards #1859) are written mid-answer while a tool runs:
4759
5026
  // held and shown under the answer, so they never cut one answer into fragments.
@@ -4880,19 +5147,17 @@
4880
5147
  shell.dataset.approvalPending = String(Boolean(approval) && !deciding);
4881
5148
  document.dispatchEvent(new CustomEvent('floless:chat-indicator'));
4882
5149
  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.
5150
+ // Keep the same buttons during polling so keyboard focus and pointer clicks survive. A card also carries the
5151
+ // permission views its wider choices are offered on (epic #2185 Slice A), so a change to any of them repaints it.
4885
5152
  const teklaBinding = teklaAllowableApproval(approval) ? currentTeklaBinding(state.chat) : null;
4886
5153
  // #1890 PR 2b: a workspace conversation's file change, with the projects/workflows it touches.
4887
5154
  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.
5155
+ // #1907: a call to one of the person's connectors.
5156
+ const connector = approval.connector && typeof approval.connector === 'object' ? approval.connector : null;
5157
+ // #1900: a connection check the AI asked for.
4891
5158
  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) : '';
5159
+ const offer = approvalOffer(approval);
5160
+ const allowanceRevision = offer ? offerStamp(offer) : '';
4896
5161
  if (existing?.dataset.approvalId === approval.approvalId && (existing.dataset.allowanceRevision || '') === allowanceRevision) return;
4897
5162
  // A permission change repaints the same approval: keep keyboard focus on the same control.
4898
5163
  const refocus = existing?.dataset.approvalId === approval.approvalId && existing.contains(document.activeElement)
@@ -4906,7 +5171,7 @@
4906
5171
  card.classList.add('has-flo'); card.append(flo);
4907
5172
  floAvatar(flo, { size: 28, mood: 'yourcall', hat: true });
4908
5173
  }
4909
- if (teklaBinding || connector || change || connectionCheck) card.dataset.allowanceRevision = allowanceRevision;
5174
+ card.dataset.allowanceRevision = allowanceRevision;
4910
5175
  // #1890 PR 3a: the AI asking to create a workflow, with where it would go.
4911
5176
  const create = approval.create && typeof approval.create === 'object' ? approval.create : null;
4912
5177
  if (approval.scopeAdd) {
@@ -4930,21 +5195,21 @@
4930
5195
  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
5196
  deny.addEventListener('click', () => decideApproval('deny'));
4932
5197
  allow.addEventListener('click', () => decideApproval('allow'));
4933
- actions.append(deny, allow); card.append(heading, copy, actions);
5198
+ actions.append(deny, allow); card.append(heading, copy, actions, ...widerChoices(approval, offer));
4934
5199
  ui.approvalTray.append(card);
4935
5200
  if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
4936
5201
  ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
4937
5202
  return;
4938
5203
  }
4939
5204
  if (create) {
4940
- paintCreateCard(card, approval, create);
5205
+ paintCreateCard(card, approval, create, offer);
4941
5206
  ui.approvalTray.append(card);
4942
5207
  if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
4943
5208
  ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
4944
5209
  return;
4945
5210
  }
4946
5211
  if (change) {
4947
- paintChangeCard(card, approval, change, Number(allowanceRevision));
5212
+ paintChangeCard(card, approval, change, offer);
4948
5213
  ui.approvalTray.append(card);
4949
5214
  if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
4950
5215
  ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
@@ -4955,43 +5220,20 @@
4955
5220
  const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
4956
5221
  const deny = button('Deny', 'shell.chat-approval-deny');
4957
5222
  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
5223
  deny.addEventListener('click', () => decideApproval('deny'));
4969
5224
  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));
5225
+ if (connectionCheck) {
5226
+ paintConnectionCheckApproval(card, approval, connectionCheck, { heading, copy, actions, deny, allow }, offer);
4988
5227
  ui.approvalTray.append(card);
4989
5228
  if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
4990
5229
  // A new question: Deny is the safe default, unless the person is typing a message.
4991
5230
  else if (existing?.dataset.approvalId !== approval.approvalId && !(document.activeElement === ui.input && ui.input.value)) deny.focus({ preventScroll: true });
4992
5231
  ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
4993
5232
  return;
4994
- } else if (connector) {
5233
+ }
5234
+ actions.append(deny, allow);
5235
+ const nodes = [heading, copy];
5236
+ if (connector) {
4995
5237
  card.dataset.explicitOnly = 'true';
4996
5238
  // The warning is the part that decides it: on its own line, not at the end of the question.
4997
5239
  const split = approval.summary.indexOf(' FloLess cannot check');
@@ -5001,33 +5243,24 @@
5001
5243
  copy.textContent = approval.summary.slice(0, split);
5002
5244
  warning.textContent = approval.summary.slice(split + 1);
5003
5245
  }
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
- }
5246
+ if (warning.textContent) nodes.push(warning);
5247
+ } else if (offer && offer.kind !== 'tool') card.dataset.explicitOnly = 'true';
5248
+ // #2196: a command naming a workflow's protected files arrives flagged, as "<one-line reason>\nCommand: <command>"
5249
+ // (the server keeps the reason to one line, so the first marker is the separator). The command goes in its own
5250
+ // block, exactly as it will run (spacing kept, long tokens wrapped, a long one scrolls). Nothing else is split.
5251
+ const commandAt = approval.protectedCommand === true && !connector ? approval.summary.indexOf('\nCommand: ') : -1;
5252
+ if (commandAt >= 0) {
5253
+ copy.textContent = approval.summary.slice(0, commandAt);
5254
+ const block = document.createElement('pre');
5255
+ block.className = 'ai-chat-approval-cmd';
5256
+ block.tabIndex = 0;
5257
+ block.setAttribute('aria-label', 'Command that will run');
5258
+ const code = document.createElement('code');
5259
+ code.textContent = approval.summary.slice(commandAt + '\nCommand: '.length);
5260
+ block.append(code);
5261
+ nodes.push(block);
5262
+ }
5263
+ card.append(...nodes, actions, ...widerChoices(approval, offer));
5031
5264
  ui.approvalTray.append(card);
5032
5265
  if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
5033
5266
  // When a request-wide grant notice is also present, keep the decision nearest the composer.
@@ -5037,12 +5270,12 @@
5037
5270
  /**
5038
5271
  * #1900 — the card for a connection check the AI asked for. The server's summary is the whole question; the two
5039
5272
  * 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).
5273
+ * lines. Like every card it offers the full set (epic #2185 Slice A); the conversation choice is the older allowance when
5274
+ * the server says that is safe (reviewed, no custom key, an identified account, a pinned tool), else exactly this plan.
5042
5275
  */
5043
5276
  const CONNECTION_UNREVIEWED_SENTENCE = 'This check comes from a tool FloLess has not reviewed.';
5044
5277
 
5045
- function paintConnectionCheckApproval(card, approval, check, parts, allowanceRevision) {
5278
+ function paintConnectionCheckApproval(card, approval, check, parts, offer) {
5046
5279
  const { heading, copy, actions, deny, allow } = parts;
5047
5280
  card.dataset.explicitOnly = 'true';
5048
5281
  card.classList.add('ai-chat-connection-approval');
@@ -5073,22 +5306,7 @@
5073
5306
  }
5074
5307
  // Deny and Approve once already answer through paintApproval's own listeners.
5075
5308
  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
- }
5309
+ const nodes = [heading, copy, ...extra, actions, ...widerChoices(approval, offer)];
5092
5310
  card.append(...nodes);
5093
5311
  }
5094
5312
 
@@ -5114,7 +5332,7 @@
5114
5332
  }
5115
5333
 
5116
5334
  /** 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) {
5335
+ function paintChangeCard(card, approval, change, offer) {
5118
5336
  card.dataset.explicitOnly = 'true';
5119
5337
  card.classList.add('ai-chat-change');
5120
5338
  card.setAttribute('role', 'group');
@@ -5153,23 +5371,7 @@
5153
5371
  deny.addEventListener('click', () => decideApproval('deny'));
5154
5372
  allow.addEventListener('click', () => decideApproval('allow'));
5155
5373
  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);
5374
+ card.append(heading, copy, ...(change.owners?.length ? [changeOwnerList(change)] : []), actions, ...widerChoices(approval, offer));
5173
5375
  }
5174
5376
 
5175
5377
  /** 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 +5384,8 @@
5182
5384
  return create.destination?.kind === 'project' ? `in project ${create.destination.label}` : 'on its own, outside any project';
5183
5385
  }
5184
5386
 
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) {
5387
+ /** The card for the AI asking to create a workflow: what and where, then Deny / Create workflow, then the wider choices. */
5388
+ function paintCreateCard(card, approval, create, offer) {
5187
5389
  card.dataset.explicitOnly = 'true';
5188
5390
  card.classList.add('ai-chat-change', 'ai-chat-create');
5189
5391
  card.setAttribute('role', 'group');
@@ -5241,7 +5443,7 @@
5241
5443
  deny.addEventListener('click', () => decideApproval('deny'));
5242
5444
  allow.addEventListener('click', () => decideApproval('allow'));
5243
5445
  actions.append(deny, allow);
5244
- card.append(heading, copy, list, actions);
5446
+ card.append(heading, copy, list, actions, ...widerChoices(approval, offer));
5245
5447
  }
5246
5448
 
5247
5449
  /** Each project or workflow the change touches, with up to five of its files. */
@@ -5281,6 +5483,136 @@
5281
5483
  return list;
5282
5484
  }
5283
5485
 
5486
+ /*
5487
+ * Epic #2185 Slice A (owner ruling 7): EVERY approval card offers Deny, Approve once, Approve for this request and
5488
+ * Approve for this conversation. `approvalOffer` says, for the card on screen, exactly WHAT each wider choice covers (the
5489
+ * same fingerprint rules as server/chat-approval-grants.ts, worded for a person), where the conversation grant is kept
5490
+ * (so the right revision travels with the click) and which instructor command the button is. The server stays the
5491
+ * authority: it recomputes the fingerprint and refuses a click decided on an older view.
5492
+ */
5493
+ function approvalOffer(approval) {
5494
+ const chat = state.chat;
5495
+ if (!approval || !chat) return null;
5496
+ const requestRevision = chat.activeTurn?.requestGrantRevision ?? 0;
5497
+ const change = approval.change && typeof approval.change === 'object' ? approval.change : null;
5498
+ const create = approval.create && typeof approval.create === 'object' ? approval.create : null;
5499
+ const check = approval.connectionCheck && typeof approval.connectionCheck === 'object' ? approval.connectionCheck : null;
5500
+ const connector = approval.connector && typeof approval.connector === 'object' ? approval.connector : null;
5501
+ const base = { requestRevision, decision: 'allow-chat', warning: '' };
5502
+ const PROTECTED_NOTE = ' A workflow’s own records (its .lock, settings and conversations) always ask.';
5503
+ if (change) {
5504
+ if (change.refused || change.busy) return null;
5505
+ if (!change.owners?.length) {
5506
+ // Only the AI's own folder: no project or workflow to name, still a file change with its own fingerprint.
5507
+ if (!change.scratchPaths?.length) return null;
5508
+ return { ...base, kind: 'change', key: 'change:scratch', revision: chat.approvalGrants?.revision ?? 0,
5509
+ 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' };
5510
+ }
5511
+ return { ...base, kind: 'change', key: 'change', revision: chat.changeAllowance?.revision ?? 0,
5512
+ what: 'File changes in this chat’s folders', conversationExtra: ', including folders you add later', protectedNote: PROTECTED_NOTE,
5513
+ commandId: `shell.chat-change-allow-chat#${change.owners.map((owner) => owner.key).join('+')}`, instance: changeNames(change) };
5514
+ }
5515
+ if (create) {
5516
+ if (create.refused || create.busy) return null;
5517
+ const inProject = create.destination?.kind === 'project';
5518
+ return { ...base, kind: 'create', key: inProject ? 'create:project' : 'create:standalone', revision: chat.approvalGrants?.revision ?? 0,
5519
+ what: inProject ? 'Creating workflows in a project, and drafting inside them' : 'Creating standalone workflows, and drafting inside them',
5520
+ commandId: 'shell.chat-approval-grant-chat', instance: inProject ? create.destination.label : 'standalone workflows' };
5521
+ }
5522
+ if (approval.scopeAdd) {
5523
+ const write = Boolean(approval.scopeAdd.allowsFileChanges || chat.changeAllowance?.allowedForChat
5524
+ || (chat.activeTurn?.requestGrants || []).some((grant) => grant.key === 'change'));
5525
+ return { ...base, kind: write ? 'scope-write' : 'scope-read', key: write ? 'scope:write' : 'scope:read', revision: chat.approvalGrants?.revision ?? 0,
5526
+ 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',
5527
+ commandId: 'shell.chat-approval-grant-chat', instance: 'adding scope' };
5528
+ }
5529
+ if (connector) {
5530
+ const who = connectorLabel(connector);
5531
+ if (connector.verified) {
5532
+ return { ...base, kind: 'connector', key: `connector:${connectorKey(connector)}`, revision: chat.connectorAllowance?.revision ?? 0,
5533
+ what: `Calls to ${who}`, commandId: `shell.chat-connector-allow-chat#${connectorKey(connector)}`, instance: who };
5534
+ }
5535
+ return { ...base, kind: 'connector-unverified', key: 'connector:unverified', revision: chat.approvalGrants?.revision ?? 0,
5536
+ what: 'Any connector call FloLess cannot identify', commandId: 'shell.chat-approval-grant-chat', instance: 'unidentified connector calls',
5537
+ warning: 'FloLess cannot tell which connector this is, so this covers every call it cannot identify, not just this one.' };
5538
+ }
5539
+ if (check) {
5540
+ const name = String(check.name || check.agent || 'this tool');
5541
+ const allowable = check.chatAllowable === true && check.reviewed && !check.sendsCustomKey && (check.kind === 'host' || Boolean(check.lastStableId));
5542
+ const route = check.kind === 'account' && !check.lastStableId ? ' through this key (the account could not be identified)' : '';
5543
+ const key = `${check.agent}${check.alias ? `.${check.alias}` : ''}`;
5544
+ return allowable
5545
+ ? { ...base, kind: 'check', key: `check:${key}`, revision: chat.integrationReadAllowance?.revision ?? 0,
5546
+ what: `Exactly this check of ${name}`, conversationWhat: `Checks of ${name}${check.kind === 'host' ? '' : ' with this account'}`,
5547
+ commandId: `shell.chat-connection-check-allow-chat#${key}`, instance: name }
5548
+ : { ...base, kind: 'check', key: `check:${key}:exact`, revision: chat.approvalGrants?.revision ?? 0,
5549
+ what: `Exactly this check of ${name}${route}`, commandId: 'shell.chat-approval-grant-chat', instance: name };
5550
+ }
5551
+ if (!approvalIsExplicitOnly(approval)) {
5552
+ return { ...base, kind: 'tool', key: 'tool', decision: 'allow-session', revision: chat.sessionApprovalRevision ?? 0,
5553
+ what: 'All access actions', conversationExtra: '. Review checkpoints still ask every time', commandId: 'shell.chat-approval-session', instance: '' };
5554
+ }
5555
+ const binding = teklaAllowableApproval(approval) ? currentTeklaBinding(chat) : null;
5556
+ if (binding) {
5557
+ return { ...base, kind: 'tekla', key: 'tekla', revision: teklaAllowanceRevision(binding),
5558
+ what: `The Tekla reads this chat is set up for (${teklaReadsCopy(binding.operations, ' and ')})`, commandId: 'shell.chat-tekla-allow-chat', instance: '' };
5559
+ }
5560
+ const words = String(approval.summary || '').replace(/\s+/g, ' ').trim();
5561
+ return { ...base, kind: 'other', key: `other:${approval.tool || ''}`, revision: chat.approvalGrants?.revision ?? 0,
5562
+ what: `This exact request: “${words.length > 80 ? `${words.slice(0, 79)}…` : words}”`, commandId: 'shell.chat-approval-grant-chat', instance: approval.tool || 'this request' };
5563
+ }
5564
+
5565
+ /** What makes a painted card out of date: its kind, the views its wider choices decide on, and their wording. */
5566
+ function offerStamp(offer) {
5567
+ return [offer.kind, offer.key, offer.revision, offer.requestRevision, offer.decision, offer.what].join('|');
5568
+ }
5569
+
5570
+ /**
5571
+ * The two wider choices, each as one row: the button and, beside or under it, a line that says exactly what it covers.
5572
+ * The line is visible text (not a tooltip alone), and the button is described by it. Returns [] when the card can only
5573
+ * be denied.
5574
+ */
5575
+ function widerChoices(approval, offer) {
5576
+ if (!offer) return [];
5577
+ const group = document.createElement('div');
5578
+ group.className = 'ai-chat-approval-wide';
5579
+ group.setAttribute('role', 'group');
5580
+ const caption = document.createElement('span');
5581
+ caption.className = 'ai-chat-approval-wide-caption';
5582
+ caption.id = `chat-approval-wide-caption-${approval.approvalId}`;
5583
+ caption.textContent = 'Or allow more than this one action';
5584
+ group.setAttribute('aria-labelledby', caption.id);
5585
+ group.append(caption);
5586
+ const rows = [
5587
+ { which: 'request', label: 'Approve for this request', decision: 'allow-request', revision: offer.requestRevision, commandId: 'shell.chat-approval-request',
5588
+ text: `${offer.what}, until this reply ends.` },
5589
+ { which: 'conversation', label: 'Approve for this conversation', decision: offer.decision, revision: offer.revision, commandId: offer.commandId,
5590
+ text: `${offer.conversationWhat || offer.what}${offer.conversationExtra || ''}, for the rest of this conversation, until you revoke it above the message box.` },
5591
+ ];
5592
+ for (const row of rows) {
5593
+ const line = document.createElement('div');
5594
+ line.className = 'ai-chat-approval-wide-row';
5595
+ const choice = button(row.label, row.commandId);
5596
+ if (offer.instance && row.which === 'conversation') choice.dataset.commandInstanceLabel = offer.instance;
5597
+ const covers = document.createElement('span');
5598
+ covers.className = 'ai-chat-approval-covers';
5599
+ covers.id = `chat-approval-covers-${row.which}-${approval.approvalId}`;
5600
+ covers.textContent = `${row.text}${offer.protectedNote || ''}`;
5601
+ choice.dataset.tip = covers.textContent;
5602
+ choice.setAttribute('aria-describedby', covers.id);
5603
+ choice.addEventListener('click', () => decideApproval(row.decision, row.revision));
5604
+ line.append(choice, covers);
5605
+ group.append(line);
5606
+ }
5607
+ if (offer.warning) {
5608
+ const warning = document.createElement('p');
5609
+ warning.className = 'ai-chat-approval-warning';
5610
+ warning.textContent = offer.warning;
5611
+ group.append(warning);
5612
+ }
5613
+ return [group];
5614
+ }
5615
+
5284
5616
  function approvalIsExplicitOnly(approval) {
5285
5617
  if (!approval) return false;
5286
5618
  if (approval.explicitOnly === true) return true;
@@ -5314,7 +5646,7 @@
5314
5646
  const explanation = document.createElement('span');
5315
5647
  explanation.className = 'sr-only';
5316
5648
  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.';
5649
+ 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
5650
  const revoke = button('Revoke', 'shell.chat-approval-revoke');
5319
5651
  revoke.dataset.tip = explanation.textContent;
5320
5652
  revoke.setAttribute('aria-describedby', explanation.id);
@@ -5343,7 +5675,7 @@
5343
5675
  const explanation = document.createElement('span');
5344
5676
  explanation.className = 'sr-only';
5345
5677
  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.';
5678
+ 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
5679
  const revoke = button('Revoke', 'shell.chat-session-revoke');
5348
5680
  revoke.dataset.tip = explanation.textContent;
5349
5681
  revoke.setAttribute('aria-describedby', explanation.id);
@@ -5651,6 +5983,7 @@
5651
5983
  chip.append(name, remove); ui.attachments.append(chip);
5652
5984
  }
5653
5985
  ui.attachments.hidden = state.attachments.length === 0 && !pill;
5986
+ placeSkills();
5654
5987
  }
5655
5988
 
5656
5989
  function selectedModel() {
@@ -5931,6 +6264,7 @@
5931
6264
  paintConnectorAllowance();
5932
6265
  paintChangeAllowance();
5933
6266
  paintCheckAllowance();
6267
+ paintApprovalGrants();
5934
6268
  const chat = state.chat;
5935
6269
  if (!chat) { providerChooser(); paintHistory(); return; }
5936
6270
  ui.historyToggle.disabled = false;
@@ -7175,8 +7509,29 @@
7175
7509
  ui.skills.append(row);
7176
7510
  }
7177
7511
  ui.skills.hidden = false;
7512
+ placeSkills();
7178
7513
  }
7179
7514
 
7515
+ // #2185: the open / list sits 4px above what is about to be sent (the attachments, right above the message box, or the
7516
+ // 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
7517
+ // clip its first options. chat.css keeps a fixed bottom and height only as the fallback before layout.
7518
+ function placeSkills() {
7519
+ const host = ui.skills.offsetParent;
7520
+ if (ui.skills.hidden || !host) return;
7521
+ const shell = host.getBoundingClientRect();
7522
+ const top = (ui.attachments.hidden ? ui.input : ui.attachments).getBoundingClientRect().top;
7523
+ ui.skills.style.bottom = `${Math.max(0, Math.round(shell.bottom - top + 4))}px`;
7524
+ ui.skills.style.maxHeight = `${Math.max(0, Math.round(Math.min(260, window.innerHeight * 0.4, top - shell.top - 8)))}px`;
7525
+ }
7526
+ // While the list is open, anything that moves its anchor moves the list: the composer (the chips, the box and the hint
7527
+ // or disclosure under it all live inside it) and the shell (the pane's own size).
7528
+ function watchSkillsPlacement() {
7529
+ if (typeof ResizeObserver !== 'function') return;
7530
+ const watch = new ResizeObserver(() => placeSkills());
7531
+ for (const node of [ui.composer, ui.skills.parentElement]) if (node) watch.observe(node);
7532
+ }
7533
+ watchSkillsPlacement();
7534
+
7180
7535
  // ── Drawing Filter context and suggestions ─────────────────────────────────────────────────────
7181
7536
  // ONE AI CHAT (#1859). With the Drawing Filter open, a message is an ordinary turn or follow-up; the
7182
7537
  // open filter only adds a snapshot of the sheet and its selection (`filterContextForSend`), and the AI
@@ -8353,6 +8708,7 @@
8353
8708
  const snapshot = captureChat();
8354
8709
  if (!snapshot) return;
8355
8710
  const approvalId = approval.approvalId;
8711
+ const offer = approvalOffer(approval);
8356
8712
  // The provider stays paused while this request reaches it, but the choice is already made.
8357
8713
  // Suppress any stale poll/SSE snapshot so the card disappears on the click itself instead of
8358
8714
  // looking like a frozen control until the provider acknowledges the decision.
@@ -8363,7 +8719,7 @@
8363
8719
  try {
8364
8720
  const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/approvals/${encodeURIComponent(approvalId)}`, {
8365
8721
  method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, decision,
8366
- ...(decision === 'allow-chat' ? { allowanceRevision } : {}) }),
8722
+ ...(allowanceRevision !== undefined ? { allowanceRevision } : {}) }),
8367
8723
  });
8368
8724
  if (!sameChat(snapshot)) return;
8369
8725
  // #1890 PR 2b: the server says what it actually did. A change it refused at its last check is announced with the
@@ -8373,12 +8729,9 @@
8373
8729
  announce(refusal ? refusal
8374
8730
  // The request ended before the choice reached the AI (it was stopped or withdrawn): claim nothing about it.
8375
8731
  : outcome?.delivered === false ? 'This request ended before your choice reached the AI.'
8376
- : decision === 'allow-request' ? 'Access auto-approval is on for this request.'
8732
+ : decision === 'allow-request' ? `Allowed until this reply ends: ${offer?.what || 'this kind of request'}.`
8377
8733
  : 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.'
8734
+ : decision === 'allow-chat' ? `Allowed for this conversation: ${offer?.conversationWhat || offer?.what || 'this kind of request'}. Revoke it above the message box.`
8382
8735
  : decision === 'allow' ? 'Approved once.' : 'Action denied.');
8383
8736
  await refreshConversation(snapshot.chatId, false);
8384
8737
  } catch (error) {
@@ -8760,6 +9113,8 @@
8760
9113
 
8761
9114
  function refreshActivity() {
8762
9115
  paintConversation();
9116
+ // Requests changed (or the list just polled): the request cards in the feed read their live state again.
9117
+ void refreshRequestCards({ force: true });
8763
9118
  }
8764
9119
 
8765
9120
  async function refreshIndex() {
@@ -8781,7 +9136,7 @@
8781
9136
 
8782
9137
  // Longer than the server's capability-check bound (CAPABILITY_PROBE_TIMEOUT_MS, 12 s) plus its locks.
8783
9138
  const REQUEST_START_TIMEOUT_MS = 30000;
8784
- async function startRequest(requestId, provider, mode = 'start') {
9139
+ async function startRequest(requestId, provider, mode = 'start', options = {}) {
8785
9140
  if (!state.scope?.owner) throw new Error('Open the Request’s project or workflow before starting its chat.');
8786
9141
  if (provider !== 'claude' && provider !== 'codex') throw new Error('Choose Claude or Codex for this chat.');
8787
9142
  const scope = state.scope;
@@ -8790,7 +9145,9 @@
8790
9145
  if (!sameScope(scope, generation)) {
8791
9146
  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
9147
  }
8793
- const currentChatId = state.chat && state.chat.provider === provider && !state.chat.activeTurn
9148
+ // #2185: "Work on it" starts the request in its OWN conversation. Without `ownChat`, an idle open chat of the same AI is
9149
+ // reused (Discuss), which is how a request used to end up as a card in whatever chat happened to be open.
9150
+ const currentChatId = options?.ownChat !== true && state.chat && state.chat.provider === provider && !state.chat.activeTurn
8794
9151
  && !state.chat.archivedAt && state.chat.state !== 'recovery' ? state.chat.chatId : undefined;
8795
9152
  // Starting a Request waits for the AI's capability check (up to 12 s on the server, longer when
8796
9153
  // it first launches a copy FloLess has only just set up), so a shorter wait here reported
@@ -8798,7 +9155,7 @@
8798
9155
  // "Still opening…" after 4 s, so the longer wait is not a silent one.
8799
9156
  const result = await request(`/api/chat/requests/${encodeURIComponent(requestId)}/start`, {
8800
9157
  method: 'POST', timeoutMs: REQUEST_START_TIMEOUT_MS,
8801
- body: JSON.stringify({ provider, mode, chatId: currentChatId, expectedOwner: scope.owner }),
9158
+ body: JSON.stringify({ provider, mode, chatId: currentChatId, expectedOwner: scope.owner, ...(options?.restoreFirst === true ? { restoreFirst: true } : {}) }),
8802
9159
  });
8803
9160
  if (!sameScope(scope, generation)) {
8804
9161
  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' });
@@ -9216,6 +9573,74 @@
9216
9573
  }
9217
9574
  }
9218
9575
 
9576
+ // Epic #2185 Slice A: what the person allowed for the kinds of request that have no box of their own - for this reply
9577
+ // (kept in the server's memory, gone when the reply ends) and for this conversation - each with its own Revoke. The
9578
+ // older boxes (file changes, connectors, checks, Tekla, the access-action strips) keep painting theirs.
9579
+ function paintApprovalGrants() {
9580
+ const host = ui.grants;
9581
+ if (!host) return;
9582
+ const chat = state.chat;
9583
+ const live = chat && !chat.archivedAt;
9584
+ const turn = live && ['running', 'awaiting-approval'].includes(chat.state) ? chat.activeTurn : null;
9585
+ const request = turn && Array.isArray(turn.requestGrants) ? turn.requestGrants.filter((grant) => grant && grant.key) : [];
9586
+ const conversation = live && Array.isArray(chat.approvalGrants?.grants) ? chat.approvalGrants.grants : [];
9587
+ const painted = `${chat?.chatId || ''}|${turn?.turnId || ''}|${request.map((grant) => grant.key).join(',')}|${conversation.map((grant) => grant.key).join(',')}|${state.grantRevoking || ''}`;
9588
+ if (host.dataset.painted === painted) return;
9589
+ host.dataset.painted = painted;
9590
+ host.replaceChildren();
9591
+ host.hidden = !request.length && !conversation.length;
9592
+ if (host.hidden) return;
9593
+ const rows = [
9594
+ ...request.map((grant) => ({ ...grant, which: 'request', turnId: turn.turnId })),
9595
+ ...conversation.map((grant) => ({ ...grant, which: 'conversation' })),
9596
+ ];
9597
+ const title = document.createElement('span');
9598
+ title.className = 'ai-chat-connectors-title';
9599
+ title.textContent = 'Allowed without asking:';
9600
+ host.append(title);
9601
+ for (const grant of rows) {
9602
+ const id = `${grant.which}:${grant.key}`;
9603
+ const pill = document.createElement('span');
9604
+ pill.className = 'ai-chat-connector-pill';
9605
+ const name = document.createElement('span');
9606
+ name.textContent = `${grant.label} · ${grant.which === 'request' ? 'this reply' : 'this conversation'}`;
9607
+ const revoke = button('Revoke', grant.which === 'request' ? 'shell.chat-request-grant-revoke' : 'shell.chat-approval-grant-revoke', 'ai-chat-connector-revoke');
9608
+ revoke.dataset.commandInstanceLabel = grant.label;
9609
+ revoke.setAttribute('aria-label', `Revoke: ${grant.label}, ${grant.which === 'request' ? 'this reply' : 'this conversation'}`);
9610
+ revoke.dataset.tip = `${grant.label} will ask you again. Something already approved may finish.`;
9611
+ revoke.disabled = state.grantRevoking === id;
9612
+ revoke.addEventListener('click', () => { void revokeApprovalGrant(grant); });
9613
+ pill.append(name, revoke);
9614
+ host.append(pill);
9615
+ }
9616
+ }
9617
+
9618
+ async function revokeApprovalGrant(grant) {
9619
+ const snapshot = captureChat();
9620
+ if (!snapshot) return;
9621
+ const id = `${grant.which}:${grant.key}`;
9622
+ state.grantRevoking = id;
9623
+ paintApprovalGrants();
9624
+ try {
9625
+ await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/${grant.which === 'request' ? 'approval-scope' : 'approval-grants'}/revoke`, {
9626
+ method: 'POST', body: JSON.stringify(grant.which === 'request'
9627
+ ? { owner: snapshot.scope.owner, turnId: grant.turnId, key: grant.key }
9628
+ : { owner: snapshot.scope.owner, key: grant.key }),
9629
+ });
9630
+ if (!sameChat(snapshot)) return;
9631
+ announce(`${grant.label} will ask you again. Something already approved may finish.`);
9632
+ await refreshConversation(snapshot.chatId, false);
9633
+ } catch (error) {
9634
+ if (!sameChat(snapshot)) return;
9635
+ report(error, 'Could not revoke');
9636
+ await refreshConversation(snapshot.chatId, false);
9637
+ } finally {
9638
+ state.grantRevoking = null;
9639
+ if (sameChat(snapshot)) paintApprovalGrants();
9640
+ (ui.grants?.querySelector('.ai-chat-connector-revoke') || ui.input)?.focus();
9641
+ }
9642
+ }
9643
+
9219
9644
  // Legacy per-owner allowances remain removable when no conversation-wide file allowance covers them.
9220
9645
  function paintChangeAllowance() {
9221
9646
  const host = ui.changeAllowance;
@@ -9636,6 +10061,28 @@
9636
10061
  });
9637
10062
  }
9638
10063
 
10064
+ /**
10065
+ * #2185: build a workflow in its own conversation (a Guide card or ≡ New workflow), then land on it: the workflow opens
10066
+ * and its conversation, already working, is the one shown. The same build id always answers the same workflow.
10067
+ */
10068
+ async function startWorkflowBuild(buildId, payload) {
10069
+ await ensureSession();
10070
+ const result = await request(`/api/chat/workflow-builds/${encodeURIComponent(buildId)}/start`, {
10071
+ method: 'POST', timeoutMs: REQUEST_START_TIMEOUT_MS, body: JSON.stringify(payload),
10072
+ });
10073
+ window.flolessBridge?.revealAiChat?.();
10074
+ let opened = false;
10075
+ // No conversation (it was deleted and its Request has left the queue): the workflow itself opens.
10076
+ if (result.chat) {
10077
+ try { opened = await openMovedChat({ owner: { kind: 'workflow', workflowId: result.workflow.workflowId }, chatId: result.chat.chatId }); }
10078
+ catch (error) { console.warn('[chat] built a workflow but could not open its conversation:', error); }
10079
+ }
10080
+ // The AI's first reply is usually a question, so the person's next move is typing in this conversation.
10081
+ if (opened) ui.input.focus();
10082
+ else await window.flolessBridge?.openOwnedWorkflow?.(result.workflow.workflowId);
10083
+ return result;
10084
+ }
10085
+
9639
10086
  async function resumeProjectIntake(submissionId) {
9640
10087
  await ensureSession();
9641
10088
  return request(`/api/chat/project-intakes/${encodeURIComponent(submissionId)}/resume`, {
@@ -9771,7 +10218,7 @@
9771
10218
  });
9772
10219
  window.flolessChat = {
9773
10220
  refreshScope, refreshActivity, refreshIndex, startRequest, openConversation, openConversationIn, openDraft, openVerifiedTeklaDraft,
9774
- startProjectIntake, resumeProjectIntake,
10221
+ startProjectIntake, resumeProjectIntake, startWorkflowBuild,
9775
10222
  // The plain-English sentence for a refusal the chat routes named, so a Start outside this panel
9776
10223
  // (the upload modal, Requests) says what happened and what to do next instead of a generic toast (#1779).
9777
10224
  describeError: errorMessage,