@floless/app 0.149.1 → 0.151.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/floless-server.cjs +104263 -88361
  2. package/dist/schemas/drawing-check.profile.v1.schema.json +45 -2
  3. package/dist/schemas/steel.model.v2.schema.json +9 -0
  4. package/dist/skills/floless-app-approval/SKILL.md +79 -4
  5. package/dist/skills/floless-app-onboarding/SKILL.md +200 -87
  6. package/dist/skills/floless-app-onboarding/references/aware-runtime.md +27 -18
  7. package/dist/skills/floless-app-onboarding/references/floless-surfaces.md +207 -0
  8. package/dist/skills/floless-app-routines/SKILL.md +4 -1
  9. package/dist/skills/floless-app-routines/references/routines-api.md +14 -2
  10. package/dist/skills/floless-app-steel-model/SKILL.md +4 -2
  11. package/dist/skills/floless-app-steel-takeoff/SKILL.md +14 -9
  12. package/dist/skills/floless-app-workflows/SKILL.md +2 -2
  13. package/dist/templates/tekla-parser.flo +13 -3
  14. package/dist/web/agents.js +983 -0
  15. package/dist/web/app.css +556 -43
  16. package/dist/web/app.js +34 -112
  17. package/dist/web/aware.js +1774 -169
  18. package/dist/web/chat.css +62 -1
  19. package/dist/web/chat.js +1666 -59
  20. package/dist/web/commands-drawing-check.js +15 -0
  21. package/dist/web/commands-revit.js +5 -0
  22. package/dist/web/commands-shell.js +955 -53
  23. package/dist/web/commands-tekla-parser.js +8 -1
  24. package/dist/web/connections.js +57 -14
  25. package/dist/web/drawing-check-editor.html +10 -2
  26. package/dist/web/drawing-check-editor.js +569 -40
  27. package/dist/web/drawing-check-overlay.js +45 -2
  28. package/dist/web/guide.js +675 -0
  29. package/dist/web/index.html +162 -31
  30. package/dist/web/instructor.js +91 -8
  31. package/dist/web/leave-guard.js +1 -0
  32. package/dist/web/left-pane.js +20 -1
  33. package/dist/web/local-discovery.js +12 -2
  34. package/dist/web/model-editor.css +32 -32
  35. package/dist/web/model-panel-bridge.js +11 -3
  36. package/dist/web/model-viewport-lighting.js +4 -2
  37. package/dist/web/model-viewport-revit-adapter.js +3 -0
  38. package/dist/web/model-viewport-toolbar.js +6 -3
  39. package/dist/web/model-viewport.js +11 -1
  40. package/dist/web/revit-editor.css +14 -14
  41. package/dist/web/revit-editor.js +64 -12
  42. package/dist/web/steel-3d-core.js +133 -0
  43. package/dist/web/steel-3d-view.js +10 -0
  44. package/dist/web/steel-editor.html +171 -39
  45. package/dist/web/steel-model-v2-client-validation.js +11 -0
  46. package/dist/web/steel-model-v2-commands.js +80 -5
  47. package/dist/web/tool-updates.js +533 -0
  48. package/dist/web/workspaces.js +896 -123
  49. package/package.json +2 -2
  50. package/dist/skills/floless-app-onboarding/references/floless-app-tour.md +0 -156
package/dist/web/chat.js CHANGED
@@ -19,7 +19,7 @@
19
19
  historyToggle: el('chat-history-toggle'), newChat: el('chat-new'), refresh: el('chat-refresh'), history: el('chat-history'),
20
20
  title: el('chat-title'), rename: el('chat-rename'), scope: el('chat-scope'), settingsToggle: el('chat-settings-toggle'),
21
21
  settings: el('chat-settings'), provider: el('chat-provider'), switchAccount: el('chat-switch-account'), model: el('chat-model'),
22
- effort: el('chat-effort'), permission: el('chat-permission'), integrations: el('chat-integrations'), ownConnectors: el('chat-own-connectors'),
22
+ effort: el('chat-effort'), permission: el('chat-permission'), guideAccess: el('chat-guide-access'), integrations: el('chat-integrations'), ownConnectors: el('chat-own-connectors'),
23
23
  desktopValue: el('chat-desktop-value'), desktopReason: el('chat-desktop-reason'), picker: el('chat-picker'),
24
24
  feed: el('chat-feed'), offscreenActivity: el('chat-offscreen-activity'), recovery: el('chat-recovery'),
25
25
  approvalTray: el('chat-approval-tray'), recoveryCopy: el('chat-recovery-copy'),
@@ -31,19 +31,28 @@
31
31
  context: el('left-chat-context'),
32
32
  teklaChip: el('chat-tekla-context'),
33
33
  connectors: el('chat-connectors'),
34
+ changeAllowance: el('chat-change-allowance'),
35
+ scopeControls: el('chat-scope-controls'), scopeToggle: el('chat-scope-toggle'),
36
+ scopePicker: el('chat-scope-picker'), scopeDisclosure: el('chat-scope-disclosure'),
37
+ checkAllowance: el('chat-check-allowance'),
34
38
  workspaceUnits: el('chat-units'),
39
+ moveNotice: el('chat-move-notice'), moveCopy: el('chat-move-copy'), movePrimary: el('chat-move-primary'),
40
+ moveSecondary: el('chat-move-secondary'), moveDismiss: el('chat-move-dismiss'),
35
41
  };
36
42
 
37
43
  const state = {
44
+ scopeView: null, scopeViewChatId: null, scopeChoice: null, scopeEditing: false, scopePickerOpen: false,
38
45
  // signInPending is keyed by provider: a wait started in one conversation must not paint an
39
46
  // unrelated conversation's button as Waiting for sign-in… for the next two minutes.
40
47
  // #1798: the chat owner's display units as the server last answered them (null = not known yet), and the
41
48
  // generation that answer belongs to. Receipts show recorded kilograms until they are known.
42
49
  displayUnits: null, displayUnitsGeneration: 0,
50
+ // #1890 PR 3b: the workspace history's pointer rows, the move notice on screen, and moves being followed now.
51
+ movedChats: [], movedChatsKnown: null, moveNotice: null, moveNoticeTimer: null, followingMoves: new Set(), movingPoll: null,
43
52
  sessionReady: false, scope: null, chats: [], archivedChats: [], unreadableChats: [], chat: null, events: [], capability: null, signInPending: new Set(), desktop: null,
44
53
  source: null, eventReconnectTimer: null, eventReconnectAttempt: 0, eventReconnectChatId: null, attachments: [], imageLimitChatId: null, followupSubmitting: false, followupUnknownId: null, resolvingFollowupIds: new Set(), retryingFollowupIds: new Set(), integrations: null, historyOpen: false, historyOpenings: 0, historyFilter: 'all', archivedHistoryOpen: false,
45
54
  instructorAnswers: [], historyLoading: false, historyRequestGeneration: 0, picker: null, loading: false,
46
- draftTimer: null, localDraft: null, backgroundDrafts: new Map(), draftWrites: new Map(), draftVersions: new Map(), unknownFollowups: new Map(), refreshTimer: null, scopeGeneration: 0, selectionGeneration: 0, choosingProvider: false,
55
+ draftTimer: null, localDraft: null, backgroundDrafts: new Map(), draftWrites: new Map(), draftVersions: new Map(), unknownFollowups: new Map(), refreshTimer: null, scopeGeneration: 0, selectionGeneration: 0, openInGeneration: 0, choosingProvider: false,
47
56
  answerJump: null, answerJumpTimer: null, scopeInitialized: false, renaming: null, historyRename: null, pendingSubmissionId: null, recoveryMessage: null, recoveryCanEnd: false,
48
57
  stream: null, liveStatusTurnId: null, decidingApprovalIds: new Set(), revokingApprovalTurns: new Set(), uploadingChatIds: new Set(),
49
58
  // #1653 stage 4: this chat owner's (project or workflow, #1890) questions linked to live Tekla parts, the card's open lists, and the receipt showing it.
@@ -78,8 +87,9 @@
78
87
  }).observe(tray);
79
88
  }
80
89
  keepApprovalTrayDecisionVisible(ui.approvalTray);
90
+ // #2037: safest to widest; Auto is the default for a project or workflow conversation.
81
91
  const permissionLabels = {
82
- 'read-only': 'Read only', 'workspace-write': 'Working folder write', 'full-access': 'Full access',
92
+ 'read-only': 'Read only', auto: 'Auto', 'workspace-write': 'Working folder write', 'full-access': 'Full access',
83
93
  };
84
94
  const providerLabels = { claude: 'Claude', codex: 'Codex' };
85
95
  // The one sign-in refusal FloLess re-words. 'chat-turn-active' is the same code every other chat
@@ -147,6 +157,11 @@
147
157
  error.reason = body?.reason || null;
148
158
  error.recovery = Array.isArray(body?.recovery) ? body.recovery : null;
149
159
  error.status = response.status;
160
+ // #1890 PR 3b: the conversation moved — wherever this was asked from, the open tab follows it.
161
+ if (error.code === 'chat-moved' && body?.to?.chatId) {
162
+ error.movedTo = body.to;
163
+ queueMicrotask(() => { void followMovedChat(body.to); });
164
+ }
150
165
  throw error;
151
166
  }
152
167
  return body;
@@ -198,6 +213,11 @@
198
213
  // #1907: the server marks a not-sent reason it already wrote for the person; it is shown as is.
199
214
  if (code === 'chat-send-refused-plain' && raw) return raw;
