@floless/app 0.156.0 → 0.158.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli-actions.mjs +28 -5
- package/dist/floless-server.cjs +110947 -67461
- package/dist/schemas/drawing-check.profile.v1.schema.json +15 -2
- package/dist/schemas/steel.model.v2.schema.json +25 -1
- package/dist/skills/floless-app-actions/SKILL.md +82 -17
- package/dist/skills/floless-app-knowledge/SKILL.md +34 -2
- package/dist/skills/floless-app-knowledge/references/schema.md +4 -1
- package/dist/skills/floless-app-new-workflow/SKILL.md +23 -7
- package/dist/skills/floless-app-onboarding/SKILL.md +31 -1
- package/dist/skills/floless-app-report-issue/SKILL.md +3 -3
- package/dist/skills/floless-app-rfi/SKILL.md +40 -6
- package/dist/skills/floless-app-routines/SKILL.md +9 -2
- package/dist/skills/floless-app-steel-model/SKILL.md +35 -1
- package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +4 -2
- package/dist/skills/floless-app-steel-takeoff/SKILL.md +51 -1
- package/dist/skills/floless-app-tweak-contract/SKILL.md +25 -5
- package/dist/skills/floless-app-workflows/SKILL.md +46 -10
- package/dist/skills/floless-app-workflows/references/agent-steps.md +119 -0
- package/dist/web/agent-steps.js +864 -47
- package/dist/web/agents.js +28 -8
- package/dist/web/app.css +620 -17
- package/dist/web/app.js +110 -11
- package/dist/web/aware-update-client.js +1 -0
- package/dist/web/aware.js +921 -220
- package/dist/web/chat-landing-scene.js +372 -0
- package/dist/web/chat.css +263 -1
- package/dist/web/chat.js +2660 -86
- package/dist/web/commands-drawing-check.js +17 -0
- package/dist/web/commands-shell.js +1059 -8
- package/dist/web/commands-steel.js +6 -0
- package/dist/web/connections.js +1 -0
- package/dist/web/drawing-check-editor.html +33 -5
- package/dist/web/drawing-check-editor.js +538 -22
- package/dist/web/drawing-check-overlay.js +13 -0
- package/dist/web/flo-avatar.js +28 -3
- package/dist/web/guide.js +7 -2
- package/dist/web/index.html +143 -8
- package/dist/web/instructor.js +4 -4
- package/dist/web/kb-categories.js +351 -0
- package/dist/web/kb-graph-worker.js +73 -0
- package/dist/web/model-view-query.js +12 -2
- package/dist/web/pages.js +978 -39
- package/dist/web/panels.js +5 -2
- package/dist/web/parser-setup-recovery.js +12 -4
- package/dist/web/project-access.js +549 -0
- package/dist/web/run-page-view.js +353 -0
- package/dist/web/startup-admission.js +132 -0
- package/dist/web/steel-3d-core.js +9 -0
- package/dist/web/steel-editor.html +681 -22
- package/dist/web/steel-model-v2-commands.js +63 -5
- package/dist/web/step-rename.js +287 -0
- package/dist/web/tab-signal.js +323 -0
- package/dist/web/terminal-requests.js +103 -13
- package/dist/web/tool-updates.js +1 -0
- package/dist/web/workspace-root-management.js +39 -0
- package/dist/web/workspaces.js +2883 -146
- package/launch-starting-page.mjs +181 -0
- package/launch.mjs +97 -12
- package/package.json +5 -1
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'), guideAccess: el('chat-guide-access'), integrations: el('chat-integrations'), ownConnectors: el('chat-own-connectors'),
|
|
22
|
+
effort: el('chat-effort'), permission: el('chat-permission'), suggest: el('chat-suggest'), 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'),
|
|
@@ -42,6 +42,8 @@
|
|
|
42
42
|
};
|
|
43
43
|
|
|
44
44
|
const state = {
|
|
45
|
+
// #2438: the picks waiting to go with the next message (per conversation), and the open @ list.
|
|
46
|
+
mentions: {}, mentionMenu: null, mentionDismissed: null,
|
|
45
47
|
scopeView: null, scopeViewChatId: null, scopeChoice: null, scopeEditing: false, scopePickerOpen: false,
|
|
46
48
|
accessExplanationExpanded: readAccessExplanationPreference(),
|
|
47
49
|
// signInPending is keyed by provider: a wait started in one conversation must not paint an
|
|
@@ -51,7 +53,8 @@
|
|
|
51
53
|
displayUnits: null, displayUnitsGeneration: 0,
|
|
52
54
|
// #1890 PR 3b: the workspace history's pointer rows, the move notice on screen, and moves being followed now.
|
|
53
55
|
movedChats: [], movedChatsKnown: null, moveNotice: null, moveNoticeTimer: null, followingMoves: new Set(), movingPoll: null,
|
|
54
|
-
sessionReady: false,
|
|
56
|
+
sessionReady: false, sessionOperation: null, sessionLifecycle: 0, sessionDisposed: false, sessionRecoveryHint: null,
|
|
57
|
+
scope: null, chats: [], archivedChats: [], unreadableChats: [], chat: null, events: [], capability: null, signInPending: new Set(), desktop: null,
|
|
55
58
|
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,
|
|
56
59
|
instructorAnswers: [], historyLoading: false, historyRequestGeneration: 0, picker: null, loading: false,
|
|
57
60
|
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,
|
|
@@ -138,6 +141,13 @@
|
|
|
138
141
|
}
|
|
139
142
|
|
|
140
143
|
async function request(path, options = {}) {
|
|
144
|
+
const scopeGeneration = state.scopeGeneration;
|
|
145
|
+
const sessionLifecycle = state.sessionLifecycle;
|
|
146
|
+
await globalThis.flolessStartupAdmission?.admit(path, { method: options.method, signal: options.signal });
|
|
147
|
+
// A new scope adopts the server-wide cookie/readiness handshake; scoped reads keep their original owner.
|
|
148
|
+
if (path === '/api/chat/session') {
|
|
149
|
+
if (state.sessionDisposed || sessionLifecycle !== state.sessionLifecycle) throw Object.assign(new Error('Chat page is closed.'), { code: 'chat-page-closed' });
|
|
150
|
+
} else if (scopeGeneration !== state.scopeGeneration) throw Object.assign(new Error('Chat scope changed.'), { code: 'chat-page-closed' });
|
|
141
151
|
const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 30000;
|
|
142
152
|
const init = { credentials: 'same-origin', ...options };
|
|
143
153
|
delete init.timeoutMs;
|
|
@@ -171,6 +181,8 @@
|
|
|
171
181
|
error.code = body?.code || null;
|
|
172
182
|
error.reason = body?.reason || null;
|
|
173
183
|
error.recovery = Array.isArray(body?.recovery) ? body.recovery : null;
|
|
184
|
+
// The subscription gate's answer (state + reason) decides which sign-in sentence errorMessage shows.
|
|
185
|
+
if (response.status === 402 && body && typeof body === 'object') error.body = body;
|
|
174
186
|
// #2061: who holds a busy project, so the person can be asked: wait, stop it, or open it.
|
|
175
187
|
error.holder = body?.holder && typeof body.holder === 'object' ? body.holder : null;
|
|
176
188
|
error.status = response.status;
|
|
@@ -211,7 +223,7 @@
|
|
|
211
223
|
}
|
|
212
224
|
|
|
213
225
|
function errorMessage(error) {
|
|
214
|
-
// A sentence written by plainError
|
|
226
|
+
// A sentence written by plainError for a browser check is already the whole
|
|
215
227
|
// plain-English explanation for this moment.
|
|
216
228
|
if (error?.plainSentence) return error.message;
|
|
217
229
|
const raw = error instanceof Error ? error.message : String(error);
|
|
@@ -229,6 +241,10 @@
|
|
|
229
241
|
if (code === 'local-timeout' && raw) return raw;
|
|
230
242
|
// #1907: the server marks a not-sent reason it already wrote for the person; it is shown as is.
|
|
231
243
|
if (code === 'chat-send-refused-plain' && raw) return raw;
|
|
244
|
+
// A lapsed FloLess sign-in or subscription refuses every chat request with 402. It used to read as "could not
|
|
245
|
+
// complete this chat action, reload", which no reload fixes; the one sentence every surface shows says to sign in.
|
|
246
|
+
const access = globalThis.flolessBridge?.accountAccessText?.(error);
|
|
247
|
+
if (access) return access;
|
|
232
248
|
const codeMessages = {
|
|
233
249
|
// #1890 PR 3b: the server's own sentences name the workflow.
|
|
234
250
|
'chat-moving': raw,
|
|
@@ -407,9 +423,11 @@
|
|
|
407
423
|
return !raw || /sign in|auth|account/i.test(raw);
|
|
408
424
|
}
|
|
409
425
|
|
|
410
|
-
function capabilityMessage(provider, reason) {
|
|
426
|
+
function capabilityMessage(provider, reason, accountAccess = false) {
|
|
411
427
|
const label = providerLabels[provider] || 'AI service';
|
|
412
428
|
const raw = String(reason || '');
|
|
429
|
+
// FloLess's own sign-in or subscription (readCapability): its sentence already says what to do.
|
|
430
|
+
if (accountAccess && raw) return raw;
|
|
413
431
|
// A check that timed out (this computer or FloLess was busy) says nothing about the AI: say that, not "not ready".
|
|
414
432
|
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.`;
|
|
415
433
|
if (signInNeeded(raw)) return `Sign in to ${label} first.`;
|
|
@@ -426,6 +444,7 @@
|
|
|
426
444
|
}
|
|
427
445
|
|
|
428
446
|
function report(error, prefix = '', messages = null) {
|
|
447
|
+
if (error?.code === 'chat-page-closed') return;
|
|
429
448
|
const code = String(error && error.code || '');
|
|
430
449
|
// #1890 PR 3b: a conversation that moved is not a failure — request() already follows it into its workflow.
|
|
431
450
|
if (code === 'chat-moved' && error?.movedTo) return;
|
|
@@ -514,6 +533,16 @@
|
|
|
514
533
|
ui.hint.classList.add('error');
|
|
515
534
|
return;
|
|
516
535
|
}
|
|
536
|
+
const pending = state.sessionRecoveryHint;
|
|
537
|
+
if (pending && sameScope(pending.scope, pending.generation)) {
|
|
538
|
+
ui.hint.classList.remove('working'); ui.hint.removeAttribute('aria-label');
|
|
539
|
+
ui.hint.textContent = pending.message;
|
|
540
|
+
if (!pending.announced) {
|
|
541
|
+
pending.announced = true;
|
|
542
|
+
announce(pending.message, () => state.sessionRecoveryHint === pending && sameScope(pending.scope, pending.generation));
|
|
543
|
+
}
|
|
544
|
+
return;
|
|
545
|
+
}
|
|
517
546
|
const message = requestExecutionBlocked()
|
|
518
547
|
? 'Another AI Chat is changing this project or workflow. Wait for it to finish or stop it before sending here.'
|
|
519
548
|
: state.followupUnknownId || hasUnknownFollowup()
|
|
@@ -524,7 +553,7 @@
|
|
|
524
553
|
: state.chat && state.capability?.runtime && state.capability.runtime.state !== 'installed'
|
|
525
554
|
? runtimeNotice(state.chat.provider, state.capability.runtime).body
|
|
526
555
|
: state.chat && !providerReady()
|
|
527
|
-
? `${capabilityMessage(state.chat.provider, state.capability?.reason)} You can still write a message; Send will retry the connection.`
|
|
556
|
+
? `${capabilityMessage(state.chat.provider, state.capability?.reason, state.capability?.accountAccess)} You can still write a message; Send will retry the connection.`
|
|
528
557
|
: state.chat?.state === 'recovery'
|
|
529
558
|
? 'Check the last AI response before continuing.'
|
|
530
559
|
: !state.scope?.owner
|
|
@@ -532,6 +561,9 @@
|
|
|
532
561
|
// #1776/#1859: a drawing read running in this conversation is where a message goes, on any screen.
|
|
533
562
|
: paintFilterComposer().replyToRead
|
|
534
563
|
? READ_REPLY_HINT
|
|
564
|
+
// #2438: in a project, @ names a member or sheet.
|
|
565
|
+
: state.scope.owner.kind === 'project'
|
|
566
|
+
? 'Enter to send · Shift+Enter for a new line · @ to mention a member or sheet'
|
|
535
567
|
: 'Enter to send · Shift+Enter for a new line';
|
|
536
568
|
if (turnIsVisiblyActive() && !state.followupUnknownId && !hasUnknownFollowup()
|
|
537
569
|
&& state.imageLimitChatId !== state.chat?.chatId) {
|
|
@@ -588,7 +620,7 @@
|
|
|
588
620
|
const selectedStep = document.querySelector('#ws-step-tabs [aria-selected="true"]')?.getAttribute('data-step');
|
|
589
621
|
const workspaceSurface = {
|
|
590
622
|
drawings: 'drawing-filter', model: 'project-model', exports: 'project-exports',
|
|
591
|
-
history: 'project-history', knowledge: 'project-knowledge',
|
|
623
|
+
history: 'project-history', knowledge: 'project-knowledge', pages: 'project-pages',
|
|
592
624
|
}[selectedStep || ''] || 'project-list';
|
|
593
625
|
const workspaceProjectOpen = document.getElementById('ws-project')?.hidden === false;
|
|
594
626
|
const dashboardVisible = document.getElementById('dashboard')?.hidden === false;
|
|
@@ -633,6 +665,7 @@
|
|
|
633
665
|
case 'project-exports': return shellText('ws-exports');
|
|
634
666
|
case 'project-history': return shellText('ws-history');
|
|
635
667
|
case 'project-knowledge': return shellText('ws-knowledge');
|
|
668
|
+
case 'project-pages': return shellText('ws-pages');
|
|
636
669
|
case 'project-list': return shellText('ws-landing');
|
|
637
670
|
case 'workflow-list': return shellText('wf-landing');
|
|
638
671
|
case 'agent-list': case 'agent-page': return shellText('agents-surface');
|
|
@@ -648,7 +681,7 @@
|
|
|
648
681
|
function floLessContextLabel(context = currentFloLessContext()) {
|
|
649
682
|
const labels = {
|
|
650
683
|
'drawing-filter': 'Drawing Filter', 'project-model': 'project model', 'project-exports': 'project exports',
|
|
651
|
-
'project-history': 'project history', 'project-knowledge': 'project Knowledge', 'project-list': 'project list',
|
|
684
|
+
'project-history': 'project history', 'project-knowledge': 'project Knowledge', 'project-pages': 'project Pages', 'project-list': 'project list',
|
|
652
685
|
'workflow-canvas': 'workflow canvas', dashboard: 'dashboard', report: 'report', '3d-report': '3D report',
|
|
653
686
|
'model-editor': 'model editor', 'workflow-list': 'workflow list', 'agent-list': 'list of agents', 'agent-page': 'agent page',
|
|
654
687
|
};
|
|
@@ -891,6 +924,8 @@
|
|
|
891
924
|
row.append(choice);
|
|
892
925
|
}
|
|
893
926
|
empty.append(strong, copy, row);
|
|
927
|
+
// Flo building Workspaces, Workflows and Agents behind the start screens (web/chat-landing-scene.js); decorative.
|
|
928
|
+
if (typeof chatLandingScene === 'function') chatLandingScene(empty, `chooser:${scopeKey(state.scope)}`);
|
|
894
929
|
const accounts = document.createElement('div');
|
|
895
930
|
accounts.className = 'ai-chat-provider-accounts';
|
|
896
931
|
accounts.textContent = 'Checking signed-in accounts…';
|
|
@@ -1076,6 +1111,7 @@
|
|
|
1076
1111
|
const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy';
|
|
1077
1112
|
copy.textContent = 'Each project or workflow keeps its own chat history in its folder.';
|
|
1078
1113
|
empty.append(strong, copy);
|
|
1114
|
+
if (typeof chatLandingScene === 'function') chatLandingScene(empty, 'unscoped');
|
|
1079
1115
|
ui.feed.append(empty);
|
|
1080
1116
|
ui.title.textContent = 'AI Chat';
|
|
1081
1117
|
ui.scope.textContent = 'No project or workflow selected';
|
|
@@ -1672,8 +1708,12 @@
|
|
|
1672
1708
|
} finally { trigger.disabled = false; }
|
|
1673
1709
|
}
|
|
1674
1710
|
|
|
1711
|
+
// Today's messages need only the time. Anything older carries its full date too: scrolling back through a chat
|
|
1712
|
+
// from days ago, a bare "14:02" says nothing about when it happened.
|
|
1675
1713
|
function eventTime(event) {
|
|
1676
|
-
|
|
1714
|
+
const today = formatDay(event.createdAt) === 'Today';
|
|
1715
|
+
return new Intl.DateTimeFormat(undefined, today ? { hour: '2-digit', minute: '2-digit' }
|
|
1716
|
+
: { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' }).format(new Date(event.createdAt));
|
|
1677
1717
|
}
|
|
1678
1718
|
|
|
1679
1719
|
function beginRename() {
|
|
@@ -1923,14 +1963,82 @@
|
|
|
1923
1963
|
}[character]));
|
|
1924
1964
|
}
|
|
1925
1965
|
|
|
1966
|
+
/*
|
|
1967
|
+
* #2437: an answer's inline directives — `:cite[anchor]` after a claim, `:assume[words]` on an assumption. While an
|
|
1968
|
+
* assistant answer is being rendered, `inlineSlots` collects each one and the text holds only an empty slot whose
|
|
1969
|
+
* number is ours; the slot becomes a real control afterwards through DOM calls (`fillInlineSlots`), so nothing the
|
|
1970
|
+
* model wrote ever becomes markup. Outside an answer (the person's own words) the same text stays literal.
|
|
1971
|
+
*/
|
|
1972
|
+
let inlineSlots = null;
|
|
1973
|
+
const CITE_ANCHOR = /^[a-z0-9-]{1,16}$/;
|
|
1974
|
+
const INLINE_DIRECTIVE = /:(cite|assume)\[([^\]\n]{1,120})\]/g;
|
|
1975
|
+
|
|
1976
|
+
function markdownEmphasis(html) {
|
|
1977
|
+
return html.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>').replace(/__([^_\n]+)__/g, '<strong>$1</strong>')
|
|
1978
|
+
.replace(/\*([^*\n]+)\*/g, '<em>$1</em>').replace(/_([^_\n]+)_/g, '<em>$1</em>');
|
|
1979
|
+
}
|
|
1980
|
+
|
|
1981
|
+
/** Plain text with emphasis and (inside an answer) directive slots; the slot markers are characters no text can hold. */
|
|
1982
|
+
function markdownRun(text) {
|
|
1983
|
+
if (!text) return '';
|
|
1984
|
+
const marked = inlineSlots ? text.replace(INLINE_DIRECTIVE, (all, kind, value) => {
|
|
1985
|
+
if (kind === 'cite' && !CITE_ANCHOR.test(value)) return all;
|
|
1986
|
+
const n = inlineSlots.push(kind === 'cite' ? { kind, anchor: value } : { kind, text: value }) - 1;
|
|
1987
|
+
return `${n}`;
|
|
1988
|
+
}) : text;
|
|
1989
|
+
return markdownEmphasis(escapeMarkdownHtml(marked)).replace(/(\d+)/g, '<span class="ai-chat-inline-slot" data-inline-slot="$1"></span>');
|
|
1990
|
+
}
|
|
1991
|
+
|
|
1992
|
+
/**
|
|
1993
|
+
* Text between code spans: links first, so their address is never parsed for anything. A link's words cannot hold a
|
|
1994
|
+
* directive (its `]` ends them) and are only escaped, so a marker never lands inside a link.
|
|
1995
|
+
*/
|
|
1996
|
+
function markdownText(text) {
|
|
1997
|
+
const out = [];
|
|
1998
|
+
let last = 0;
|
|
1999
|
+
for (const match of text.matchAll(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g)) {
|
|
2000
|
+
out.push(markdownRun(text.slice(last, match.index)));
|
|
2001
|
+
out.push(`<a href="${escapeMarkdownHtml(match[2])}" target="_blank" rel="noreferrer">${markdownEmphasis(escapeMarkdownHtml(match[1]))}</a>`);
|
|
2002
|
+
last = match.index + match[0].length;
|
|
2003
|
+
}
|
|
2004
|
+
out.push(markdownRun(text.slice(last)));
|
|
2005
|
+
return out.join('');
|
|
2006
|
+
}
|
|
2007
|
+
|
|
1926
2008
|
function markdownInline(value) {
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
2009
|
+
// The slot markers are private-use characters; any the text itself holds are shown as the replacement character,
|
|
2010
|
+
// so no text can forge a slot.
|
|
2011
|
+
const source = String(value ?? '').replace(/[]/g, '�');
|
|
2012
|
+
const out = [];
|
|
2013
|
+
let last = 0;
|
|
2014
|
+
// Code spans first: nothing inside one is a link, an emphasis or a directive. A span opens on a whole run of
|
|
2015
|
+
// backticks and closes on the next whole run of exactly that length on the same line; a run with no partner is text.
|
|
2016
|
+
// Linear in the text: each run's partner (the next run of its length) is found in one backward pass, and each run's
|
|
2017
|
+
// line in one forward pass, so a long answer full of short spans renders as fast as a short one.
|
|
2018
|
+
const runs = [...source.matchAll(/`+/g)];
|
|
2019
|
+
const partner = new Array(runs.length).fill(-1);
|
|
2020
|
+
const nextOfLength = new Map();
|
|
2021
|
+
for (let i = runs.length - 1; i >= 0; i -= 1) {
|
|
2022
|
+
partner[i] = nextOfLength.get(runs[i][0].length) ?? -1;
|
|
2023
|
+
nextOfLength.set(runs[i][0].length, i);
|
|
2024
|
+
}
|
|
2025
|
+
const line = new Array(runs.length);
|
|
2026
|
+
for (let i = 0, at = 0, count = 0; i < runs.length; i += 1) {
|
|
2027
|
+
for (; at < runs[i].index; at += 1) if (source.charCodeAt(at) === 10) count += 1;
|
|
2028
|
+
line[i] = count;
|
|
2029
|
+
}
|
|
2030
|
+
for (let i = 0; i < runs.length; i += 1) {
|
|
2031
|
+
const open = runs[i];
|
|
2032
|
+
const j = partner[i];
|
|
2033
|
+
if (open.index < last || j < 0 || line[j] !== line[i]) continue;
|
|
2034
|
+
const close = runs[j];
|
|
2035
|
+
const inner = source.slice(open.index + open[0].length, close.index);
|
|
2036
|
+
out.push(markdownText(source.slice(last, open.index)), `<code>${escapeMarkdownHtml(inner.replace(/^ (.*) $/, '$1'))}</code>`);
|
|
2037
|
+
last = close.index + close[0].length;
|
|
2038
|
+
i = j;
|
|
2039
|
+
}
|
|
2040
|
+
out.push(markdownText(source.slice(last)));
|
|
2041
|
+
return out.join('');
|
|
1934
2042
|
}
|
|
1935
2043
|
|
|
1936
2044
|
function markdownHtml(value, depth = 0) {
|
|
@@ -2044,6 +2152,447 @@
|
|
|
2044
2152
|
.trim();
|
|
2045
2153
|
}
|
|
2046
2154
|
|
|
2155
|
+
/* ---- #2437: the sources an answer cited ------------------------------------------------------------------------------
|
|
2156
|
+
* FloLess writes a `citation` event for each floless_cite call; every label, identity and read state in it is FloLess's
|
|
2157
|
+
* own. An answer's turn folds them by anchor (a later source for an anchor replaces it); resolved sources are numbered
|
|
2158
|
+
* in the order they were first cited, and the number is the same on the marker in the text and on its chip. A chip says
|
|
2159
|
+
* what is guaranteed, in words: found, read by the AI, and never "checked" — nothing here checks a claim.
|
|
2160
|
+
*/
|
|
2161
|
+
const CITATION_READ = {
|
|
2162
|
+
'whole-sheet': 'yes, the whole sheet', tiles: 'yes, enlarged in 9 tiles', yes: 'yes', no: 'no', unknown: 'not recorded',
|
|
2163
|
+
};
|
|
2164
|
+
|
|
2165
|
+
function citationIndex(turnId) {
|
|
2166
|
+
const byAnchor = new Map();
|
|
2167
|
+
const order = [];
|
|
2168
|
+
for (const event of state.events) {
|
|
2169
|
+
if (event.type !== 'citation' || !turnId || event.turnId !== turnId) continue;
|
|
2170
|
+
const entries = Array.isArray(event.payload?.entries) ? event.payload.entries : [];
|
|
2171
|
+
entries.forEach((entry, index) => {
|
|
2172
|
+
if (!entry || typeof entry.anchor !== 'string' || !CITE_ANCHOR.test(entry.anchor)) return;
|
|
2173
|
+
if (!byAnchor.has(entry.anchor)) order.push(entry.anchor);
|
|
2174
|
+
// The conversation and owner are taken now, from what is being rendered: a chip clicked later opens THIS
|
|
2175
|
+
// conversation's source even while the app is between conversations (QA #2437: after Open in Knowledge).
|
|
2176
|
+
byAnchor.set(entry.anchor, { anchor: entry.anchor, entry, citationId: event.eventId, index, number: 0,
|
|
2177
|
+
chatId: state.chat?.chatId ?? null, owner: ownerQuery(), ownerObject: state.scope?.owner ?? null });
|
|
2178
|
+
});
|
|
2179
|
+
}
|
|
2180
|
+
let n = 0;
|
|
2181
|
+
for (const anchor of order) { const row = byAnchor.get(anchor); row.number = row.entry.status === 'resolved' ? ++n : 0; }
|
|
2182
|
+
return { byAnchor, order };
|
|
2183
|
+
}
|
|
2184
|
+
|
|
2185
|
+
/**
|
|
2186
|
+
* #2471: what "Read by AI" says, by kind — each kind has its own receipts. A member counts only by its @-mention line in
|
|
2187
|
+
* the person's message; a file only by a look that showed it, and one that merely went with the question says so.
|
|
2188
|
+
*/
|
|
2189
|
+
function citationReadWords(entry) {
|
|
2190
|
+
if (entry.kind === 'member') return entry.read === 'mentioned' ? 'yes, its @-mention was in your message' : 'not recorded';
|
|
2191
|
+
if (entry.kind === 'attachment') {
|
|
2192
|
+
if (entry.read === 'looked') {
|
|
2193
|
+
const pages = Array.isArray(entry.ref?.pagesLooked) ? entry.ref.pagesLooked : [];
|
|
2194
|
+
return pages.length ? `yes, ${pages.length === 1 ? 'page' : 'pages'} ${pages.join(', ')}` : 'yes';
|
|
2195
|
+
}
|
|
2196
|
+
// In the message itself: a data file as its text, checked against the attached file and cut at 16,000 characters.
|
|
2197
|
+
if (entry.read === 'in-message') return 'yes, its text was in your message (up to the first 16,000 characters)';
|
|
2198
|
+
return entry.read === 'sent' ? 'not recorded, it went with your question' : 'not recorded';
|
|
2199
|
+
}
|
|
2200
|
+
return CITATION_READ[entry.read] || CITATION_READ.no;
|
|
2201
|
+
}
|
|
2202
|
+
|
|
2203
|
+
function citationProvenance(entry) {
|
|
2204
|
+
return `Found: yes · Read by AI: ${citationReadWords(entry)} · Checked: no`;
|
|
2205
|
+
}
|
|
2206
|
+
|
|
2207
|
+
/** The chip's tag, in words: never a colour or a tick. */
|
|
2208
|
+
function citationMarks(entry) {
|
|
2209
|
+
if (entry.kind === 'attachment' && entry.read === 'sent') return 'FOUND · SENT WITH QUESTION';
|
|
2210
|
+
return ['whole-sheet', 'tiles', 'yes', 'mentioned', 'looked', 'in-message'].includes(entry.read) ? 'FOUND · READ BY AI' : 'FOUND';
|
|
2211
|
+
}
|
|
2212
|
+
|
|
2213
|
+
/** A member is named with its profile, which is what tells it from a member with a like mark. */
|
|
2214
|
+
function citationLabel(entry) {
|
|
2215
|
+
return entry.kind === 'member' && entry.status === 'resolved' && entry.ref?.profile ? `${entry.label} · ${entry.ref.profile}` : entry.label;
|
|
2216
|
+
}
|
|
2217
|
+
|
|
2218
|
+
function citationUrl(row, what, extra = '') {
|
|
2219
|
+
if (!row.chatId) return null;
|
|
2220
|
+
return `/api/chat/conversations/${encodeURIComponent(row.chatId)}/citations/${encodeURIComponent(row.citationId)}/${row.index}/${what}?${row.owner}${extra}`;
|
|
2221
|
+
}
|
|
2222
|
+
|
|
2223
|
+
/** An answer's text, with its source markers made from FloLess's record of what it cited. */
|
|
2224
|
+
function renderAnswerBody(body, text, turnId) {
|
|
2225
|
+
inlineSlots = [];
|
|
2226
|
+
let slots = [];
|
|
2227
|
+
try { body.innerHTML = markdownHtml(text); }
|
|
2228
|
+
finally { slots = inlineSlots; inlineSlots = null; }
|
|
2229
|
+
if (slots.length) fillInlineSlots(body, slots, turnId);
|
|
2230
|
+
}
|
|
2231
|
+
|
|
2232
|
+
/** The markers an answer's directives asked for, built from FloLess's own record of what was cited. */
|
|
2233
|
+
function fillInlineSlots(body, slots, turnId) {
|
|
2234
|
+
const index = citationIndex(turnId);
|
|
2235
|
+
for (const slot of body.querySelectorAll('[data-inline-slot]')) {
|
|
2236
|
+
const spec = slots[Number(slot.dataset.inlineSlot)];
|
|
2237
|
+
if (!spec) { slot.remove(); continue; }
|
|
2238
|
+
if (spec.kind === 'assume') {
|
|
2239
|
+
const tag = document.createElement('span'); tag.className = 'ai-chat-assume';
|
|
2240
|
+
tag.textContent = 'Assumption';
|
|
2241
|
+
tag.dataset.tip = `The AI marked this as an assumption: ${spec.text}`;
|
|
2242
|
+
slot.replaceWith(tag);
|
|
2243
|
+
continue;
|
|
2244
|
+
}
|
|
2245
|
+
const row = index.byAnchor.get(spec.anchor) ?? null;
|
|
2246
|
+
const resolved = row?.entry.status === 'resolved';
|
|
2247
|
+
const marker = button(resolved ? String(row.number) : '?', 'shell.chat-cite-anchor', `ai-chat-cite${resolved ? '' : ' unresolved'}`);
|
|
2248
|
+
marker.dataset.turnId = turnId || '';
|
|
2249
|
+
marker.dataset.anchor = spec.anchor;
|
|
2250
|
+
const label = resolved ? citationLabel(row.entry) : 'no source';
|
|
2251
|
+
// No citation for this anchor on this page is "none recorded", not "none found": the AI may have given none, or the
|
|
2252
|
+
// record has not reached this page yet.
|
|
2253
|
+
const missing = row ? 'No source was found for this claim' : 'No source is recorded for this claim';
|
|
2254
|
+
marker.dataset.commandInstanceLabel = label;
|
|
2255
|
+
marker.setAttribute('aria-label', resolved ? `Source ${row.number}: ${label}` : missing);
|
|
2256
|
+
marker.dataset.tip = resolved ? `${label} · ${citationProvenance(row.entry)}` : missing;
|
|
2257
|
+
marker.addEventListener('click', () => {
|
|
2258
|
+
const chip = [...ui.feed.querySelectorAll('.ai-chat-source')].find((node) => node.dataset.turnId === turnId && node.dataset.anchor === spec.anchor);
|
|
2259
|
+
if (!chip) { announce(resolved ? 'Its source is listed under the answer.' : 'The AI gave no source for this claim.'); return; }
|
|
2260
|
+
chip.scrollIntoView({ block: 'nearest' });
|
|
2261
|
+
chip.classList.remove('answer-jump'); void chip.offsetWidth; chip.classList.add('answer-jump');
|
|
2262
|
+
(chip.querySelector('button') ?? chip).focus({ preventScroll: true });
|
|
2263
|
+
});
|
|
2264
|
+
slot.replaceWith(marker);
|
|
2265
|
+
}
|
|
2266
|
+
}
|
|
2267
|
+
|
|
2268
|
+
/** One chip: the sheet or page, what FloLess can vouch for, and (unresolved) the person's two ways on. */
|
|
2269
|
+
function citationChip(turnId, row) {
|
|
2270
|
+
const chip = document.createElement('span');
|
|
2271
|
+
chip.className = 'ai-chat-attachment ai-chat-source';
|
|
2272
|
+
chip.dataset.turnId = turnId || '';
|
|
2273
|
+
chip.dataset.anchor = row.anchor;
|
|
2274
|
+
const number = document.createElement('span'); number.className = 'ai-chat-source-n';
|
|
2275
|
+
number.textContent = row.number ? String(row.number) : '?';
|
|
2276
|
+
chip.append(number);
|
|
2277
|
+
const entry = row.entry;
|
|
2278
|
+
if (entry.status !== 'resolved') {
|
|
2279
|
+
chip.classList.add('unresolved');
|
|
2280
|
+
const why = document.createElement('span'); why.className = 'ai-chat-source-why';
|
|
2281
|
+
why.textContent = `No source: ${entry.reason}`;
|
|
2282
|
+
const ask = button('Ask for the source', 'shell.chat-cite-ask', 'ai-chat-source-action');
|
|
2283
|
+
ask.dataset.tip = 'Puts a question in the message box asking where this comes from. Nothing is sent until you press Send';
|
|
2284
|
+
ask.addEventListener('click', () => addToMessageBox(`${unsourcedClaim(turnId, row.anchor)}: which sheet, model member, attached file or Knowledge page does it come from? Cite it, or say plainly that it is an assumption.`));
|
|
2285
|
+
const assume = button('Go on with this as an assumption', 'shell.chat-cite-assume', 'ai-chat-source-action');
|
|
2286
|
+
assume.dataset.tip = 'Puts a message in the message box asking the AI to carry on with it as a labelled assumption. Nothing is sent until you press Send';
|
|
2287
|
+
assume.addEventListener('click', () => addToMessageBox(`${unsourcedClaim(turnId, row.anchor)}: go on with it as an assumption, and label it as an assumption wherever you use it.`));
|
|
2288
|
+
chip.append(why, ask, assume);
|
|
2289
|
+
return chip;
|
|
2290
|
+
}
|
|
2291
|
+
if (entry.kind === 'sheet') {
|
|
2292
|
+
const thumb = document.createElement('img'); thumb.alt = ''; thumb.loading = 'lazy';
|
|
2293
|
+
// A preview is only the picture the AI was shown (never a render): a tiles look or a changed picture has none.
|
|
2294
|
+
const preview = citationUrl(row, 'image', '&thumb=1');
|
|
2295
|
+
if (preview) {
|
|
2296
|
+
thumb.src = preview;
|
|
2297
|
+
thumb.addEventListener('error', () => thumb.remove(), { once: true });
|
|
2298
|
+
chip.append(thumb);
|
|
2299
|
+
}
|
|
2300
|
+
}
|
|
2301
|
+
const label = citationLabel(entry);
|
|
2302
|
+
const open = button(label, 'shell.chat-cite-open', 'ai-chat-answer-open ai-chat-source-open');
|
|
2303
|
+
open.dataset.commandInstanceLabel = label;
|
|
2304
|
+
open.setAttribute('aria-label', `Open ${label}`);
|
|
2305
|
+
open.dataset.tip = citationProvenance(entry);
|
|
2306
|
+
open.addEventListener('click', () => openCitedSource(row, turnId));
|
|
2307
|
+
const marks = document.createElement('span'); marks.className = 'ai-chat-source-marks';
|
|
2308
|
+
marks.textContent = citationMarks(entry);
|
|
2309
|
+
chip.append(open, marks);
|
|
2310
|
+
return chip;
|
|
2311
|
+
}
|
|
2312
|
+
|
|
2313
|
+
/** The Sources row of one answer, shown once, under the answer, after its last citation. */
|
|
2314
|
+
function renderCitationSources(event) {
|
|
2315
|
+
const last = state.events.filter((candidate) => candidate.type === 'citation' && candidate.turnId === event.turnId).at(-1);
|
|
2316
|
+
if (last !== event) return null;
|
|
2317
|
+
const index = citationIndex(event.turnId);
|
|
2318
|
+
if (!index.order.length) return null;
|
|
2319
|
+
return citationRow(index.order.map((anchor) => citationChip(event.turnId, index.byAnchor.get(anchor))));
|
|
2320
|
+
}
|
|
2321
|
+
|
|
2322
|
+
/** #2436: a Knowledge citation written before #2437 — its pages as chips; whether the AI read them was never recorded. */
|
|
2323
|
+
function renderLegacyKnowledgeCitation(event) {
|
|
2324
|
+
const pages = Array.isArray(event.payload?.pages) ? event.payload.pages.filter((page) => page && typeof page.slug === 'string') : [];
|
|
2325
|
+
if (!pages.length) return null;
|
|
2326
|
+
return citationRow(pages.map((page, i) => {
|
|
2327
|
+
const label = typeof page.title === 'string' && page.title ? page.title : page.slug;
|
|
2328
|
+
const chip = document.createElement('span'); chip.className = 'ai-chat-attachment ai-chat-source';
|
|
2329
|
+
const number = Object.assign(document.createElement('span'), { className: 'ai-chat-source-n', textContent: String(i + 1) });
|
|
2330
|
+
const open = button(label, 'shell.chat-cite-open-knowledge', 'ai-chat-answer-open ai-chat-source-open');
|
|
2331
|
+
open.dataset.commandInstanceLabel = label;
|
|
2332
|
+
open.setAttribute('aria-label', `Open ${label}`);
|
|
2333
|
+
open.dataset.tip = citationProvenance({ kind: 'kb-page', read: 'unknown' });
|
|
2334
|
+
open.addEventListener('click', () => {
|
|
2335
|
+
if (window.flolessWorkspaces?.openKnowledgePage) window.flolessWorkspaces.openKnowledgePage(event.payload.projectId, page.slug, event.payload.generationId);
|
|
2336
|
+
else announce('Knowledge is not available on this page.');
|
|
2337
|
+
});
|
|
2338
|
+
const marks = Object.assign(document.createElement('span'), { className: 'ai-chat-source-marks', textContent: 'FOUND' });
|
|
2339
|
+
chip.append(number, open, marks);
|
|
2340
|
+
return chip;
|
|
2341
|
+
}));
|
|
2342
|
+
}
|
|
2343
|
+
|
|
2344
|
+
function citationRow(chips) {
|
|
2345
|
+
const wrap = document.createElement('div'); wrap.className = 'ai-chat-sources';
|
|
2346
|
+
const head = document.createElement('span'); head.className = 'ai-chat-sources-head';
|
|
2347
|
+
head.textContent = 'Sources the AI gave for this answer';
|
|
2348
|
+
head.dataset.tip = 'FloLess found each source and says whether the AI was shown it. It does not check that a source supports the claim.';
|
|
2349
|
+
const list = document.createElement('div'); list.className = 'ai-chat-sources-list';
|
|
2350
|
+
list.append(...chips);
|
|
2351
|
+
wrap.append(head, list);
|
|
2352
|
+
return wrap;
|
|
2353
|
+
}
|
|
2354
|
+
|
|
2355
|
+
/**
|
|
2356
|
+
* Which claim a "no source" chip is about, in words the AI can find: the answer it is in (by its time) and the text
|
|
2357
|
+
* just before its "?" marker. Several "?" claims, or a chip under an older answer, each name their own.
|
|
2358
|
+
*/
|
|
2359
|
+
function unsourcedClaim(turnId, anchor) {
|
|
2360
|
+
const marker = [...ui.feed.querySelectorAll('button.ai-chat-cite')].find((node) => node.dataset.turnId === (turnId || '') && node.dataset.anchor === anchor);
|
|
2361
|
+
// The answer is found by its turn even when the AI put no marker after the claim (it is not obliged to).
|
|
2362
|
+
const answer = marker?.closest('.ai-chat-message')
|
|
2363
|
+
?? [...ui.feed.querySelectorAll('.ai-chat-message.assistant')].filter((node) => node.dataset.turnId === turnId).at(-1);
|
|
2364
|
+
const when = answer?.querySelector('time')?.textContent?.trim();
|
|
2365
|
+
const block = marker?.closest('p, li, h1, h2, h3, blockquote');
|
|
2366
|
+
let before = '';
|
|
2367
|
+
if (block && marker) {
|
|
2368
|
+
// The block's text up to the marker, read in document order; other markers and tags add no words.
|
|
2369
|
+
const parts = [];
|
|
2370
|
+
const walk = (node) => {
|
|
2371
|
+
if (node === marker) return true;
|
|
2372
|
+
if (node.nodeType === 3) parts.push(node.textContent);
|
|
2373
|
+
else if (!(node.matches?.('button.ai-chat-cite, .ai-chat-assume'))) for (const child of node.childNodes) if (walk(child)) return true;
|
|
2374
|
+
return false;
|
|
2375
|
+
};
|
|
2376
|
+
walk(block);
|
|
2377
|
+
before = parts.join('').replace(/\s+/g, ' ').trim();
|
|
2378
|
+
}
|
|
2379
|
+
const words = [...before];
|
|
2380
|
+
const claim = words.length > 90 ? `…${words.slice(-90).join('').trimStart()}` : before;
|
|
2381
|
+
const where = when ? `in your answer of ${when}` : 'in your answer';
|
|
2382
|
+
return claim ? `For this claim ${where}, which has no source: “${claim}”` : `For the claim with no source ${where}`;
|
|
2383
|
+
}
|
|
2384
|
+
|
|
2385
|
+
/** Never overwrites what the person is writing: the text goes after it. */
|
|
2386
|
+
function addToMessageBox(text) {
|
|
2387
|
+
const held = ui.input.value.trim();
|
|
2388
|
+
putInMessageBox(held ? `${ui.input.value.replace(/\s+$/, '')}\n\n${text}` : text);
|
|
2389
|
+
}
|
|
2390
|
+
|
|
2391
|
+
/** The cited sheet or page, in a themed dialog over the app; it shows only what the server re-checked just now. */
|
|
2392
|
+
/**
|
|
2393
|
+
* The chip's open button as it is NOW: the feed repaints, so the node that was clicked may be gone; the live one is
|
|
2394
|
+
* found again by its answer and anchor, for focus to return to.
|
|
2395
|
+
*/
|
|
2396
|
+
function liveCitationOpener(turnId, anchor) {
|
|
2397
|
+
const chip = [...ui.feed.querySelectorAll('.ai-chat-source')].find((node) => node.dataset.turnId === (turnId || '') && node.dataset.anchor === anchor);
|
|
2398
|
+
return chip?.querySelector('.ai-chat-source-open') ?? null;
|
|
2399
|
+
}
|
|
2400
|
+
|
|
2401
|
+
async function openCitedSource(row, turnId) {
|
|
2402
|
+
const entry = row.entry;
|
|
2403
|
+
const dialog = document.createElement('dialog'); dialog.className = 'ai-chat-source-viewer';
|
|
2404
|
+
dialog.setAttribute('aria-label', citationLabel(entry));
|
|
2405
|
+
const head = document.createElement('div'); head.className = 'ai-chat-source-viewer-head';
|
|
2406
|
+
const title = Object.assign(document.createElement('strong'), { textContent: citationLabel(entry) });
|
|
2407
|
+
const close = button('Close', 'shell.chat-cite-close', 'ai-chat-source-viewer-close');
|
|
2408
|
+
// Closing is done here, not left to the dialog's own `close` event, which an embedding browser may never fire: the
|
|
2409
|
+
// viewer is removed, its picture released and focus handed back to the chip, once, whichever way it closes.
|
|
2410
|
+
let picture = null;
|
|
2411
|
+
let finished = false;
|
|
2412
|
+
const finish = () => {
|
|
2413
|
+
if (finished) return;
|
|
2414
|
+
finished = true;
|
|
2415
|
+
if (dialog.open) dialog.close();
|
|
2416
|
+
dialog.remove();
|
|
2417
|
+
if (picture) URL.revokeObjectURL(picture);
|
|
2418
|
+
liveCitationOpener(turnId, row.anchor)?.focus({ preventScroll: true });
|
|
2419
|
+
};
|
|
2420
|
+
close.addEventListener('click', finish);
|
|
2421
|
+
dialog.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.preventDefault(); finish(); } });
|
|
2422
|
+
dialog.addEventListener('close', finish);
|
|
2423
|
+
head.append(title, close);
|
|
2424
|
+
const note = Object.assign(document.createElement('span'), { className: 'ai-chat-source-viewer-note', textContent: citationProvenance(entry) });
|
|
2425
|
+
const body = document.createElement('div'); body.className = 'ai-chat-source-viewer-body';
|
|
2426
|
+
const status = Object.assign(document.createElement('p'), { className: 'ai-chat-source-viewer-status', textContent: 'Opening…' });
|
|
2427
|
+
status.setAttribute('role', 'status');
|
|
2428
|
+
body.append(status);
|
|
2429
|
+
dialog.append(head, note, body);
|
|
2430
|
+
document.body.append(dialog);
|
|
2431
|
+
dialog.showModal();
|
|
2432
|
+
const refused = async (response) => {
|
|
2433
|
+
if (response.status === 404) return 'FloLess no longer holds this source, or its project is no longer part of this conversation.';
|
|
2434
|
+
if (response.status === 410) {
|
|
2435
|
+
if (entry.kind !== 'attachment') return 'This Knowledge page has changed since the answer, so FloLess does not show it as the page the answer cited.';
|
|
2436
|
+
// Changed bytes, or no longer the plain file that was attached: the server says which.
|
|
2437
|
+
const said = await response.json().catch(() => null);
|
|
2438
|
+
return typeof said?.message === 'string' && said.message ? said.message : 'This file has changed since the answer cited it, so FloLess does not show it as the cited file.';
|
|
2439
|
+
}
|
|
2440
|
+
// 503: FloLess could not check it just now; anything else is said as "try again", never as "gone".
|
|
2441
|
+
const said = await response.json().catch(() => null);
|
|
2442
|
+
return typeof said?.message === 'string' && said.message ? said.message : 'FloLess could not open this source right now. Try again in a moment.';
|
|
2443
|
+
};
|
|
2444
|
+
const SHOWN = {
|
|
2445
|
+
'as-seen': 'The sheet picture the AI was shown.',
|
|
2446
|
+
'from-source:tiles': 'The whole sheet, rendered from its source drawing. The AI saw this sheet enlarged in tiles.',
|
|
2447
|
+
'from-source:changed': 'Rendered from the source drawing: the sheet picture FloLess holds has changed since the AI looked at it.',
|
|
2448
|
+
'from-source:missing': 'Rendered from the source drawing: FloLess no longer holds the sheet picture the AI was shown.',
|
|
2449
|
+
'from-source:unchecked': 'Rendered from the source drawing: FloLess could not check the stored sheet picture just now.',
|
|
2450
|
+
};
|
|
2451
|
+
try {
|
|
2452
|
+
if (!citationUrl(row, 'page')) {
|
|
2453
|
+
status.textContent = 'Open this conversation again to open its sources.';
|
|
2454
|
+
return;
|
|
2455
|
+
}
|
|
2456
|
+
if (entry.kind === 'sheet') {
|
|
2457
|
+
const response = await fetch(citationUrl(row, 'image'), { credentials: 'same-origin', cache: 'no-store' });
|
|
2458
|
+
if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
|
|
2459
|
+
const shown = response.headers.get('X-FloLess-Shown') || 'as-seen';
|
|
2460
|
+
const bytes = await response.blob();
|
|
2461
|
+
// Checked after every wait: a viewer closed meanwhile creates nothing it would never release.
|
|
2462
|
+
if (finished) return;
|
|
2463
|
+
picture = URL.createObjectURL(bytes);
|
|
2464
|
+
const image = Object.assign(document.createElement('img'), { src: picture, alt: `${entry.label}${shown === 'as-seen' ? '' : ', rendered from the source drawing'}` });
|
|
2465
|
+
status.textContent = SHOWN[shown] || SHOWN['as-seen'];
|
|
2466
|
+
body.append(image);
|
|
2467
|
+
return;
|
|
2468
|
+
}
|
|
2469
|
+
if (entry.kind === 'member') { await showCitedMember(row, { dialog, body, status, finish, refused, done: () => finished }); return; }
|
|
2470
|
+
if (entry.kind === 'attachment') {
|
|
2471
|
+
const response = await fetch(citationUrl(row, 'attachment'), { credentials: 'same-origin', cache: 'no-store' });
|
|
2472
|
+
if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
|
|
2473
|
+
const type = (response.headers.get('Content-Type') || '').split(';')[0].trim().toLowerCase();
|
|
2474
|
+
if (type.startsWith('image/')) {
|
|
2475
|
+
const bytes = await response.blob();
|
|
2476
|
+
if (finished) return;
|
|
2477
|
+
picture = URL.createObjectURL(bytes);
|
|
2478
|
+
status.textContent = 'The file as it was attached.';
|
|
2479
|
+
body.append(Object.assign(document.createElement('img'), { src: picture, alt: entry.label }));
|
|
2480
|
+
} else if (type === 'text/plain') {
|
|
2481
|
+
const text = await response.text();
|
|
2482
|
+
if (finished) return;
|
|
2483
|
+
// A data file reaches the AI cut to its first 16,000 characters (attachment-text.ts MAX_TEXT_CHARS): said, never hidden.
|
|
2484
|
+
status.textContent = 'The file as it was attached. The AI is given at most the first 16,000 characters of a data file.';
|
|
2485
|
+
const shown = [...text];
|
|
2486
|
+
const pre = Object.assign(document.createElement('pre'), { className: 'ai-chat-source-viewer-text', tabIndex: 0,
|
|
2487
|
+
textContent: shown.length > 16000 ? shown.slice(0, 16000).join('') : text });
|
|
2488
|
+
pre.setAttribute('aria-label', `Text of ${entry.label}`);
|
|
2489
|
+
body.append(pre);
|
|
2490
|
+
if (shown.length > 16000) {
|
|
2491
|
+
body.append(Object.assign(document.createElement('p'), { className: 'ai-chat-source-viewer-status',
|
|
2492
|
+
textContent: `Showing the first 16,000 of ${shown.length.toLocaleString()} characters. Open it in its default app to see all of it.` }));
|
|
2493
|
+
}
|
|
2494
|
+
} else {
|
|
2495
|
+
await response.body?.cancel().catch(() => {});
|
|
2496
|
+
if (finished) return;
|
|
2497
|
+
status.textContent = 'FloLess does not show this kind of file here. Open it in its default app.';
|
|
2498
|
+
}
|
|
2499
|
+
const external = button('Open in its default app', 'shell.chat-cite-open-file', 'ai-chat-source-viewer-knowledge');
|
|
2500
|
+
external.addEventListener('click', async () => {
|
|
2501
|
+
try {
|
|
2502
|
+
await request(citationUrl(row, 'attachment/open'), { method: 'POST', body: JSON.stringify({ owner: row.ownerObject }) });
|
|
2503
|
+
announce(`Opened ${entry.label} in its default app.`);
|
|
2504
|
+
} catch (error) {
|
|
2505
|
+
// Why, by what the server answered (its code), or why it could not be asked.
|
|
2506
|
+
const why = {
|
|
2507
|
+
'chat-page-closed': 'This conversation is no longer the one open here. Open it again, then press Open in its default app.',
|
|
2508
|
+
'citation-source-unavailable': 'FloLess no longer holds this file in this conversation, so there is nothing to open.',
|
|
2509
|
+
'citation-source-changed': 'This file has changed since the answer cited it, so FloLess does not open it as the cited file.',
|
|
2510
|
+
'citation-source-not-as-attached': 'This file is no longer the plain file that was attached, so FloLess does not open it as the cited file. Attach the file again if you still need it.',
|
|
2511
|
+
'citation-source-unreadable': 'FloLess could not check this file just now. Try again in a moment.',
|
|
2512
|
+
}[error?.code] || '';
|
|
2513
|
+
if (!why) console.error('[chat] a cited file could not be opened in its app', error);
|
|
2514
|
+
announce(why || `FloLess could not open ${entry.label} in its default app. Try again in a moment, or open the file from the message it was attached to.`);
|
|
2515
|
+
}
|
|
2516
|
+
});
|
|
2517
|
+
dialog.append(external);
|
|
2518
|
+
return;
|
|
2519
|
+
}
|
|
2520
|
+
const response = await fetch(citationUrl(row, 'page'), { credentials: 'same-origin', cache: 'no-store' });
|
|
2521
|
+
if (!response.ok) { const why = await refused(response); if (!finished) status.textContent = why; return; }
|
|
2522
|
+
const { page } = await response.json();
|
|
2523
|
+
if (finished) return;
|
|
2524
|
+
status.textContent = 'The Knowledge page as it was when the answer cited it.';
|
|
2525
|
+
const article = document.createElement('div'); article.className = 'ai-chat-message-body ai-chat-source-viewer-page';
|
|
2526
|
+
article.innerHTML = markdownHtml(page.body);
|
|
2527
|
+
const knowledge = button('Open in Knowledge', 'shell.chat-cite-open-knowledge', 'ai-chat-source-viewer-knowledge');
|
|
2528
|
+
knowledge.addEventListener('click', () => {
|
|
2529
|
+
finish();
|
|
2530
|
+
if (window.flolessWorkspaces?.openKnowledgePage) window.flolessWorkspaces.openKnowledgePage(page.projectId, page.slug, page.generationId);
|
|
2531
|
+
else announce('Knowledge is not available on this page.');
|
|
2532
|
+
});
|
|
2533
|
+
body.append(article);
|
|
2534
|
+
dialog.append(knowledge);
|
|
2535
|
+
} catch (error) {
|
|
2536
|
+
console.error('[chat] a cited source could not be opened', error);
|
|
2537
|
+
if (!finished) status.textContent = 'FloLess could not open this source right now. Try again in a moment.';
|
|
2538
|
+
}
|
|
2539
|
+
}
|
|
2540
|
+
|
|
2541
|
+
/**
|
|
2542
|
+
* #2471: a cited member in the source viewer — first as it was cited (FloLess's snapshot), then where the model stands
|
|
2543
|
+
* now, then the way to it. "Show current in the model" whenever the model changed: what is framed is the member as it
|
|
2544
|
+
* is now, not as the answer described it. The member's route is asked again right before moving, so a project that
|
|
2545
|
+
* left the conversation since is never opened.
|
|
2546
|
+
*/
|
|
2547
|
+
async function showCitedMember(row, view) {
|
|
2548
|
+
const { dialog, body, status, finish, refused, done } = view;
|
|
2549
|
+
const response = await fetch(citationUrl(row, 'member'), { credentials: 'same-origin', cache: 'no-store' });
|
|
2550
|
+
if (!response.ok) { const why = await refused(response); if (!done()) status.textContent = why; return; }
|
|
2551
|
+
const { member } = await response.json();
|
|
2552
|
+
if (done()) return;
|
|
2553
|
+
const facts = document.createElement('dl'); facts.className = 'ai-chat-source-viewer-facts';
|
|
2554
|
+
const fact = (term, value) => facts.append(Object.assign(document.createElement('dt'), { textContent: term }),
|
|
2555
|
+
Object.assign(document.createElement('dd'), { textContent: value }));
|
|
2556
|
+
fact('Mark', member.mark ?? 'No mark');
|
|
2557
|
+
fact('Profile', member.profile ?? 'Not recorded');
|
|
2558
|
+
const views = Array.isArray(member.views) ? member.views : [];
|
|
2559
|
+
fact('Read on', views.length ? views.map((v) => (v.title ? `${v.sheet} (${v.title})` : v.sheet)).join(', ') : 'No sheet recorded');
|
|
2560
|
+
body.insertBefore(Object.assign(document.createElement('p'), { className: 'ai-chat-source-viewer-sub', textContent: 'As the answer cited it' }), status);
|
|
2561
|
+
body.insertBefore(facts, status);
|
|
2562
|
+
status.textContent = member.model === 'same' ? 'The model is the same version as when the answer cited it.'
|
|
2563
|
+
: member.model === 'changed' ? 'The model has changed since this answer; the member is still in it. Its size or position may differ from what the answer described.'
|
|
2564
|
+
: member.model === 'no-model' ? 'This project has no steel model FloLess can show now, so the member cannot be shown in it.'
|
|
2565
|
+
: 'This member is no longer in the model.';
|
|
2566
|
+
if (member.model === 'gone' || member.model === 'no-model') return;
|
|
2567
|
+
const show = button(member.model === 'same' ? 'Show in the model' : 'Show current in the model', 'shell.chat-cite-show-member', 'ai-chat-source-viewer-knowledge');
|
|
2568
|
+
show.dataset.tip = 'Opens the project\'s model with this member selected and framed. Nothing changes';
|
|
2569
|
+
show.addEventListener('click', async () => {
|
|
2570
|
+
const unreachable = 'FloLess could not open the model from here. Open the project from Workspaces, then try again.';
|
|
2571
|
+
let said;
|
|
2572
|
+
try {
|
|
2573
|
+
const again = await fetch(citationUrl(row, 'member'), { credentials: 'same-origin', cache: 'no-store' });
|
|
2574
|
+
if (!again.ok) { status.textContent = await refused(again); return; }
|
|
2575
|
+
const now = (await again.json()).member;
|
|
2576
|
+
if (now.model === 'gone' || now.model === 'no-model') {
|
|
2577
|
+
status.textContent = now.model === 'gone' ? 'This member is no longer in the model.' : 'This project has no steel model FloLess can show now, so the member cannot be shown in it.';
|
|
2578
|
+
show.remove(); return;
|
|
2579
|
+
}
|
|
2580
|
+
finish();
|
|
2581
|
+
if (typeof window.flolessWorkspaces?.openConnection !== 'function') { announce(unreachable); return; }
|
|
2582
|
+
const outcome = await window.flolessWorkspaces.openConnection({ projectId: now.projectId, projectUuid: now.projectUuid, memberId: now.memberId });
|
|
2583
|
+
if (outcome?.superseded) return;
|
|
2584
|
+
const name = now.mark ? `member ${now.mark}` : `member ${now.memberId}`;
|
|
2585
|
+
said = !outcome ? unreachable : outcome.ok !== true ? (outcome.said || `The ${name} was not shown. Open the Model step, then press Show in the model again.`)
|
|
2586
|
+
: `Showing ${name} in the model.`;
|
|
2587
|
+
} catch (error) {
|
|
2588
|
+
if (error?.plain !== true) console.error('[chat] Show in the model failed', error);
|
|
2589
|
+
said = error?.plain === true && error.message ? error.message : unreachable;
|
|
2590
|
+
}
|
|
2591
|
+
if (said) announce(said);
|
|
2592
|
+
});
|
|
2593
|
+
dialog.append(show);
|
|
2594
|
+
}
|
|
2595
|
+
|
|
2047
2596
|
function openChatAttachment(attachment) {
|
|
2048
2597
|
return request(`/api/chat/conversations/${encodeURIComponent(state.chat.chatId)}/attachments/${encodeURIComponent(attachment.attachmentId)}/open`, {
|
|
2049
2598
|
method: 'POST', body: JSON.stringify({ owner: state.scope.owner }),
|
|
@@ -2100,7 +2649,9 @@
|
|
|
2100
2649
|
head.append(who, time); item.append(head);
|
|
2101
2650
|
if (role === 'assistant' || visibleText) {
|
|
2102
2651
|
const body = document.createElement('div'); body.className = 'ai-chat-message-body';
|
|
2103
|
-
|
|
2652
|
+
// #2437: only an answer's own directives become source markers; the person's words stay literal.
|
|
2653
|
+
if (role === 'assistant') renderAnswerBody(body, visibleText, event.turnId);
|
|
2654
|
+
else body.innerHTML = markdownHtml(visibleText);
|
|
2104
2655
|
item.append(body);
|
|
2105
2656
|
}
|
|
2106
2657
|
if (role === 'user' && Array.isArray(event.payload?.attachmentIds)) {
|
|
@@ -2121,6 +2672,13 @@
|
|
|
2121
2672
|
line.textContent = about;
|
|
2122
2673
|
item.append(line);
|
|
2123
2674
|
}
|
|
2675
|
+
const mentioned = role === 'user' && event.payload?.mentions ? mentionsLine(event.payload.mentions) : '';
|
|
2676
|
+
if (mentioned) {
|
|
2677
|
+
const line = document.createElement('span'); line.className = 'ai-chat-message-subjects ai-chat-message-mentions';
|
|
2678
|
+
line.textContent = mentioned.text;
|
|
2679
|
+
line.setAttribute('aria-label', mentioned.spoken);
|
|
2680
|
+
item.append(line);
|
|
2681
|
+
}
|
|
2124
2682
|
if (role === 'user' && (event.payload?.followup || event.payload?.deliveryState)) {
|
|
2125
2683
|
const delivery = followupDelivery(event);
|
|
2126
2684
|
const deliveryReceipt = [...state.events].reverse().find((candidate) => candidate.type === 'followup-status'
|
|
@@ -2870,7 +3428,12 @@
|
|
|
2870
3428
|
'workflows.apply-update': 'Update it', 'workflows.freeze-step': 'Freeze it', 'workflows.unfreeze-step': 'Unfreeze it',
|
|
2871
3429
|
'workflows.rename-installed': 'Rename it', 'workflows.reinstall-approved-tool': 'Reinstall it', 'workflows.run-live': 'Start it',
|
|
2872
3430
|
'requests.run': 'Start it', 'requests.desktop-launch': 'Open the app', 'routines.create': 'Create it',
|
|
2873
|
-
'routines.create-for-agent': 'Create it', 'routines.update': 'Save changes'
|
|
3431
|
+
'routines.create-for-agent': 'Create it', 'routines.update': 'Save changes',
|
|
3432
|
+
// #2363: what each button does on the window's side of the card, so none of them says a bare "Do it".
|
|
3433
|
+
'models.start-import': 'Choose the file', 'tekla.start-upload': 'Choose the source', 'models.retry-import': 'Try it again',
|
|
3434
|
+
'models.cancel-import': 'Cancel it', 'tekla.cancel-import': 'Cancel it', 'parser-setup.start-fresh': 'Open the review',
|
|
3435
|
+
'models.retry-revit-setup': 'Try setup again', 'models.retry-tekla-setup': 'Try setup again',
|
|
3436
|
+
'workspace-root.review-retirement': 'Open the review', 'workspace-root.confirm-retirement': 'Record it' };
|
|
2874
3437
|
const ACTION_EYEBROWS = { write: 'Suggested change', destructive: 'Needs your OK', 'human-only': 'Your decision' };
|
|
2875
3438
|
const ACTION_FINAL = new Set(['done', 'failed', 'cancelled', 'declined', 'expired', 'superseded', 'unknown']);
|
|
2876
3439
|
|
|
@@ -2883,8 +3446,44 @@
|
|
|
2883
3446
|
}
|
|
2884
3447
|
const fromServer = latest ? { state: latest.state, result: latest.result || null, supersededBy: latest.supersededBy || null, next: latest.next || null } : null;
|
|
2885
3448
|
// A click's own answer is newer than the journal until the journal catches up; a final journal state always wins.
|
|
2886
|
-
if (
|
|
2887
|
-
|
|
3449
|
+
if (fromServer && ACTION_FINAL.has(fromServer.state)) return fromServer;
|
|
3450
|
+
// #2266: the stored proposal, read once when the card was painted unfinished. A journal write that failed leaves the
|
|
3451
|
+
// card saying "Running…" over a stored "done"; the stored state is newer when it is further along.
|
|
3452
|
+
if (entry?.stored && ACTION_FINAL.has(entry.stored.state)) return entry.stored;
|
|
3453
|
+
if (entry?.local) return entry.local;
|
|
3454
|
+
const journal = fromServer || { state: 'proposed', result: null, supersededBy: null };
|
|
3455
|
+
if (entry?.stored && actionStateRank(entry.stored.state) > actionStateRank(journal.state)) return entry.stored;
|
|
3456
|
+
return journal;
|
|
3457
|
+
}
|
|
3458
|
+
|
|
3459
|
+
/** How far along a card's state is: waiting, then running, then any final state. */
|
|
3460
|
+
function actionStateRank(value) { return value === 'proposed' ? 0 : value === 'executing' ? 1 : 2; }
|
|
3461
|
+
|
|
3462
|
+
/**
|
|
3463
|
+
* #2266: read a card's proposal from FloLess once, when it is painted unfinished (a chat opened or reloaded), and
|
|
3464
|
+
* repaint it if the stored state is further along than the conversation recorded. A failed read leaves the card as
|
|
3465
|
+
* the conversation has it; nothing is retried until the chat is opened again.
|
|
3466
|
+
*/
|
|
3467
|
+
async function syncActionProposal(proposalId) {
|
|
3468
|
+
try {
|
|
3469
|
+
const path = `/api/actions/proposals/${encodeURIComponent(proposalId)}`;
|
|
3470
|
+
await globalThis.flolessStartupAdmission?.admit(path);
|
|
3471
|
+
const response = await fetch(path, { credentials: 'same-origin' });
|
|
3472
|
+
// FloLess no longer has it: nothing newer to show. Anything else that is not an answer is tried again (below).
|
|
3473
|
+
if (response.status === 404) return;
|
|
3474
|
+
const body = response.ok ? await response.json().catch(() => null) : null;
|
|
3475
|
+
const p = body?.ok === true ? body.proposal : null;
|
|
3476
|
+
if (!p || typeof p.state !== 'string') throw new Error(`the stored proposal could not be read (${response.status})`);
|
|
3477
|
+
const entry = actionCards.get(proposalId);
|
|
3478
|
+
if (!entry) return;
|
|
3479
|
+
entry.stored = { state: p.state, result: p.result || null, supersededBy: p.supersededBy || null, next: p.next || null };
|
|
3480
|
+
repaintActionCards();
|
|
3481
|
+
} catch (error) {
|
|
3482
|
+
// FloLess could not be reached: the conversation's own record stays on the card, and the next paint asks again.
|
|
3483
|
+
const entry = actionCards.get(proposalId);
|
|
3484
|
+
if (entry) entry.synced = false;
|
|
3485
|
+
console.warn('[floless] a suggested action card could not be checked against FloLess', error);
|
|
3486
|
+
}
|
|
2888
3487
|
}
|
|
2889
3488
|
|
|
2890
3489
|
function renderActionProposal(event) {
|
|
@@ -2897,6 +3496,8 @@
|
|
|
2897
3496
|
while (actionCards.size > ACTION_CARDS_KEPT) actionCards.delete(actionCards.keys().next().value);
|
|
2898
3497
|
}
|
|
2899
3498
|
const current = actionProposalState(proposalId);
|
|
3499
|
+
// #2266: an unfinished card asks FloLess once whether it has moved on (see syncActionProposal).
|
|
3500
|
+
if (!entry.synced && !ACTION_FINAL.has(current.state)) { entry.synced = true; void syncActionProposal(proposalId); }
|
|
2900
3501
|
const signature = JSON.stringify([event.eventId, current.state, current.result?.message || null, current.supersededBy, current.next || null, entry.busy, entry.error]);
|
|
2901
3502
|
if (entry.node && entry.signature === signature) return entry.node;
|
|
2902
3503
|
entry.node = paintActionProposal(event, payload, proposalId, entry, current);
|
|
@@ -2926,6 +3527,18 @@
|
|
|
2926
3527
|
return control;
|
|
2927
3528
|
}
|
|
2928
3529
|
|
|
3530
|
+
/**
|
|
3531
|
+
* Show one connection in its project's model editor, selected and framed (#2450). Resolves the editor's
|
|
3532
|
+
* own outcome (see `openConnection` in workspaces.js), or null when the shell cannot do it here. Throws
|
|
3533
|
+
* a sentence written for the person (`plain`) when the editor was never reached.
|
|
3534
|
+
*/
|
|
3535
|
+
async function openConnectionInModel(projectId, jointId, extra = {}) {
|
|
3536
|
+
if (typeof window.flolessWorkspaces?.openConnection !== 'function') return null;
|
|
3537
|
+
// #2450: `extra` asks the editor to open its "Raise an RFI" dialog too, with one check first.
|
|
3538
|
+
return await window.flolessWorkspaces.openConnection({ projectId, jointId,
|
|
3539
|
+
...(extra.raiseRfi === true ? { raiseRfi: true } : {}), ...(typeof extra.checkId === 'string' && extra.checkId ? { checkId: extra.checkId } : {}) });
|
|
3540
|
+
}
|
|
3541
|
+
|
|
2929
3542
|
/** Open the screen a human-only action names, or the one showing what a finished action made. Nothing runs. */
|
|
2930
3543
|
async function openActionScreen(screen) {
|
|
2931
3544
|
if (screen?.view === 'page' && screen.pageHome && screen.pageId && typeof window.flolessPages?.open === 'function') {
|
|
@@ -2946,6 +3559,12 @@
|
|
|
2946
3559
|
if (screen?.view === 'requests' && screen.requestId && typeof window.flolessBridge?.openRequest === 'function') {
|
|
2947
3560
|
await window.flolessBridge.openRequest(screen.requestId); return true;
|
|
2948
3561
|
}
|
|
3562
|
+
// #2450: one connection, selected and framed in the project's model editor. Like every screen here it
|
|
3563
|
+
// answers only whether it opened; the readiness card reads the editor's full outcome itself.
|
|
3564
|
+
if (screen?.view === 'connection' && screen.projectId && screen.jointId) {
|
|
3565
|
+
const outcome = await openConnectionInModel(screen.projectId, screen.jointId);
|
|
3566
|
+
return outcome?.ok === true || outcome?.superseded === true;
|
|
3567
|
+
}
|
|
2949
3568
|
if (screen?.view === 'project' && screen.step === 'drawings' && screen.projectId && typeof window.flolessWorkspaces?.openDrawingsStep === 'function') {
|
|
2950
3569
|
await window.flolessWorkspaces.openDrawingsStep(screen.projectId); return true;
|
|
2951
3570
|
}
|
|
@@ -2955,6 +3574,10 @@
|
|
|
2955
3574
|
if (['workspaces', 'workflows'].includes(screen?.view) && typeof window.flolessWorkspaces?.setMode === 'function') {
|
|
2956
3575
|
await window.flolessWorkspaces.setMode(screen.view); return true;
|
|
2957
3576
|
}
|
|
3577
|
+
// Automatic tool updates: the dialog where the person reads the wording and chooses (it opens nothing else, runs nothing).
|
|
3578
|
+
if (screen?.view === 'tool-update-policy' && typeof window.openToolUpdatePolicy === 'function') {
|
|
3579
|
+
window.openToolUpdatePolicy(); return true;
|
|
3580
|
+
}
|
|
2958
3581
|
// Requests, at the request the screen names.
|
|
2959
3582
|
if (screen?.view === 'requests' && typeof window.flolessBridge?.openRequest === 'function') {
|
|
2960
3583
|
await window.flolessBridge.openRequest(screen.requestId || null); return true;
|
|
@@ -2962,7 +3585,10 @@
|
|
|
2962
3585
|
return false;
|
|
2963
3586
|
}
|
|
2964
3587
|
|
|
2965
|
-
/**
|
|
3588
|
+
/**
|
|
3589
|
+
* Take a confirmed step FloLess's own window must take (#2290). Returns a plain failure sentence, or '' when it went,
|
|
3590
|
+
* or { handedOver: sentence } when it went as far as it may and the last click is the person's (#2427).
|
|
3591
|
+
*/
|
|
2966
3592
|
async function runBrowserStep(step) {
|
|
2967
3593
|
if (step?.flow === 'stop-app') {
|
|
2968
3594
|
// The menu's own Stop FloLess: it asks about anything not saved, then closes FloLess and shows the stopped screen.
|
|
@@ -2989,8 +3615,58 @@
|
|
|
2989
3615
|
return 'FloLess could not be reached to open the desktop app. Check that it is still running.';
|
|
2990
3616
|
}
|
|
2991
3617
|
}
|
|
3618
|
+
if (step?.flow === 'model-source') {
|
|
3619
|
+
// #2363: the project's own Source step presses its own Replace / Try again / Cancel control, so the real call
|
|
3620
|
+
// runs with this window's editor session. It answers a plain sentence when it could not, or when the person must act.
|
|
3621
|
+
if (typeof window.flolessWorkspaces?.modelSourceStep !== 'function') return 'FloLess could not open the project from here. Open it from Workspaces and use its Source step.';
|
|
3622
|
+
try { return stepAnswer(await window.flolessWorkspaces.modelSourceStep(step)); }
|
|
3623
|
+
catch { return 'FloLess could not open the project’s Source step from here. Open it from Workspaces.'; }
|
|
3624
|
+
}
|
|
3625
|
+
if (step?.flow === 'knowledge-pick') {
|
|
3626
|
+
// #2399 slice 0b: the project's Knowledge step opens its own file picker; what the person picks there is added.
|
|
3627
|
+
if (typeof window.flolessWorkspaces?.knowledgePickStep !== 'function') return 'FloLess could not open the project from here. Open it from Workspaces and use its Knowledge step.';
|
|
3628
|
+
try { return stepAnswer(await window.flolessWorkspaces.knowledgePickStep(step)); }
|
|
3629
|
+
catch { return 'FloLess could not open the project’s Knowledge step from here. Open it from Workspaces.'; }
|
|
3630
|
+
}
|
|
3631
|
+
if (step?.flow === 'parser-setup') {
|
|
3632
|
+
if (typeof window.flolessParserSetupRecovery?.open !== 'function') return 'FloLess could not open the setup review from here. Use the setup card on the Workspaces screen.';
|
|
3633
|
+
try { const said = await window.flolessParserSetupRecovery.open(step.appId); return typeof said === 'string' ? said : ''; }
|
|
3634
|
+
catch { return 'FloLess could not open the setup review from here. Use the setup card on the Workspaces screen.'; }
|
|
3635
|
+
}
|
|
3636
|
+
if (step?.flow === 'workspace-root') {
|
|
3637
|
+
if (typeof window.flolessWorkspaceRootReview !== 'function') return 'FloLess could not open the saved directories from here. Use the Workspace directory button on the Workspaces screen.';
|
|
3638
|
+
try { return String((await window.flolessWorkspaceRootReview(step)) || ''); }
|
|
3639
|
+
catch { return 'FloLess could not open the saved directories from here. Use the Workspace directory button on the Workspaces screen.'; }
|
|
3640
|
+
}
|
|
2992
3641
|
return 'FloLess did not recognise the step this card asked its window to take, so it did nothing. Try it from the screen instead.';
|
|
2993
3642
|
}
|
|
3643
|
+
/** A step's own answer: a failure sentence, '' when it went, or a hand-over to the person with the sentence it showed. */
|
|
3644
|
+
function stepAnswer(said) {
|
|
3645
|
+
if (said && typeof said === 'object' && typeof said.handedOver === 'string' && said.handedOver) {
|
|
3646
|
+
return { handedOver: said.handedOver, ...(said.focus && typeof said.focus.focus === 'function' ? { focus: said.focus } : {}) };
|
|
3647
|
+
}
|
|
3648
|
+
return String(said || '');
|
|
3649
|
+
}
|
|
3650
|
+
/**
|
|
3651
|
+
* Tell FloLess how a step this window took for a confirmed card went: done, or not done with the sentence shown here.
|
|
3652
|
+
* Until it is told, the card stays running (a restart marks it "not known"), so a failed report only leaves it
|
|
3653
|
+
* honest, never "done". Returns the settled proposal, or null when the report did not land.
|
|
3654
|
+
*/
|
|
3655
|
+
async function reportBrowserStep(proposalId, outcome) {
|
|
3656
|
+
const handed = outcome && typeof outcome === 'object' && outcome.handedOver ? String(outcome.handedOver) : '';
|
|
3657
|
+
const failed = handed ? '' : outcome;
|
|
3658
|
+
try {
|
|
3659
|
+
const response = await fetch(`/api/actions/proposals/${encodeURIComponent(proposalId)}/step`, {
|
|
3660
|
+
method: 'POST', credentials: 'same-origin', headers: { 'content-type': 'application/json' },
|
|
3661
|
+
body: JSON.stringify(handed ? { done: true, handedOver: true, note: handed } : failed ? { done: false, note: String(failed) } : { done: true }),
|
|
3662
|
+
});
|
|
3663
|
+
const body = await response.json().catch(() => null);
|
|
3664
|
+
return response.ok && body?.ok === true ? body.proposal || null : null;
|
|
3665
|
+
} catch { return null; }
|
|
3666
|
+
}
|
|
3667
|
+
// The terminal-request dialog takes the same steps for a request a terminal made (terminal-requests.js).
|
|
3668
|
+
window.flolessRunBrowserStep = runBrowserStep;
|
|
3669
|
+
window.flolessReportBrowserStep = reportBrowserStep;
|
|
2994
3670
|
|
|
2995
3671
|
async function sendActionProposal(proposalId, verb) {
|
|
2996
3672
|
const response = await fetch(`/api/actions/proposals/${encodeURIComponent(proposalId)}/${verb}`, {
|
|
@@ -3016,8 +3692,16 @@
|
|
|
3016
3692
|
// #2290: a step only this window may take (its route checks the window's own origin) is taken here, now that the
|
|
3017
3693
|
// person confirmed it: the same flow the menu or the Requests button runs.
|
|
3018
3694
|
if (verb === 'confirm' && event.payload?.browserStep) {
|
|
3019
|
-
const
|
|
3695
|
+
const outcome = await runBrowserStep(event.payload.browserStep);
|
|
3696
|
+
const failed = typeof outcome === 'string' ? outcome : '';
|
|
3020
3697
|
if (failed) entry.error = failed;
|
|
3698
|
+
// The record says how the step went, so neither the card nor the AI calls it done when it was not. A Stop FloLess
|
|
3699
|
+
// that went ahead is settled by the server when it accepts the stop: this window's requests are already stopped.
|
|
3700
|
+
const stopped = event.payload.browserStep.flow === 'stop-app' && !failed;
|
|
3701
|
+
const settled = stopped ? null : await reportBrowserStep(proposalId, outcome);
|
|
3702
|
+
if (settled) entry.local = { state: settled.state || entry.local.state, result: settled.result || null, supersededBy: null };
|
|
3703
|
+
// #2427: the report did not land, so the card stays running: still show the person what to press.
|
|
3704
|
+
else if (outcome && typeof outcome === 'object' && outcome.handedOver) entry.error = String(outcome.handedOver);
|
|
3021
3705
|
}
|
|
3022
3706
|
} else if (body.fresh) {
|
|
3023
3707
|
// The target changed or the offer ended: the old card says so, and a fresh card shows the current state.
|
|
@@ -3076,7 +3760,10 @@
|
|
|
3076
3760
|
const eyebrow = document.createElement('span');
|
|
3077
3761
|
eyebrow.className = 'guide-move-eyebrow';
|
|
3078
3762
|
// A request that has been answered no longer "needs your OK": the eyebrow says where it ended up.
|
|
3079
|
-
|
|
3763
|
+
// #2427: a step that left the last click to the person is theirs to finish, not a failure and not yet done.
|
|
3764
|
+
const handedOver = current.state === 'done' && current.result?.code === 'step-handed-over';
|
|
3765
|
+
eyebrow.textContent = handedOver ? 'Waiting for you'
|
|
3766
|
+
: { executing: actionId === 'workflows.run' || actionId === 'routines.run' ? 'Running' : 'Working', done: 'Finished', failed: 'Could not finish', unknown: 'Outcome unknown' }[current.state] || ACTION_EYEBROWS[risk];
|
|
3080
3767
|
const strong = document.createElement('strong');
|
|
3081
3768
|
strong.id = titleId;
|
|
3082
3769
|
strong.textContent = title;
|
|
@@ -3084,7 +3771,7 @@
|
|
|
3084
3771
|
named.className = 'ai-chat-action-named';
|
|
3085
3772
|
named.append(eyebrow, strong);
|
|
3086
3773
|
head.append(named);
|
|
3087
|
-
const badgeText = { executing: 'Running', done: 'Done', failed: 'Not done', unknown: 'Unknown' }[current.state];
|
|
3774
|
+
const badgeText = handedOver ? 'Your turn' : { executing: 'Running', done: 'Done', failed: 'Not done', unknown: 'Unknown' }[current.state];
|
|
3088
3775
|
if (badgeText) {
|
|
3089
3776
|
const badge = document.createElement('span');
|
|
3090
3777
|
badge.className = 'ai-chat-filter-state';
|
|
@@ -3102,11 +3789,33 @@
|
|
|
3102
3789
|
summary.className = 'ai-chat-action-summary';
|
|
3103
3790
|
summary.textContent = summaryText;
|
|
3104
3791
|
card.append(summary);
|
|
3105
|
-
|
|
3792
|
+
// #2521 row 3a: what confirming agrees to (a Quick model read), whole and on its own line: the summary is cut to its
|
|
3793
|
+
// limit, terms never are.
|
|
3794
|
+
if (payload.terms) {
|
|
3795
|
+
const terms = document.createElement('p');
|
|
3796
|
+
terms.className = 'ai-chat-action-summary ai-chat-action-terms';
|
|
3797
|
+
// A real element, not CSS content, so a screen reader announces it with the terms.
|
|
3798
|
+
const label = document.createElement('strong');
|
|
3799
|
+
label.className = 'ai-chat-action-terms-label';
|
|
3800
|
+
label.textContent = 'What you agree to';
|
|
3801
|
+
terms.append(label, document.createTextNode(String(payload.terms)));
|
|
3802
|
+
card.append(terms);
|
|
3803
|
+
}
|
|
3804
|
+
|
|
3805
|
+
if (handedOver) {
|
|
3806
|
+
card.classList.add('is-handed-over');
|
|
3807
|
+
status.textContent = entry.error || String(current.result?.message || 'It is ready for you. Press it to finish.');
|
|
3808
|
+
card.append(status);
|
|
3809
|
+
return card;
|
|
3810
|
+
}
|
|
3106
3811
|
if (current.state === 'done') {
|
|
3107
3812
|
card.classList.add('is-done');
|
|
3108
3813
|
// A step this window took after the confirm (#2290) can still fail here; that is said, never "Done." over it.
|
|
3109
|
-
|
|
3814
|
+
// #2521 row 3a: the route's own answer, when it changed what happened (a Quick read queued Precise), comes first,
|
|
3815
|
+
// and the card's edge turns amber so the person notices their choice was not what ran.
|
|
3816
|
+
const resultNote = typeof current.result?.note === 'string' && current.result.note ? current.result.note : '';
|
|
3817
|
+
if (resultNote) card.classList.add('is-fallback');
|
|
3818
|
+
status.textContent = entry.error || resultNote || (current.next ? 'Done. Its result is ready to view.' : String(payload.doneNote || 'Done.'));
|
|
3110
3819
|
if (current.next) {
|
|
3111
3820
|
// What the finished action made (a run's report): opening it only shows it, it runs nothing again.
|
|
3112
3821
|
const actions = document.createElement('div');
|
|
@@ -3130,7 +3839,10 @@
|
|
|
3130
3839
|
// A route's refusal can be a bare fragment: show it as a sentence, with the next step after it.
|
|
3131
3840
|
const refusal = String(current.result?.message || '').trim();
|
|
3132
3841
|
const sentence = refusal ? refusal.charAt(0).toUpperCase() + refusal.slice(1) + (/[.!?…]$/.test(refusal) ? '' : '.') : '';
|
|
3133
|
-
|
|
3842
|
+
// A step this window could not take already says what to do instead (open the review, try it from Requests).
|
|
3843
|
+
status.textContent = current.result?.code === 'step-not-done' && sentence
|
|
3844
|
+
? sentence
|
|
3845
|
+
: `${sentence || 'It did not complete.'} You can ask the AI to suggest it again.`;
|
|
3134
3846
|
card.append(status);
|
|
3135
3847
|
return card;
|
|
3136
3848
|
}
|
|
@@ -3154,7 +3866,8 @@
|
|
|
3154
3866
|
const actions = document.createElement('div');
|
|
3155
3867
|
actions.className = 'ai-chat-filter-actions';
|
|
3156
3868
|
if (current.state === 'executing') {
|
|
3157
|
-
|
|
3869
|
+
// A window step whose report did not land stays running here; what the window said (what to press) still shows.
|
|
3870
|
+
status.textContent = entry.error || (actionId === 'workflows.run' || actionId === 'routines.run' ? 'Running…' : 'Working…');
|
|
3158
3871
|
if (actionId === 'workflows.run') {
|
|
3159
3872
|
const stop = actionButton('Stop', 'shell.chat-action-stop', proposalId, summaryText);
|
|
3160
3873
|
stop.dataset.tip = 'Asks the run to stop. Work already sent to the host may remain.';
|
|
@@ -3239,14 +3952,22 @@
|
|
|
3239
3952
|
const badge = document.createElement('span');
|
|
3240
3953
|
badge.className = 'pg-ai-badge';
|
|
3241
3954
|
badge.textContent = 'AI-made';
|
|
3242
|
-
|
|
3955
|
+
// A Page the chat only SHOWED (#2389) may have been made elsewhere: the tip must not claim this conversation made it.
|
|
3956
|
+
badge.dataset.tip = card.shown ? 'Made by AI. Check it before you rely on it or share it.' : 'Made by AI in this conversation. Check it before you rely on it or share it.';
|
|
3243
3957
|
badge.tabIndex = 0;
|
|
3244
3958
|
head.append(badge);
|
|
3245
3959
|
}
|
|
3246
3960
|
const line = document.createElement('p');
|
|
3247
3961
|
line.className = 'ai-chat-action-line ai-chat-page-ver';
|
|
3248
|
-
line.textContent = card.based ? 'Version 1 · a new Page' : version > 1 ? `Version ${version} · added to this Page` : 'Version 1';
|
|
3962
|
+
line.textContent = card.shown ? `Version ${version} · shown here` : card.based ? 'Version 1 · a new Page' : version > 1 ? `Version ${version} · added to this Page` : 'Version 1';
|
|
3249
3963
|
node.append(head, line);
|
|
3964
|
+
if (card.shown && typeof card.note === 'string' && card.note) {
|
|
3965
|
+
// FloLess's own sentence when the version asked for isn't kept, so the latest is shown instead.
|
|
3966
|
+
const shownNote = document.createElement('p');
|
|
3967
|
+
shownNote.className = 'ai-chat-action-line ai-chat-page-based';
|
|
3968
|
+
shownNote.textContent = card.note;
|
|
3969
|
+
node.append(shownNote);
|
|
3970
|
+
}
|
|
3250
3971
|
const basedOn = card.basedOn && card.basedOn.home && card.basedOn.pageId ? card.basedOn : null;
|
|
3251
3972
|
if (card.based) {
|
|
3252
3973
|
const note = document.createElement('p');
|
|
@@ -3285,10 +4006,580 @@
|
|
|
3285
4006
|
return node;
|
|
3286
4007
|
}
|
|
3287
4008
|
|
|
4009
|
+
/* ---- #2439: connection readiness ------------------------------------------------------------------------------------
|
|
4010
|
+
* What FloLess measured and recorded for each connection, drawn as the action returned it. It certifies nothing: there
|
|
4011
|
+
* is no "ready" state, a check outside its limit says by how much in words, a check FloLess could not make says so, and
|
|
4012
|
+
* sign-off stays the person's. The three choices only fill the message box.
|
|
4013
|
+
*/
|
|
4014
|
+
/** The card's note that a built connection had no checks to measure: shown, but not a question to raise. Worded as connection-readiness.ts writes it. */
|
|
4015
|
+
const READINESS_NOTHING_MEASURED = 'No checks were measured for this connection';
|
|
4016
|
+
const READINESS_REVIEW = {
|
|
4017
|
+
'signed-off': 'You accepted this imported connection as drawn. That is not a fabrication check.',
|
|
4018
|
+
'needs-review': 'This imported connection has changed since FloLess recorded its placement. Review it before you sign it off.',
|
|
4019
|
+
untracked: 'This imported connection is not watched for review, so FloLess cannot record a sign-off for it. Place it again in the model to watch it.',
|
|
4020
|
+
'clean-not-signed-off': 'This imported connection is not signed off yet.',
|
|
4021
|
+
'not-available': 'FloLess has no sign-off for this kind of connection yet.',
|
|
4022
|
+
unavailable: 'FloLess could not read the sign-offs just now, so it cannot say whether this connection is signed off.',
|
|
4023
|
+
};
|
|
4024
|
+
/** Only these states have a sign-off waiting for the person; the others would refuse it or have nothing to sign. */
|
|
4025
|
+
const READINESS_SIGNABLE = new Set(['needs-review', 'clean-not-signed-off']);
|
|
4026
|
+
|
|
4027
|
+
/**
|
|
4028
|
+
* Millimetres to one decimal, with more digits when one decimal would hide a small, real difference. Below a millionth
|
|
4029
|
+
* of a millimetre (the finest tolerance FloLess measures to) a value is arithmetic noise and reads as 0.0.
|
|
4030
|
+
*/
|
|
4031
|
+
function readinessMm(value) {
|
|
4032
|
+
if (!Number.isFinite(value)) return '—';
|
|
4033
|
+
if (Math.abs(value) < 1e-6) return '0.0 mm';
|
|
4034
|
+
const rounded = Math.round(value * 10) / 10;
|
|
4035
|
+
return `${rounded !== 0 ? rounded.toFixed(1) : String(Number(value.toPrecision(2)))} mm`;
|
|
4036
|
+
}
|
|
4037
|
+
|
|
4038
|
+
function readinessCount(n, word) {
|
|
4039
|
+
return `${n} ${word}${n === 1 ? '' : 's'}`;
|
|
4040
|
+
}
|
|
4041
|
+
|
|
4042
|
+
/**
|
|
4043
|
+
* Whether the tolerance decided this result: the measurement misses the limit taken strictly, by more than the
|
|
4044
|
+
* arithmetic noise `readinessMm` reads as zero, and passes only because of the tolerance.
|
|
4045
|
+
*/
|
|
4046
|
+
function readinessToleranceDecided(fact) {
|
|
4047
|
+
if (fact.verdict !== 'within' || !Number.isFinite(fact.actualMm) || !Number.isFinite(fact.limitMm)) return false;
|
|
4048
|
+
const diff = fact.actualMm - fact.limitMm;
|
|
4049
|
+
if (Math.abs(diff) < 1e-6) return false;
|
|
4050
|
+
return fact.relation === 'at-least' ? diff < 0 : fact.relation === 'at-most' ? diff > 0 : true;
|
|
4051
|
+
}
|
|
4052
|
+
|
|
4053
|
+
/** The limit, and its tolerance wherever the tolerance explains the result: outside it, decided by it, or big enough to matter. */
|
|
4054
|
+
function readinessLimit(fact) {
|
|
4055
|
+
const relation = fact.relation === 'at-least' ? 'at least ' : fact.relation === 'at-most' ? 'at most ' : '';
|
|
4056
|
+
const telling = fact.verdict === 'outside' || readinessToleranceDecided(fact) || fact.toleranceMm >= 0.05;
|
|
4057
|
+
const tolerance = Number.isFinite(fact.toleranceMm) && fact.toleranceMm > 0 && telling ? ` (±${readinessMm(fact.toleranceMm)})` : '';
|
|
4058
|
+
return `${relation}${readinessMm(fact.limitMm)}${tolerance}`;
|
|
4059
|
+
}
|
|
4060
|
+
|
|
4061
|
+
/** A connection has two welds, two edges, several bolts: number the repeats so each row is its own check. */
|
|
4062
|
+
function readinessLabels(facts) {
|
|
4063
|
+
const total = new Map();
|
|
4064
|
+
for (const fact of facts) total.set(fact.label, (total.get(fact.label) || 0) + 1);
|
|
4065
|
+
const seen = new Map();
|
|
4066
|
+
return facts.map((fact) => {
|
|
4067
|
+
if (total.get(fact.label) < 2) return fact.label;
|
|
4068
|
+
seen.set(fact.label, (seen.get(fact.label) || 0) + 1);
|
|
4069
|
+
return `${fact.label} ${seen.get(fact.label)}`;
|
|
4070
|
+
});
|
|
4071
|
+
}
|
|
4072
|
+
|
|
4073
|
+
/** The result of one check, in words: never a colour or a tick alone. */
|
|
4074
|
+
function readinessResult(fact) {
|
|
4075
|
+
if (fact.verdict === 'unmeasured') return 'Not measured';
|
|
4076
|
+
if (fact.verdict === 'within') return 'Within limit';
|
|
4077
|
+
const off = Math.abs((fact.actualMm ?? 0) - (fact.limitMm ?? 0));
|
|
4078
|
+
if (fact.relation === 'at-least') return `Short by ${readinessMm(off)}`;
|
|
4079
|
+
if (fact.relation === 'at-most') return `Over by ${readinessMm(off)}`;
|
|
4080
|
+
return `Off by ${readinessMm(off)}`;
|
|
4081
|
+
}
|
|
4082
|
+
|
|
4083
|
+
/** The small dashed tag on a check that rests on a holding assumption: dashed is this card's "assumed", never a pass. */
|
|
4084
|
+
function readinessAssumedTag(assumption) {
|
|
4085
|
+
const tag = Object.assign(document.createElement('span'), { className: 'ai-chat-assume ai-chat-readiness-assumed', textContent: 'Assumed' });
|
|
4086
|
+
const words = String(assumption.statement || '');
|
|
4087
|
+
tag.dataset.tip = `You confirmed: “${words}${/[.!?]$/.test(words) ? '' : '.'}” The result is still the measured one`;
|
|
4088
|
+
tag.tabIndex = 0;
|
|
4089
|
+
tag.dataset.assumptionId = String(assumption.id || '');
|
|
4090
|
+
tag.setAttribute('aria-label', `Assumed: ${assumption.statement}`);
|
|
4091
|
+
return tag;
|
|
4092
|
+
}
|
|
4093
|
+
|
|
4094
|
+
const READINESS_STALE = {
|
|
4095
|
+
'connection-changed': 'No longer applies. This connection changed after you confirmed it.',
|
|
4096
|
+
'check-gone': 'No longer applies. The check it was about is not on this connection any more.',
|
|
4097
|
+
'connection-gone': 'No longer applies. This connection is not in the model any more.',
|
|
4098
|
+
};
|
|
4099
|
+
|
|
4100
|
+
function readinessDate(iso) {
|
|
4101
|
+
const date = new Date(iso);
|
|
4102
|
+
return Number.isFinite(date.getTime()) ? date.toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' }) : 'an earlier date';
|
|
4103
|
+
}
|
|
4104
|
+
|
|
4105
|
+
function readinessTime(iso) {
|
|
4106
|
+
const date = new Date(iso);
|
|
4107
|
+
return Number.isFinite(date.getTime()) ? date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }) : '';
|
|
4108
|
+
}
|
|
4109
|
+
|
|
4110
|
+
/**
|
|
4111
|
+
* #2449: the assumptions a person confirmed on this connection, as this answer read them. A holding one carries the
|
|
4112
|
+
* dashed edge; one that no longer applies says why, in words, and carries no weight. The person can withdraw each here.
|
|
4113
|
+
*/
|
|
4114
|
+
function readinessAssumptions(row, card, assumptions) {
|
|
4115
|
+
if (!assumptions.length && !row.assumptionsHeldBack) return null;
|
|
4116
|
+
const wrap = document.createElement('div'); wrap.className = 'ai-chat-readiness-list ai-chat-readiness-assumptions';
|
|
4117
|
+
wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-sub', textContent: 'Assumptions you confirmed' }));
|
|
4118
|
+
const at = card.readAt ? readinessTime(card.readAt) : '';
|
|
4119
|
+
if (at) wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-asread', textContent: `As read at ${at}. Ask again to see them now.` }));
|
|
4120
|
+
const list = document.createElement('ul');
|
|
4121
|
+
list.setAttribute('aria-label', `Assumptions you confirmed for ${row.kindLabel || row.kind} ${row.jointId}`);
|
|
4122
|
+
for (const a of assumptions) {
|
|
4123
|
+
const item = document.createElement('li');
|
|
4124
|
+
item.className = `ai-chat-readiness-assumption is-${a.state === 'holds' ? 'holding' : 'stale'}`;
|
|
4125
|
+
item.dataset.assumptionId = String(a.id || '');
|
|
4126
|
+
if (a.state !== 'holds') item.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-assumption-state', textContent: READINESS_STALE[a.staleReason] || READINESS_STALE['connection-changed'] }));
|
|
4127
|
+
item.append(Object.assign(document.createElement('q'), { className: 'ai-chat-readiness-assumption-words', textContent: String(a.statement || '') }),
|
|
4128
|
+
Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-assumption-meta', textContent: `About: ${a.readingText}` }),
|
|
4129
|
+
Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-assumption-meta',
|
|
4130
|
+
textContent: `You confirmed this on ${readinessDate(a.confirmedAt)}.${a.proposedBy === 'ai' ? ' The AI wrote the words.' : ''}` }));
|
|
4131
|
+
if (card.projectId) {
|
|
4132
|
+
const withdraw = button('Withdraw', 'shell.chat-readiness-withdraw-assumption', 'ai-chat-source-action');
|
|
4133
|
+
withdraw.setAttribute('aria-label', `Withdraw assumption: ${a.statement}`);
|
|
4134
|
+
withdraw.dataset.commandInstanceLabel = `${row.jointId}: ${a.statement}`;
|
|
4135
|
+
withdraw.dataset.tip = 'Removes this assumption. The check then reads as the plain check again';
|
|
4136
|
+
withdraw.addEventListener('click', () => withdrawReadinessAssumption(card.projectId, row.jointId, a.id, withdraw));
|
|
4137
|
+
const actions = document.createElement('div'); actions.className = 'ai-chat-readiness-actions';
|
|
4138
|
+
actions.append(withdraw);
|
|
4139
|
+
item.append(actions);
|
|
4140
|
+
}
|
|
4141
|
+
list.append(item);
|
|
4142
|
+
}
|
|
4143
|
+
wrap.append(list);
|
|
4144
|
+
if (row.assumptionsHeldBack) wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-sub', textContent: `${readinessCount(row.assumptionsHeldBack, 'more assumption')} on this connection not shown here. Ask about it alone to see them.` }));
|
|
4145
|
+
return wrap;
|
|
4146
|
+
}
|
|
4147
|
+
|
|
4148
|
+
/**
|
|
4149
|
+
* Withdraw one assumption: a person's click in this window. Success replaces the button with a receipt, which takes the
|
|
4150
|
+
* focus; a failure keeps the button (and the focus on it) and says why underneath.
|
|
4151
|
+
*/
|
|
4152
|
+
async function withdrawReadinessAssumption(projectId, jointId, assumptionId, control) {
|
|
4153
|
+
if (control.getAttribute('aria-disabled') === 'true') return;
|
|
4154
|
+
control.setAttribute('aria-disabled', 'true');
|
|
4155
|
+
control.textContent = 'Withdrawing…';
|
|
4156
|
+
const item = control.closest('li');
|
|
4157
|
+
const row = control.closest('.ai-chat-readiness-row');
|
|
4158
|
+
item?.querySelector('.ai-chat-readiness-receipt')?.remove();
|
|
4159
|
+
let answer;
|
|
4160
|
+
try {
|
|
4161
|
+
answer = await request(`/api/projects/${encodeURIComponent(projectId)}/connections/${encodeURIComponent(jointId)}/assumptions/${encodeURIComponent(assumptionId)}/withdraw`, { method: 'POST' });
|
|
4162
|
+
} catch (error) {
|
|
4163
|
+
control.removeAttribute('aria-disabled');
|
|
4164
|
+
control.textContent = 'Withdraw';
|
|
4165
|
+
// What happened, why, and what to do next: only a reason that can pass is followed by "try again".
|
|
4166
|
+
const text = error?.code === 'project-not-found'
|
|
4167
|
+
? 'Not withdrawn: this project is no longer in FloLess, so there is nothing to withdraw here.'
|
|
4168
|
+
: `Not withdrawn: ${String(error?.message || 'FloLess could not reach this project just now').replace(/[.\s]+$/, '')}. Nothing was changed. Try again in a moment.`;
|
|
4169
|
+
const note = Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-receipt is-failed', textContent: text });
|
|
4170
|
+
note.setAttribute('role', 'alert');
|
|
4171
|
+
control.parentElement?.after(note);
|
|
4172
|
+
return;
|
|
4173
|
+
}
|
|
4174
|
+
// Already gone (another tab, or recorded again under a new id) is said as such, never as this click's doing.
|
|
4175
|
+
const receipt = answer?.changed === false
|
|
4176
|
+
? 'It was already withdrawn. Nothing changed. Ask again to see the connection as it is now.'
|
|
4177
|
+
: 'Withdrawn. Ask again to see the connection as it is now.';
|
|
4178
|
+
const note = Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-receipt', textContent: receipt, tabIndex: -1 });
|
|
4179
|
+
note.setAttribute('role', 'status');
|
|
4180
|
+
const wasHolding = item?.classList.contains('is-holding');
|
|
4181
|
+
control.replaceWith(note);
|
|
4182
|
+
item?.classList.add('is-withdrawn');
|
|
4183
|
+
// Nothing on this card rests on it any more: its tags go with it, and the counts stop including it.
|
|
4184
|
+
for (const tag of row ? row.querySelectorAll('.ai-chat-readiness-assumed') : []) if (tag.dataset.assumptionId === String(assumptionId)) tag.remove();
|
|
4185
|
+
if (wasHolding) {
|
|
4186
|
+
readinessUncount(row?.querySelector('.ai-chat-readiness-status'), ' · ');
|
|
4187
|
+
readinessUncount(row?.closest('.ai-chat-readiness-card')?.querySelector('.ai-chat-filter-card-head .ai-chat-filter-state'), ' · ');
|
|
4188
|
+
}
|
|
4189
|
+
note.focus({ preventScroll: true });
|
|
4190
|
+
}
|
|
4191
|
+
|
|
4192
|
+
/** One fewer "N on an assumption" in a count line, the part dropped at zero (a person withdrew one on this card). */
|
|
4193
|
+
function readinessUncount(node, separator) {
|
|
4194
|
+
if (!node) return;
|
|
4195
|
+
const parts = node.textContent.split(separator);
|
|
4196
|
+
const next = parts.flatMap((part) => {
|
|
4197
|
+
const m = /^(\d+) on an assumption$/.exec(part);
|
|
4198
|
+
if (!m) return [part];
|
|
4199
|
+
const n = Number(m[1]) - 1;
|
|
4200
|
+
return n > 0 ? [`${n} on an assumption`] : [];
|
|
4201
|
+
});
|
|
4202
|
+
node.textContent = next.length ? next.join(separator) : 'Nothing measured is outside a limit';
|
|
4203
|
+
}
|
|
4204
|
+
|
|
4205
|
+
/** The holding assumption a person confirmed on one line of the answer, if any. */
|
|
4206
|
+
function readinessHolding(assumptions, kind, text) {
|
|
4207
|
+
return assumptions.find((a) => a.state === 'holds' && a.covers?.kind === kind && a.covers.text === text) || null;
|
|
4208
|
+
}
|
|
4209
|
+
|
|
4210
|
+
/** A list whose lines may rest on an assumption: each such line keeps its words and gains the dashed tag. */
|
|
4211
|
+
function readinessAssumedList(title, entries) {
|
|
4212
|
+
const node = readinessList(title, entries.map(([text]) => text));
|
|
4213
|
+
if (!node) return null;
|
|
4214
|
+
const items = node.querySelectorAll('li');
|
|
4215
|
+
entries.forEach(([, on], index) => { if (on && items[index]) items[index].append(' ', readinessAssumedTag(on)); });
|
|
4216
|
+
return node;
|
|
4217
|
+
}
|
|
4218
|
+
|
|
4219
|
+
function readinessList(title, items) {
|
|
4220
|
+
if (!items.length) return null;
|
|
4221
|
+
const wrap = document.createElement('div'); wrap.className = 'ai-chat-readiness-list';
|
|
4222
|
+
const head = Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-sub', textContent: title });
|
|
4223
|
+
const list = document.createElement('ul');
|
|
4224
|
+
for (const item of items) list.append(Object.assign(document.createElement('li'), { textContent: item }));
|
|
4225
|
+
wrap.append(head, list);
|
|
4226
|
+
return wrap;
|
|
4227
|
+
}
|
|
4228
|
+
|
|
4229
|
+
/*
|
|
4230
|
+
* #2451: where on the drawings each member, and the detail a member's size came from, were read. Each place opens the
|
|
4231
|
+
* source page cropped to it. The tag says who drew the area; nothing here says the connection fits.
|
|
4232
|
+
*/
|
|
4233
|
+
const EVIDENCE_ORIGIN = {
|
|
4234
|
+
'member-line': { tag: 'line framed by FloLess', note: (e) => `FloLess outlined this member's line on page ${e.page} of ${e.sheet}. This shows where it was read, not that the connection fits.` },
|
|
4235
|
+
'reader-detail': { tag: 'area recorded by the drawing reader', note: (e) => `The drawing reader recorded this area on page ${e.page} of ${e.sheet}. This shows where a size was read, not that the connection fits.` },
|
|
4236
|
+
};
|
|
4237
|
+
|
|
4238
|
+
function readinessEvidence(row, card) {
|
|
4239
|
+
const places = (Array.isArray(row.drawingEvidence) ? row.drawingEvidence : []).filter((e) => e && EVIDENCE_ORIGIN[e.origin]);
|
|
4240
|
+
const gaps = Array.isArray(row.drawingEvidenceGaps) ? row.drawingEvidenceGaps.map(String) : [];
|
|
4241
|
+
if (!places.length && !gaps.length) return null;
|
|
4242
|
+
const wrap = document.createElement('div'); wrap.className = 'ai-chat-readiness-list ai-chat-readiness-evidence';
|
|
4243
|
+
wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-sub', textContent: 'Where on the drawings' }),
|
|
4244
|
+
Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-asread', textContent: 'Shows where each member and size was read. It does not show that the connection fits.' }));
|
|
4245
|
+
const list = document.createElement('ul');
|
|
4246
|
+
for (const place of places) {
|
|
4247
|
+
const item = document.createElement('li');
|
|
4248
|
+
const open = button('', 'shell.chat-readiness-open-evidence', 'ai-chat-readiness-place');
|
|
4249
|
+
open.dataset.commandInstanceLabel = String(place.where || place.label);
|
|
4250
|
+
open.setAttribute('aria-label', `${place.label}, ${EVIDENCE_ORIGIN[place.origin].tag}: opens the drawing`);
|
|
4251
|
+
open.dataset.tip = `Opens sheet ${place.sheet} with this area outlined`;
|
|
4252
|
+
open.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-place-sheet', textContent: String(place.sheet) }),
|
|
4253
|
+
Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-place-label', textContent: String(place.label) }),
|
|
4254
|
+
Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-place-origin', textContent: EVIDENCE_ORIGIN[place.origin].tag }));
|
|
4255
|
+
open.addEventListener('click', () => openReadinessEvidence(place, row, card, open));
|
|
4256
|
+
item.append(open);
|
|
4257
|
+
list.append(item);
|
|
4258
|
+
}
|
|
4259
|
+
for (const line of gaps) list.append(Object.assign(document.createElement('li'), { className: 'ai-chat-readiness-place-gap', textContent: line }));
|
|
4260
|
+
wrap.append(list);
|
|
4261
|
+
const more = [[Number(row.drawingEvidenceHeldBack) || 0, 'more place', 'on the drawings'], [Number(row.drawingEvidenceGapsHeldBack) || 0, 'more note', 'about places not shown']]
|
|
4262
|
+
.filter(([n]) => n > 0).map(([n, word, rest]) => `${readinessCount(n, word)} ${rest} not listed here.`);
|
|
4263
|
+
if (more.length) wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-asread', textContent: more.join(' ') }));
|
|
4264
|
+
return wrap;
|
|
4265
|
+
}
|
|
4266
|
+
|
|
4267
|
+
/** The crop of the page around a place: the area and some room around it, never smaller than a fifth of the page. */
|
|
4268
|
+
function evidenceCrop(place) {
|
|
4269
|
+
const [px0, py0, px1, py1] = place.pageBounds;
|
|
4270
|
+
const [rx0, ry0, rx1, ry1] = place.region;
|
|
4271
|
+
const grow = (lo, hi, min, max) => {
|
|
4272
|
+
const pad = Math.max((hi - lo) * 0.15, (max - min) * 0.01);
|
|
4273
|
+
let a = lo - pad, b = hi + pad;
|
|
4274
|
+
const least = (max - min) * 0.2;
|
|
4275
|
+
if (b - a < least) { const mid = (a + b) / 2; a = mid - least / 2; b = mid + least / 2; }
|
|
4276
|
+
if (a < min) { b += min - a; a = min; }
|
|
4277
|
+
if (b > max) { a -= b - max; b = max; }
|
|
4278
|
+
return [Math.max(min, a), Math.min(max, b)];
|
|
4279
|
+
};
|
|
4280
|
+
const [cx0, cx1] = grow(rx0, rx1, px0, px1);
|
|
4281
|
+
const [cy0, cy1] = grow(ry0, ry1, py0, py1);
|
|
4282
|
+
return { x0: cx0, y0: cy0, w: cx1 - cx0, h: cy1 - cy0, pageW: px1 - px0, pageH: py1 - py0, px0, py0 };
|
|
4283
|
+
}
|
|
4284
|
+
|
|
4285
|
+
/** The place's page in the cited-source viewer, cropped to the place, with the whole sheet a press away. */
|
|
4286
|
+
async function openReadinessEvidence(place, row, card, opener) {
|
|
4287
|
+
const title = String(place.title || place.label);
|
|
4288
|
+
const dialog = document.createElement('dialog'); dialog.className = 'ai-chat-source-viewer ai-chat-evidence-viewer';
|
|
4289
|
+
dialog.setAttribute('aria-label', title);
|
|
4290
|
+
const head = document.createElement('div'); head.className = 'ai-chat-source-viewer-head';
|
|
4291
|
+
const close = button('Close', 'shell.chat-readiness-evidence-close', 'ai-chat-source-viewer-close');
|
|
4292
|
+
let picture = null;
|
|
4293
|
+
let finished = false;
|
|
4294
|
+
const finish = () => {
|
|
4295
|
+
if (finished) return;
|
|
4296
|
+
finished = true;
|
|
4297
|
+
if (dialog.open) dialog.close();
|
|
4298
|
+
dialog.remove();
|
|
4299
|
+
if (picture) URL.revokeObjectURL(picture);
|
|
4300
|
+
if (opener?.isConnected) opener.focus({ preventScroll: true });
|
|
4301
|
+
};
|
|
4302
|
+
close.addEventListener('click', finish);
|
|
4303
|
+
dialog.addEventListener('keydown', (event) => { if (event.key === 'Escape') { event.preventDefault(); finish(); } });
|
|
4304
|
+
dialog.addEventListener('close', finish);
|
|
4305
|
+
head.append(Object.assign(document.createElement('strong'), { textContent: title }), close);
|
|
4306
|
+
const note = Object.assign(document.createElement('span'), { className: 'ai-chat-source-viewer-note', textContent: EVIDENCE_ORIGIN[place.origin].note(place) });
|
|
4307
|
+
const views = document.createElement('div'); views.className = 'ai-chat-evidence-views'; views.setAttribute('role', 'group'); views.setAttribute('aria-label', 'How much of the sheet to show');
|
|
4308
|
+
const area = button('This area', 'shell.chat-readiness-evidence-view', 'ai-chat-evidence-view');
|
|
4309
|
+
const whole = button('Whole sheet', 'shell.chat-readiness-evidence-view', 'ai-chat-evidence-view');
|
|
4310
|
+
area.dataset.commandInstanceLabel = 'this area'; whole.dataset.commandInstanceLabel = 'the whole sheet';
|
|
4311
|
+
views.append(area, whole);
|
|
4312
|
+
const body = document.createElement('div'); body.className = 'ai-chat-source-viewer-body';
|
|
4313
|
+
const status = Object.assign(document.createElement('p'), { className: 'ai-chat-source-viewer-status', textContent: 'Loading the drawing…' });
|
|
4314
|
+
status.setAttribute('role', 'status');
|
|
4315
|
+
const crop = evidenceCrop(place);
|
|
4316
|
+
const frame = document.createElement('div'); frame.className = 'ai-chat-evidence-frame';
|
|
4317
|
+
const show = (all) => {
|
|
4318
|
+
area.setAttribute('aria-pressed', String(!all)); whole.setAttribute('aria-pressed', String(all));
|
|
4319
|
+
frame.dataset.view = all ? 'sheet' : 'area';
|
|
4320
|
+
const c = all ? { x0: crop.px0, y0: crop.py0, w: crop.pageW, h: crop.pageH } : crop;
|
|
4321
|
+
// Shaped like the crop and never taller than most of the window: narrowed, not squashed, so the picture stays true.
|
|
4322
|
+
frame.style.aspectRatio = `${c.w} / ${c.h}`;
|
|
4323
|
+
frame.style.width = `min(100%, calc(62vh * ${c.w / c.h}))`;
|
|
4324
|
+
const image = frame.querySelector('img');
|
|
4325
|
+
if (image) Object.assign(image.style, { width: `${(crop.pageW / c.w) * 100}%`, left: `${(-(c.x0 - crop.px0) / c.w) * 100}%`, top: `${(-(c.y0 - crop.py0) / c.h) * 100}%` });
|
|
4326
|
+
};
|
|
4327
|
+
area.addEventListener('click', () => show(false));
|
|
4328
|
+
whole.addEventListener('click', () => show(true));
|
|
4329
|
+
show(false);
|
|
4330
|
+
body.append(status, frame);
|
|
4331
|
+
dialog.append(head, note, views, body);
|
|
4332
|
+
document.body.append(dialog);
|
|
4333
|
+
dialog.showModal();
|
|
4334
|
+
close.focus({ preventScroll: true });
|
|
4335
|
+
// A place that changed or is gone says so and offers the way on: the card asked for again, never sent for the person.
|
|
4336
|
+
const offerAgain = (why) => {
|
|
4337
|
+
if (finished) return;
|
|
4338
|
+
status.textContent = why;
|
|
4339
|
+
frame.remove(); views.remove();
|
|
4340
|
+
const again = button('Ask for the readiness card again', 'shell.chat-readiness-evidence-again', 'ai-chat-source-viewer-knowledge');
|
|
4341
|
+
again.dataset.tip = 'Puts the request in the message box. Nothing is sent until you press Send';
|
|
4342
|
+
again.addEventListener('click', () => {
|
|
4343
|
+
finish();
|
|
4344
|
+
addToMessageBox(`Show the readiness of connection ${row.jointId} again.`);
|
|
4345
|
+
ui.input.focus?.();
|
|
4346
|
+
});
|
|
4347
|
+
dialog.append(again);
|
|
4348
|
+
};
|
|
4349
|
+
try {
|
|
4350
|
+
const url = `/api/projects/${encodeURIComponent(card.projectId)}/connections/${encodeURIComponent(row.jointId)}/evidence/drawing?key=${encodeURIComponent(place.key)}&digest=${encodeURIComponent(place.digest)}`;
|
|
4351
|
+
const response = await fetch(url, { credentials: 'same-origin', cache: 'no-store' });
|
|
4352
|
+
if (finished) return;
|
|
4353
|
+
if (!response.ok) {
|
|
4354
|
+
const said = await response.json().catch(() => null);
|
|
4355
|
+
offerAgain(typeof said?.error === 'string' && said.error ? said.error : 'FloLess could not open this drawing just now. Try again in a moment.');
|
|
4356
|
+
return;
|
|
4357
|
+
}
|
|
4358
|
+
const bytes = await response.blob();
|
|
4359
|
+
if (finished) return;
|
|
4360
|
+
picture = URL.createObjectURL(bytes);
|
|
4361
|
+
const image = Object.assign(document.createElement('img'), { src: picture, alt: `${title}, page ${place.page}, with the area outlined` });
|
|
4362
|
+
frame.append(image);
|
|
4363
|
+
show(false);
|
|
4364
|
+
status.textContent = `${place.sheet} · page ${place.page}`;
|
|
4365
|
+
} catch (error) {
|
|
4366
|
+
console.error('[chat] a drawing place could not be opened', error);
|
|
4367
|
+
offerAgain('FloLess could not open this drawing just now. Try again in a moment.');
|
|
4368
|
+
}
|
|
4369
|
+
}
|
|
4370
|
+
|
|
4371
|
+
/*
|
|
4372
|
+
* The feed is rebuilt on every streamed word and every 5 s poll (#2163). An action's card never changes once it is
|
|
4373
|
+
* recorded, so the node painted for an event is handed back as long as the event is the same one: the person's place
|
|
4374
|
+
* in the card's own scroll area and a focused button survive the rebuild. Bounded, oldest first.
|
|
4375
|
+
*/
|
|
4376
|
+
const readinessNodes = new Map();
|
|
4377
|
+
function renderReadinessCard(event) {
|
|
4378
|
+
const kept = readinessNodes.get(event.eventId);
|
|
4379
|
+
if (kept && kept.sequence === event.sequence) return kept.node;
|
|
4380
|
+
const node = paintReadinessCard(event);
|
|
4381
|
+
readinessNodes.delete(event.eventId);
|
|
4382
|
+
readinessNodes.set(event.eventId, { sequence: event.sequence, node });
|
|
4383
|
+
while (readinessNodes.size > 40) readinessNodes.delete(readinessNodes.keys().next().value);
|
|
4384
|
+
return node;
|
|
4385
|
+
}
|
|
4386
|
+
|
|
4387
|
+
function paintReadinessCard(event) {
|
|
4388
|
+
const card = event.payload.card;
|
|
4389
|
+
const rows = Array.isArray(card.rows) ? card.rows : [];
|
|
4390
|
+
const node = document.createElement('section');
|
|
4391
|
+
node.className = 'ai-chat-filter-card ai-chat-action-card ai-chat-readiness-card';
|
|
4392
|
+
node.dataset.eventId = event.eventId;
|
|
4393
|
+
node.dataset.eventSequence = String(event.sequence);
|
|
4394
|
+
node.setAttribute('role', 'group');
|
|
4395
|
+
node.setAttribute('aria-label', 'Connection readiness');
|
|
4396
|
+
const sum = (key) => rows.reduce((total, row) => total + (Number(row.summary?.[key]) || 0), 0);
|
|
4397
|
+
const head = document.createElement('div'); head.className = 'ai-chat-filter-card-head';
|
|
4398
|
+
// The counts are of the connections shown, and say so: with some held back they are not the project's totals.
|
|
4399
|
+
head.append(Object.assign(document.createElement('strong'), { textContent: 'Connection readiness' }),
|
|
4400
|
+
Object.assign(document.createElement('span'), { className: 'ai-chat-filter-state',
|
|
4401
|
+
textContent: `${rows.length} of ${readinessCount(card.total ?? rows.length, 'connection')} shown · in these: ${sum('outside')} outside a limit · ${sum('unmeasured')} not measured · ${readinessCount(sum('issues'), 'build issue')} · ${readinessCount(sum('openRfis'), 'open RFI')}${sum('onAssumption') ? ` · ${sum('onAssumption')} on an assumption` : ''}` }));
|
|
4402
|
+
const limits = Object.assign(document.createElement('p'), { className: 'ai-chat-readiness-limits',
|
|
4403
|
+
textContent: 'These are the checks FloLess measured. They do not certify a connection for fabrication.' });
|
|
4404
|
+
const body = document.createElement('div'); body.className = 'ai-chat-readiness-body'; body.tabIndex = 0;
|
|
4405
|
+
body.setAttribute('aria-label', 'Connections and their checks');
|
|
4406
|
+
for (const row of rows) body.append(readinessRow(row, card));
|
|
4407
|
+
node.append(head, limits, body);
|
|
4408
|
+
const notes = [];
|
|
4409
|
+
// The card names at most a few of each; the rest are counted, never dropped.
|
|
4410
|
+
const andMore = (list, more) => `${list.join(', ')}${more ? `, and ${more} more` : ''}`;
|
|
4411
|
+
const missing = Array.isArray(card.notFound?.jointIds) ? card.notFound.jointIds : [];
|
|
4412
|
+
const missingCount = missing.length + (Number(card.notFound?.jointIdsHeldBack) || 0);
|
|
4413
|
+
if (missing.length) notes.push(`${missingCount === 1 ? 'This connection is' : 'These connections are'} not in the model, so nothing is said about ${missingCount === 1 ? 'it' : 'them'}: ${andMore(missing, Number(card.notFound.jointIdsHeldBack) || 0)}.`);
|
|
4414
|
+
const otherKind = Array.isArray(card.notFound?.otherKind) ? card.notFound.otherKind : [];
|
|
4415
|
+
if (otherKind.length) notes.push(`Not of the kind "${card.notFound.askedKind || ''}" you asked about, so not shown: ${andMore(otherKind.map((row) => `${row.jointId} (${row.kind})`), Number(card.notFound.otherKindHeldBack) || 0)}.`);
|
|
4416
|
+
if (card.notFound?.kind) notes.push(`The model has no connections of the kind "${card.notFound.kind}", so nothing is said about that kind.`);
|
|
4417
|
+
if (card.reviewUnavailable) notes.push(card.reviewUnavailable);
|
|
4418
|
+
if (card.assumptionsUnavailable) notes.push(card.assumptionsUnavailable);
|
|
4419
|
+
if (card.drawingEvidenceUnavailable) notes.push(card.drawingEvidenceUnavailable);
|
|
4420
|
+
if (card.rfisUnavailable) notes.push(card.rfisUnavailable);
|
|
4421
|
+
if (card.heldBack?.rows) notes.push(`${card.heldBack.rows} more connections are not shown${card.heldBack.needingAttention ? `, and ${card.heldBack.needingAttention} of them need attention` : ''}. Ask about one kind or one connection to see them.`);
|
|
4422
|
+
for (const line of Array.isArray(card.unattached) ? card.unattached : []) notes.push(String(line));
|
|
4423
|
+
if (card.unattachedHeldBack) notes.push(`${readinessCount(card.unattachedHeldBack, 'more build failure')} that name no connection are not listed here.`);
|
|
4424
|
+
if (notes.length) node.append(readinessList('Also', notes));
|
|
4425
|
+
const foot = document.createElement('div'); foot.className = 'ai-chat-readiness-foot';
|
|
4426
|
+
foot.append(Object.assign(document.createElement('span'), { textContent: 'The AI does not mark this checked. Sign-off is yours.' }));
|
|
4427
|
+
node.append(foot);
|
|
4428
|
+
return node;
|
|
4429
|
+
}
|
|
4430
|
+
|
|
4431
|
+
function readinessRow(row, card) {
|
|
4432
|
+
const wrap = document.createElement('div'); wrap.className = 'ai-chat-readiness-row';
|
|
4433
|
+
wrap.dataset.jointId = String(row.jointId || '');
|
|
4434
|
+
const title = document.createElement('div'); title.className = 'ai-chat-readiness-title';
|
|
4435
|
+
title.append(Object.assign(document.createElement('strong'), { textContent: `${row.kindLabel || row.kind} · ${row.place}` }),
|
|
4436
|
+
Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-id', textContent: String(row.jointId || '') }));
|
|
4437
|
+
wrap.append(title);
|
|
4438
|
+
// One line per connection a detailer can scan down: what holds it back, in counts, worst first. Never "ready":
|
|
4439
|
+
// with nothing counted it says only that nothing measured is outside a limit.
|
|
4440
|
+
const s = row.summary || {};
|
|
4441
|
+
const holding = [[s.outside, 'outside a limit'], [s.issues, 'build issue'], [s.unmeasured, 'not measured'], [s.openRfis, 'open RFI'], [s.onAssumption, 'on an assumption']]
|
|
4442
|
+
.filter(([n]) => Number(n) > 0).map(([n, word]) => word === 'outside a limit' || word === 'not measured' || word === 'on an assumption' ? `${n} ${word}` : readinessCount(Number(n), word));
|
|
4443
|
+
wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-status',
|
|
4444
|
+
textContent: holding.length ? holding.join(' · ') : 'Nothing measured is outside a limit' }));
|
|
4445
|
+
const facts = Array.isArray(row.facts) ? row.facts : [];
|
|
4446
|
+
const assumptions = Array.isArray(row.assumptions) ? row.assumptions : [];
|
|
4447
|
+
if (facts.length) {
|
|
4448
|
+
const scroll = document.createElement('div'); scroll.className = 'ai-chat-readiness-table';
|
|
4449
|
+
const table = document.createElement('table');
|
|
4450
|
+
const headRow = document.createElement('tr');
|
|
4451
|
+
for (const label of ['Check', 'Measured', 'Limit', 'Result']) headRow.append(Object.assign(document.createElement('th'), { textContent: label, scope: 'col' }));
|
|
4452
|
+
const thead = document.createElement('thead');
|
|
4453
|
+
const tbody = document.createElement('tbody');
|
|
4454
|
+
thead.append(headRow);
|
|
4455
|
+
table.append(thead, tbody);
|
|
4456
|
+
const labels = readinessLabels(facts);
|
|
4457
|
+
for (const [index, fact] of facts.entries()) {
|
|
4458
|
+
const tr = document.createElement('tr');
|
|
4459
|
+
if (fact.verdict !== 'within') tr.className = `is-${fact.verdict}`;
|
|
4460
|
+
const result = Object.assign(document.createElement('td'), { textContent: readinessResult(fact) });
|
|
4461
|
+
// #2449: a check resting on a holding assumption keeps its result; the tag says only what it rests on.
|
|
4462
|
+
const on = fact.assumptionId ? assumptions.find((a) => a.id === fact.assumptionId) : null;
|
|
4463
|
+
if (on) result.append(' ', readinessAssumedTag(on));
|
|
4464
|
+
// #2450: a check that already has an RFI says which, so the card and the RFI stay linked.
|
|
4465
|
+
const filed = (Array.isArray(row.checkRfis) ? row.checkRfis : []).find((c) => c.checkId === fact.id);
|
|
4466
|
+
if (filed) result.append(' ', Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-rfi', textContent: `${filed.rfiId} · ${filed.status}` }));
|
|
4467
|
+
tr.append(Object.assign(document.createElement('td'), { textContent: labels[index] }),
|
|
4468
|
+
Object.assign(document.createElement('td'), { textContent: readinessMm(fact.actualMm) }),
|
|
4469
|
+
Object.assign(document.createElement('td'), { textContent: readinessLimit(fact) }),
|
|
4470
|
+
result);
|
|
4471
|
+
tbody.append(tr);
|
|
4472
|
+
}
|
|
4473
|
+
scroll.append(table);
|
|
4474
|
+
wrap.append(scroll);
|
|
4475
|
+
if (row.factsHeldBack) wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-sub', textContent: `${readinessCount(row.factsHeldBack, 'more check')} not shown here.` }));
|
|
4476
|
+
}
|
|
4477
|
+
const assumed = readinessAssumptions(row, card, assumptions);
|
|
4478
|
+
if (assumed) wrap.append(assumed);
|
|
4479
|
+
for (const part of [
|
|
4480
|
+
readinessAssumedList('Not measured', (row.unmeasured || []).map((line) => [String(line), readinessHolding(assumptions, 'unmeasured', String(line))])),
|
|
4481
|
+
readinessAssumedList('Build issues', (row.issues || []).map((issue) => [String(issue.text), issue.assumptionId ? assumptions.find((a) => a.id === issue.assumptionId) : null])),
|
|
4482
|
+
readinessList('RFIs on this connection', (row.rfis || []).map((rfi) => `${rfi.rfiId} · ${rfi.status} · ${rfi.question}`)),
|
|
4483
|
+
readinessList('RFIs on its members', (row.relatedRfis || []).map((rfi) => `${rfi.rfiId} · ${rfi.status} · ${rfi.question}`)),
|
|
4484
|
+
readinessList('Drawing references for these members', (row.drawingReferences || []).map((ref) => `${ref.member}, end ${Number(ref.end) + 1}: detail ${ref.detail}`)),
|
|
4485
|
+
card.projectId ? readinessEvidence(row, card) : null,
|
|
4486
|
+
]) if (part) wrap.append(part);
|
|
4487
|
+
if (row.itemsHeldBack) wrap.append(Object.assign(document.createElement('span'), { className: 'ai-chat-readiness-sub', textContent: `${readinessCount(row.itemsHeldBack, 'more item')} about this connection not shown here. Ask about it alone to see them.` }));
|
|
4488
|
+
wrap.append(Object.assign(document.createElement('p'), { className: 'ai-chat-readiness-review', textContent: READINESS_REVIEW[row.review] || READINESS_REVIEW['not-available'] }));
|
|
4489
|
+
const attention = (row.summary?.outside || 0) + (row.summary?.unmeasured || 0) + (row.summary?.issues || 0);
|
|
4490
|
+
const actions = document.createElement('div'); actions.className = 'ai-chat-readiness-actions';
|
|
4491
|
+
// What holds this connection back, in the card's own words: failing checks, then build issues, then what was not measured.
|
|
4492
|
+
const failing = [
|
|
4493
|
+
...facts.filter((fact) => fact.verdict !== 'within').map((fact) => `${fact.label} (${fact.id}) measured ${readinessMm(fact.actualMm)} against ${readinessMm(fact.limitMm)}`),
|
|
4494
|
+
...(row.issues || []).map((issue) => String(issue.text)),
|
|
4495
|
+
...(row.unmeasured || []).map(String),
|
|
4496
|
+
];
|
|
4497
|
+
const about = `${row.kindLabel || row.kind} ${row.jointId} at ${row.place}`;
|
|
4498
|
+
if (card.projectId) {
|
|
4499
|
+
const open = button('Open in the model', 'shell.chat-readiness-open-model', 'ai-chat-source-action');
|
|
4500
|
+
open.dataset.commandInstanceLabel = about;
|
|
4501
|
+
open.setAttribute('aria-label', `Open in the model: ${about}`);
|
|
4502
|
+
open.dataset.tip = 'Shows this connection in the model, selected and framed';
|
|
4503
|
+
open.addEventListener('click', async () => {
|
|
4504
|
+
// The line here says what happened, never more than the editor did: it waits for the editor's own
|
|
4505
|
+
// outcome. A refusal carries the editor's sentence; success and the fallback stay short.
|
|
4506
|
+
const unreachable = 'FloLess could not open the model from here. Open the project from Workspaces, then try again.';
|
|
4507
|
+
let said;
|
|
4508
|
+
try {
|
|
4509
|
+
const outcome = await openConnectionInModel(card.projectId, String(row.jointId || ''));
|
|
4510
|
+
if (outcome?.superseded) return; // a later click reports for itself
|
|
4511
|
+
said = !outcome ? unreachable
|
|
4512
|
+
: outcome.ok !== true ? (outcome.said || `Connection ${row.jointId} was not shown. Open the Model step, then press Open in the model again.`)
|
|
4513
|
+
: outcome.fallback === 'main-member' ? `FloLess could not build connection ${row.jointId}, so its main member is selected in the model instead.`
|
|
4514
|
+
: `Showing connection ${row.jointId} in the model.`;
|
|
4515
|
+
} catch (error) {
|
|
4516
|
+
// Only a sentence written for the person is shown as is; anything else gets the plain fallback,
|
|
4517
|
+
// and its cause goes to the console for a bug report.
|
|
4518
|
+
if (error?.plain !== true) console.error('[chat] Open in the model failed', error);
|
|
4519
|
+
said = error?.plain === true && error.message ? error.message : unreachable;
|
|
4520
|
+
}
|
|
4521
|
+
announce(said);
|
|
4522
|
+
});
|
|
4523
|
+
actions.append(open);
|
|
4524
|
+
}
|
|
4525
|
+
// What the model raises a question about, the way the server's question list counts it: a check outside
|
|
4526
|
+
// its limit or not measured, a build error, a connection that could not be built. A warning, and the
|
|
4527
|
+
// plain note that nothing was measured, are shown on the card but are not questions — offering
|
|
4528
|
+
// "Raise an RFI" for them would open a dialog with nothing to file.
|
|
4529
|
+
const raisableIssues = (row.issues || []).filter((issue) => issue.severity !== 'warning');
|
|
4530
|
+
const raisable = facts.some((fact) => fact.verdict !== 'within') || raisableIssues.length > 0
|
|
4531
|
+
|| (row.unmeasured || []).some((line) => String(line) !== READINESS_NOTHING_MEASURED);
|
|
4532
|
+
if (raisable) {
|
|
4533
|
+
// #2450: the editor shows the connection and its questions as FloLess wrote them; the person files one there.
|
|
4534
|
+
const rfi = button('Raise an RFI', 'shell.chat-readiness-ask-rfi', 'ai-chat-source-action');
|
|
4535
|
+
rfi.dataset.commandInstanceLabel = about;
|
|
4536
|
+
rfi.setAttribute('aria-label', `Raise an RFI: ${about}`);
|
|
4537
|
+
rfi.dataset.tip = 'Opens this connection in the model so you can review the question and file the RFI yourself';
|
|
4538
|
+
const firstCheck = facts.find((fact) => fact.verdict !== 'within')?.id || raisableIssues[0]?.code || '';
|
|
4539
|
+
rfi.addEventListener('click', async () => {
|
|
4540
|
+
const unreachable = 'FloLess could not open the model from here. Open the project from Workspaces, then try again.';
|
|
4541
|
+
let said;
|
|
4542
|
+
try {
|
|
4543
|
+
const outcome = await openConnectionInModel(card.projectId, String(row.jointId || ''), { raiseRfi: true, ...(firstCheck ? { checkId: firstCheck } : {}) });
|
|
4544
|
+
if (outcome?.superseded) return; // a later click reports for itself
|
|
4545
|
+
// Said only when the editor really opened the questions; otherwise its own reason, or the plain fallback.
|
|
4546
|
+
said = !outcome ? unreachable
|
|
4547
|
+
: outcome.raised === true ? `The questions for connection ${row.jointId} are open in the model. Review one there and file it.`
|
|
4548
|
+
: outcome.raiseSaid || outcome.said || `The questions for connection ${row.jointId} could not be opened in the model. Open the Model step, then press Raise an RFI again.`;
|
|
4549
|
+
} catch (error) {
|
|
4550
|
+
if (error?.plain !== true) console.error('[chat] Raise an RFI failed', error);
|
|
4551
|
+
said = error?.plain === true && error.message ? error.message : unreachable;
|
|
4552
|
+
}
|
|
4553
|
+
announce(said);
|
|
4554
|
+
});
|
|
4555
|
+
const assume = button('Ask the AI to propose an assumption', 'shell.chat-readiness-assume', 'ai-chat-source-action');
|
|
4556
|
+
assume.dataset.commandInstanceLabel = about;
|
|
4557
|
+
assume.setAttribute('aria-label', `Ask the AI to propose an assumption: ${about}`);
|
|
4558
|
+
assume.dataset.tip = 'Puts a request in the message box. Nothing is sent until you press Send. The AI then shows the assumption on a card, and only your Confirm records it';
|
|
4559
|
+
assume.addEventListener('click', () => addToMessageBox(`For ${about}: propose an assumption I can go on with for ${failing.length ? failing.join('; ') : 'what FloLess could not check'}, on a card for me to confirm. Name each check exactly as the readiness card does.`));
|
|
4560
|
+
actions.append(rfi, assume);
|
|
4561
|
+
}
|
|
4562
|
+
if (READINESS_SIGNABLE.has(row.review) && card.projectId) {
|
|
4563
|
+
const sign = button('Open to sign off', 'shell.chat-readiness-sign-off', 'ai-chat-source-action');
|
|
4564
|
+
sign.dataset.commandInstanceLabel = about;
|
|
4565
|
+
sign.setAttribute('aria-label', `Open to sign off: ${about}`);
|
|
4566
|
+
sign.dataset.tip = 'Opens the project, where you sign off an imported connection yourself. The AI cannot';
|
|
4567
|
+
sign.addEventListener('click', async () => {
|
|
4568
|
+
let opened = false;
|
|
4569
|
+
try { opened = await openActionScreen({ view: 'project', projectId: card.projectId }); } catch { opened = false; }
|
|
4570
|
+
announce(opened ? `Sign off connection ${row.jointId} in the model's connections.` : 'FloLess could not open the project from here. Open it from Workspaces.');
|
|
4571
|
+
});
|
|
4572
|
+
actions.append(sign);
|
|
4573
|
+
}
|
|
4574
|
+
if (actions.childElementCount) wrap.append(actions);
|
|
4575
|
+
return wrap;
|
|
4576
|
+
}
|
|
4577
|
+
|
|
3288
4578
|
/** One line per action the AI ran itself from this conversation: what it was, and how it ended. */
|
|
3289
4579
|
function renderActionRow(event) {
|
|
3290
4580
|
const payload = event.payload || {};
|
|
3291
4581
|
if (payload.outcome === 'ok' && payload.card?.kind === 'page' && payload.card.home && payload.card.pageId) return renderPageCard(event);
|
|
4582
|
+
if (payload.outcome === 'ok' && payload.card?.kind === 'connection-readiness') return renderReadinessCard(event);
|
|
3292
4583
|
const row = document.createElement('div');
|
|
3293
4584
|
const outcome = payload.outcome === 'ok' ? 'ok' : payload.outcome === 'cancelled' ? 'stopped' : 'failed';
|
|
3294
4585
|
row.className = `ai-chat-action-row is-${outcome}`;
|
|
@@ -3300,7 +4591,8 @@
|
|
|
3300
4591
|
glyph.textContent = outcome === 'ok' ? '✓' : outcome === 'stopped' ? '■' : '!';
|
|
3301
4592
|
const verb = document.createElement('span');
|
|
3302
4593
|
verb.className = 'ai-chat-action-row-verb';
|
|
3303
|
-
|
|
4594
|
+
// "Changed" only when the change happened (#2326): a write that ended not done or stopped changed nothing.
|
|
4595
|
+
verb.textContent = payload.risk === 'read' ? 'Read' : outcome === 'ok' ? 'Changed' : 'Tried';
|
|
3304
4596
|
const title = document.createElement('span');
|
|
3305
4597
|
title.className = 'ai-chat-action-row-title';
|
|
3306
4598
|
title.textContent = String(payload.title || payload.actionId || 'A FloLess action');
|
|
@@ -3401,6 +4693,728 @@
|
|
|
3401
4693
|
return item;
|
|
3402
4694
|
}
|
|
3403
4695
|
|
|
4696
|
+
/*
|
|
4697
|
+
* #2399 PR C2 — THE ASSISTANT'S CARDS in a project, workflow or workspace chat (`next-move` events with
|
|
4698
|
+
* `payload.assistant`; the Guide's own cards stay in web/guide.js). The server owns everything a card is: its class
|
|
4699
|
+
* (blocking / resume / idea, with FloLess's own `fact` line), whose it is, and what a click does. The browser draws it,
|
|
4700
|
+
* names its buttons, and sends only the card id. A card is hidden until the server says how it stands now
|
|
4701
|
+
* (`/api/assistant/cards/state`), so a reload never shows a card already used or set aside as new, and never shows
|
|
4702
|
+
* another account's card. Nothing here sends a message: a follow-up only goes into the message box.
|
|
4703
|
+
*/
|
|
4704
|
+
const assistantCardEntries = new Map();
|
|
4705
|
+
const ASSISTANT_CARDS_KEPT = 300;
|
|
4706
|
+
const ASSISTANT_FALLBACK_ERROR = 'FloLess couldn’t do that just now. Try again in a moment.';
|
|
4707
|
+
// A click whose refusal means the card can't be used any more: the card folds to a dimmed line that says why.
|
|
4708
|
+
const ASSISTANT_GONE_CODES = new Set(['assistant-card-target-changed', 'assistant-card-action-gone', 'assistant-card-action-changed',
|
|
4709
|
+
'assistant-card-project-changed', 'assistant-card-chat-gone', 'assistant-card-missing', 'assistant-card-not-shown', 'assistant-card-scope',
|
|
4710
|
+
'assistant-card-policy', 'assistant-card-input', 'assistant-quiet', 'assistant-card-instructor']);
|
|
4711
|
+
const assistantStateWanted = new Set();
|
|
4712
|
+
let assistantStateTimer = null;
|
|
4713
|
+
// Bumped when every drawn card is asked again (another account may have signed in): an answer to an older ask is dropped.
|
|
4714
|
+
let assistantStateGeneration = 0;
|
|
4715
|
+
// The one card showing "FloLess had to reset your suggestion settings" (shown once, until the person chooses).
|
|
4716
|
+
let assistantRecoveredCard = '';
|
|
4717
|
+
|
|
4718
|
+
function assistantNode(tag, className, text) {
|
|
4719
|
+
const node = document.createElement(tag);
|
|
4720
|
+
if (className) node.className = className;
|
|
4721
|
+
if (text !== undefined) node.textContent = text;
|
|
4722
|
+
return node;
|
|
4723
|
+
}
|
|
4724
|
+
|
|
4725
|
+
/** "check-connections" → "Check connections". */
|
|
4726
|
+
function assistantPatternLabel(pattern) {
|
|
4727
|
+
const words = String(pattern || '').split('-').filter(Boolean).join(' ');
|
|
4728
|
+
return words ? words.charAt(0).toUpperCase() + words.slice(1) : 'a follow-up';
|
|
4729
|
+
}
|
|
4730
|
+
|
|
4731
|
+
/** What a card says and what its main button is called, by kind (and an action's risk). Never an action's input. */
|
|
4732
|
+
function assistantCardText(move) {
|
|
4733
|
+
const guideText = window.flolessGuide?.moveText?.(move);
|
|
4734
|
+
switch (move?.kind) {
|
|
4735
|
+
case 'action': {
|
|
4736
|
+
const title = String(move.title || 'A FloLess action');
|
|
4737
|
+
if (move.risk === 'read') return { title, action: 'Show it', note: 'Reads only. Nothing changes.' };
|
|
4738
|
+
if (move.risk === 'human-only') return { title, action: 'Open…', note: 'Only you can do this.' };
|
|
4739
|
+
return { title, action: 'Review…', note: 'Opens a request for your OK below. Nothing runs yet.' };
|
|
4740
|
+
}
|
|
4741
|
+
case 'follow-up':
|
|
4742
|
+
return { title: `Ask next: ${assistantPatternLabel(move.pattern)}`, action: 'Put in message box',
|
|
4743
|
+
note: 'Nothing is sent until you press Send. It goes with this chat’s Access when you do.' };
|
|
4744
|
+
case 'create-workflow':
|
|
4745
|
+
return { title: guideText?.title || `Build a workflow: ${move.name || ''}`, action: 'Build it', detail: move.purpose,
|
|
4746
|
+
note: 'Opens New workflow with its name filled in. Nothing is built until you confirm there.' };
|
|
4747
|
+
default:
|
|
4748
|
+
return guideText ? { ...guideText, note: 'Nothing happens until you confirm in the next step.' } : null;
|
|
4749
|
+
}
|
|
4750
|
+
}
|
|
4751
|
+
|
|
4752
|
+
/** What the message box should do with a follow-up's prompt: fill an empty box, leave one that has it, or ask. */
|
|
4753
|
+
function followUpComposeAction(current, prompt) {
|
|
4754
|
+
const held = String(current || '');
|
|
4755
|
+
if (!held.trim()) return 'fill';
|
|
4756
|
+
if (held.includes(prompt)) return 'focus';
|
|
4757
|
+
return 'choose';
|
|
4758
|
+
}
|
|
4759
|
+
|
|
4760
|
+
/** Put text in the message box as the person's own draft, and give them the box with the caret at its end. Never sends. */
|
|
4761
|
+
function putInMessageBox(text) {
|
|
4762
|
+
ui.input.value = text;
|
|
4763
|
+
autosize();
|
|
4764
|
+
saveDraftSoon();
|
|
4765
|
+
updateSendState();
|
|
4766
|
+
ui.input.focus({ preventScroll: true });
|
|
4767
|
+
const end = ui.input.value.length;
|
|
4768
|
+
try { ui.input.setSelectionRange(end, end); } catch { /* a box that takes no selection still has the text */ }
|
|
4769
|
+
}
|
|
4770
|
+
|
|
4771
|
+
function assistantEntry(event) {
|
|
4772
|
+
const payload = event.payload || {};
|
|
4773
|
+
const cardId = String(payload.cardId || event.eventId || '');
|
|
4774
|
+
let entry = assistantCardEntries.get(cardId);
|
|
4775
|
+
if (!entry) {
|
|
4776
|
+
entry = { cardId, event, node: null, signature: '', server: null, busy: '', error: '', fold: null, result: null, compose: null, recovered: false, focus: '' };
|
|
4777
|
+
assistantCardEntries.set(cardId, entry);
|
|
4778
|
+
while (assistantCardEntries.size > ASSISTANT_CARDS_KEPT) {
|
|
4779
|
+
const oldest = assistantCardEntries.keys().next().value;
|
|
4780
|
+
const gone = assistantCardEntries.get(oldest);
|
|
4781
|
+
assistantCardEntries.delete(oldest);
|
|
4782
|
+
// A forgotten card is no longer asked again when the account changes, so nothing it showed may stay up:
|
|
4783
|
+
// its node is emptied and hidden. Drawing the conversation again draws it afresh, checked like a new one.
|
|
4784
|
+
if (gone?.node) { gone.node.replaceChildren(); gone.node.hidden = true; }
|
|
4785
|
+
}
|
|
4786
|
+
}
|
|
4787
|
+
entry.event = event;
|
|
4788
|
+
return entry;
|
|
4789
|
+
}
|
|
4790
|
+
|
|
4791
|
+
/** Ask the server how cards stand, a few at a time (every card drawn in one repaint goes in one request). */
|
|
4792
|
+
function wantAssistantState(cardId) {
|
|
4793
|
+
assistantStateWanted.add(cardId);
|
|
4794
|
+
if (assistantStateTimer) return;
|
|
4795
|
+
assistantStateTimer = setTimeout(() => { assistantStateTimer = null; void readAssistantStates(); }, 0);
|
|
4796
|
+
}
|
|
4797
|
+
|
|
4798
|
+
async function readAssistantStates() {
|
|
4799
|
+
const ids = [...assistantStateWanted].slice(0, 100);
|
|
4800
|
+
for (const id of ids) assistantStateWanted.delete(id);
|
|
4801
|
+
if (!ids.length) return;
|
|
4802
|
+
const generation = assistantStateGeneration;
|
|
4803
|
+
try {
|
|
4804
|
+
const body = await request('/api/assistant/cards/state', { method: 'POST', body: JSON.stringify({ cardIds: ids }) });
|
|
4805
|
+
// Asked again meanwhile: this answer may be for the account before, and the newer ask covers these cards.
|
|
4806
|
+
if (generation !== assistantStateGeneration) return;
|
|
4807
|
+
const answered = new Set();
|
|
4808
|
+
for (const row of Array.isArray(body?.cards) ? body.cards : []) {
|
|
4809
|
+
const entry = assistantCardEntries.get(row?.cardId);
|
|
4810
|
+
if (!entry) continue;
|
|
4811
|
+
answered.add(row.cardId);
|
|
4812
|
+
entry.server = row;
|
|
4813
|
+
entry.stateError = '';
|
|
4814
|
+
if (row.state === 'used' && row.outcome === 'read' && row.result) entry.result = row.result;
|
|
4815
|
+
repaintAssistantCard(entry);
|
|
4816
|
+
}
|
|
4817
|
+
// An id the server did not answer (not a card id) is a card FloLess does not have.
|
|
4818
|
+
for (const id of ids) {
|
|
4819
|
+
const entry = assistantCardEntries.get(id);
|
|
4820
|
+
if (entry && !answered.has(id)) { entry.server = { cardId: id, state: 'missing' }; repaintAssistantCard(entry); }
|
|
4821
|
+
}
|
|
4822
|
+
} catch (error) {
|
|
4823
|
+
if (generation !== assistantStateGeneration) return;
|
|
4824
|
+
// Not known yet. The card is never drawn hidden for good: the AI has said a card is shown, so the person sees that
|
|
4825
|
+
// FloLess couldn't check it, with Retry — and nothing of the card itself (it may belong to another account).
|
|
4826
|
+
console.warn('[assistant] could not read how the suggestion cards stand:', error);
|
|
4827
|
+
for (const id of ids) {
|
|
4828
|
+
const entry = assistantCardEntries.get(id);
|
|
4829
|
+
if (!entry) continue;
|
|
4830
|
+
// A card already drawn is forgotten too: what it showed may have been for the account before.
|
|
4831
|
+
entry.server = null;
|
|
4832
|
+
entry.result = null;
|
|
4833
|
+
entry.stateError = 'FloLess couldn’t check this suggestion just now.';
|
|
4834
|
+
repaintAssistantCard(entry);
|
|
4835
|
+
}
|
|
4836
|
+
}
|
|
4837
|
+
if (assistantStateWanted.size) wantAssistantState([...assistantStateWanted][0]);
|
|
4838
|
+
}
|
|
4839
|
+
|
|
4840
|
+
/** Every card drawn on this page, asked about again (the account or the window may have changed meanwhile). */
|
|
4841
|
+
function rereadAssistantStates() {
|
|
4842
|
+
assistantStateGeneration++;
|
|
4843
|
+
for (const entry of assistantCardEntries.values()) { entry.stateError = ''; wantAssistantState(entry.cardId); }
|
|
4844
|
+
}
|
|
4845
|
+
|
|
4846
|
+
function renderAssistantCard(event) {
|
|
4847
|
+
const entry = assistantEntry(event);
|
|
4848
|
+
// A failed check waits for Retry (or the window coming back) rather than asking again on every repaint.
|
|
4849
|
+
if (!entry.server && !entry.stateError) wantAssistantState(entry.cardId);
|
|
4850
|
+
const signature = JSON.stringify([entry.server, entry.stateError || '', entry.busy, entry.error, entry.fold, entry.result, entry.compose, entry.recovered,
|
|
4851
|
+
entry.cardId === assistantRecoveredCard]);
|
|
4852
|
+
if (entry.node && entry.signature === signature) return entry.node;
|
|
4853
|
+
entry.node = paintAssistantCard(entry);
|
|
4854
|
+
entry.signature = signature;
|
|
4855
|
+
return entry.node;
|
|
4856
|
+
}
|
|
4857
|
+
|
|
4858
|
+
function repaintAssistantCard(entry) {
|
|
4859
|
+
const old = entry.node;
|
|
4860
|
+
const hadFocus = Boolean(old && old.contains(document.activeElement));
|
|
4861
|
+
const focusId = entry.focus || (hadFocus ? document.activeElement?.dataset?.commandId : '');
|
|
4862
|
+
entry.signature = '';
|
|
4863
|
+
const next = renderAssistantCard(entry.event);
|
|
4864
|
+
if (old && old !== next && old.isConnected) old.replaceWith(next);
|
|
4865
|
+
if (focusId === 'status') { entry.focus = ''; focusAssistantStatus(entry); return; }
|
|
4866
|
+
if (focusId || hadFocus) {
|
|
4867
|
+
const target = (focusId && [...next.querySelectorAll('button')].find((b) => b.dataset.commandId === focusId && !b.disabled))
|
|
4868
|
+
|| next.querySelector('button:not([disabled])') || next.querySelector('[role="status"]');
|
|
4869
|
+
target?.focus({ preventScroll: true });
|
|
4870
|
+
}
|
|
4871
|
+
entry.focus = '';
|
|
4872
|
+
}
|
|
4873
|
+
|
|
4874
|
+
/** A button of this card. Its Instructor instance is the card's title. */
|
|
4875
|
+
function assistantButton(label, commandId, title, className = '') {
|
|
4876
|
+
const control = button(label, commandId, className);
|
|
4877
|
+
control.dataset.commandInstanceLabel = title;
|
|
4878
|
+
return control;
|
|
4879
|
+
}
|
|
4880
|
+
|
|
4881
|
+
function paintAssistantCard(entry) {
|
|
4882
|
+
const payload = entry.event.payload || {};
|
|
4883
|
+
const move = payload.move || {};
|
|
4884
|
+
const text = assistantCardText(move) || { title: 'A suggestion', action: 'Open', note: '' };
|
|
4885
|
+
const card = assistantNode('section', 'ai-chat-filter-card ai-chat-action-card assistant-card');
|
|
4886
|
+
card.dataset.eventId = entry.event.eventId;
|
|
4887
|
+
card.dataset.cardId = entry.cardId;
|
|
4888
|
+
card.setAttribute('role', 'group');
|
|
4889
|
+
const titleId = `assistant-card-title-${entry.cardId}`;
|
|
4890
|
+
card.setAttribute('aria-labelledby', titleId);
|
|
4891
|
+
const server = entry.server;
|
|
4892
|
+
// Not known yet: drawn hidden, so another account's card or one already used never flashes up as new.
|
|
4893
|
+
if (!server && entry.stateError) {
|
|
4894
|
+
// The check failed: say so where the card would be, with Retry, and show nothing of the card itself.
|
|
4895
|
+
card.classList.add('is-collapsed');
|
|
4896
|
+
const line = assistantNode('p', 'ai-chat-action-line', entry.stateError);
|
|
4897
|
+
const retry = button('Retry', 'shell.assistant-card-retry');
|
|
4898
|
+
retry.dataset.commandInstanceLabel = 'this suggestion';
|
|
4899
|
+
retry.dataset.tip = 'Checks this suggestion again.';
|
|
4900
|
+
retry.addEventListener('click', () => { entry.stateError = ''; repaintAssistantCard(entry); });
|
|
4901
|
+
card.append(line, retry);
|
|
4902
|
+
return card;
|
|
4903
|
+
}
|
|
4904
|
+
if (!server) { card.hidden = true; return card; }
|
|
4905
|
+
|
|
4906
|
+
const status = assistantNode('p', 'ai-chat-filter-note ai-chat-action-status assistant-card-status');
|
|
4907
|
+
status.setAttribute('role', 'status');
|
|
4908
|
+
status.tabIndex = -1;
|
|
4909
|
+
status.textContent = entry.error;
|
|
4910
|
+
const fold = (line, { undo = false, dim = false, again = false } = {}) => {
|
|
4911
|
+
card.classList.add('is-collapsed');
|
|
4912
|
+
if (dim) card.classList.add('is-gone');
|
|
4913
|
+
const row = assistantNode('div', 'assistant-card-line');
|
|
4914
|
+
const words = assistantNode('p', 'ai-chat-action-line', line);
|
|
4915
|
+
words.id = titleId;
|
|
4916
|
+
row.append(words);
|
|
4917
|
+
if (undo) {
|
|
4918
|
+
const back = assistantButton('Undo', 'shell.assistant-card-undo', text.title);
|
|
4919
|
+
back.dataset.tip = 'Shows this suggestion again.';
|
|
4920
|
+
back.disabled = Boolean(entry.busy);
|
|
4921
|
+
back.addEventListener('click', () => { void bringBackAssistantCard(entry, text.title); });
|
|
4922
|
+
row.append(back);
|
|
4923
|
+
}
|
|
4924
|
+
if (again) {
|
|
4925
|
+
// The request this card made is its own card below; this finds it again (and puts it back if it went missing).
|
|
4926
|
+
const show = assistantButton(entry.busy === 'use' ? 'Checking…' : 'Show the request', `shell.assistant-card-use#${move.kind || 'action'}`, text.title);
|
|
4927
|
+
show.dataset.tip = 'Shows the request for your OK again. Nothing runs from this card.';
|
|
4928
|
+
show.disabled = Boolean(entry.busy);
|
|
4929
|
+
show.addEventListener('click', () => { void useAssistantCard(entry, text); });
|
|
4930
|
+
row.append(show);
|
|
4931
|
+
}
|
|
4932
|
+
card.append(row, status);
|
|
4933
|
+
return card;
|
|
4934
|
+
};
|
|
4935
|
+
|
|
4936
|
+
if (server.state === 'other-account') return fold('This suggestion belongs to another account.', { dim: true });
|
|
4937
|
+
if (server.state === 'missing') return fold(`No longer applies: ${text.title}. FloLess no longer has this suggestion.`, { dim: true });
|
|
4938
|
+
if (entry.fold?.gone) return fold(`No longer applies: ${text.title}. ${entry.fold.reason}`, { dim: true });
|
|
4939
|
+
if (server.state === 'dismissed') {
|
|
4940
|
+
const returns = server.dismissed?.returns ? new Date(server.dismissed.returns) : null;
|
|
4941
|
+
const day = returns && !Number.isNaN(returns.getTime()) ? returns.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) : '';
|
|
4942
|
+
return fold(server.dismissed?.how === 'never' ? `Won’t suggest again: ${text.title}.`
|
|
4943
|
+
: day ? `Not now: ${text.title}. Back on ${day}.` : `Not now: ${text.title}.`, { undo: true });
|
|
4944
|
+
}
|
|
4945
|
+
// Folded only when this window put it there: after a reload the card is offered again (its button replays it).
|
|
4946
|
+
if (server.state === 'used' && server.outcome === 'compose' && entry.fold?.composed) return fold(`Put in message box: ${text.title}`);
|
|
4947
|
+
if (server.state === 'used' && server.outcome === 'proposal') return fold(`Sent for your OK below: ${text.title}`, { again: true });
|
|
4948
|
+
if (server.state === 'used' && (server.outcome === 'open' || server.outcome === 'screen') && entry.fold?.opened !== false) {
|
|
4949
|
+
return fold(`Opened: ${text.title}`);
|
|
4950
|
+
}
|
|
4951
|
+
|
|
4952
|
+
// The server re-checks the reason on every click: its answer wins over the card as first drawn (a failed workflow
|
|
4953
|
+
// that has since run fine is no longer a "Next step", and its old fact must not stay on the card).
|
|
4954
|
+
const cardClass = server.cardClass ?? payload.cardClass;
|
|
4955
|
+
const fact = 'fact' in server ? server.fact : payload.fact;
|
|
4956
|
+
const blocking = cardClass === 'blocking' || cardClass === 'resume';
|
|
4957
|
+
if (!blocking) card.classList.add('is-idea');
|
|
4958
|
+
const head = assistantNode('div', 'ai-chat-filter-card-head');
|
|
4959
|
+
const named = assistantNode('div', 'ai-chat-action-named');
|
|
4960
|
+
const strong = assistantNode('strong', '', text.title);
|
|
4961
|
+
strong.id = titleId;
|
|
4962
|
+
named.append(assistantNode('span', 'guide-move-eyebrow', blocking ? 'Next step' : 'Suggested'), strong);
|
|
4963
|
+
head.append(named);
|
|
4964
|
+
card.append(head);
|
|
4965
|
+
if (blocking && typeof fact === 'string' && fact.trim()) card.append(assistantNode('p', 'ai-chat-filter-note assistant-card-fact', fact.trim()));
|
|
4966
|
+
// The catalog summary only when it says more than the title (some actions repeat their title as their summary).
|
|
4967
|
+
if (move.kind === 'action' && move.summary && String(move.summary).trim() !== String(text.title).trim()) card.append(assistantNode('p', 'ai-chat-action-summary', String(move.summary)));
|
|
4968
|
+
if (text.detail) card.append(assistantNode('p', 'ai-chat-filter-why', String(text.detail)));
|
|
4969
|
+
if (move.kind === 'follow-up') card.append(assistantNode('blockquote', 'assistant-card-prompt', String(move.prompt || '')));
|
|
4970
|
+
const why = typeof payload.why === 'string' ? payload.why.trim() : '';
|
|
4971
|
+
if (why) card.append(assistantNode('p', 'ai-chat-filter-why ai-chat-action-why assistant-card-why', `Why: ${why}`));
|
|
4972
|
+
if (entry.result) card.append(paintAssistantResult(entry.result));
|
|
4973
|
+
if (server.state === 'used' && server.message && !entry.result) status.textContent = entry.error || String(server.message);
|
|
4974
|
+
|
|
4975
|
+
if (entry.compose) {
|
|
4976
|
+
// The person is writing something else: never overwrite it without asking.
|
|
4977
|
+
const choice = assistantNode('div', 'assistant-card-compose');
|
|
4978
|
+
choice.append(assistantNode('p', 'ai-chat-filter-note', 'You’re writing a message.'));
|
|
4979
|
+
const row = assistantNode('div', 'ai-chat-filter-actions');
|
|
4980
|
+
const replace = assistantButton('Replace it', 'shell.assistant-card-compose-replace', text.title);
|
|
4981
|
+
replace.dataset.tip = 'Replaces what is in the message box with this message. Nothing is sent.';
|
|
4982
|
+
replace.addEventListener('click', () => { composeAssistantFollowUp(entry, text.title, 'replace'); });
|
|
4983
|
+
const append = assistantButton('Add below it', 'shell.assistant-card-compose-append', text.title, 'ai-chat-filter-apply');
|
|
4984
|
+
append.dataset.tip = 'Adds this message below what you are writing. Nothing is sent.';
|
|
4985
|
+
append.addEventListener('click', () => { composeAssistantFollowUp(entry, text.title, 'append'); });
|
|
4986
|
+
row.append(replace, append);
|
|
4987
|
+
choice.append(row);
|
|
4988
|
+
card.append(choice, status);
|
|
4989
|
+
return card;
|
|
4990
|
+
}
|
|
4991
|
+
|
|
4992
|
+
const actions = assistantNode('div', 'ai-chat-filter-actions');
|
|
4993
|
+
const later = assistantButton('Not now', 'shell.assistant-card-not-now', text.title);
|
|
4994
|
+
later.dataset.tip = 'Hides this for 7 days. Undo on this card brings it back, or ask the AI in any chat to bring it back.';
|
|
4995
|
+
later.addEventListener('click', () => { void dismissAssistantCard(entry, text.title, 'not-now'); });
|
|
4996
|
+
const never = assistantButton('Don’t suggest again', 'shell.assistant-card-never', text.title);
|
|
4997
|
+
never.dataset.tip = 'Stops this suggestion for your account. Undo on this card brings it back, or ask the AI in any chat to bring it back.';
|
|
4998
|
+
never.addEventListener('click', () => { void dismissAssistantCard(entry, text.title, 'never'); });
|
|
4999
|
+
const use = assistantButton(entry.busy === 'use' ? 'Checking…' : text.action, `shell.assistant-card-use#${move.kind || 'open'}`, text.title, 'ai-chat-filter-apply');
|
|
5000
|
+
use.dataset.tip = move.kind === 'follow-up' ? 'Puts this message in the message box. Nothing is sent.'
|
|
5001
|
+
: move.kind === 'action' && move.risk === 'read' ? 'Shows the result here. Nothing changes.'
|
|
5002
|
+
: move.kind === 'action' && move.risk !== 'human-only' ? 'Opens a request below for your OK. Nothing runs from this card.'
|
|
5003
|
+
: 'Opens the place to do this. Nothing happens until you confirm there.';
|
|
5004
|
+
if (entry.busy === 'use') use.setAttribute('aria-busy', 'true');
|
|
5005
|
+
use.addEventListener('click', () => { void useAssistantCard(entry, text); });
|
|
5006
|
+
for (const control of [later, never, use]) control.disabled = Boolean(entry.busy);
|
|
5007
|
+
if (entry.busy) card.setAttribute('aria-busy', 'true');
|
|
5008
|
+
actions.append(later, never, use);
|
|
5009
|
+
card.append(actions);
|
|
5010
|
+
if (text.note) card.append(assistantNode('p', 'ai-chat-filter-note', text.note));
|
|
5011
|
+
if (entry.recovered && entry.cardId === assistantRecoveredCard) {
|
|
5012
|
+
const line = assistantNode('div', 'assistant-card-recovered');
|
|
5013
|
+
line.append(assistantNode('p', 'ai-chat-filter-note', 'FloLess had to reset your suggestion settings. Suggestions are paused until you choose.'));
|
|
5014
|
+
const choose = assistantButton('Choose…', 'shell.assistant-recovered-choose', 'Suggest next steps');
|
|
5015
|
+
choose.dataset.tip = 'Opens Suggest next steps in this chat’s settings.';
|
|
5016
|
+
choose.addEventListener('click', () => { void chooseAssistantMode(); });
|
|
5017
|
+
line.append(choose);
|
|
5018
|
+
card.append(line);
|
|
5019
|
+
}
|
|
5020
|
+
card.append(status);
|
|
5021
|
+
return card;
|
|
5022
|
+
}
|
|
5023
|
+
|
|
5024
|
+
/**
|
|
5025
|
+
* A read result as plain rows: each top-level field with a readable name ("runId" → "Run id") and a plain value
|
|
5026
|
+
* (Yes/No, a date as written, "—" for none). Nested lists and objects are counted ("12 items", "details"), and
|
|
5027
|
+
* `rows.hidden` says some detail was left out.
|
|
5028
|
+
*/
|
|
5029
|
+
function assistantResultRows(data) {
|
|
5030
|
+
const rows = [];
|
|
5031
|
+
rows.hidden = false;
|
|
5032
|
+
const clip = (value, max) => { const s = String(value); if (s.length <= max) return s; rows.hidden = true; return `${s.slice(0, max - 1)}… (shortened)`; };
|
|
5033
|
+
if (typeof data === 'string') { if (data.trim()) rows.push(['Result', clip(data.trim(), 400)]); return rows; }
|
|
5034
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) {
|
|
5035
|
+
if (Array.isArray(data)) { rows.push(['Items', `${data.length}`]); rows.hidden = data.length > 0; }
|
|
5036
|
+
else if (data !== undefined && data !== null) rows.push(['Result', String(data)]);
|
|
5037
|
+
return rows;
|
|
5038
|
+
}
|
|
5039
|
+
const label = (key) => {
|
|
5040
|
+
const words = String(key).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').trim().toLowerCase();
|
|
5041
|
+
return words.charAt(0).toUpperCase() + words.slice(1);
|
|
5042
|
+
};
|
|
5043
|
+
for (const [key, value] of Object.entries(data)) {
|
|
5044
|
+
// A route's own `ok: true` only repeats that the read worked; any other `ok` is data and is shown.
|
|
5045
|
+
if (key === 'ok' && value === true) continue;
|
|
5046
|
+
if (rows.length >= 12) { rows.hidden = true; break; }
|
|
5047
|
+
if (value === null || value === undefined) rows.push([label(key), '—']);
|
|
5048
|
+
else if (typeof value === 'boolean') rows.push([label(key), value ? 'Yes' : 'No']);
|
|
5049
|
+
else if (typeof value === 'number' || typeof value === 'string') rows.push([label(key), clip(value, 200)]);
|
|
5050
|
+
else if (Array.isArray(value)) { rows.push([label(key), value.length === 1 ? '1 item' : `${value.length} items`]); if (value.length) rows.hidden = true; }
|
|
5051
|
+
else { rows.push([label(key), 'details']); rows.hidden = true; }
|
|
5052
|
+
}
|
|
5053
|
+
return rows;
|
|
5054
|
+
}
|
|
5055
|
+
|
|
5056
|
+
/** Every field of a read result, nested lists and objects included, as plain rows; values in full. */
|
|
5057
|
+
function assistantResultTree(data, depth) {
|
|
5058
|
+
const label = (key) => {
|
|
5059
|
+
const words = String(key).replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/[_-]+/g, ' ').trim().toLowerCase();
|
|
5060
|
+
return words.charAt(0).toUpperCase() + words.slice(1);
|
|
5061
|
+
};
|
|
5062
|
+
const plain = (value) => value === null || value === undefined ? '—' : typeof value === 'boolean' ? (value ? 'Yes' : 'No') : String(value);
|
|
5063
|
+
if (data === null || typeof data !== 'object') return assistantNode('span', '', plain(data));
|
|
5064
|
+
const list = document.createElement('dl');
|
|
5065
|
+
list.className = 'assistant-card-result-list';
|
|
5066
|
+
// Only the route's own top-level `ok: true` is left out (it repeats that the read worked); any other `ok` is data.
|
|
5067
|
+
const entries = Array.isArray(data) ? data.map((value, i) => [`${i + 1}`, value])
|
|
5068
|
+
: Object.entries(data).filter(([key, value]) => depth > 0 || key !== 'ok' || value !== true);
|
|
5069
|
+
if (!entries.length) return assistantNode('span', '', Array.isArray(data) ? 'None' : '—');
|
|
5070
|
+
for (const [key, value] of entries) {
|
|
5071
|
+
const dd = document.createElement('dd');
|
|
5072
|
+
// Every level is laid out: the result is the server's own bounded JSON, so nothing is cut here.
|
|
5073
|
+
if (value !== null && typeof value === 'object') dd.append(assistantResultTree(value, depth + 1));
|
|
5074
|
+
else dd.textContent = plain(value);
|
|
5075
|
+
list.append(assistantNode('dt', '', Array.isArray(data) ? key : label(key)), dd);
|
|
5076
|
+
}
|
|
5077
|
+
return list;
|
|
5078
|
+
}
|
|
5079
|
+
|
|
5080
|
+
/** A read's result, kept by the server: shown in plain rows in a bounded themed scroller. */
|
|
5081
|
+
function paintAssistantResult(result) {
|
|
5082
|
+
const wrap = assistantNode('div', 'assistant-card-result');
|
|
5083
|
+
if (!result.ok) {
|
|
5084
|
+
wrap.append(assistantNode('p', 'ai-chat-filter-note', String(result.message || 'It did not complete.')));
|
|
5085
|
+
return wrap;
|
|
5086
|
+
}
|
|
5087
|
+
// Plain words, never raw data: a person reads this card. Top-level facts become "Field: value" rows; anything
|
|
5088
|
+
// nested is counted, not dumped — the AI in this chat can explain the details if the person asks.
|
|
5089
|
+
const body = assistantNode('div', 'assistant-card-result-body');
|
|
5090
|
+
body.tabIndex = 0;
|
|
5091
|
+
body.setAttribute('role', 'group');
|
|
5092
|
+
body.setAttribute('aria-label', 'Result');
|
|
5093
|
+
const rows = assistantResultRows(result.data);
|
|
5094
|
+
if (!rows.length) body.append(assistantNode('p', 'assistant-card-result-empty', 'Nothing to show.'));
|
|
5095
|
+
else {
|
|
5096
|
+
const list = document.createElement('dl');
|
|
5097
|
+
list.className = 'assistant-card-result-list';
|
|
5098
|
+
for (const [label, value] of rows) list.append(assistantNode('dt', '', label), assistantNode('dd', '', value));
|
|
5099
|
+
body.append(list);
|
|
5100
|
+
}
|
|
5101
|
+
wrap.append(body);
|
|
5102
|
+
if (rows.hidden) {
|
|
5103
|
+
// Everything the read returned, laid out in plain nested rows (never raw data), on request.
|
|
5104
|
+
const more = button('Show all details', 'shell.assistant-card-result-details', 'assistant-card-result-more');
|
|
5105
|
+
more.setAttribute('aria-expanded', 'false');
|
|
5106
|
+
more.dataset.tip = 'Shows everything this read returned, in full.';
|
|
5107
|
+
const full = assistantNode('div', 'assistant-card-result-body assistant-card-result-full');
|
|
5108
|
+
full.tabIndex = 0;
|
|
5109
|
+
full.setAttribute('role', 'group');
|
|
5110
|
+
full.setAttribute('aria-label', 'All details');
|
|
5111
|
+
full.hidden = true;
|
|
5112
|
+
full.append(assistantResultTree(result.data, 0));
|
|
5113
|
+
more.addEventListener('click', () => {
|
|
5114
|
+
const open = full.hidden;
|
|
5115
|
+
full.hidden = !open;
|
|
5116
|
+
more.setAttribute('aria-expanded', String(open));
|
|
5117
|
+
more.textContent = open ? 'Hide details' : 'Show all details';
|
|
5118
|
+
});
|
|
5119
|
+
wrap.append(more, full);
|
|
5120
|
+
}
|
|
5121
|
+
if (result.truncated && result.message) wrap.append(assistantNode('p', 'ai-chat-filter-note', String(result.message)));
|
|
5122
|
+
return wrap;
|
|
5123
|
+
}
|
|
5124
|
+
|
|
5125
|
+
/** A refusal from a card route: a plain sentence on the card, a fold when the card can't be used any more. */
|
|
5126
|
+
function assistantRefused(entry, error) {
|
|
5127
|
+
const code = error?.code || '';
|
|
5128
|
+
const message = typeof error?.message === 'string' && error.message && error.status ? error.message : ASSISTANT_FALLBACK_ERROR;
|
|
5129
|
+
if (code === 'assistant-card-other-account') { entry.server = { cardId: entry.cardId, state: 'other-account' }; return; }
|
|
5130
|
+
if (code === 'assistant-card-dismissed') { entry.server = null; wantAssistantState(entry.cardId); return; }
|
|
5131
|
+
if (ASSISTANT_GONE_CODES.has(code)) { entry.fold = { gone: true, reason: message }; return; }
|
|
5132
|
+
if (code === 'assistant-settings-recovered' && (!assistantRecoveredCard || !assistantCardEntries.has(assistantRecoveredCard))) {
|
|
5133
|
+
assistantRecoveredCard = entry.cardId; entry.recovered = true;
|
|
5134
|
+
}
|
|
5135
|
+
entry.error = message;
|
|
5136
|
+
}
|
|
5137
|
+
|
|
5138
|
+
async function useAssistantCard(entry, text) {
|
|
5139
|
+
if (entry.busy) return;
|
|
5140
|
+
const chatId = entry.event.chatId;
|
|
5141
|
+
entry.busy = 'use'; entry.error = '';
|
|
5142
|
+
repaintAssistantCard(entry);
|
|
5143
|
+
let answer = null;
|
|
5144
|
+
try {
|
|
5145
|
+
const body = await request(`/api/assistant/cards/${encodeURIComponent(entry.cardId)}/use`, { method: 'POST', body: '{}' });
|
|
5146
|
+
answer = body?.card || null;
|
|
5147
|
+
} catch (error) {
|
|
5148
|
+
assistantRefused(entry, error);
|
|
5149
|
+
}
|
|
5150
|
+
entry.busy = '';
|
|
5151
|
+
if (!answer) { entry.focus = 'status'; repaintAssistantCard(entry); return; }
|
|
5152
|
+
entry.server = { ...(entry.server || {}), cardId: entry.cardId, state: 'used', outcome: answer.outcome,
|
|
5153
|
+
...(typeof answer.cardClass === 'string' ? { cardClass: answer.cardClass } : {}),
|
|
5154
|
+
// An answer without a fact clears the one the card was drawn with: it no longer holds.
|
|
5155
|
+
...(typeof answer.cardClass === 'string' ? { fact: typeof answer.fact === 'string' ? answer.fact : null } : {}) };
|
|
5156
|
+
const title = text.title;
|
|
5157
|
+
if (answer.outcome === 'read') {
|
|
5158
|
+
entry.result = answer.result || { ok: false, message: 'FloLess kept no result for this.' };
|
|
5159
|
+
repaintAssistantCard(entry);
|
|
5160
|
+
announce(entry.result.ok ? `${title}: shown on the card.` : `${title}: it did not complete.`);
|
|
5161
|
+
return;
|
|
5162
|
+
}
|
|
5163
|
+
if (answer.outcome === 'indeterminate') {
|
|
5164
|
+
entry.error = answer.message || ASSISTANT_FALLBACK_ERROR;
|
|
5165
|
+
entry.focus = 'status'; repaintAssistantCard(entry); return;
|
|
5166
|
+
}
|
|
5167
|
+
if (answer.outcome === 'compose') {
|
|
5168
|
+
// The conversation may have changed while FloLess answered: the message box now belongs to another chat.
|
|
5169
|
+
if (state.chat?.chatId !== chatId || !ui.input || ui.input.disabled) {
|
|
5170
|
+
entry.server = { ...entry.server, state: 'shown' };
|
|
5171
|
+
entry.error = 'Open this conversation, then press Put in message box again. Nothing was sent.';
|
|
5172
|
+
entry.focus = 'status'; repaintAssistantCard(entry); return;
|
|
5173
|
+
}
|
|
5174
|
+
const prompt = String(answer.prompt || entry.event.payload?.move?.prompt || '');
|
|
5175
|
+
const action = followUpComposeAction(ui.input.value, prompt);
|
|
5176
|
+
if (action === 'choose') {
|
|
5177
|
+
entry.server = { ...entry.server, state: 'shown' };
|
|
5178
|
+
entry.compose = { prompt };
|
|
5179
|
+
entry.focus = 'shell.assistant-card-compose-append';
|
|
5180
|
+
repaintAssistantCard(entry);
|
|
5181
|
+
return;
|
|
5182
|
+
}
|
|
5183
|
+
entry.fold = { composed: true };
|
|
5184
|
+
repaintAssistantCard(entry);
|
|
5185
|
+
// After the repaint, so the keyboard ends in the message box, never back on the card.
|
|
5186
|
+
if (action === 'fill') putInMessageBox(prompt);
|
|
5187
|
+
else ui.input.focus({ preventScroll: true });
|
|
5188
|
+
announce(`Put in message box: ${title}. Press Send when you are ready.`);
|
|
5189
|
+
return;
|
|
5190
|
+
}
|
|
5191
|
+
if (answer.outcome === 'proposal') {
|
|
5192
|
+
repaintAssistantCard(entry);
|
|
5193
|
+
announce(`Sent for your OK below: ${title}.`);
|
|
5194
|
+
// The request arrives as its own card; if it never does, say so here (pressing Show the request asks again).
|
|
5195
|
+
const missing = () => { entry.error = 'FloLess couldn’t show the request just now. Press Show the request to try again.'; entry.focus = 'status'; repaintAssistantCard(entry); };
|
|
5196
|
+
if (answer.proposalId) focusProposalConfirm(answer.proposalId, missing); else missing();
|
|
5197
|
+
return;
|
|
5198
|
+
}
|
|
5199
|
+
// Open the place: a human-only action's screen, or the flow for a tool, workflow, agent, routine or page.
|
|
5200
|
+
let opened = false;
|
|
5201
|
+
try {
|
|
5202
|
+
if (answer.outcome === 'screen') opened = await openActionScreen(answer.screen);
|
|
5203
|
+
else if (answer.move?.kind === 'create-workflow' && typeof window.flolessBridge?.newWorkflow === 'function') {
|
|
5204
|
+
opened = true;
|
|
5205
|
+
void window.flolessBridge.newWorkflow({ name: answer.move.name });
|
|
5206
|
+
} else if (answer.move) opened = Boolean(await window.flolessGuide?.openFlow?.(answer.move));
|
|
5207
|
+
} catch (error) {
|
|
5208
|
+
console.warn('[assistant] a suggestion could not open its place:', error);
|
|
5209
|
+
opened = false;
|
|
5210
|
+
}
|
|
5211
|
+
if (!opened) {
|
|
5212
|
+
entry.fold = { opened: false };
|
|
5213
|
+
entry.error = 'FloLess couldn’t open that from here. Open it from the ≡ menu instead.';
|
|
5214
|
+
entry.focus = 'status'; repaintAssistantCard(entry); return;
|
|
5215
|
+
}
|
|
5216
|
+
entry.fold = null;
|
|
5217
|
+
repaintAssistantCard(entry);
|
|
5218
|
+
announce(`Opened: ${title}.`);
|
|
5219
|
+
}
|
|
5220
|
+
|
|
5221
|
+
/** The follow-up into a box that holds something else, as the person chose: below it, or instead of it. Never sends. */
|
|
5222
|
+
function composeAssistantFollowUp(entry, title, how) {
|
|
5223
|
+
const prompt = entry.compose?.prompt || '';
|
|
5224
|
+
if (!prompt) return;
|
|
5225
|
+
if (state.chat?.chatId !== entry.event.chatId || !ui.input || ui.input.disabled) {
|
|
5226
|
+
entry.error = 'Open this conversation to put the message in its message box. Nothing was sent.';
|
|
5227
|
+
repaintAssistantCard(entry); return;
|
|
5228
|
+
}
|
|
5229
|
+
const held = ui.input.value;
|
|
5230
|
+
entry.compose = null;
|
|
5231
|
+
entry.fold = { composed: true };
|
|
5232
|
+
entry.server = { ...(entry.server || {}), cardId: entry.cardId, state: 'used', outcome: 'compose' };
|
|
5233
|
+
repaintAssistantCard(entry);
|
|
5234
|
+
// After the repaint, so the caret ends in the message box.
|
|
5235
|
+
putInMessageBox(how === 'replace' || !held.trim() ? prompt : held.includes(prompt) ? held : `${held.replace(/\s+$/, '')}\n\n${prompt}`);
|
|
5236
|
+
announce(`Put in message box: ${title}. Press Send when you are ready.`);
|
|
5237
|
+
}
|
|
5238
|
+
|
|
5239
|
+
async function dismissAssistantCard(entry, title, how) {
|
|
5240
|
+
if (entry.busy) return;
|
|
5241
|
+
entry.busy = how; entry.error = '';
|
|
5242
|
+
repaintAssistantCard(entry);
|
|
5243
|
+
try {
|
|
5244
|
+
const body = await request(`/api/assistant/cards/${encodeURIComponent(entry.cardId)}/${how}`, { method: 'POST', body: '{}' });
|
|
5245
|
+
entry.server = { ...(entry.server || {}), cardId: entry.cardId, state: 'dismissed',
|
|
5246
|
+
dismissed: { how, ...(body?.suggestion?.until ? { returns: body.suggestion.until } : {}) } };
|
|
5247
|
+
entry.focus = 'shell.assistant-card-undo';
|
|
5248
|
+
announce(how === 'never' ? `Won’t suggest again: ${title}.` : `Not now: ${title}.`);
|
|
5249
|
+
} catch (error) {
|
|
5250
|
+
assistantRefused(entry, error);
|
|
5251
|
+
entry.focus = 'status';
|
|
5252
|
+
} finally {
|
|
5253
|
+
entry.busy = '';
|
|
5254
|
+
repaintAssistantCard(entry);
|
|
5255
|
+
}
|
|
5256
|
+
}
|
|
5257
|
+
|
|
5258
|
+
async function bringBackAssistantCard(entry, title) {
|
|
5259
|
+
if (entry.busy) return;
|
|
5260
|
+
entry.busy = 'undo'; entry.error = '';
|
|
5261
|
+
repaintAssistantCard(entry);
|
|
5262
|
+
try {
|
|
5263
|
+
const body = await request(`/api/assistant/cards/${encodeURIComponent(entry.cardId)}/bring-back`, { method: 'POST', body: '{}' });
|
|
5264
|
+
const status = body?.card?.status === 'used' ? 'used' : 'shown';
|
|
5265
|
+
entry.server = { ...(entry.server || {}), cardId: entry.cardId, state: status };
|
|
5266
|
+
delete entry.server.dismissed;
|
|
5267
|
+
entry.focus = `shell.assistant-card-use#${entry.event.payload?.move?.kind || 'open'}`;
|
|
5268
|
+
announce(`Brought back: ${title}.`);
|
|
5269
|
+
} catch (error) {
|
|
5270
|
+
assistantRefused(entry, error);
|
|
5271
|
+
entry.focus = 'status';
|
|
5272
|
+
} finally {
|
|
5273
|
+
entry.busy = '';
|
|
5274
|
+
repaintAssistantCard(entry);
|
|
5275
|
+
}
|
|
5276
|
+
}
|
|
5277
|
+
|
|
5278
|
+
function focusAssistantStatus(entry) {
|
|
5279
|
+
const status = entry.node?.querySelector('.assistant-card-status');
|
|
5280
|
+
if (status?.textContent) status.focus({ preventScroll: true });
|
|
5281
|
+
}
|
|
5282
|
+
|
|
5283
|
+
/** The request a card made arrives as its own card below (an event): its Confirm gets the keyboard once it is drawn. */
|
|
5284
|
+
function focusProposalConfirm(proposalId, onMissing = () => {}, tries = 40) {
|
|
5285
|
+
const proposal = ui.feed?.querySelector(`.ai-chat-action-card[data-proposal-id="${CSS.escape(proposalId)}"]`);
|
|
5286
|
+
if (proposal) {
|
|
5287
|
+
// Its Confirm (or a person-only step's Open); a request already answered has neither, so its own line.
|
|
5288
|
+
const target = proposal.querySelector('[data-command-id^="shell.chat-action-confirm"]:not([disabled])')
|
|
5289
|
+
|| proposal.querySelector('[data-command-id^="shell.chat-action-open"]') || proposal.querySelector('.ai-chat-action-status');
|
|
5290
|
+
if (target && !target.hasAttribute('tabindex') && target.tagName === 'P') target.tabIndex = -1;
|
|
5291
|
+
(target || proposal).focus?.({ preventScroll: false });
|
|
5292
|
+
return;
|
|
5293
|
+
}
|
|
5294
|
+
if (tries > 0) setTimeout(() => focusProposalConfirm(proposalId, onMissing, tries - 1), 125);
|
|
5295
|
+
else onMissing();
|
|
5296
|
+
}
|
|
5297
|
+
|
|
5298
|
+
/** The recovered line's Choose…: the chat's settings, open at Suggest next steps. */
|
|
5299
|
+
async function chooseAssistantMode() {
|
|
5300
|
+
if (ui.settings?.hidden) ui.settingsToggle?.click();
|
|
5301
|
+
await assistantMode.refresh();
|
|
5302
|
+
if (ui.suggest && !ui.suggest.disabled) openPicker('suggest', ui.suggest, assistantMode.choices());
|
|
5303
|
+
}
|
|
5304
|
+
|
|
5305
|
+
/*
|
|
5306
|
+
* #2478: what FloLess recorded while the AI answered (objects it linked or named, sheets it looked at, a change it
|
|
5307
|
+
* made to the model view) folds under the answer into one quiet line, the way AI apps show their working. The line
|
|
5308
|
+
* says what happened: a change is named in words with anything still to be said about it, and only reads are
|
|
5309
|
+
* counted. Anything that went wrong, anything still running, anything that asks the person, and the answer's sources
|
|
5310
|
+
* never fold. Each fold is one node, kept while its conversation is open and reused across repaints, so whether it
|
|
5311
|
+
* is open and its focus survive streaming.
|
|
5312
|
+
*/
|
|
5313
|
+
const receiptFolds = new Map();
|
|
5314
|
+
let receiptFoldsChat = null;
|
|
5315
|
+
let receiptFoldIds = 0;
|
|
5316
|
+
const EVIDENCE_COUNTS = { sheet: 'sheets', 'sheet-tiles': 'sheets', 'attachment-image': 'attachments', 'attachment-pdf': 'attachments' };
|
|
5317
|
+
|
|
5318
|
+
/** One receipt's part of its answer's fold line, or null when it must stay in sight. */
|
|
5319
|
+
function foldableReceipt(event) {
|
|
5320
|
+
const payload = event?.payload || {};
|
|
5321
|
+
if (event?.type === 'chat-subjects') {
|
|
5322
|
+
const count = Array.isArray(payload.items) ? payload.items.length : 0;
|
|
5323
|
+
return count ? { count: payload.role === 'answer' ? 'named' : 'linked', n: count } : null;
|
|
5324
|
+
}
|
|
5325
|
+
if (event?.type === 'evidence-read') return payload.outcome === 'read' ? { count: EVIDENCE_COUNTS[payload.kind] || 'items', n: 1 } : null;
|
|
5326
|
+
if (event?.type === 'view-command') {
|
|
5327
|
+
// Only a change the editor confirmed folds, named by its own words and every caveat FloLess wrote beside it. A
|
|
5328
|
+
// change still running, not confirmed or not fully done stays in sight, and so does one recorded before FloLess
|
|
5329
|
+
// wrote its caveats separately: what it left unsaid cannot be told apart from a change that had none.
|
|
5330
|
+
let update = null;
|
|
5331
|
+
for (const item of state.events) if (item.type === 'view-command-update' && item.payload?.commandId === payload.commandId) update = item;
|
|
5332
|
+
const done = update?.payload;
|
|
5333
|
+
if (done?.status !== 'applied' || typeof done.action !== 'string' || !done.action || !Array.isArray(done.caveats)) return null;
|
|
5334
|
+
const caveats = done.caveats.filter((caveat) => typeof caveat === 'string' && caveat);
|
|
5335
|
+
return { change: caveats.length ? `${done.action} (${caveats.join('; ')})` : done.action };
|
|
5336
|
+
}
|
|
5337
|
+
return null;
|
|
5338
|
+
}
|
|
5339
|
+
|
|
5340
|
+
/** The fold line's words: each change in its own words, then what was read, counted. */
|
|
5341
|
+
function receiptFoldSummary(parts) {
|
|
5342
|
+
const changes = [];
|
|
5343
|
+
const totals = { linked: 0, named: 0, sheets: 0, attachments: 0, items: 0 };
|
|
5344
|
+
for (const part of parts) {
|
|
5345
|
+
if (part.change) changes.push(part.change);
|
|
5346
|
+
else if (part.count in totals) totals[part.count] += part.n;
|
|
5347
|
+
}
|
|
5348
|
+
const counted = (n, one, many) => `${n} ${n === 1 ? one : many}`;
|
|
5349
|
+
const looked = [totals.sheets && counted(totals.sheets, 'sheet', 'sheets'), totals.attachments && counted(totals.attachments, 'attachment', 'attachments'),
|
|
5350
|
+
totals.items && counted(totals.items, 'other item', 'other items')].filter(Boolean);
|
|
5351
|
+
const line = [
|
|
5352
|
+
...changes,
|
|
5353
|
+
totals.linked && `linked ${counted(totals.linked, 'object', 'objects')}`,
|
|
5354
|
+
totals.named && `named ${counted(totals.named, 'object', 'objects')}`,
|
|
5355
|
+
looked.length && `looked at ${looked.length > 1 ? `${looked.slice(0, -1).join(', ')} and ${looked.at(-1)}` : looked[0]}`,
|
|
5356
|
+
].filter(Boolean).join(' · ');
|
|
5357
|
+
return line.charAt(0).toUpperCase() + line.slice(1);
|
|
5358
|
+
}
|
|
5359
|
+
|
|
5360
|
+
/**
|
|
5361
|
+
* An answer's held receipts, as the feed shows them, in the order they were written: each unbroken stretch of
|
|
5362
|
+
* foldable receipts becomes one line, and anything that stays in sight keeps its own place between them, so an open
|
|
5363
|
+
* fold reads in event order. A stretch only grows (receipts are added at the end, and one that was still running can
|
|
5364
|
+
* become foldable later and join its neighbours), so it reuses the fold of the earliest receipt in it that already
|
|
5365
|
+
* had one: a fold the person opened stays the same fold, still open, as its stretch grows.
|
|
5366
|
+
*/
|
|
5367
|
+
function receiptFold(links) {
|
|
5368
|
+
const parts = links.map((link) => (link.event ? foldableReceipt(link.event) : null));
|
|
5369
|
+
if (!parts.some(Boolean)) return links.map((link) => link.node);
|
|
5370
|
+
const chatId = state.chat?.chatId || '';
|
|
5371
|
+
if (receiptFoldsChat !== chatId) { receiptFolds.clear(); receiptFoldsChat = chatId; }
|
|
5372
|
+
const shown = [];
|
|
5373
|
+
for (let start = 0; start < links.length;) {
|
|
5374
|
+
if (!parts[start]) { shown.push(links[start].node); start += 1; continue; }
|
|
5375
|
+
let end = start;
|
|
5376
|
+
while (end < links.length && parts[end]) end += 1;
|
|
5377
|
+
const stretch = links.slice(start, end);
|
|
5378
|
+
let fold = null;
|
|
5379
|
+
for (const link of stretch) if ((fold = receiptFolds.get(link.event.eventId))) break;
|
|
5380
|
+
if (!fold) fold = newReceiptFold(stretch[0].event.eventId);
|
|
5381
|
+
const summary = receiptFoldSummary(parts.slice(start, end));
|
|
5382
|
+
fold.text.textContent = summary;
|
|
5383
|
+
fold.toggle.dataset.commandInstanceLabel = summary;
|
|
5384
|
+
fold.body.replaceChildren(...stretch.map((link) => link.node));
|
|
5385
|
+
shown.push(fold.root);
|
|
5386
|
+
start = end;
|
|
5387
|
+
}
|
|
5388
|
+
return shown;
|
|
5389
|
+
}
|
|
5390
|
+
|
|
5391
|
+
/** One fold line, closed, kept under the event id of the receipt it starts at. */
|
|
5392
|
+
function newReceiptFold(key) {
|
|
5393
|
+
const root = document.createElement('div'); root.className = 'ai-chat-fold';
|
|
5394
|
+
const toggle = button('', 'shell.chat-answer-record', 'ai-chat-fold-toggle');
|
|
5395
|
+
const chevron = Object.assign(document.createElement('span'), { className: 'ai-chat-fold-chevron', textContent: '›' });
|
|
5396
|
+
chevron.setAttribute('aria-hidden', 'true');
|
|
5397
|
+
const text = Object.assign(document.createElement('span'), { className: 'ai-chat-fold-text' });
|
|
5398
|
+
toggle.append(chevron, text);
|
|
5399
|
+
const body = document.createElement('div'); body.className = 'ai-chat-fold-body';
|
|
5400
|
+
body.id = `ai-chat-fold-${++receiptFoldIds}`;
|
|
5401
|
+
body.setAttribute('role', 'group');
|
|
5402
|
+
body.setAttribute('aria-label', 'What FloLess recorded for this answer');
|
|
5403
|
+
toggle.setAttribute('aria-controls', body.id);
|
|
5404
|
+
root.append(toggle, body);
|
|
5405
|
+
const fold = { root, toggle, text, body, open: false };
|
|
5406
|
+
const paint = () => {
|
|
5407
|
+
toggle.setAttribute('aria-expanded', String(fold.open));
|
|
5408
|
+
toggle.dataset.tip = fold.open ? 'Hide what FloLess recorded' : 'Show what FloLess recorded while the AI answered';
|
|
5409
|
+
root.classList.toggle('is-open', fold.open);
|
|
5410
|
+
body.hidden = !fold.open;
|
|
5411
|
+
};
|
|
5412
|
+
toggle.addEventListener('click', () => { fold.open = !fold.open; paint(); });
|
|
5413
|
+
paint();
|
|
5414
|
+
receiptFolds.set(key, fold);
|
|
5415
|
+
return fold;
|
|
5416
|
+
}
|
|
5417
|
+
|
|
3404
5418
|
function renderEvent(event) {
|
|
3405
5419
|
if (event.type === 'user-message' && event.payload?.source === 'request' && event.payload?.filterAi) return renderFilterQuestion(event);
|
|
3406
5420
|
if (event.type === 'user-message' && event.payload?.source === 'request') return renderRequestCard(event);
|
|
@@ -3420,6 +5434,8 @@
|
|
|
3420
5434
|
if (event.type === 'connection-proposal-update') return null;
|
|
3421
5435
|
if (event.type === 'connection-check') return renderConnectionCheck(event);
|
|
3422
5436
|
// #2046: a next move the Guide suggested; web/guide.js paints it and owns its button.
|
|
5437
|
+
// #2399 PR C2: a next step the assistant suggested in a project, workflow or workspace chat; this file paints it.
|
|
5438
|
+
if (event.type === 'next-move' && event.payload?.assistant === true) return renderAssistantCard(event);
|
|
3423
5439
|
if (event.type === 'next-move') return window.flolessGuide?.renderNextMove?.(event) || null;
|
|
3424
5440
|
// #2185: what came of a card's button repaints that card; it is never a line of its own.
|
|
3425
5441
|
if (event.type === 'next-move-update') { window.flolessGuide?.applyMoveUpdate?.(event); return null; }
|
|
@@ -3444,13 +5460,13 @@
|
|
|
3444
5460
|
if (event.type === 'height-question') return renderHeightQuestion(event);
|
|
3445
5461
|
if (event.type === 'setup-question') return renderSetupQuestion(event);
|
|
3446
5462
|
const item = document.createElement('div');
|
|
3447
|
-
item.className = `ai-chat-event ${event.type === 'error' ? 'error' : ''}
|
|
5463
|
+
item.className = `ai-chat-event ${event.type === 'error' ? 'error' : ''}`;
|
|
3448
5464
|
item.dataset.eventSequence = String(event.sequence);
|
|
3449
5465
|
item.dataset.eventId = event.eventId;
|
|
3450
5466
|
const label = document.createElement('strong');
|
|
3451
5467
|
const labels = {
|
|
3452
5468
|
attachment: 'Attachment', tool: 'AI action', error: 'Error', interrupted: 'Stopped', usage: 'AI usage',
|
|
3453
|
-
compaction: 'Conversation summary updated',
|
|
5469
|
+
compaction: 'Conversation summary updated', state: 'Status', request: 'Request',
|
|
3454
5470
|
};
|
|
3455
5471
|
const payload = event.payload || {};
|
|
3456
5472
|
if (event.type === 'chat-subjects') {
|
|
@@ -3494,7 +5510,6 @@
|
|
|
3494
5510
|
const statusLabels = { started: 'started', completed: 'completed', failed: 'failed', denied: 'not allowed' };
|
|
3495
5511
|
detail = [toolLabels[payload.tool] || 'AI action', statusLabels[payload.status] || payload.status].filter(Boolean).join(' · ');
|
|
3496
5512
|
}
|
|
3497
|
-
if (!detail && event.type === 'knowledge-citation') detail = Array.isArray(payload.pageSlugs) ? payload.pageSlugs.join(', ') : '';
|
|
3498
5513
|
if (!detail && event.type === 'interrupted') detail = 'The AI response was interrupted.';
|
|
3499
5514
|
if (!detail && event.type === 'usage') {
|
|
3500
5515
|
detail = 'Usage updated';
|
|
@@ -3599,7 +5614,9 @@
|
|
|
3599
5614
|
if (!snapshot) return '';
|
|
3600
5615
|
if (snapshot.state === 'unknown' || typeof snapshot.value !== 'number') return 'In the model when asked: no height.';
|
|
3601
5616
|
const value = heightInModelValue(snapshot.value, units);
|
|
3602
|
-
const tail = snapshot.state === 'assumed' ? ' (placed, not from the drawings)' : snapshot.state === 'answered' ? ' (your earlier answer)'
|
|
5617
|
+
const tail = snapshot.state === 'assumed' ? ' (placed, not from the drawings)' : snapshot.state === 'answered' ? ' (your earlier answer)'
|
|
5618
|
+
// #2521: chosen by the AI in a Quick model build. Said plainly, so the person never takes it for a drawn height.
|
|
5619
|
+
: snapshot.state === 'decided' ? ' (chosen by the AI in the Quick model, not from the drawings or you)' : '';
|
|
3603
5620
|
return `In the model when asked: ${value}${tail}.`;
|
|
3604
5621
|
};
|
|
3605
5622
|
const HEIGHT_PROPOSED_TEXT = 'Proposed in the review; the model changes only if you accept it there.';
|
|
@@ -5316,7 +7333,11 @@
|
|
|
5316
7333
|
caret = { start: focusedNode.selectionStart, end: focusedNode.selectionEnd, direction: focusedNode.selectionDirection || 'none' };
|
|
5317
7334
|
}
|
|
5318
7335
|
} catch { caret = null; } // a checkbox or radio has no caret, and some engines throw on reading it
|
|
5319
|
-
|
|
7336
|
+
// A reused card node is detached and re-attached here, and a detached element forgets its scroll: the height
|
|
7337
|
+
// card's lists, and the readiness card's own scroll area and table (#2439), are noted and put back below.
|
|
7338
|
+
for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows, .ai-chat-readiness-body, .ai-chat-readiness-table')) {
|
|
7339
|
+
list.keptScrollTop = list.scrollTop; list.keptScrollLeft = list.scrollLeft;
|
|
7340
|
+
}
|
|
5320
7341
|
ui.feed.replaceChildren();
|
|
5321
7342
|
if (!state.events.length) {
|
|
5322
7343
|
ui.feed.append(emptyFeedNotice());
|
|
@@ -5331,15 +7352,20 @@
|
|
|
5331
7352
|
ui.feed.append(renderMessage(assistant.event, 'assistant', rendered.text, rendered.streaming));
|
|
5332
7353
|
assistant = null;
|
|
5333
7354
|
};
|
|
5334
|
-
const flushLinks = () => { if (links.length) { ui.feed.append(...links
|
|
7355
|
+
const flushLinks = () => { if (links.length) { ui.feed.append(...receiptFold(links)); links = []; } };
|
|
5335
7356
|
for (const event of state.events) {
|
|
5336
7357
|
if (links.length && event.turnId !== links[0].turnId) { flushAssistant(); flushLinks(); }
|
|
5337
7358
|
if (event.type === 'assistant-message' && event.payload?.delta) {
|
|
5338
7359
|
// Codex keeps a stable item id while Claude's SDK may assign one per stream packet.
|
|
5339
|
-
//
|
|
5340
|
-
//
|
|
7360
|
+
// Same-turn deltas stay in one visible answer. Tools separate progress paragraphs;
|
|
7361
|
+
// conversation events that render their own prose still flush the block below.
|
|
5341
7362
|
if (assistant && assistant.event.turnId === event.turnId) {
|
|
5342
7363
|
assistant.event = event;
|
|
7364
|
+
// A tool separates progress paragraphs, whereas adjacent provider packets may split a word.
|
|
7365
|
+
if (assistant.afterTool && payloadText(event)) {
|
|
7366
|
+
if (assistant.text && !/\n\s*$/.test(assistant.text) && !/^\s*\n/.test(payloadText(event))) assistant.text += '\n\n';
|
|
7367
|
+
assistant.afterTool = false;
|
|
7368
|
+
}
|
|
5343
7369
|
assistant.text += payloadText(event);
|
|
5344
7370
|
} else {
|
|
5345
7371
|
flushAssistant();
|
|
@@ -5347,6 +7373,8 @@
|
|
|
5347
7373
|
}
|
|
5348
7374
|
continue;
|
|
5349
7375
|
}
|
|
7376
|
+
if (assistant && event.turnId === assistant.event.turnId && event.type === 'tool'
|
|
7377
|
+
&& !event.payload?.plain && !['agent', 'guide', 'instructor'].includes(event.payload?.tool)) assistant.afterTool = true;
|
|
5350
7378
|
// Something FloLess itself refused during the answer (a file change it declined, a connector it turned away,
|
|
5351
7379
|
// #1890 PR 2b / #1907), written for the person: held and shown under the answer, like the receipts below.
|
|
5352
7380
|
if (event.type === 'tool' && event.payload?.plain === true && !['agent', 'guide', 'instructor'].includes(event.payload?.tool)
|
|
@@ -5375,17 +7403,26 @@
|
|
|
5375
7403
|
if (event.type === 'action-proposal-update') continue;
|
|
5376
7404
|
if (event.type === 'action-proposal' || event.type === 'action-call') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
|
|
5377
7405
|
// #2255: a model view change is written mid-answer while the tool waits, so it is held under the answer too.
|
|
5378
|
-
if (event.type === 'view-command') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
|
|
5379
|
-
|
|
7406
|
+
if (event.type === 'view-command') { links.push({ turnId: event.turnId, node: renderEvent(event), event }); continue; }
|
|
7407
|
+
// #2437 / #2436: an answer's sources are held under it, like the receipts below; one row per answer.
|
|
7408
|
+
if (event.type === 'citation' || event.type === 'knowledge-citation') {
|
|
7409
|
+
const node = event.type === 'citation' ? renderCitationSources(event) : renderLegacyKnowledgeCitation(event);
|
|
7410
|
+
if (node) links.push({ turnId: event.turnId, node });
|
|
7411
|
+
continue;
|
|
7412
|
+
}
|
|
7413
|
+
if (['tool', 'usage', 'attachment', 'compaction', 'state'].includes(event.type)) continue;
|
|
5380
7414
|
// FloLess's own receipts (object links #1653; evidence looks and suggestion cards #1859) are written mid-answer while a tool runs:
|
|
5381
7415
|
// held and shown under the answer, so they never cut one answer into fragments.
|
|
5382
|
-
if (event.type === 'chat-subjects' || event.type === 'evidence-read' || event.type === 'filter-proposal') { links.push({ turnId: event.turnId, node: renderEvent(event) }); continue; }
|
|
7416
|
+
if (event.type === 'chat-subjects' || event.type === 'evidence-read' || event.type === 'filter-proposal') { links.push({ turnId: event.turnId, node: renderEvent(event), event }); continue; }
|
|
5383
7417
|
flushAssistant();
|
|
5384
7418
|
const node = renderEvent(event);
|
|
5385
7419
|
if (node) ui.feed.append(node);
|
|
5386
7420
|
}
|
|
5387
7421
|
flushAssistant();
|
|
5388
7422
|
flushLinks();
|
|
7423
|
+
// #2399: an Instructor answer the person keeps talking to offers to continue with tools, under its latest reply.
|
|
7424
|
+
const continueRow = renderInstructorContinue();
|
|
7425
|
+
if (continueRow) ui.feed.append(continueRow);
|
|
5389
7426
|
// A provider can send text before it finishes tools, usage, or its terminal turn signal.
|
|
5390
7427
|
// Keep this fixed activity row visible for the full durable turn so an intermittent stream
|
|
5391
7428
|
// never looks like a failed response. Recovery deliberately has no live indicator.
|
|
@@ -5399,8 +7436,9 @@
|
|
|
5399
7436
|
if (refocused && caret) {
|
|
5400
7437
|
try { refocused.setSelectionRange(caret.start, caret.end, caret.direction); } catch { /* no caret on this control */ }
|
|
5401
7438
|
}
|
|
5402
|
-
for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows')) {
|
|
7439
|
+
for (const list of ui.feed.querySelectorAll('.ai-chat-height-rows, .ai-chat-readiness-body, .ai-chat-readiness-table')) {
|
|
5403
7440
|
if (typeof list.keptScrollTop === 'number' && list.scrollTop !== list.keptScrollTop) list.scrollTop = list.keptScrollTop;
|
|
7441
|
+
if (typeof list.keptScrollLeft === 'number' && list.scrollLeft !== list.keptScrollLeft) list.scrollLeft = list.keptScrollLeft;
|
|
5404
7442
|
}
|
|
5405
7443
|
// Removing a focused control makes the browser lay out the half-built feed, which clamps its scroll near the top.
|
|
5406
7444
|
// Scrolled up, the reader stays where they were.
|
|
@@ -5423,6 +7461,7 @@
|
|
|
5423
7461
|
// a new user is never told to "sign in first" with nowhere to do it.
|
|
5424
7462
|
function emptyFeedNotice() {
|
|
5425
7463
|
const empty = document.createElement('div'); empty.className = 'ai-chat-empty';
|
|
7464
|
+
if (typeof chatLandingScene === 'function') chatLandingScene(empty, `chat:${state.chat?.chatId || ''}`);
|
|
5426
7465
|
const strong = document.createElement('strong');
|
|
5427
7466
|
const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy';
|
|
5428
7467
|
const provider = state.chat?.provider;
|
|
@@ -5457,10 +7496,12 @@
|
|
|
5457
7496
|
: 'You can write your first message now. Send becomes available when setup finishes.';
|
|
5458
7497
|
empty.append(strong, copy);
|
|
5459
7498
|
} else {
|
|
5460
|
-
|
|
5461
|
-
|
|
7499
|
+
// A FloLess sign-in or subscription refusal is about FloLess, not the AI app: say so, and offer no AI-app sign-in.
|
|
7500
|
+
const accountAccess = Boolean(state.capability?.accountAccess);
|
|
7501
|
+
strong.textContent = accountAccess ? 'FloLess account needs attention' : `${label} needs attention`;
|
|
7502
|
+
copy.textContent = capabilityMessage(provider, state.capability?.reason, accountAccess);
|
|
5462
7503
|
empty.append(strong, copy);
|
|
5463
|
-
if (signInNeeded(state.capability?.reason)) empty.append(emptySignInButton(label, false));
|
|
7504
|
+
if (!accountAccess && signInNeeded(state.capability?.reason)) empty.append(emptySignInButton(label, false));
|
|
5464
7505
|
}
|
|
5465
7506
|
return empty;
|
|
5466
7507
|
}
|
|
@@ -5628,6 +7669,12 @@
|
|
|
5628
7669
|
const commandAt = approval.protectedCommand === true && !connector ? approval.summary.indexOf('\nCommand: ') : -1;
|
|
5629
7670
|
if (commandAt >= 0) {
|
|
5630
7671
|
copy.textContent = approval.summary.slice(0, commandAt);
|
|
7672
|
+
// #2224 item 1: why it asks although actions may be approved for this request or conversation.
|
|
7673
|
+
const why = document.createElement('p');
|
|
7674
|
+
why.className = 'ai-chat-approval-note';
|
|
7675
|
+
why.textContent = 'This command names, or could match, a workflow’s approved lock, record or conversations, so FloLess '
|
|
7676
|
+
+ 'asks every time, even when actions are approved for this request or conversation.';
|
|
7677
|
+
nodes.push(why);
|
|
5631
7678
|
const block = document.createElement('pre');
|
|
5632
7679
|
block.className = 'ai-chat-approval-cmd';
|
|
5633
7680
|
block.tabIndex = 0;
|
|
@@ -6190,7 +8237,12 @@
|
|
|
6190
8237
|
const create = approval.create && typeof approval.create === 'object' ? approval.create : null;
|
|
6191
8238
|
const check = approval.connectionCheck && typeof approval.connectionCheck === 'object' ? approval.connectionCheck : null;
|
|
6192
8239
|
const connector = approval.connector && typeof approval.connector === 'object' ? approval.connector : null;
|
|
6193
|
-
|
|
8240
|
+
// #2196 follow-up: a command that names, or could match, a workflow's records is outside every grant. Its card keeps
|
|
8241
|
+
// the full set of choices (owner ruling 7), and the wider ones say plainly that they approve THIS command once and
|
|
8242
|
+
// cover other actions only.
|
|
8243
|
+
const protectedCommand = approval.protectedCommand === true
|
|
8244
|
+
? { protectedNote: ' This command is approved once: a command that names or could match a workflow’s records still asks every time.' } : {};
|
|
8245
|
+
const base = { requestRevision, decision: 'allow-chat', warning: '', ...protectedCommand };
|
|
6194
8246
|
const PROTECTED_NOTE = ' A workflow’s own records (its .lock, settings and conversations) always ask.';
|
|
6195
8247
|
if (change) {
|
|
6196
8248
|
if (change.refused || change.busy) return null;
|
|
@@ -6635,9 +8687,274 @@
|
|
|
6635
8687
|
return true;
|
|
6636
8688
|
}
|
|
6637
8689
|
|
|
8690
|
+
/* ---- #2438: @-mentions ------------------------------------------------------------------------------------------------
|
|
8691
|
+
* Typing @ in a project conversation lists the project's members (by the marks its drawings gave them) and its sheets;
|
|
8692
|
+
* a pick becomes a chip above the message box and goes with the next message as identity only — the server resolves it
|
|
8693
|
+
* and says to the AI what it is. Two members sharing a mark are two rows, each saying how to tell it apart. The list
|
|
8694
|
+
* shares the slash list's box and placement; the message box keeps focus throughout (aria-activedescendant).
|
|
8695
|
+
*/
|
|
8696
|
+
function currentMentions() {
|
|
8697
|
+
return state.mentions?.[state.chat?.chatId] || [];
|
|
8698
|
+
}
|
|
8699
|
+
/** Each conversation keeps its own picks: switching away and back finds them where they were. */
|
|
8700
|
+
function setMentions(items) { if (state.chat?.chatId) state.mentions = { ...state.mentions, [state.chat.chatId]: items }; }
|
|
8701
|
+
function mentionKey(pick) {
|
|
8702
|
+
return pick.kind === 'member' ? JSON.stringify(['member', pick.id, pick.mark]) : JSON.stringify(['sheet', pick.sheet, pick.pageId, pick.sourceHash]);
|
|
8703
|
+
}
|
|
8704
|
+
|
|
8705
|
+
/**
|
|
8706
|
+
* What tells one ref from another of the same name: its profile, the views it was read on, its id; a sheet's page.
|
|
8707
|
+
* `all` lists every view (the tooltip); the row shows two and counts the rest, so it never wraps into a paragraph.
|
|
8708
|
+
*/
|
|
8709
|
+
function refDetail(ref, all = false) {
|
|
8710
|
+
if (ref.kind === 'sheet') return [`Sheet${ref.pageNumber ? `, page ${ref.pageNumber}` : ''}`, `source ${String(ref.sourceHash).slice(0, 8)}`].join(' · ');
|
|
8711
|
+
const named = (ref.views || []).map((view) => (view.title ? `${view.sheet} ${view.title}` : view.sheet));
|
|
8712
|
+
const shown = all ? named : named.slice(0, 2);
|
|
8713
|
+
const views = shown.join(', ') + (named.length > shown.length ? ` +${named.length - shown.length} more` : '');
|
|
8714
|
+
return [ref.mark ? null : 'No mark', ref.profile, views ? `on ${views}` : null, `id ${ref.id}`].filter(Boolean).join(' · ');
|
|
8715
|
+
}
|
|
8716
|
+
function mentionOf(ref) {
|
|
8717
|
+
const pick = ref.kind === 'member'
|
|
8718
|
+
? { kind: 'member', id: ref.id, mark: ref.mark ?? null }
|
|
8719
|
+
: { kind: 'sheet', sheet: ref.sheet, pageId: ref.pageId, sourceHash: ref.sourceHash };
|
|
8720
|
+
const label = ref.kind === 'member' ? (ref.mark || ref.id) : ref.sheet;
|
|
8721
|
+
return { key: mentionKey(pick), pick, label, tip: `${ref.kind === 'member' ? 'Member' : 'Sheet'} ${label} · ${refDetail(ref, true)}` };
|
|
8722
|
+
}
|
|
8723
|
+
|
|
8724
|
+
/** Why a mention did not resolve, in a few words, by what it is. */
|
|
8725
|
+
function mentionNotFound(mention) {
|
|
8726
|
+
if (mention.reason === 'not-found') return mention.kind === 'sheet' ? 'not in this project' : 'not in the model';
|
|
8727
|
+
if (mention.reason === 'unreadable') return 'could not be checked';
|
|
8728
|
+
if (mention.reason === 'no-model') return 'no model yet';
|
|
8729
|
+
if (mention.reason === 'not-steel') return 'not checked, not a steel project';
|
|
8730
|
+
return 'not found';
|
|
8731
|
+
}
|
|
8732
|
+
|
|
8733
|
+
/**
|
|
8734
|
+
* The line under a sent message naming what was mentioned, and what FloLess could not find or check: `text` to show,
|
|
8735
|
+
* `spoken` with each reason as a sentence, so a reason is never heard as part of a mark.
|
|
8736
|
+
*/
|
|
8737
|
+
function mentionsLine(mentions) {
|
|
8738
|
+
if (!Array.isArray(mentions) || !mentions.length) return '';
|
|
8739
|
+
const listed = mentions.slice(0, 6);
|
|
8740
|
+
const name = (m) => m.label || m.mark || m.id || m.sheet;
|
|
8741
|
+
const more = mentions.length > listed.length ? ` and ${mentions.length - listed.length} more` : '';
|
|
8742
|
+
const text = `Mentioned: ${listed.map((m) => `${name(m)}${m.resolved === false ? ` (${mentionNotFound(m)})` : ''}`).join(', ')}${more}`;
|
|
8743
|
+
const spoken = `Mentioned: ${listed.map(name).join(', ')}${more}.`
|
|
8744
|
+
+ listed.filter((m) => m.resolved === false).map((m) => ` ${name(m)}: ${mentionNotFound(m)}.`).join('');
|
|
8745
|
+
return { text, spoken };
|
|
8746
|
+
}
|
|
8747
|
+
|
|
8748
|
+
function paintMentionChips() {
|
|
8749
|
+
const items = currentMentions();
|
|
8750
|
+
for (const item of items) {
|
|
8751
|
+
const chip = document.createElement('span'); chip.className = 'ai-chat-attachment ai-chat-mention';
|
|
8752
|
+
chip.dataset.mentionKey = item.key;
|
|
8753
|
+
const label = button(`@${item.label}`, 'shell.chat-mention', 'ai-chat-subjects-label');
|
|
8754
|
+
label.dataset.commandInstanceLabel = item.label;
|
|
8755
|
+
label.dataset.tip = `${item.tip}. Goes with your next message.`;
|
|
8756
|
+
label.setAttribute('aria-label', `${item.tip}, mentioned in your next message`);
|
|
8757
|
+
label.addEventListener('click', () => announce(label.dataset.tip));
|
|
8758
|
+
const remove = button('×', `shell.chat-mention-remove#${item.key}`);
|
|
8759
|
+
remove.dataset.commandInstanceLabel = item.label;
|
|
8760
|
+
remove.setAttribute('aria-label', `Leave ${item.label} out of your next message`);
|
|
8761
|
+
remove.dataset.tip = 'Leave out of the next message';
|
|
8762
|
+
remove.addEventListener('click', () => {
|
|
8763
|
+
setMentions(currentMentions().filter((m) => m.key !== item.key));
|
|
8764
|
+
paintAttachments(); updateSendState(); ui.input.focus();
|
|
8765
|
+
announce(`${item.label} will not go with your next message.`);
|
|
8766
|
+
});
|
|
8767
|
+
chip.append(label, remove);
|
|
8768
|
+
ui.attachments.append(chip);
|
|
8769
|
+
}
|
|
8770
|
+
return items.length > 0;
|
|
8771
|
+
}
|
|
8772
|
+
|
|
8773
|
+
/** The @token the caret sits at the end of, or null. A selection, or a caret elsewhere, is no token. */
|
|
8774
|
+
function mentionToken() {
|
|
8775
|
+
if (state.scope?.owner?.kind !== 'project' || !state.chat) return null;
|
|
8776
|
+
const { selectionStart, selectionEnd, value } = ui.input;
|
|
8777
|
+
if (selectionStart !== selectionEnd) return null;
|
|
8778
|
+
const match = value.slice(0, selectionStart).match(/(?:^|\s)@([^\s@]{0,80})$/u);
|
|
8779
|
+
if (!match) return null;
|
|
8780
|
+
return { start: selectionStart - match[1].length - 1, end: selectionStart, query: match[1] };
|
|
8781
|
+
}
|
|
8782
|
+
|
|
8783
|
+
function closeMentionMenu() {
|
|
8784
|
+
const menu = state.mentionMenu;
|
|
8785
|
+
if (!menu) return;
|
|
8786
|
+
clearTimeout(menu.timer);
|
|
8787
|
+
state.mentionMenu = null;
|
|
8788
|
+
ui.skills.hidden = true; ui.skills.replaceChildren(); ui.skills.classList.remove('is-mentions');
|
|
8789
|
+
ui.skills.removeAttribute('aria-label');
|
|
8790
|
+
ui.input.setAttribute('aria-expanded', 'false'); ui.input.removeAttribute('aria-activedescendant');
|
|
8791
|
+
}
|
|
8792
|
+
|
|
8793
|
+
/** Opens, follows or closes the @ list for where the caret is; true while the list owns the shared box. */
|
|
8794
|
+
function paintMentionMenu() {
|
|
8795
|
+
const token = mentionToken();
|
|
8796
|
+
if (!token) { state.mentionDismissed = null; closeMentionMenu(); return false; }
|
|
8797
|
+
// Dismissed for this @word in THIS conversation only: another conversation's word at the same place opens its own list.
|
|
8798
|
+
if (state.mentionDismissed?.chatId === state.chat.chatId && state.mentionDismissed.start === token.start) { closeMentionMenu(); return false; }
|
|
8799
|
+
let menu = state.mentionMenu;
|
|
8800
|
+
if (!menu || menu.start !== token.start || menu.chatId !== state.chat.chatId) {
|
|
8801
|
+
closeMentionMenu();
|
|
8802
|
+
menu = { start: token.start, chatId: state.chat.chatId, query: null, status: 'loading', refs: [], heldBack: 0, note: '', active: -1, seq: 0, timer: null };
|
|
8803
|
+
state.mentionMenu = menu;
|
|
8804
|
+
}
|
|
8805
|
+
// A new word keeps the rows already shown until its answer comes, so the list does not flash on each letter.
|
|
8806
|
+
if (menu.query !== token.query) {
|
|
8807
|
+
menu.query = token.query;
|
|
8808
|
+
if (menu.status !== 'options') { menu.status = 'loading'; menu.active = -1; }
|
|
8809
|
+
// Rows for an earlier word stay in sight but cannot be picked until this word's answer comes.
|
|
8810
|
+
menu.stale = true;
|
|
8811
|
+
fetchMentionRefs(menu);
|
|
8812
|
+
}
|
|
8813
|
+
renderMentionMenu();
|
|
8814
|
+
return true;
|
|
8815
|
+
}
|
|
8816
|
+
|
|
8817
|
+
function fetchMentionRefs(menu) {
|
|
8818
|
+
clearTimeout(menu.timer);
|
|
8819
|
+
const seq = ++menu.seq;
|
|
8820
|
+
const projectId = state.scope?.owner?.projectId;
|
|
8821
|
+
menu.timer = setTimeout(async () => {
|
|
8822
|
+
let body = null;
|
|
8823
|
+
try { body = await request(`/api/projects/${encodeURIComponent(projectId)}/refs?q=${encodeURIComponent(menu.query)}`); }
|
|
8824
|
+
catch { body = null; }
|
|
8825
|
+
// A newer keystroke, a closed list or another conversation: this answer is for a question nobody is asking now.
|
|
8826
|
+
if (state.mentionMenu !== menu || menu.seq !== seq) return;
|
|
8827
|
+
menu.stale = false;
|
|
8828
|
+
if (!body) { menu.status = 'error'; menu.active = 0; }
|
|
8829
|
+
else if (body.status && body.status !== 'ok') { menu.status = 'note'; menu.note = String(body.note || ''); menu.active = -1; }
|
|
8830
|
+
else {
|
|
8831
|
+
// The row that was active stays active if it is still listed.
|
|
8832
|
+
const was = menu.status === 'options' && menu.refs[menu.active] ? mentionOf(menu.refs[menu.active]).key : null;
|
|
8833
|
+
menu.refs = Array.isArray(body.refs) ? body.refs : [];
|
|
8834
|
+
menu.heldBack = Number(body.heldBack) || 0;
|
|
8835
|
+
menu.status = menu.refs.length ? 'options' : 'empty';
|
|
8836
|
+
const kept = was ? menu.refs.findIndex((ref) => mentionOf(ref).key === was) : -1;
|
|
8837
|
+
menu.active = menu.refs.length ? Math.max(0, kept) : -1;
|
|
8838
|
+
}
|
|
8839
|
+
renderMentionMenu();
|
|
8840
|
+
announce(menu.status === 'options' ? `${menu.refs.length + menu.heldBack} ${menu.refs.length + menu.heldBack === 1 ? 'match' : 'matches'}`
|
|
8841
|
+
: menu.status === 'empty' ? 'No matches' : menu.status === 'error' ? 'FloLess could not list members and sheets' : menu.note);
|
|
8842
|
+
}, 150);
|
|
8843
|
+
}
|
|
8844
|
+
|
|
8845
|
+
function renderMentionMenu() {
|
|
8846
|
+
const menu = state.mentionMenu;
|
|
8847
|
+
if (!menu) return;
|
|
8848
|
+
ui.skills.replaceChildren();
|
|
8849
|
+
ui.skills.classList.add('is-mentions');
|
|
8850
|
+
ui.skills.setAttribute('aria-label', 'Members and sheets you can mention');
|
|
8851
|
+
const status = (text) => {
|
|
8852
|
+
const row = document.createElement('div'); row.className = 'ai-chat-mention-status'; row.setAttribute('role', 'option');
|
|
8853
|
+
row.setAttribute('aria-disabled', 'true'); row.textContent = text; ui.skills.append(row);
|
|
8854
|
+
};
|
|
8855
|
+
let activeId = '';
|
|
8856
|
+
if (menu.status === 'loading') status('Looking for members and sheets…');
|
|
8857
|
+
else if (menu.status === 'note') status(menu.note);
|
|
8858
|
+
else if (menu.status === 'empty') {
|
|
8859
|
+
status(menu.query ? `Nothing in this project is named “${menu.query}”. Type it in your message instead.`
|
|
8860
|
+
: 'This project has no members or sheets to mention yet.');
|
|
8861
|
+
} else if (menu.status === 'error') {
|
|
8862
|
+
status('FloLess could not list this project’s members and sheets just now.');
|
|
8863
|
+
const retry = button('Try again', 'shell.chat-mention-retry', 'ai-chat-choice');
|
|
8864
|
+
retry.id = 'chat-mention-retry'; retry.setAttribute('role', 'option'); retry.setAttribute('aria-selected', 'true');
|
|
8865
|
+
retry.addEventListener('pointerdown', (event) => event.preventDefault());
|
|
8866
|
+
retry.addEventListener('click', () => { menu.status = 'loading'; fetchMentionRefs(menu); renderMentionMenu(); ui.input.focus(); });
|
|
8867
|
+
ui.skills.append(retry);
|
|
8868
|
+
activeId = retry.id;
|
|
8869
|
+
} else {
|
|
8870
|
+
menu.refs.forEach((ref, index) => {
|
|
8871
|
+
const item = mentionOf(ref);
|
|
8872
|
+
const row = button('', `shell.chat-mention-pick#${item.key}`, 'ai-chat-choice ai-chat-mention-option');
|
|
8873
|
+
row.id = `chat-mention-option-${index}`; row.tabIndex = -1;
|
|
8874
|
+
row.setAttribute('role', 'option'); row.setAttribute('aria-selected', String(index === menu.active));
|
|
8875
|
+
row.dataset.commandInstanceLabel = item.label;
|
|
8876
|
+
row.dataset.tip = item.tip;
|
|
8877
|
+
const name = document.createElement('span'); name.className = 'ai-chat-mention-name'; name.textContent = item.label;
|
|
8878
|
+
const meta = document.createElement('small'); meta.className = 'ai-chat-skill-origin'; meta.textContent = refDetail(ref);
|
|
8879
|
+
row.append(name, meta);
|
|
8880
|
+
row.addEventListener('pointerdown', (event) => event.preventDefault()); // the message box keeps focus
|
|
8881
|
+
row.addEventListener('click', () => pickMention(ref));
|
|
8882
|
+
ui.skills.append(row);
|
|
8883
|
+
if (index === menu.active) activeId = row.id;
|
|
8884
|
+
});
|
|
8885
|
+
if (menu.heldBack) status(`${menu.heldBack} more match. Type more of the name to narrow the list.`);
|
|
8886
|
+
}
|
|
8887
|
+
ui.skills.hidden = false;
|
|
8888
|
+
ui.input.setAttribute('aria-controls', ui.skills.id);
|
|
8889
|
+
ui.input.setAttribute('aria-autocomplete', 'list');
|
|
8890
|
+
ui.input.setAttribute('aria-expanded', 'true');
|
|
8891
|
+
if (activeId) {
|
|
8892
|
+
ui.input.setAttribute('aria-activedescendant', activeId);
|
|
8893
|
+
document.getElementById(activeId)?.scrollIntoView?.({ block: 'nearest' });
|
|
8894
|
+
} else ui.input.removeAttribute('aria-activedescendant');
|
|
8895
|
+
placeSkills();
|
|
8896
|
+
}
|
|
8897
|
+
|
|
8898
|
+
function pickMention(ref) {
|
|
8899
|
+
// Rows for an earlier word are in sight but not pickable, by key or by click, until this word is answered.
|
|
8900
|
+
if (state.mentionMenu?.stale) { announce('Still looking. Pick again when the list updates.'); return; }
|
|
8901
|
+
const token = mentionToken();
|
|
8902
|
+
const item = mentionOf(ref);
|
|
8903
|
+
// The @word becomes the plain name, so the message still reads as a sentence; the chip carries which one it is.
|
|
8904
|
+
if (token) ui.input.setRangeText(`${item.label} `, token.start, token.end, 'end');
|
|
8905
|
+
if (!currentMentions().some((m) => m.key === item.key)) setMentions([...currentMentions(), item]);
|
|
8906
|
+
state.mentionDismissed = null;
|
|
8907
|
+
closeMentionMenu();
|
|
8908
|
+
autosize(); saveDraftSoon(); paintAttachments(); updateSendState(); ui.input.focus();
|
|
8909
|
+
announce(`${item.label} will go with your next message. Remove it from the list above the message box.`);
|
|
8910
|
+
}
|
|
8911
|
+
|
|
8912
|
+
/**
|
|
8913
|
+
* A refused message's mentions go back to their own conversation, before any picked there since (never over them),
|
|
8914
|
+
* and are painted at once if that conversation is the one on screen: the next Send must never carry a chip nobody sees.
|
|
8915
|
+
* Nothing is ever dropped here: the box may hold more than one message carries, and Send takes them in turn.
|
|
8916
|
+
*/
|
|
8917
|
+
function restoreRefusedMentions(chatId, items) {
|
|
8918
|
+
const since = state.mentions?.[chatId] || [];
|
|
8919
|
+
state.mentions = { ...state.mentions, [chatId]: [...items, ...since.filter((item) => !items.some((m) => m.key === item.key))] };
|
|
8920
|
+
if (state.chat?.chatId === chatId) { paintAttachments(); updateSendState(); }
|
|
8921
|
+
}
|
|
8922
|
+
|
|
8923
|
+
/** The keys the open @ list takes; everything else, and everything while it is closed, is the message box's. */
|
|
8924
|
+
function handleMentionKey(event) {
|
|
8925
|
+
const menu = state.mentionMenu;
|
|
8926
|
+
if (!menu || ui.skills.hidden || event.isComposing || event.ctrlKey || event.altKey || event.metaKey) return false;
|
|
8927
|
+
// A select-all, a click elsewhere or a caret moved by the mouse leaves no token: the list is stale, and steps aside.
|
|
8928
|
+
if (mentionToken()?.start !== menu.start) { closeMentionMenu(); return false; }
|
|
8929
|
+
const count = menu.status === 'options' ? menu.refs.length : 0;
|
|
8930
|
+
if (event.key === 'ArrowDown' || event.key === 'ArrowUp') {
|
|
8931
|
+
event.preventDefault();
|
|
8932
|
+
if (count) { menu.active = (menu.active + (event.key === 'ArrowDown' ? 1 : -1) + count) % count; renderMentionMenu(); }
|
|
8933
|
+
return true;
|
|
8934
|
+
}
|
|
8935
|
+
if ((event.key === 'Enter' && !event.shiftKey) || (event.key === 'Tab' && !event.shiftKey)) {
|
|
8936
|
+
// Never sends while the list is open: picks the active row, retries, or waits.
|
|
8937
|
+
event.preventDefault();
|
|
8938
|
+
if (menu.stale) { /* still answering this word: nothing to pick yet, and nothing is sent */ }
|
|
8939
|
+
else if (menu.status === 'options' && menu.active >= 0) pickMention(menu.refs[menu.active]);
|
|
8940
|
+
else if (menu.status === 'error') { menu.status = 'loading'; fetchMentionRefs(menu); renderMentionMenu(); }
|
|
8941
|
+
// Nothing to pick: the list steps aside, the word stays as typed, and the next Enter sends.
|
|
8942
|
+
else if (menu.status === 'empty' || menu.status === 'note') { state.mentionDismissed = { chatId: menu.chatId, start: menu.start }; closeMentionMenu(); }
|
|
8943
|
+
return true;
|
|
8944
|
+
}
|
|
8945
|
+
if (event.key === 'Escape') {
|
|
8946
|
+
event.preventDefault();
|
|
8947
|
+
state.mentionDismissed = { chatId: menu.chatId, start: menu.start };
|
|
8948
|
+
closeMentionMenu();
|
|
8949
|
+
return true;
|
|
8950
|
+
}
|
|
8951
|
+
return false;
|
|
8952
|
+
}
|
|
8953
|
+
|
|
6638
8954
|
function paintAttachments() {
|
|
6639
8955
|
ui.attachments.replaceChildren();
|
|
6640
|
-
|
|
8956
|
+
if (state.mentionMenu && state.mentionMenu.chatId !== state.chat?.chatId) closeMentionMenu();
|
|
8957
|
+
const pill = paintSubjectsPill() | paintMentionChips();
|
|
6641
8958
|
// paintAttachControl, not the two lines #1653 had here: it says the same thing but asks the
|
|
6642
8959
|
// SURFACE what may be attached, so the Drawing Filter reads “Attach a picture” (#1681).
|
|
6643
8960
|
paintAttachControl();
|
|
@@ -6674,7 +8991,7 @@
|
|
|
6674
8991
|
});
|
|
6675
8992
|
chip.append(name, remove); ui.attachments.append(chip);
|
|
6676
8993
|
}
|
|
6677
|
-
ui.attachments.hidden = state.attachments.length === 0 && !pill;
|
|
8994
|
+
ui.attachments.hidden = state.attachments.length === 0 && !pill; // the pill includes any mention chips (#2438)
|
|
6678
8995
|
placeSkills();
|
|
6679
8996
|
}
|
|
6680
8997
|
|
|
@@ -6830,8 +9147,64 @@
|
|
|
6830
9147
|
}
|
|
6831
9148
|
}
|
|
6832
9149
|
|
|
9150
|
+
/**
|
|
9151
|
+
* #2399: "Suggest next steps" — the signed-in account's mode, shared by every chat and the ≡ menu (one
|
|
9152
|
+
* `floless:assistant-mode` event keeps them in step). Not this conversation's setting, so it never goes through
|
|
9153
|
+
* saveSettings. The Guide is exempt and says so.
|
|
9154
|
+
*/
|
|
9155
|
+
const SUGGEST_LABELS = { on: 'On', quiet: 'Quiet', off: 'Off' };
|
|
9156
|
+
// Short tags: the picker's meta column is sized for tags (it never wraps). The full meaning is in the row's tooltip.
|
|
9157
|
+
const SUGGEST_META = { on: 'Problems, unfinished, ideas', quiet: 'Problems and unfinished', off: 'No cards' };
|
|
9158
|
+
const assistantMode = window.flolessAssistantMode || (window.flolessAssistantMode = (() => {
|
|
9159
|
+
let current = null; // { mode, recovered } once read
|
|
9160
|
+
let reading = null;
|
|
9161
|
+
const publish = () => window.dispatchEvent(new CustomEvent('floless:assistant-mode', { detail: current }));
|
|
9162
|
+
return {
|
|
9163
|
+
get value() { return current; },
|
|
9164
|
+
async refresh() {
|
|
9165
|
+
reading ??= request('/api/assistant/preference').then((body) => { current = { mode: body.mode, recovered: body.recovered === true }; publish(); })
|
|
9166
|
+
.catch((error) => { console.warn('[assistant] the suggestion setting could not be read:', error); })
|
|
9167
|
+
.finally(() => { reading = null; });
|
|
9168
|
+
return reading;
|
|
9169
|
+
},
|
|
9170
|
+
async set(mode) {
|
|
9171
|
+
try {
|
|
9172
|
+
const body = await request('/api/assistant/preference', { method: 'PUT', body: JSON.stringify({ mode }) });
|
|
9173
|
+
current = { mode: body.mode, recovered: body.recovered === true }; publish();
|
|
9174
|
+
announce(`Suggest next steps: ${SUGGEST_LABELS[body.mode] || body.mode}.`);
|
|
9175
|
+
} catch (error) {
|
|
9176
|
+
announce(error?.message || 'FloLess couldn’t save that just now. Try again in a moment.');
|
|
9177
|
+
}
|
|
9178
|
+
},
|
|
9179
|
+
choices() {
|
|
9180
|
+
return ['on', 'quiet', 'off'].map((mode) => ({
|
|
9181
|
+
id: `suggest:${mode}`, label: SUGGEST_LABELS[mode], meta: SUGGEST_META[mode],
|
|
9182
|
+
selected: current?.mode === mode && !current?.recovered, onPick: () => this.set(mode),
|
|
9183
|
+
}));
|
|
9184
|
+
},
|
|
9185
|
+
};
|
|
9186
|
+
})());
|
|
9187
|
+
|
|
9188
|
+
function paintSuggestSetting() {
|
|
9189
|
+
if (!ui.suggest) return;
|
|
9190
|
+
const value = ui.suggest.querySelector('strong');
|
|
9191
|
+
const guideChat = state.chat?.initiator?.kind === 'guide';
|
|
9192
|
+
const current = assistantMode.value;
|
|
9193
|
+
const text = guideChat ? 'Guide: always on'
|
|
9194
|
+
: current?.recovered ? 'Paused: choose'
|
|
9195
|
+
: current ? SUGGEST_LABELS[current.mode] || 'On' : 'On';
|
|
9196
|
+
if (value.textContent !== text) value.textContent = text;
|
|
9197
|
+
ui.suggest.disabled = guideChat;
|
|
9198
|
+
ui.suggest.dataset.tip = guideChat
|
|
9199
|
+
? 'The Guide always suggests next steps; close it to stop. This setting is for your project, workflow and workspace chats.'
|
|
9200
|
+
: current?.recovered
|
|
9201
|
+
? 'FloLess had to reset your suggestion settings. Suggestions are paused until you choose.'
|
|
9202
|
+
: 'Your account, in every project, workflow and workspace chat. On: problems to fix, unfinished work and ideas. Quiet: only problems and unfinished work. Off: no cards; the AI still knows where the project stands. The Guide always suggests; close it to stop.';
|
|
9203
|
+
}
|
|
9204
|
+
|
|
6833
9205
|
function paintSettings() {
|
|
6834
9206
|
if (ui.scopeControls) paintScopeControl();
|
|
9207
|
+
paintSuggestSetting();
|
|
6835
9208
|
const chat = state.chat;
|
|
6836
9209
|
ui.settingsToggle.disabled = !chat;
|
|
6837
9210
|
const answer = capabilityAnswer(state.capability);
|
|
@@ -6886,7 +9259,7 @@
|
|
|
6886
9259
|
? 'Connected accounts are fixed after the first message. Start a new chat to use another account.'
|
|
6887
9260
|
: !chat ? 'Open a conversation first.'
|
|
6888
9261
|
: chat.activeTurn ? 'Connected accounts cannot change during an active turn.'
|
|
6889
|
-
: !state.capability?.available ? capabilityMessage(chat.provider, state.capability?.reason)
|
|
9262
|
+
: !state.capability?.available ? capabilityMessage(chat.provider, state.capability?.reason, state.capability?.accountAccess)
|
|
6890
9263
|
: '';
|
|
6891
9264
|
ui.integrations.dataset.tip = integrationBlocked || 'Choose which connected account this chat can use';
|
|
6892
9265
|
if (integrationBlocked) ui.integrations.dataset.blockedReason = integrationBlocked;
|
|
@@ -7173,10 +9546,82 @@
|
|
|
7173
9546
|
void writeChatDraft(chatId, state.scope.owner, '').catch(error => report(error, 'Draft was not saved'));
|
|
7174
9547
|
}
|
|
7175
9548
|
|
|
9549
|
+
function closedChatSession() {
|
|
9550
|
+
return Object.assign(new Error('Chat page is closed.'), { code: 'chat-page-closed' });
|
|
9551
|
+
}
|
|
9552
|
+
|
|
9553
|
+
function showSessionRecoveryHint(operation) {
|
|
9554
|
+
const prior = state.sessionRecoveryHint;
|
|
9555
|
+
if (!prior || prior.operation !== operation || !sameScope(prior.scope, prior.generation)) {
|
|
9556
|
+
state.sessionRecoveryHint = { operation, scope: state.scope, generation: state.scopeGeneration, announced: false,
|
|
9557
|
+
message: 'FloLess is finishing project recovery. Chat will open automatically when it’s ready. If this continues, open Workspaces and choose Review folders.' };
|
|
9558
|
+
}
|
|
9559
|
+
clearReport();
|
|
9560
|
+
}
|
|
9561
|
+
|
|
9562
|
+
function clearSessionRecoveryHint(operation) {
|
|
9563
|
+
const notice = state.sessionRecoveryHint;
|
|
9564
|
+
if (!notice || notice.operation !== operation) return;
|
|
9565
|
+
state.sessionRecoveryHint = null;
|
|
9566
|
+
if (!sameScope(notice.scope, notice.generation)) return;
|
|
9567
|
+
if (ui.status.textContent === notice.message) ui.status.textContent = '';
|
|
9568
|
+
if (ui.hint.textContent === notice.message) clearReport();
|
|
9569
|
+
}
|
|
9570
|
+
|
|
9571
|
+
function disposeChatSession() {
|
|
9572
|
+
state.sessionDisposed = true; state.sessionLifecycle += 1; state.sessionReady = false;
|
|
9573
|
+
state.sessionOperation?.cancel();
|
|
9574
|
+
state.sessionOperation = null;
|
|
9575
|
+
}
|
|
9576
|
+
|
|
9577
|
+
function restoreChatSession() {
|
|
9578
|
+
state.sessionDisposed = false; state.sessionLifecycle += 1; state.sessionReady = false;
|
|
9579
|
+
void loadScope(state.scope);
|
|
9580
|
+
}
|
|
9581
|
+
|
|
7176
9582
|
async function ensureSession() {
|
|
7177
|
-
if (state.
|
|
7178
|
-
|
|
7179
|
-
|
|
9583
|
+
if (state.sessionDisposed) throw closedChatSession();
|
|
9584
|
+
if (state.sessionOperation) {
|
|
9585
|
+
if (state.sessionOperation.waiting) showSessionRecoveryHint(state.sessionOperation);
|
|
9586
|
+
return state.sessionOperation.promise;
|
|
9587
|
+
}
|
|
9588
|
+
// Readiness is server-owned. Recheck even a cached cookie after a server restart.
|
|
9589
|
+
const operation = { generation: state.sessionLifecycle, waiting: false, timer: null, promise: null, cancel: null };
|
|
9590
|
+
let cancel;
|
|
9591
|
+
const cancelled = new Promise((_, reject) => { cancel = () => reject(closedChatSession()); });
|
|
9592
|
+
operation.cancel = () => { clearTimeout(operation.timer); cancel(); };
|
|
9593
|
+
const current = () => {
|
|
9594
|
+
if (state.sessionDisposed || operation.generation !== state.sessionLifecycle) throw closedChatSession();
|
|
9595
|
+
};
|
|
9596
|
+
state.sessionOperation = operation;
|
|
9597
|
+
operation.promise = Promise.resolve().then(async () => {
|
|
9598
|
+
try {
|
|
9599
|
+
for (;;) {
|
|
9600
|
+
current();
|
|
9601
|
+
const session = await Promise.race([request('/api/chat/session'), cancelled]);
|
|
9602
|
+
current();
|
|
9603
|
+
if (session?.ready === true) {
|
|
9604
|
+
state.sessionReady = true;
|
|
9605
|
+
clearSessionRecoveryHint(operation);
|
|
9606
|
+
return;
|
|
9607
|
+
}
|
|
9608
|
+
if (session?.ready !== false) throw plainError('FloLess could not open Chat just now. Try again in a moment.');
|
|
9609
|
+
state.sessionReady = false; operation.waiting = true;
|
|
9610
|
+
showSessionRecoveryHint(operation);
|
|
9611
|
+
await Promise.race([new Promise((resolve) => { operation.timer = setTimeout(resolve, 1000); }), cancelled]);
|
|
9612
|
+
operation.timer = null;
|
|
9613
|
+
current();
|
|
9614
|
+
}
|
|
9615
|
+
} catch (error) {
|
|
9616
|
+
if (operation.generation === state.sessionLifecycle) state.sessionReady = false;
|
|
9617
|
+
clearSessionRecoveryHint(operation);
|
|
9618
|
+
throw error;
|
|
9619
|
+
} finally {
|
|
9620
|
+
clearTimeout(operation.timer);
|
|
9621
|
+
if (state.sessionOperation === operation) state.sessionOperation = null;
|
|
9622
|
+
}
|
|
9623
|
+
});
|
|
9624
|
+
return operation.promise;
|
|
7180
9625
|
}
|
|
7181
9626
|
|
|
7182
9627
|
function sessionNeedsRenewal(error) {
|
|
@@ -7190,7 +9635,10 @@
|
|
|
7190
9635
|
// Claude or Codex as "not ready".
|
|
7191
9636
|
return await request(`/api/chat/providers/${chat.provider}?${ownerQuery()}&chatId=${encodeURIComponent(chat.chatId)}`);
|
|
7192
9637
|
} catch (error) {
|
|
7193
|
-
|
|
9638
|
+
// A FloLess sign-in or subscription refusal is not the AI app's sign-in: kept apart so the readiness copy
|
|
9639
|
+
// shows it as written and never offers a Claude or Codex sign-in for it.
|
|
9640
|
+
const accountAccess = Boolean(window.flolessBridge?.accountAccessText?.(error));
|
|
9641
|
+
return { provider: chat.provider, available: false, models: [], skills: [], reason: errorMessage(error), readFailed: true, accountAccess };
|
|
7194
9642
|
}
|
|
7195
9643
|
}
|
|
7196
9644
|
|
|
@@ -7223,6 +9671,7 @@
|
|
|
7223
9671
|
if (!sessionNeedsRenewal(error)) throw error;
|
|
7224
9672
|
state.sessionReady = false;
|
|
7225
9673
|
await ensureSession();
|
|
9674
|
+
if (!sameChat(snapshot)) return;
|
|
7226
9675
|
chat = await request(path);
|
|
7227
9676
|
}
|
|
7228
9677
|
if (!sameChat(snapshot)) return;
|
|
@@ -7264,7 +9713,7 @@
|
|
|
7264
9713
|
const copy = document.createElement('div'); copy.className = 'ai-chat-empty-copy'; copy.textContent = listed
|
|
7265
9714
|
? `Loading “${listed.title}”…`
|
|
7266
9715
|
: 'Loading the selected conversation…';
|
|
7267
|
-
loading.append(strong, copy); ui.feed.append(loading);
|
|
9716
|
+
loading.append(strong, copy); if (typeof chatLandingScene === 'function') chatLandingScene(loading, `chat:${chatId}`); ui.feed.append(loading);
|
|
7268
9717
|
paintHistory(); paintSettings(); paintRecovery();
|
|
7269
9718
|
}
|
|
7270
9719
|
|
|
@@ -7447,6 +9896,7 @@
|
|
|
7447
9896
|
setBusy(true);
|
|
7448
9897
|
try {
|
|
7449
9898
|
await ensureSession();
|
|
9899
|
+
if (generation !== state.scopeGeneration) return;
|
|
7450
9900
|
const result = await request(`/api/chat/conversations?${ownerQuery(scope.owner)}`);
|
|
7451
9901
|
if (generation !== state.scopeGeneration) return;
|
|
7452
9902
|
state.chats = result.chats || [];
|
|
@@ -7700,7 +10150,7 @@
|
|
|
7700
10150
|
|
|
7701
10151
|
function closePicker() {
|
|
7702
10152
|
state.picker = null; state.pickerOpener = null; ui.picker.hidden = true; ui.picker.replaceChildren();
|
|
7703
|
-
for (const control of [ui.model, ui.effort, ui.permission, ui.integrations]) control
|
|
10153
|
+
for (const control of [ui.model, ui.effort, ui.permission, ui.suggest, ui.integrations]) control?.setAttribute('aria-expanded', 'false');
|
|
7704
10154
|
}
|
|
7705
10155
|
|
|
7706
10156
|
function closePickerOnEscape(event) {
|
|
@@ -7723,7 +10173,8 @@
|
|
|
7723
10173
|
const label = document.createElement('span'); label.textContent = choice.label;
|
|
7724
10174
|
row.append(label);
|
|
7725
10175
|
if (choice.meta) { const meta = document.createElement('small'); meta.textContent = choice.meta; row.append(meta); }
|
|
7726
|
-
|
|
10176
|
+
// A choice that is not this conversation's own setting (#2399: the account's suggestion mode) saves itself.
|
|
10177
|
+
row.addEventListener('click', async () => { closePicker(); if (choice.onPick) await choice.onPick(); else await saveSettings(choice.patch); anchor.focus(); });
|
|
7727
10178
|
ui.picker.append(row);
|
|
7728
10179
|
}
|
|
7729
10180
|
ui.picker.hidden = false; anchor.setAttribute('aria-expanded', 'true');
|
|
@@ -7731,6 +10182,30 @@
|
|
|
7731
10182
|
selected?.focus();
|
|
7732
10183
|
}
|
|
7733
10184
|
|
|
10185
|
+
/**
|
|
10186
|
+
* #2399: "Continue with tools" under an answer-only (Instructor) chat's latest reply, once the person has typed a
|
|
10187
|
+
* follow-up — the moment a no-tools answer starts to get in their way. FloLess draws it, never the AI (that chat has
|
|
10188
|
+
* no tools). It opens the existing confirmation (confirmInstructorRelease) with the least widening, Read only; the
|
|
10189
|
+
* Access row stays the place for anything wider. Hidden while a reply is running.
|
|
10190
|
+
*/
|
|
10191
|
+
function renderInstructorContinue() {
|
|
10192
|
+
const chat = state.chat;
|
|
10193
|
+
if (!isInstructorAnswer(chat) || turnIsVisiblyActive()) return null;
|
|
10194
|
+
const asked = state.events.filter((event) => event.type === 'user-message').length;
|
|
10195
|
+
const answered = state.events.some((event) => event.type === 'assistant-message');
|
|
10196
|
+
if (asked < 2 || !answered) return null;
|
|
10197
|
+
const row = document.createElement('div');
|
|
10198
|
+
row.className = 'ai-chat-request-actions ai-chat-instructor-continue';
|
|
10199
|
+
const note = document.createElement('span');
|
|
10200
|
+
note.className = 'ai-chat-instructor-continue-note';
|
|
10201
|
+
note.textContent = 'This chat answers without tools.';
|
|
10202
|
+
const go = button('Continue with tools…', 'shell.chat-instructor-continue');
|
|
10203
|
+
go.dataset.tip = 'Lets the AI read files and use tools in this chat. FloLess asks first.';
|
|
10204
|
+
go.addEventListener('click', () => { void saveSettings({ permissionProfile: 'read-only' }).finally(() => { if (go.isConnected) go.focus(); }); });
|
|
10205
|
+
row.append(note, go);
|
|
10206
|
+
return row;
|
|
10207
|
+
}
|
|
10208
|
+
|
|
7734
10209
|
/** #2059: an Instructor-started conversation the person has not widened: its AI answers with no tools. */
|
|
7735
10210
|
function isInstructorAnswer(chat) {
|
|
7736
10211
|
// The server's rule (chatIsInstructorAnswer): durable facts only, never the stored settings.
|
|
@@ -8087,7 +10562,8 @@
|
|
|
8087
10562
|
}
|
|
8088
10563
|
}
|
|
8089
10564
|
ui.send.disabled = state.loading || state.followupSubmitting || Boolean(state.followupUnknownId) || hasUnknownFollowup() || uploading || !state.chat || blocked || frozen
|
|
8090
|
-
|| (!ui.input.value.trim() && state.attachments.length === 0
|
|
10565
|
+
|| (!ui.input.value.trim() && state.attachments.length === 0
|
|
10566
|
+
&& !(state.mentions?.[state.chat?.chatId]?.length)) || settingUp;
|
|
8091
10567
|
if (moving) ui.send.disabled = true;
|
|
8092
10568
|
// The paperclip is the same on every surface, the Drawing Filter included (#1681, #1859): a message
|
|
8093
10569
|
// there carries the filter's context AND whatever the person attached, under the general rules only.
|
|
@@ -8843,6 +11319,13 @@
|
|
|
8843
11319
|
}
|
|
8844
11320
|
const snapshot = captureChat();
|
|
8845
11321
|
if (!snapshot) return given ? givenNotSent() : undefined;
|
|
11322
|
+
// #2438: what the person mentioned rides with the box's message too, decided at the click. Inline, not the helpers:
|
|
11323
|
+
// several harnesses run this function on its own.
|
|
11324
|
+
const liveMentions = () => (state.mentions?.[state.chat?.chatId] || []);
|
|
11325
|
+
// One message carries at most 20 (the server's limit); any more stay in the box, as chips, for the next message.
|
|
11326
|
+
const mentionItems = given ? [] : liveMentions().slice(0, 20);
|
|
11327
|
+
const mentionsField = mentionItems.length ? { mentions: mentionItems.map((item) => item.pick) } : {};
|
|
11328
|
+
const mentionsKey = (items) => items.map((item) => item.key).join('\n');
|
|
8846
11329
|
// Bind a carried-over Tekla library first; a refused binding keeps the message unsent.
|
|
8847
11330
|
if (!(await bindPendingTeklaRead(snapshot))) return given ? givenNotSent('Wait for the Tekla library change to finish, then send your answer again.') : undefined;
|
|
8848
11331
|
const text = given ? given.text : ui.input.value.trim();
|
|
@@ -8850,20 +11333,22 @@
|
|
|
8850
11333
|
const chatId = snapshot.chatId;
|
|
8851
11334
|
const attachmentIds = (given ? given.attachments : state.attachments).map((item) => item.attachmentId);
|
|
8852
11335
|
// #2061: the message as it was asked about, should the project turn out to be busy (see askIfProjectBusy).
|
|
8853
|
-
const busyMessage = { chatId, text, attachmentIds, subjectsField, filterField: filterContext.field };
|
|
11336
|
+
const busyMessage = { chatId, text, attachmentIds, subjectsField, filterField: filterContext.field, mentionsField };
|
|
8854
11337
|
// The busy-project question and its wait send what is in the box; an answer written elsewhere is told the refusal instead.
|
|
8855
11338
|
const askedBusy = !sendOverride && !given && await projectBusyBeforeSend(snapshot, busyMessage);
|
|
8856
11339
|
if (askedBusy || !sameChat(snapshot)) return given ? givenNotSent() : undefined;
|
|
8857
11340
|
// Edited while FloLess checked — or already sent by an earlier click, which empties the box — nothing is sent over
|
|
8858
11341
|
// the box's text now; it stays for the next Send.
|
|
8859
|
-
if (!given && (ui.input.value.trim() !== text || JSON.stringify(state.attachments.map((item) => item.attachmentId)) !== JSON.stringify(attachmentIds)
|
|
11342
|
+
if (!given && (ui.input.value.trim() !== text || JSON.stringify(state.attachments.map((item) => item.attachmentId)) !== JSON.stringify(attachmentIds)
|
|
11343
|
+
|| mentionsKey(liveMentions().slice(0, 20)) !== mentionsKey(mentionItems))) return;
|
|
8860
11344
|
const clientSubmissionId = crypto.randomUUID();
|
|
8861
11345
|
const previousChat = state.chat;
|
|
8862
11346
|
const previousAttachments = state.attachments;
|
|
8863
11347
|
const optimisticEvent = {
|
|
8864
11348
|
eventId: `local:${clientSubmissionId}`, sequence: Math.max(0, ...state.events.map((event) => Number(event.sequence) || 0)) + .5,
|
|
8865
11349
|
chatId, turnId: clientSubmissionId, clientSubmissionId, providerItemId: null, type: 'user-message',
|
|
8866
|
-
payload: { text, attachmentIds, ...subjectsField
|
|
11350
|
+
payload: { text, attachmentIds, ...subjectsField, ...(mentionItems.length ? { mentions: mentionItems.map((m) => ({ ...m.pick, label: m.label, resolved: true })) } : {}) },
|
|
11351
|
+
createdAt: new Date().toISOString(), optimistic: true,
|
|
8867
11352
|
};
|
|
8868
11353
|
if (!given) {
|
|
8869
11354
|
clearTimeout(state.draftTimer);
|
|
@@ -8873,8 +11358,10 @@
|
|
|
8873
11358
|
state.pendingSubmissionId = clientSubmissionId;
|
|
8874
11359
|
state.events.push(optimisticEvent);
|
|
8875
11360
|
state.chat = { ...previousChat, draft: given ? previousChat.draft : '', state: 'starting', activeTurn: { turnId: clientSubmissionId, local: true } };
|
|
8876
|
-
if (!given) { ui.input.value = ''; autosize(); state.attachments = []; paintAttachments(); }
|
|
8877
|
-
setBusy(true); paintConversation();
|
|
11361
|
+
if (!given) { ui.input.value = ''; autosize(); state.attachments = []; if (mentionItems.length) state.mentions = { ...state.mentions, [chatId]: liveMentions().slice(20) }; paintAttachments(); }
|
|
11362
|
+
setBusy(true); paintConversation();
|
|
11363
|
+
const mentionsLeft = given ? 0 : liveMentions().length;
|
|
11364
|
+
announce(mentionsLeft ? `Message sent. ${mentionsLeft} more ${mentionsLeft === 1 ? 'mention stays' : 'mentions stay'} above the box for your next message: one message carries up to 20.` : 'Message sent.');
|
|
8878
11365
|
try {
|
|
8879
11366
|
// A debounced save already in flight must finish before the server clears
|
|
8880
11367
|
// the draft while admitting this message.
|
|
@@ -8884,7 +11371,7 @@
|
|
|
8884
11371
|
// The server alone appends this context to the provider copy. The submitted text and
|
|
8885
11372
|
// durable transcript must remain exactly what the user typed.
|
|
8886
11373
|
owner: snapshot.scope.owner, clientSubmissionId, text, displayText: text, uiContext, attachmentIds,
|
|
8887
|
-
modifying: previousChat.settings.permissionProfile !== 'read-only', ...subjectsField, ...filterContext.field,
|
|
11374
|
+
modifying: previousChat.settings.permissionProfile !== 'read-only', ...subjectsField, ...mentionsField, ...filterContext.field,
|
|
8888
11375
|
// #2061: the person chose "Send my message now" over a request that was waiting first.
|
|
8889
11376
|
...(sendOverride ? { overrideWaiting: true } : {}),
|
|
8890
11377
|
// #2223 Revision 7: a message written on a card leaves the box's saved draft as it is.
|
|
@@ -8915,7 +11402,11 @@
|
|
|
8915
11402
|
} catch (error) {
|
|
8916
11403
|
if (!sameChat(snapshot)) {
|
|
8917
11404
|
if (given) return givenNotSent();
|
|
8918
|
-
if (initialTurnDefinitelyRefused(error))
|
|
11405
|
+
if (initialTurnDefinitelyRefused(error)) {
|
|
11406
|
+
await restoreBackgroundDraft(snapshot, text, clientSubmissionId);
|
|
11407
|
+
// #2438: the mentions go back to their own conversation with the words.
|
|
11408
|
+
if (mentionItems.length) restoreRefusedMentions(chatId, mentionItems);
|
|
11409
|
+
}
|
|
8919
11410
|
return;
|
|
8920
11411
|
}
|
|
8921
11412
|
state.pendingSubmissionId = null;
|
|
@@ -8923,6 +11414,7 @@
|
|
|
8923
11414
|
state.chat = previousChat;
|
|
8924
11415
|
if (given) { paintConversation(); return givenNotSent(givenRefusal(error)); }
|
|
8925
11416
|
state.attachments = previousAttachments;
|
|
11417
|
+
if (mentionItems.length) restoreRefusedMentions(chatId, mentionItems);
|
|
8926
11418
|
ui.input.value = text; autosize(); paintAttachments(); saveDraftSoon(); paintConversation();
|
|
8927
11419
|
// #2061: the project is busy — ask (wait / open it / stop it) instead of only saying it failed. Nothing was sent.
|
|
8928
11420
|
if (!askIfProjectBusy(error, busyMessage)) report(error, 'Message was not sent');
|
|
@@ -8943,14 +11435,15 @@
|
|
|
8943
11435
|
const KNOWLEDGE_STUCK_REMEDY = 'If organizing has stopped, restart FloLess — that clears an organize that already finished. If it still shows as organizing after that, open a terminal outside FloLess (Claude Code or Codex) and ask it to check and recover the stuck knowledge organize for this project, then send again.';
|
|
8944
11436
|
|
|
8945
11437
|
/** What a message means beyond its words: the selected objects and the open Drawing Filter's context. */
|
|
8946
|
-
function projectWaitContext(subjectsField, filterField) {
|
|
8947
|
-
try { return JSON.stringify({ subjects: subjectsField?.subjects ?? null, filter: filterField ?? {} }); }
|
|
11438
|
+
function projectWaitContext(subjectsField, filterField, mentionsField) {
|
|
11439
|
+
try { return JSON.stringify({ subjects: subjectsField?.subjects ?? null, filter: filterField ?? {}, mentions: mentionsField?.mentions ?? null }); }
|
|
8948
11440
|
catch { return ''; }
|
|
8949
11441
|
}
|
|
8950
11442
|
|
|
8951
11443
|
function currentProjectWaitContext() {
|
|
8952
11444
|
const subjects = subjectsPayload(composerSelection());
|
|
8953
|
-
|
|
11445
|
+
const mentioned = (state.mentions?.[state.chat?.chatId] || []).slice(0, 20);
|
|
11446
|
+
return projectWaitContext(subjects ? { subjects } : {}, filterContextForSend().field, mentioned.length ? { mentions: mentioned.map((item) => item.pick) } : {});
|
|
8954
11447
|
}
|
|
8955
11448
|
|
|
8956
11449
|
function holderTitle(holder) {
|
|
@@ -8974,7 +11467,7 @@
|
|
|
8974
11467
|
/** The pending-message record the wait compares against before it sends by itself. */
|
|
8975
11468
|
function busyMessageRecord(message) {
|
|
8976
11469
|
return { chatId: message.chatId, text: message.text, attachmentIds: JSON.stringify(message.attachmentIds),
|
|
8977
|
-
context: projectWaitContext(message.subjectsField, message.filterField) };
|
|
11470
|
+
context: projectWaitContext(message.subjectsField, message.filterField, message.mentionsField) };
|
|
8978
11471
|
}
|
|
8979
11472
|
|
|
8980
11473
|
/**
|
|
@@ -9244,7 +11737,7 @@
|
|
|
9244
11737
|
* usable, which already rules out recovery, an unconfirmed message, an upload and a provider still
|
|
9245
11738
|
* being set up. Otherwise the original notice is shown and the draft stays for the user to decide.
|
|
9246
11739
|
*/
|
|
9247
|
-
async function resendAfterTurnEnded({ snapshot, text, attachmentIds, error, given }) {
|
|
11740
|
+
async function resendAfterTurnEnded({ snapshot, text, attachmentIds, mentionsKey = '', error, given }) {
|
|
9248
11741
|
state.followupSubmitting = true;
|
|
9249
11742
|
updateSendState();
|
|
9250
11743
|
try { await refreshConversation(snapshot.chatId); }
|
|
@@ -9255,7 +11748,8 @@
|
|
|
9255
11748
|
if (given) return !turnIsVisiblyActive() && !givenMessageBlocked();
|
|
9256
11749
|
if (!turnIsVisiblyActive() && !ui.send.disabled
|
|
9257
11750
|
&& ui.input.value.trim() === text
|
|
9258
|
-
&& JSON.stringify(state.attachments.map((item) => item.attachmentId)) === JSON.stringify(attachmentIds)
|
|
11751
|
+
&& JSON.stringify(state.attachments.map((item) => item.attachmentId)) === JSON.stringify(attachmentIds)
|
|
11752
|
+
&& (state.mentions?.[state.chat?.chatId] || []).slice(0, 20).map((item) => item.key).join('\n') === mentionsKey) return true;
|
|
9259
11753
|
report(error, '');
|
|
9260
11754
|
return false;
|
|
9261
11755
|
}
|
|
@@ -9275,7 +11769,10 @@
|
|
|
9275
11769
|
if (!snapshot) return notSent();
|
|
9276
11770
|
const text = given ? given.text : ui.input.value.trim();
|
|
9277
11771
|
const attachmentIds = (given ? given.attachments : state.attachments).map((item) => item.attachmentId);
|
|
9278
|
-
|
|
11772
|
+
// #2438: a follow-up carries what the person mentioned, into the running reply or the next one.
|
|
11773
|
+
// At most 20 go with it (the server's limit); any more stay as chips for the next message.
|
|
11774
|
+
const mentionItems = given ? [] : (state.mentions?.[state.chat?.chatId] || []).slice(0, 20);
|
|
11775
|
+
if (!text && !attachmentIds.length && !mentionItems.length) return notSent();
|
|
9279
11776
|
if (new TextEncoder().encode(text).length > 128 * 1024) {
|
|
9280
11777
|
if (given) return notSent(errorMessage({ code: 'chat-message-too-long' }));
|
|
9281
11778
|
report({ code: 'chat-message-too-long' }, 'Message was not sent');
|
|
@@ -9292,7 +11789,8 @@
|
|
|
9292
11789
|
sequence: Math.max(0, ...state.events.map((event) => Number(event.sequence) || 0)) + .5,
|
|
9293
11790
|
chatId: snapshot.chatId, turnId: state.chat.activeTurn.turnId, clientSubmissionId,
|
|
9294
11791
|
providerItemId: null, type: 'user-message',
|
|
9295
|
-
payload: { text, attachmentIds, followup: true, deliveryState: 'pending'
|
|
11792
|
+
payload: { text, attachmentIds, followup: true, deliveryState: 'pending',
|
|
11793
|
+
...(mentionItems.length ? { mentions: mentionItems.map((m) => ({ ...m.pick, label: m.label, resolved: true })) } : {}) },
|
|
9296
11794
|
createdAt: new Date().toISOString(), optimistic: true,
|
|
9297
11795
|
};
|
|
9298
11796
|
if (!given) {
|
|
@@ -9303,14 +11801,14 @@
|
|
|
9303
11801
|
state.followupSubmitting = true;
|
|
9304
11802
|
if (!given) state.chat.draft = '';
|
|
9305
11803
|
state.events.push(optimisticEvent);
|
|
9306
|
-
if (!given) { ui.input.value = ''; autosize(); state.attachments = []; paintAttachments(); }
|
|
11804
|
+
if (!given) { ui.input.value = ''; autosize(); state.attachments = []; if (mentionItems.length) state.mentions = { ...state.mentions, [snapshot.chatId]: (state.mentions?.[snapshot.chatId] || []).slice(20) }; paintAttachments(); }
|
|
9307
11805
|
paintEvents({ forceBottom: true }); updateSendState();
|
|
9308
11806
|
try {
|
|
9309
11807
|
await state.draftWrites.get(snapshot.chatId)?.catch(() => {});
|
|
9310
11808
|
const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/followups`, {
|
|
9311
11809
|
method: 'POST', body: JSON.stringify({
|
|
9312
11810
|
owner: snapshot.scope.owner, clientSubmissionId, text,
|
|
9313
|
-
uiContext: currentFloLessContext(), attachmentIds, ...filterContext.field,
|
|
11811
|
+
uiContext: currentFloLessContext(), attachmentIds, ...(mentionItems.length ? { mentions: mentionItems.map((item) => item.pick) } : {}), ...filterContext.field,
|
|
9314
11812
|
...(given ? { keepDraft: true } : {}), // #2223 Revision 7: see sendTurn
|
|
9315
11813
|
}),
|
|
9316
11814
|
});
|
|
@@ -9322,19 +11820,24 @@
|
|
|
9322
11820
|
state.chat = result.chat;
|
|
9323
11821
|
// The server kept the saved draft (keepDraft); the box's own words, newer than any save, stay in the box and its record.
|
|
9324
11822
|
if (given) { keepComposerDraft(); outcome = { sent: true }; }
|
|
9325
|
-
|
|
11823
|
+
// #2438: as for a new message, mentions past the 20 one message carries stay above the box, and that is said.
|
|
11824
|
+
const mentionsLeft = given || !mentionItems.length ? 0 : (state.mentions?.[snapshot.chatId] || []).length;
|
|
11825
|
+
const leftNote = mentionsLeft ? ` ${mentionsLeft} more ${mentionsLeft === 1 ? 'mention stays' : 'mentions stay'} above the box for your next message: one message carries up to 20.` : '';
|
|
11826
|
+
announce((result.followup?.deliveryState === 'queued-next'
|
|
9326
11827
|
? 'Message queued for the next AI response.'
|
|
9327
11828
|
: result.followup?.deliveryState === 'accepted'
|
|
9328
11829
|
? 'Follow-up sent to AI.'
|
|
9329
11830
|
: result.followup?.deliveryState === 'not-sent'
|
|
9330
11831
|
? (result.followup?.deliveryFailure?.reason || 'FloLess could not finish saving this message. Use Retry sending if you still want to send it.')
|
|
9331
|
-
: 'Follow-up saved. Waiting for AI.');
|
|
11832
|
+
: 'Follow-up saved. Waiting for AI.') + leftNote);
|
|
9332
11833
|
paintConversation();
|
|
9333
11834
|
} catch (error) {
|
|
9334
11835
|
if (!sameChat(snapshot)) {
|
|
9335
11836
|
if (given && followupDefinitelyRefused(error)) return notSent();
|
|
9336
|
-
if (followupDefinitelyRefused(error))
|
|
9337
|
-
|
|
11837
|
+
if (followupDefinitelyRefused(error)) {
|
|
11838
|
+
await restoreBackgroundDraft(snapshot, text, clientSubmissionId);
|
|
11839
|
+
if (mentionItems.length) restoreRefusedMentions(snapshot.chatId, mentionItems);
|
|
11840
|
+
} else {
|
|
9338
11841
|
optimisticEvent.payload.deliveryState = 'unknown';
|
|
9339
11842
|
state.unknownFollowups.set(snapshot.chatId, { submissionId: clientSubmissionId, text, event: optimisticEvent });
|
|
9340
11843
|
// The user may have selected A → B → A while this request was in flight.
|
|
@@ -9365,6 +11868,8 @@
|
|
|
9365
11868
|
// message, and restore chips only when the server definitely refused it.
|
|
9366
11869
|
if (!given) {
|
|
9367
11870
|
state.attachments = definitiveRefusal ? previousAttachments : [];
|
|
11871
|
+
// Definitely refused: the mentions come back with the words. Uncertain: they stay with the message that may have gone.
|
|
11872
|
+
if (definitiveRefusal && mentionItems.length) restoreRefusedMentions(snapshot.chatId, mentionItems);
|
|
9368
11873
|
ui.input.value = text; autosize(); paintAttachments();
|
|
9369
11874
|
if (definitiveRefusal) saveDraftSoon();
|
|
9370
11875
|
else state.localDraft = { chatId: snapshot.chatId, text };
|
|
@@ -9373,7 +11878,7 @@
|
|
|
9373
11878
|
// The response ended before this arrived (#1616). sendTurn resends it as a new turn, and
|
|
9374
11879
|
// shows this refusal only if it cannot.
|
|
9375
11880
|
if (definitiveRefusal && error?.code === 'chat-followup-refused' && error?.reason === 'chat-turn-stale') {
|
|
9376
|
-
outcome = { outcome: 'turn-ended', snapshot, text, attachmentIds, error, given };
|
|
11881
|
+
outcome = { outcome: 'turn-ended', snapshot, text, attachmentIds, mentionsKey: mentionItems.map((item) => item.key).join('\n'), error, given };
|
|
9377
11882
|
} else if (given) {
|
|
9378
11883
|
outcome = notSent(definitiveRefusal ? givenRefusal(error)
|
|
9379
11884
|
: 'FloLess couldn’t confirm your answer reached the AI. Check the conversation before you answer again.');
|
|
@@ -10428,28 +12933,63 @@
|
|
|
10428
12933
|
}
|
|
10429
12934
|
|
|
10430
12935
|
function closeScopePicker(restoreFocus = false) {
|
|
12936
|
+
state.scopeRead = null;
|
|
10431
12937
|
state.scopePickerOpen = false; state.scopeChoice = null;
|
|
10432
12938
|
if (ui.scopePicker) { ui.scopePicker.hidden = true; ui.scopePicker.replaceChildren(); }
|
|
10433
12939
|
ui.scopeToggle?.setAttribute('aria-expanded', 'false');
|
|
10434
12940
|
if (restoreFocus) ui.scopeToggle?.focus();
|
|
10435
12941
|
}
|
|
10436
12942
|
|
|
12943
|
+
function paintScopePickerNotice(message, retry = false) {
|
|
12944
|
+
const host = ui.scopePicker;
|
|
12945
|
+
const hadFocus = host.contains(document.activeElement);
|
|
12946
|
+
host.replaceChildren();
|
|
12947
|
+
const head = document.createElement('div'); head.className = 'ai-chat-scope-head';
|
|
12948
|
+
const heading = document.createElement('strong'); heading.textContent = 'Conversation scope';
|
|
12949
|
+
const close = button('×', 'shell.chat-scope-close', 'ai-chat-scope-close');
|
|
12950
|
+
close.setAttribute('aria-label', 'Close conversation scope'); close.dataset.tip = 'Close conversation scope';
|
|
12951
|
+
close.addEventListener('click', () => closeScopePicker(true));
|
|
12952
|
+
head.append(heading, close); host.append(head);
|
|
12953
|
+
const note = document.createElement('p'); note.className = 'ai-chat-scope-note';
|
|
12954
|
+
note.setAttribute('role', 'status'); note.textContent = message; host.append(note);
|
|
12955
|
+
if (retry) {
|
|
12956
|
+
const again = button('Try again', 'shell.chat-scope-retry', 'ai-chat-scope-action');
|
|
12957
|
+
again.addEventListener('click', () => { closeScopePicker(); void openScopePicker(); });
|
|
12958
|
+
host.append(again);
|
|
12959
|
+
}
|
|
12960
|
+
if (hadFocus) close.focus();
|
|
12961
|
+
}
|
|
12962
|
+
|
|
10437
12963
|
async function openScopePicker() {
|
|
10438
12964
|
if (state.scopePickerOpen) { closeScopePicker(true); return; }
|
|
10439
12965
|
const snapshot = captureChat();
|
|
10440
12966
|
if (!snapshot || state.chat.archivedAt) return;
|
|
10441
12967
|
closePicker(); state.scopeChoice = null; state.scopePickerOpen = true; state.scopeViewChatId = snapshot.chatId;
|
|
12968
|
+
state.scopeView = null;
|
|
12969
|
+
const read = {}; state.scopeRead = read;
|
|
12970
|
+
// A selection refresh can advance selectionGeneration without changing this conversation. Scope belongs to
|
|
12971
|
+
// the conversation and owner, not that transient generation; each opening still owns its reply.
|
|
12972
|
+
const current = () => {
|
|
12973
|
+
if (state.scopeRead !== read || !state.scopePickerOpen) return false;
|
|
12974
|
+
if (!sameScope(snapshot.scope, snapshot.generation) || state.chat?.chatId !== snapshot.chatId) {
|
|
12975
|
+
closeScopePicker(); return false;
|
|
12976
|
+
}
|
|
12977
|
+
return true;
|
|
12978
|
+
};
|
|
10442
12979
|
ui.scopePicker.hidden = false; ui.scopeToggle.setAttribute('aria-expanded', 'true');
|
|
10443
|
-
|
|
12980
|
+
paintScopePickerNotice('Loading conversation scope…');
|
|
10444
12981
|
try {
|
|
10445
|
-
const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/scope?${ownerQuery(snapshot.scope.owner)}
|
|
10446
|
-
if (!
|
|
12982
|
+
const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/scope?${ownerQuery(snapshot.scope.owner)}`, { timeoutMs: 15000 });
|
|
12983
|
+
if (!current()) return;
|
|
12984
|
+
const hadFocus = document.activeElement === ui.scopeToggle || ui.scopePicker.contains(document.activeElement);
|
|
10447
12985
|
state.scopeView = result; state.scopeViewChatId = snapshot.chatId;
|
|
10448
12986
|
state.chat = { ...state.chat, scopeExtensions: result.scope.extensions.map((entry) => entry.target), scopeRevision: result.scope.revision, changeAllowance: result.changeAllowance };
|
|
10449
12987
|
paintScopePicker(); paintScopeControl();
|
|
10450
|
-
ui.scopePicker.querySelector('button')?.focus();
|
|
12988
|
+
if (hadFocus) ui.scopePicker.querySelector('button')?.focus();
|
|
10451
12989
|
} catch (error) {
|
|
10452
|
-
if (
|
|
12990
|
+
if (current()) paintScopePickerNotice(error?.code === 'local-timeout'
|
|
12991
|
+
? 'Conversation scope took too long to load. Try again.'
|
|
12992
|
+
: 'Conversation scope could not be loaded. Try again.', true);
|
|
10453
12993
|
}
|
|
10454
12994
|
}
|
|
10455
12995
|
|
|
@@ -11117,11 +13657,33 @@
|
|
|
11117
13657
|
ui.settings.hidden = !open;
|
|
11118
13658
|
ui.settingsToggle.setAttribute('aria-expanded', String(open));
|
|
11119
13659
|
closePicker();
|
|
13660
|
+
// #2399: the account's suggestion mode may have changed in another tab or the ≡ menu.
|
|
13661
|
+
if (open) void assistantMode.refresh();
|
|
11120
13662
|
});
|
|
11121
13663
|
ui.model.addEventListener('click', () => openPicker('model', ui.model, modelChoices()));
|
|
11122
13664
|
ui.switchAccount.addEventListener('click', () => { void switchAccount(); });
|
|
11123
13665
|
ui.effort.addEventListener('click', () => openPicker('effort', ui.effort, effortChoices()));
|
|
11124
13666
|
ui.permission.addEventListener('click', () => openPicker('permission', ui.permission, permissionChoices()));
|
|
13667
|
+
ui.suggest?.addEventListener('click', async () => {
|
|
13668
|
+
if (state.picker === 'suggest') { closePicker(); return; }
|
|
13669
|
+
await assistantMode.refresh();
|
|
13670
|
+
openPicker('suggest', ui.suggest, assistantMode.choices());
|
|
13671
|
+
});
|
|
13672
|
+
window.addEventListener('floless:assistant-mode', (event) => {
|
|
13673
|
+
paintSuggestSetting();
|
|
13674
|
+
// #2399 PR C2: the setting was read again (settings opened, or the ≡ menu): the cards drawn here are asked again how
|
|
13675
|
+
// they stand too — another account may have signed in since they were drawn.
|
|
13676
|
+
rereadAssistantStates();
|
|
13677
|
+
// #2399 PR C2: once the person chooses a mode again, the "suggestions are paused" line on a card goes.
|
|
13678
|
+
if (assistantRecoveredCard && event.detail && !event.detail.recovered) {
|
|
13679
|
+
const entry = assistantCardEntries.get(assistantRecoveredCard);
|
|
13680
|
+
assistantRecoveredCard = '';
|
|
13681
|
+
if (entry) { entry.recovered = false; entry.error = ''; repaintAssistantCard(entry); }
|
|
13682
|
+
}
|
|
13683
|
+
});
|
|
13684
|
+
// #2399 PR C2: the window coming back may mean another account signed in, or a card used in another window: every
|
|
13685
|
+
// assistant card drawn here asks again how it stands.
|
|
13686
|
+
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') rereadAssistantStates(); });
|
|
11125
13687
|
// #2046: the Guide's own controls (web/guide.js does the work and says what happened).
|
|
11126
13688
|
el('chat-guide-off')?.addEventListener('click', () => { void window.flolessGuide?.turnOff?.(); });
|
|
11127
13689
|
el('chat-guide-delete')?.addEventListener('click', () => { void window.flolessGuide?.deleteHistory?.(); });
|
|
@@ -11149,8 +13711,17 @@
|
|
|
11149
13711
|
ui.reconcile.addEventListener('click', reconcile);
|
|
11150
13712
|
ui.attach.addEventListener('click', () => ui.file.click());
|
|
11151
13713
|
ui.file.addEventListener('change', () => attachFiles(ui.file.files));
|
|
11152
|
-
ui.input.addEventListener('input', () => { autosize(); saveDraftSoon(); paintSkills(); updateSendState(); });
|
|
13714
|
+
ui.input.addEventListener('input', () => { autosize(); saveDraftSoon(); if (!paintMentionMenu()) paintSkills(); updateSendState(); });
|
|
13715
|
+
// #2438: the @ list follows the caret, and closes when the caret leaves its token or the box loses focus.
|
|
13716
|
+
ui.input.addEventListener('click', () => { if (state.mentionMenu || mentionToken()) paintMentionMenu(); });
|
|
13717
|
+
ui.input.addEventListener('keyup', (event) => {
|
|
13718
|
+
if (['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key) && (state.mentionMenu || mentionToken())) paintMentionMenu();
|
|
13719
|
+
});
|
|
13720
|
+
ui.input.addEventListener('select', () => { if (state.mentionMenu || mentionToken()) paintMentionMenu(); });
|
|
13721
|
+
ui.input.addEventListener('blur', () => closeMentionMenu());
|
|
13722
|
+
ui.skills.addEventListener('pointerdown', (event) => { if (state.mentionMenu) event.preventDefault(); });
|
|
11153
13723
|
ui.input.addEventListener('keydown', (event) => {
|
|
13724
|
+
if (handleMentionKey(event)) return;
|
|
11154
13725
|
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { event.preventDefault(); sendTurn(); }
|
|
11155
13726
|
else if (event.key === 'Escape') { ui.skills.hidden = true; closePicker(); }
|
|
11156
13727
|
});
|
|
@@ -11210,7 +13781,8 @@
|
|
|
11210
13781
|
}
|
|
11211
13782
|
|
|
11212
13783
|
state.refreshTimer = setInterval(pollChatsTick, 5000);
|
|
11213
|
-
window.addEventListener('pagehide', () => { closeSource(); contextObserver.disconnect(); activityResizeObserver.disconnect(); clearInterval(state.refreshTimer); clearTimeout(state.draftTimer); });
|
|
13784
|
+
window.addEventListener('pagehide', () => { disposeChatSession(); closeSource(); contextObserver.disconnect(); activityResizeObserver.disconnect(); clearInterval(state.refreshTimer); clearTimeout(state.draftTimer); });
|
|
13785
|
+
window.addEventListener('pageshow', (event) => { if (event.persisted) restoreChatSession(); });
|
|
11214
13786
|
// A new selection is a new decision: a pill left out for the old one comes back for it.
|
|
11215
13787
|
window.addEventListener('floless:model-selection', () => {
|
|
11216
13788
|
let selection = null;
|
|
@@ -11227,6 +13799,8 @@
|
|
|
11227
13799
|
currentProvider: () => state.chat?.provider ?? null,
|
|
11228
13800
|
// The project this panel's conversations belong to; an object card offers Show in chat only for it (#1653).
|
|
11229
13801
|
scopeProjectId: () => (state.scope?.owner?.kind === 'project' ? state.scope.owner.projectId : null),
|
|
13802
|
+
// The Knowledge step's "Ask AI to index" (#2399 slice 0b): the person's own draft in the message box; never sent.
|
|
13803
|
+
fillMessageBox: (text) => putInMessageBox(String(text || '')),
|
|
11230
13804
|
// The New project dialog's AI choice (#1605) words each provider's sign-in the way this
|
|
11231
13805
|
// panel's own chooser does, so the two ways into a conversation read the same.
|
|
11232
13806
|
providerAccountLabel,
|