@floless/app 0.139.1 → 0.140.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
@@ -8,7 +8,7 @@
8
8
  const ui = {
9
9
  historyToggle: el('chat-history-toggle'), newChat: el('chat-new'), refresh: el('chat-refresh'), history: el('chat-history'),
10
10
  title: el('chat-title'), rename: el('chat-rename'), scope: el('chat-scope'), settingsToggle: el('chat-settings-toggle'),
11
- settings: el('chat-settings'), provider: el('chat-provider'), model: el('chat-model'),
11
+ settings: el('chat-settings'), provider: el('chat-provider'), switchAccount: el('chat-switch-account'), model: el('chat-model'),
12
12
  effort: el('chat-effort'), permission: el('chat-permission'), integrations: el('chat-integrations'),
13
13
  desktopValue: el('chat-desktop-value'), desktopReason: el('chat-desktop-reason'), picker: el('chat-picker'),
14
14
  feed: el('chat-feed'), recovery: el('chat-recovery'), recoveryCopy: el('chat-recovery-copy'),
@@ -20,17 +20,32 @@
20
20
  };
21
21
 
22
22
  const state = {
23
- sessionReady: false, scope: null, chats: [], archivedChats: [], chat: null, events: [], capability: null, desktop: null,
23
+ // signInPending is keyed by provider: a wait started in one conversation must not paint an
24
+ // unrelated conversation's button as Waiting for sign-in… for the next two minutes.
25
+ sessionReady: false, scope: null, chats: [], archivedChats: [], chat: null, events: [], capability: null, signInPending: new Set(), desktop: null,
24
26
  source: null, eventReconnectTimer: null, eventReconnectAttempt: 0, eventReconnectChatId: null, attachments: [], integrations: null, historyOpen: false, historyFilter: 'all', archivedHistoryOpen: false,
25
27
  instructorAnswers: [], historyLoading: false, historyRequestGeneration: 0, picker: null, loading: false,
26
28
  draftTimer: null, refreshTimer: null, scopeGeneration: 0, selectionGeneration: 0, choosingProvider: false,
27
29
  answerJump: null, answerJumpTimer: null, scopeInitialized: false, renaming: null, pendingSubmissionId: null, recoveryMessage: null, recoveryCanEnd: false,
28
- stream: null, liveStatusTurnId: null, decidingApprovalIds: new Set(),
30
+ stream: null, liveStatusTurnId: null, decidingApprovalIds: new Set(), revokingApprovalTurns: new Set(), uploadingChatIds: new Set(),
31
+ // Latched so the 5 s account poll logs an outage once instead of twelve times a minute; cleared
32
+ // on the next successful read, so a later, separate outage is logged too.
33
+ accountReadWarned: false,
29
34
  };
30
35
  const permissionLabels = {
31
36
  'read-only': 'Read only', 'workspace-write': 'Working folder write', 'full-access': 'Full access',
32
37
  };
33
38
  const providerLabels = { claude: 'Claude', codex: 'Codex' };
39
+ // The one sign-in refusal FloLess re-words. 'chat-turn-active' is the same code every other chat
40
+ // action returns, whose shared sentence (stop the response before changing the conversation) would
41
+ // be wrong here: the user is not changing the conversation, only waiting to switch who answers it.
42
+ // Every other sign-in refusal keeps the server's own sentence — see SERVER_WORDED_SIGN_IN_CODES.
43
+ const signInMessages = {
44
+ 'chat-turn-active': 'Wait for the current AI reply to finish before switching accounts.',
45
+ };
46
+ // The server's own sentence is more accurate than anything we can substitute: it names WHICH
47
+ // runtime problem happened and WHICH command to run by hand. errorMessage() would flatten it.
48
+ const SERVER_WORDED_SIGN_IN_CODES = new Set(['runtime-unavailable', 'launch-failed', 'launch-unsafe', 'sign-in-active', 'sign-out-failed']);
34
49
  const requestTypeLabels = { 'drawing-intake': 'Initial drawing read', 'initial-drawing-read': 'Initial drawing read', 'tweak-contract': 'Workflow change', guide: 'Question' };
35
50
  const requestStatusLabels = { pending: 'Queued', queued: 'Queued', running: 'Running', ready: 'Ready', completed: 'Complete', failed: 'Failed', stopped: 'Stopped' };
36
51
  const allowedTypes = new Set(['image/png', 'image/jpeg', 'image/webp', 'application/pdf']);
@@ -88,13 +103,15 @@
88
103
  choice.setAttribute('aria-busy', String(busy));
89
104
  }
90
105
  const blocked = requestExecutionBlocked();
106
+ const uploading = Boolean(state.chat?.chatId && state.uploadingChatIds.has(state.chat.chatId));
91
107
  // Freeze the draft while the server is accepting it. The acceptance transaction clears the
92
108
  // durable draft; allowing typing in this short window can race a new autosave over that clear
93
109
  // and make the submitted message reappear after the turn finishes.
94
110
  ui.input.disabled = busy || !state.chat || Boolean(state.chat?.archivedAt)
95
111
  || state.chat?.state === 'recovery' || blocked;
96
- ui.send.disabled = busy || !state.chat || blocked || !ui.input.value.trim() || Boolean(state.chat?.activeTurn);
97
- ui.attach.disabled = busy || !state.chat || blocked || Boolean(state.chat?.activeTurn);
112
+ ui.send.disabled = busy || uploading || !state.chat || blocked
113
+ || (!ui.input.value.trim() && state.attachments.length === 0) || Boolean(state.chat?.activeTurn);
114
+ ui.attach.disabled = busy || uploading || !state.chat || blocked || Boolean(state.chat?.activeTurn);
98
115
  }
99
116
 
100
117
  function errorMessage(error) {
@@ -213,11 +230,17 @@
213
230
  return 'FloLess could not complete this chat action. Reload the conversation and try again.';
214
231
  }
215
232
 