200
215
  const codeMessages = {
216
+ // #1890 PR 3b: the server's own sentences name the workflow.
217
+ 'chat-moving': raw,
218
+ 'chat-moved': raw,
219
+ 'chat-arriving': raw,
220
+ 'chat-move-busy': raw,
201
221
  'chat-origin-refused': 'This chat can only be used from the FloLess app. Reload the page and try again.',
202
222
  'chat-owner-stale': 'This conversation no longer matches the current project or workflow folder. Reopen the project or workflow, then try again.',
203
223
  'chat-cwd-stale': 'This conversation no longer matches the current project or workflow folder. Reopen the project or workflow, then try again.',
@@ -356,6 +376,8 @@
356
376
  function capabilityMessage(provider, reason) {
357
377
  const label = providerLabels[provider] || 'AI service';
358
378
  const raw = String(reason || '');
379
+ // A check that timed out (this computer or FloLess was busy) says nothing about the AI: say that, not "not ready".
380
+ if (/timed out|took too long|computer was busy|\bis busy\b/i.test(raw)) return `FloLess couldn’t finish checking ${label} because this computer was busy. Try again in a moment.`;
359
381
  if (signInNeeded(raw)) return `Sign in to ${label} first.`;
360
382
  if (/EPERM|EACCES|ENOENT|ENOTDIR|operation not permitted|permission denied|watch ['"]/i.test(raw)) {
361
383
  return 'FloLess cannot open this conversation’s project or workflow folder. Restore or reconnect that folder, then try again.';
@@ -371,6 +393,8 @@
371
393
 
372
394
  function report(error, prefix = '', messages = null) {
373
395
  const code = String(error && error.code || '');
396
+ // #1890 PR 3b: a conversation that moved is not a failure — request() already follows it into its workflow.
397
+ if (code === 'chat-moved' && error?.movedTo) return;
374
398
  const message = `${prefix}${prefix ? ': ' : ''}${messages?.[code] || errorMessage(error)}`;
375
399
  // Keep the raw cause (#1604): the user-facing sentence deliberately drops it, and without it a
376
400
  // failure could only be diagnosed from the server log. A timeout, a network failure or a server
@@ -536,13 +560,15 @@
536
560
  const dashboardVisible = document.getElementById('dashboard')?.hidden === false;
537
561
  // #1890: the Workflows landing (the list of workflows), not the canvas of the workflow loaded underneath.
538
562
  const workflowLanding = document.getElementById('wf-landing')?.hidden === false;
539
- const surface = reportOpen ? (threeDimensionalReport ? '3d-report' : 'report')
563
+ // #2007: the Agents tab is its own surface; where you are adds context only.
564
+ const agentsMode = document.body.classList.contains('mode-agents');
565
+ const surface = agentsMode && !reportOpen ? (window.flolessAgents?.surface?.() || 'agent-list') : reportOpen ? (threeDimensionalReport ? '3d-report' : 'report')
540
566
  : editorOpen ? 'model-editor'
541
567
  : workspaceMode ? (workspaceProjectOpen ? workspaceSurface : 'project-list')
542
568
  : workflowLanding ? 'workflow-list' : dashboardVisible ? 'dashboard' : 'workflow-canvas';
543
569
  if (options.surfaceOnly) return { surface };
544
570
  return {
545
- mode: workspaceMode ? 'workspaces' : workflowMode ? 'workflows' : 'canvas',
571
+ mode: agentsMode ? 'agents' : workspaceMode ? 'workspaces' : workflowMode ? 'workflows' : 'canvas',
546
572
  surface,
547
573
  activity: workflowRunning ? 'workflow-running' : 'idle',
548
574
  visibleText: visibleFloLessSurfaceText(surface),
@@ -575,6 +601,7 @@
575
601
  case 'project-knowledge': return shellText('ws-knowledge');
576
602
  case 'project-list': return shellText('ws-landing');
577
603
  case 'workflow-list': return shellText('wf-landing');
604
+ case 'agent-list': case 'agent-page': return shellText('agents-surface');
578
605
  case 'workflow-canvas': return shellText('canvas-main', 'inspect');
579
606
  case 'dashboard': return shellText('dashboard');
580
607
  case 'report': return boundedVisibleText(readVisibleFrameText('report-frame'), shellText('report-title', 'report-sub', 'report-overlay'));
@@ -589,7 +616,7 @@
589
616
  'drawing-filter': 'Drawing Filter', 'project-model': 'project model', 'project-exports': 'project exports',
590
617
  'project-history': 'project history', 'project-knowledge': 'project Knowledge', 'project-list': 'project list',
591
618
  'workflow-canvas': 'workflow canvas', dashboard: 'dashboard', report: 'report', '3d-report': '3D report',
592
- 'model-editor': 'model editor', 'workflow-list': 'workflow list',
619
+ 'model-editor': 'model editor', 'workflow-list': 'workflow list', 'agent-list': 'list of agents', 'agent-page': 'agent page',
593
620
  };
594
621
  return `${labels[context.surface] || 'FloLess'} · visible state${context.activity === 'workflow-running' ? ' · workflow running' : ''}`;
595
622
  }
@@ -779,6 +806,21 @@
779
806
  ui.disclosure.hidden = options.opening === true || Boolean(state.chat) || !state.scope?.owner;
780
807
  }
781
808
 
809
+ // Everything a conversation paints above the composer is painted from `state.chat`, which is null on the
810
+ // chooser. Repaint each one so none of it is left over from another conversation: the pending approval card
811
+ // and its Deny / Approve buttons (#1958 — they did nothing, with no chat to decide on, and the shell still
812
+ // reported an approval waiting), the "Auto-approval on" scope card, the library chip ("added to this chat"),
813
+ // the "connectors are on" line and allowances (#1907), the allowed changes (#1890) and checks (#1956), and the
814
+ // scope control. Each paints itself back when its conversation is opened again.
815
+ function clearOtherConversationLines() {
816
+ paintApproval();
817
+ paintTeklaChip();
818
+ paintConnectorAllowance();
819
+ paintChangeAllowance();
820
+ paintScopeControl();
821
+ paintCheckAllowance();
822
+ }
823
+
782
824
  function providerChooser() {
783
825
  paintComposerDisclosure();
784
826
  // Without a conversation owner there is no provider, history, or refresh to offer: none of those
@@ -787,6 +829,11 @@
787
829
  // conversation must go with it — and so must the previous conversation's units line.
788
830
  shell.querySelector('.ai-chat-runtime')?.remove(); stopRuntimePoll();
789
831
  if (ui.workspaceUnits) { ui.workspaceUnits.hidden = true; ui.workspaceUnits.replaceChildren(); delete ui.workspaceUnits.dataset.painted; }
832
+ // And its recovery banner, with its Stop response / Check again (#1921). The banner is painted from
833
+ // the selected conversation, so it is repainted here — on every way onto the chooser, not only + New
834
+ // conversation — and paints itself back when that conversation is opened again.
835
+ paintRecovery();
836
+ clearOtherConversationLines();
790
837
  if (!state.scope?.owner) { showUnscoped(); return; }
791
838
  ui.feed.replaceChildren();
792
839
  updateOffscreenActivity();
@@ -984,7 +1031,7 @@
984
1031
  clearProviderChoice();
985
1032
  closeSource();
986
1033
  clearLiveStream(true);
987
- state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.chat = null; state.events = []; state.capability = null; state.attachments = []; state.followupUnknownId = null;
1034
+ state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.movedChats = []; state.movedChatsKnown = null; state.chat = null; state.events = []; state.capability = null; state.attachments = []; state.followupUnknownId = null;
988
1035
  ui.feed.replaceChildren();
989
1036
  updateOffscreenActivity();
990
1037
  const empty = document.createElement('div');
@@ -1169,8 +1216,10 @@
1169
1216
  const archivedChats = state.archivedChats.filter((chat) => Boolean(chat.archivedAt));
1170
1217
  const unreadableChats = state.unreadableChats || [];
1171
1218
  if (unreadableChats.length) appendUnreadableChats(unreadableChats, ui.history);
1219
+ const movedChats = state.scope.owner.kind === 'workspace' ? (state.movedChats || []) : [];
1220
+ if (movedChats.length) appendMovedChats(movedChats, ui.history);
1172
1221
  if (!state.chats.length && !archivedChats.length) {
1173
- if (unreadableChats.length) { restoreHistoryFocus(focusedCommand); return; }
1222
+ if (unreadableChats.length || movedChats.length) { restoreHistoryFocus(focusedCommand); return; }
1174
1223
  const empty = document.createElement('div'); empty.className = 'ai-chat-history-empty';
1175
1224
  empty.textContent = 'No conversations here yet.';
1176
1225
  ui.history.append(empty); return;
@@ -1280,6 +1329,240 @@
1280
1329
  // A conversation whose saved file is damaged (#1619). The server knows nothing trustworthy about it
1281
1330
  // beyond its id — no title, no provider — so the row says what happened and offers the one thing
1282
1331
  // that can be done here. It opens nothing, so it is not a button; only Discard acts.
1332
+ /*
1333
+ * #1890 PR 3b: a conversation that moved into the workflow it built. Its old home keeps a pointer row that opens it
1334
+ * there; a row whose new home is gone says so and offers Remove (the pointer only, never a conversation).
1335
+ */
1336
+ function appendMovedChats(entries, destination) {
1337
+ const group = document.createElement('section'); group.className = 'ai-chat-history-group ai-chat-history-moved';
1338
+ group.setAttribute('aria-label', 'Conversations that moved into a workflow');
1339
+ const label = document.createElement('div'); label.className = 'ai-chat-history-label'; label.textContent = 'Moved';
1340
+ group.append(label);
1341
+ for (const entry of entries) {
1342
+ if (entry.targetGone) {
1343
+ const row = document.createElement('div');
1344
+ row.className = 'ai-chat-history-row unreadable moved-gone';
1345
+ row.dataset.chatId = entry.chatId;
1346
+ const title = document.createElement('span'); title.className = 'ai-chat-history-title'; title.textContent = entry.title;
1347
+ const meta = document.createElement('span'); meta.className = 'ai-chat-history-meta';
1348
+ meta.textContent = 'This conversation’s workflow is no longer here.';
1349
+ const actions = document.createElement('span'); actions.className = 'ai-chat-history-actions always-on';
1350
+ const remove = document.createElement('button');
1351
+ remove.type = 'button'; remove.className = 'ai-chat-history-moved-remove'; remove.textContent = 'Remove';
1352
+ remove.dataset.commandId = `shell.chat-moved-remove#${entry.chatId}`;
1353
+ remove.dataset.commandInstanceLabel = entry.title;
1354
+ remove.setAttribute('aria-label', `Remove ${entry.title}`);
1355
+ remove.dataset.tip = 'Removes only this row';
1356
+ remove.addEventListener('click', (event) => { event.preventDefault(); event.stopPropagation(); void removeMovedPointer(entry, remove); });
1357
+ actions.append(remove);
1358
+ row.append(title, meta, actions);
1359
+ group.append(row);
1360
+ continue;
1361
+ }
1362
+ const row = button('', `shell.chat-moved-open#${entry.chatId}`, 'ai-chat-history-row moved');
1363
+ row.dataset.commandInstanceLabel = `${entry.title} · ${entry.to.label}`;
1364
+ row.setAttribute('aria-label', `${entry.title}, moved to workflow ${entry.to.label}. Open it there`);
1365
+ const title = document.createElement('span'); title.className = 'ai-chat-history-title'; title.textContent = entry.title;
1366
+ const meta = document.createElement('span'); meta.className = 'ai-chat-history-meta'; meta.textContent = `Moved to workflow ${entry.to.label}`;
1367
+ row.append(title, meta);
1368
+ row.addEventListener('click', () => { void openMovedChat(movedTarget(entry)).catch((error) => report(error, 'Could not open that conversation')); });
1369
+ group.append(row);
1370
+ }
1371
+ destination.append(group);
1372
+ }
1373
+
1374
+ async function removeMovedPointer(entry, trigger) {
1375
+ const snapshot = captureScope();
1376
+ if (!snapshot) return;
1377
+ trigger.hidden = true;
1378
+ try {
1379
+ await request(`/api/chat/conversations/${encodeURIComponent(entry.chatId)}/moved-pointer`, {
1380
+ method: 'DELETE', body: JSON.stringify({ owner: snapshot.scope.owner }),
1381
+ });
1382
+ if (!sameScope(snapshot.scope, snapshot.generation)) return;
1383
+ state.movedChats = (state.movedChats || []).filter((item) => item.chatId !== entry.chatId);
1384
+ paintHistory();
1385
+ announce(`Removed ${entry.title} from this list.`);
1386
+ (ui.history.querySelector('.ai-chat-history-row:not(.unreadable)') || ui.history.querySelector('button'))?.focus();
1387
+ } catch (error) {
1388
+ trigger.hidden = false;
1389
+ report(error, 'Could not remove that row');
1390
+ }
1391
+ }
1392
+
1393
+ /** New pointer rows since the last history read: a conversation not on screen moved — say so, with Open workflow. */
1394
+ function noteMovedChats(rows) {
1395
+ const list = Array.isArray(rows) ? rows : [];
1396
+ const known = state.movedChatsKnown;
1397
+ state.movedChats = list;
1398
+ state.movedChatsKnown = new Set(list.map((row) => row.chatId));
1399
+ if (!known) return;
1400
+ const fresh = list.find((row) => !known.has(row.chatId) && !row.targetGone && !state.followingMoves.has(row.chatId));
1401
+ if (!fresh) return;
1402
+ showMoveNotice({
1403
+ neutral: true, text: `${fresh.title} moved into workflow ${fresh.to.label}.`,
1404
+ primary: { label: 'Open workflow', command: 'shell.chat-move-open', run: () => openMovedChat(movedTarget(fresh)) }, dismiss: true,
1405
+ });
1406
+ announce(`${fresh.title} moved into workflow ${fresh.to.label}.`);
1407
+ }
1408
+
1409
+ /** Where a pointer row's conversation lives now, in the shape the server's "moved" answer uses. */
1410
+ function movedTarget(pointer) {
1411
+ return { owner: { kind: 'workflow', workflowId: pointer.to.workflowId }, chatId: pointer.chatId, label: pointer.to.label };
1412
+ }
1413
+
1414
+ /**
1415
+ * #2007: show one conversation of any owner — an agent run's — without the location changing. Loads that owner's
1416
+ * history when it is not the one on screen, then selects the conversation. The last call wins.
1417
+ */
1418
+ async function openConversationIn(scope, chatId) {
1419
+ const ticket = ++state.openInGeneration;
1420
+ if (!scope?.owner || typeof chatId !== 'string') return false;
1421
+ if (scopeKey(scope) !== scopeKey(state.scope)) await loadScope({ ...scope, chatId });
1422
+ else if (scope.label && state.scope && scope.label !== state.scope.label) { state.scope = { ...state.scope, label: scope.label }; ui.scope.textContent = scope.label; }
1423
+ if (ticket !== state.openInGeneration) return false;
1424
+ if (state.chat?.chatId !== chatId) await selectConversation(chatId, { replaceProviderChoice: true, focus: false });
1425
+ return ticket === state.openInGeneration && state.chat?.chatId === chatId;
1426
+ }
1427
+
1428
+ /** Open a moved conversation in its new home: the workflow (published or draft), then the conversation there. */
1429
+ async function openMovedChat(to) {
1430
+ const bridge = window.flolessBridge;
1431
+ if (typeof bridge?.openOwnedWorkflow !== 'function') throw new Error('Open the workflow from Workflows to see this conversation.');
1432
+ await bridge.openOwnedWorkflow(to.owner.workflowId);
1433
+ await refreshScope(true);
1434
+ if (state.scope?.owner?.kind !== 'workflow' || state.scope.owner.workflowId !== to.owner.workflowId) return false;
1435
+ await selectConversation(to.chatId, { replaceProviderChoice: true, focus: false });
1436
+ return true;
1437
+ }
1438
+
1439
+ /*
1440
+ * The conversation on screen moved (its stream said so, or a request was answered 410): follow it into the workflow,
1441
+ * keep the person's unsent text — it wins over the copied draft — and keep their focus where it was.
1442
+ */
1443
+ async function followMovedChat(to) {
1444
+ const chatId = to?.chatId;
1445
+ if (!chatId || state.followingMoves.has(chatId)) return;
1446
+ if (state.chat?.chatId !== chatId || state.scope?.owner?.kind !== 'workspace') return;
1447
+ state.followingMoves.add(chatId);
1448
+ // The newest text the person typed wins — including anything typed while the workflow opens. Loading clears the
1449
+ // box without an input event, so only the person's own typing updates this.
1450
+ let draft = ui.input.value;
1451
+ let typed = false;
1452
+ const keepTyping = () => { draft = ui.input.value; typed = true; };
1453
+ ui.input.addEventListener('input', keepTyping);
1454
+ const hadFocus = document.activeElement === ui.input || ui.feed.contains(document.activeElement);
1455
+ closeSource();
1456
+ try {
1457
+ let opened;
1458
+ try { opened = await openMovedChat(to); } finally { ui.input.removeEventListener('input', keepTyping); }
1459
+ if (!opened) return;
1460
+ if ((draft || typed) && state.chat?.chatId === chatId && ui.input.value !== draft) {
1461
+ ui.input.value = draft; autosize(); saveDraftSoon(); updateSendState();
1462
+ }
1463
+ if (hadFocus && state.chat?.chatId === chatId) ui.input.focus({ preventScroll: true });
1464
+ showMoveNotice({ neutral: true, text: `This conversation moved into workflow ${to.label}.`, autoDismissMs: 8000 });
1465
+ announce(`This conversation moved into workflow ${to.label}.`);
1466
+ } catch (error) {
1467
+ report(error, 'Could not open the workflow this conversation moved into');
1468
+ } finally { state.followingMoves.delete(chatId); }
1469
+ }
1470
+
1471
+ /*
1472
+ * While the conversation on screen moves: look at the history list, never at the conversation itself — once the move
1473
+ * lands its old address answers "moved", which the browser would log as a failed request. The list says either that it
1474
+ * is still moving (its row) or where it went (its pointer row), and the tab follows from the pointer.
1475
+ */
1476
+ async function checkMoveProgress(chatId) {
1477
+ const snapshot = captureChat();
1478
+ if (!snapshot || snapshot.chatId !== chatId) return;
1479
+ let listed;
1480
+ try { listed = await request(`/api/chat/conversations?${ownerQuery(snapshot.scope.owner)}`); }
1481
+ catch { if (sameChat(snapshot)) updateSendState(); return; }
1482
+ if (!sameChat(snapshot)) return;
1483
+ const pointer = (listed.movedChats || []).find((row) => row.chatId === chatId);
1484
+ if (pointer) {
1485
+ void followMovedChat(movedTarget(pointer));
1486
+ return;
1487
+ }
1488
+ const row = (listed.chats || []).find((item) => item.chatId === chatId);
1489
+ if (row && state.chat) {
1490
+ state.chat = { ...state.chat, ...row };
1491
+ paintConversation();
1492
+ }
1493
+ updateSendState();
1494
+ }
1495
+
1496
+ function showMoveNotice(notice) {
1497
+ clearTimeout(state.moveNoticeTimer);
1498
+ state.moveNotice = notice;
1499
+ if (notice?.autoDismissMs) {
1500
+ state.moveNoticeTimer = setTimeout(() => { if (state.moveNotice === notice) { state.moveNotice = null; paintMoveNotice(); } }, notice.autoDismissMs);
1501
+ }
1502
+ paintMoveNotice();
1503
+ }
1504
+
1505
+ /** A waiting move with a warning, for the conversation on screen: the sentence and the person's choices. */
1506
+ function moveNoticeForChat(chat) {
1507
+ const rehome = chat?.rehome;
1508
+ if (!rehome || state.scope?.owner?.kind !== 'workspace' || rehome.state !== 'pending' || !rehome.warning) return null;
1509
+ const keep = { label: 'Keep it here', command: 'shell.chat-move-keep', run: () => keepConversationHere(chat.chatId) };
1510
+ const retry = { label: 'Try again', command: 'shell.chat-move-retry', run: () => retryConversationMove(chat.chatId) };
1511
+ return rehome.targetGone
1512
+ ? { neutral: false, text: rehome.warning, primary: keep, secondary: retry, chatId: chat.chatId }
1513
+ : { neutral: false, text: rehome.warning, primary: retry, chatId: chat.chatId };
1514
+ }
1515
+
1516
+ function paintMoveNotice() {
1517
+ if (!ui.moveNotice) return;
1518
+ const notice = (state.moveBusy && state.moveBusy.chatId === state.chat?.chatId ? state.moveBusy : null)
1519
+ || moveNoticeForChat(state.chat) || state.moveNotice;
1520
+ ui.moveNotice.hidden = !notice;
1521
+ if (!notice) return;
1522
+ ui.moveNotice.classList.toggle('neutral', Boolean(notice.neutral));
1523
+ const text = notice.busyText || notice.text;
1524
+ if (ui.moveCopy.textContent !== text) ui.moveCopy.textContent = text;
1525
+ for (const [control, action] of [[ui.movePrimary, notice.primary], [ui.moveSecondary, notice.secondary]]) {
1526
+ // A choice that cannot apply right now is hidden, not disabled.
1527
+ control.hidden = !action || Boolean(notice.busyText);
1528
+ if (!action) continue;
1529
+ control.textContent = action.label;
1530
+ control.dataset.commandId = action.command;
1531
+ control.onclick = () => { void runMoveAction(notice, action); };
1532
+ }
1533
+ ui.moveDismiss.hidden = !notice.dismiss;
1534
+ ui.moveDismiss.onclick = () => { state.moveNotice = null; paintMoveNotice(); ui.input.focus({ preventScroll: true }); };
1535
+ }
1536
+
1537
+ async function runMoveAction(notice, action) {
1538
+ state.moveBusy = { ...notice, chatId: notice.chatId ?? state.chat?.chatId ?? null, busyText: action.label === 'Try again' ? 'Trying again…' : 'One moment…' };
1539
+ paintMoveNotice();
1540
+ try { await action.run(); }
1541
+ catch (error) { report(error, 'Could not do that'); }
1542
+ finally {
1543
+ state.moveBusy = null;
1544
+ if (state.moveNotice === notice) state.moveNotice = null;
1545
+ paintMoveNotice();
1546
+ }
1547
+ }
1548
+
1549
+ async function retryConversationMove(chatId) {
1550
+ const snapshot = captureChat();
1551
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(chatId)}/move/retry`, {
1552
+ method: 'POST', body: JSON.stringify({ owner: { kind: 'workspace' } }),
1553
+ });
1554
+ if (result?.outcome !== 'moved' && snapshot && sameChat(snapshot)) await refreshConversation(chatId, false);
1555
+ }
1556
+
1557
+ async function keepConversationHere(chatId) {
1558
+ await request(`/api/chat/conversations/${encodeURIComponent(chatId)}/move/keep`, {
1559
+ method: 'POST', body: JSON.stringify({ owner: { kind: 'workspace' } }),
1560
+ });
1561
+ await refreshConversation(chatId, false);
1562
+ announce('This conversation stays in the workspace.');
1563
+ ui.input.focus({ preventScroll: true });
1564
+ }
1565
+
1283
1566
  function appendUnreadableChats(entries, destination) {
1284
1567
  const group = document.createElement('section'); group.className = 'ai-chat-history-group ai-chat-history-unreadable';
1285
1568
  group.setAttribute('aria-label', 'Conversations that can’t be opened');
@@ -1933,6 +2216,407 @@
1933
2216
  return item;
1934
2217
  }
1935
2218
 
2219
+ /** A refusal FloLess wrote for the person (`plain`), shown as is: what happened, why, and what to do next. */
2220
+ function renderPlainNotice(event) {
2221
+ const item = document.createElement('div');
2222
+ // #2037: a Codex auto-review decision is a receipt, not a failure: approved is information, held back is a notice.
2223
+ const review = event.payload?.tool === 'auto-review' ? event.payload.decision : null;
2224
+ // #2035: a step declined because nobody was watching a scheduled run is a notice the person reads later, not an error.
2225
+ const unattended = event.payload?.tool === 'unattended-decline';
2226
+ item.className = review === 'approved' ? 'ai-chat-event auto-review' : review || unattended ? 'ai-chat-event auto-review held' : 'ai-chat-event error';
2227
+ item.dataset.eventSequence = String(event.sequence);
2228
+ item.dataset.eventId = event.eventId;
2229
+ const label = document.createElement('strong');
2230
+ label.textContent = review === 'approved' ? 'Auto-approved' : review ? 'Held back' : unattended ? 'Declined' : 'Not done';
2231
+ item.append(label, document.createTextNode(` · ${event.payload.message}`));
2232
+ return item;
2233
+ }
2234
+
2235
+ /** #2007: the first line of an agent run — who started it and the scope it was given. Information, not a refusal. */
2236
+ function renderAgentRunLine(event) {
2237
+ const item = document.createElement('div');
2238
+ item.className = 'ai-chat-event connector agent-run';
2239
+ item.dataset.eventSequence = String(event.sequence);
2240
+ item.dataset.eventId = event.eventId;
2241
+ const label = document.createElement('strong');
2242
+ label.textContent = event.payload.tool === 'guide' ? 'FloLess' : 'Agent run';
2243
+ item.append(label, document.createTextNode(` · ${String(event.payload.message || '')}`));
2244
+ return item;
2245
+ }
2246
+
2247
+ function renderChangeReceipt(event) {
2248
+ const item = document.createElement('div');
2249
+ item.className = 'ai-chat-event connector';
2250
+ item.dataset.eventSequence = String(event.sequence);
2251
+ item.dataset.eventId = event.eventId;
2252
+ const change = event.payload.change;
2253
+ const label = document.createElement('strong');
2254
+ if (event.payload.reason) {
2255
+ label.textContent = 'Not changed';
2256
+ 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.'));
2257
+ return item;
2258
+ }
2259
+ label.textContent = event.payload.coveredBy === 'create' ? 'Part of creating the workflow' : 'Allowed for this chat';
2260
+ // The receipt records the approval FloLess gave; whether the file was then written is the AI's own reply to report.
2261
+ const owners = Array.isArray(change?.owners) ? change.owners : [];
2262
+ const paths = owners.flatMap((owner) => owner.paths || []);
2263
+ const detail = paths.length === 1 ? `Approved a change to ${paths[0]}`
2264
+ : owners.length === 1 ? `Approved changes to ${paths.length} files in ${owners[0].label}` : `Approved changes to ${paths.length} files in ${changeNames(change)}`;
2265
+ item.append(label, document.createTextNode(` · ${detail}`));
2266
+ return item;
2267
+ }
2268
+
2269
+ /*
2270
+ * #1900 — the AI suggests connecting something to FloLess. The card never connects anything: every button is the
2271
+ * person's own act on a part A surface (Check it works, or Integrations). It shows what is connected NOW, read live
2272
+ * from /api/connections/services when painted and again when the person comes back to it, never the state the AI saw.
2273
+ * The feed repaints on every streamed word, so each card is painted once per state and reused: a check in progress,
2274
+ * its inline question and its result all live in the card itself and survive the repaint.
2275
+ */
2276
+ const connectionCards = new Map();
2277
+ const CONNECTION_CARDS_KEPT = 200;
2278
+ const connectionLive = { services: null, loading: false, loadedAt: 0, error: '' };
2279
+ const connectionsApi = () => window.flolessConnections || null;
2280
+
2281
+ /** Re-reads what is connected (and the latest checks) when the copy on screen is older than `maxAgeMs`. */
2282
+ function refreshConnectionLive(maxAgeMs = 15000) {
2283
+ const api = connectionsApi();
2284
+ if (!api || connectionLive.loading) return;
2285
+ if (connectionLive.loadedAt && Date.now() - connectionLive.loadedAt < maxAgeMs) return;
2286
+ connectionLive.loading = true;
2287
+ Promise.all([api.loadServices(), api.loadReceipts()])
2288
+ .then(([services]) => { connectionLive.services = services; connectionLive.error = ''; })
2289
+ .catch((error) => { connectionLive.error = api.sentenceOf(error); })
2290
+ .finally(() => { connectionLive.loading = false; connectionLive.loadedAt = Date.now(); repaintConnectionCards(); });
2291
+ }
2292
+
2293
+ function repaintConnectionCards() {
2294
+ for (const old of ui.feed?.querySelectorAll('.ai-chat-connection-card[data-proposal-id]') || []) {
2295
+ const event = state.events.find((known) => known.eventId === old.dataset.eventId);
2296
+ if (!event) continue;
2297
+ const next = renderConnectionProposal(event);
2298
+ if (next !== old) {
2299
+ const focused = old.contains(document.activeElement) ? document.activeElement.dataset.commandId : null;
2300
+ old.replaceWith(next);
2301
+ if (focused) [...next.querySelectorAll('[data-command-id]')].find((node) => node.dataset.commandId === focused && !node.disabled)?.focus({ preventScroll: true });
2302
+ }
2303
+ }
2304
+ }
2305
+
2306
+ window.addEventListener('focus', () => { if (ui.feed?.querySelector('.ai-chat-connection-card[data-proposal-id]')) refreshConnectionLive(0); });
2307
+
2308
+ /**
2309
+ * Did the person answer Not now to this target? Dismissal is per target. The newest Not now / Show again in the
2310
+ * transcript decides; with none loaded, the conversation record's own list does.
2311
+ */
2312
+ function connectionDismissed(target) {
2313
+ let latest = null;
2314
+ for (const event of state.events) {
2315
+ if (event.type === 'connection-proposal-update' && event.payload?.target === target) latest = event;
2316
+ }
2317
+ if (latest) return latest.payload.dismissed === true;
2318
+ return Array.isArray(state.chat?.connectionDismissals) && state.chat.connectionDismissals.some((row) => row.target === target);
2319
+ }
2320
+
2321
+ function renderConnectionProposal(event) {
2322
+ const payload = event.payload || {};
2323
+ const proposalId = String(payload.proposalId || event.eventId || '');
2324
+ refreshConnectionLive();
2325
+ let entry = connectionCards.get(proposalId);
2326
+ if (!entry) {
2327
+ entry = { node: null, signature: '', error: '', said: '', busy: false };
2328
+ connectionCards.set(proposalId, entry);
2329
+ while (connectionCards.size > CONNECTION_CARDS_KEPT) connectionCards.delete(connectionCards.keys().next().value);
2330
+ }
2331
+ const dismissed = connectionDismissed(payload.target);
2332
+ const services = connectionLive.services;
2333
+ const service = payload.targetKind === 'host' || !services ? null : services.find((row) => row.id === payload.target) || null;
2334
+ const alias = payload.targetKind === 'host' ? null : service?.choice?.source === 'floless' ? (service.choice.alias ?? null) : undefined;
2335
+ const receipt = payload.checkAgent && alias !== undefined ? connectionsApi()?.cachedReceipt(payload.checkAgent, alias) : null;
2336
+ const signature = JSON.stringify([event.eventId, dismissed, service, Boolean(services?.choicesUnreadable), Boolean(services),
2337
+ connectionLive.error, receipt?.probedAt || null, receipt?.state || null, entry.error, entry.busy]);
2338
+ if (entry.node && entry.signature === signature) return entry.node;
2339
+ // A check running, or its inline question open, lives in this node: keep it until it settles.
2340
+ if (entry.node && entry.node.querySelector('[aria-busy="true"], [aria-expanded="true"]')) return entry.node;
2341
+ entry.node = paintConnectionProposal(event, payload, proposalId, entry, { dismissed, service, alias });
2342
+ entry.signature = signature;
2343
+ return entry.node;
2344
+ }
2345
+
2346
+ function connectionButton(label, commandId, target, name, className = '') {
2347
+ const control = button(label, `${commandId}#${target}`, className);
2348
+ control.dataset.commandInstanceLabel = name;
2349
+ return control;
2350
+ }
2351
+
2352
+ function paintConnectionProposal(event, payload, proposalId, entry, { dismissed, service, alias }) {
2353
+ const api = connectionsApi();
2354
+ const target = String(payload.target || '');
2355
+ const name = String(payload.name || target || 'this');
2356
+ const card = document.createElement('section');
2357
+ card.className = 'ai-chat-filter-card ai-chat-connection-card';
2358
+ card.dataset.eventId = event.eventId;
2359
+ card.dataset.eventSequence = String(event.sequence);
2360
+ card.dataset.proposalId = proposalId;
2361
+ card.dataset.target = target;
2362
+ // Coming back to the card (after Integrations, say) reads what is connected again.
2363
+ card.addEventListener('focusin', () => refreshConnectionLive(3000));
2364
+ card.addEventListener('pointerenter', () => refreshConnectionLive(3000));
2365
+ const error = document.createElement('p');
2366
+ error.className = 'ai-chat-filter-note ai-chat-connection-error';
2367
+ error.setAttribute('role', 'status');
2368
+ error.textContent = entry.error;
2369
+ if (dismissed) {
2370
+ card.classList.add('is-dismissed');
2371
+ card.setAttribute('aria-label', `Suggestion to connect ${name}, set aside`);
2372
+ const line = document.createElement('div');
2373
+ line.className = 'ai-chat-connection-collapsed';
2374
+ const text = document.createElement('span');
2375
+ text.textContent = 'Not now — you can ask again any time';
2376
+ const again = connectionButton('Show again', 'shell.chat-connection-show-again', target, name);
2377
+ again.setAttribute('aria-label', `Show the suggestion to connect ${name} again`);
2378
+ again.dataset.tip = `Shows this card again, so you can connect ${name} or check it.`;
2379
+ again.disabled = entry.busy;
2380
+ again.addEventListener('click', () => { void setConnectionDismissed(event, false); });
2381
+ line.append(text, again);
2382
+ card.append(line, error);
2383
+ return card;
2384
+ }
2385
+ const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
2386
+ const title = document.createElement('strong');
2387
+ title.id = `chat-connection-title-${proposalId}`;
2388
+ title.textContent = `Would you like me to connect ${name} to FloLess?`;
2389
+ card.setAttribute('aria-labelledby', title.id);
2390
+ head.append(title);
2391
+ card.append(head);
2392
+ // The AI's own words: plain text only.
2393
+ const why = typeof payload.why === 'string' ? payload.why.trim() : '';
2394
+ if (why) {
2395
+ const reason = document.createElement('p'); reason.className = 'ai-chat-filter-why';
2396
+ reason.textContent = why;
2397
+ card.append(reason);
2398
+ }
2399
+ const stateLine = document.createElement('p'); stateLine.className = 'ai-chat-filter-note ai-chat-connection-state';
2400
+ const actions = document.createElement('div'); actions.className = 'ai-chat-filter-actions';
2401
+ const confirmHost = document.createElement('div'); confirmHost.className = 'conn-confirm-host';
2402
+ const receiptHost = document.createElement('div'); receiptHost.className = 'conn-receipt-host';
2403
+ receiptHost.setAttribute('role', 'status');
2404
+ const said = document.createElement('p'); said.className = 'ai-chat-filter-note ai-chat-connection-said';
2405
+ said.setAttribute('role', 'status');
2406
+ said.textContent = entry.said;
2407
+ const say = (text) => { entry.said = text; said.textContent = text; };
2408
+ const integrations = (label, commandId, tip, primary = false) => {
2409
+ const control = connectionButton(label, commandId, target, name, primary ? 'ai-chat-filter-apply' : '');
2410
+ control.setAttribute('aria-label', `${label}: open Integrations at ${name}`);
2411
+ control.dataset.tip = tip;
2412
+ control.addEventListener('click', () => {
2413
+ if (typeof window.openIntegrations === 'function') window.openIntegrations(target);
2414
+ else say('FloLess couldn’t open Integrations. Open it from the menu, then find ' + name + '.');
2415
+ });
2416
+ return control;
2417
+ };
2418
+ const check = (checkAlias, pinned) => {
2419
+ const control = api.checkButton({ commandId: 'shell.chat-connection-check', agent: payload.checkAgent, alias: checkAlias, label: name, receiptHost, confirmHost, announce: say,
2420
+ onReceipt: () => repaintConnectionCards(), ...pinned });
2421
+ control.classList.add('ai-chat-filter-apply');
2422
+ const latest = api.cachedReceipt(payload.checkAgent, checkAlias);
2423
+ if (latest) receiptHost.replaceChildren(api.receiptNode(latest));
2424
+ return control;
2425
+ };
2426
+ const services = connectionLive.services;
2427
+ let keyCode = null;
2428
+ if (payload.targetKind === 'host') {
2429
+ if (payload.checkAgent && api) {
2430
+ actions.append(check(null, {}));
2431
+ stateLine.textContent = receiptHost.childElementCount ? `The last check of ${name} is below.` : `${name} has not been checked yet. Check it works runs a read-only check on this computer.`;
2432
+ } else {
2433
+ stateLine.textContent = `FloLess can’t check ${name} from here. Open Discover Local Tools to connect it.`;
2434
+ }
2435
+ } else if (!api || (!services && connectionLive.error)) {
2436
+ stateLine.textContent = connectionLive.error || 'FloLess couldn’t load what is connected. Try again.';
2437
+ const retry = connectionButton('Try again', 'shell.chat-connection-retry', target, name);
2438
+ retry.dataset.tip = 'Reads again what is connected to FloLess.';
2439
+ retry.addEventListener('click', () => refreshConnectionLive(0));
2440
+ if (api) actions.append(retry);
2441
+ } else if (!services) {
2442
+ stateLine.textContent = 'Checking what is connected…';
2443
+ } else if (!service) {
2444
+ stateLine.textContent = `FloLess can’t find ${name} in its connections right now. Open Integrations to see what is connected.`;
2445
+ actions.append(integrations('Open Integrations', 'shell.chat-connection-connect', `Opens Integrations at ${name}.`, true));
2446
+ } else if (service.statusUnknown) {
2447
+ stateLine.textContent = `FloLess couldn’t read whether the key for ${name} is saved. Open Integrations to see it.`;
2448
+ actions.append(integrations('Open Integrations', 'shell.chat-connection-connect', `Opens Integrations at ${name}.`, true));
2449
+ } else if (service.kind === 'key' && !service.connected) {
2450
+ // A key is added in a terminal, never typed into FloLess: the command, and a button that copies it.
2451
+ const command = `aware credential put ${service.id}`;
2452
+ stateLine.textContent = `${name} needs a key from the service. Run this in a terminal, then paste your key when it asks:`;
2453
+ keyCode = document.createElement('code'); keyCode.className = 'conn-code ai-chat-connection-command';
2454
+ keyCode.textContent = command;
2455
+ const copyLabel = 'Copy the command';
2456
+ const copy = connectionButton(copyLabel, 'shell.chat-connection-copy-key', target, name, 'ai-chat-filter-apply');
2457
+ copy.setAttribute('aria-label', `Copy the command that adds your key for ${name}`);
2458
+ copy.dataset.tip = 'Copies the terminal command. FloLess never sees the key you paste.';
2459
+ copy.addEventListener('click', async () => {
2460
+ try {
2461
+ await navigator.clipboard.writeText(command);
2462
+ say('Command copied. Run it in a terminal, then paste your key when it asks.');
2463
+ } catch { say('FloLess couldn’t copy the command. Select it and copy it yourself.'); }
2464
+ });
2465
+ actions.append(copy);
2466
+ } else if (!services.choicesUnreadable && service.choice?.source === 'native') {
2467
+ // Their own Claude/Codex connection is the choice, whatever FloLess's own accounts look like (#1900 review): the
2468
+ // way out is Change account, never Connect or Reconnect of an account FloLess was told not to use.
2469
+ stateLine.textContent = `FloLess uses your Claude or Codex connection for ${name}. FloLess can’t see or check that connection.`;
2470
+ actions.append(integrations('Change account', 'shell.chat-connection-change-account', `Opens Integrations at ${name}, where you choose the account FloLess uses.`));
2471
+ } else if (api.signInExpired(service)) {
2472
+ stateLine.textContent = `The sign-in for ${name} expired. Reconnect it in Integrations, then check it works.`;
2473
+ actions.append(integrations('Reconnect', 'shell.chat-connection-connect', `Opens Integrations at ${name} so you can sign in again.`, true));
2474
+ } else if (!service.connected) {
2475
+ stateLine.textContent = `${name} is not connected yet. Connect opens Integrations, where you sign in.`;
2476
+ actions.append(integrations('Connect', 'shell.chat-connection-connect', `Opens Integrations at ${name} so you can connect it.`, true));
2477
+ } else if (services.choicesUnreadable) {
2478
+ stateLine.textContent = `FloLess couldn’t read which account it uses for ${name}. Open Integrations to choose it again.`;
2479
+ actions.append(integrations('Open Integrations', 'shell.chat-connection-change-account', `Opens Integrations at ${name}.`, true));
2480
+ } else if (service.choice?.source === 'floless') {
2481
+ stateLine.textContent = `FloLess uses ${service.choice.alias ? service.choice.alias : 'the default account'} for ${name}.`;
2482
+ // The card checks the CHOSEN account at the choice it was painted on: the server refuses a card that is out of date.
2483
+ if (payload.checkAgent && alias !== undefined) {
2484
+ actions.append(check(alias, { integration: target, expectedChoiceRevision: service.choice.revision }));
2485
+ }
2486
+ actions.append(integrations('Change account', 'shell.chat-connection-change-account', `Opens Integrations at ${name}, where you choose the account FloLess uses.`));
2487
+ } else {
2488
+ const count = (service.accounts || []).length;
2489
+ stateLine.textContent = `${count === 1 ? 'An account is' : `${count} accounts are`} already connected for ${name}, but FloLess hasn’t been told which one to use. Integrations is where you choose it.`;
2490
+ actions.append(
2491
+ integrations('Use existing connection', 'shell.chat-connection-use-existing', `Opens Integrations at ${name}, where you choose the account FloLess uses.`, true),
2492
+ integrations('Set up a separate connection', 'shell.chat-connection-set-up-separate', `Opens Integrations at ${name}, where you can connect another account for FloLess.`),
2493
+ );
2494
+ }
2495
+ const notNow = connectionButton('Not now', 'shell.chat-connection-not-now', target, name);
2496
+ notNow.setAttribute('aria-label', `Not now: don’t connect ${name}`);
2497
+ notNow.dataset.tip = `Sets this suggestion aside. The AI won’t suggest ${name} again in this chat unless you choose Show again.`;
2498
+ notNow.disabled = entry.busy;
2499
+ notNow.addEventListener('click', () => { void setConnectionDismissed(event, true); });
2500
+ actions.append(notNow);
2501
+ card.append(stateLine, ...(keyCode ? [keyCode] : []), actions, confirmHost, receiptHost, said, error);
2502
+ return card;
2503
+ }
2504
+
2505
+ async function setConnectionDismissed(event, dismiss) {
2506
+ const payload = event.payload || {};
2507
+ const proposalId = String(payload.proposalId || '');
2508
+ const entry = connectionCards.get(proposalId);
2509
+ const snapshot = captureChat();
2510
+ if (!snapshot || !entry || entry.busy || !proposalId) return;
2511
+ const name = String(payload.name || payload.target || 'this');
2512
+ entry.busy = true; entry.error = '';
2513
+ repaintConnectionCards();
2514
+ try {
2515
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/connection-proposals/${encodeURIComponent(proposalId)}/${dismiss ? 'dismiss' : 'undismiss'}`, {
2516
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner }),
2517
+ });
2518
+ if (!sameChat(snapshot)) return;
2519
+ if (result?.chat?.chatId === snapshot.chatId) state.chat = { ...state.chat, connectionDismissals: result.chat.connectionDismissals ?? [] };
2520
+ if (result?.event && !state.events.some((known) => known.eventId === result.event.eventId)) state.events.push(result.event);
2521
+ announce(dismiss ? `Not now. The AI won’t suggest connecting ${name} again in this chat unless you choose Show again.`
2522
+ : `The suggestion to connect ${name} is back.`);
2523
+ } catch (error) {
2524
+ if (sameChat(snapshot)) entry.error = errorMessage(error);
2525
+ } finally {
2526
+ entry.busy = false;
2527
+ if (sameChat(snapshot)) {
2528
+ repaintConnectionCards();
2529
+ // The pressed button is gone with the card's old face: keep the keyboard on this card.
2530
+ const card = ui.feed?.querySelector(`.ai-chat-connection-card[data-proposal-id="${CSS.escape(proposalId)}"]`);
2531
+ const next = card?.querySelector(entry.error ? 'button' : dismiss ? '[data-command-id^="shell.chat-connection-show-again"]' : '.ai-chat-filter-actions button');
2532
+ next?.focus({ preventScroll: true });
2533
+ }
2534
+ }
2535
+ }
2536
+
2537
+ /** The result of a check the person approved in chat: the same receipt Discover and Integrations show. */
2538
+ function renderConnectionCheck(event) {
2539
+ const payload = event.payload || {};
2540
+ const api = connectionsApi();
2541
+ const name = String(payload.name || payload.agent || 'this tool');
2542
+ const card = document.createElement('section');
2543
+ card.className = 'ai-chat-filter-card ai-chat-connection-card ai-chat-connection-receipt';
2544
+ card.dataset.eventId = event.eventId;
2545
+ card.dataset.eventSequence = String(event.sequence);
2546
+ const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
2547
+ const title = document.createElement('strong');
2548
+ title.id = `chat-connection-check-${event.eventId}`;
2549
+ title.textContent = `Connection check · ${name}`;
2550
+ card.setAttribute('aria-labelledby', title.id);
2551
+ head.append(title);
2552
+ card.append(head);
2553
+ const receipt = payload.receipt && typeof payload.receipt === 'object' ? payload.receipt : null;
2554
+ const identity = receipt?.reported?.identity || 'a different account';
2555
+ if (receipt && api) {
2556
+ // The transcript is a record: a check reads "Checked · when", never "Verified". Whether it still holds is shown
2557
+ // live on the suggestion card, Discover and Integrations (#1900 review, owner ruling: history only).
2558
+ const shown = { ...receipt, historical: true };
2559
+ // A changed account gets its own line below, worded for this moment, instead of the receipt's general one.
2560
+ card.append(api.receiptNode(payload.changedTarget ? { ...shown, previousIdentity: null } : shown,
2561
+ payload.ok ? null : (typeof payload.error === 'string' && payload.error) || null));
2562
+ }
2563
+ if (payload.changedTarget) {
2564
+ const changed = document.createElement('p');
2565
+ changed.className = 'ai-chat-filter-note ai-chat-approval-warning';
2566
+ changed.textContent = `The account behind ${name} is now ${identity}, not ${payload.previousIdentity || 'the one checked before'}. Nothing else was read.`;
2567
+ card.append(changed);
2568
+ }
2569
+ if (payload.restarted) {
2570
+ const restarted = document.createElement('p');
2571
+ restarted.className = 'ai-chat-filter-note';
2572
+ restarted.textContent = 'The program was restarted since the last check.';
2573
+ card.append(restarted);
2574
+ }
2575
+ if (!payload.ok && !(receipt && api)) {
2576
+ const failed = document.createElement('p');
2577
+ // A check that was stopped is not a failed one (#1900): its outcome is unknown, said plainly, not in error red.
2578
+ failed.className = payload.stopped === true ? 'ai-chat-filter-note' : 'ai-chat-filter-note ai-chat-connection-error';
2579
+ failed.textContent = (typeof payload.error === 'string' && payload.error) || `The check of ${name} did not succeed. Ask the AI to try again.`;
2580
+ card.append(failed);
2581
+ }
2582
+ return card;
2583
+ }
2584
+
2585
+ /** A check that ran under "Allow checks … for this chat": one line, like a connector's receipt. */
2586
+ function renderConnectionCheckAllowed(event) {
2587
+ const item = document.createElement('div');
2588
+ item.className = 'ai-chat-event connector';
2589
+ item.dataset.eventSequence = String(event.sequence);
2590
+ item.dataset.eventId = event.eventId;
2591
+ const label = document.createElement('strong');
2592
+ label.textContent = 'Allowed for this chat';
2593
+ const name = String(event.payload.connectionCheck?.name || event.payload.connectionCheck?.agent || 'a connection');
2594
+ item.append(label, document.createTextNode(` · checked ${name}`));
2595
+ return item;
2596
+ }
2597
+
2598
+ /** One line for a decided workflow create (#1890 PR 3a): approved, denied, or stopped at FloLess's last check. */
2599
+ function renderCreateReceipt(event) {
2600
+ const item = document.createElement('div');
2601
+ item.className = 'ai-chat-event connector';
2602
+ item.dataset.eventSequence = String(event.sequence);
2603
+ item.dataset.eventId = event.eventId;
2604
+ const create = event.payload.create;
2605
+ const label = document.createElement('strong');
2606
+ const what = `the workflow “${create.name}” ${createWhere(create)}`;
2607
+ if (event.payload.reason) {
2608
+ label.textContent = 'Not created';
2609
+ item.append(label, document.createTextNode(` · ${event.payload.reason}`));
2610
+ } else if (event.payload.decision === 'allow') {
2611
+ label.textContent = 'Approved once';
2612
+ item.append(label, document.createTextNode(` · Create ${what}`));
2613
+ } else {
2614
+ label.textContent = 'Not created';
2615
+ item.append(label, document.createTextNode(` · ${what}`));
2616
+ }
2617
+ return item;
2618
+ }
2619
+
1936
2620
  function renderEvent(event) {
1937
2621
  if (event.type === 'user-message' && event.payload?.source === 'request' && event.payload?.filterAi) return renderFilterQuestion(event);
1938
2622
  if (event.type === 'user-message' && event.payload?.source === 'request') return renderRequestCard(event);
@@ -1940,10 +2624,22 @@
1940
2624
  if (event.type === 'user-message') return withFilterNotShared(renderMessage(event, 'user', payloadText(event)), event);
1941
2625
  if (event.type === 'filter-proposal') return renderServerProposal(event);
1942
2626
  if (event.type === 'filter-proposal-update') return null;
2627
+ // #1900: a connection the AI suggested, the result of a check it asked for, and a check run under "Allow for this chat".
2628
+ if (event.type === 'connection-proposal') return renderConnectionProposal(event);
2629
+ if (event.type === 'connection-proposal-update') return null;
2630
+ if (event.type === 'connection-check') return renderConnectionCheck(event);
2631
+ // #2046: a next move the Guide suggested; web/guide.js paints it and owns its button.
2632
+ if (event.type === 'next-move') return window.flolessGuide?.renderNextMove?.(event) || null;
2633
+ if (event.type === 'approval-decided' && event.payload?.automatic === true && event.payload?.connectionCheck) return renderConnectionCheckAllowed(event);
1943
2634
  if (event.type === 'assistant-message') return renderMessage(event, 'assistant', payloadText(event), Boolean(event.payload?.delta));
1944
2635
  // #1907: a connector call that ran under "Allow for this chat" leaves a visible receipt; every other decision is audit only.
1945
2636
  if (event.type === 'approval-decided' && event.payload?.automatic === true && event.payload?.connector) return renderConnectorReceipt(event);
2637
+ // #1890 PR 2b: a workspace change that ran under "Allow for this chat", or one FloLess stopped at the last check.
2638
+ if (event.type === 'approval-decided' && event.payload?.change && (event.payload?.automatic === true || event.payload?.reason)) return renderChangeReceipt(event);
2639
+ // #1890 PR 3a: a decided workflow create stays visible as one line, so a reload never shows it as pending.
2640
+ if (event.type === 'approval-decided' && event.payload?.create) return renderCreateReceipt(event);
1946
2641
  if (event.type === 'approval-requested' || event.type === 'approval-decided' || event.type === 'state' || event.type === 'followup-status') return null;
2642
+ if (event.type === 'tool' && (event.payload?.tool === 'agent' || event.payload?.tool === 'guide') && typeof event.payload?.message === 'string') return renderAgentRunLine(event);
1947
2643
  if (event.type === 'tekla-read') return renderTeklaReadEvent(event);
1948
2644
  if (event.type === 'height-question') return renderHeightQuestion(event);
1949
2645
  if (event.type === 'setup-question') return renderSetupQuestion(event);
@@ -2048,6 +2744,22 @@
2048
2744
  const heightEndKey = (row) => `${row.memberId}\u0000${row.end}`;
2049
2745
  const heightEndWord = (row) => (row.endWord === 'from' ? 'start' : 'end');
2050
2746
  const heightAnswerText = (answer) => (answer?.how === 'typed' ? `You typed ${answer.typed}` : `Confirmed ${answer?.shownAs || ''}`);
2747
+ /*
2748
+ * #1903: a row about a member ALREADY in the model. The server snapshotted that end when the question was
2749
+ * asked; the card says what it held THEN (the model can change before the person answers, and the review
2750
+ * always compares against the model as it is when the read is staged), and that the answer is only
2751
+ * proposed. The number is shown in the question's own units through the shared helper; until that helper
2752
+ * has loaded it reads in millimetres rather than not at all.
2753
+ */
2754
+ const heightInModelValue = (mm, units) => (displayUnitsModule ? displayUnitsModule.formatElevation(mm, units) : `${Math.round(mm)} mm`);
2755
+ const heightInModelText = (snapshot, units) => {
2756
+ if (!snapshot) return '';
2757
+ if (snapshot.state === 'unknown' || typeof snapshot.value !== 'number') return 'In the model when asked: no height.';
2758
+ const value = heightInModelValue(snapshot.value, units);
2759
+ const tail = snapshot.state === 'assumed' ? ' (placed, not from the drawings)' : snapshot.state === 'answered' ? ' (your earlier answer)' : '';
2760
+ return `In the model when asked: ${value}${tail}.`;
2761
+ };
2762
+ const HEIGHT_PROPOSED_TEXT = 'Proposed in the review; the model changes only if you accept it there.';
2051
2763
  // The server's sentence, then what to do next when it names a step (a damaged record says to discard the read).
2052
2764
  const heightErrorText = (error, fallback) => {
2053
2765
  const next = (error?.recovery || []).map((step) => step && typeof step.action === 'string' ? step.action : '').filter(Boolean);
@@ -2066,7 +2778,13 @@
2066
2778
  if (entry.loading) return;
2067
2779
  entry.loading = true;
2068
2780
  request(`/api/chat/height-questions/${encodeURIComponent(entry.requestId)}/${encodeURIComponent(entry.questionId)}?${new URLSearchParams({ chatId: entry.chatId || '' })}`)
2069
- .then((result) => { if (result?.readClosed) { entry.finished = true; entry.view = null; } else entry.view = result.question; entry.loadError = ''; })
2781
+ .then((result) => {
2782
+ if (result?.readClosed) { entry.finished = true; entry.view = null; } else entry.view = result.question;
2783
+ entry.loadError = '';
2784
+ // #1903: an existing member's "in the model" height is shown in the question's units, which needs
2785
+ // the shared helper; repaint once it has loaded.
2786
+ if (entry.view?.ends?.some((row) => row.inModel) && !displayUnitsModule) loadDisplayUnitsModule().then(() => repaintHeightCard(entry));
2787
+ })
2070
2788
  .catch((error) => {
2071
2789
  if (CARD_READ_FINISHED.has(error?.code)) { entry.finished = true; entry.loadError = ''; return; }
2072
2790
  entry.loadError = heightErrorText(error, 'FloLess could not load this height question.');
@@ -2141,7 +2859,12 @@
2141
2859
  note.textContent = !view
2142
2860
  ? (entry.finished ? CARD_FINISHED_TEXT : entry.loadError || 'Loading the heights this read is asking about…')
2143
2861
  : open
2144
- ? 'The drawings don’t settle these heights. Only you can answer — the AI can’t fill this in. What you confirm or type goes straight into the model.'
2862
+ ? (rows.some((row) => row.inModel)
2863
+ // #1903: never say "straight into the model" about a member already in it — that answer is proposed.
2864
+ // Neutral about the drawings: an existing member's end may well be drawn, and the person is being
2865
+ // asked whether it still holds (code review).
2866
+ ? 'Only you can answer these heights — the AI can’t fill this in. For a new member, what you confirm or type goes straight into the model; for one already in the model, it is proposed in the review.'
2867
+ : 'The drawings don’t settle these heights. Only you can answer — the AI can’t fill this in. What you confirm or type goes straight into the model.')
2145
2868
  : 'This read is no longer waiting for an answer.';
2146
2869
  card.append(note);
2147
2870
  if (!view) {
@@ -2319,8 +3042,15 @@
2319
3042
  label.dataset.tip = row.label;
2320
3043
  labelLine.append(label);
2321
3044
  const meta = document.createElement('div'); meta.className = 'ai-chat-height-meta';
2322
- meta.textContent = `${row.memberId} · ${heightEndWord(row)}`;
3045
+ // #1903: an existing member's PROFILE comes from the model, not from the read's label, so a label that
3046
+ // names the wrong member is visibly at odds with what the id really is.
3047
+ meta.textContent = [row.inModel?.profile, row.memberId, heightEndWord(row)].filter(Boolean).join(' · ');
2323
3048
  item.append(labelLine, meta);
3049
+ if (row.inModel) {
3050
+ const inModel = document.createElement('div'); inModel.className = 'ai-chat-height-inmodel';
3051
+ inModel.textContent = `${heightInModelText(row.inModel, entry.view?.units)} ${HEIGHT_PROPOSED_TEXT}`;
3052
+ item.append(inModel);
3053
+ }
2324
3054
 
2325
3055
  if (row.status === 'superseded') {
2326
3056
  const gone = document.createElement('div'); gone.className = 'ai-chat-height-answered';
@@ -2457,7 +3187,21 @@
2457
3187
  target?.focus({ preventScroll: true });
2458
3188
  }
2459
3189
 
2460
- const heightTellText = (entry) => `I've answered height question ${entry.view?.n ?? ''}.`.replace(' .', '.');
3190
+ /*
3191
+ * The words the person sees for a card in "Tell the read" (#1911): its place among the cards of its own kind
3192
+ * actually shown in this conversation, never the ledger's running record number (`view.n`, which also counts
3193
+ * answers and so jumps from 1 to 13). The read does not need the number: it reads the ledger, never the
3194
+ * prose (#1882 plan), so the visible text carries no id at all.
3195
+ */
3196
+ const CARD_ORDINALS = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth'];
3197
+ function cardPlace(entry, attribute, noun) {
3198
+ const keys = [...(ui.feed?.querySelectorAll(`[${attribute}]`) || [])].map((node) => node.getAttribute(attribute));
3199
+ const at = keys.indexOf(entry.key);
3200
+ if (keys.length < 2 || at < 0) return `the ${noun}`;
3201
+ return at < CARD_ORDINALS.length ? `the ${CARD_ORDINALS[at]} ${noun}` : `${noun} ${at + 1} of ${keys.length}`;
3202
+ }
3203
+ const heightTellText = (entry) => `I've answered ${cardPlace(entry, 'data-height-question', 'height card')}.`;
3204
+ const setupTellText = (entry) => `I've answered ${cardPlace(entry, 'data-setup-question', 'read setup card')}.`;
2461
3205
 
2462
3206
  /*
2463
3207
  * TELL THE READ puts one short message in the composer and moves focus to Send; the PERSON sends it
@@ -2911,7 +3655,7 @@
2911
3655
  : 'All answered. Press Tell the read, then Send: the read looks at what you sent and asks you to confirm its reading here.';
2912
3656
  card.append(done);
2913
3657
  const tell = heightActionButton('Tell the read', `shell.chat-setup-tell-read#${entry.questionId}`, questionLabel, 'ai-chat-filter-apply', null);
2914
- tell.addEventListener('click', () => tellReadAnswered(entry, `I've answered setup question ${view.n}.`, repaintSetupCard));
3658
+ tell.addEventListener('click', () => tellReadAnswered(entry, setupTellText(entry), repaintSetupCard));
2915
3659
  actions.append(tell);
2916
3660
  }
2917
3661
  actions.hidden = !actions.childNodes.length;
@@ -3297,7 +4041,7 @@
3297
4041
  fact('Library', payload.library);
3298
4042
  fact('Checked', checkedTime(payload.checkedAt));
3299
4043
  card.append(facts);
3300
- const note = document.createElement('p'); note.textContent = 'The generated agent\'s commands remain unverified.';
4044
+ const note = document.createElement('p'); note.textContent = 'The generated tool\'s commands remain unverified.';
3301
4045
  card.append(note);
3302
4046
  } else {
3303
4047
  const message = document.createElement('p');
@@ -3745,6 +4489,8 @@
3745
4489
  announceLiveResponseOnce();
3746
4490
  const focusedCommand = ui.feed.contains(document.activeElement)
3747
4491
  ? document.activeElement?.dataset?.commandId : null;
4492
+ // A card painted once and reused across repaints (a connection suggestion, #1900) keeps its own control focused.
4493
+ const focusedNode = ui.feed.contains(document.activeElement) ? document.activeElement : null;
3748
4494
  const nearBottom = ui.feed.scrollHeight - ui.feed.scrollTop - ui.feed.clientHeight < 56;
3749
4495
  const scrollTop = ui.feed.scrollTop;
3750
4496
  ui.feed.replaceChildren();
@@ -3777,8 +4523,28 @@
3777
4523
  }
3778
4524
  continue;
3779
4525
  }
4526
+ // Something FloLess itself refused during the answer (a file change it declined, a connector it turned away,
4527
+ // #1890 PR 2b / #1907), written for the person: held and shown under the answer, like the receipts below.
4528
+ if (event.type === 'tool' && event.payload?.plain === true && event.payload?.tool !== 'agent' && event.payload?.tool !== 'guide'
4529
+ && typeof event.payload?.message === 'string' && event.payload.message) {
4530
+ links.push({ turnId: event.turnId, node: renderPlainNotice(event) });
4531
+ continue;
4532
+ }
3780
4533
  // Provider tools commonly split one answer into before/after chunks. They are not prose,
3781
4534
  // so keep collecting same-turn deltas across them instead of rendering abandoned fragments.
4535
+ // #1900: a connection suggestion's Not now / Show again only changes its card, never a reason to split the answer;
4536
+ // the suggestion and a check's result are receipts like the ones below, held under the answer they were written during.
4537
+ // #2007: an agent run's first line (who started it, its scope) is a tool event too, but it is the conversation's
4538
+ // opening line, not a tool: shown where it was written, before the instructions.
4539
+ if (event.type === 'tool' && (event.payload?.tool === 'agent' || event.payload?.tool === 'guide') && typeof event.payload?.message === 'string') {
4540
+ flushAssistant();
4541
+ ui.feed.append(renderAgentRunLine(event));
4542
+ continue;
4543
+ }
4544
+ if (event.type === 'connection-proposal-update') continue;
4545
+ if (event.type === 'connection-proposal' || event.type === 'connection-check') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
4546
+ // #2046: the Guide's next-move cards are held under the answer they were suggested in, like the cards above.
4547
+ if (event.type === 'next-move') { const node = renderEvent(event); if (node) links.push({ turnId: event.turnId, node }); continue; }
3782
4548
  if (['tool', 'usage', 'knowledge-citation', 'attachment', 'compaction', 'state'].includes(event.type)) continue;
3783
4549
  // FloLess's own receipts (object links #1653; evidence looks and suggestion cards #1859) are written mid-answer while a tool runs:
3784
4550
  // held and shown under the answer, so they never cut one answer into fragments.
@@ -3794,7 +4560,9 @@
3794
4560
  // never looks like a failed response. Recovery deliberately has no live indicator.
3795
4561
  if (turnIsVisiblyActive()) ui.feed.append(renderLiveStatus());
3796
4562
  }
3797
- restoreFeedFocus(focusedCommand);
4563
+ if (focusedNode?.isConnected && ui.feed.contains(focusedNode)) {
4564
+ if (document.activeElement !== focusedNode) focusedNode.focus({ preventScroll: true });
4565
+ } else restoreFeedFocus(focusedCommand);
3798
4566
  // Removing a focused control makes the browser lay out the half-built feed, which clamps its scroll near the top.
3799
4567
  // Scrolled up, the reader stays where they were.
3800
4568
  if (!nearBottom) ui.feed.scrollTop = scrollTop;
@@ -3898,10 +4666,16 @@
3898
4666
  // Keep the same buttons during polling so keyboard focus and pointer clicks survive. A Tekla card
3899
4667
  // also carries the permission view it offers "Allow for this chat" on, so a change repaints it.
3900
4668
  const teklaBinding = teklaAllowableApproval(approval) ? currentTeklaBinding(state.chat) : null;
4669
+ // #1890 PR 2b: a workspace conversation's file change, with the projects/workflows it touches.
4670
+ const change = approval.change && typeof approval.change === 'object' ? approval.change : null;
3901
4671
  // #1907: a call to one of the person's connectors FloLess could identify may be allowed for the whole chat.
3902
4672
  const connector = approval.connector?.verified ? approval.connector : null;
3903
- const allowanceRevision = teklaBinding ? String(teklaAllowanceRevision(teklaBinding))
3904
- : connector ? String(state.chat?.connectorAllowance?.revision ?? 0) : '';
4673
+ // #1900: a connection check the AI asked for; "Allow for this chat" only when the server says it may be.
4674
+ const connectionCheck = approval.connectionCheck && typeof approval.connectionCheck === 'object' ? approval.connectionCheck : null;
4675
+ const allowanceRevision = connectionCheck ? String(state.chat?.integrationReadAllowance?.revision ?? 0)
4676
+ : change ? String(state.chat?.changeAllowance?.revision ?? 0)
4677
+ : teklaBinding ? String(teklaAllowanceRevision(teklaBinding))
4678
+ : connector ? String(state.chat?.connectorAllowance?.revision ?? 0) : '';
3905
4679
  if (existing?.dataset.approvalId === approval.approvalId && (existing.dataset.allowanceRevision || '') === allowanceRevision) return;
3906
4680
  // A permission change repaints the same approval: keep keyboard focus on the same control.
3907
4681
  const refocus = existing?.dataset.approvalId === approval.approvalId && existing.contains(document.activeElement)
@@ -3909,14 +4683,57 @@
3909
4683
  existing?.remove();
3910
4684
  const card = document.createElement('section'); card.className = 'ai-chat-approval';
3911
4685
  card.dataset.approvalId = approval.approvalId;
3912
- if (teklaBinding || connector) card.dataset.allowanceRevision = allowanceRevision;
4686
+ if (teklaBinding || connector || change || connectionCheck) card.dataset.allowanceRevision = allowanceRevision;
4687
+ // #1890 PR 3a: the AI asking to create a workflow, with where it would go.
4688
+ const create = approval.create && typeof approval.create === 'object' ? approval.create : null;
4689
+ if (approval.scopeAdd) {
4690
+ const scope = approval.scopeAdd;
4691
+ card.classList.add('ai-chat-scope-add');
4692
+ card.setAttribute('role', 'group');
4693
+ const heading = document.createElement('strong');
4694
+ heading.id = `chat-scope-add-heading-${approval.approvalId}`;
4695
+ heading.textContent = `Let this conversation also work on ${scope.target.kind} “${scope.label}”?`;
4696
+ card.setAttribute('aria-labelledby', heading.id);
4697
+ const copy = document.createElement('p');
4698
+ const readOnly = state.chat?.settings?.permissionProfile === 'read-only';
4699
+ const writeProfile = state.chat?.owner?.kind === 'workspace' ? 'Make changes (asks first)' : 'Working folder write';
4700
+ copy.textContent = readOnly
4701
+ ? 'The AI’s file tools cannot change files while Read only is on. Commands keep their own approvals and may authorize file changes.'
4702
+ + (scope.allowsFileChanges ? ` If you choose ${writeProfile}, file changes here will also be allowed without asking.` : '')
4703
+ : scope.allowsFileChanges ? 'File changes here will also be allowed without asking. Commands and tools keep their own approvals.'
4704
+ : 'Adds this folder to the conversation. Your current file approval setting stays unchanged.';
4705
+ const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
4706
+ const deny = button('Deny', 'shell.chat-approval-deny');
4707
+ 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');
4708
+ deny.addEventListener('click', () => decideApproval('deny'));
4709
+ allow.addEventListener('click', () => decideApproval('allow'));
4710
+ actions.append(deny, allow); card.append(heading, copy, actions);
4711
+ ui.approvalTray.append(card);
4712
+ if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
4713
+ ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
4714
+ return;
4715
+ }
4716
+ if (create) {
4717
+ paintCreateCard(card, approval, create);
4718
+ ui.approvalTray.append(card);
4719
+ if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
4720
+ ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
4721
+ return;
4722
+ }
4723
+ if (change) {
4724
+ paintChangeCard(card, approval, change, Number(allowanceRevision));
4725
+ ui.approvalTray.append(card);
4726
+ if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
4727
+ ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
4728
+ return;
4729
+ }
3913
4730
  const heading = document.createElement('strong'); heading.textContent = 'Approval needed';
3914
4731
  const copy = document.createElement('p'); copy.textContent = approval.summary;
3915
4732
  const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
3916
4733
  const deny = button('Deny', 'shell.chat-approval-deny');
3917
4734
  const allow = button('Approve once', 'shell.chat-approval-allow', 'allow');
3918
4735
  // A Tekla read is never covered by a request-wide grant; it may instead be allowed for the whole chat (below).
3919
- const explicitOnly = approvalIsExplicitOnly(approval);
4736
+ const explicitOnly = approvalIsExplicitOnly(approval) || Boolean(connectionCheck);
3920
4737
  const allowRequest = explicitOnly ? null : button('Approve for this request', 'shell.chat-approval-request', 'allow');
3921
4738
  const scope = document.createElement('span');
3922
4739
  scope.className = 'sr-only';
@@ -3929,6 +4746,14 @@
3929
4746
  allowRequest.setAttribute('aria-describedby', scope.id);
3930
4747
  allowRequest.addEventListener('click', () => decideApproval('allow-request'));
3931
4748
  actions.append(deny, allow, allowRequest); card.append(heading, copy, actions, scope);
4749
+ } else if (connectionCheck) {
4750
+ paintConnectionCheckApproval(card, approval, connectionCheck, { heading, copy, actions, deny, allow }, Number(allowanceRevision));
4751
+ ui.approvalTray.append(card);
4752
+ if (refocus) [...card.querySelectorAll('button')].find((node) => node.dataset.commandId === refocus)?.focus();
4753
+ // A new question: Deny is the safe default, unless the person is typing a message.
4754
+ else if (existing?.dataset.approvalId !== approval.approvalId && !(document.activeElement === ui.input && ui.input.value)) deny.focus({ preventScroll: true });
4755
+ ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
4756
+ return;
3932
4757
  } else if (connector) {
3933
4758
  card.dataset.explicitOnly = 'true';
3934
4759
  // The warning is the part that decides it: on its own line, not at the end of the question.
@@ -3972,6 +4797,253 @@
3972
4797
  ui.approvalTray.scrollTop = ui.approvalTray.scrollHeight;
3973
4798
  }
3974
4799
 
4800
+ /**
4801
+ * #1900 — the card for a connection check the AI asked for. The server's summary is the whole question; the two
4802
+ * things that decide it (a tool FloLess has not reviewed, a key sent to an address) are pulled out onto their own
4803
+ * lines. Never "Approve for this request": each check is approved once, or allowed for this chat when the server
4804
+ * says that is safe (reviewed, no custom key, an identified account, a pinned tool).
4805
+ */
4806
+ const CONNECTION_UNREVIEWED_SENTENCE = 'This check comes from a tool FloLess has not reviewed.';
4807
+
4808
+ function paintConnectionCheckApproval(card, approval, check, parts, allowanceRevision) {
4809
+ const { heading, copy, actions, deny, allow } = parts;
4810
+ card.dataset.explicitOnly = 'true';
4811
+ card.classList.add('ai-chat-connection-approval');
4812
+ const name = String(check.name || check.agent || 'this tool');
4813
+ const keySentence = check.sendsCustomKey && check.origin ? `Your ${check.credentialHandle} key will be sent to ${check.origin}.` : '';
4814
+ copy.textContent = String(approval.summary || `Check ${name}.`)
4815
+ .replace(CONNECTION_UNREVIEWED_SENTENCE, '').replace(keySentence || '\u0000', '').replace(/\s{2,}/g, ' ').trim();
4816
+ const extra = [];
4817
+ if (check.reviewed === false) {
4818
+ const badge = document.createElement('span');
4819
+ badge.className = 'local-discovery-found conn-chip is-chat-warning ai-chat-connection-badge';
4820
+ badge.textContent = 'Not reviewed';
4821
+ heading.append(' ', badge);
4822
+ const warning = document.createElement('p');
4823
+ warning.className = 'ai-chat-approval-warning';
4824
+ warning.textContent = 'FloLess has not reviewed the tool this check comes from, so it can’t confirm the check only reads.';
4825
+ extra.push(warning);
4826
+ }
4827
+ if (check.sendsCustomKey) {
4828
+ const warning = document.createElement('p');
4829
+ warning.className = 'ai-chat-approval-warning';
4830
+ const handle = check.credentialHandle ? `${check.credentialHandle} ` : '';
4831
+ if (check.origin) {
4832
+ const address = document.createElement('code'); address.className = 'conn-code'; address.textContent = check.origin;
4833
+ warning.append(`Your ${handle}key will be sent to `, address, '. Only approve if you trust that address.');
4834
+ } else warning.textContent = `Your ${handle}key will be sent to an address this tool chose. Only approve if you trust it.`;
4835
+ extra.push(warning);
4836
+ }
4837
+ // Deny and Approve once already answer through paintApproval's own listeners.
4838
+ actions.append(deny, allow);
4839
+ const nodes = [heading, copy, ...extra, actions];
4840
+ if (check.chatAllowable === true) {
4841
+ const label = check.kind === 'host' ? `Allow checks of ${name} for this chat` : `Allow checks of ${name} with this account for this chat`;
4842
+ const key = `${check.agent}${check.alias ? `.${check.alias}` : ''}`;
4843
+ const allowChat = button(label, `shell.chat-connection-check-allow-chat#${key}`, 'allow');
4844
+ allowChat.dataset.commandInstanceLabel = name;
4845
+ const help = document.createElement('span');
4846
+ help.className = 'sr-only';
4847
+ help.id = `chat-approval-check-scope-help-${approval.approvalId}`;
4848
+ 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.`;
4849
+ allowChat.dataset.tip = help.textContent;
4850
+ allowChat.setAttribute('aria-describedby', help.id);
4851
+ allowChat.addEventListener('click', () => decideApproval('allow-chat', allowanceRevision));
4852
+ actions.append(allowChat);
4853
+ nodes.push(help);
4854
+ }
4855
+ card.append(...nodes);
4856
+ }
4857
+
4858
+ // #1890 PR 2b — why a workspace change can only be dismissed. Mirrors the server's reasons in plain words.
4859
+ const CHANGE_REFUSED_COPY = {
4860
+ 'outside-workspace': 'This file is outside your FloLess workspace folder, so nothing was changed. Ask the AI to keep the change inside a project or workflow.',
4861
+ 'conversation-records': 'This would change FloLess’s own conversation records, which the AI never changes, so nothing was changed. Ask the AI to put the change in a project or workflow.',
4862
+ 'not-in-project': 'FloLess can’t tell which project or workflow this file belongs to, so nothing was changed. Ask the AI to save it in a project or workflow folder instead.',
4863
+ 'unreadable-path': 'FloLess couldn’t confirm where this file really is, because the path goes through a folder link, so nothing was changed. Ask the AI to use the project’s own folder.',
4864
+ 'ambiguous-path': 'FloLess cannot confirm how the provider expands this path, so nothing was changed. Use an absolute file path in the intended project or workflow, then retry.',
4865
+ 'provider-settings': 'FloLess doesn’t let the AI change its own settings files, so nothing was changed. Ask it to make the change somewhere else.',
4866
+ 'too-many': 'This change touches too many files to review at once, so nothing was changed. Ask the AI to make it in smaller steps.',
4867
+ };
4868
+ const CHANGE_PATHS_SHOWN = 5;
4869
+
4870
+ function changeFileCount(change) {
4871
+ return (change.owners || []).reduce((sum, owner) => sum + (owner.paths?.length || 0), 0);
4872
+ }
4873
+
4874
+ function changeNames(change) {
4875
+ const names = (change.owners || []).map((owner) => owner.label);
4876
+ return names.length <= 1 ? (names[0] || 'this project') : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`;
4877
+ }
4878
+
4879
+ /** The card for a workspace conversation's file change: where it lands, then Deny / Approve once / Allow for this chat. */
4880
+ function paintChangeCard(card, approval, change, allowanceRevision) {
4881
+ card.dataset.explicitOnly = 'true';
4882
+ card.classList.add('ai-chat-change');
4883
+ card.setAttribute('role', 'group');
4884
+ const id = approval.approvalId;
4885
+ const denyOnly = Boolean(change.refused || change.busy);
4886
+ const heading = document.createElement('strong');
4887
+ heading.id = `chat-change-heading-${id}`;
4888
+ heading.textContent = denyOnly ? 'Can’t change this' : 'Approval needed';
4889
+ card.setAttribute('aria-labelledby', heading.id);
4890
+ const provider = providerLabels[state.chat?.provider] || 'The AI';
4891
+ const files = changeFileCount(change);
4892
+ const copy = document.createElement('p');
4893
+ copy.id = `chat-change-copy-${id}`;
4894
+ copy.textContent = files === 1 ? `${provider} wants to change a file in your workspace.`
4895
+ : files > 1 ? `${provider} wants to change these ${files} files in your workspace.` : `${provider} wants to change files in your workspace.`;
4896
+ card.setAttribute('aria-describedby', copy.id);
4897
+ const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
4898
+ if (denyOnly) {
4899
+ // Nothing is waiting for approval: one way out, and a plain reason why.
4900
+ card.setAttribute('role', 'status');
4901
+ const reason = document.createElement('p');
4902
+ reason.className = 'ai-chat-change-reason';
4903
+ reason.textContent = change.refused
4904
+ ? (CHANGE_REFUSED_COPY[change.refused] || CHANGE_REFUSED_COPY['not-in-project'])
4905
+ : change.busy?.chatTitle
4906
+ ? `${changeNames(change)} ${change.owners.length > 1 ? 'are' : 'is'} being changed by another conversation (“${change.busy.chatTitle}”), so nothing was changed here. Ask again when it’s finished.`
4907
+ : `${changeNames(change)} ${change.owners.length > 1 ? 'are' : 'is'} being changed by other work right now, so nothing was changed here. Ask again when it’s finished.`;
4908
+ const dismiss = button('Dismiss', 'shell.chat-approval-deny');
4909
+ dismiss.addEventListener('click', () => decideApproval('deny'));
4910
+ actions.append(dismiss);
4911
+ card.append(heading, ...(change.owners?.length ? [copy, changeOwnerList(change)] : []), reason, actions);
4912
+ return;
4913
+ }
4914
+ const deny = button('Deny', 'shell.chat-approval-deny');
4915
+ const allow = button('Approve once', 'shell.chat-approval-allow', 'allow');
4916
+ deny.addEventListener('click', () => decideApproval('deny'));
4917
+ allow.addEventListener('click', () => decideApproval('allow'));
4918
+ actions.append(deny, allow);
4919
+ if (change.owners?.length) {
4920
+ const label = 'Allow file changes for this chat';
4921
+ const key = change.owners.map((owner) => owner.key).join('+');
4922
+ const allowChat = button(label, `shell.chat-change-allow-chat#${key}`, 'allow');
4923
+ allowChat.dataset.commandInstanceLabel = changeNames(change);
4924
+ const help = document.createElement('span');
4925
+ help.className = 'ai-chat-change-scope-help';
4926
+ help.id = `chat-change-scope-help-${id}`;
4927
+ 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.';
4928
+ allowChat.dataset.tip = help.textContent;
4929
+ allowChat.setAttribute('aria-describedby', help.id);
4930
+ allowChat.addEventListener('click', () => decideApproval('allow-chat', allowanceRevision));
4931
+ actions.append(allowChat);
4932
+ card.append(heading, copy, changeOwnerList(change), actions, help);
4933
+ return;
4934
+ }
4935
+ card.append(heading, copy, actions);
4936
+ }
4937
+
4938
+ /** Why a workflow the AI asked to create can only be dismissed (#1890 PR 3a); the server says the same to the AI. */
4939
+ const CREATE_REFUSED_COPY = {
4940
+ 'bad-name': 'A workflow name needs 1 to 120 characters you can see, so nothing was created. Ask the AI for a shorter or plainer name.',
4941
+ 'project-missing': 'That project isn’t in your workspace any more (it may have been archived or renamed), so nothing was created. Ask the AI to pick another project, or to create the workflow on its own.',
4942
+ };
4943
+
4944
+ function createWhere(create) {
4945
+ return create.destination?.kind === 'project' ? `in project ${create.destination.label}` : 'on its own, outside any project';
4946
+ }
4947
+
4948
+ /** The card for the AI asking to create a workflow: what and where, then Deny / Create workflow. Approve once only. */
4949
+ function paintCreateCard(card, approval, create) {
4950
+ card.dataset.explicitOnly = 'true';
4951
+ card.classList.add('ai-chat-change', 'ai-chat-create');
4952
+ card.setAttribute('role', 'group');
4953
+ const id = approval.approvalId;
4954
+ const denyOnly = Boolean(create.refused || create.busy);
4955
+ const heading = document.createElement('strong');
4956
+ heading.id = `chat-create-heading-${id}`;
4957
+ heading.textContent = denyOnly ? 'Can’t create this yet' : 'Create a workflow?';
4958
+ card.setAttribute('aria-labelledby', heading.id);
4959
+ const provider = providerLabels[state.chat?.provider] || 'The AI';
4960
+ const copy = document.createElement('p');
4961
+ copy.id = `chat-create-copy-${id}`;
4962
+ copy.textContent = `${provider} wants to create a workflow.`;
4963
+ card.setAttribute('aria-describedby', copy.id);
4964
+ // One row in the change card's own style: the new workflow's name, and where it would go.
4965
+ const list = document.createElement('ul');
4966
+ list.className = 'ai-chat-change-owners';
4967
+ const row = document.createElement('li');
4968
+ const name = document.createElement('span');
4969
+ name.className = 'ai-chat-change-owner';
4970
+ const strong = document.createElement('b');
4971
+ strong.textContent = create.name;
4972
+ strong.dataset.tip = create.name;
4973
+ const kind = document.createElement('span');
4974
+ kind.className = 'ai-chat-change-kind';
4975
+ kind.textContent = 'new workflow';
4976
+ name.append(strong, kind);
4977
+ const where = document.createElement('span');
4978
+ where.className = 'ai-chat-change-paths';
4979
+ const whereLine = document.createElement('span');
4980
+ whereLine.className = 'ai-chat-change-path ai-chat-create-where';
4981
+ whereLine.textContent = createWhere(create);
4982
+ where.append(whereLine);
4983
+ row.append(name, where);
4984
+ list.append(row);
4985
+ const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
4986
+ if (denyOnly) {
4987
+ card.setAttribute('role', 'status');
4988
+ const reason = document.createElement('p');
4989
+ reason.className = 'ai-chat-change-reason';
4990
+ const place = create.destination?.kind === 'project' ? create.destination.label : 'that workflow';
4991
+ reason.textContent = create.refused
4992
+ ? (CREATE_REFUSED_COPY[create.refused] || CREATE_REFUSED_COPY['project-missing'])
4993
+ : create.busy?.chatTitle
4994
+ ? `Another conversation (“${create.busy.chatTitle}”) is changing ${place} right now, so nothing was created. Ask again when it’s finished.`
4995
+ : `Other work is changing ${place} right now, so nothing was created. Ask again when it’s finished.`;
4996
+ const dismiss = button('Dismiss', 'shell.chat-approval-deny');
4997
+ dismiss.addEventListener('click', () => decideApproval('deny'));
4998
+ actions.append(dismiss);
4999
+ card.append(heading, copy, list, reason, actions);
5000
+ return;
5001
+ }
5002
+ const deny = button('Deny', 'shell.chat-approval-deny');
5003
+ const allow = button('Create workflow', 'shell.chat-workflow-create-approve', 'allow');
5004
+ deny.addEventListener('click', () => decideApproval('deny'));
5005
+ allow.addEventListener('click', () => decideApproval('allow'));
5006
+ actions.append(deny, allow);
5007
+ card.append(heading, copy, list, actions);
5008
+ }
5009
+
5010
+ /** Each project or workflow the change touches, with up to five of its files. */
5011
+ function changeOwnerList(change) {
5012
+ const list = document.createElement('ul');
5013
+ list.className = 'ai-chat-change-owners';
5014
+ for (const owner of change.owners || []) {
5015
+ const row = document.createElement('li');
5016
+ const name = document.createElement('span');
5017
+ name.className = 'ai-chat-change-owner';
5018
+ const strong = document.createElement('b');
5019
+ strong.textContent = owner.label;
5020
+ const kind = document.createElement('span');
5021
+ kind.className = 'ai-chat-change-kind';
5022
+ kind.textContent = owner.kind === 'workflow' ? 'workflow' : 'project';
5023
+ name.append(strong, kind);
5024
+ const paths = document.createElement('span');
5025
+ paths.className = 'ai-chat-change-paths';
5026
+ const shown = (owner.paths || []).slice(0, CHANGE_PATHS_SHOWN);
5027
+ for (const path of shown) {
5028
+ const line = document.createElement('span');
5029
+ line.className = 'ai-chat-change-path';
5030
+ line.textContent = path;
5031
+ line.dataset.tip = path;
5032
+ paths.append(line);
5033
+ }
5034
+ const more = (owner.paths?.length || 0) - shown.length;
5035
+ if (more > 0) {
5036
+ const extra = document.createElement('span');
5037
+ extra.className = 'ai-chat-change-more';
5038
+ extra.textContent = `and ${more} more file${more === 1 ? '' : 's'}`;
5039
+ paths.append(extra);
5040
+ }
5041
+ row.append(name, paths);
5042
+ list.append(row);
5043
+ }
5044
+ return list;
5045
+ }
5046
+
3975
5047
  function approvalIsExplicitOnly(approval) {
3976
5048
  if (!approval) return false;
3977
5049
  if (approval.explicitOnly === true) return true;
@@ -4453,6 +5525,7 @@
4453
5525
  }
4454
5526
 
4455
5527
  function paintSettings() {
5528
+ if (ui.scopeControls) paintScopeControl();
4456
5529
  const chat = state.chat;
4457
5530
  ui.settingsToggle.disabled = !chat;
4458
5531
  const answer = capabilityAnswer(state.capability);
@@ -4478,9 +5551,12 @@
4478
5551
  ui.model.querySelector('strong').textContent = chat?.settings.model ? (model?.label || chat.settings.model) : (model?.label || 'Choose model');
4479
5552
  const medium = (model?.efforts || []).find((effort) => effort.toLowerCase() === 'medium');
4480
5553
  ui.effort.querySelector('strong').textContent = effortLabel(chat?.settings.effort || medium || model?.efforts?.[0]) || 'Choose effort';
4481
- ui.permission.querySelector('strong').textContent = permissionLabels[chat?.settings.permissionProfile] || 'Read only';
4482
- if (state.scope?.owner?.kind === 'workspace') ui.permission.dataset.tip = 'From the workspace, AI Chat reads and answers. Open a project or workflow to let it change files there.';
4483
- else delete ui.permission.dataset.tip;
5554
+ ui.permission.querySelector('strong').textContent = permissionLabel(chat?.settings.permissionProfile);
5555
+ ui.permission.dataset.tip = permissionTip(chat?.settings.permissionProfile);
5556
+ // #2046: the Guide always reads only; its Access is said, not chosen, beside its Turn off and Delete.
5557
+ const guideChat = chat?.initiator?.kind === 'guide';
5558
+ ui.permission.hidden = guideChat;
5559
+ if (ui.guideAccess) ui.guideAccess.hidden = !guideChat;
4484
5560
  paintWorkspaceUnits();
4485
5561
  const bindings = chat?.integrationBindings || [];
4486
5562
  ui.integrations.querySelector('strong').textContent = bindings.length
@@ -4560,6 +5636,7 @@
4560
5636
  }
4561
5637
 
4562
5638
  function paintRecovery() {
5639
+ paintMoveNotice();
4563
5640
  const recovery = state.chat?.state === 'recovery';
4564
5641
  ui.recovery.hidden = !recovery;
4565
5642
  ui.recoveryStop.hidden = !recovery;
@@ -4570,9 +5647,12 @@
4570
5647
  }
4571
5648
 
4572
5649
  function paintConversation() {
5650
+ paintScopeControl();
4573
5651
  paintComposerDisclosure();
4574
5652
  paintTeklaChip();
4575
5653
  paintConnectorAllowance();
5654
+ paintChangeAllowance();
5655
+ paintCheckAllowance();
4576
5656
  const chat = state.chat;
4577
5657
  if (!chat) { providerChooser(); paintHistory(); return; }
4578
5658
  ui.historyToggle.disabled = false;
@@ -4690,6 +5770,12 @@
4690
5770
  // waiting for a follow-up fetch, which can leave a finished answer showing dots.
4691
5771
  state.chat = { ...state.chat, state: 'completed', activeTurn: null };
4692
5772
  paintConversation();
5773
+ // An answer just arrived, so the AI is reachable: a readiness check that failed earlier (it timed out while
5774
+ // this computer was busy) must not keep saying "not ready" under it. Read it again.
5775
+ if (!providerReady()) {
5776
+ const snapshot = captureChat();
5777
+ void loadCapability().then(() => { if (sameChat(snapshot)) { paintSettings(); updateSendState(); } });
5778
+ }
4693
5779
  }
4694
5780
  if (event.type === 'followup-status') {
4695
5781
  const notices = {
@@ -4705,7 +5791,20 @@
4705
5791
  paintEvents(); paintUnread();
4706
5792
  if (!document.hidden && !ui.feed.closest('[hidden]')) markRead();
4707
5793
  if (['approval-requested', 'approval-decided', 'error', 'interrupted', 'state', 'followup-status'].includes(event.type)
4708
- || (event.type === 'user-message' && event.payload?.followup)) refreshConversation(chatId, false);
5794
+ || (event.type === 'user-message' && event.payload?.followup)) {
5795
+ // #1890 PR 3b: a reply ending in a conversation waiting to move is when it moves; read the history list then,
5796
+ // because the conversation's own address answers "moved" the moment the move lands.
5797
+ const moveDue = state.scope?.owner?.kind === 'workspace' && state.chat?.rehome?.state === 'pending'
5798
+ && ['state', 'error', 'interrupted'].includes(event.type);
5799
+ if (moveDue) void checkMoveProgress(chatId); else refreshConversation(chatId, false);
5800
+ }
5801
+ });
5802
+ // #1890 PR 3b: the conversation moved into the workflow it built; the stream closes and the tab follows.
5803
+ source.addEventListener('chat-moved', (message) => {
5804
+ if (state.source !== source) return;
5805
+ let payload = null;
5806
+ try { payload = JSON.parse(message.data); } catch { return; }
5807
+ if (payload?.to?.chatId) void followMovedChat(payload.to);
4709
5808
  });
4710
5809
  source.addEventListener('ready', () => {
4711
5810
  if (state.source !== source || !sameScope(scope, generation) || state.chat?.chatId !== chatId) return;
@@ -5002,7 +6101,7 @@
5002
6101
  state.scope = scope;
5003
6102
  state.scopeInitialized = true;
5004
6103
  if (scopeChanged) { try { window.flolessLeftPane?.chatLinksChanged?.(); } catch { /* the card refreshes on its next read */ } }
5005
- state.chat = null; state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.events = []; state.capability = null; state.desktop = null; state.attachments = []; state.integrations = null;
6104
+ state.chat = null; state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.movedChats = []; state.movedChatsKnown = null; state.events = []; state.capability = null; state.desktop = null; state.attachments = []; state.integrations = null;
5006
6105
  if (scopeChanged) clearReport();
5007
6106
  state.filterCardMessages.clear();
5008
6107
  updateOffscreenActivity();
@@ -5019,17 +6118,19 @@
5019
6118
  const result = await request(`/api/chat/conversations?${ownerQuery(scope.owner)}`);
5020
6119
  if (generation !== state.scopeGeneration) return;
5021
6120
  state.chats = result.chats || [];
5022
- state.unreadableChats = result.unreadableChats || [];
6121
+ state.unreadableChats = result.unreadableChats || []; noteMovedChats(result.movedChats);
5023
6122
  seedReadCursors(state.chats, scope.owner);
5024
6123
  paintHistory(); paintUnread();
5025
- if (state.chats.length) await selectConversation(state.chats[0].chatId);
6124
+ // #2007: a scope may name the conversation it is for (an agent run's); otherwise the newest one opens.
6125
+ const wanted = scope.chatId && state.chats.some((chat) => chat.chatId === scope.chatId) ? scope.chatId : state.chats[0]?.chatId;
6126
+ if (wanted) await selectConversation(wanted);
5026
6127
  else providerChooser();
5027
6128
  } catch (error) {
5028
6129
  if (generation === state.scopeGeneration) {
5029
6130
  // A history read can fail independently of the selected project (for example while an
5030
6131
  // older, stale conversation is being recovered). Do not erase the scope and disable the
5031
6132
  // whole panel: the user can still start a new conversation in the project that is open.
5032
- state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.chat = null; state.events = []; state.capability = null;
6133
+ state.chats = []; state.archivedChats = []; state.unreadableChats = []; state.movedChats = []; state.movedChatsKnown = null; state.chat = null; state.events = []; state.capability = null;
5033
6134
  updateOffscreenActivity();
5034
6135
  ui.scope.textContent = scope.label;
5035
6136
  ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : scope.owner.kind === 'workflow' ? 'Workflow conversation' : 'Workspace conversation';
@@ -5168,7 +6269,8 @@
5168
6269
  const chat = await request('/api/chat/conversations', {
5169
6270
  method: 'POST', body: JSON.stringify({
5170
6271
  owner, provider, title: 'New chat',
5171
- settings: { model: null, effort: null, permissionProfile: 'read-only' },
6272
+ // #2037: no access level — the server starts a project or workflow conversation in Auto, the workspace in Read only.
6273
+ settings: { model: null, effort: null },
5172
6274
  initiator: { kind: 'user' },
5173
6275
  ...(displayUnitsSuggestion ? { displayUnitsSuggestion } : {}),
5174
6276
  }),
@@ -5202,7 +6304,7 @@
5202
6304
  const result = await request(`/api/chat/conversations?${ownerQuery()}&filter=instructor-answers`);
5203
6305
  if (requestGeneration !== state.historyRequestGeneration || scopeGeneration !== state.scopeGeneration) return;
5204
6306
  state.chats = result.chats || [];
5205
- state.unreadableChats = result.unreadableChats || [];
6307
+ state.unreadableChats = result.unreadableChats || []; noteMovedChats(result.movedChats);
5206
6308
  state.instructorAnswers = result.instructorAnswers || [];
5207
6309
  } catch (error) {
5208
6310
  if (requestGeneration === state.historyRequestGeneration) report(error, 'Could not load Instructor answers');
@@ -5295,14 +6397,22 @@
5295
6397
  }
5296
6398
 
5297
6399
  function closePicker() {
5298
- state.picker = null; ui.picker.hidden = true; ui.picker.replaceChildren();
6400
+ state.picker = null; state.pickerOpener = null; ui.picker.hidden = true; ui.picker.replaceChildren();
5299
6401
  for (const control of [ui.model, ui.effort, ui.permission, ui.integrations]) control.setAttribute('aria-expanded', 'false');
5300
6402
  }
5301
6403
 
6404
+ function closePickerOnEscape(event) {
6405
+ if (event.key !== 'Escape' || ui.picker.hidden || !state.picker) return;
6406
+ if (!ui.picker.contains(event.target) && event.target !== state.pickerOpener) return;
6407
+ const opener = state.pickerOpener;
6408
+ event.preventDefault(); event.stopPropagation(); closePicker();
6409
+ if (opener?.isConnected && !opener.disabled) opener.focus();
6410
+ }
6411
+
5302
6412
  function openPicker(kind, anchor, choices) {
5303
6413
  if (anchor.disabled) return;
5304
6414
  if (state.picker === kind) { closePicker(); return; }
5305
- toggleHistory(false); closePicker(); state.picker = kind;
6415
+ toggleHistory(false); closePicker(); state.picker = kind; state.pickerOpener = anchor;
5306
6416
  ui.picker.replaceChildren();
5307
6417
  for (const choice of choices) {
5308
6418
  const row = button('', `shell.chat-choice#${commandInstance(choice.id)}`, 'ai-chat-choice');
@@ -5348,17 +6458,67 @@
5348
6458
  selected: (state.chat.settings.effort || 'medium').toLowerCase() === effort.toLowerCase(), patch: { effort } }));
5349
6459
  }
5350
6460
 
6461
+ /** #1890 PR 2b: in a workspace conversation, "Make changes" — every change outside the AI's own folder asks first. */
6462
+ function permissionLabel(value) {
6463
+ if (state.scope?.owner?.kind === 'workspace' && value === 'workspace-write') return 'Make changes (asks first)';
6464
+ return permissionLabels[value] || 'Read only';
6465
+ }
6466
+
6467
+ /**
6468
+ * #2037: when Auto cannot do what it promises, the picker says so. Claude Haiku has no auto mode; Codex with the
6469
+ * person's own connectors on keeps asking, so each connector call still reaches its card (#1907).
6470
+ */
6471
+ function autoUnavailable() {
6472
+ if (state.chat?.integrationBindings?.length) return 'accounts';
6473
+ if (state.chat?.provider === 'codex') return state.chat?.settings?.useOwnConnectors === true ? 'connectors' : null;
6474
+ return state.chat?.provider === 'claude' && selectedModel()?.autoMode === false ? 'model' : null;
6475
+ }
6476
+
6477
+ function permissionMeta(value, workspace) {
6478
+ if (value === 'read-only') return 'Looks and answers. Changes nothing.';
6479
+ if (value === 'auto') {
6480
+ const why = autoUnavailable();
6481
+ if (why === 'connectors') return 'With your Codex connectors on, Codex asks you before steps that need approval.';
6482
+ if (why === 'accounts') return 'With a FloLess account selected, the AI asks you before steps that need approval.';
6483
+ return why ? 'Not available with this model. It asks before changes.' : 'Does safe work by itself. Checks risky steps first.';
6484
+ }
6485
+ if (value === 'workspace-write') return workspace ? 'Asks before changing project files.' : 'Asks you whenever the AI needs approval.';
6486
+ return 'Can change any file on this computer.';
6487
+ }
6488
+
6489
+ function permissionTip(value) {
6490
+ if (state.scope?.owner?.kind === 'workspace') return `Access: ${permissionLabel(value)}. Full access and Auto are offered only inside a project or workflow.`;
6491
+ const why = value === 'auto' ? autoUnavailable() : null;
6492
+ const label = why === 'connectors' ? 'Auto (asking first while your connectors are on)'
6493
+ : why === 'accounts' ? 'Auto (asking first while a FloLess account is selected)'
6494
+ : why ? 'Auto (asking first with this model)' : permissionLabel(value);
6495
+ return `Access: ${label}. ${permissionMeta(value || 'read-only', false)}`;
6496
+ }
6497
+
5351
6498
  function permissionChoices() {
5352
- // #1890: from the workspace, AI Chat reads and answers; it changes files only from a project or workflow.
5353
- const offered = state.scope?.owner?.kind === 'workspace'
5354
- ? Object.entries(permissionLabels).filter(([value]) => value === 'read-only')
5355
- : Object.entries(permissionLabels);
5356
- return offered.map(([value, label]) => ({
5357
- id: `permission:${value}`, label, meta: value === 'full-access' ? 'all local files' : value === 'workspace-write' ? 'project or workflow folder' : 'no file changes',
6499
+ // #1890 PR 2b: from the workspace, Full access is not offered — it would remove the approvals each change needs.
6500
+ // #2037: nor Auto — Codex's auto review would approve a change around the claim its card makes.
6501
+ const workspace = state.scope?.owner?.kind === 'workspace';
6502
+ const offered = workspace
6503
+ ? Object.keys(permissionLabels).filter((value) => value !== 'full-access' && value !== 'auto')
6504
+ : Object.keys(permissionLabels);
6505
+ return offered.map((value) => ({
6506
+ id: `permission:${value}`, label: permissionLabel(value), meta: permissionMeta(value, workspace),
5358
6507
  selected: state.chat.settings.permissionProfile === value, patch: { permissionProfile: value },
5359
6508
  }));
5360
6509
  }
5361
6510
 
6511
+ /** #2037: what Auto means in this conversation's Scope view; Codex's review may approve a change outside the folder. */
6512
+ function autoScopeNote() {
6513
+ const why = autoUnavailable();
6514
+ if (why === 'connectors') return 'Auto: while your Codex connectors are on, Codex asks you — instead of its own review — before any step that needs approval, so each connector call reaches its card. Turn the connectors off to let its review decide. Scope does not limit file reads.';
6515
+ if (why === 'accounts') return 'Auto: while a FloLess account is selected for this chat, the AI asks you — instead of its own review — before any step that needs approval, so that account stays its only way to reach the service. Scope does not limit file reads.';
6516
+ if (why) return 'Auto isn’t available with this model, so the AI asks before changes. File edits outside your home folder ask for approval. Scope does not limit file reads.';
6517
+ return state.chat?.provider === 'codex'
6518
+ ? 'Auto: Codex’s built-in review checks each step. Safe changes go ahead; risky ones, like deleting, are held back. Its review may also approve a change outside your home folder on its own — each decision is noted in the conversation. Scope does not limit file reads.'
6519
+ : 'Auto: Claude checks each step itself. Safe changes in your home folder go ahead; it asks you before touching anything outside it, and holds back risky steps like deleting. Scope does not limit file reads.';
6520
+ }
6521
+
5362
6522
  async function loadIntegrations() {
5363
6523
  const snapshot = captureChat();
5364
6524
  if (!snapshot) return null;
@@ -5429,7 +6589,7 @@
5429
6589
  if (!snapshot) return;
5430
6590
  if (ui.integrations.disabled) return;
5431
6591
  if (state.picker === 'integrations') { closePicker(); return; }
5432
- toggleHistory(false); closePicker(); state.picker = 'integrations';
6592
+ toggleHistory(false); closePicker(); state.picker = 'integrations'; state.pickerOpener = ui.integrations;
5433
6593
  ui.integrations.setAttribute('aria-expanded', 'true'); ui.picker.hidden = false;
5434
6594
  const loading = document.createElement('div'); loading.className = 'ai-chat-integration-empty'; loading.textContent = 'Checking FloLess accounts…';
5435
6595
  ui.picker.replaceChildren(loading);
@@ -5464,8 +6624,21 @@
5464
6624
  const settingUp = Boolean(state.capability?.runtime && state.capability.runtime.state !== 'installed');
5465
6625
  const uploading = Boolean(state.chat?.chatId && state.uploadingChatIds.has(state.chat.chatId));
5466
6626
  ui.input.disabled = state.followupSubmitting || !state.chat || Boolean(state.chat?.archivedAt) || recovery || blocked;
6627
+ // #1890 PR 3b: while the conversation moves, typing goes on (the draft is kept) and Send waits. Inline, not a helper:
6628
+ // several harnesses run this function on its own.
6629
+ const movingTo = state.chat?.rehome && ['freezing', 'copying', 'publishing'].includes(state.chat.rehome.state)
6630
+ && state.scope?.owner?.kind === 'workspace' ? state.chat.rehome.to.label : null;
6631
+ const moving = Boolean(movingTo);
6632
+ if (moving) {
6633
+ ui.hint.textContent = `Moving this conversation into workflow ${movingTo} — one moment.`;
6634
+ if (!state.movingPoll) {
6635
+ const movingChatId = state.chat.chatId;
6636
+ state.movingPoll = setTimeout(() => { state.movingPoll = null; void checkMoveProgress(movingChatId); }, 800);
6637
+ }
6638
+ }
5467
6639
  ui.send.disabled = state.loading || state.followupSubmitting || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen
5468
6640
  || (!ui.input.value.trim() && state.attachments.length === 0) || settingUp;
6641
+ if (moving) ui.send.disabled = true;
5469
6642
  // The paperclip is the same on every surface, the Drawing Filter included (#1681, #1859): a message
5470
6643
  // there carries the filter's context AND whatever the person attached, under the general rules only.
5471
6644
  ui.attach.disabled = state.loading || state.followupSubmitting || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen;
@@ -6490,12 +7663,22 @@
6490
7663
  paintConversation();
6491
7664
  announce('Applying your choice…');
6492
7665
  try {
6493
- await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/approvals/${encodeURIComponent(approvalId)}`, {
7666
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/approvals/${encodeURIComponent(approvalId)}`, {
6494
7667
  method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, decision,
6495
7668
  ...(decision === 'allow-chat' ? { allowanceRevision } : {}) }),
6496
7669
  });
6497
7670
  if (!sameChat(snapshot)) return;
6498
- announce(decision === 'allow-request' ? 'Access auto-approval is on for this request.'
7671
+ // #1890 PR 2b: the server says what it actually did. A change it refused at its last check is announced with the
7672
+ // reason it gave, never as allowed.
7673
+ const outcome = result?.outcome;
7674
+ const refusal = typeof outcome?.reason === 'string' && outcome.reason ? outcome.reason : '';
7675
+ announce(refusal ? refusal
7676
+ // The request ended before the choice reached the AI (it was stopped or withdrawn): claim nothing about it.
7677
+ : outcome?.delivered === false ? 'This request ended before your choice reached the AI.'
7678
+ : decision === 'allow-request' ? 'Access auto-approval is on for this request.'
7679
+ : 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.'
7680
+ : decision === 'allow-chat' && approval.connectionCheck ? `Checks of ${approval.connectionCheck.name || 'this tool'} are allowed for this chat. Revoke them above the message box.`
7681
+ : decision === 'allow-chat' && approval.connector ? `${connectorLabel(approval.connector)} is allowed for this chat. Revoke it above the message box.`
6499
7682
  : decision === 'allow-chat' ? 'Tekla reads are allowed for this chat. Revoke them from the Tekla box above the message.'
6500
7683
  : decision === 'allow' ? 'Approved once.' : 'Action denied.');
6501
7684
  await refreshConversation(snapshot.chatId, false);
@@ -6538,12 +7721,15 @@
6538
7721
  }
6539
7722
 
6540
7723
  /**
6541
- * The cut a large data file gets, said on its chip, or ''. Measured in bytes because that is what a
6542
- * stored attachment records; a UTF-8 file never has more characters than bytes, so a file at or under
6543
- * the limit is always read whole, and "up to" keeps the sentence true for one just over it.
7724
+ * The cut a large data file gets, said on its chip, or ''. Measured in the characters the server decoded
7725
+ * (`textChars`), because a UTF-16 file has about half as many characters as bytes and is read whole well
7726
+ * past 16,000 bytes (#1889). A file stored before that was recorded falls back to bytes: a UTF-8 file never
7727
+ * has more characters than bytes, so one at or under the limit is always read whole, and "up to" keeps the
7728
+ * sentence true for one just over it.
6544
7729
  */
6545
7730
  function dataCutTip(attachment) {
6546
- if (!DATA_TYPES.has(attachment.mediaType) || (attachment.bytes || 0) <= MAX_DATA_TEXT_CHARS) return '';
7731
+ const size = Number.isFinite(attachment.textChars) ? attachment.textChars : (attachment.bytes || 0);
7732
+ if (!DATA_TYPES.has(attachment.mediaType) || size <= MAX_DATA_TEXT_CHARS) return '';
6547
7733
  return 'Large file. The AI reads up to its first 16,000 characters.';
6548
7734
  }
6549
7735
 
@@ -6551,19 +7737,42 @@
6551
7737
  * Can FloLess read this data file, and what is it? The browser-side twin of server/attachment-text.ts
6552
7738
  * (isDwg + sniffTextKind), run on the WHOLE file before anything in the batch uploads, so a refused
6553
7739
  * file never reaches the server (#1853). A parity test runs both over the same fixtures.
6554
- * Returns 'dwg', 'ifc', 'dxf', 'text', or null for a file that is not readable text.
7740
+ * Returns 'dwg', 'ifc', 'dxf', 'text', 'utf16' (a UTF-16 file that could not be read), or null for a file that is not readable text.
6555
7741
  */
6556
7742
  function sniffDataFile(bytes) {
6557
7743
  // A DWG is named only when the file is not text: a CSV may begin "AC1234,…" (isDwg).
6558
7744
  const dwg = bytes.length >= 6 && bytes[0] === 0x41 && bytes[1] === 0x43
6559
7745
  && [2, 3, 4, 5].every((i) => bytes[i] >= 0x30 && bytes[i] <= 0x39);
6560
7746
  const kind = sniffTextBytes(bytes);
6561
- return kind || (dwg ? 'dwg' : null);
7747
+ if (kind) return kind;
7748
+ // A UTF-16 file (FF FE / FE FF) the sniffer could not read is named, so the refusal can say "save it as CSV UTF-8" (#1889).
7749
+ if (bytes.length >= 2 && ((bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0xfe && bytes[1] === 0xff))) return 'utf16';
7750
+ return dwg ? 'dwg' : null;
6562
7751
  }
6563
7752
 
6564
7753
  /** The text half of sniffDataFile: 'ifc', 'dxf', 'text', or null (server/attachment-text.ts sniffTextKind). */
6565
7754
  function sniffTextBytes(bytes) {
6566
- if (!bytes.length || bytes.includes(0)) return null;
7755
+ if (!bytes.length) return null;
7756
+ const headKind = (head) => head.startsWith('ISO-10303-21') ? 'ifc' : /^\s*0\s*[\r\n]+\s*SECTION/.test(head) ? 'dxf' : 'text';
7757
+ // A UTF-16 file (Excel "Unicode Text") is full of NULs by design: judge its DECODED text (server decodeUtf16, #1889).
7758
+ if ((bytes[0] === 0xff && bytes[1] === 0xfe) || (bytes[0] === 0xfe && bytes[1] === 0xff)) {
7759
+ let body = bytes.subarray(2);
7760
+ if (body.length % 2) return null;
7761
+ if (bytes[0] === 0xfe) {
7762
+ body = new Uint8Array(body);
7763
+ for (let i = 0; i < body.length; i += 2) { const t = body[i]; body[i] = body[i + 1]; body[i + 1] = t; }
7764
+ }
7765
+ let text;
7766
+ try { text = new TextDecoder('utf-16le', { fatal: true }).decode(body); } catch { return null; }
7767
+ if (!text.length || text.includes('\0')) return null;
7768
+ let readable = 0;
7769
+ for (let i = 0; i < text.length; i++) {
7770
+ const c = text.charCodeAt(i);
7771
+ if (c === 0x09 || c === 0x0a || c === 0x0d || (c >= 0x20 && c !== 0x7f)) readable++;
7772
+ }
7773
+ return readable / text.length <= 0.9 ? null : headKind(text.slice(0, 512));
7774
+ }
7775
+ if (bytes.includes(0)) return null;
6567
7776
  let printable = 0;
6568
7777
  for (const byte of bytes) {
6569
7778
  if (byte === 0x09 || byte === 0x0a || byte === 0x0d || (byte >= 0x20 && byte !== 0x7f)) printable++;
@@ -6574,9 +7783,7 @@
6574
7783
  if (!utf8 && bytes.filter((byte) => byte >= 0x80).length / bytes.length > 0.3) return null;
6575
7784
  let head = '';
6576
7785
  for (const byte of bytes.subarray(0, 512)) head += String.fromCharCode(byte);
6577
- if (head.startsWith('ISO-10303-21')) return 'ifc';
6578
- if (/^\s*0\s*[\r\n]+\s*SECTION/.test(head)) return 'dxf';
6579
- return 'text';
7786
+ return headKind(head);
6580
7787
  }
6581
7788
 
6582
7789
  /**
@@ -6593,6 +7800,7 @@
6593
7800
  return `“${file.name}” could not be read. Check that the file is still there, then attach it again. Nothing was attached.`;
6594
7801
  }
6595
7802
  if (kind === 'dwg') return `“${file.name}” is a DWG, which FloLess can’t read. Export it as IFC or PDF and attach that instead. Nothing was sent.`;
7803
+ if (kind === 'utf16') return `“${file.name}” is a UTF-16 text file that FloLess couldn’t read. Save it as “CSV UTF-8” and attach that instead. Nothing was sent.`;
6596
7804
  if (kind) return null;
6597
7805
  if (String(file.type || '').startsWith('image/')) {
6598
7806
  return `“${file.name}” is a picture format FloLess can’t send. Save it as PNG, JPEG or WebP and attach that instead. Nothing was sent.`;
@@ -6600,6 +7808,33 @@
6600
7808
  return `“${file.name}” isn’t a file type FloLess can read. Attach a picture, PDF, IFC, DXF, or a text file such as CSV. Nothing was sent.`;
6601
7809
  }
6602
7810
 
7811
+ /**
7812
+ * The browser twin of server/attachment-text.ts pictureMismatchSentence (#1888): a file the browser
7813
+ * calls a picture or PDF is only that when its first bytes say so, so a DWG renamed .pdf is turned
7814
+ * away at the chooser. Returns the plain sentence, or null when the bytes match the declared type.
7815
+ */
7816
+ async function pictureFileRefusal(file) {
7817
+ let bytes;
7818
+ try { bytes = new Uint8Array(await file.slice(0, 1024).arrayBuffer()); }
7819
+ catch (error) {
7820
+ console.warn('[ai-chat] a chosen file could not be read', error);
7821
+ return `“${file.name}” could not be read. Check that the file is still there, then attach it again. Nothing was attached.`;
7822
+ }
7823
+ const at = (offset, sig) => sig.every((byte, i) => bytes[offset + i] === byte);
7824
+ const ascii = (text) => [...text].map((ch) => ch.charCodeAt(0));
7825
+ // A PDF may carry a short preamble: the header can sit anywhere in the first 1024 bytes (server twin).
7826
+ const hasPdfHeader = () => { for (let i = 0; i + 5 <= bytes.length; i++) if (at(i, ascii('%PDF-'))) return true; return false; };
7827
+ const kind = at(0, [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]) ? 'image/png'
7828
+ : at(0, [0xff, 0xd8, 0xff]) ? 'image/jpeg'
7829
+ : at(0, ascii('RIFF')) && at(8, ascii('WEBP')) ? 'image/webp'
7830
+ : hasPdfHeader() ? 'application/pdf' : null;
7831
+ if (kind === file.type) return null;
7832
+ const dwg = bytes.length >= 6 && bytes[0] === 0x41 && bytes[1] === 0x43 && [2, 3, 4, 5].every((i) => bytes[i] >= 0x30 && bytes[i] <= 0x39);
7833
+ if (dwg) return `“${file.name}” is a DWG, which FloLess can’t read. Export it as IFC or PDF and attach that instead. Nothing was sent.`;
7834
+ const words = { 'image/png': 'a real PNG picture', 'image/jpeg': 'a real JPEG picture', 'image/webp': 'a real WebP picture', 'application/pdf': 'a real PDF' }[file.type] || 'a real picture';
7835
+ return `“${file.name}” doesn’t look like ${words} inside, so FloLess can’t send it. Save or export it again from the program that made it, then attach it. Nothing was sent.`;
7836
+ }
7837
+
6603
7838
  /**
6604
7839
  * An error whose message is already the whole plain sentence the person should read. Without the mark
6605
7840
  * errorMessage() replaces an unrecognised message with "FloLess could not complete this chat action",
@@ -6652,6 +7887,11 @@
6652
7887
  if (!sameChat(snapshot)) return;
6653
7888
  if (refusal) { report(plainError(refusal)); return; }
6654
7889
  }
7890
+ for (const file of incoming.filter((item) => !isData(item))) {
7891
+ const refusal = await pictureFileRefusal(file);
7892
+ if (!sameChat(snapshot)) return;
7893
+ if (refusal) { report(plainError(refusal)); return; }
7894
+ }
6655
7895
  for (const file of incoming) {
6656
7896
  const data = await fileBase64(file);
6657
7897
  if (!sameChat(snapshot)) return;
@@ -6708,7 +7948,7 @@
6708
7948
  }
6709
7949
  if (!sameScope(scope, generation)) return;
6710
7950
  state.chats = result.chats || [];
6711
- state.unreadableChats = result.unreadableChats || [];
7951
+ state.unreadableChats = result.unreadableChats || []; noteMovedChats(result.movedChats);
6712
7952
  const active = state.chats.find((item) => item.chatId === state.chat?.chatId);
6713
7953
  if (active && state.chat) {
6714
7954
  // An event-stream completion can win the race against this list request. Never let a
@@ -6855,9 +8095,22 @@
6855
8095
 
6856
8096
  async function openConversation(chatId, options = {}) {
6857
8097
  await refreshScope();
8098
+ if (options.owner !== undefined) {
8099
+ const owner = options.owner;
8100
+ const validId = (id) => typeof id === 'string' && !!id && id.length <= 200;
8101
+ if (!owner || typeof owner !== 'object'
8102
+ || !(owner.kind === 'workspace' || owner.kind === 'project' && validId(owner.projectId)
8103
+ || owner.kind === 'workflow' && validId(owner.workflowId))) throw new Error('That conversation has no valid home to open.');
8104
+ if (scopeKey({ owner }) !== scopeKey(state.scope)) {
8105
+ if (typeof window.flolessWorkspaces?.openChatOwner !== 'function') throw new Error('Open the project or workflow this conversation belongs to, then choose Show in chat again.');
8106
+ await window.flolessWorkspaces.openChatOwner(owner);
8107
+ await refreshScope(true);
8108
+ }
8109
+ if (scopeKey({ owner }) !== scopeKey(state.scope)) throw new Error('The conversation’s home could not be opened. Try Show in chat again.');
8110
+ }
6858
8111
  if (!state.scope?.owner) throw new Error('Open this conversation’s project or workflow, then try again.');
6859
- // An object card names its project; a conversation is only ever asked for in that project's scope (#1653).
6860
- if (typeof options.projectId === 'string' && (state.scope.owner.kind !== 'project' || state.scope.owner.projectId !== options.projectId)) {
8112
+ // Legacy object cards name only their project. New cross-project pins carry the server-resolved chat home.
8113
+ if (options.owner === undefined && typeof options.projectId === 'string' && (state.scope.owner.kind !== 'project' || state.scope.owner.projectId !== options.projectId)) {
6861
8114
  throw new Error('Open this project in Workspaces to see that conversation.');
6862
8115
  }
6863
8116
  if (typeof options.ownerKey === 'string' && scopeKey(state.scope) !== options.ownerKey) {
@@ -6865,7 +8118,9 @@
6865
8118
  }
6866
8119
  window.flolessBridge?.revealAiChat?.();
6867
8120
  ui.tab.click();
8121
+ const requestedScope = scopeKey(state.scope);
6868
8122
  const listed = await request(`/api/chat/conversations?${ownerQuery()}`);
8123
+ if (scopeKey(state.scope) !== requestedScope) throw new Error('The project or workflow changed while this conversation was opening. Choose Show in chat again.');
6869
8124
  state.chats = listed.chats || [];
6870
8125
  paintHistory(); paintUnread();
6871
8126
  const messageEventId = typeof options.messageEventId === 'string' ? options.messageEventId : undefined;
@@ -7053,6 +8308,348 @@
7053
8308
  }
7054
8309
  }
7055
8310
 
8311
+ function paintScopeControl() {
8312
+ if (!ui.scopeControls) return;
8313
+ const chat = state.chat;
8314
+ ui.scopeControls.hidden = !chat || Boolean(chat.archivedAt);
8315
+ if (!chat) { closeScopePicker(); return; }
8316
+ if (state.scopeViewChatId !== chat.chatId) { state.scopeView = null; closeScopePicker(); }
8317
+ if (state.scopeView && state.scopeView.scope.revision !== (chat.scopeRevision ?? 0)) {
8318
+ state.scopeView = null; closeScopePicker();
8319
+ }
8320
+ const count = Array.isArray(chat.scopeExtensions) ? chat.scopeExtensions.length : 0;
8321
+ const home = state.scopeView?.scope?.home?.label || state.scope?.label || 'Home';
8322
+ ui.scopeToggle.textContent = `Scope · ${home}${count ? ` + ${count}` : ''}`;
8323
+ ui.scopeToggle.dataset.tip = 'See the conversation’s home folder and add or remove other projects and workflows.';
8324
+ ui.scopeToggle.disabled = state.loading;
8325
+ if (ui.scopeToggle.disabled) ui.scopeToggle.dataset.blockedReason = 'The conversation is still loading.';
8326
+ else delete ui.scopeToggle.dataset.blockedReason;
8327
+ const disclosure = chat.settings?.permissionProfile === 'read-only'
8328
+ ? 'Read only: the AI’s file tools cannot change files. Commands keep their own approvals and may authorize file changes.'
8329
+ : chat.settings?.permissionProfile === 'full-access' ? 'Full access is on. The AI can change files without asking.'
8330
+ : chat.settings?.permissionProfile === 'auto' ? autoScopeNote()
8331
+ : chat.changeAllowance?.allowedForChat ? 'File changes in scope, including folders you add later, are allowed for this chat.' : '';
8332
+ if (ui.scopeDisclosure.textContent !== disclosure) ui.scopeDisclosure.textContent = disclosure;
8333
+ // Poll/SSE can change permissions or pause a reply while Scope stays open. Refresh only when
8334
+ // these states change, retaining its selected add choice and focus on an enabled control.
8335
+ const picker = ui.scopePicker;
8336
+ const availability = JSON.stringify([Boolean(chat.activeTurn), Boolean(chat.pendingApproval), Boolean(state.scopeEditing), chat.settings?.permissionProfile, Boolean(chat.changeAllowance?.allowedForChat)]);
8337
+ if (state.scopePickerOpen && state.scopeView && picker?.dataset.availability !== availability) {
8338
+ const focused = picker.contains(document.activeElement) ? document.activeElement?.dataset?.commandId : null;
8339
+ paintScopePicker();
8340
+ if (focused) {
8341
+ const buttons = [...picker.querySelectorAll('button')];
8342
+ const target = buttons.find((node) => node.dataset.commandId === focused && !node.disabled)
8343
+ || buttons.find((node) => !node.disabled);
8344
+ target?.focus();
8345
+ }
8346
+ }
8347
+ }
8348
+
8349
+ function closeScopePicker(restoreFocus = false) {
8350
+ state.scopePickerOpen = false; state.scopeChoice = null;
8351
+ if (ui.scopePicker) { ui.scopePicker.hidden = true; ui.scopePicker.replaceChildren(); }
8352
+ ui.scopeToggle?.setAttribute('aria-expanded', 'false');
8353
+ if (restoreFocus) ui.scopeToggle?.focus();
8354
+ }
8355
+
8356
+ async function openScopePicker() {
8357
+ if (state.scopePickerOpen) { closeScopePicker(true); return; }
8358
+ const snapshot = captureChat();
8359
+ if (!snapshot || state.chat.archivedAt) return;
8360
+ closePicker(); state.scopeChoice = null; state.scopePickerOpen = true; state.scopeViewChatId = snapshot.chatId;
8361
+ ui.scopePicker.hidden = false; ui.scopeToggle.setAttribute('aria-expanded', 'true');
8362
+ ui.scopePicker.textContent = 'Loading conversation scope…';
8363
+ try {
8364
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/scope?${ownerQuery(snapshot.scope.owner)}`);
8365
+ if (!sameChat(snapshot) || !state.scopePickerOpen) return;
8366
+ state.scopeView = result; state.scopeViewChatId = snapshot.chatId;
8367
+ state.chat = { ...state.chat, scopeExtensions: result.scope.extensions.map((entry) => entry.target), scopeRevision: result.scope.revision, changeAllowance: result.changeAllowance };
8368
+ paintScopePicker(); paintScopeControl();
8369
+ ui.scopePicker.querySelector('button')?.focus();
8370
+ } catch (error) {
8371
+ if (sameChat(snapshot) && state.scopePickerOpen) { closeScopePicker(true); report(error, 'Could not load conversation scope'); }
8372
+ }
8373
+ }
8374
+
8375
+ function paintScopePicker() {
8376
+ const host = ui.scopePicker;
8377
+ if (!host || !state.scopePickerOpen || !state.scopeView) return;
8378
+ const view = state.scopeView;
8379
+ const profile = state.chat?.settings?.permissionProfile;
8380
+ const readOnly = profile === 'read-only';
8381
+ const globalAllowance = Boolean(state.chat?.changeAllowance?.allowedForChat);
8382
+ host.dataset.availability = JSON.stringify([Boolean(state.chat?.activeTurn), Boolean(state.chat?.pendingApproval), Boolean(state.scopeEditing), profile, globalAllowance]);
8383
+ host.replaceChildren();
8384
+ const heading = document.createElement('strong'); heading.textContent = 'Conversation scope';
8385
+ const close = button('×', 'shell.chat-scope-close', 'ai-chat-scope-close');
8386
+ close.setAttribute('aria-label', 'Close conversation scope'); close.dataset.tip = 'Close conversation scope';
8387
+ close.addEventListener('click', () => closeScopePicker(true));
8388
+ const head = document.createElement('div'); head.className = 'ai-chat-scope-head'; head.append(heading, close); host.append(head);
8389
+ const note = document.createElement('p'); note.className = 'ai-chat-scope-note';
8390
+ note.textContent = readOnly ? 'The AI’s file tools cannot change files while Read only is on. Commands keep their own approvals and may authorize file changes. Scope adds folders and project data; it does not limit file reads.'
8391
+ + (globalAllowance ? ' Your saved file-change allowance does not override Read only.' : '')
8392
+ : profile === 'full-access' ? 'Full access is on. The AI can change files without asking.'
8393
+ : profile === 'auto' ? autoScopeNote()
8394
+ : globalAllowance ? 'File changes in this scope, including folders you add later, are allowed without asking. Commands and tools keep their own approvals. Scope does not limit file reads.'
8395
+ : 'File edits outside your home folder ask for approval unless you allow file changes for this chat. Scope adds folders and project data to this conversation; it does not limit file reads. Your home folder keeps its native provider permissions.';
8396
+ host.append(note);
8397
+ if (view.scope.dropped?.length) {
8398
+ const dropped = document.createElement('p'); dropped.className = 'ai-chat-scope-note'; dropped.setAttribute('role', 'status');
8399
+ dropped.textContent = 'An added project or workflow is no longer available and has been removed from this conversation’s scope.';
8400
+ host.append(dropped);
8401
+ }
8402
+ const home = document.createElement('div'); home.className = 'ai-chat-scope-row';
8403
+ const homeName = document.createElement('span'); homeName.textContent = view.scope.home.label;
8404
+ const pinned = document.createElement('small'); pinned.textContent = 'Home'; home.append(homeName, pinned); host.append(home);
8405
+ for (const entry of view.scope.extensions) {
8406
+ const row = document.createElement('div'); row.className = 'ai-chat-scope-row';
8407
+ const name = document.createElement('span'); name.textContent = `${entry.target.kind === 'project' ? 'Project' : 'Workflow'} · ${entry.label}`;
8408
+ const targetId = entry.target.kind === 'project' ? entry.target.projectId : entry.target.workflowId;
8409
+ const remove = button('Remove', `shell.chat-scope-remove#${commandInstance(`${entry.target.kind}:${targetId}`)}`, 'ai-chat-scope-action');
8410
+ remove.dataset.commandInstanceLabel = entry.label;
8411
+ remove.setAttribute('aria-label', `Remove ${entry.target.kind} ${entry.label} from this conversation’s scope`);
8412
+ const removeBlocked = state.scopeEditing ? 'Saving conversation scope…'
8413
+ : state.chat?.activeTurn && !state.chat?.pendingApproval ? 'Wait for the current reply to finish before removing scope.' : '';
8414
+ remove.disabled = Boolean(removeBlocked);
8415
+ if (removeBlocked) { remove.dataset.blockedReason = removeBlocked; remove.dataset.tip = removeBlocked; }
8416
+ remove.addEventListener('click', () => { void mutateScope('remove', entry.target, entry.label); });
8417
+ row.append(name, remove); host.append(row);
8418
+ }
8419
+ if (state.chat?.activeTurn) {
8420
+ const busy = document.createElement('p'); busy.className = 'ai-chat-scope-note';
8421
+ busy.textContent = state.chat.pendingApproval ? 'You can remove a folder while this reply waits for approval. Add folders after the reply finishes.' : 'Wait for the current reply to finish before changing scope.';
8422
+ host.append(busy);
8423
+ }
8424
+ if (state.scopeChoice) {
8425
+ const choice = state.scopeChoice;
8426
+ const choiceKey = choice.target.kind === 'project' ? choice.target.projectId : choice.target.workflowId;
8427
+ const question = document.createElement('p'); question.className = 'ai-chat-scope-note';
8428
+ const writeProfile = state.chat?.owner?.kind === 'workspace' ? 'Make changes (asks first)' : 'Working folder write';
8429
+ question.textContent = `Add ${choice.target.kind} “${choice.label}” to this conversation?${globalAllowance ? readOnly
8430
+ ? ` If you choose ${writeProfile}, file changes here will also be allowed without asking.`
8431
+ : ' File changes here will also be allowed without asking.' : ''}`;
8432
+ const add = button(globalAllowance ? readOnly ? 'Add scope for later file changes' : 'Add scope and allow file changes' : 'Add scope', `shell.chat-scope-add#${commandInstance(`${choice.target.kind}:${choiceKey}`)}`, 'ai-chat-scope-action');
8433
+ add.dataset.commandInstanceLabel = choice.label; add.disabled = state.scopeEditing || Boolean(state.chat?.activeTurn);
8434
+ if (add.disabled) { add.dataset.blockedReason = state.scopeEditing ? 'Saving conversation scope…' : 'Wait for the current reply to finish before adding scope.'; add.dataset.tip = add.dataset.blockedReason; }
8435
+ add.addEventListener('click', () => { void mutateScope('add', choice.target, choice.label); });
8436
+ const back = button('Back', 'shell.chat-scope-back', 'ai-chat-scope-action'); back.disabled = state.scopeEditing;
8437
+ if (back.disabled) { back.dataset.blockedReason = 'Saving conversation scope…'; back.dataset.tip = back.dataset.blockedReason; }
8438
+ back.addEventListener('click', () => { state.scopeChoice = null; paintScopePicker(); host.querySelector('button')?.focus(); });
8439
+ host.append(question, add, back);
8440
+ } else {
8441
+ const title = document.createElement('strong'); title.textContent = 'Add project or workflow'; host.append(title);
8442
+ const options = (view.options || []).filter((option) => !option.inScope);
8443
+ if (!options.length) {
8444
+ const empty = document.createElement('p'); empty.className = 'ai-chat-scope-note'; empty.textContent = 'No other projects or workflows to add.'; host.append(empty);
8445
+ }
8446
+ for (const option of options) {
8447
+ const key = option.target.kind === 'project' ? option.target.projectId : option.target.workflowId;
8448
+ const choose = button(`${option.target.kind === 'project' ? 'Project' : 'Workflow'} · ${option.label}`, `shell.chat-scope-choose#${commandInstance(`${option.target.kind}:${key}`)}`, 'ai-chat-choice');
8449
+ choose.dataset.commandInstanceLabel = option.label; choose.disabled = state.scopeEditing || Boolean(state.chat?.activeTurn);
8450
+ if (choose.disabled) { choose.dataset.blockedReason = state.scopeEditing ? 'Saving conversation scope…' : 'Wait for the current reply to finish before adding scope.'; choose.dataset.tip = choose.dataset.blockedReason; }
8451
+ choose.addEventListener('click', () => { state.scopeChoice = option; paintScopePicker(); host.querySelector('[data-command-id^="shell.chat-scope-add#"]')?.focus(); });
8452
+ host.append(choose);
8453
+ }
8454
+ }
8455
+ }
8456
+
8457
+ async function mutateScope(verb, target, label) {
8458
+ const snapshot = captureChat();
8459
+ if (!snapshot || state.scopeEditing || !state.scopeView) return;
8460
+ const view = state.scopeView;
8461
+ state.scopeEditing = true; paintScopePicker();
8462
+ try {
8463
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/scope/${verb}`, {
8464
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, target, revision: view.scope.revision,
8465
+ ...(verb === 'add' ? { allowanceRevision: view.changeAllowance?.revision ?? 0 } : {}) }),
8466
+ });
8467
+ if (!sameChat(snapshot)) return;
8468
+ state.scopeView = result; state.scopeViewChatId = snapshot.chatId; state.scopeChoice = null;
8469
+ state.chat = { ...state.chat, scopeExtensions: result.scope.extensions.map((entry) => entry.target), scopeRevision: result.scope.revision, changeAllowance: result.changeAllowance };
8470
+ announce(verb === 'add' ? `${label} added to this conversation’s scope.` : `${label} removed from this conversation’s scope. Changes already made are kept.`);
8471
+ paintScopeControl(); paintChangeAllowance();
8472
+ } catch (error) {
8473
+ if (sameChat(snapshot)) {
8474
+ report(error, 'Could not change conversation scope');
8475
+ // A different tab can change either revision while this confirmation is open.
8476
+ // Refresh the disclosed permission before offering another Add; never retry silently.
8477
+ if (error?.status === 409 && state.scopePickerOpen) {
8478
+ try {
8479
+ const current = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/scope?${ownerQuery(snapshot.scope.owner)}`);
8480
+ if (sameChat(snapshot) && state.scopePickerOpen) {
8481
+ state.scopeView = current; state.scopeChoice = null;
8482
+ state.chat = { ...state.chat, scopeExtensions: current.scope.extensions.map((entry) => entry.target), scopeRevision: current.scope.revision, changeAllowance: current.changeAllowance };
8483
+ paintScopeControl(); paintChangeAllowance();
8484
+ }
8485
+ } catch { /* Keep the original refusal visible; the person can reopen Scope to retry. */ }
8486
+ }
8487
+ }
8488
+ } finally {
8489
+ state.scopeEditing = false;
8490
+ if (sameChat(snapshot) && state.scopePickerOpen) { paintScopePicker(); ui.scopePicker.querySelector('button')?.focus(); }
8491
+ }
8492
+ }
8493
+
8494
+ // Legacy per-owner allowances remain removable when no conversation-wide file allowance covers them.
8495
+ function paintChangeAllowance() {
8496
+ const host = ui.changeAllowance;
8497
+ if (!host) return;
8498
+ const chat = state.chat;
8499
+ const allowed = chat && !chat.archivedAt && Array.isArray(chat.changeAllowance?.allowed)
8500
+ ? chat.changeAllowance.allowed : [];
8501
+ const global = chat && !chat.archivedAt && chat.changeAllowance?.allowedForChat;
8502
+ const readOnly = chat?.settings?.permissionProfile === 'read-only';
8503
+ const painted = `${chat?.chatId || ''}|${allowed.map((entry) => entry.key).join(',')}|${Boolean(global)}|${readOnly}|${state.changeRevoking || ''}`;
8504
+ if (host.dataset.painted === painted) return;
8505
+ host.dataset.painted = painted;
8506
+ host.replaceChildren();
8507
+ host.hidden = !allowed.length && !global;
8508
+ if (!allowed.length && !global) return;
8509
+ if (global) {
8510
+ const copy = document.createElement('span'); copy.textContent = readOnly ? 'File-change allowance saved; Read only blocks file tools' : 'File changes allowed for this chat';
8511
+ const revoke = button('Revoke', 'shell.chat-change-allowance-revoke-all', 'ai-chat-connector-revoke');
8512
+ revoke.dataset.tip = 'Future file changes will ask again where your permission setting requires approval. Your home folder keeps its current permissions.';
8513
+ revoke.disabled = state.changeRevoking === 'all';
8514
+ if (revoke.disabled) revoke.dataset.blockedReason = 'Revoking file-change allowance…';
8515
+ revoke.addEventListener('click', () => { void revokeChangeAllowance({ key: null, label: 'file changes in this chat' }); });
8516
+ host.append(copy, revoke);
8517
+ // A legacy owner-specific Revoke would imply that folder stops being allowed, but the
8518
+ // conversation-wide grant still covers it. Its one Revoke ends every standing file grant.
8519
+ return;
8520
+ }
8521
+ const title = document.createElement('span');
8522
+ title.className = 'ai-chat-connectors-title';
8523
+ title.textContent = readOnly ? 'Saved change allowances; Read only blocks file tools:' : 'Changes allowed for this chat:';
8524
+ host.append(title);
8525
+ for (const entry of allowed) {
8526
+ const pill = document.createElement('span');
8527
+ pill.className = 'ai-chat-connector-pill';
8528
+ const name = document.createElement('span');
8529
+ name.textContent = entry.label;
8530
+ const revoke = button('Revoke', `shell.chat-change-allowance-revoke#${entry.key}`, 'ai-chat-connector-revoke');
8531
+ revoke.dataset.commandInstanceLabel = entry.label;
8532
+ revoke.setAttribute('aria-label', `Stop allowing changes to ${entry.label}`);
8533
+ revoke.dataset.tip = readOnly ? `Remove the saved allowance for ${entry.label}. Read only continues to block file tools.` : `The AI will ask you again before it changes ${entry.label}.`;
8534
+ revoke.disabled = state.changeRevoking === entry.key;
8535
+ if (revoke.disabled) revoke.dataset.blockedReason = 'Revoking file-change allowance…';
8536
+ revoke.addEventListener('click', () => { void revokeChangeAllowance(entry); });
8537
+ pill.append(name, revoke);
8538
+ host.append(pill);
8539
+ }
8540
+ }
8541
+
8542
+ async function revokeChangeAllowance(entry) {
8543
+ const snapshot = captureChat();
8544
+ if (!snapshot) return;
8545
+ const revokingKey = entry.key ?? 'all';
8546
+ state.changeRevoking = revokingKey;
8547
+ paintChangeAllowance();
8548
+ try {
8549
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/change-allowance/revoke`, {
8550
+ method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, key: entry.key }),
8551
+ });
8552
+ if (!sameChat(snapshot)) return;
8553
+ // Only the server's own record, without that project, may say it ended.
8554
+ const updated = result?.chat;
8555
+ if (!updated || updated.chatId !== snapshot.chatId || (entry.key === null
8556
+ ? updated.changeAllowance?.allowedForChat || (updated.changeAllowance?.allowed || []).length
8557
+ : (updated.changeAllowance?.allowed || []).some((row) => row.key === entry.key))) {
8558
+ report(new Error(`FloLess could not confirm that ${entry.label} will ask again. Choose Revoke again.`), 'Could not revoke');
8559
+ return;
8560
+ }
8561
+ state.chat = { ...state.chat, changeAllowance: updated.changeAllowance };
8562
+ if (state.scopeViewChatId === snapshot.chatId && state.scopeView) state.scopeView.changeAllowance = updated.changeAllowance;
8563
+ announce(entry.key === null ? 'File change approval is restored where your permission setting requires it. Your home folder keeps its current permissions. Actions already approved may finish.' : `The AI will ask you again before it changes ${entry.label}.`);
8564
+ state.changeRevoking = null;
8565
+ paintChangeAllowance();
8566
+ (ui.changeAllowance?.querySelector('.ai-chat-connector-revoke') || ui.input)?.focus();
8567
+ } catch (error) {
8568
+ if (sameChat(snapshot)) report(error, 'Could not revoke');
8569
+ } finally {
8570
+ if (state.changeRevoking === revokingKey) state.changeRevoking = null;
8571
+ paintChangeAllowance();
8572
+ }
8573
+ }
8574
+
8575
+ // #1900: the connection checks this conversation may run without asking, each with its own Revoke (and Revoke all).
8576
+ function checkGrantKey(grant) { return `${grant.agent}${grant.alias ? `.${grant.alias}` : ''}`; }
8577
+ function checkGrantLabel(grant) { return `${grant.name || grant.agent} · ${grant.identity || grant.alias || 'this computer'}`; }
8578
+
8579
+ function paintCheckAllowance() {
8580
+ const host = ui.checkAllowance;
8581
+ if (!host) return;
8582
+ const chat = state.chat;
8583
+ const grants = chat && !chat.archivedAt && Array.isArray(chat.integrationReadAllowance?.grants) ? chat.integrationReadAllowance.grants : [];
8584
+ const painted = `${chat?.chatId || ''}|${grants.map((grant) => `${checkGrantKey(grant)}:${grant.identity || ''}`).join(',')}|${state.checkRevoking || ''}`;
8585
+ if (host.dataset.painted === painted) return;
8586
+ host.dataset.painted = painted;
8587
+ host.replaceChildren();
8588
+ host.hidden = !grants.length;
8589
+ if (!grants.length) return;
8590
+ const title = document.createElement('span');
8591
+ title.className = 'ai-chat-connectors-title';
8592
+ title.textContent = 'Checks allowed for this chat:';
8593
+ host.append(title);
8594
+ for (const grant of grants) {
8595
+ const pill = document.createElement('span');
8596
+ pill.className = 'ai-chat-connector-pill';
8597
+ const name = document.createElement('span');
8598
+ name.textContent = checkGrantLabel(grant);
8599
+ const key = checkGrantKey(grant);
8600
+ const who = grant.name || grant.agent;
8601
+ const revoke = button('Revoke', `shell.chat-check-allowance-revoke#${key}`, 'ai-chat-connector-revoke');
8602
+ revoke.dataset.commandInstanceLabel = checkGrantLabel(grant);
8603
+ revoke.setAttribute('aria-label', `Stop allowing checks of ${checkGrantLabel(grant)}`);
8604
+ revoke.dataset.tip = `Chat will ask you again before it checks ${who}.`;
8605
+ revoke.disabled = Boolean(state.checkRevoking);
8606
+ revoke.addEventListener('click', () => { void revokeCheckAllowance(grant); });
8607
+ pill.append(name, revoke);
8608
+ host.append(pill);
8609
+ }
8610
+ if (grants.length > 1) {
8611
+ const all = button('Revoke all', 'shell.chat-check-allowance-revoke-all', 'ai-chat-connector-revoke');
8612
+ all.setAttribute('aria-label', 'Stop allowing every connection check in this chat');
8613
+ all.dataset.tip = 'Chat will ask you again before every connection check in this conversation.';
8614
+ all.disabled = Boolean(state.checkRevoking);
8615
+ all.addEventListener('click', () => { void revokeCheckAllowance(null); });
8616
+ host.append(all);
8617
+ }
8618
+ }
8619
+
8620
+ /** Ends one grant (or, with none named, all of them). Only the server's own record, without it, may say it ended. */
8621
+ async function revokeCheckAllowance(grant) {
8622
+ const snapshot = captureChat();
8623
+ if (!snapshot || state.checkRevoking) return;
8624
+ const key = grant ? checkGrantKey(grant) : '*';
8625
+ state.checkRevoking = key;
8626
+ paintCheckAllowance();
8627
+ try {
8628
+ const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/integration-read-allowance/revoke`, {
8629
+ method: 'POST', body: JSON.stringify(grant ? { owner: snapshot.scope.owner, agent: grant.agent, alias: grant.alias ?? null } : { owner: snapshot.scope.owner }),
8630
+ });
8631
+ if (!sameChat(snapshot)) return;
8632
+ const updated = result?.chat;
8633
+ const left = updated?.integrationReadAllowance?.grants || [];
8634
+ if (!updated || updated.chatId !== snapshot.chatId || (grant ? left.some((row) => checkGrantKey(row) === key) : left.length)) {
8635
+ report(new Error(grant ? `FloLess could not confirm that checks of ${grant.name || grant.agent} will ask again. Choose Revoke again.`
8636
+ : 'FloLess could not confirm that every connection check will ask again. Choose Revoke all again.'), 'Could not revoke');
8637
+ return;
8638
+ }
8639
+ state.chat = { ...state.chat, integrationReadAllowance: updated.integrationReadAllowance };
8640
+ announce(grant ? `Chat will ask you again before it checks ${grant.name || grant.agent}.` : 'Chat will ask you again before every connection check.');
8641
+ state.checkRevoking = null;
8642
+ paintCheckAllowance();
8643
+ // The pressed Revoke is gone with its pill: keep keyboard focus on the next one, or on the message box.
8644
+ (ui.checkAllowance?.querySelector('.ai-chat-connector-revoke') || ui.input)?.focus();
8645
+ } catch (error) {
8646
+ if (sameChat(snapshot)) report(error, 'Could not revoke');
8647
+ } finally {
8648
+ if (state.checkRevoking === key) state.checkRevoking = null;
8649
+ paintCheckAllowance();
8650
+ }
8651
+ }
8652
+
7056
8653
  async function turnOffOwnConnectors() {
7057
8654
  state.ownConnectorsSaving = true;
7058
8655
  paintConnectorAllowance();
@@ -7229,7 +8826,7 @@
7229
8826
  // The earlier model name is deliberately left out: the open model may have changed since, and
7230
8827
  // the AI would repeat a stale name as current. A fresh read shows the name at that moment.
7231
8828
  return `Earlier FloLess check: reading the open model name through the Tekla model library at ${receipt.sourcePath} `
7232
- + `worked (Tekla ${receipt.hostVersion}${checked}). The generated agent's commands remain unverified. `
8829
+ + `worked (Tekla ${receipt.hostVersion}${checked}). The generated tool's commands remain unverified. `
7233
8830
  + 'You can ask to read the open model name or the parts I have selected in Tekla. Help me use these reads in this project.';
7234
8831
  }
7235
8832
 
@@ -7242,10 +8839,8 @@
7242
8839
  closeSource(); clearLiveStream(true);
7243
8840
  state.chat = null; state.events = []; state.attachments = []; state.integrations = null; state.capability = null;
7244
8841
  updateOffscreenActivity();
7245
- // The left chat's library chip ("added to this chat") must not linger over the chooser.
7246
- paintTeklaChip();
7247
- // Nor the left chat's "connectors are on" line and its allowances (#1907).
7248
- paintConnectorAllowance();
8842
+ // What the left chat painted above the composer is cleared by providerChooser(), which every route onto
8843
+ // the chooser runs (#1958) — not only this one.
7249
8844
  }
7250
8845
 
7251
8846
  // Graft receipt → unsent Chat draft. Opening performs no binding, sends nothing and never
@@ -7323,6 +8918,8 @@
7323
8918
  if (event.key === 'Escape') { event.preventDefault(); toggleHistory(false, { focusToggle: true }); }
7324
8919
  }
7325
8920
  ui.history.addEventListener('keydown', closeHistoryOnEscape);
8921
+ ui.picker.addEventListener('keydown', closePickerOnEscape);
8922
+ ui.integrations.addEventListener('keydown', closePickerOnEscape);
7326
8923
  ui.newChat.addEventListener('click', () => {
7327
8924
  beginProviderChoice();
7328
8925
  toggleHistory(false); setBusy(false); providerChooser(); clearReport();
@@ -7346,6 +8943,9 @@
7346
8943
  ui.switchAccount.addEventListener('click', () => { void switchAccount(); });
7347
8944
  ui.effort.addEventListener('click', () => openPicker('effort', ui.effort, effortChoices()));
7348
8945
  ui.permission.addEventListener('click', () => openPicker('permission', ui.permission, permissionChoices()));
8946
+ // #2046: the Guide's own controls (web/guide.js does the work and says what happened).
8947
+ el('chat-guide-off')?.addEventListener('click', () => { void window.flolessGuide?.turnOff?.(); });
8948
+ el('chat-guide-delete')?.addEventListener('click', () => { void window.flolessGuide?.deleteHistory?.(); });
7349
8949
  ui.ownConnectors?.addEventListener('click', () => {
7350
8950
  if (ui.ownConnectors.disabled || !state.chat) return;
7351
8951
  closePicker();
@@ -7372,6 +8972,13 @@
7372
8972
  if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { event.preventDefault(); sendTurn(); }
7373
8973
  else if (event.key === 'Escape') { ui.skills.hidden = true; closePicker(); }
7374
8974
  });
8975
+ ui.scopeToggle?.addEventListener('click', () => { void openScopePicker(); });
8976
+ ui.scopePicker?.addEventListener('keydown', (event) => {
8977
+ if (event.key === 'Escape') { event.preventDefault(); closeScopePicker(true); }
8978
+ });
8979
+ document.addEventListener('pointerdown', (event) => {
8980
+ if (state.scopePickerOpen && !ui.scopeControls?.contains(event.target)) closeScopePicker();
8981
+ });
7375
8982
  // Capture phase: the control's own handler runs after, so a sentence it reports is held afresh.
7376
8983
  shell.addEventListener('click', releaseReportOnControl, true);
7377
8984
  shell.addEventListener('dragover', (event) => { if (event.dataTransfer?.types.includes('Files')) event.preventDefault(); });
@@ -7429,7 +9036,7 @@
7429
9036
  paintAttachments();
7430
9037
  });
7431
9038
  window.flolessChat = {
7432
- refreshScope, refreshActivity, refreshIndex, startRequest, openConversation, openDraft, openVerifiedTeklaDraft,
9039
+ refreshScope, refreshActivity, refreshIndex, startRequest, openConversation, openConversationIn, openDraft, openVerifiedTeklaDraft,
7433
9040
  startProjectIntake, resumeProjectIntake,
7434
9041
  // The plain-English sentence for a refusal the chat routes named, so a Start outside this panel
7435
9042
  // (the upload modal, Requests) says what happened and what to do next instead of a generic toast (#1779).