233
+ // The one reason the empty state can act on itself: a sign-in. Every other reason names a problem
234
+ // a sign-in button would not fix, so the button follows THIS rule, not the reason's wording.
235
+ function signInNeeded(reason) {
236
+ const raw = String(reason || '');
237
+ return !raw || /sign in|auth|account/i.test(raw);
238
+ }
239
+
216
240
  function capabilityMessage(provider, reason) {
217
241
  const label = providerLabels[provider] || 'AI service';
218
242
  const raw = String(reason || '');
219
- if (!raw) return `Sign in to ${label} first.`;
220
- if (/sign in|auth|account/i.test(raw)) return `Sign in to ${label} first.`;
243
+ if (signInNeeded(raw)) return `Sign in to ${label} first.`;
221
244
  if (/EPERM|EACCES|ENOENT|ENOTDIR|operation not permitted|permission denied|watch ['"]/i.test(raw)) {
222
245
  return 'FloLess cannot open this conversation’s project or workflow folder. Restore or reconnect that folder, then try again.';
223
246
  }
@@ -230,8 +253,9 @@
230
253
  return `The ${label} chat is not ready on this computer. Reload FloLess and try again.`;
231
254
  }
232
255
 
233
- function report(error, prefix = '') {
234
- const message = `${prefix}${prefix ? ': ' : ''}${errorMessage(error)}`;
256
+ function report(error, prefix = '', messages = null) {
257
+ const code = String(error && error.code || '');
258
+ const message = `${prefix}${prefix ? ': ' : ''}${messages?.[code] || errorMessage(error)}`;
235
259
  announce(message);
236
260
  ui.hint.textContent = message;
237
261
  ui.hint.classList.add('error');
@@ -270,8 +294,13 @@
270
294
  return typeof ownerId === 'string' ? `${owner.kind}:${ownerId}` : '';
271
295
  }
272
296
 
297
+ // The probe's `authenticated` is read once per capability load; the CLI's own answer is merged
298
+ // in by the 5 s poll. A parsed sign-OUT from the CLI overrides the probe here exactly as the
299
+ // server's registry does on a fresh read: a chat is not ready on a CLI that says "not logged in",
300
+ // however recently the probe said otherwise — the feed and the Provider row must not disagree.
273
301
  function providerReady() {
274
- return Boolean(state.capability?.available && state.capability?.authenticated === true);
302
+ return Boolean(state.capability?.available && state.capability?.authenticated === true
303
+ && capabilityAnswer(state.capability).state !== 'signed-out');
275
304
  }
276
305
 
277
306
  function currentFloLessContext() {
@@ -405,10 +434,35 @@
405
434
  function renderedLiveAssistantText(event, text) {
406
435
  if (!event?.payload?.delta || !event.turnId || !state.chat) return { text, streaming: false };
407
436
  const key = `${state.chat.chatId}:${event.turnId}`;
437
+ const isActiveTurn = state.chat.activeTurn?.turnId === event.turnId;
438
+ // One animator can own only the final prose block. Earlier blocks must not
439
+ // reset its target on every repaint (even when they belong to the same turn).
440
+ if (state.chat.state === 'recovery') {
441
+ // Recovery may reconcile back to this same running turn. Preserve the fully revealed target so
442
+ // that return does not restart an already-read answer from its first 12 characters.
443
+ const latest = isActiveTurn
444
+ ? state.events?.findLast((item) => item.type === 'assistant-message' && item.turnId === event.turnId)
445
+ : null;
446
+ if (isActiveTurn && (!latest || latest.eventId === event.eventId)) {
447
+ if (state.stream?.key !== key) {
448
+ clearLiveStream();
449
+ state.stream = { key, chatId: state.chat.chatId, turnId: event.turnId, target: text, shown: text, frame: null };
450
+ } else {
451
+ state.stream.target = text;
452
+ }
453
+ flushLiveStream();
454
+ }
455
+ return { text, streaming: false };
456
+ }
457
+ if (!state.chat.activeTurn) {
458
+ clearLiveStream();
459
+ return { text, streaming: false };
460
+ }
408
461
  // Historical stream chunks are stored as deltas too. Only animate the active turn; otherwise
409
462
  // opening a conversation would reset every prior answer and leave the last one half-rendered.
410
- const isActiveTurn = state.chat.activeTurn?.turnId === event.turnId;
411
- if (!isActiveTurn && state.stream?.key !== key) return { text, streaming: false };
463
+ if (!isActiveTurn) return { text, streaming: false };
464
+ const latest = state.events?.findLast((item) => item.type === 'assistant-message' && item.turnId === event.turnId);
465
+ if (latest && latest.eventId !== event.eventId) return { text, streaming: false };
412
466
  if (state.stream?.key !== key) {
413
467
  clearLiveStream();
414
468
  state.stream = { key, chatId: state.chat.chatId, turnId: event.turnId, target: '', shown: '', frame: null };
@@ -501,9 +555,33 @@
501
555
  row.append(choice);
502
556
  }
503
557
  empty.append(strong, copy, row);
558
+ const accounts = document.createElement('div');
559
+ accounts.className = 'ai-chat-provider-accounts';
560
+ accounts.textContent = 'Checking signed-in accounts…';
561
+ empty.append(accounts);
562
+ // There is no chat yet, so no capability probe exists; the runtimes read carries the same sign-in.
563
+ request('/api/terminal-runtimes').then((info) => {
564
+ if (!accounts.isConnected) return;
565
+ accounts.replaceChildren(...['claude', 'codex'].map((provider) => {
566
+ const cell = document.createElement('span');
567
+ const runtime = info?.runtimes?.find((r) => r?.id === provider);
568
+ // Each row carries its OWN answer — including that its status read failed — so this must
569
+ // state that answer rather than assume the read landed. A runtime missing from the list
570
+ // is a known absence, not an unchecked one, hence the flat "not installed" wording.
571
+ cell.textContent = runtime ? providerAccountLabel(provider, runtime.account) : `${providerLabels[provider]} · not installed`;
572
+ return cell;
573
+ }));
574
+ }).catch((error) => {
575
+ // The line disappears rather than guessing; without this the feature vanishing is invisible.
576
+ console.warn('floless: could not read the signed-in accounts for the chooser', error);
577
+ if (accounts.isConnected) accounts.remove();
578
+ });
504
579
  ui.feed.append(empty);
505
580
  ui.title.textContent = 'New conversation';
506
- ui.provider.querySelector('strong').textContent = 'Choose Claude or Codex';
581
+ const providerValue = ui.provider.querySelector('strong');
582
+ providerValue.textContent = 'Choose Claude or Codex';
583
+ delete providerValue.dataset.tip;
584
+ ui.switchAccount.hidden = true;
507
585
  ui.input.disabled = true;
508
586
  ui.attach.disabled = true;
509
587
  ui.send.disabled = true;
@@ -1056,9 +1134,13 @@
1056
1134
  const head = document.createElement('div'); head.className = 'ai-chat-message-head';
1057
1135
  const who = document.createElement('span'); who.textContent = role === 'user' ? 'You' : providerLabels[state.chat?.provider] || 'AI';
1058
1136
  const time = document.createElement('time'); time.dateTime = event.createdAt; time.textContent = eventTime(event);
1059
- const body = document.createElement('div'); body.className = 'ai-chat-message-body';
1060
- body.innerHTML = markdownHtml(role === 'assistant' ? visibleAssistantText(text) : visibleUserText(text));
1061
- head.append(who, time); item.append(head, body);
1137
+ const visibleText = role === 'assistant' ? visibleAssistantText(text) : visibleUserText(text);
1138
+ head.append(who, time); item.append(head);
1139
+ if (role === 'assistant' || visibleText) {
1140
+ const body = document.createElement('div'); body.className = 'ai-chat-message-body';
1141
+ body.innerHTML = markdownHtml(visibleText);
1142
+ item.append(body);
1143
+ }
1062
1144
  if (role === 'user' && Array.isArray(event.payload?.attachmentIds)) {
1063
1145
  const attachments = event.payload.attachmentIds
1064
1146
  .map((id) => state.chat?.attachments?.find((candidate) => candidate.attachmentId === id))
@@ -1152,7 +1234,7 @@
1152
1234
  }
1153
1235
 
1154
1236
  function announceLiveResponseOnce() {
1155
- const turnId = state.chat?.activeTurn?.turnId || null;
1237
+ const turnId = turnIsVisiblyActive() ? state.chat.activeTurn.turnId : null;
1156
1238
  if (!turnId) {
1157
1239
  state.liveStatusTurnId = null;
1158
1240
  // The screen-reader announcement is a transient status. Once the durable turn ends,
@@ -1164,7 +1246,11 @@
1164
1246
  state.liveStatusTurnId = turnId;
1165
1247
  const provider = providerLabels[state.chat?.provider] || 'AI';
1166
1248
  ui.status.textContent = '';
1167
- requestAnimationFrame(() => { ui.status.textContent = `${provider} is responding.`; });
1249
+ requestAnimationFrame(() => {
1250
+ // Recovery or completion may land between scheduling and painting this transient sentence.
1251
+ if (!turnIsVisiblyActive() || state.chat?.activeTurn?.turnId !== turnId || state.liveStatusTurnId !== turnId) return;
1252
+ ui.status.textContent = `${provider} is responding.`;
1253
+ });
1168
1254
  }
1169
1255
 
1170
1256
  function renderedAnswerTarget(events, eventId, turnId) {
@@ -1198,23 +1284,7 @@
1198
1284
  const nearBottom = ui.feed.scrollHeight - ui.feed.scrollTop - ui.feed.clientHeight < 56;
1199
1285
  ui.feed.replaceChildren();
1200
1286
  if (!state.events.length) {
1201
- const empty = document.createElement('div'); empty.className = 'ai-chat-empty';
1202
- const strong = document.createElement('strong');
1203
- const copy = document.createElement('div');
1204
- if (providerReady()) {
1205
- strong.textContent = 'Ready when you are';
1206
- copy.textContent = `This ${providerLabels[state.chat?.provider] || 'AI'} conversation is stored with ${state.scope?.label || 'this work'}.`;
1207
- } else if (state.capability?.runtime && state.capability.runtime.state !== 'installed') {
1208
- const notice = runtimeNotice(state.chat?.provider, state.capability.runtime);
1209
- strong.textContent = notice.title;
1210
- copy.textContent = state.capability.runtime.state === 'failed'
1211
- ? notice.body
1212
- : 'You can write your first message now. Send becomes available when setup finishes.';
1213
- } else {
1214
- strong.textContent = `${providerLabels[state.chat?.provider] || 'AI'} needs attention`;
1215
- copy.textContent = capabilityMessage(state.chat?.provider, state.capability?.reason);
1216
- }
1217
- empty.append(strong, copy); ui.feed.append(empty);
1287
+ ui.feed.append(emptyFeedNotice());
1218
1288
  } else {
1219
1289
  let assistant = null;
1220
1290
  const flushAssistant = () => {
@@ -1246,30 +1316,131 @@
1246
1316
  }
1247
1317
  flushAssistant();
1248
1318
  // A provider can send text before it finishes tools, usage, or its terminal turn signal.
1249
- // Keep this fixed activity row visible for the full durable turn (and while text drains)
1250
- // so an intermittent stream never looks like a failed response.
1251
- if (turnIsVisiblyActive() || hasPendingLiveStream()) ui.feed.append(renderLiveStatus());
1319
+ // Keep this fixed activity row visible for the full durable turn so an intermittent stream
1320
+ // never looks like a failed response. Recovery deliberately has no live indicator.
1321
+ if (turnIsVisiblyActive()) ui.feed.append(renderLiveStatus());
1252
1322
  }
1253
1323
  restoreAnswerJump();
1254
1324
  if (!state.answerJump && (nearBottom || options.forceBottom)) requestAnimationFrame(() => { ui.feed.scrollTop = ui.feed.scrollHeight; });
1255
1325
  }
1256
1326
 
1327
+ // The feed's empty state. Four cases, in the order they must win: a sign-in window FloLess
1328
+ // opened from this chat is still the user's to finish (the CLI is signed OUT while it is open —
1329
+ // "Ready when you are" would be a lie for up to two minutes); the provider is ready; the runtime
1330
+ // is still being set up; or the provider needs attention — and when that attention is a sign-in,
1331
+ // the action sits right here (#1484), on the same state machine as the settings-strip button, so
1332
+ // a new user is never told to "sign in first" with nowhere to do it.
1333
+ function emptyFeedNotice() {
1334
+ const empty = document.createElement('div'); empty.className = 'ai-chat-empty';
1335
+ const strong = document.createElement('strong');
1336
+ const copy = document.createElement('div');
1337
+ const provider = state.chat?.provider;
1338
+ const label = providerLabels[provider] || 'AI';
1339
+ const pendingSignIn = Boolean(provider && state.signInPending.has(provider));
1340
+ if (pendingSignIn) {
1341
+ strong.textContent = 'Waiting for sign-in…';
1342
+ // The claude.ai page in the browser keeps its OWN session: it may still show the previous
1343
+ // account with an "Switch account" link of its own, and no CLI verb can clear that. Said
1344
+ // at the one moment it matters, for the one provider it applies to.
1345
+ copy.textContent = `Finish signing in using the window FloLess opened.${provider === 'claude'
1346
+ ? ' If the Claude page in your browser still shows the previous account, use its own Switch account link.' : ''}`;
1347
+ empty.append(strong, copy, emptySignInButton(label, true));
1348
+ } else if (providerReady()) {
1349
+ strong.textContent = 'Ready when you are';
1350
+ copy.textContent = `This ${label} conversation is stored with ${state.scope?.label || 'this work'}.`;
1351
+ empty.append(strong, copy);
1352
+ } else if (state.capability?.runtime && state.capability.runtime.state !== 'installed') {
1353
+ const notice = runtimeNotice(provider, state.capability.runtime);
1354
+ strong.textContent = notice.title;
1355
+ copy.textContent = state.capability.runtime.state === 'failed'
1356
+ ? notice.body
1357
+ : 'You can write your first message now. Send becomes available when setup finishes.';
1358
+ empty.append(strong, copy);
1359
+ } else {
1360
+ strong.textContent = `${label} needs attention`;
1361
+ copy.textContent = capabilityMessage(provider, state.capability?.reason);
1362
+ empty.append(strong, copy);
1363
+ if (signInNeeded(state.capability?.reason)) empty.append(emptySignInButton(label, false));
1364
+ }
1365
+ return empty;
1366
+ }
1367
+
1368
+ // The same control as the settings strip's, in the empty state: one `switchAccount()`, one
1369
+ // pending set. Only ever a sign-in — the reason that shows it guarantees that — so it never needs
1370
+ // the strip's "Switch account…" label. Its own command id because it is its own carrier, in its
1371
+ // own place.
1372
+ function emptySignInButton(label, pending) {
1373
+ const signIn = document.createElement('button');
1374
+ signIn.type = 'button';
1375
+ signIn.className = 'ai-chat-provider-switch ai-chat-empty-signin';
1376
+ signIn.dataset.commandId = 'shell.chat-sign-in';
1377
+ signIn.setAttribute('aria-label', `Sign in to ${label}`);
1378
+ signIn.textContent = pending ? 'Waiting for sign-in…' : 'Sign in…';
1379
+ signIn.disabled = pending;
1380
+ if (pending) signIn.dataset.blockedReason = 'Waiting for the sign-in window.';
1381
+ signIn.addEventListener('click', () => { void switchAccount(); });
1382
+ return signIn;
1383
+ }
1384
+
1257
1385
  function paintApproval() {
1258
- shell.querySelector('.ai-chat-approval')?.remove();
1386
+ paintApprovalScope();
1387
+ const existing = shell.querySelector('.ai-chat-approval:not(.ai-chat-approval-scope)');
1259
1388
  const approval = state.chat?.pendingApproval;
1260
1389
  const deciding = Boolean(approval && state.decidingApprovalIds.has(approval.approvalId));
1261
1390
  shell.dataset.approvalPending = String(Boolean(approval) && !deciding);
1262
1391
  document.dispatchEvent(new CustomEvent('floless:chat-indicator'));
1263
- if (!approval || deciding) return;
1392
+ if (!approval || deciding) { existing?.remove(); return; }
1393
+ // Keep the same buttons during polling so keyboard focus and pointer clicks survive.
1394
+ if (existing?.dataset.approvalId === approval.approvalId) return;
1395
+ existing?.remove();
1264
1396
  const card = document.createElement('section'); card.className = 'ai-chat-approval';
1397
+ card.dataset.approvalId = approval.approvalId;
1265
1398
  const heading = document.createElement('strong'); heading.textContent = 'Approval needed';
1266
1399
  const copy = document.createElement('p'); copy.textContent = approval.summary;
1267
1400
  const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
1268
1401
  const deny = button('Deny', 'shell.chat-approval-deny');
1269
1402
  const allow = button('Approve once', 'shell.chat-approval-allow', 'allow');
1403
+ const allowRequest = button('Approve for this request', 'shell.chat-approval-request', 'allow');
1404
+ allowRequest.dataset.tip = 'Approve access actions until this response finishes. Your permission setting stays unchanged.';
1405
+ const scope = document.createElement('p');
1406
+ scope.textContent = 'Request approval lasts until this response finishes. Review checkpoints still need your decision.';
1270
1407
  deny.addEventListener('click', () => decideApproval('deny'));
1271
1408
  allow.addEventListener('click', () => decideApproval('allow'));
1272
- actions.append(deny, allow); card.append(heading, copy, actions);
1409
+ allowRequest.addEventListener('click', () => decideApproval('allow-request'));
1410
+ actions.append(deny, allow, allowRequest); card.append(heading, copy, scope, actions);
1411
+ shell.insertBefore(card, ui.recovery);
1412
+ }
1413
+
1414
+ function paintApprovalScope() {
1415
+ const existing = shell.querySelector('.ai-chat-approval-scope');
1416
+ const turn = state.chat?.activeTurn;
1417
+ if (!turn?.accessApprovalGranted || !['running', 'awaiting-approval'].includes(state.chat?.state)) {
1418
+ existing?.remove(); return;
1419
+ }
1420
+ const busy = state.revokingApprovalTurns.has(turn.turnId);
1421
+ if (existing?.dataset.turnId === turn.turnId) {
1422
+ const revoke = existing.querySelector('button');
1423
+ revoke.disabled = busy;
1424
+ revoke.setAttribute('aria-busy', String(busy));
1425
+ return;
1426
+ }
1427
+ existing?.remove();
1428
+ const card = document.createElement('section');
1429
+ card.className = 'ai-chat-approval ai-chat-approval-scope';
1430
+ card.dataset.turnId = turn.turnId;
1431
+ const heading = document.createElement('strong');
1432
+ heading.textContent = 'Access auto-approval on for this request';
1433
+ const copy = document.createElement('p');
1434
+ copy.textContent = 'Your permission setting is unchanged. Review checkpoints still need your decision.';
1435
+ const note = document.createElement('p');
1436
+ note.textContent = 'Actions already approved may finish.';
1437
+ const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
1438
+ const revoke = button('Revoke', 'shell.chat-approval-revoke');
1439
+ revoke.dataset.tip = 'Ask before future access actions in this request.';
1440
+ revoke.disabled = busy;
1441
+ revoke.setAttribute('aria-busy', String(busy));
1442
+ revoke.addEventListener('click', revokeApprovalScope);
1443
+ actions.append(revoke); card.append(heading, copy, note, actions);
1273
1444
  shell.insertBefore(card, ui.recovery);
1274
1445
  }
1275
1446
 
@@ -1474,10 +1645,132 @@
1474
1645
  return text ? text.charAt(0).toUpperCase() + text.slice(1) : '';
1475
1646
  }
1476
1647
 
1648
+ // A plan token is an internal id, not a product name — this machine really reports Codex
1649
+ // `plan: "prolite"`, which means nothing to a user. Only plans a person would recognise from
1650
+ // their own bill are shown; anything else is omitted, because the email is the load-bearing part.
1651
+ const planLabels = { free: 'Free', pro: 'Pro', plus: 'Plus', max: 'Max', team: 'Team', enterprise: 'Enterprise' };
1652
+ function planLabel(plan) {
1653
+ return planLabels[String(plan || '').trim().toLowerCase()] || '';
1654
+ }
1655
+
1656
+ // The server answers with exactly one of four things, and the row says which. Anything else —
1657
+ // a missing or null `account`, which is what readCapability's catch synthesises when the HTTP
1658
+ // request itself failed — is 'unknown': FloLess never learned who would answer, and "not signed
1659
+ // in" there would be a claim it never checked. A working install on Bedrock/Vertex or an API key
1660
+ // answers 'no-identity': signed in, with no email to name.
1661
+ function signInAnswer(answer) {
1662
+ const state = answer && answer.state;
1663
+ if (state === 'signed-in' || state === 'signed-out' || state === 'no-identity') return answer;
1664
+ return { state: 'unknown', reason: (answer && answer.reason) || 'no answer' };
1665
+ }
1666
+
1667
+ // The one place `state.capability` becomes something the row can say. A null capability is the
1668
+ // first read still in flight — a phase, not an answer — so it is the only value that is not one
1669
+ // of the four. paintSettings and the empty state both go through here.
1670
+ function capabilityAnswer(capability) {
1671
+ return capability ? signInAnswer(capability.account) : { state: 'checking' };
1672
+ }
1673
+
1674
+ // A stable identity for "is this a different answer than the one we had?". Comparing emails alone
1675
+ // could not see a sign-OUT (both sides are absent), which is why one never propagated.
1676
+ function answerKey(answer) {
1677
+ const settled = signInAnswer(answer);
1678
+ return settled.state === 'signed-in' ? `signed-in:${settled.email}` : settled.state;
1679
+ }
1680
+
1681
+ function providerAccountLabel(provider, answer) {
1682
+ const label = providerLabels[provider] || provider;
1683
+ if (answer && answer.state === 'checking') return `${label} · checking…`;
1684
+ const settled = signInAnswer(answer);
1685
+ if (settled.state === 'signed-out') return `${label} · not signed in`;
1686
+ if (settled.state === 'no-identity') return `${label} · signed in (no account to show)`;
1687
+ if (settled.state === 'unknown') return `${label} · could not check`;
1688
+ const plan = planLabel(settled.plan);
1689
+ return plan ? `${label} · ${settled.email} · ${plan}` : `${label} · ${settled.email}`;
1690
+ }
1691
+
1692
+ async function switchAccount() {
1693
+ const chat = state.chat;
1694
+ if (!chat || state.signInPending.has(chat.provider)) return;
1695
+ const snapshot = captureChat();
1696
+ const before = answerKey(state.capability?.account);
1697
+ state.signInPending.add(chat.provider);
1698
+ // Both carriers of this action flip to "Waiting for sign-in…" at the click, not at the next
1699
+ // 5 s poll: the empty state's button is the one a new user just pressed.
1700
+ paintSettings(); paintEvents();
1701
+ try {
1702
+ await request(`/api/terminal-runtimes/${encodeURIComponent(chat.provider)}/sign-in`, { method: 'POST' });
1703
+ await waitForSignIn(chat.provider, before);
1704
+ if (sameChat(snapshot)) await loadCapability();
1705
+ } catch (error) {
1706
+ const code = String(error && error.code || '');
1707
+ const worded = SERVER_WORDED_SIGN_IN_CODES.has(code) && typeof error?.message === 'string' && error.message.trim();
1708
+ if (sameChat(snapshot)) {
1709
+ report(error, 'Could not switch account', worded ? { [code]: error.message } : signInMessages);
1710
+ // The server signs the CLI out BEFORE it opens the window, so a launch that failed after that
1711
+ // step left the CLI signed out: re-read, or the feed says "Ready when you are" over a dead Send.
1712
+ await loadCapability();
1713
+ }
1714
+ } finally {
1715
+ state.signInPending.delete(chat.provider);
1716
+ // This runs outside every try above, and the click handler calls switchAccount() with `void`:
1717
+ // a throw from the repaint would surface as an unhandled rejection with nothing to catch it.
1718
+ // The feed's empty state carries the same button and the waiting copy, so it repaints too.
1719
+ try { if (sameChat(snapshot)) { paintSettings(); paintEvents(); updateSendState(); } } catch (error) {
1720
+ console.warn('floless: could not repaint the provider row after a sign-in', error);
1721
+ }
1722
+ }
1723
+ }
1724
+
1725
+ // The sign-in itself happens in the window FloLess opened. Poll the cheap runtimes read (no
1726
+ // provider launch, 10 s server cache) until that provider NAMES a sign-in different from the one
1727
+ // held at click time, or give up. A different sign-in, not "a different email": signing in with
1728
+ // an API key produces no email, and the button would sit disabled for the full two minutes. And
1729
+ // not "any definite change" either: the server signs the CLI out BEFORE the window opens, so
1730
+ // signed-out is what every poll sees while the user is still in it — ending there would offer
1731
+ // "Sign in…" again with the window open (the server refuses that click for its launch cooldown).
1732
+ // And once that sign-out HAS been seen, any named sign-in is the landed one — including the same
1733
+ // account again: a user who changes their mind in the browser must not wait out the deadline.
1734
+ async function waitForSignIn(provider, before, deadlineMs = 120_000, everyMs = 3_000) {
1735
+ const until = Date.now() + deadlineMs;
1736
+ let signedOutSeen = false;
1737
+ while (Date.now() < until) {
1738
+ await new Promise((resolve) => setTimeout(resolve, everyMs));
1739
+ let info = null;
1740
+ try { info = await request('/api/terminal-runtimes'); } catch { continue; }
1741
+ const row = info?.runtimes?.find((runtime) => runtime?.id === provider);
1742
+ if (!row) continue;
1743
+ const answer = signInAnswer(row.account);
1744
+ // An 'unknown' answer is a read that never completed; it is not evidence the window closed.
1745
+ if (answer.state === 'unknown') continue;
1746
+ // A 'signed-out' is FloLess's own doing (above), not the sign-in the user went off to make.
1747
+ if (answer.state === 'signed-out') { signedOutSeen = true; continue; }
1748
+ if (signedOutSeen || answerKey(answer) !== before) return;
1749
+ }
1750
+ }
1751
+
1477
1752
  function paintSettings() {
1478
1753
  const chat = state.chat;
1479
1754
  ui.settingsToggle.disabled = !chat;
1480
- ui.provider.querySelector('strong').textContent = chat ? providerLabels[chat.provider] : '—';
1755
+ const answer = capabilityAnswer(state.capability);
1756
+ const pendingSignIn = Boolean(chat && state.signInPending.has(chat.provider));
1757
+ const accountLabel = chat ? providerAccountLabel(chat.provider, answer) : '—';
1758
+ const providerValue = ui.provider.querySelector('strong');
1759
+ // The value is an aria-live region and this repaints on every 5 s poll: writing an unchanged
1760
+ // string would read the account out to a screen reader again every five seconds.
1761
+ if (providerValue.textContent !== accountLabel) providerValue.textContent = accountLabel;
1762
+ // The tooltip repeats that same text, so keep it in step without a redundant attribute write.
1763
+ if (!chat) delete providerValue.dataset.tip;
1764
+ else if (providerValue.dataset.tip !== accountLabel) providerValue.dataset.tip = accountLabel;
1765
+ ui.switchAccount.hidden = !chat;
1766
+ // Only a parsed negative may invite a sign-in. A read that never completed has not earned the
1767
+ // invitation, and a CLI on Bedrock/Vertex or an API key is signed in already.
1768
+ ui.switchAccount.textContent = pendingSignIn ? 'Waiting for sign-in…'
1769
+ : answer.state === 'signed-out' ? 'Sign in…' : 'Switch account…';
1770
+ ui.switchAccount.disabled = !chat || pendingSignIn || Boolean(chat.activeTurn);
1771
+ const switchBlocked = chat?.activeTurn && !pendingSignIn ? 'Wait for the current AI reply to finish before switching accounts.' : '';
1772
+ if (switchBlocked) { ui.switchAccount.dataset.tip = switchBlocked; ui.switchAccount.dataset.blockedReason = switchBlocked; }
1773
+ else { delete ui.switchAccount.dataset.tip; delete ui.switchAccount.dataset.blockedReason; }
1481
1774
  const model = selectedModel();
1482
1775
  ui.model.querySelector('strong').textContent = chat?.settings.model ? (model?.label || chat.settings.model) : (model?.label || 'Choose model');
1483
1776
  const medium = (model?.efforts || []).find((effort) => effort.toLowerCase() === 'medium');
@@ -1746,6 +2039,9 @@
1746
2039
  // A provider picker is an explicit user choice. Only an action that explicitly replaces it
1747
2040
  // may select a stored chat; background scope refreshes must leave the picker untouched.
1748
2041
  if (state.choosingProvider && options.replaceProviderChoice !== true) return;
2042
+ // Opening an existing conversation abandons an unsent discovery handoff. Only the
2043
+ // conversation created from that chooser should inherit its draft.
2044
+ if (!options.preserveDiscoveryDraft) state.discoveryDraft = null;
1749
2045
  clearProviderChoice();
1750
2046
  const selection = ++state.selectionGeneration;
1751
2047
  const exactAnswer = typeof options.answerEventId === 'string' ? options.answerEventId : null;
@@ -1830,6 +2126,7 @@
1830
2126
  return;
1831
2127
  }
1832
2128
  const generation = ++state.scopeGeneration;
2129
+ if (scopeKey(scope) !== scopeKey(state.scope)) state.discoveryDraft = null;
1833
2130
  state.selectionGeneration += 1;
1834
2131
  clearAnswerJump();
1835
2132
  clearLiveStream(true);
@@ -1891,7 +2188,12 @@
1891
2188
  }),
1892
2189
  });
1893
2190
  state.chats.unshift(chat);
1894
- await selectConversation(chat.chatId, { focus: true, applyProviderDefaults: true, replaceProviderChoice: true });
2191
+ await selectConversation(chat.chatId, { focus: true, applyProviderDefaults: true, replaceProviderChoice: true, preserveDiscoveryDraft: true });
2192
+ if (state.discoveryDraft && state.chat?.chatId === chat.chatId) {
2193
+ ui.input.value = state.discoveryDraft;
2194
+ state.discoveryDraft = null;
2195
+ ui.input.dispatchEvent(new Event('input', { bubbles: true }));
2196
+ }
1895
2197
  announce(`${providerLabels[provider]} conversation created.`);
1896
2198
  } catch (error) { report(error, 'Could not start conversation'); }
1897
2199
  finally { setBusy(false); }
@@ -2144,9 +2446,11 @@
2144
2446
  const blocked = requestExecutionBlocked();
2145
2447
  // A provider FloLess is still setting up cannot take a message; the runtime card explains why.
2146
2448
  const settingUp = Boolean(state.capability?.runtime && state.capability.runtime.state !== 'installed');
2449
+ const uploading = Boolean(state.chat?.chatId && state.uploadingChatIds.has(state.chat.chatId));
2147
2450
  ui.input.disabled = !state.chat || Boolean(state.chat?.archivedAt) || recovery || blocked;
2148
- ui.send.disabled = state.loading || !state.chat || blocked || frozen || !ui.input.value.trim() || settingUp;
2149
- ui.attach.disabled = state.loading || !state.chat || blocked || frozen;
2451
+ ui.send.disabled = state.loading || uploading || !state.chat || blocked || frozen
2452
+ || (!ui.input.value.trim() && state.attachments.length === 0) || settingUp;
2453
+ ui.attach.disabled = state.loading || uploading || !state.chat || blocked || frozen;
2150
2454
  ui.stop.hidden = !active || Boolean(state.chat?.activeTurn?.local);
2151
2455
  ui.send.hidden = active;
2152
2456
  // Session recovery must remain available even while provider capability discovery is loading
@@ -2401,13 +2705,40 @@
2401
2705
  method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, decision }),
2402
2706
  });
2403
2707
  if (!sameChat(snapshot)) return;
2404
- announce(decision === 'allow' ? 'Approved once.' : 'Action denied.');
2708
+ announce(decision === 'allow-request' ? 'Access auto-approval is on for this request.'
2709
+ : decision === 'allow' ? 'Approved once.' : 'Action denied.');
2405
2710
  await refreshConversation(snapshot.chatId, false);
2406
2711
  } catch (error) {
2407
2712
  if (!sameChat(snapshot)) return;
2408
2713
  report(error, 'Could not apply your choice');
2409
2714
  await refreshConversation(snapshot.chatId, false);
2410
- } finally { state.decidingApprovalIds.delete(approvalId); }
2715
+ } finally {
2716
+ state.decidingApprovalIds.delete(approvalId);
2717
+ if (sameChat(snapshot)) paintApproval();
2718
+ }
2719
+ }
2720
+
2721
+ async function revokeApprovalScope() {
2722
+ const turn = state.chat?.activeTurn;
2723
+ const snapshot = captureChat();
2724
+ if (!snapshot || !turn?.accessApprovalGranted || state.revokingApprovalTurns.has(turn.turnId)) return;
2725
+ state.revokingApprovalTurns.add(turn.turnId);
2726
+ paintApprovalScope();
2727
+ try {
2728
+ await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/approval-scope/revoke`, {
2729
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, turnId: turn.turnId }),
2730
+ });
2731
+ if (!sameChat(snapshot)) return;
2732
+ announce('Auto-approval revoked. Future access actions will ask again. Actions already approved may finish.');
2733
+ await refreshConversation(snapshot.chatId, false);
2734
+ } catch (error) {
2735
+ if (!sameChat(snapshot)) return;
2736
+ report(error, 'Could not revoke auto-approval');
2737
+ await refreshConversation(snapshot.chatId, false);
2738
+ } finally {
2739
+ state.revokingApprovalTurns.delete(turn.turnId);
2740
+ if (sameChat(snapshot)) paintApprovalScope();
2741
+ }
2411
2742
  }
2412
2743
 
2413
2744
  function fileBase64(file) {
@@ -2423,6 +2754,7 @@
2423
2754
  if (!state.chat || state.chat.activeTurn) return;
2424
2755
  const snapshot = captureChat();
2425
2756
  if (!snapshot) return;
2757
+ if (state.uploadingChatIds.has(snapshot.chatId)) return;
2426
2758
  const incoming = [...files];
2427
2759
  const known = [...new Map([...(state.chat.attachments || []), ...state.attachments]
2428
2760
  .map((attachment) => [attachment.attachmentId, attachment])).values()];
@@ -2431,7 +2763,8 @@
2431
2763
  if (incoming.some((file) => !allowedTypes.has(file.type))) { report(new Error('Attach a PNG, JPEG, WebP, or PDF')); return; }
2432
2764
  if (incoming.some((file) => file.size > 20 * MB)) { report(new Error('Each attachment must be 20 MB or smaller')); return; }
2433
2765
  if (existingBytes + incoming.reduce((sum, file) => sum + file.size, 0) > 50 * MB) { report(new Error('Attachments must stay within 50 MB per conversation')); return; }
2434
- ui.attach.disabled = true;
2766
+ state.uploadingChatIds.add(snapshot.chatId);
2767
+ updateSendState();
2435
2768
  try {
2436
2769
  for (const file of incoming) {
2437
2770
  const data = await fileBase64(file);
@@ -2441,11 +2774,19 @@
2441
2774
  });
2442
2775
  if (!sameChat(snapshot)) return;
2443
2776
  state.attachments.push(attachment);
2777
+ state.chat.attachments = [...(state.chat.attachments || []).filter((item) => item.attachmentId !== attachment.attachmentId), attachment];
2778
+ // Commit each successful upload to the visible composer immediately. A later file in the
2779
+ // same batch can fail, but it must not leave this persisted attachment hidden or Send stale.
2780
+ paintAttachments(); updateSendState();
2444
2781
  }
2445
2782
  if (!sameChat(snapshot)) return;
2446
- paintAttachments(); announce(`${incoming.length} attachment${incoming.length === 1 ? '' : 's'} ready for the next message.`);
2783
+ announce(`${incoming.length} attachment${incoming.length === 1 ? '' : 's'} ready for the next message.`);
2447
2784
  } catch (error) { if (sameChat(snapshot)) report(error, 'Could not attach file'); }
2448
- finally { if (sameChat(snapshot)) ui.attach.disabled = false; ui.file.value = ''; }
2785
+ finally {
2786
+ state.uploadingChatIds.delete(snapshot.chatId);
2787
+ ui.file.value = '';
2788
+ if (sameChat(snapshot)) updateSendState();
2789
+ }
2449
2790
  }
2450
2791
 
2451
2792
  async function pollChats() {
@@ -2486,6 +2827,40 @@
2486
2827
  // so a completed turn removes any stale live activity indicator. With no conversation
2487
2828
  // selected the feed is the Claude/Codex chooser, which a repaint would erase.
2488
2829
  paintHistory(); paintUnread();
2830
+ // A sign-in OR a sign-OUT made from Integrations or from the user's own terminal changes who
2831
+ // answers, and nothing else re-reads it — the row would keep naming the old account for the
2832
+ // whole conversation. Use the cheap runtimes read (no provider launch, 10 s server cache)
2833
+ // rather than re-probing the provider, which would start the CLI every five seconds. While
2834
+ // the account is on screen: the settings strip, or the feed's empty state — which shows the
2835
+ // sign-in too (its Sign in… button, and providerReady()), and the first capability read
2836
+ // after a sign-out made elsewhere can still carry the reader's stale answer. Not for a
2837
+ // conversation with messages and the strip closed: past the 10 s server cache this read
2838
+ // asks both CLIs for their status, and nothing there would show the answer.
2839
+ if (state.chat && (!ui.settings.hidden || !state.events.length)) {
2840
+ const chatId = state.chat.chatId;
2841
+ try {
2842
+ const info = await request('/api/terminal-runtimes');
2843
+ state.accountReadWarned = false;
2844
+ const row = info?.runtimes?.find((runtime) => runtime?.id === state.chat?.provider);
2845
+ const answer = row ? signInAnswer(row.account) : null;
2846
+ // Merge on any DEFINITE answer whose identity differs, not on a present email: an email
2847
+ // is absent both when the user signed out and when they never signed in, so an email
2848
+ // comparison can never see a sign-out. An 'unknown' answer is a read that never
2849
+ // completed, and must not overwrite what the row already knows.
2850
+ if (sameScope(scope, generation) && state.chat?.chatId === chatId && state.capability
2851
+ && answer && answer.state !== 'unknown' && answerKey(answer) !== answerKey(state.capability.account)) {
2852
+ state.capability = { ...state.capability, account: answer };
2853
+ }
2854
+ } catch (error) {
2855
+ // The row keeps its last known account and the next poll tries again — but a silent retry
2856
+ // loop leaves an outage with nothing to diagnose it by. Once per outage, not every 5 s.
2857
+ if (!state.accountReadWarned) {
2858
+ state.accountReadWarned = true;
2859
+ console.warn('floless: could not re-read which account will answer', error);
2860
+ }
2861
+ }
2862
+ if (!sameScope(scope, generation)) return;
2863
+ }
2489
2864
  if (state.chat) { paintSettings(); paintRecovery(); paintApproval(); paintEvents(); updateSendState(); }
2490
2865
  if (state.historyOpen && state.historyFilter === 'instructor-answers') refreshInstructorAnswers();
2491
2866
  } catch { /* SSE or the next poll will recover */ }
@@ -2556,6 +2931,24 @@
2556
2931
  await selectConversation(chatId, { focus: true, replaceProviderChoice: true });
2557
2932
  }
2558
2933
 
2934
+ async function openDraft(draft) {
2935
+ if (typeof draft !== 'string' || !draft.trim()) return;
2936
+ await refreshScope();
2937
+ if (!state.scope?.owner) throw new Error('Open a project or workflow before asking AI Chat about a local tool.');
2938
+ window.flolessBridge?.revealAiChat?.();
2939
+ ui.tab.click();
2940
+ if (!state.chat || state.chat.activeTurn || state.chat.archivedAt || state.chat.state === 'recovery') {
2941
+ state.discoveryDraft = draft;
2942
+ state.choosingProvider = true;
2943
+ providerChooser();
2944
+ return;
2945
+ }
2946
+ const existing = ui.input.value.trim();
2947
+ ui.input.value = existing ? `${existing}\n\n${draft}` : draft;
2948
+ ui.input.dispatchEvent(new Event('input', { bubbles: true }));
2949
+ ui.input.focus();
2950
+ }
2951
+
2559
2952
  async function startProjectIntake(submissionId, payload) {
2560
2953
  await ensureSession();
2561
2954
  return request(`/api/chat/project-intakes/${encodeURIComponent(submissionId)}/start`, {
@@ -2599,6 +2992,7 @@
2599
2992
  closePicker();
2600
2993
  });
2601
2994
  ui.model.addEventListener('click', () => openPicker('model', ui.model, modelChoices()));
2995
+ ui.switchAccount.addEventListener('click', () => { void switchAccount(); });
2602
2996
  ui.effort.addEventListener('click', () => openPicker('effort', ui.effort, effortChoices()));
2603
2997
  ui.permission.addEventListener('click', () => openPicker('permission', ui.permission, permissionChoices()));
2604
2998
  ui.integrations.addEventListener('click', openIntegrations);
@@ -2622,7 +3016,10 @@
2622
3016
  ui.tab.addEventListener('click', () => markRead());
2623
3017
  document.addEventListener('visibilitychange', () => { if (!document.hidden) { markRead(); pollChats(); } });
2624
3018
  document.addEventListener('pointerdown', (event) => {
2625
- if (!ui.picker.hidden && !ui.picker.contains(event.target) && !event.target.closest('.ai-chat-setting')) closePicker();
3019
+ // Switch account lives inside the Provider .ai-chat-setting but opens no picker of its own, so
3020
+ // it must not be treated as "clicked the picker's own control" and leave an open list behind.
3021
+ if (!ui.picker.hidden && !ui.picker.contains(event.target)
3022
+ && (!event.target.closest('.ai-chat-setting') || event.target.closest('.ai-chat-provider-switch'))) closePicker();
2626
3023
  });
2627
3024
  window.addEventListener('floless:chat-scope-changed', (event) => {
2628
3025
  const next = event.detail || null;
@@ -2641,7 +3038,7 @@
2641
3038
  state.refreshTimer = setInterval(pollChats, 5000);
2642
3039
  window.addEventListener('pagehide', () => { closeSource(); contextObserver.disconnect(); clearInterval(state.refreshTimer); clearTimeout(state.draftTimer); });
2643
3040
  window.flolessChat = {
2644
- refreshScope, refreshActivity, refreshIndex, startRequest, openConversation,
3041
+ refreshScope, refreshActivity, refreshIndex, startRequest, openConversation, openDraft,
2645
3042
  startProjectIntake, resumeProjectIntake,
2646
3043
  currentProvider: () => state.chat?.provider ?? null,
2647
3044
  };