@floless/app 0.138.2 → 0.139.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/autostart.mjs +6 -2
- package/desktop-access-production-manifest.mjs +7 -0
- package/dist/floless-server.cjs +157202 -70901
- package/dist/schemas/model.continuation.v1.schema.json +19 -0
- package/dist/schemas/model.continuation.v2.schema.json +19 -0
- package/dist/schemas/model.query-response.v1.schema.json +95 -0
- package/dist/schemas/model.query-response.v2.schema.json +80 -0
- package/dist/schemas/model.query.v1.schema.json +87 -0
- package/dist/schemas/model.query.v2.schema.json +87 -0
- package/dist/schemas/model.snap-candidate.v1.schema.json +48 -0
- package/dist/schemas/model.snap-constraint.v1.schema.json +18 -0
- package/dist/schemas/model.snap-query.v1.schema.json +24 -0
- package/dist/schemas/model.snap-result.v1.schema.json +33 -0
- package/dist/schemas/model.snapshot.v1.schema.json +136 -0
- package/dist/schemas/revit.model.v1.schema.json +24 -0
- package/dist/schemas/steel.model.v2.schema.json +45 -6
- package/dist/skills/floless-app-approval/SKILL.md +19 -5
- package/dist/skills/floless-app-bridge/SKILL.md +19 -6
- package/dist/skills/floless-app-knowledge/SKILL.md +22 -1
- package/dist/skills/floless-app-new-workflow/SKILL.md +31 -27
- package/dist/skills/floless-app-new-workflow/references/build-and-verify.md +13 -12
- package/dist/skills/floless-app-onboarding/SKILL.md +3 -3
- package/dist/skills/floless-app-onboarding/references/floless-app-tour.md +16 -9
- package/dist/skills/floless-app-steel-model/SKILL.md +11 -2
- package/dist/skills/floless-app-steel-model/references/detail-from-a-screenshot.md +95 -0
- package/dist/skills/floless-app-steel-takeoff/SKILL.md +142 -21
- package/dist/skills/floless-app-steel-takeoff/references/elevation-registration.md +19 -0
- package/dist/skills/floless-app-tweak-contract/SKILL.md +42 -8
- package/dist/skills/floless-app-vectorize/SKILL.md +19 -6
- package/dist/skills/floless-app-workflows/SKILL.md +30 -3
- package/dist/skills/floless-app-workflows/references/workspace-data.md +77 -4
- package/dist/templates/floless-workspace-model-report.flo +77 -0
- package/dist/templates/revit-model.flo +111 -0
- package/dist/web/app.css +415 -177
- package/dist/web/app.js +302 -51
- package/dist/web/aware.js +1357 -1032
- package/dist/web/chat.css +692 -0
- package/dist/web/chat.js +2651 -0
- package/dist/web/commands-revit.js +42 -0
- package/dist/web/commands-shell.js +531 -70
- package/dist/web/commands-steel.js +344 -146
- package/dist/web/commands.js +1 -1
- package/dist/web/index.html +283 -77
- package/dist/web/instructor.js +217 -36
- package/dist/web/left-pane.js +636 -0
- package/dist/web/model-artifact-loader.js +75 -0
- package/dist/web/model-authoring-gestures.js +141 -0
- package/dist/web/model-cad-tools.js +20 -0
- package/dist/web/model-clip-gesture.js +148 -0
- package/dist/web/model-clip-list.js +156 -0
- package/dist/web/model-clip-session.js +274 -0
- package/dist/web/model-clip-three-overlay.js +295 -0
- package/dist/web/model-clip-three-preview.js +59 -0
- package/dist/web/model-editor-contract.js +519 -0
- package/dist/web/model-editor-revit-adapter.js +139 -0
- package/dist/web/model-editor-shell.js +271 -0
- package/dist/web/model-editor-state-recovery.js +44 -0
- package/dist/web/model-editor-steel-adapter.js +410 -0
- package/dist/web/model-editor.css +268 -0
- package/dist/web/model-frame.js +192 -0
- package/dist/web/model-inspector.js +128 -0
- package/dist/web/model-measure.js +390 -0
- package/dist/web/model-navigation-controls.js +246 -0
- package/dist/web/model-orientation-overlay.js +217 -0
- package/dist/web/model-panel-bridge.js +230 -0
- package/dist/web/model-pointer-dock.js +164 -0
- package/dist/web/model-revit-module.js +83 -0
- package/dist/web/model-selection-coordinator.js +151 -0
- package/dist/web/model-selection-tools.js +290 -0
- package/dist/web/model-snap-contract.js +267 -0
- package/dist/web/model-snapping.js +497 -0
- package/dist/web/model-spatial-panel.js +294 -0
- package/dist/web/model-spatial-tools.js +249 -0
- package/dist/web/model-tree.js +47 -0
- package/dist/web/model-viewport-lighting.js +166 -0
- package/dist/web/model-viewport-revit-adapter.js +1224 -0
- package/dist/web/model-viewport-state.js +505 -0
- package/dist/web/model-viewport-steel-adapter.js +150 -0
- package/dist/web/model-viewport-toolbar.js +516 -0
- package/dist/web/model-viewport.js +717 -0
- package/dist/web/panels.js +8 -15
- package/dist/web/renderers.js +3 -0
- package/dist/web/revit-editor.css +35 -0
- package/dist/web/revit-editor.html +74 -0
- package/dist/web/revit-editor.js +845 -0
- package/dist/web/steel-3d-core.js +16 -44
- package/dist/web/steel-3d-view.js +1384 -633
- package/dist/web/steel-canvas-guidance.js +3 -1
- package/dist/web/steel-editor.html +2121 -1253
- package/dist/web/steel-filter.html +5 -1
- package/dist/web/steel-model-v2-commands.js +72 -1
- package/dist/web/steel-split-view.js +5 -39
- package/dist/web/steel-view-generation.js +107 -17
- package/dist/web/vector-3d.html +12 -0
- package/dist/web/workspaces.js +2154 -283
- package/distribution-profile-active.mjs +2 -0
- package/distribution-profile-production.mjs +47 -0
- package/distribution-profile-shared.mjs +8 -0
- package/distribution-profile.mjs +18 -0
- package/distribution-resource-inventory.mjs +81 -0
- package/launch.mjs +18 -10
- package/log.mjs +2 -1
- package/managed-runtime-policy.mjs +104 -0
- package/model-reader-policy-active.mjs +7 -0
- package/network-policy-active.mjs +6 -0
- package/package.json +17 -2
- package/post-update-marker.mjs +3 -1
- package/rvt-production-uat-authority.mjs +60 -0
- package/teardown.mjs +4 -3
package/dist/web/chat.js
ADDED
|
@@ -0,0 +1,2651 @@
|
|
|
1
|
+
(function () {
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const shell = document.getElementById('ai-chat-shell');
|
|
5
|
+
if (!shell) return;
|
|
6
|
+
|
|
7
|
+
const el = (id) => document.getElementById(id);
|
|
8
|
+
const ui = {
|
|
9
|
+
historyToggle: el('chat-history-toggle'), newChat: el('chat-new'), refresh: el('chat-refresh'), history: el('chat-history'),
|
|
10
|
+
title: el('chat-title'), rename: el('chat-rename'), scope: el('chat-scope'), settingsToggle: el('chat-settings-toggle'),
|
|
11
|
+
settings: el('chat-settings'), provider: el('chat-provider'), model: el('chat-model'),
|
|
12
|
+
effort: el('chat-effort'), permission: el('chat-permission'), integrations: el('chat-integrations'),
|
|
13
|
+
desktopValue: el('chat-desktop-value'), desktopReason: el('chat-desktop-reason'), picker: el('chat-picker'),
|
|
14
|
+
feed: el('chat-feed'), recovery: el('chat-recovery'), recoveryCopy: el('chat-recovery-copy'),
|
|
15
|
+
reconcile: el('chat-reconcile'), recoveryStop: el('chat-recovery-stop'), attachments: el('chat-attachments'), skills: el('chat-skills'),
|
|
16
|
+
composer: el('chat-composer'), input: el('chat-input'), file: el('chat-file'), attach: el('chat-attach'),
|
|
17
|
+
hint: el('chat-compose-hint'), contextNote: el('chat-compose-context'), stop: el('chat-stop'), send: el('chat-send'), status: el('chat-status'),
|
|
18
|
+
unread: el('chat-unread'), tab: el('narrative-tab'),
|
|
19
|
+
context: el('left-chat-context'),
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
const state = {
|
|
23
|
+
sessionReady: false, scope: null, chats: [], archivedChats: [], chat: null, events: [], capability: null, desktop: null,
|
|
24
|
+
source: null, eventReconnectTimer: null, eventReconnectAttempt: 0, eventReconnectChatId: null, attachments: [], integrations: null, historyOpen: false, historyFilter: 'all', archivedHistoryOpen: false,
|
|
25
|
+
instructorAnswers: [], historyLoading: false, historyRequestGeneration: 0, picker: null, loading: false,
|
|
26
|
+
draftTimer: null, refreshTimer: null, scopeGeneration: 0, selectionGeneration: 0, choosingProvider: false,
|
|
27
|
+
answerJump: null, answerJumpTimer: null, scopeInitialized: false, renaming: null, pendingSubmissionId: null, recoveryMessage: null, recoveryCanEnd: false,
|
|
28
|
+
stream: null, liveStatusTurnId: null, decidingApprovalIds: new Set(),
|
|
29
|
+
};
|
|
30
|
+
const permissionLabels = {
|
|
31
|
+
'read-only': 'Read only', 'workspace-write': 'Working folder write', 'full-access': 'Full access',
|
|
32
|
+
};
|
|
33
|
+
const providerLabels = { claude: 'Claude', codex: 'Codex' };
|
|
34
|
+
const requestTypeLabels = { 'drawing-intake': 'Initial drawing read', 'initial-drawing-read': 'Initial drawing read', 'tweak-contract': 'Workflow change', guide: 'Question' };
|
|
35
|
+
const requestStatusLabels = { pending: 'Queued', queued: 'Queued', running: 'Running', ready: 'Ready', completed: 'Complete', failed: 'Failed', stopped: 'Stopped' };
|
|
36
|
+
const allowedTypes = new Set(['image/png', 'image/jpeg', 'image/webp', 'application/pdf']);
|
|
37
|
+
const MB = 1024 * 1024;
|
|
38
|
+
|
|
39
|
+
function ownerQuery(owner = state.scope?.owner) {
|
|
40
|
+
if (!owner) return '';
|
|
41
|
+
const ownerId = owner.kind === 'project' ? owner.projectId : owner.workflowId;
|
|
42
|
+
return new URLSearchParams({ ownerKind: owner.kind, ownerId }).toString();
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function request(path, options = {}) {
|
|
46
|
+
const timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 30000;
|
|
47
|
+
const init = { credentials: 'same-origin', ...options };
|
|
48
|
+
delete init.timeoutMs;
|
|
49
|
+
// Every chat request is local, but a stopped server or a provider capability probe can otherwise
|
|
50
|
+
// leave a button in Opening… forever. Abort the browser wait after 30 seconds and turn it into a
|
|
51
|
+
// user-facing error; the server-side request remains durable and can still be retried from Requests.
|
|
52
|
+
if (!init.signal && timeoutMs > 0 && typeof AbortSignal?.timeout === 'function') {
|
|
53
|
+
init.signal = AbortSignal.timeout(timeoutMs);
|
|
54
|
+
}
|
|
55
|
+
if (init.body && !init.headers) init.headers = { 'content-type': 'application/json' };
|
|
56
|
+
let response;
|
|
57
|
+
try {
|
|
58
|
+
response = await fetch(path, init);
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (error?.name === 'TimeoutError' || error?.name === 'AbortError') {
|
|
61
|
+
const timeout = new Error('FloLess did not respond in time. Check that the local server is running, then try again.');
|
|
62
|
+
timeout.code = 'local-timeout';
|
|
63
|
+
throw timeout;
|
|
64
|
+
}
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
const contentType = response.headers.get('content-type') || '';
|
|
68
|
+
const body = contentType.includes('application/json') ? await response.json() : await response.text();
|
|
69
|
+
if (!response.ok) {
|
|
70
|
+
const error = new Error(body?.error || body || `Chat request failed (${response.status})`);
|
|
71
|
+
error.code = body?.code || null;
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
return body;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
function announce(message) {
|
|
78
|
+
ui.status.textContent = '';
|
|
79
|
+
requestAnimationFrame(() => { ui.status.textContent = message; });
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function setBusy(busy) {
|
|
83
|
+
state.loading = busy;
|
|
84
|
+
ui.newChat.disabled = busy || !state.scope;
|
|
85
|
+
// A provider button that looks ready while the chat is still loading silently ignored the click.
|
|
86
|
+
for (const choice of ui.feed.querySelectorAll('.ai-chat-start-provider')) {
|
|
87
|
+
choice.disabled = busy;
|
|
88
|
+
choice.setAttribute('aria-busy', String(busy));
|
|
89
|
+
}
|
|
90
|
+
const blocked = requestExecutionBlocked();
|
|
91
|
+
// Freeze the draft while the server is accepting it. The acceptance transaction clears the
|
|
92
|
+
// durable draft; allowing typing in this short window can race a new autosave over that clear
|
|
93
|
+
// and make the submitted message reappear after the turn finishes.
|
|
94
|
+
ui.input.disabled = busy || !state.chat || Boolean(state.chat?.archivedAt)
|
|
95
|
+
|| state.chat?.state === 'recovery' || blocked;
|
|
96
|
+
ui.send.disabled = busy || !state.chat || blocked || !ui.input.value.trim() || Boolean(state.chat?.activeTurn);
|
|
97
|
+
ui.attach.disabled = busy || !state.chat || blocked || Boolean(state.chat?.activeTurn);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function errorMessage(error) {
|
|
101
|
+
const raw = error instanceof Error ? error.message : String(error);
|
|
102
|
+
const code = String(error && error.code || '');
|
|
103
|
+
const codeMessages = {
|
|
104
|
+
'chat-origin-refused': 'This chat can only be used from the FloLess app. Reload the page and try again.',
|
|
105
|
+
'chat-owner-stale': 'This conversation no longer matches the current project or workflow folder. Reopen the project or workflow, then try again.',
|
|
106
|
+
'chat-cwd-stale': 'This conversation no longer matches the current project or workflow folder. Reopen the project or workflow, then try again.',
|
|
107
|
+
'chat-turn-stale': 'This response is no longer active. Refresh the conversation before trying again.',
|
|
108
|
+
'chat-initiator-unknown': 'FloLess could not identify what started this conversation. Reload the conversation and try again.',
|
|
109
|
+
'chat-record-unsafe': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
|
|
110
|
+
'chat-record-invalid': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
|
|
111
|
+
'chat-session-bindings-corrupt': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
|
|
112
|
+
'chat-ownership-corrupt': 'FloLess could not safely open this conversation. Keep it read only and use Report an issue.',
|
|
113
|
+
'chat-journal-gap': 'FloLess could not safely read this conversation history. Refresh it and use Report an issue if the problem remains.',
|
|
114
|
+
'chat-journal-mismatch': 'FloLess could not safely read this conversation history. Refresh it and use Report an issue if the problem remains.',
|
|
115
|
+
'chat-owner-archived': 'This project or workflow is archived. Restore it before continuing the conversation.',
|
|
116
|
+
'chat-archived': 'This conversation is archived. Start a new conversation to continue.',
|
|
117
|
+
'chat-turn-active': 'Stop the active response before changing this conversation.',
|
|
118
|
+
'chat-send-refused': 'The AI service did not accept this message. Check your sign-in and conversation settings, then try again.',
|
|
119
|
+
'chat-approval-stale': 'This approval is no longer active. Refresh the conversation.',
|
|
120
|
+
'chat-provider-identity-changed': 'The connected AI account changed while this response was running. Refresh the conversation and try again.',
|
|
121
|
+
'chat-integration-unavailable': 'Connected accounts are unavailable right now. Open Integrations and try again.',
|
|
122
|
+
'chat-integration-input-invalid': 'The connected account request was not valid. Check Integrations and try again.',
|
|
123
|
+
'chat-integration-limit-invalid': 'The connected account request was too large. Remove some items and try again.',
|
|
124
|
+
'chat-integration-stale': 'This connected account needs attention. Reconnect it in Integrations, then try again.',
|
|
125
|
+
'chat-integration-not-runnable': 'This connected account cannot be used right now. Check Integrations and try again.',
|
|
126
|
+
'chat-integration-contract-mismatch': 'FloLess could not verify this connected service. Check Integrations and try again.',
|
|
127
|
+
'chat-native-connector-conflict': 'FloLess cannot safely use this account while the provider has another connection for the same service.',
|
|
128
|
+
'chat-model-invalid': 'That model is no longer available. Choose another model.',
|
|
129
|
+
'chat-effort-invalid': 'That effort level is no longer available. Choose another option.',
|
|
130
|
+
'chat-desktop-unavailable': 'Desktop continuation is not available for this chat yet.',
|
|
131
|
+
'request-chat-unscoped': 'This request is not linked to a project or workflow. Open it from the project or workflow that owns it.',
|
|
132
|
+
'request-background-owned': 'This request is already running in the background. Open its existing conversation or wait for it to finish.',
|
|
133
|
+
'request-chat-not-runnable': 'This request is not ready to start in AI Chat. Open Requests to see what it needs.',
|
|
134
|
+
'request-chat-no-prompt': 'This request has no safe instruction to send. Clear it and create the request again.',
|
|
135
|
+
'project-intake-unavailable': 'Project chat is unavailable right now. Create the project, then start a new conversation from it.',
|
|
136
|
+
'request-chat-conflict': 'This request is already linked to another conversation. Open that conversation to continue it.',
|
|
137
|
+
'request-chat-link-invalid': 'FloLess could not open this request link. Open the request again from Requests.',
|
|
138
|
+
'request-chat-link-changed': 'This request changed while it was opening. Open it again from Requests.',
|
|
139
|
+
'request-chat-not-ready': 'This request is still being prepared. Wait a moment, then try again.',
|
|
140
|
+
'chat-knowledge-unscoped': 'Knowledge is available only inside a project conversation. Open a project and try again.',
|
|
141
|
+
'chat-knowledge-page-missing': 'That Knowledge page is no longer available in this project. Refresh the conversation.',
|
|
142
|
+
};
|
|
143
|
+
if (codeMessages[code]) return codeMessages[code];
|
|
144
|
+
if (code === 'request-chat-owner-mismatch' || /request chat link belongs to another owner/i.test(raw)) {
|
|
145
|
+
return 'This request is linked to another project or workflow. Open the project or workflow shown on the request, then try again.';
|
|
146
|
+
}
|
|
147
|
+
if (code === 'chat-session-required' || /chat UI session is missing or expired/i.test(raw)) {
|
|
148
|
+
return 'Your FloLess session has expired. Reload the page and try again.';
|
|
149
|
+
}
|
|
150
|
+
if (code === 'chat-session-owned' || /provider session .*belongs to another chat/i.test(raw)) {
|
|
151
|
+
return 'This Claude or Codex conversation is already open in another FloLess chat. Open that chat instead.';
|
|
152
|
+
}
|
|
153
|
+
if (code === 'chat-owner-busy' || /project or workflow already has a modifying chat turn/i.test(raw)) {
|
|
154
|
+
return 'Another AI Chat is changing this project or workflow. Wait for it to finish or stop it before sending here.';
|
|
155
|
+
}
|
|
156
|
+
if (code === 'chat-host-busy' || /host application instance already has a modifying owner/i.test(raw)) {
|
|
157
|
+
return 'Another task is using the connected design application. Wait for it to finish or stop it before trying again.';
|
|
158
|
+
}
|
|
159
|
+
if (code === 'chat-project-busy' || code === 'chat-workflow-busy') {
|
|
160
|
+
return 'Finish or stop the active AI Chat before changing this project or workflow.';
|
|
161
|
+
}
|
|
162
|
+
if (code === 'chat-root-stale') {
|
|
163
|
+
return 'This conversation no longer matches the current project or workflow folder. Reopen the project or workflow, then try again.';
|
|
164
|
+
}
|
|
165
|
+
if (code === 'chat-integration-not-selected') {
|
|
166
|
+
return 'Choose a connected account in Chat settings before using this service.';
|
|
167
|
+
}
|
|
168
|
+
if (code === 'chat-integration-unsupported') {
|
|
169
|
+
return 'This service is not available in FloLess Chat yet.';
|
|
170
|
+
}
|
|
171
|
+
if (code === 'chat-integration-binding-changed' || code === 'chat-integration-binding-invalid'
|
|
172
|
+
|| code === 'chat-integration-identity-invalid' || code === 'chat-integration-identity-unverified') {
|
|
173
|
+
return 'FloLess could not verify that connected account. Check Integrations and try again.';
|
|
174
|
+
}
|
|
175
|
+
if (code === 'chat-integration-turn-stale') {
|
|
176
|
+
return 'This connected-account request is no longer active. Send your message again.';
|
|
177
|
+
}
|
|
178
|
+
if (code === 'chat-send-uncertain' || code === 'chat-stop-uncertain' || code === 'chat-approval-uncertain') {
|
|
179
|
+
return 'FloLess could not confirm the last AI action. Check the last AI response before sending or approving anything else.';
|
|
180
|
+
}
|
|
181
|
+
if (code === 'chat-turn-recovery' || code === 'chat-ownership-lost') {
|
|
182
|
+
return 'FloLess could not confirm the last AI action. Check the last AI response before sending or approving anything else.';
|
|
183
|
+
}
|
|
184
|
+
if (code === 'chat-ownership-stale' || code === 'chat-approval-stale'
|
|
185
|
+
|| /ownership generation is stale|approval belongs to a stale/i.test(raw)) {
|
|
186
|
+
return 'This response is no longer active. Refresh the conversation before trying again.';
|
|
187
|
+
}
|
|
188
|
+
if (code === 'request-chat-unavailable' || /Request chat is not configured/i.test(raw)) {
|
|
189
|
+
return 'Requests cannot be opened in AI Chat right now. Reload the page and try again.';
|
|
190
|
+
}
|
|
191
|
+
if (code === 'chat-provider-unavailable' || /chat providers are not configured/i.test(raw)) {
|
|
192
|
+
return 'No AI provider is ready for this chat. Sign in to Claude or Codex, then try again.';
|
|
193
|
+
}
|
|
194
|
+
if (/chat model .*invalid|model .*not offered/i.test(raw)) return 'That model is no longer available. Choose another model.';
|
|
195
|
+
if (/chat effort .*invalid|effort .*not offered/i.test(raw)) return 'That effort level is no longer available. Choose another option.';
|
|
196
|
+
if (/\b(?:EPERM|EACCES|EBUSY|ENOENT|ENOTDIR)\b|operation not permitted|permission denied/i.test(raw)) {
|
|
197
|
+
return 'FloLess could not access that file or folder. Check that it is available and try again.';
|
|
198
|
+
}
|
|
199
|
+
// The provider itself can no longer load this conversation: Codex after its desktop app migrates
|
|
200
|
+
// thread storage to a format the pinned CLI cannot read, Claude after its saved session is gone.
|
|
201
|
+
// Retrying never helps, so point at the one action that works.
|
|
202
|
+
// Match only the complete provider envelopes; quoted or nested text must not end a working chat.
|
|
203
|
+
if (/^paginated_threads is not supported yet$/.test(raw.trim())
|
|
204
|
+
|| /^(?:Claude Code returned an error result: )?No conversation found with session ID: [0-9a-f-]{36}$/i.test(raw.trim())) {
|
|
205
|
+
return `${providerLabels[state.chat?.provider] || 'This AI app'} can no longer open this conversation’s saved history. Start a new conversation to continue.`;
|
|
206
|
+
}
|
|
207
|
+
if (/process exited|app-server|command-line runtime|did not return a session|provider .* unavailable/i.test(raw)) {
|
|
208
|
+
return 'The selected AI service could not complete this request. Check your sign-in and try again.';
|
|
209
|
+
}
|
|
210
|
+
if (/\b(?:identity|ownership|generation|binding|reconciliation|corrupt|not configured|internal)\b/i.test(raw)) {
|
|
211
|
+
return 'FloLess could not complete this chat action. Reload the conversation and try again.';
|
|
212
|
+
}
|
|
213
|
+
return 'FloLess could not complete this chat action. Reload the conversation and try again.';
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function capabilityMessage(provider, reason) {
|
|
217
|
+
const label = providerLabels[provider] || 'AI service';
|
|
218
|
+
const raw = String(reason || '');
|
|
219
|
+
if (!raw) return `Sign in to ${label} first.`;
|
|
220
|
+
if (/sign in|auth|account/i.test(raw)) return `Sign in to ${label} first.`;
|
|
221
|
+
if (/EPERM|EACCES|ENOENT|ENOTDIR|operation not permitted|permission denied|watch ['"]/i.test(raw)) {
|
|
222
|
+
return 'FloLess cannot open this conversation’s project or workflow folder. Restore or reconnect that folder, then try again.';
|
|
223
|
+
}
|
|
224
|
+
if (/process exited|app-server|command-line runtime|did not return a session|unavailable|failed|error/i.test(raw)) {
|
|
225
|
+
return `The ${label} service could not be reached. Check your sign-in and try again.`;
|
|
226
|
+
}
|
|
227
|
+
if (/\b(?:identity|ownership|generation|binding|configured|internal|session)\b/i.test(raw)) {
|
|
228
|
+
return `The ${label} chat is not ready on this computer. Reload FloLess and try again.`;
|
|
229
|
+
}
|
|
230
|
+
return `The ${label} chat is not ready on this computer. Reload FloLess and try again.`;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function report(error, prefix = '') {
|
|
234
|
+
const message = `${prefix}${prefix ? ': ' : ''}${errorMessage(error)}`;
|
|
235
|
+
announce(message);
|
|
236
|
+
ui.hint.textContent = message;
|
|
237
|
+
ui.hint.classList.add('error');
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function clearReport() {
|
|
241
|
+
ui.hint.classList.remove('error');
|
|
242
|
+
const message = requestExecutionBlocked()
|
|
243
|
+
? 'Another AI Chat is changing this project or workflow. Wait for it to finish or stop it before sending here.'
|
|
244
|
+
: state.chat && state.capability?.runtime && state.capability.runtime.state !== 'installed'
|
|
245
|
+
? runtimeNotice(state.chat.provider, state.capability.runtime).body
|
|
246
|
+
: state.chat && !providerReady()
|
|
247
|
+
? `${capabilityMessage(state.chat.provider, state.capability?.reason)} You can still write a message; Send will retry the connection.`
|
|
248
|
+
: state.chat?.state === 'recovery'
|
|
249
|
+
? 'Check the last AI response before continuing.'
|
|
250
|
+
: !state.scope?.owner
|
|
251
|
+
? 'Open a project or workflow to start chatting.'
|
|
252
|
+
: 'Enter to send · Shift+Enter for a new line';
|
|
253
|
+
if (turnIsVisiblyActive()) {
|
|
254
|
+
ui.hint.replaceChildren();
|
|
255
|
+
ui.hint.classList.remove('working');
|
|
256
|
+
ui.hint.setAttribute('aria-label', 'AI is working');
|
|
257
|
+
} else {
|
|
258
|
+
ui.hint.classList.remove('working');
|
|
259
|
+
ui.hint.removeAttribute('aria-label');
|
|
260
|
+
ui.hint.textContent = message;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function scopeKey(scope) {
|
|
265
|
+
const owner = scope?.owner;
|
|
266
|
+
if (!owner) return '';
|
|
267
|
+
// Events and the bridge can construct the same owner with different property order; JSON
|
|
268
|
+
// serialization made those equal scopes look different and reset the provider chooser.
|
|
269
|
+
const ownerId = owner.kind === 'project' ? owner.projectId : owner.workflowId;
|
|
270
|
+
return typeof ownerId === 'string' ? `${owner.kind}:${ownerId}` : '';
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
function providerReady() {
|
|
274
|
+
return Boolean(state.capability?.available && state.capability?.authenticated === true);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function currentFloLessContext() {
|
|
278
|
+
const workspaceMode = document.querySelector('#mode-switch [data-mode="workspaces"]')?.getAttribute('aria-selected') === 'true';
|
|
279
|
+
const workflowMode = document.querySelector('#mode-switch [data-mode="workflows"]')?.getAttribute('aria-selected') === 'true';
|
|
280
|
+
const reportOpen = document.getElementById('report-modal')?.classList.contains('show') === true;
|
|
281
|
+
const editorOpen = document.getElementById('contract-editor')?.hidden === false;
|
|
282
|
+
const threeDimensionalReport = document.getElementById('report-frame-3d')?.hidden === false;
|
|
283
|
+
const workflowRunning = document.getElementById('stop-run')?.hidden === false
|
|
284
|
+
|| document.getElementById('report-stop')?.hidden === false;
|
|
285
|
+
const selectedStep = document.querySelector('#ws-step-tabs [aria-selected="true"]')?.getAttribute('data-step');
|
|
286
|
+
const workspaceSurface = {
|
|
287
|
+
drawings: 'drawing-filter', model: 'project-model', exports: 'project-exports',
|
|
288
|
+
history: 'project-history', knowledge: 'project-knowledge',
|
|
289
|
+
}[selectedStep || ''] || 'project-list';
|
|
290
|
+
const workspaceProjectOpen = document.getElementById('ws-project')?.hidden === false;
|
|
291
|
+
const dashboardVisible = document.getElementById('dashboard')?.hidden === false;
|
|
292
|
+
const surface = reportOpen ? (threeDimensionalReport ? '3d-report' : 'report')
|
|
293
|
+
: editorOpen ? 'model-editor'
|
|
294
|
+
: workspaceMode ? (workspaceProjectOpen ? workspaceSurface : 'project-list')
|
|
295
|
+
: dashboardVisible ? 'dashboard' : 'workflow-canvas';
|
|
296
|
+
return {
|
|
297
|
+
mode: workspaceMode ? 'workspaces' : workflowMode ? 'workflows' : 'canvas',
|
|
298
|
+
surface,
|
|
299
|
+
activity: workflowRunning ? 'workflow-running' : 'idle',
|
|
300
|
+
visibleText: visibleFloLessSurfaceText(surface),
|
|
301
|
+
};
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function readVisibleText(node) {
|
|
305
|
+
if (!node) return '';
|
|
306
|
+
const source = typeof node.innerText === 'string' ? node.innerText : node.textContent;
|
|
307
|
+
return String(source || '').replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g, '')
|
|
308
|
+
.split(/\r?\n/).map((line) => line.trim().replace(/\s+/g, ' ')).filter(Boolean).join('\n');
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function readVisibleFrameText(id) {
|
|
312
|
+
try { return readVisibleText(document.getElementById(id)?.contentDocument?.body); } catch { return ''; }
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
function boundedVisibleText(...values) {
|
|
316
|
+
const joined = values.filter(Boolean).join('\n').trim();
|
|
317
|
+
return [...joined].slice(0, 6000).join('');
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function visibleFloLessSurfaceText(surface) {
|
|
321
|
+
const shellText = (...ids) => boundedVisibleText(...ids.map((id) => readVisibleText(document.getElementById(id))));
|
|
322
|
+
switch (surface) {
|
|
323
|
+
case 'drawing-filter': return boundedVisibleText(readVisibleFrameText('ws-frame-drawings'), shellText('ws-stage-guidance', 'ws-revision-card'));
|
|
324
|
+
case 'project-model': return boundedVisibleText(readVisibleFrameText('ws-frame-model'), shellText('ws-stage-guidance'));
|
|
325
|
+
case 'project-exports': return shellText('ws-exports');
|
|
326
|
+
case 'project-history': return shellText('ws-history');
|
|
327
|
+
case 'project-knowledge': return shellText('ws-knowledge');
|
|
328
|
+
case 'project-list': return shellText('ws-landing');
|
|
329
|
+
case 'workflow-canvas': return shellText('canvas-main', 'inspect');
|
|
330
|
+
case 'dashboard': return shellText('dashboard');
|
|
331
|
+
case 'report': return boundedVisibleText(readVisibleFrameText('report-frame'), shellText('report-title', 'report-sub', 'report-overlay'));
|
|
332
|
+
case '3d-report': return shellText('report-title', 'report-sub', 'report-overlay');
|
|
333
|
+
case 'model-editor': return boundedVisibleText(readVisibleFrameText('contract-editor-frame'), shellText('contract-editor-title'));
|
|
334
|
+
default: return '';
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
function floLessContextLabel(context = currentFloLessContext()) {
|
|
339
|
+
const labels = {
|
|
340
|
+
'drawing-filter': 'Drawing Filter', 'project-model': 'project model', 'project-exports': 'project exports',
|
|
341
|
+
'project-history': 'project history', 'project-knowledge': 'project Knowledge', 'project-list': 'project list',
|
|
342
|
+
'workflow-canvas': 'workflow canvas', dashboard: 'dashboard', report: 'report', '3d-report': '3D report',
|
|
343
|
+
'model-editor': 'model editor',
|
|
344
|
+
};
|
|
345
|
+
return `${labels[context.surface] || 'FloLess'} · visible state${context.activity === 'workflow-running' ? ' · workflow running' : ''}`;
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function paintFloLessContext() {
|
|
349
|
+
if (!ui.contextNote) return;
|
|
350
|
+
const context = currentFloLessContext();
|
|
351
|
+
ui.contextNote.replaceChildren();
|
|
352
|
+
const prefix = document.createElement('strong');
|
|
353
|
+
prefix.textContent = 'Sharing with AI: ';
|
|
354
|
+
ui.contextNote.append(prefix, document.createTextNode(floLessContextLabel(context)));
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function commandInstance(value) {
|
|
358
|
+
return encodeURIComponent(String(value));
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function requestExecutionBlocked() {
|
|
362
|
+
const requestId = state.chat?.runContext?.requestId;
|
|
363
|
+
return Boolean(requestId && window.flolessBridge?.isRequestChatBlocked?.(requestId));
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function turnIsVisiblyActive(chat = state.chat) {
|
|
367
|
+
return Boolean(chat?.activeTurn) && chat.state !== 'recovery';
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function clearLiveStream(flush = false) {
|
|
371
|
+
if (flush && state.stream) state.stream.shown = state.stream.target;
|
|
372
|
+
if (state.stream?.frame) cancelAnimationFrame(state.stream.frame);
|
|
373
|
+
state.stream = null;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
function flushLiveStream() {
|
|
377
|
+
if (!state.stream) return;
|
|
378
|
+
if (state.stream.frame) cancelAnimationFrame(state.stream.frame);
|
|
379
|
+
state.stream.frame = null;
|
|
380
|
+
state.stream.shown = state.stream.target;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function hasPendingLiveStream() {
|
|
384
|
+
return Boolean(state.stream && state.stream.chatId === state.chat?.chatId
|
|
385
|
+
&& state.stream.shown.length < state.stream.target.length);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function scheduleLiveStreamPaint() {
|
|
389
|
+
if (!hasPendingLiveStream() || state.stream.frame) return;
|
|
390
|
+
state.stream.frame = requestAnimationFrame(() => {
|
|
391
|
+
const stream = state.stream;
|
|
392
|
+
if (!stream) return;
|
|
393
|
+
stream.frame = null;
|
|
394
|
+
const remaining = stream.target.length - stream.shown.length;
|
|
395
|
+
if (remaining <= 0) return;
|
|
396
|
+
// Reveal every received burst over a few frames. This preserves the provider's real text
|
|
397
|
+
// while avoiding a staccato redraw when Codex or Claude delivers several chunks at once.
|
|
398
|
+
const count = Math.max(1, Math.min(12, Math.ceil(remaining / 12)));
|
|
399
|
+
stream.shown += stream.target.slice(stream.shown.length, stream.shown.length + count);
|
|
400
|
+
paintEvents();
|
|
401
|
+
scheduleLiveStreamPaint();
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function renderedLiveAssistantText(event, text) {
|
|
406
|
+
if (!event?.payload?.delta || !event.turnId || !state.chat) return { text, streaming: false };
|
|
407
|
+
const key = `${state.chat.chatId}:${event.turnId}`;
|
|
408
|
+
// Historical stream chunks are stored as deltas too. Only animate the active turn; otherwise
|
|
409
|
+
// opening a conversation would reset every prior answer and leave the last one half-rendered.
|
|
410
|
+
const isActiveTurn = state.chat.activeTurn?.turnId === event.turnId;
|
|
411
|
+
if (!isActiveTurn && state.stream?.key !== key) return { text, streaming: false };
|
|
412
|
+
if (state.stream?.key !== key) {
|
|
413
|
+
clearLiveStream();
|
|
414
|
+
state.stream = { key, chatId: state.chat.chatId, turnId: event.turnId, target: '', shown: '', frame: null };
|
|
415
|
+
}
|
|
416
|
+
const stream = state.stream;
|
|
417
|
+
stream.target = text;
|
|
418
|
+
if (!stream.target.startsWith(stream.shown)) stream.shown = '';
|
|
419
|
+
if (!stream.shown && stream.target) stream.shown = stream.target.slice(0, Math.min(12, stream.target.length));
|
|
420
|
+
if (window.matchMedia?.('(prefers-reduced-motion: reduce)').matches) stream.shown = stream.target;
|
|
421
|
+
scheduleLiveStreamPaint();
|
|
422
|
+
return { text: stream.shown, streaming: stream.shown.length < stream.target.length };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
function readCursor(chatId) {
|
|
426
|
+
try { return Number(localStorage.getItem(`floless:chat-read:${chatId}`) || 0); } catch { return 0; }
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function isUnreadConversation(chat) {
|
|
430
|
+
return Boolean(chat) && (chat.lastEventSequence || 0) > readCursor(chat.chatId);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// A browser seeing an owner's history for the first time has no honest way to call its existing
|
|
434
|
+
// backlog unread. Establish a one-time baseline, then retain unread state for conversations that
|
|
435
|
+
// receive later events. This prevents a migrated chat history from showing hundreds of old events.
|
|
436
|
+
function seedReadCursors(chats, owner = state.scope?.owner) {
|
|
437
|
+
if (!owner) return;
|
|
438
|
+
const ownerId = owner.kind === 'project' ? owner.projectId : owner.workflowId;
|
|
439
|
+
const key = `floless:chat-read-seeded:${owner.kind}:${ownerId}`;
|
|
440
|
+
try {
|
|
441
|
+
if (localStorage.getItem(key)) return;
|
|
442
|
+
for (const chat of chats) localStorage.setItem(`floless:chat-read:${chat.chatId}`, String(chat.lastEventSequence || 0));
|
|
443
|
+
localStorage.setItem(key, '1');
|
|
444
|
+
} catch { /* private mode retains an in-memory-free conservative indicator */ }
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
function markRead(chat = state.chat) {
|
|
448
|
+
if (!chat || document.hidden || ui.feed.closest('[hidden]')
|
|
449
|
+
|| document.querySelector('.app')?.classList.contains('left-collapsed')) return;
|
|
450
|
+
try { localStorage.setItem(`floless:chat-read:${chat.chatId}`, String(chat.lastEventSequence || 0)); } catch { /* private mode */ }
|
|
451
|
+
paintUnread();
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function markReadThrough(chat, sequence) {
|
|
455
|
+
if (!chat) return;
|
|
456
|
+
const through = Math.max(readCursor(chat.chatId), Math.min(Number(sequence) || 0, chat.lastEventSequence || 0));
|
|
457
|
+
try { localStorage.setItem(`floless:chat-read:${chat.chatId}`, String(through)); } catch { /* private mode */ }
|
|
458
|
+
paintUnread();
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
function paintUnread() {
|
|
462
|
+
const unread = state.chats.reduce((sum, chat) => sum + Number(isUnreadConversation(chat)), 0);
|
|
463
|
+
ui.unread.hidden = unread === 0;
|
|
464
|
+
ui.unread.textContent = unread > 99 ? '99+' : String(unread);
|
|
465
|
+
ui.unread.setAttribute('aria-label', `${unread} unread conversation${unread === 1 ? '' : 's'}`);
|
|
466
|
+
shell.dataset.unreadCount = String(unread);
|
|
467
|
+
document.dispatchEvent(new CustomEvent('floless:chat-indicator'));
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
function button(label, commandId, className = '') {
|
|
471
|
+
const node = document.createElement('button');
|
|
472
|
+
node.type = 'button';
|
|
473
|
+
node.textContent = label;
|
|
474
|
+
node.className = className;
|
|
475
|
+
node.dataset.commandId = commandId;
|
|
476
|
+
return node;
|
|
477
|
+
}
|
|
478
|
+
|
|
479
|
+
function providerChooser() {
|
|
480
|
+
// The workspace landing page has no conversation owner. It must never offer a provider,
|
|
481
|
+
// history, or refresh there: none of those actions has a chat to operate on.
|
|
482
|
+
// No provider is chosen here (nor on the unscoped landing), so a setup card left from the previous
|
|
483
|
+
// conversation must go with it.
|
|
484
|
+
shell.querySelector('.ai-chat-runtime')?.remove(); stopRuntimePoll();
|
|
485
|
+
if (!state.scope?.owner) { showUnscoped(); return; }
|
|
486
|
+
ui.feed.replaceChildren();
|
|
487
|
+
const empty = document.createElement('div');
|
|
488
|
+
empty.className = 'ai-chat-empty';
|
|
489
|
+
const strong = document.createElement('strong');
|
|
490
|
+
strong.textContent = state.chats.length ? 'Start a new conversation' : 'Start this conversation';
|
|
491
|
+
const copy = document.createElement('div');
|
|
492
|
+
copy.textContent = 'FloLess keeps this chat with the project on this computer. Messages and attachments are sent to Claude or Codex through your account.';
|
|
493
|
+
const row = document.createElement('div');
|
|
494
|
+
row.className = 'ai-chat-provider-row';
|
|
495
|
+
for (const provider of ['claude', 'codex']) {
|
|
496
|
+
const choice = button(providerLabels[provider], `shell.chat-provider#${providerLabels[provider]}`, 'ai-chat-start-provider');
|
|
497
|
+
choice.dataset.provider = provider;
|
|
498
|
+
choice.disabled = state.loading;
|
|
499
|
+
choice.setAttribute('aria-busy', String(state.loading));
|
|
500
|
+
choice.addEventListener('click', () => createConversation(provider));
|
|
501
|
+
row.append(choice);
|
|
502
|
+
}
|
|
503
|
+
empty.append(strong, copy, row);
|
|
504
|
+
ui.feed.append(empty);
|
|
505
|
+
ui.title.textContent = 'New conversation';
|
|
506
|
+
ui.provider.querySelector('strong').textContent = 'Choose Claude or Codex';
|
|
507
|
+
ui.input.disabled = true;
|
|
508
|
+
ui.attach.disabled = true;
|
|
509
|
+
ui.send.disabled = true;
|
|
510
|
+
ui.historyToggle.disabled = false;
|
|
511
|
+
ui.refresh.disabled = true;
|
|
512
|
+
ui.settingsToggle.disabled = true;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function clearProviderChoice() {
|
|
516
|
+
state.choosingProvider = false;
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
function showUnscoped() {
|
|
520
|
+
clearProviderChoice();
|
|
521
|
+
closeSource();
|
|
522
|
+
clearLiveStream(true);
|
|
523
|
+
state.chats = []; state.archivedChats = []; state.chat = null; state.events = []; state.capability = null; state.attachments = [];
|
|
524
|
+
ui.feed.replaceChildren();
|
|
525
|
+
const empty = document.createElement('div');
|
|
526
|
+
empty.className = 'ai-chat-empty';
|
|
527
|
+
const strong = document.createElement('strong');
|
|
528
|
+
strong.textContent = 'Open a project or workflow';
|
|
529
|
+
const copy = document.createElement('div');
|
|
530
|
+
copy.textContent = 'Each project or workflow keeps its own chat history in its folder.';
|
|
531
|
+
empty.append(strong, copy);
|
|
532
|
+
ui.feed.append(empty);
|
|
533
|
+
ui.title.textContent = 'AI Chat';
|
|
534
|
+
ui.scope.textContent = 'No project or workflow selected';
|
|
535
|
+
ui.context.textContent = document.getElementById('mode-workflows')?.getAttribute('aria-selected') === 'true'
|
|
536
|
+
? 'Workflow conversation' : 'Project conversation';
|
|
537
|
+
ui.input.value = '';
|
|
538
|
+
ui.input.disabled = true;
|
|
539
|
+
ui.attach.disabled = true;
|
|
540
|
+
ui.send.disabled = true;
|
|
541
|
+
ui.newChat.disabled = true;
|
|
542
|
+
ui.historyToggle.disabled = true;
|
|
543
|
+
ui.refresh.disabled = true;
|
|
544
|
+
ui.settingsToggle.disabled = true;
|
|
545
|
+
ui.settings.hidden = true; ui.settingsToggle.setAttribute('aria-expanded', 'false');
|
|
546
|
+
ui.skills.hidden = true; closePicker(); paintAttachments();
|
|
547
|
+
paintRecovery(); paintApproval(); paintSettings();
|
|
548
|
+
ui.stop.hidden = true; ui.send.hidden = false;
|
|
549
|
+
ui.rename.hidden = true;
|
|
550
|
+
ui.status.textContent = ''; ui.hint.classList.remove('error');
|
|
551
|
+
ui.hint.textContent = 'Open a project or workflow to start chatting.';
|
|
552
|
+
paintHistory(); paintUnread();
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
function formatDay(iso) {
|
|
556
|
+
const date = new Date(iso);
|
|
557
|
+
const today = new Date();
|
|
558
|
+
const yesterday = new Date(today); yesterday.setDate(today.getDate() - 1);
|
|
559
|
+
const key = (value) => `${value.getFullYear()}-${value.getMonth()}-${value.getDate()}`;
|
|
560
|
+
if (key(date) === key(today)) return 'Today';
|
|
561
|
+
if (key(date) === key(yesterday)) return 'Yesterday';
|
|
562
|
+
return new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric', year: date.getFullYear() === today.getFullYear() ? undefined : 'numeric' }).format(date);
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function restoreHistoryFocus(commandId) {
|
|
566
|
+
if (!commandId) return;
|
|
567
|
+
requestAnimationFrame(() => {
|
|
568
|
+
[...ui.history.querySelectorAll('[data-command-id]')]
|
|
569
|
+
.find((candidate) => candidate.dataset.commandId === commandId)?.focus();
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
function paintHistory() {
|
|
574
|
+
const focusedCommand = ui.history.contains(document.activeElement) ? document.activeElement?.dataset?.commandId : null;
|
|
575
|
+
ui.history.replaceChildren();
|
|
576
|
+
if (!state.scope) return;
|
|
577
|
+
|
|
578
|
+
const filters = [
|
|
579
|
+
{ id: 'all', label: 'All' },
|
|
580
|
+
{ id: 'instructor-answers', label: 'Instructor answers' },
|
|
581
|
+
];
|
|
582
|
+
const filterBar = document.createElement('div');
|
|
583
|
+
filterBar.className = 'ai-chat-history-filters';
|
|
584
|
+
filterBar.setAttribute('role', 'group');
|
|
585
|
+
filterBar.setAttribute('aria-label', 'Filter conversation history');
|
|
586
|
+
for (const filter of filters) {
|
|
587
|
+
const choice = button(filter.label, `shell.chat-history-filter#${commandInstance(filter.label)}`, 'ai-chat-history-filter');
|
|
588
|
+
choice.dataset.commandInstanceLabel = filter.label;
|
|
589
|
+
choice.setAttribute('aria-pressed', String(state.historyFilter === filter.id));
|
|
590
|
+
choice.addEventListener('click', () => setHistoryFilter(filter.id));
|
|
591
|
+
filterBar.append(choice);
|
|
592
|
+
}
|
|
593
|
+
ui.history.append(filterBar);
|
|
594
|
+
|
|
595
|
+
if (state.historyFilter === 'instructor-answers') {
|
|
596
|
+
if (state.historyLoading) {
|
|
597
|
+
const loading = document.createElement('div'); loading.className = 'ai-chat-history-empty';
|
|
598
|
+
loading.textContent = 'Loading Instructor answers…'; ui.history.append(loading);
|
|
599
|
+
} else if (!state.instructorAnswers.length) {
|
|
600
|
+
const empty = document.createElement('div'); empty.className = 'ai-chat-history-empty';
|
|
601
|
+
empty.append(document.createTextNode(`No Instructor answers in this ${state.scope.owner.kind} yet.`), document.createElement('br'),
|
|
602
|
+
document.createTextNode('Use Ask AI now in Instructor to start one.'));
|
|
603
|
+
ui.history.append(empty);
|
|
604
|
+
} else {
|
|
605
|
+
const groups = new Map();
|
|
606
|
+
for (const answer of state.instructorAnswers) {
|
|
607
|
+
const day = formatDay(answer.answerAt);
|
|
608
|
+
if (!groups.has(day)) groups.set(day, []);
|
|
609
|
+
groups.get(day).push(answer);
|
|
610
|
+
}
|
|
611
|
+
for (const [day, answers] of groups) {
|
|
612
|
+
const group = document.createElement('section'); group.className = 'ai-chat-history-group';
|
|
613
|
+
const label = document.createElement('div'); label.className = 'ai-chat-history-label'; label.textContent = day;
|
|
614
|
+
group.append(label);
|
|
615
|
+
for (const answer of answers) {
|
|
616
|
+
const row = button('', `shell.chat-instructor-answer#${answer.answerEventId}`, 'ai-chat-history-row ai-chat-instructor-answer');
|
|
617
|
+
row.dataset.commandInstanceLabel = `${answer.conversationTitle} · ${answer.question}`;
|
|
618
|
+
row.setAttribute('aria-label', `Open Instructor answer in ${answer.conversationTitle}, ${answer.question}, ${eventTime({ createdAt: answer.answerAt })}`);
|
|
619
|
+
const title = document.createElement('span'); title.textContent = answer.conversationTitle;
|
|
620
|
+
const meta = document.createElement('span'); meta.className = 'ai-chat-history-meta'; meta.textContent = eventTime({ createdAt: answer.answerAt });
|
|
621
|
+
const question = document.createElement('span'); question.className = 'ai-chat-history-question'; question.textContent = answer.question;
|
|
622
|
+
row.append(title, meta, question);
|
|
623
|
+
row.addEventListener('click', () => selectConversation(answer.chatId, {
|
|
624
|
+
replaceProviderChoice: true,
|
|
625
|
+
answerEventId: answer.answerEventId, answerTurnId: answer.answerTurnId,
|
|
626
|
+
answerSequence: answer.answerSequence,
|
|
627
|
+
}));
|
|
628
|
+
group.append(row);
|
|
629
|
+
}
|
|
630
|
+
ui.history.append(group);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
restoreHistoryFocus(focusedCommand);
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
const archivedChats = state.archivedChats.filter((chat) => Boolean(chat.archivedAt));
|
|
638
|
+
if (!state.chats.length && !archivedChats.length) {
|
|
639
|
+
const empty = document.createElement('div'); empty.className = 'ai-chat-history-empty';
|
|
640
|
+
empty.textContent = 'No conversations here yet.';
|
|
641
|
+
ui.history.append(empty); return;
|
|
642
|
+
}
|
|
643
|
+
appendChatHistoryGroups(state.chats, ui.history);
|
|
644
|
+
if (archivedChats.length) {
|
|
645
|
+
const archive = document.createElement('details'); archive.className = 'ai-chat-history-archived';
|
|
646
|
+
// History is refreshed in the background. Keep the disclosure state outside the DOM so a
|
|
647
|
+
// completed refresh cannot immediately undo the user's click on the native <summary>.
|
|
648
|
+
archive.open = state.archivedHistoryOpen;
|
|
649
|
+
const summary = document.createElement('summary'); summary.className = 'ai-chat-history-archived-summary';
|
|
650
|
+
summary.dataset.tip = 'Show archived conversations';
|
|
651
|
+
summary.textContent = `Archived (${archivedChats.length})`;
|
|
652
|
+
// `click` runs before the browser toggles <details>. Recording the intended next state here
|
|
653
|
+
// also covers a repaint that lands in that small interval; `toggle` confirms the final value.
|
|
654
|
+
summary.addEventListener('click', () => { state.archivedHistoryOpen = !archive.open; });
|
|
655
|
+
archive.addEventListener('toggle', () => { state.archivedHistoryOpen = archive.open; });
|
|
656
|
+
const archivedList = document.createElement('div'); archivedList.className = 'ai-chat-history-archived-list';
|
|
657
|
+
appendChatHistoryGroups(archivedChats, archivedList, { archived: true });
|
|
658
|
+
archive.append(summary, archivedList); ui.history.append(archive);
|
|
659
|
+
}
|
|
660
|
+
restoreHistoryFocus(focusedCommand);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
function appendChatHistoryGroups(chats, destination, { archived = false } = {}) {
|
|
664
|
+
const groups = new Map();
|
|
665
|
+
for (const chat of chats) {
|
|
666
|
+
const day = formatDay(archived ? chat.archivedAt || chat.updatedAt : chat.updatedAt);
|
|
667
|
+
if (!groups.has(day)) groups.set(day, []);
|
|
668
|
+
groups.get(day).push(chat);
|
|
669
|
+
}
|
|
670
|
+
for (const [day, chats] of groups) {
|
|
671
|
+
const group = document.createElement('section'); group.className = 'ai-chat-history-group';
|
|
672
|
+
const label = document.createElement('div'); label.className = 'ai-chat-history-label'; label.textContent = day;
|
|
673
|
+
group.append(label);
|
|
674
|
+
for (const chat of chats) {
|
|
675
|
+
// A history row contains a real Rename button, so it cannot itself be a button.
|
|
676
|
+
// Keep the row keyboard-operable without nesting interactive controls.
|
|
677
|
+
const row = document.createElement('div');
|
|
678
|
+
row.className = 'ai-chat-history-row';
|
|
679
|
+
row.tabIndex = 0;
|
|
680
|
+
row.setAttribute('role', 'button');
|
|
681
|
+
row.dataset.commandId = `shell.chat-history-item#${chat.chatId}`;
|
|
682
|
+
row.dataset.commandInstanceLabel = chat.title;
|
|
683
|
+
row.classList.toggle('active', chat.chatId === state.chat?.chatId);
|
|
684
|
+
row.classList.toggle('working', turnIsVisiblyActive(chat));
|
|
685
|
+
const unread = !archived && isUnreadConversation(chat);
|
|
686
|
+
row.classList.toggle('unread', unread);
|
|
687
|
+
const title = document.createElement('span'); title.className = 'ai-chat-history-title'; title.textContent = chat.title;
|
|
688
|
+
const meta = document.createElement('span'); meta.className = 'ai-chat-history-meta';
|
|
689
|
+
meta.textContent = archived
|
|
690
|
+
? `${providerLabels[chat.provider]} · Archived ${eventTime({ createdAt: chat.archivedAt || chat.updatedAt })}`
|
|
691
|
+
: `${providerLabels[chat.provider]} · Created ${eventTime(chat)}`;
|
|
692
|
+
row.setAttribute('aria-label', `${chat.title}, ${unread ? 'unread conversation, ' : ''}${providerLabels[chat.provider]}, ${chat.archivedAt ? 'archived' : 'created'} ${eventTime({ createdAt: chat.archivedAt || chat.createdAt })}`);
|
|
693
|
+
const rename = document.createElement('button');
|
|
694
|
+
rename.type = 'button'; rename.className = 'ai-chat-history-rename'; rename.textContent = '✎';
|
|
695
|
+
rename.dataset.commandId = `shell.chat-history-rename#${chat.chatId}`;
|
|
696
|
+
rename.dataset.commandInstanceLabel = chat.title;
|
|
697
|
+
rename.setAttribute('aria-label', `Rename ${chat.title}`);
|
|
698
|
+
rename.dataset.tip = 'Rename conversation';
|
|
699
|
+
rename.hidden = turnIsVisiblyActive(chat) || Boolean(chat.archivedAt);
|
|
700
|
+
rename.addEventListener('click', (event) => {
|
|
701
|
+
event.preventDefault(); event.stopPropagation(); beginHistoryRename(chat, title, rename);
|
|
702
|
+
});
|
|
703
|
+
const actions = document.createElement('span'); actions.className = 'ai-chat-history-actions';
|
|
704
|
+
const archive = document.createElement('button');
|
|
705
|
+
archive.type = 'button'; archive.className = 'ai-chat-history-action';
|
|
706
|
+
const isArchived = Boolean(chat.archivedAt);
|
|
707
|
+
archive.dataset.commandId = `shell.chat-history-${isArchived ? 'restore' : 'archive'}#${chat.chatId}`;
|
|
708
|
+
archive.dataset.commandInstanceLabel = chat.title;
|
|
709
|
+
archive.append(historyActionIcon(isArchived ? 'restore' : 'archive'));
|
|
710
|
+
archive.setAttribute('aria-label', `${isArchived ? 'Restore' : 'Archive'} ${chat.title}`);
|
|
711
|
+
archive.dataset.tip = isArchived ? 'Restore conversation' : 'Archive conversation';
|
|
712
|
+
archive.addEventListener('click', (event) => {
|
|
713
|
+
event.preventDefault(); event.stopPropagation();
|
|
714
|
+
if (isArchived) restoreConversation(chat, archive); else archiveConversation(chat, archive);
|
|
715
|
+
});
|
|
716
|
+
const remove = document.createElement('button');
|
|
717
|
+
remove.type = 'button'; remove.className = 'ai-chat-history-action danger'; remove.append(historyActionIcon('delete'));
|
|
718
|
+
remove.dataset.commandId = `shell.chat-history-delete#${chat.chatId}`;
|
|
719
|
+
remove.dataset.commandInstanceLabel = chat.title;
|
|
720
|
+
remove.setAttribute('aria-label', `Delete ${chat.title}`); remove.dataset.tip = 'Delete conversation permanently';
|
|
721
|
+
remove.addEventListener('click', (event) => {
|
|
722
|
+
event.preventDefault(); event.stopPropagation(); deleteConversation(chat, remove);
|
|
723
|
+
});
|
|
724
|
+
actions.append(rename, archive, remove);
|
|
725
|
+
actions.hidden = turnIsVisiblyActive(chat);
|
|
726
|
+
row.append(title, meta, actions);
|
|
727
|
+
if (turnIsVisiblyActive(chat)) {
|
|
728
|
+
const spinner = document.createElement('span'); spinner.className = 'ai-chat-history-working';
|
|
729
|
+
spinner.setAttribute('role', 'status'); spinner.setAttribute('aria-label', 'AI is working');
|
|
730
|
+
row.append(spinner);
|
|
731
|
+
}
|
|
732
|
+
row.addEventListener('click', () => selectConversation(chat.chatId, { focus: true, replaceProviderChoice: true }));
|
|
733
|
+
row.addEventListener('keydown', (event) => {
|
|
734
|
+
if (event.target !== row) return;
|
|
735
|
+
if (event.key === 'Enter' || event.key === ' ') {
|
|
736
|
+
event.preventDefault(); selectConversation(chat.chatId, { focus: true, replaceProviderChoice: true });
|
|
737
|
+
}
|
|
738
|
+
});
|
|
739
|
+
group.append(row);
|
|
740
|
+
}
|
|
741
|
+
destination.append(group);
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
function eventTime(event) {
|
|
746
|
+
return new Intl.DateTimeFormat(undefined, { hour: '2-digit', minute: '2-digit' }).format(new Date(event.createdAt));
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
function beginRename() {
|
|
750
|
+
if (!state.chat || turnIsVisiblyActive() || state.renaming) return;
|
|
751
|
+
state.renaming = { original: state.chat.title };
|
|
752
|
+
ui.title.contentEditable = 'true';
|
|
753
|
+
ui.title.setAttribute('role', 'textbox');
|
|
754
|
+
ui.title.setAttribute('aria-label', 'Conversation name');
|
|
755
|
+
ui.title.classList.add('editing');
|
|
756
|
+
ui.rename.hidden = true;
|
|
757
|
+
ui.title.focus();
|
|
758
|
+
document.getSelection()?.selectAllChildren(ui.title);
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
async function finishRename(save = true) {
|
|
762
|
+
if (!state.renaming) return;
|
|
763
|
+
const snapshot = captureChat();
|
|
764
|
+
const original = state.renaming.original;
|
|
765
|
+
const title = ui.title.textContent?.trim() || '';
|
|
766
|
+
state.renaming = null;
|
|
767
|
+
ui.title.contentEditable = 'false';
|
|
768
|
+
ui.title.removeAttribute('role');
|
|
769
|
+
ui.title.removeAttribute('aria-label');
|
|
770
|
+
ui.title.classList.remove('editing');
|
|
771
|
+
ui.rename.hidden = !state.chat || Boolean(state.chat.activeTurn);
|
|
772
|
+
if (!save || !title || title === original || !snapshot) {
|
|
773
|
+
ui.title.textContent = original;
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
try {
|
|
777
|
+
const chat = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/title`, {
|
|
778
|
+
method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, title }),
|
|
779
|
+
});
|
|
780
|
+
if (!sameChat(snapshot)) return;
|
|
781
|
+
state.chat = chat;
|
|
782
|
+
const index = state.chats.findIndex((item) => item.chatId === chat.chatId);
|
|
783
|
+
if (index >= 0) state.chats[index] = chat;
|
|
784
|
+
ui.title.textContent = chat.title;
|
|
785
|
+
paintHistory();
|
|
786
|
+
announce('Conversation name saved.');
|
|
787
|
+
} catch (error) {
|
|
788
|
+
if (!sameChat(snapshot)) return;
|
|
789
|
+
ui.title.textContent = original;
|
|
790
|
+
report(error, 'Could not rename conversation');
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
function beginHistoryRename(chat, titleNode, rename) {
|
|
795
|
+
if (turnIsVisiblyActive(chat) || titleNode.closest('.ai-chat-history-row')?.dataset.renaming === 'true') return;
|
|
796
|
+
const row = titleNode.closest('.ai-chat-history-row');
|
|
797
|
+
if (!row) return;
|
|
798
|
+
const snapshot = captureScope();
|
|
799
|
+
if (!snapshot) return;
|
|
800
|
+
const original = chat.title;
|
|
801
|
+
const input = document.createElement('input');
|
|
802
|
+
input.type = 'text'; input.className = 'ai-chat-history-title-input'; input.value = original;
|
|
803
|
+
input.setAttribute('aria-label', 'Conversation name');
|
|
804
|
+
row.dataset.renaming = 'true'; rename.hidden = true;
|
|
805
|
+
titleNode.replaceWith(input);
|
|
806
|
+
input.focus(); input.select();
|
|
807
|
+
let finished = false;
|
|
808
|
+
const finish = async (save = true) => {
|
|
809
|
+
if (finished) return;
|
|
810
|
+
finished = true;
|
|
811
|
+
const title = input.value.trim();
|
|
812
|
+
if (!save || !title || title === original) { if (sameScope(snapshot.scope, snapshot.generation)) paintHistory(); return; }
|
|
813
|
+
input.disabled = true;
|
|
814
|
+
try {
|
|
815
|
+
const updated = await request(`/api/chat/conversations/${encodeURIComponent(chat.chatId)}/title`, {
|
|
816
|
+
method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, title }),
|
|
817
|
+
});
|
|
818
|
+
if (!sameScope(snapshot.scope, snapshot.generation)) return;
|
|
819
|
+
const index = state.chats.findIndex((item) => item.chatId === updated.chatId);
|
|
820
|
+
if (index >= 0) state.chats[index] = updated;
|
|
821
|
+
if (state.chat?.chatId === updated.chatId) {
|
|
822
|
+
state.chat = updated;
|
|
823
|
+
ui.title.textContent = updated.title;
|
|
824
|
+
}
|
|
825
|
+
paintHistory(); announce('Conversation name saved.');
|
|
826
|
+
} catch (error) {
|
|
827
|
+
if (!sameScope(snapshot.scope, snapshot.generation)) return;
|
|
828
|
+
paintHistory(); report(error, 'Could not rename conversation');
|
|
829
|
+
}
|
|
830
|
+
};
|
|
831
|
+
input.addEventListener('keydown', (event) => {
|
|
832
|
+
if (event.key === 'Enter') { event.preventDefault(); finish(true); }
|
|
833
|
+
if (event.key === 'Escape') { event.preventDefault(); finish(false); }
|
|
834
|
+
});
|
|
835
|
+
input.addEventListener('blur', () => finish(true));
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
async function leaveConversationAfterRemoval(chatId, announcement, snapshot) {
|
|
839
|
+
if (!sameScope(snapshot.scope, snapshot.generation)) return;
|
|
840
|
+
state.chats = state.chats.filter((item) => item.chatId !== chatId);
|
|
841
|
+
state.archivedChats = state.archivedChats.filter((item) => item.chatId !== chatId);
|
|
842
|
+
paintHistory(); paintUnread();
|
|
843
|
+
if (state.chat?.chatId !== chatId) { announce(announcement); return; }
|
|
844
|
+
closeSource(); clearLiveStream(true);
|
|
845
|
+
state.chat = null; state.events = []; state.attachments = []; state.integrations = null;
|
|
846
|
+
if (state.chats.length) await selectConversation(state.chats[0].chatId, { focus: true, replaceProviderChoice: true });
|
|
847
|
+
else providerChooser();
|
|
848
|
+
if (sameScope(snapshot.scope, snapshot.generation)) announce(announcement);
|
|
849
|
+
}
|
|
850
|
+
|
|
851
|
+
async function archiveConversation(chat, trigger) {
|
|
852
|
+
const snapshot = captureScope();
|
|
853
|
+
if (!snapshot) return;
|
|
854
|
+
const confirm = window.flolessBridge?.formModal;
|
|
855
|
+
if (!confirm) { report(new Error('Could not open the confirmation dialog'), 'Could not archive conversation'); return; }
|
|
856
|
+
const approved = await confirm({
|
|
857
|
+
title: `Archive “${chat.title}”?`,
|
|
858
|
+
sub: 'It will be hidden from this list. You can restore it later.',
|
|
859
|
+
fields: [], okLabel: 'Archive chat', returnFocusTo: trigger,
|
|
860
|
+
});
|
|
861
|
+
if (!approved || !sameScope(snapshot.scope, snapshot.generation)) return;
|
|
862
|
+
trigger.disabled = true;
|
|
863
|
+
try {
|
|
864
|
+
const archived = await request(`/api/chat/conversations/${encodeURIComponent(chat.chatId)}/archive`, {
|
|
865
|
+
method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, archived: true }),
|
|
866
|
+
});
|
|
867
|
+
if (!sameScope(snapshot.scope, snapshot.generation)) return;
|
|
868
|
+
await leaveConversationAfterRemoval(chat.chatId, `Archived “${chat.title}”.`, snapshot);
|
|
869
|
+
if (!sameScope(snapshot.scope, snapshot.generation)) return;
|
|
870
|
+
state.archivedChats = [archived, ...state.archivedChats.filter((item) => item.chatId !== archived.chatId)];
|
|
871
|
+
paintHistory(); pulseArchivedBucket();
|
|
872
|
+
} catch (error) { if (sameScope(snapshot.scope, snapshot.generation)) report(error, 'Could not archive conversation'); }
|
|
873
|
+
finally { trigger.disabled = false; }
|
|
874
|
+
}
|
|
875
|
+
|
|
876
|
+
async function restoreConversation(chat, trigger) {
|
|
877
|
+
const snapshot = captureScope();
|
|
878
|
+
if (!snapshot) return;
|
|
879
|
+
trigger.disabled = true;
|
|
880
|
+
try {
|
|
881
|
+
const restored = await request(`/api/chat/conversations/${encodeURIComponent(chat.chatId)}/archive`, {
|
|
882
|
+
method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, archived: false }),
|
|
883
|
+
});
|
|
884
|
+
if (!sameScope(snapshot.scope, snapshot.generation)) return;
|
|
885
|
+
state.archivedChats = state.archivedChats.filter((item) => item.chatId !== restored.chatId);
|
|
886
|
+
state.chats = [restored, ...state.chats.filter((item) => item.chatId !== restored.chatId)];
|
|
887
|
+
if (state.chat?.chatId === restored.chatId) state.chat = restored;
|
|
888
|
+
paintHistory(); paintUnread(); pulseHistoryRow(restored.chatId);
|
|
889
|
+
announce(`Restored “${restored.title}”.`);
|
|
890
|
+
} catch (error) { if (sameScope(snapshot.scope, snapshot.generation)) report(error, 'Could not restore conversation'); }
|
|
891
|
+
finally { trigger.disabled = false; }
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
async function deleteConversation(chat, trigger) {
|
|
895
|
+
const snapshot = captureScope();
|
|
896
|
+
if (!snapshot) return;
|
|
897
|
+
const confirm = window.flolessBridge?.formModal;
|
|
898
|
+
if (!confirm) { report(new Error('Could not open the confirmation dialog'), 'Could not delete conversation'); return; }
|
|
899
|
+
const approved = await confirm({
|
|
900
|
+
title: `Delete “${chat.title}”?`,
|
|
901
|
+
sub: 'This permanently deletes this conversation and its attachments from this computer. This can’t be undone.',
|
|
902
|
+
fields: [], okLabel: 'Delete permanently', danger: true, returnFocusTo: trigger,
|
|
903
|
+
});
|
|
904
|
+
if (!approved || !sameScope(snapshot.scope, snapshot.generation)) return;
|
|
905
|
+
trigger.disabled = true;
|
|
906
|
+
try {
|
|
907
|
+
await request(`/api/chat/conversations/${encodeURIComponent(chat.chatId)}`, {
|
|
908
|
+
method: 'DELETE', body: JSON.stringify({ owner: snapshot.scope.owner }),
|
|
909
|
+
});
|
|
910
|
+
if (!sameScope(snapshot.scope, snapshot.generation)) return;
|
|
911
|
+
await leaveConversationAfterRemoval(chat.chatId, `Deleted “${chat.title}”.`, snapshot);
|
|
912
|
+
} catch (error) { if (sameScope(snapshot.scope, snapshot.generation)) report(error, 'Could not delete conversation'); }
|
|
913
|
+
finally { trigger.disabled = false; }
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
function pulseHistoryRow(chatId) {
|
|
917
|
+
const row = [...ui.history.querySelectorAll('.ai-chat-history-row')]
|
|
918
|
+
.find((candidate) => candidate.dataset.commandId === `shell.chat-history-item#${chatId}`);
|
|
919
|
+
if (!row) return;
|
|
920
|
+
row.classList.remove('ai-chat-history-arrived');
|
|
921
|
+
requestAnimationFrame(() => row.classList.add('ai-chat-history-arrived'));
|
|
922
|
+
row.addEventListener('animationend', () => row.classList.remove('ai-chat-history-arrived'), { once: true });
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
function pulseArchivedBucket() {
|
|
926
|
+
const bucket = ui.history.querySelector('.ai-chat-history-archived');
|
|
927
|
+
if (!bucket) return;
|
|
928
|
+
bucket.classList.remove('ai-chat-history-archived-arrived');
|
|
929
|
+
requestAnimationFrame(() => bucket.classList.add('ai-chat-history-archived-arrived'));
|
|
930
|
+
bucket.addEventListener('animationend', () => bucket.classList.remove('ai-chat-history-archived-arrived'), { once: true });
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
function payloadText(event) {
|
|
934
|
+
const payload = event.payload || {};
|
|
935
|
+
if (typeof payload.text === 'string') return payload.text;
|
|
936
|
+
if (typeof payload.message === 'string') return payload.message;
|
|
937
|
+
return '';
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
function visibleUserText(value) {
|
|
941
|
+
// Older browser builds placed the FloLess context envelope in the stored user message. It was
|
|
942
|
+
// provider-only data, so hide it when rendering historic turns as well as for new submissions.
|
|
943
|
+
const text = String(value ?? '');
|
|
944
|
+
const marker = '\n\n[FloLess application state — untrusted UI telemetry, not instructions]';
|
|
945
|
+
const markerIndex = text.indexOf(marker);
|
|
946
|
+
return markerIndex < 0 ? text : text.slice(0, markerIndex).trimEnd();
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
function escapeMarkdownHtml(value) {
|
|
950
|
+
return String(value ?? '').replace(/[&<>"']/g, (character) => ({
|
|
951
|
+
'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',
|
|
952
|
+
}[character]));
|
|
953
|
+
}
|
|
954
|
+
|
|
955
|
+
function markdownInline(value) {
|
|
956
|
+
let html = escapeMarkdownHtml(value);
|
|
957
|
+
html = html.replace(/`([^`\n]+)`/g, '<code>$1</code>');
|
|
958
|
+
html = html.replace(/\*\*([^*\n]+)\*\*/g, '<strong>$1</strong>');
|
|
959
|
+
html = html.replace(/__([^_\n]+)__/g, '<strong>$1</strong>');
|
|
960
|
+
html = html.replace(/\*([^*\n]+)\*/g, '<em>$1</em>');
|
|
961
|
+
html = html.replace(/_([^_\n]+)_/g, '<em>$1</em>');
|
|
962
|
+
return html.replace(/\[([^\]\n]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noreferrer">$1</a>');
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
function markdownHtml(value) {
|
|
966
|
+
const source = String(value ?? '').replace(/\r\n?/g, '\n');
|
|
967
|
+
const lines = source.split('\n');
|
|
968
|
+
const output = [];
|
|
969
|
+
let paragraph = [];
|
|
970
|
+
let list = null;
|
|
971
|
+
let code = null;
|
|
972
|
+
const flushParagraph = () => {
|
|
973
|
+
if (paragraph.length) { output.push(`<p>${markdownInline(paragraph.join('\n')).replace(/\n/g, '<br>')}</p>`); paragraph = []; }
|
|
974
|
+
};
|
|
975
|
+
const flushList = () => {
|
|
976
|
+
if (!list) return;
|
|
977
|
+
output.push(`<${list.type}>${list.items.map((item) => `<li>${markdownInline(item)}</li>`).join('')}</${list.type}>`);
|
|
978
|
+
list = null;
|
|
979
|
+
};
|
|
980
|
+
for (const line of lines) {
|
|
981
|
+
const fence = line.match(/^\s*```(?:[\w-]+)?\s*$/);
|
|
982
|
+
if (fence) {
|
|
983
|
+
flushParagraph(); flushList();
|
|
984
|
+
if (code === null) code = []; else { output.push(`<pre><code>${escapeMarkdownHtml(code.join('\n'))}</code></pre>`); code = null; }
|
|
985
|
+
continue;
|
|
986
|
+
}
|
|
987
|
+
if (code !== null) { code.push(line); continue; }
|
|
988
|
+
const heading = line.match(/^\s{0,3}(#{1,3})\s+(.+?)\s*#*$/);
|
|
989
|
+
if (heading) { flushParagraph(); flushList(); const level = heading[1].length; output.push(`<h${level}>${markdownInline(heading[2])}</h${level}>`); continue; }
|
|
990
|
+
const bullet = line.match(/^\s*[-*]\s+(.+)$/);
|
|
991
|
+
const numbered = line.match(/^\s*\d+[.)]\s+(.+)$/);
|
|
992
|
+
if (bullet || numbered) {
|
|
993
|
+
flushParagraph();
|
|
994
|
+
const type = bullet ? 'ul' : 'ol';
|
|
995
|
+
if (!list || list.type !== type) { flushList(); list = { type, items: [] }; }
|
|
996
|
+
list.items.push((bullet || numbered)[1]); continue;
|
|
997
|
+
}
|
|
998
|
+
if (!line.trim()) { flushParagraph(); flushList(); continue; }
|
|
999
|
+
paragraph.push(line);
|
|
1000
|
+
}
|
|
1001
|
+
if (code !== null) output.push(`<pre><code>${escapeMarkdownHtml(code.join('\n'))}</code></pre>`);
|
|
1002
|
+
flushParagraph(); flushList();
|
|
1003
|
+
return output.join('') || '<p></p>';
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
function visibleAssistantText(value) {
|
|
1007
|
+
// Provider-side citations and follow-up directives are instructions for this shell, not prose
|
|
1008
|
+
// for an AEC user. Never render their implementation syntax into the conversation.
|
|
1009
|
+
return String(value ?? '')
|
|
1010
|
+
.replace(/:codex-file-citation\{[^}\n]*\}/g, '')
|
|
1011
|
+
.replace(/(?:^|\n)\s*(?:[-*]\s*)?:codex-followup\[[^\]]*\]\{[^}]*\}[^\n]*/gu, '\n')
|
|
1012
|
+
.replace(/\n{3,}/g, '\n\n')
|
|
1013
|
+
.trim();
|
|
1014
|
+
}
|
|
1015
|
+
|
|
1016
|
+
function openChatAttachment(attachment) {
|
|
1017
|
+
return request(`/api/chat/conversations/${encodeURIComponent(state.chat.chatId)}/attachments/${encodeURIComponent(attachment.attachmentId)}/open`, {
|
|
1018
|
+
method: 'POST', body: JSON.stringify({ owner: state.scope.owner }),
|
|
1019
|
+
}).then(() => announce(`Opened ${attachment.fileName} in its default app.`))
|
|
1020
|
+
.catch((error) => report(error, `Could not open ${attachment.fileName}`));
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
function renderChatAttachment(attachment) {
|
|
1024
|
+
const target = document.createElement('div');
|
|
1025
|
+
target.className = 'ai-chat-message-attachment';
|
|
1026
|
+
target.tabIndex = 0;
|
|
1027
|
+
target.setAttribute('role', 'button');
|
|
1028
|
+
target.setAttribute('aria-label', `Open ${attachment.fileName} in its default app`);
|
|
1029
|
+
target.dataset.tip = 'Double-click to open in your default app';
|
|
1030
|
+
target.addEventListener('dblclick', () => { void openChatAttachment(attachment); });
|
|
1031
|
+
target.addEventListener('keydown', (event) => {
|
|
1032
|
+
if (event.key === 'Enter' || event.key === ' ') {
|
|
1033
|
+
event.preventDefault(); void openChatAttachment(attachment);
|
|
1034
|
+
}
|
|
1035
|
+
});
|
|
1036
|
+
if (attachment.mediaType.startsWith('image/')) {
|
|
1037
|
+
const image = document.createElement('img'); image.alt = attachment.fileName; image.loading = 'lazy';
|
|
1038
|
+
image.src = `/api/chat/conversations/${encodeURIComponent(state.chat.chatId)}/attachments/${encodeURIComponent(attachment.attachmentId)}?${ownerQuery()}`;
|
|
1039
|
+
target.append(image);
|
|
1040
|
+
} else {
|
|
1041
|
+
const file = document.createElement('span');
|
|
1042
|
+
file.textContent = `${attachment.mediaType === 'application/pdf' ? 'PDF' : 'File'} · ${attachment.fileName}`;
|
|
1043
|
+
target.append(file);
|
|
1044
|
+
}
|
|
1045
|
+
return target;
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
function renderMessage(event, role, text, streaming = false) {
|
|
1049
|
+
const item = document.createElement('article');
|
|
1050
|
+
item.className = `ai-chat-message ${role}${streaming ? ' streaming' : ''}`;
|
|
1051
|
+
item.dataset.eventSequence = String(event.sequence);
|
|
1052
|
+
item.dataset.eventId = event.eventId;
|
|
1053
|
+
item.tabIndex = -1;
|
|
1054
|
+
if (event.providerItemId) item.dataset.providerItemId = event.providerItemId;
|
|
1055
|
+
if (event.turnId) item.dataset.turnId = event.turnId;
|
|
1056
|
+
const head = document.createElement('div'); head.className = 'ai-chat-message-head';
|
|
1057
|
+
const who = document.createElement('span'); who.textContent = role === 'user' ? 'You' : providerLabels[state.chat?.provider] || 'AI';
|
|
1058
|
+
const time = document.createElement('time'); time.dateTime = event.createdAt; time.textContent = eventTime(event);
|
|
1059
|
+
const body = document.createElement('div'); body.className = 'ai-chat-message-body';
|
|
1060
|
+
body.innerHTML = markdownHtml(role === 'assistant' ? visibleAssistantText(text) : visibleUserText(text));
|
|
1061
|
+
head.append(who, time); item.append(head, body);
|
|
1062
|
+
if (role === 'user' && Array.isArray(event.payload?.attachmentIds)) {
|
|
1063
|
+
const attachments = event.payload.attachmentIds
|
|
1064
|
+
.map((id) => state.chat?.attachments?.find((candidate) => candidate.attachmentId === id))
|
|
1065
|
+
.filter(Boolean);
|
|
1066
|
+
if (attachments.length) {
|
|
1067
|
+
const gallery = document.createElement('div'); gallery.className = 'ai-chat-message-attachments';
|
|
1068
|
+
for (const attachment of attachments) {
|
|
1069
|
+
gallery.append(renderChatAttachment(attachment));
|
|
1070
|
+
}
|
|
1071
|
+
item.append(gallery);
|
|
1072
|
+
}
|
|
1073
|
+
}
|
|
1074
|
+
return item;
|
|
1075
|
+
}
|
|
1076
|
+
|
|
1077
|
+
function renderRequestCard(event) {
|
|
1078
|
+
const payload = event.payload || {};
|
|
1079
|
+
const item = document.createElement('article');
|
|
1080
|
+
item.className = 'ai-chat-request-card';
|
|
1081
|
+
item.dataset.eventSequence = String(event.sequence);
|
|
1082
|
+
item.dataset.eventId = event.eventId;
|
|
1083
|
+
item.dataset.requestId = String(payload.requestId || '');
|
|
1084
|
+
if (event.turnId) item.dataset.turnId = event.turnId;
|
|
1085
|
+
const head = document.createElement('div'); head.className = 'ai-chat-request-head';
|
|
1086
|
+
const label = document.createElement('strong');
|
|
1087
|
+
label.textContent = requestTypeLabels[payload.requestType] || String(payload.requestType || 'Request').replace(/-/g, ' ');
|
|
1088
|
+
const status = document.createElement('span'); status.className = 'ai-chat-request-status';
|
|
1089
|
+
status.textContent = requestStatusLabels[payload.requestStatus] || String(payload.requestStatus || 'pending').replace(/-/g, ' ');
|
|
1090
|
+
head.append(label, status);
|
|
1091
|
+
const body = document.createElement('p'); body.textContent = payloadText(event);
|
|
1092
|
+
item.append(head, body);
|
|
1093
|
+
if (Array.isArray(payload.sourceNames) && payload.sourceNames.length) {
|
|
1094
|
+
const sources = document.createElement('div'); sources.className = 'ai-chat-request-sources';
|
|
1095
|
+
for (const sourceName of payload.sourceNames) {
|
|
1096
|
+
const source = document.createElement('span'); source.textContent = String(sourceName); sources.append(source);
|
|
1097
|
+
}
|
|
1098
|
+
item.append(sources);
|
|
1099
|
+
}
|
|
1100
|
+
const actions = document.createElement('div'); actions.className = 'ai-chat-request-actions';
|
|
1101
|
+
const open = button('Open Requests', `shell.requests-open#${payload.requestId || 'linked request'}`);
|
|
1102
|
+
open.dataset.tip = 'Open the linked request and its detailed progress';
|
|
1103
|
+
open.addEventListener('click', () => window.flolessBridge?.openRequest?.(payload.requestId));
|
|
1104
|
+
actions.append(open); item.append(actions);
|
|
1105
|
+
return item;
|
|
1106
|
+
}
|
|
1107
|
+
|
|
1108
|
+
function renderEvent(event) {
|
|
1109
|
+
if (event.type === 'user-message' && event.payload?.source === 'request') return renderRequestCard(event);
|
|
1110
|
+
if (event.type === 'user-message') return renderMessage(event, 'user', payloadText(event));
|
|
1111
|
+
if (event.type === 'assistant-message') return renderMessage(event, 'assistant', payloadText(event), Boolean(event.payload?.delta));
|
|
1112
|
+
if (event.type === 'approval-requested' || event.type === 'approval-decided' || event.type === 'state') return null;
|
|
1113
|
+
const item = document.createElement('div');
|
|
1114
|
+
item.className = `ai-chat-event ${event.type === 'error' ? 'error' : ''}${event.type === 'knowledge-citation' ? ' knowledge' : ''}`;
|
|
1115
|
+
item.dataset.eventSequence = String(event.sequence);
|
|
1116
|
+
item.dataset.eventId = event.eventId;
|
|
1117
|
+
const label = document.createElement('strong');
|
|
1118
|
+
const labels = {
|
|
1119
|
+
attachment: 'Attachment', tool: 'AI action', error: 'Error', interrupted: 'Stopped', usage: 'AI usage',
|
|
1120
|
+
compaction: 'Conversation summary updated', 'knowledge-citation': 'Knowledge cited', state: 'Status', request: 'Request',
|
|
1121
|
+
};
|
|
1122
|
+
label.textContent = labels[event.type] || event.type;
|
|
1123
|
+
const payload = event.payload || {};
|
|
1124
|
+
let detail = event.type === 'error' ? errorMessage(payloadText(event)) : payloadText(event);
|
|
1125
|
+
if (!detail && event.type === 'tool') {
|
|
1126
|
+
const toolLabels = { provider: 'AI provider', integration: 'Connected service', attachment: 'Attachment', knowledge: 'Knowledge', filesystem: 'Project files' };
|
|
1127
|
+
const statusLabels = { started: 'started', completed: 'completed', failed: 'failed', denied: 'not allowed' };
|
|
1128
|
+
detail = [toolLabels[payload.tool] || 'AI action', statusLabels[payload.status] || payload.status].filter(Boolean).join(' · ');
|
|
1129
|
+
}
|
|
1130
|
+
if (!detail && event.type === 'knowledge-citation') detail = Array.isArray(payload.pageSlugs) ? payload.pageSlugs.join(', ') : '';
|
|
1131
|
+
if (!detail && event.type === 'interrupted') detail = 'The AI response was interrupted.';
|
|
1132
|
+
if (!detail && event.type === 'usage') {
|
|
1133
|
+
detail = 'Usage updated';
|
|
1134
|
+
}
|
|
1135
|
+
item.append(label, document.createTextNode(detail ? ` · ${detail}` : ''));
|
|
1136
|
+
return item;
|
|
1137
|
+
}
|
|
1138
|
+
|
|
1139
|
+
function animatedDots() {
|
|
1140
|
+
const dots = document.createElement('span'); dots.className = 'ai-chat-live-dots'; dots.setAttribute('aria-hidden', 'true');
|
|
1141
|
+
dots.append(document.createElement('i'), document.createElement('i'), document.createElement('i'));
|
|
1142
|
+
return dots;
|
|
1143
|
+
}
|
|
1144
|
+
|
|
1145
|
+
function renderLiveStatus(event) {
|
|
1146
|
+
const item = document.createElement('div'); item.className = 'ai-chat-live-status';
|
|
1147
|
+
item.classList.add('dots-only');
|
|
1148
|
+
item.setAttribute('aria-hidden', 'true');
|
|
1149
|
+
const label = document.createElement('span'); label.className = 'ai-chat-live-label';
|
|
1150
|
+
const dots = animatedDots();
|
|
1151
|
+
item.append(label, dots); return item;
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
function announceLiveResponseOnce() {
|
|
1155
|
+
const turnId = state.chat?.activeTurn?.turnId || null;
|
|
1156
|
+
if (!turnId) {
|
|
1157
|
+
state.liveStatusTurnId = null;
|
|
1158
|
+
// The screen-reader announcement is a transient status. Once the durable turn ends,
|
|
1159
|
+
// leaving its text behind makes the finished chat sound as though it is still working.
|
|
1160
|
+
ui.status.textContent = '';
|
|
1161
|
+
return;
|
|
1162
|
+
}
|
|
1163
|
+
if (state.liveStatusTurnId === turnId) return;
|
|
1164
|
+
state.liveStatusTurnId = turnId;
|
|
1165
|
+
const provider = providerLabels[state.chat?.provider] || 'AI';
|
|
1166
|
+
ui.status.textContent = '';
|
|
1167
|
+
requestAnimationFrame(() => { ui.status.textContent = `${provider} is responding.`; });
|
|
1168
|
+
}
|
|
1169
|
+
|
|
1170
|
+
function renderedAnswerTarget(events, eventId, turnId) {
|
|
1171
|
+
if (turnId) {
|
|
1172
|
+
return [...events].reverse().find((event) => event.turnId === turnId && event.type === 'assistant-message') || null;
|
|
1173
|
+
}
|
|
1174
|
+
return events.find((event) => event.eventId === eventId && event.type === 'assistant-message') || null;
|
|
1175
|
+
}
|
|
1176
|
+
|
|
1177
|
+
function clearAnswerJump() {
|
|
1178
|
+
if (state.answerJumpTimer) clearTimeout(state.answerJumpTimer);
|
|
1179
|
+
state.answerJumpTimer = null;
|
|
1180
|
+
state.answerJump = null;
|
|
1181
|
+
ui.feed.querySelector('.answer-jump')?.classList.remove('answer-jump');
|
|
1182
|
+
}
|
|
1183
|
+
|
|
1184
|
+
function restoreAnswerJump() {
|
|
1185
|
+
const jump = state.answerJump;
|
|
1186
|
+
if (!jump || state.chat?.chatId !== jump.chatId) return;
|
|
1187
|
+
if (Date.now() >= jump.expiresAt) { clearAnswerJump(); return; }
|
|
1188
|
+
const target = [...ui.feed.querySelectorAll('[data-event-id]')]
|
|
1189
|
+
.find((item) => item.dataset.eventId === jump.eventId);
|
|
1190
|
+
if (!target) return;
|
|
1191
|
+
target.classList.add('answer-jump');
|
|
1192
|
+
target.focus({ preventScroll: true });
|
|
1193
|
+
target.scrollIntoView({ block: 'center' });
|
|
1194
|
+
}
|
|
1195
|
+
|
|
1196
|
+
function paintEvents(options = {}) {
|
|
1197
|
+
announceLiveResponseOnce();
|
|
1198
|
+
const nearBottom = ui.feed.scrollHeight - ui.feed.scrollTop - ui.feed.clientHeight < 56;
|
|
1199
|
+
ui.feed.replaceChildren();
|
|
1200
|
+
if (!state.events.length) {
|
|
1201
|
+
const empty = document.createElement('div'); empty.className = 'ai-chat-empty';
|
|
1202
|
+
const strong = document.createElement('strong');
|
|
1203
|
+
const copy = document.createElement('div');
|
|
1204
|
+
if (providerReady()) {
|
|
1205
|
+
strong.textContent = 'Ready when you are';
|
|
1206
|
+
copy.textContent = `This ${providerLabels[state.chat?.provider] || 'AI'} conversation is stored with ${state.scope?.label || 'this work'}.`;
|
|
1207
|
+
} else if (state.capability?.runtime && state.capability.runtime.state !== 'installed') {
|
|
1208
|
+
const notice = runtimeNotice(state.chat?.provider, state.capability.runtime);
|
|
1209
|
+
strong.textContent = notice.title;
|
|
1210
|
+
copy.textContent = state.capability.runtime.state === 'failed'
|
|
1211
|
+
? notice.body
|
|
1212
|
+
: 'You can write your first message now. Send becomes available when setup finishes.';
|
|
1213
|
+
} else {
|
|
1214
|
+
strong.textContent = `${providerLabels[state.chat?.provider] || 'AI'} needs attention`;
|
|
1215
|
+
copy.textContent = capabilityMessage(state.chat?.provider, state.capability?.reason);
|
|
1216
|
+
}
|
|
1217
|
+
empty.append(strong, copy); ui.feed.append(empty);
|
|
1218
|
+
} else {
|
|
1219
|
+
let assistant = null;
|
|
1220
|
+
const flushAssistant = () => {
|
|
1221
|
+
if (!assistant) return;
|
|
1222
|
+
const rendered = renderedLiveAssistantText(assistant.event, assistant.text);
|
|
1223
|
+
ui.feed.append(renderMessage(assistant.event, 'assistant', rendered.text, rendered.streaming));
|
|
1224
|
+
assistant = null;
|
|
1225
|
+
};
|
|
1226
|
+
for (const event of state.events) {
|
|
1227
|
+
if (event.type === 'assistant-message' && event.payload?.delta) {
|
|
1228
|
+
// Codex keeps a stable item id while Claude's SDK may assign one per stream packet.
|
|
1229
|
+
// Consecutive deltas in the same turn are one visible answer; a tool or other event
|
|
1230
|
+
// flushes the block, so genuinely separate assistant items remain separate.
|
|
1231
|
+
if (assistant && assistant.event.turnId === event.turnId) {
|
|
1232
|
+
assistant.event = event;
|
|
1233
|
+
assistant.text += payloadText(event);
|
|
1234
|
+
} else {
|
|
1235
|
+
flushAssistant();
|
|
1236
|
+
assistant = { event, text: payloadText(event) };
|
|
1237
|
+
}
|
|
1238
|
+
continue;
|
|
1239
|
+
}
|
|
1240
|
+
// Provider tools commonly split one answer into before/after chunks. They are not prose,
|
|
1241
|
+
// so keep collecting same-turn deltas across them instead of rendering abandoned fragments.
|
|
1242
|
+
if (['tool', 'usage', 'knowledge-citation', 'attachment', 'compaction', 'state'].includes(event.type)) continue;
|
|
1243
|
+
flushAssistant();
|
|
1244
|
+
const node = renderEvent(event);
|
|
1245
|
+
if (node) ui.feed.append(node);
|
|
1246
|
+
}
|
|
1247
|
+
flushAssistant();
|
|
1248
|
+
// A provider can send text before it finishes tools, usage, or its terminal turn signal.
|
|
1249
|
+
// Keep this fixed activity row visible for the full durable turn (and while text drains)
|
|
1250
|
+
// so an intermittent stream never looks like a failed response.
|
|
1251
|
+
if (turnIsVisiblyActive() || hasPendingLiveStream()) ui.feed.append(renderLiveStatus());
|
|
1252
|
+
}
|
|
1253
|
+
restoreAnswerJump();
|
|
1254
|
+
if (!state.answerJump && (nearBottom || options.forceBottom)) requestAnimationFrame(() => { ui.feed.scrollTop = ui.feed.scrollHeight; });
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
function paintApproval() {
|
|
1258
|
+
shell.querySelector('.ai-chat-approval')?.remove();
|
|
1259
|
+
const approval = state.chat?.pendingApproval;
|
|
1260
|
+
const deciding = Boolean(approval && state.decidingApprovalIds.has(approval.approvalId));
|
|
1261
|
+
shell.dataset.approvalPending = String(Boolean(approval) && !deciding);
|
|
1262
|
+
document.dispatchEvent(new CustomEvent('floless:chat-indicator'));
|
|
1263
|
+
if (!approval || deciding) return;
|
|
1264
|
+
const card = document.createElement('section'); card.className = 'ai-chat-approval';
|
|
1265
|
+
const heading = document.createElement('strong'); heading.textContent = 'Approval needed';
|
|
1266
|
+
const copy = document.createElement('p'); copy.textContent = approval.summary;
|
|
1267
|
+
const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
|
|
1268
|
+
const deny = button('Deny', 'shell.chat-approval-deny');
|
|
1269
|
+
const allow = button('Approve once', 'shell.chat-approval-allow', 'allow');
|
|
1270
|
+
deny.addEventListener('click', () => decideApproval('deny'));
|
|
1271
|
+
allow.addEventListener('click', () => decideApproval('allow'));
|
|
1272
|
+
actions.append(deny, allow); card.append(heading, copy, actions);
|
|
1273
|
+
shell.insertBefore(card, ui.recovery);
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
// FloLess installs its own tested copy of Claude Code / Codex. While that copy is being set up (or
|
|
1277
|
+
// could not be), the server reports it on the capability as `runtime`; this card renders that state
|
|
1278
|
+
// and relays the two user intents. The server owns every state and decision.
|
|
1279
|
+
const RUNTIME_NETWORK_BLOCKED = 'Your network or security software blocked the download. Ask your IT team to allow FloLess to reach the npm registry, then try again.';
|
|
1280
|
+
const RUNTIME_NOT_TESTED_BUILD = 'The download didn’t match the version FloLess was tested with, so FloLess didn’t use it. Try again.';
|
|
1281
|
+
const RUNTIME_FAILURE_COPY = {
|
|
1282
|
+
offline: 'FloLess couldn’t download it. Check your internet connection, then try again.',
|
|
1283
|
+
'proxy-auth': RUNTIME_NETWORK_BLOCKED,
|
|
1284
|
+
'tls-intercepted': RUNTIME_NETWORK_BLOCKED,
|
|
1285
|
+
'registry-refused': RUNTIME_NETWORK_BLOCKED,
|
|
1286
|
+
integrity: RUNTIME_NOT_TESTED_BUILD,
|
|
1287
|
+
'unexpected-files': RUNTIME_NOT_TESTED_BUILD,
|
|
1288
|
+
'version-mismatch': RUNTIME_NOT_TESTED_BUILD,
|
|
1289
|
+
damaged: 'Some of its files are missing or changed. Try again to reinstall it.',
|
|
1290
|
+
'disk-space': 'There isn’t enough free disk space. Free up about 1 GB, then try again.',
|
|
1291
|
+
'blocked-by-policy': 'Your computer’s security settings blocked it. Ask your IT team to allow programs in the FloLess data folder.',
|
|
1292
|
+
'unsafe-runtime-folder': 'FloLess won’t use its runtimes folder because it points somewhere else. Ask your IT team to check it.',
|
|
1293
|
+
'path-too-long': 'The FloLess data folder path is too long for Windows to start programs from. Ask your IT team to move it to a shorter path.',
|
|
1294
|
+
'launch-failed': 'Windows couldn’t start it on this computer. Try again, or use Report an issue if it keeps happening.',
|
|
1295
|
+
'maintenance-pending': 'FloLess is still starting up. Try again in a moment.',
|
|
1296
|
+
'no-npm': 'FloLess needs Node.js to set this up. Install Node.js, then restart FloLess.',
|
|
1297
|
+
'npm-too-old': 'FloLess needs a newer Node.js to set this up. Update Node.js, then restart FloLess.',
|
|
1298
|
+
'restart-required': 'Restart FloLess to repair it.',
|
|
1299
|
+
'in-use': 'Another FloLess window is using it. Close other FloLess windows, then try again.',
|
|
1300
|
+
cancelled: 'Setup was cancelled. Try again when you’re ready.',
|
|
1301
|
+
'timed-out': 'Setup took too long and was stopped. This is often a slow connection. Try again.',
|
|
1302
|
+
};
|
|
1303
|
+
|
|
1304
|
+
function runtimeNotice(provider, status) {
|
|
1305
|
+
const label = providerLabels[provider] || 'AI service';
|
|
1306
|
+
if (status.state === 'preparing' || status.state === 'not-installed') {
|
|
1307
|
+
const elsewhere = status.owner === 'another-process';
|
|
1308
|
+
return {
|
|
1309
|
+
title: elsewhere ? `Setting up ${label} in another window` : `Setting up ${label}`,
|
|
1310
|
+
body: elsewhere
|
|
1311
|
+
? `Another FloLess window is installing ${label}. This chat unlocks as soon as it finishes.`
|
|
1312
|
+
: `FloLess is installing the ${label} version it was tested with. This happens once per FloLess update.`,
|
|
1313
|
+
action: status.owner === 'this-process' ? 'cancel' : null,
|
|
1314
|
+
};
|
|
1315
|
+
}
|
|
1316
|
+
const untested = status.npmUntested ? ' Your npm is newer than FloLess has tested; updating FloLess may help.' : '';
|
|
1317
|
+
return {
|
|
1318
|
+
title: `${label} couldn’t be set up`,
|
|
1319
|
+
body: (RUNTIME_FAILURE_COPY[status.code]
|
|
1320
|
+
|| `Something went wrong while installing it (${status.npmCode || status.code || 'unknown'}). Try again, or use Report an issue if it keeps happening.`) + untested,
|
|
1321
|
+
action: status.retryable ? 'retry' : null,
|
|
1322
|
+
};
|
|
1323
|
+
}
|
|
1324
|
+
|
|
1325
|
+
function paintRuntime() {
|
|
1326
|
+
const existing = shell.querySelector('.ai-chat-runtime');
|
|
1327
|
+
const status = state.chat ? state.capability?.runtime : null;
|
|
1328
|
+
if (!status || status.state === 'installed' || status.state === 'unsupported-platform') { existing?.remove(); stopRuntimePoll(); return; }
|
|
1329
|
+
const notice = runtimeNotice(state.chat.provider, status);
|
|
1330
|
+
const settingUp = status.state === 'preparing' || status.state === 'not-installed';
|
|
1331
|
+
// Polls repeat the same state every two seconds; rebuilding the card each time would swap its button
|
|
1332
|
+
// out from under the pointer (a lost click) and drop keyboard focus. Rebuild only when it changes.
|
|
1333
|
+
const key = `${state.chat.chatId}:${status.state}:${status.owner || ''}:${status.code || ''}:${status.retryable ? 1 : 0}`;
|
|
1334
|
+
if (existing?.dataset.runtimeKey === key && existing.isConnected) { if (settingUp) startRuntimePoll(); return; }
|
|
1335
|
+
existing?.remove();
|
|
1336
|
+
const card = document.createElement('section');
|
|
1337
|
+
card.className = `ai-chat-runtime${settingUp ? '' : ' is-failed'}`;
|
|
1338
|
+
card.dataset.runtimeKey = key;
|
|
1339
|
+
const heading = document.createElement('strong'); heading.textContent = notice.title;
|
|
1340
|
+
if (settingUp) {
|
|
1341
|
+
const dots = document.createElement('span'); dots.className = 'ai-chat-live-dots'; dots.setAttribute('aria-hidden', 'true');
|
|
1342
|
+
dots.append(document.createElement('i'), document.createElement('i'), document.createElement('i'));
|
|
1343
|
+
heading.append(dots);
|
|
1344
|
+
}
|
|
1345
|
+
const copy = document.createElement('p'); copy.textContent = notice.body;
|
|
1346
|
+
card.append(heading, copy);
|
|
1347
|
+
// The panel's one live region announces each state change once, not every 2-second poll.
|
|
1348
|
+
const announced = `${state.chat.chatId}:${status.state}:${status.owner || status.code || ''}`;
|
|
1349
|
+
if (state.runtimeAnnounced !== announced) { state.runtimeAnnounced = announced; announce(`${notice.title}. ${notice.body}`); }
|
|
1350
|
+
if (settingUp) startRuntimePoll();
|
|
1351
|
+
else stopRuntimePoll();
|
|
1352
|
+
if (notice.action) {
|
|
1353
|
+
const actions = document.createElement('div'); actions.className = 'ai-chat-approval-actions';
|
|
1354
|
+
const action = notice.action === 'retry'
|
|
1355
|
+
? button('Try again', 'shell.chat-runtime-retry', 'allow')
|
|
1356
|
+
: button('Cancel setup', 'shell.chat-runtime-cancel');
|
|
1357
|
+
action.addEventListener('click', () => void runtimeAction(notice.action, action));
|
|
1358
|
+
actions.append(action); card.append(actions);
|
|
1359
|
+
}
|
|
1360
|
+
shell.insertBefore(card, ui.recovery);
|
|
1361
|
+
}
|
|
1362
|
+
|
|
1363
|
+
async function runtimeAction(kind, control) {
|
|
1364
|
+
const provider = state.chat?.provider;
|
|
1365
|
+
if (!provider) return;
|
|
1366
|
+
control.disabled = true;
|
|
1367
|
+
try {
|
|
1368
|
+
const body = await request(`/api/managed-runtimes/${provider}/${kind === 'retry' ? 'prepare' : 'cancel'}`, { method: 'POST', body: '{}' });
|
|
1369
|
+
if (state.chat?.provider !== provider || !state.capability) return;
|
|
1370
|
+
state.capability = { ...state.capability, runtime: body.runtime };
|
|
1371
|
+
if (body.runtime?.state === 'installed') { await runtimeBecameReady(captureChat()); return; }
|
|
1372
|
+
paintRuntime(); clearReport();
|
|
1373
|
+
} catch (error) {
|
|
1374
|
+
control.disabled = false; // the card did not change, so keep its action usable
|
|
1375
|
+
// Another FloLess window owns this setup; refresh the status instead of reporting an error.
|
|
1376
|
+
if (error?.code === 'not-owner') void pollRuntime();
|
|
1377
|
+
else report(error, kind === 'retry' ? 'Could not start setup' : 'Could not cancel setup');
|
|
1378
|
+
} finally {
|
|
1379
|
+
updateSendState();
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
function startRuntimePoll() {
|
|
1384
|
+
if (state.runtimePoll) return;
|
|
1385
|
+
state.runtimePoll = setInterval(() => void pollRuntime(), 2000);
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
function stopRuntimePoll() {
|
|
1389
|
+
if (state.runtimePoll) { clearInterval(state.runtimePoll); state.runtimePoll = null; }
|
|
1390
|
+
}
|
|
1391
|
+
|
|
1392
|
+
async function pollRuntime() {
|
|
1393
|
+
const snapshot = captureChat();
|
|
1394
|
+
if (!snapshot || !state.capability?.runtime) { stopRuntimePoll(); return; }
|
|
1395
|
+
// A slow server can take longer than the 2-second tick; never stack a second poll behind the first.
|
|
1396
|
+
if (state.runtimePollInFlight) return;
|
|
1397
|
+
state.runtimePollInFlight = true;
|
|
1398
|
+
let body;
|
|
1399
|
+
try { body = await request('/api/managed-runtimes', { timeoutMs: 10000 }); } catch { return; } finally { state.runtimePollInFlight = false; }
|
|
1400
|
+
if (!sameChat(snapshot)) return;
|
|
1401
|
+
const next = (body.runtimes || []).find((row) => row.runtime === state.chat.provider);
|
|
1402
|
+
if (!next) return;
|
|
1403
|
+
if (next.state === 'installed') { await runtimeBecameReady(snapshot); return; }
|
|
1404
|
+
state.capability = { ...state.capability, runtime: next };
|
|
1405
|
+
paintRuntime(); clearReport();
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
// Setup finished: the real capability (sign-in, models) replaces the runtime card. readCapability never
|
|
1409
|
+
// throws — a failure becomes a capability with a reason — so the chat cannot stay in a setup state.
|
|
1410
|
+
async function runtimeBecameReady(snapshot) {
|
|
1411
|
+
stopRuntimePoll();
|
|
1412
|
+
if (!snapshot) return;
|
|
1413
|
+
await loadCapability();
|
|
1414
|
+
if (!sameChat(snapshot)) return;
|
|
1415
|
+
paintConversation();
|
|
1416
|
+
clearReport();
|
|
1417
|
+
if (providerReady()) void request(`/api/chat/conversations/${encodeURIComponent(state.chat.chatId)}/warm`, {
|
|
1418
|
+
method: 'POST', body: JSON.stringify({ owner: state.scope.owner }),
|
|
1419
|
+
}).catch(() => {});
|
|
1420
|
+
}
|
|
1421
|
+
|
|
1422
|
+
function paintAttachments() {
|
|
1423
|
+
ui.attachments.replaceChildren();
|
|
1424
|
+
for (const attachment of state.attachments) {
|
|
1425
|
+
const chip = document.createElement('span'); chip.className = 'ai-chat-attachment';
|
|
1426
|
+
if (attachment.mediaType.startsWith('image/')) {
|
|
1427
|
+
const preview = document.createElement('img'); preview.alt = ''; preview.loading = 'lazy';
|
|
1428
|
+
preview.src = `/api/chat/conversations/${encodeURIComponent(state.chat.chatId)}/attachments/${encodeURIComponent(attachment.attachmentId)}?${ownerQuery()}`;
|
|
1429
|
+
chip.append(preview);
|
|
1430
|
+
}
|
|
1431
|
+
const name = document.createElement('span'); name.textContent = attachment.fileName;
|
|
1432
|
+
const remove = button('×', `shell.chat-attachment-remove#${attachment.attachmentId}`);
|
|
1433
|
+
remove.dataset.commandInstanceLabel = attachment.fileName;
|
|
1434
|
+
remove.setAttribute('aria-label', `Remove ${attachment.fileName} from the next message`);
|
|
1435
|
+
remove.dataset.tip = 'Remove from the next message';
|
|
1436
|
+
remove.addEventListener('click', async () => {
|
|
1437
|
+
remove.disabled = true;
|
|
1438
|
+
try {
|
|
1439
|
+
await request(`/api/chat/conversations/${encodeURIComponent(state.chat.chatId)}/attachments/${encodeURIComponent(attachment.attachmentId)}`, {
|
|
1440
|
+
method: 'DELETE', body: JSON.stringify({ owner: state.scope.owner }),
|
|
1441
|
+
});
|
|
1442
|
+
state.attachments = state.attachments.filter((item) => item.attachmentId !== attachment.attachmentId);
|
|
1443
|
+
state.chat.attachments = (state.chat.attachments || []).filter((item) => item.attachmentId !== attachment.attachmentId);
|
|
1444
|
+
paintAttachments(); updateSendState(); ui.input.focus();
|
|
1445
|
+
} catch (error) { remove.disabled = false; report(error, 'Could not remove attachment'); }
|
|
1446
|
+
});
|
|
1447
|
+
chip.append(name, remove); ui.attachments.append(chip);
|
|
1448
|
+
}
|
|
1449
|
+
ui.attachments.hidden = state.attachments.length === 0;
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
function selectedModel() {
|
|
1453
|
+
if (!state.capability) return null;
|
|
1454
|
+
return state.capability.models.find((model) => model.id === state.chat?.settings.model)
|
|
1455
|
+
|| preferredModel(state.chat?.provider, state.capability.models)
|
|
1456
|
+
|| state.capability.models[0] || null;
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
function preferredModel(provider, models) {
|
|
1460
|
+
if (!provider || !Array.isArray(models)) return null;
|
|
1461
|
+
const pattern = provider === 'codex' ? /gpt[- .]?5\.6[- .]?terra/i : /opus/i;
|
|
1462
|
+
return models.find((model) => pattern.test(`${model.id} ${model.label}`)) || null;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
function preferredSettings(provider, capability) {
|
|
1466
|
+
const model = preferredModel(provider, capability?.models || []);
|
|
1467
|
+
if (!model) return null;
|
|
1468
|
+
const medium = (model.efforts || []).find((effort) => effort.toLowerCase() === 'medium') || null;
|
|
1469
|
+
return { model: model.id, effort: medium };
|
|
1470
|
+
}
|
|
1471
|
+
|
|
1472
|
+
function effortLabel(value) {
|
|
1473
|
+
const text = String(value || '');
|
|
1474
|
+
return text ? text.charAt(0).toUpperCase() + text.slice(1) : '';
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
function paintSettings() {
|
|
1478
|
+
const chat = state.chat;
|
|
1479
|
+
ui.settingsToggle.disabled = !chat;
|
|
1480
|
+
ui.provider.querySelector('strong').textContent = chat ? providerLabels[chat.provider] : '—';
|
|
1481
|
+
const model = selectedModel();
|
|
1482
|
+
ui.model.querySelector('strong').textContent = chat?.settings.model ? (model?.label || chat.settings.model) : (model?.label || 'Choose model');
|
|
1483
|
+
const medium = (model?.efforts || []).find((effort) => effort.toLowerCase() === 'medium');
|
|
1484
|
+
ui.effort.querySelector('strong').textContent = effortLabel(chat?.settings.effort || medium || model?.efforts?.[0]) || 'Choose effort';
|
|
1485
|
+
ui.permission.querySelector('strong').textContent = permissionLabels[chat?.settings.permissionProfile] || 'Read only';
|
|
1486
|
+
const bindings = chat?.integrationBindings || [];
|
|
1487
|
+
ui.integrations.querySelector('strong').textContent = bindings.length
|
|
1488
|
+
? `${bindings.length} FloLess account${bindings.length === 1 ? '' : 's'}`
|
|
1489
|
+
: `Using ${providerLabels[chat?.provider] || 'provider'} connections`;
|
|
1490
|
+
const frozen = !chat || Boolean(chat.activeTurn) || !state.capability?.available;
|
|
1491
|
+
ui.model.disabled = frozen; ui.effort.disabled = frozen; ui.permission.disabled = frozen;
|
|
1492
|
+
ui.integrations.disabled = frozen || Boolean(chat?.nativeSessionId);
|
|
1493
|
+
const integrationBlocked = chat?.nativeSessionId
|
|
1494
|
+
? 'Connected accounts are fixed after the first message. Start a new chat to use another account.'
|
|
1495
|
+
: !chat ? 'Open a conversation first.'
|
|
1496
|
+
: chat.activeTurn ? 'Connected accounts cannot change during an active turn.'
|
|
1497
|
+
: !state.capability?.available ? capabilityMessage(chat.provider, state.capability?.reason)
|
|
1498
|
+
: '';
|
|
1499
|
+
ui.integrations.dataset.tip = integrationBlocked || 'Choose which connected account this chat can use';
|
|
1500
|
+
if (integrationBlocked) ui.integrations.dataset.blockedReason = integrationBlocked;
|
|
1501
|
+
else delete ui.integrations.dataset.blockedReason;
|
|
1502
|
+
paintDesktopStatus();
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
function paintDesktopStatus() {
|
|
1506
|
+
const desktop = state.desktop;
|
|
1507
|
+
if (!state.chat) {
|
|
1508
|
+
ui.desktopValue.textContent = '—';
|
|
1509
|
+
ui.desktopReason.textContent = 'Open a conversation to check whether the desktop app can continue it.';
|
|
1510
|
+
return;
|
|
1511
|
+
}
|
|
1512
|
+
if (!desktop) {
|
|
1513
|
+
ui.desktopValue.textContent = 'Checking…';
|
|
1514
|
+
ui.desktopReason.textContent = 'Checking whether the installed desktop app can continue this chat.';
|
|
1515
|
+
return;
|
|
1516
|
+
}
|
|
1517
|
+
ui.desktopValue.textContent = 'Unavailable';
|
|
1518
|
+
const provider = providerLabels[state.chat.provider];
|
|
1519
|
+
const reasons = {
|
|
1520
|
+
'version-unsupported': `This installed ${provider} and FloLess combination has not been verified for chat transfer. Keep working here.`,
|
|
1521
|
+
'runtime-unavailable': `The ${provider} app is not available on this computer.`,
|
|
1522
|
+
'unsupported-platform': 'Continuing in the desktop app is currently available only on Windows.',
|
|
1523
|
+
'handler-unavailable': `${provider} Desktop is not installed or not set up.`,
|
|
1524
|
+
'handler-untrusted': `FloLess could not verify the installed ${provider} Desktop app, so chat transfer is blocked.`,
|
|
1525
|
+
'handler-identity-mismatch': `A different app is registered to open ${provider} links, so FloLess will not send this chat to it.`,
|
|
1526
|
+
'capability-check-failed': `FloLess couldn’t check ${provider} Desktop.`,
|
|
1527
|
+
};
|
|
1528
|
+
ui.desktopReason.textContent = desktop.available
|
|
1529
|
+
? `Your installed ${provider} app is compatible, but this FloLess version cannot transfer chats yet.`
|
|
1530
|
+
: (reasons[desktop.reason] || 'This chat cannot be continued in the desktop app yet.');
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
function paintRecovery() {
|
|
1534
|
+
const recovery = state.chat?.state === 'recovery';
|
|
1535
|
+
ui.recovery.hidden = !recovery;
|
|
1536
|
+
ui.recoveryStop.hidden = !recovery;
|
|
1537
|
+
ui.recoveryStop.textContent = state.recoveryCanEnd ? 'End recovery' : 'Stop response';
|
|
1538
|
+
ui.recoveryCopy.textContent = recovery
|
|
1539
|
+
? (state.recoveryMessage || 'FloLess needs to check the last AI response before sending another message.')
|
|
1540
|
+
: '';
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
function paintConversation() {
|
|
1544
|
+
const chat = state.chat;
|
|
1545
|
+
if (!chat) { providerChooser(); paintHistory(); return; }
|
|
1546
|
+
ui.historyToggle.disabled = false;
|
|
1547
|
+
ui.refresh.disabled = false;
|
|
1548
|
+
ui.title.textContent = chat.title;
|
|
1549
|
+
ui.scope.textContent = `${state.scope.label} · ${providerLabels[chat.provider]}`;
|
|
1550
|
+
ui.rename.hidden = Boolean(chat.activeTurn) || Boolean(chat.archivedAt);
|
|
1551
|
+
ui.input.disabled = Boolean(chat.archivedAt) || chat.state === 'recovery' || requestExecutionBlocked();
|
|
1552
|
+
if (ui.input.value !== chat.draft && document.activeElement !== ui.input) ui.input.value = chat.draft || '';
|
|
1553
|
+
const active = turnIsVisiblyActive(chat);
|
|
1554
|
+
ui.stop.hidden = !active || Boolean(chat.activeTurn?.local);
|
|
1555
|
+
ui.send.hidden = active;
|
|
1556
|
+
paintSettings(); paintRecovery(); paintApproval(); paintRuntime(); paintAttachments(); paintEvents(); paintHistory(); updateSendState();
|
|
1557
|
+
}
|
|
1558
|
+
|
|
1559
|
+
function closeSource() {
|
|
1560
|
+
if (state.eventReconnectTimer) { clearTimeout(state.eventReconnectTimer); state.eventReconnectTimer = null; }
|
|
1561
|
+
if (state.source) { state.source.close(); state.source = null; }
|
|
1562
|
+
}
|
|
1563
|
+
|
|
1564
|
+
function sameScope(scope, generation) {
|
|
1565
|
+
return generation === state.scopeGeneration && scopeKey(scope) === scopeKey(state.scope);
|
|
1566
|
+
}
|
|
1567
|
+
|
|
1568
|
+
// Every request carries the scope and selected conversation that started it. A user can switch
|
|
1569
|
+
// project, workflow, or conversation while the local server is still answering; stale work may
|
|
1570
|
+
// finish on the server, but it must never repaint the newly selected chat.
|
|
1571
|
+
function captureScope() {
|
|
1572
|
+
if (!state.scope?.owner) return null;
|
|
1573
|
+
return { scope: state.scope, generation: state.scopeGeneration };
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
function captureChat() {
|
|
1577
|
+
const scope = captureScope();
|
|
1578
|
+
if (!scope || !state.chat) return null;
|
|
1579
|
+
return { ...scope, chatId: state.chat.chatId, selection: state.selectionGeneration };
|
|
1580
|
+
}
|
|
1581
|
+
|
|
1582
|
+
function sameChat(snapshot) {
|
|
1583
|
+
return Boolean(snapshot && sameScope(snapshot.scope, snapshot.generation)
|
|
1584
|
+
&& state.selectionGeneration === snapshot.selection && state.chat?.chatId === snapshot.chatId);
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
function scheduleEventReconnect(chatId, scope, generation) {
|
|
1588
|
+
// EventSource permanently closes on the 401 emitted after a local-server restart. It does not
|
|
1589
|
+
// retry a closed stream itself, so renew the short-lived UI session and reconnect once.
|
|
1590
|
+
if (state.eventReconnectTimer || state.eventReconnectAttempt >= 1
|
|
1591
|
+
|| state.chat?.chatId !== chatId || !sameScope(scope, generation)) return;
|
|
1592
|
+
state.eventReconnectAttempt += 1;
|
|
1593
|
+
state.eventReconnectTimer = setTimeout(async () => {
|
|
1594
|
+
state.eventReconnectTimer = null;
|
|
1595
|
+
if (state.chat?.chatId !== chatId || !sameScope(scope, generation)) return;
|
|
1596
|
+
state.sessionReady = false;
|
|
1597
|
+
await refreshConversation(chatId, true);
|
|
1598
|
+
}, 300);
|
|
1599
|
+
}
|
|
1600
|
+
|
|
1601
|
+
function connectEvents() {
|
|
1602
|
+
closeSource();
|
|
1603
|
+
if (!state.chat || !state.scope) return;
|
|
1604
|
+
const chatId = state.chat.chatId;
|
|
1605
|
+
const scope = state.scope;
|
|
1606
|
+
const generation = state.scopeGeneration;
|
|
1607
|
+
if (state.eventReconnectChatId !== chatId) {
|
|
1608
|
+
state.eventReconnectChatId = chatId;
|
|
1609
|
+
state.eventReconnectAttempt = 0;
|
|
1610
|
+
}
|
|
1611
|
+
const after = state.events.reduce((max, event) => Math.max(max, event.sequence || 0), 0);
|
|
1612
|
+
const source = new EventSource(`/api/chat/conversations/${encodeURIComponent(chatId)}/events?${ownerQuery(scope.owner)}&after=${after}`);
|
|
1613
|
+
state.source = source;
|
|
1614
|
+
source.addEventListener('chat-event', (message) => {
|
|
1615
|
+
if (state.chat?.chatId !== chatId) return;
|
|
1616
|
+
const event = JSON.parse(message.data);
|
|
1617
|
+
if (event.clientSubmissionId) {
|
|
1618
|
+
state.events = state.events.filter((item) => !(item.optimistic && item.clientSubmissionId === event.clientSubmissionId));
|
|
1619
|
+
}
|
|
1620
|
+
if (state.events.some((item) => item.eventId === event.eventId)) return;
|
|
1621
|
+
state.events.push(event);
|
|
1622
|
+
state.events.sort((a, b) => a.sequence - b.sequence);
|
|
1623
|
+
state.chat.lastEventSequence = Math.max(state.chat.lastEventSequence || 0, event.sequence || 0);
|
|
1624
|
+
const listChat = state.chats.find((item) => item.chatId === chatId);
|
|
1625
|
+
if (listChat) listChat.lastEventSequence = state.chat.lastEventSequence;
|
|
1626
|
+
if (['error', 'interrupted', 'state'].includes(event.type)) flushLiveStream();
|
|
1627
|
+
if (event.type === 'state' && event.payload?.state === 'completed'
|
|
1628
|
+
&& state.chat?.activeTurn?.turnId === event.turnId) {
|
|
1629
|
+
// The terminal event is authoritative. Clear the live state immediately instead of
|
|
1630
|
+
// waiting for a follow-up fetch, which can leave a finished answer showing dots.
|
|
1631
|
+
state.chat = { ...state.chat, state: 'completed', activeTurn: null };
|
|
1632
|
+
paintConversation();
|
|
1633
|
+
}
|
|
1634
|
+
paintEvents(); paintUnread();
|
|
1635
|
+
if (!document.hidden && !ui.feed.closest('[hidden]')) markRead();
|
|
1636
|
+
if (['approval-requested', 'approval-decided', 'error', 'interrupted', 'state'].includes(event.type)) refreshConversation(chatId, false);
|
|
1637
|
+
});
|
|
1638
|
+
source.addEventListener('ready', () => {
|
|
1639
|
+
if (state.source !== source || !sameScope(scope, generation) || state.chat?.chatId !== chatId) return;
|
|
1640
|
+
state.eventReconnectAttempt = 0;
|
|
1641
|
+
refreshConversation(chatId, false);
|
|
1642
|
+
});
|
|
1643
|
+
source.onerror = () => {
|
|
1644
|
+
if (state.source !== source || !sameScope(scope, generation) || state.chat?.chatId !== chatId) return;
|
|
1645
|
+
ui.hint.textContent = 'Reconnecting to this conversation…';
|
|
1646
|
+
if (source.readyState === EventSource.CLOSED) scheduleEventReconnect(chatId, scope, generation);
|
|
1647
|
+
};
|
|
1648
|
+
}
|
|
1649
|
+
|
|
1650
|
+
async function ensureSession() {
|
|
1651
|
+
if (state.sessionReady) return;
|
|
1652
|
+
await request('/api/chat/session');
|
|
1653
|
+
state.sessionReady = true;
|
|
1654
|
+
}
|
|
1655
|
+
|
|
1656
|
+
function sessionNeedsRenewal(error) {
|
|
1657
|
+
return error?.code === 'chat-session-required'
|
|
1658
|
+
|| /chat UI session is missing or expired/i.test(error instanceof Error ? error.message : String(error));
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
async function readCapability(chat) {
|
|
1662
|
+
try {
|
|
1663
|
+
// The server bounds this check itself; a shorter browser deadline reported a slow but ready
|
|
1664
|
+
// Claude or Codex as "not ready".
|
|
1665
|
+
return await request(`/api/chat/providers/${chat.provider}?${ownerQuery()}&chatId=${encodeURIComponent(chat.chatId)}`);
|
|
1666
|
+
} catch (error) {
|
|
1667
|
+
return { provider: chat.provider, available: false, models: [], skills: [], reason: errorMessage(error) };
|
|
1668
|
+
}
|
|
1669
|
+
}
|
|
1670
|
+
|
|
1671
|
+
async function readDesktopCapability(chat) {
|
|
1672
|
+
try {
|
|
1673
|
+
return await request(`/api/chat/conversations/${encodeURIComponent(chat.chatId)}/desktop-continuation?${ownerQuery()}`, { timeoutMs: 5000 });
|
|
1674
|
+
} catch {
|
|
1675
|
+
return { available: false, provider: chat.provider, reason: 'capability-check-failed' };
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
|
|
1679
|
+
async function loadCapability() {
|
|
1680
|
+
const chat = state.chat;
|
|
1681
|
+
if (!chat || !state.scope) { state.capability = null; return; }
|
|
1682
|
+
const capability = await readCapability(chat);
|
|
1683
|
+
if (state.chat?.chatId === chat.chatId) state.capability = capability;
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
async function refreshConversation(chatId, reconnect = false) {
|
|
1687
|
+
const snapshot = captureChat();
|
|
1688
|
+
if (!snapshot || snapshot.chatId !== chatId) return;
|
|
1689
|
+
try {
|
|
1690
|
+
const path = `/api/chat/conversations/${encodeURIComponent(chatId)}?${ownerQuery(snapshot.scope.owner)}`;
|
|
1691
|
+
let chat;
|
|
1692
|
+
try {
|
|
1693
|
+
chat = await request(path);
|
|
1694
|
+
} catch (error) {
|
|
1695
|
+
// The server session is deliberately short-lived. A completed turn must not remain
|
|
1696
|
+
// visually active just because the first reconciliation request used an old cookie.
|
|
1697
|
+
if (!sessionNeedsRenewal(error)) throw error;
|
|
1698
|
+
state.sessionReady = false;
|
|
1699
|
+
await ensureSession();
|
|
1700
|
+
chat = await request(path);
|
|
1701
|
+
}
|
|
1702
|
+
if (!sameChat(snapshot)) return;
|
|
1703
|
+
state.chat = chat;
|
|
1704
|
+
state.attachments = (chat.attachments || []).filter((attachment) => !attachment.turnId);
|
|
1705
|
+
const index = state.chats.findIndex((item) => item.chatId === chatId);
|
|
1706
|
+
if (index >= 0) state.chats[index] = chat;
|
|
1707
|
+
paintConversation();
|
|
1708
|
+
if (reconnect) connectEvents();
|
|
1709
|
+
} catch (error) { if (sameChat(snapshot)) report(error, 'Could not refresh chat'); }
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
function showConversationLoading(chatId) {
|
|
1713
|
+
const listed = state.chats.find((chat) => chat.chatId === chatId);
|
|
1714
|
+
closeSource();
|
|
1715
|
+
clearLiveStream(true);
|
|
1716
|
+
state.chat = null; state.events = []; state.capability = null; state.desktop = null;
|
|
1717
|
+
state.attachments = []; state.integrations = null;
|
|
1718
|
+
// The header switches to the next conversation now; the previous provider's setup card and composer
|
|
1719
|
+
// hint must not stay under it while that conversation opens.
|
|
1720
|
+
paintRuntime(); clearReport();
|
|
1721
|
+
ui.title.textContent = listed?.title || 'Opening conversation';
|
|
1722
|
+
ui.scope.textContent = listed ? `${state.scope?.label || ''} · ${providerLabels[listed.provider]}` : 'Opening conversation';
|
|
1723
|
+
ui.rename.hidden = true;
|
|
1724
|
+
ui.input.value = '';
|
|
1725
|
+
ui.stop.hidden = true; ui.send.hidden = false;
|
|
1726
|
+
ui.settings.hidden = true; ui.settingsToggle.setAttribute('aria-expanded', 'false');
|
|
1727
|
+
ui.recovery.hidden = true;
|
|
1728
|
+
shell.querySelector('.ai-chat-approval')?.remove();
|
|
1729
|
+
ui.attachments.replaceChildren();
|
|
1730
|
+
ui.feed.replaceChildren();
|
|
1731
|
+
const loading = document.createElement('div'); loading.className = 'ai-chat-empty';
|
|
1732
|
+
const strong = document.createElement('strong'); strong.textContent = 'Opening conversation';
|
|
1733
|
+
const copy = document.createElement('div'); copy.textContent = listed
|
|
1734
|
+
? `Loading “${listed.title}”…`
|
|
1735
|
+
: 'Loading the selected conversation…';
|
|
1736
|
+
loading.append(strong, copy); ui.feed.append(loading);
|
|
1737
|
+
paintHistory(); paintSettings(); paintRecovery();
|
|
1738
|
+
}
|
|
1739
|
+
|
|
1740
|
+
async function selectConversation(chatId, options = {}) {
|
|
1741
|
+
if (!state.scope) return;
|
|
1742
|
+
// An explicit re-open is allowed to try a new event stream after the single automatic retry
|
|
1743
|
+
// was exhausted during a local-server outage. It never resets a background reconnect loop.
|
|
1744
|
+
state.eventReconnectChatId = chatId;
|
|
1745
|
+
state.eventReconnectAttempt = 0;
|
|
1746
|
+
// A provider picker is an explicit user choice. Only an action that explicitly replaces it
|
|
1747
|
+
// may select a stored chat; background scope refreshes must leave the picker untouched.
|
|
1748
|
+
if (state.choosingProvider && options.replaceProviderChoice !== true) return;
|
|
1749
|
+
clearProviderChoice();
|
|
1750
|
+
const selection = ++state.selectionGeneration;
|
|
1751
|
+
const exactAnswer = typeof options.answerEventId === 'string' ? options.answerEventId : null;
|
|
1752
|
+
clearAnswerJump();
|
|
1753
|
+
if (!exactAnswer) {
|
|
1754
|
+
closeSource(); closePicker();
|
|
1755
|
+
state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
|
|
1756
|
+
}
|
|
1757
|
+
const generation = state.scopeGeneration;
|
|
1758
|
+
showConversationLoading(chatId);
|
|
1759
|
+
setBusy(true);
|
|
1760
|
+
try {
|
|
1761
|
+
const [chat, snapshot] = await Promise.all([
|
|
1762
|
+
request(`/api/chat/conversations/${encodeURIComponent(chatId)}?${ownerQuery()}`),
|
|
1763
|
+
request(`/api/chat/conversations/${encodeURIComponent(chatId)}/events-snapshot?${ownerQuery()}`),
|
|
1764
|
+
]);
|
|
1765
|
+
if (generation !== state.scopeGeneration || selection !== state.selectionGeneration) return;
|
|
1766
|
+
const answerTarget = exactAnswer
|
|
1767
|
+
? renderedAnswerTarget(snapshot.events || [], exactAnswer,
|
|
1768
|
+
typeof options.answerTurnId === 'string' ? options.answerTurnId : null)
|
|
1769
|
+
: null;
|
|
1770
|
+
if (exactAnswer && !answerTarget) {
|
|
1771
|
+
announce('That Instructor answer is no longer available.');
|
|
1772
|
+
return;
|
|
1773
|
+
}
|
|
1774
|
+
const [capability, desktop] = await Promise.all([readCapability(chat), readDesktopCapability(chat)]);
|
|
1775
|
+
if (generation !== state.scopeGeneration || selection !== state.selectionGeneration) return;
|
|
1776
|
+
closeSource(); closePicker();
|
|
1777
|
+
state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
|
|
1778
|
+
state.chat = chat;
|
|
1779
|
+
state.events = snapshot.events || [];
|
|
1780
|
+
state.capability = capability;
|
|
1781
|
+
state.desktop = desktop;
|
|
1782
|
+
state.attachments = (chat.attachments || []).filter((attachment) => !attachment.turnId);
|
|
1783
|
+
ui.input.value = chat.draft || '';
|
|
1784
|
+
if (answerTarget) {
|
|
1785
|
+
state.answerJump = { chatId, eventId: answerTarget.eventId, expiresAt: Date.now() + 2600 };
|
|
1786
|
+
state.answerJumpTimer = setTimeout(() => {
|
|
1787
|
+
if (state.answerJump?.chatId === chatId && state.answerJump?.eventId === answerTarget.eventId) clearAnswerJump();
|
|
1788
|
+
}, 2600);
|
|
1789
|
+
}
|
|
1790
|
+
paintConversation(); connectEvents();
|
|
1791
|
+
if (options.applyProviderDefaults || !chat.nativeSessionId) await applyProviderDefaults(chatId);
|
|
1792
|
+
// Let the server prepare the provider for the next message while the user types, after the
|
|
1793
|
+
// default model and effort are saved so the prepared runtime matches the first message. Best-effort:
|
|
1794
|
+
// the server decides whether a runtime can be prepared; nothing here waits on it.
|
|
1795
|
+
if (providerReady()) void request(`/api/chat/conversations/${encodeURIComponent(chatId)}/warm`, {
|
|
1796
|
+
method: 'POST', body: JSON.stringify({ owner: state.scope.owner }),
|
|
1797
|
+
}).catch(() => { /* a missed warm-up only means a slower first message */ });
|
|
1798
|
+
if (answerTarget) {
|
|
1799
|
+
markReadThrough(chat, answerTarget.sequence);
|
|
1800
|
+
announce(`Opened Instructor answer in ${state.chat.title}.`);
|
|
1801
|
+
} else {
|
|
1802
|
+
markRead();
|
|
1803
|
+
if (options.focus) ui.input.focus();
|
|
1804
|
+
}
|
|
1805
|
+
} catch (error) {
|
|
1806
|
+
if (generation === state.scopeGeneration && selection === state.selectionGeneration) {
|
|
1807
|
+
report(error, 'Could not open conversation');
|
|
1808
|
+
}
|
|
1809
|
+
}
|
|
1810
|
+
finally { if (selection === state.selectionGeneration) setBusy(false); }
|
|
1811
|
+
}
|
|
1812
|
+
|
|
1813
|
+
async function applyProviderDefaults(chatId) {
|
|
1814
|
+
if (!state.chat || state.chat.chatId !== chatId || state.chat.nativeSessionId || !state.capability?.available) return;
|
|
1815
|
+
const defaults = preferredSettings(state.chat.provider, state.capability);
|
|
1816
|
+
if (!defaults?.model) return;
|
|
1817
|
+
const patch = {};
|
|
1818
|
+
if (!state.chat.settings.model) patch.model = defaults.model;
|
|
1819
|
+
if (!state.chat.settings.effort && defaults.effort) patch.effort = defaults.effort;
|
|
1820
|
+
if (Object.keys(patch).length) await saveSettings(patch, { announce: false });
|
|
1821
|
+
}
|
|
1822
|
+
|
|
1823
|
+
async function loadScope(scope) {
|
|
1824
|
+
// Choosing a provider is deliberate local UI state. The legacy workspace render seam can
|
|
1825
|
+
// refresh this same scope while it paints; it must not turn the picker back into the first
|
|
1826
|
+
// stored conversation. A genuinely different project/workflow still replaces the picker.
|
|
1827
|
+
if (state.choosingProvider && scopeKey(scope) === scopeKey(state.scope)) {
|
|
1828
|
+
setBusy(false);
|
|
1829
|
+
providerChooser();
|
|
1830
|
+
return;
|
|
1831
|
+
}
|
|
1832
|
+
const generation = ++state.scopeGeneration;
|
|
1833
|
+
state.selectionGeneration += 1;
|
|
1834
|
+
clearAnswerJump();
|
|
1835
|
+
clearLiveStream(true);
|
|
1836
|
+
closeSource(); closePicker();
|
|
1837
|
+
clearProviderChoice();
|
|
1838
|
+
state.scope = scope;
|
|
1839
|
+
state.scopeInitialized = true;
|
|
1840
|
+
state.chat = null; state.chats = []; state.archivedChats = []; state.events = []; state.capability = null; state.desktop = null; state.attachments = []; state.integrations = null;
|
|
1841
|
+
state.historyFilter = 'all'; state.instructorAnswers = []; state.historyLoading = false; state.historyRequestGeneration += 1;
|
|
1842
|
+
state.historyOpen = false; shell.classList.remove('history-open'); ui.history.hidden = true;
|
|
1843
|
+
if (!scope?.owner) { showUnscoped(); return; }
|
|
1844
|
+
ui.scope.textContent = scope.label;
|
|
1845
|
+
ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : 'Workflow conversation';
|
|
1846
|
+
setBusy(true);
|
|
1847
|
+
try {
|
|
1848
|
+
await ensureSession();
|
|
1849
|
+
const result = await request(`/api/chat/conversations?${ownerQuery(scope.owner)}`);
|
|
1850
|
+
if (generation !== state.scopeGeneration) return;
|
|
1851
|
+
state.chats = result.chats || [];
|
|
1852
|
+
seedReadCursors(state.chats, scope.owner);
|
|
1853
|
+
paintHistory(); paintUnread();
|
|
1854
|
+
if (state.chats.length) await selectConversation(state.chats[0].chatId);
|
|
1855
|
+
else providerChooser();
|
|
1856
|
+
} catch (error) {
|
|
1857
|
+
if (generation === state.scopeGeneration) {
|
|
1858
|
+
// A history read can fail independently of the selected project (for example while an
|
|
1859
|
+
// older, stale conversation is being recovered). Do not erase the scope and disable the
|
|
1860
|
+
// whole panel: the user can still start a new conversation in the project that is open.
|
|
1861
|
+
state.chats = []; state.archivedChats = []; state.chat = null; state.events = []; state.capability = null;
|
|
1862
|
+
ui.scope.textContent = scope.label;
|
|
1863
|
+
ui.context.textContent = scope.owner.kind === 'project' ? 'Project conversation' : 'Workflow conversation';
|
|
1864
|
+
paintHistory(); paintUnread(); providerChooser();
|
|
1865
|
+
report(error, 'Could not load this conversation history');
|
|
1866
|
+
}
|
|
1867
|
+
} finally { if (generation === state.scopeGeneration) setBusy(false); }
|
|
1868
|
+
}
|
|
1869
|
+
|
|
1870
|
+
async function refreshScope(force = false) {
|
|
1871
|
+
const next = window.flolessBridge?.getChatScope?.() || null;
|
|
1872
|
+
if (state.choosingProvider && scopeKey(next) === scopeKey(state.scope)) {
|
|
1873
|
+
setBusy(false);
|
|
1874
|
+
providerChooser();
|
|
1875
|
+
return;
|
|
1876
|
+
}
|
|
1877
|
+
if (!force && state.scopeInitialized && scopeKey(next) === scopeKey(state.scope)) return;
|
|
1878
|
+
await loadScope(next);
|
|
1879
|
+
}
|
|
1880
|
+
|
|
1881
|
+
async function createConversation(provider) {
|
|
1882
|
+
if (!state.scope || state.loading) return;
|
|
1883
|
+
clearProviderChoice();
|
|
1884
|
+
setBusy(true);
|
|
1885
|
+
try {
|
|
1886
|
+
const chat = await request('/api/chat/conversations', {
|
|
1887
|
+
method: 'POST', body: JSON.stringify({
|
|
1888
|
+
owner: state.scope.owner, provider, title: 'New chat',
|
|
1889
|
+
settings: { model: null, effort: null, permissionProfile: 'read-only' },
|
|
1890
|
+
initiator: { kind: 'user' },
|
|
1891
|
+
}),
|
|
1892
|
+
});
|
|
1893
|
+
state.chats.unshift(chat);
|
|
1894
|
+
await selectConversation(chat.chatId, { focus: true, applyProviderDefaults: true, replaceProviderChoice: true });
|
|
1895
|
+
announce(`${providerLabels[provider]} conversation created.`);
|
|
1896
|
+
} catch (error) { report(error, 'Could not start conversation'); }
|
|
1897
|
+
finally { setBusy(false); }
|
|
1898
|
+
}
|
|
1899
|
+
|
|
1900
|
+
async function refreshInstructorAnswers(focusFilter = false) {
|
|
1901
|
+
if (!state.scope?.owner) return;
|
|
1902
|
+
const requestGeneration = ++state.historyRequestGeneration;
|
|
1903
|
+
const scopeGeneration = state.scopeGeneration;
|
|
1904
|
+
state.historyLoading = true; paintHistory();
|
|
1905
|
+
try {
|
|
1906
|
+
const result = await request(`/api/chat/conversations?${ownerQuery()}&filter=instructor-answers`);
|
|
1907
|
+
if (requestGeneration !== state.historyRequestGeneration || scopeGeneration !== state.scopeGeneration) return;
|
|
1908
|
+
state.chats = result.chats || [];
|
|
1909
|
+
state.instructorAnswers = result.instructorAnswers || [];
|
|
1910
|
+
} catch (error) {
|
|
1911
|
+
if (requestGeneration === state.historyRequestGeneration) report(error, 'Could not load Instructor answers');
|
|
1912
|
+
} finally {
|
|
1913
|
+
if (requestGeneration === state.historyRequestGeneration) {
|
|
1914
|
+
state.historyLoading = false; paintHistory();
|
|
1915
|
+
if (focusFilter) ui.history.querySelector('[aria-pressed="true"]')?.focus();
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
}
|
|
1919
|
+
|
|
1920
|
+
async function refreshArchivedChats(focusFilter = false) {
|
|
1921
|
+
if (!state.scope?.owner) return;
|
|
1922
|
+
const requestGeneration = ++state.historyRequestGeneration;
|
|
1923
|
+
const scopeGeneration = state.scopeGeneration;
|
|
1924
|
+
state.historyLoading = true; paintHistory();
|
|
1925
|
+
try {
|
|
1926
|
+
const result = await request(`/api/chat/conversations?${ownerQuery()}&archived=1`);
|
|
1927
|
+
if (requestGeneration !== state.historyRequestGeneration || scopeGeneration !== state.scopeGeneration) return;
|
|
1928
|
+
state.archivedChats = (result.chats || []).filter((chat) => Boolean(chat.archivedAt));
|
|
1929
|
+
} catch (error) {
|
|
1930
|
+
if (requestGeneration === state.historyRequestGeneration) report(error, 'Could not load archived conversations');
|
|
1931
|
+
} finally {
|
|
1932
|
+
if (requestGeneration === state.historyRequestGeneration) {
|
|
1933
|
+
state.historyLoading = false; paintHistory();
|
|
1934
|
+
if (focusFilter) ui.history.querySelector('[aria-pressed="true"]')?.focus();
|
|
1935
|
+
}
|
|
1936
|
+
}
|
|
1937
|
+
}
|
|
1938
|
+
|
|
1939
|
+
function historyActionIcon(kind) {
|
|
1940
|
+
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
|
|
1941
|
+
svg.setAttribute('class', 'ai-chat-history-action-icon');
|
|
1942
|
+
svg.setAttribute('viewBox', '0 0 24 24');
|
|
1943
|
+
svg.setAttribute('fill', 'none');
|
|
1944
|
+
svg.setAttribute('stroke', 'currentColor');
|
|
1945
|
+
svg.setAttribute('stroke-width', '2');
|
|
1946
|
+
svg.setAttribute('stroke-linecap', 'round');
|
|
1947
|
+
svg.setAttribute('stroke-linejoin', 'round');
|
|
1948
|
+
svg.setAttribute('aria-hidden', 'true');
|
|
1949
|
+
const paths = kind === 'archive'
|
|
1950
|
+
? ['M21 8v13H3V8', 'M1 3h22v5H1z', 'M10 12h4']
|
|
1951
|
+
: kind === 'restore'
|
|
1952
|
+
? ['M3 12a9 9 0 1 0 3-6.7', 'M3 3v5h5']
|
|
1953
|
+
: ['M3 6h18', 'M8 6V4h8v2', 'M19 6l-1 14H6L5 6', 'M10 11v5', 'M14 11v5'];
|
|
1954
|
+
for (const d of paths) {
|
|
1955
|
+
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
|
1956
|
+
path.setAttribute('d', d); svg.append(path);
|
|
1957
|
+
}
|
|
1958
|
+
return svg;
|
|
1959
|
+
}
|
|
1960
|
+
|
|
1961
|
+
async function setHistoryFilter(filter) {
|
|
1962
|
+
if (filter !== 'all' && filter !== 'instructor-answers') return;
|
|
1963
|
+
state.historyFilter = filter;
|
|
1964
|
+
paintHistory();
|
|
1965
|
+
if (filter === 'instructor-answers') await refreshInstructorAnswers(true);
|
|
1966
|
+
else ui.history.querySelector('[aria-pressed="true"]')?.focus();
|
|
1967
|
+
}
|
|
1968
|
+
|
|
1969
|
+
function toggleHistory(force, options = {}) {
|
|
1970
|
+
const open = force === undefined ? !state.historyOpen : Boolean(force);
|
|
1971
|
+
state.historyOpen = open;
|
|
1972
|
+
shell.classList.toggle('history-open', open);
|
|
1973
|
+
ui.history.hidden = !open;
|
|
1974
|
+
ui.historyToggle.setAttribute('aria-expanded', String(open));
|
|
1975
|
+
if (open) {
|
|
1976
|
+
ui.settings.hidden = true;
|
|
1977
|
+
ui.settingsToggle.setAttribute('aria-expanded', 'false');
|
|
1978
|
+
closePicker(); paintHistory(); ui.history.querySelector('[aria-pressed="true"]')?.focus();
|
|
1979
|
+
if (state.historyFilter === 'instructor-answers') refreshInstructorAnswers(true);
|
|
1980
|
+
else refreshArchivedChats();
|
|
1981
|
+
} else if (options.focusToggle) ui.historyToggle.focus();
|
|
1982
|
+
else ui.input.focus();
|
|
1983
|
+
}
|
|
1984
|
+
|
|
1985
|
+
function closePicker() {
|
|
1986
|
+
state.picker = null; ui.picker.hidden = true; ui.picker.replaceChildren();
|
|
1987
|
+
for (const control of [ui.model, ui.effort, ui.permission, ui.integrations]) control.setAttribute('aria-expanded', 'false');
|
|
1988
|
+
}
|
|
1989
|
+
|
|
1990
|
+
function openPicker(kind, anchor, choices) {
|
|
1991
|
+
if (anchor.disabled) return;
|
|
1992
|
+
if (state.picker === kind) { closePicker(); return; }
|
|
1993
|
+
toggleHistory(false); closePicker(); state.picker = kind;
|
|
1994
|
+
ui.picker.replaceChildren();
|
|
1995
|
+
for (const choice of choices) {
|
|
1996
|
+
const row = button('', `shell.chat-choice#${commandInstance(choice.id)}`, 'ai-chat-choice');
|
|
1997
|
+
row.dataset.commandInstanceLabel = choice.label;
|
|
1998
|
+
row.setAttribute('role', 'option'); row.setAttribute('aria-selected', String(choice.selected));
|
|
1999
|
+
const label = document.createElement('span'); label.textContent = choice.label;
|
|
2000
|
+
row.append(label);
|
|
2001
|
+
if (choice.meta) { const meta = document.createElement('small'); meta.textContent = choice.meta; row.append(meta); }
|
|
2002
|
+
row.addEventListener('click', async () => { closePicker(); await saveSettings(choice.patch); anchor.focus(); });
|
|
2003
|
+
ui.picker.append(row);
|
|
2004
|
+
}
|
|
2005
|
+
ui.picker.hidden = false; anchor.setAttribute('aria-expanded', 'true');
|
|
2006
|
+
const selected = ui.picker.querySelector('[aria-selected="true"]') || ui.picker.querySelector('button');
|
|
2007
|
+
selected?.focus();
|
|
2008
|
+
}
|
|
2009
|
+
|
|
2010
|
+
async function saveSettings(patch, options = {}) {
|
|
2011
|
+
const snapshot = captureChat();
|
|
2012
|
+
if (!snapshot) return;
|
|
2013
|
+
const settings = { ...state.chat.settings, ...patch };
|
|
2014
|
+
if ('model' in patch && !('effort' in patch)) settings.effort = null;
|
|
2015
|
+
try {
|
|
2016
|
+
const chat = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/settings`, {
|
|
2017
|
+
method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, ...settings }),
|
|
2018
|
+
});
|
|
2019
|
+
if (!sameChat(snapshot)) return;
|
|
2020
|
+
state.chat = chat;
|
|
2021
|
+
paintConversation(); if (options.announce !== false) announce('Chat settings updated.');
|
|
2022
|
+
} catch (error) { if (sameChat(snapshot)) report(error, 'Could not update settings'); }
|
|
2023
|
+
}
|
|
2024
|
+
|
|
2025
|
+
function modelChoices() {
|
|
2026
|
+
const models = state.capability?.models || [];
|
|
2027
|
+
return models.map((model) => ({
|
|
2028
|
+
id: `model:${model.id}`, label: model.label, meta: '',
|
|
2029
|
+
selected: (state.chat.settings.model || selectedModel()?.id) === model.id, patch: { model: model.id },
|
|
2030
|
+
}));
|
|
2031
|
+
}
|
|
2032
|
+
|
|
2033
|
+
function effortChoices() {
|
|
2034
|
+
const efforts = selectedModel()?.efforts || [];
|
|
2035
|
+
return efforts.map((effort) => ({ id: `effort:${effort}`, label: effortLabel(effort), meta: '',
|
|
2036
|
+
selected: (state.chat.settings.effort || 'medium').toLowerCase() === effort.toLowerCase(), patch: { effort } }));
|
|
2037
|
+
}
|
|
2038
|
+
|
|
2039
|
+
function permissionChoices() {
|
|
2040
|
+
return Object.entries(permissionLabels).map(([value, label]) => ({
|
|
2041
|
+
id: `permission:${value}`, label, meta: value === 'full-access' ? 'all local files' : value === 'workspace-write' ? 'project or workflow folder' : 'no file changes',
|
|
2042
|
+
selected: state.chat.settings.permissionProfile === value, patch: { permissionProfile: value },
|
|
2043
|
+
}));
|
|
2044
|
+
}
|
|
2045
|
+
|
|
2046
|
+
async function loadIntegrations() {
|
|
2047
|
+
const snapshot = captureChat();
|
|
2048
|
+
if (!snapshot) return null;
|
|
2049
|
+
const integrations = await request(`/api/chat/integrations?${ownerQuery(snapshot.scope.owner)}&chatId=${encodeURIComponent(snapshot.chatId)}`);
|
|
2050
|
+
if (!sameChat(snapshot)) return null;
|
|
2051
|
+
state.integrations = integrations;
|
|
2052
|
+
return state.integrations;
|
|
2053
|
+
}
|
|
2054
|
+
|
|
2055
|
+
function selectedIntegrationBinding(row) {
|
|
2056
|
+
return state.chat?.integrationBindings?.find((binding) => binding.integration === row.integration
|
|
2057
|
+
&& (binding.alias || null) === (row.alias || null)) || null;
|
|
2058
|
+
}
|
|
2059
|
+
|
|
2060
|
+
function integrationAccountLabel(row) {
|
|
2061
|
+
return row.binding?.presentationLabel || selectedIntegrationBinding(row)?.presentationLabel
|
|
2062
|
+
|| row.alias || 'Provider account';
|
|
2063
|
+
}
|
|
2064
|
+
|
|
2065
|
+
function integrationReason(row) {
|
|
2066
|
+
const raw = String(row?.reason || '');
|
|
2067
|
+
if (!raw) return 'This connected account is unavailable.';
|
|
2068
|
+
if (/expired|sign in|auth|token/i.test(raw)) return 'Sign in again to this connected account in Integrations.';
|
|
2069
|
+
if (/unsupported|not available/i.test(raw)) return 'This service is not available in FloLess Chat yet.';
|
|
2070
|
+
if (/identity|verify|binding|account|principal|capability|operation|registry|aware/i.test(raw)) return 'FloLess could not verify this connected account. Check Integrations and try again.';
|
|
2071
|
+
return 'This connected account is unavailable. Check Integrations and try again.';
|
|
2072
|
+
}
|
|
2073
|
+
|
|
2074
|
+
function paintIntegrationPicker() {
|
|
2075
|
+
if (state.picker !== 'integrations') return;
|
|
2076
|
+
ui.picker.replaceChildren();
|
|
2077
|
+
const data = state.integrations;
|
|
2078
|
+
const note = document.createElement('div'); note.className = 'ai-chat-integration-note';
|
|
2079
|
+
const lead = document.createElement('strong');
|
|
2080
|
+
const detail = document.createTextNode(state.chat?.integrationBindings?.length
|
|
2081
|
+
? ' When you select a FloLess account, this chat uses it for that service instead of the account connected in Claude or Codex.'
|
|
2082
|
+
: ' Claude or Codex uses its own connected accounts until you select a FloLess account here.');
|
|
2083
|
+
lead.textContent = state.chat?.integrationBindings?.length ? 'This chat will use the FloLess account you selected.' : 'Choose a connected account for this chat.';
|
|
2084
|
+
note.append(lead, detail); ui.picker.append(note);
|
|
2085
|
+
const rows = data?.rows || [];
|
|
2086
|
+
if (!rows.length) {
|
|
2087
|
+
const empty = document.createElement('div'); empty.className = 'ai-chat-integration-empty';
|
|
2088
|
+
empty.textContent = 'No supported FloLess accounts are connected. Add Google Workspace or Microsoft 365 from Integrations.';
|
|
2089
|
+
ui.picker.append(empty); return;
|
|
2090
|
+
}
|
|
2091
|
+
for (const row of rows) {
|
|
2092
|
+
const stableAccount = selectedIntegrationBinding(row)?.bindingId || row.binding?.bindingId
|
|
2093
|
+
|| `${row.integration}:${row.alias || 'default'}`;
|
|
2094
|
+
const choice = button('', `shell.chat-integration-choice#${commandInstance(stableAccount)}`, 'ai-chat-choice');
|
|
2095
|
+
choice.dataset.commandInstanceLabel = `${row.label} · ${integrationAccountLabel(row)}`;
|
|
2096
|
+
choice.setAttribute('role', 'option'); choice.setAttribute('aria-selected', String(Boolean(row.selected)));
|
|
2097
|
+
const label = document.createElement('span'); label.textContent = `${row.label} · ${integrationAccountLabel(row)}`;
|
|
2098
|
+
const meta = document.createElement('small');
|
|
2099
|
+
meta.textContent = row.selected ? 'Selected for this chat' : row.callable ? 'Available' : 'Needs attention';
|
|
2100
|
+
choice.append(label, meta);
|
|
2101
|
+
if (row.reason) choice.dataset.tip = integrationReason(row);
|
|
2102
|
+
choice.disabled = !row.selected && !row.callable;
|
|
2103
|
+
if (choice.disabled) choice.dataset.blockedReason = integrationReason(row);
|
|
2104
|
+
choice.addEventListener('click', () => chooseIntegration(row));
|
|
2105
|
+
ui.picker.append(choice);
|
|
2106
|
+
}
|
|
2107
|
+
}
|
|
2108
|
+
|
|
2109
|
+
async function openIntegrations() {
|
|
2110
|
+
const snapshot = captureChat();
|
|
2111
|
+
if (!snapshot) return;
|
|
2112
|
+
if (ui.integrations.disabled) return;
|
|
2113
|
+
if (state.picker === 'integrations') { closePicker(); return; }
|
|
2114
|
+
toggleHistory(false); closePicker(); state.picker = 'integrations';
|
|
2115
|
+
ui.integrations.setAttribute('aria-expanded', 'true'); ui.picker.hidden = false;
|
|
2116
|
+
const loading = document.createElement('div'); loading.className = 'ai-chat-integration-empty'; loading.textContent = 'Checking FloLess accounts…';
|
|
2117
|
+
ui.picker.replaceChildren(loading);
|
|
2118
|
+
try { await loadIntegrations(); if (sameChat(snapshot)) paintIntegrationPicker(); }
|
|
2119
|
+
catch (error) { if (sameChat(snapshot) && state.picker === 'integrations') { closePicker(); report(error, 'Could not load connected accounts'); } }
|
|
2120
|
+
}
|
|
2121
|
+
|
|
2122
|
+
async function chooseIntegration(row) {
|
|
2123
|
+
if (!state.chat || (!row.selected && !row.callable)) return;
|
|
2124
|
+
const snapshot = captureChat();
|
|
2125
|
+
if (!snapshot) return;
|
|
2126
|
+
const chatId = snapshot.chatId;
|
|
2127
|
+
for (const choice of ui.picker.querySelectorAll('button')) choice.disabled = true;
|
|
2128
|
+
try {
|
|
2129
|
+
const chat = await request(`/api/chat/conversations/${encodeURIComponent(chatId)}/integrations/${encodeURIComponent(row.integration)}`, {
|
|
2130
|
+
method: 'PUT', body: JSON.stringify({ owner: snapshot.scope.owner, enabled: !row.selected, alias: row.alias }),
|
|
2131
|
+
});
|
|
2132
|
+
if (!sameChat(snapshot)) return;
|
|
2133
|
+
state.chat = chat;
|
|
2134
|
+
const index = state.chats.findIndex((item) => item.chatId === chatId); if (index >= 0) state.chats[index] = state.chat;
|
|
2135
|
+
await loadIntegrations(); paintSettings(); paintIntegrationPicker();
|
|
2136
|
+
announce(row.selected ? `${row.label} now uses the account connected in Claude or Codex.` : `${integrationAccountLabel(row)} selected in FloLess.`);
|
|
2137
|
+
} catch (error) { if (sameChat(snapshot)) { report(error, 'Could not change the connected account'); paintIntegrationPicker(); } }
|
|
2138
|
+
}
|
|
2139
|
+
|
|
2140
|
+
function updateSendState() {
|
|
2141
|
+
const active = turnIsVisiblyActive();
|
|
2142
|
+
const recovery = state.chat?.state === 'recovery';
|
|
2143
|
+
const frozen = recovery || Boolean(state.chat?.activeTurn) || Boolean(state.chat?.archivedAt);
|
|
2144
|
+
const blocked = requestExecutionBlocked();
|
|
2145
|
+
// A provider FloLess is still setting up cannot take a message; the runtime card explains why.
|
|
2146
|
+
const settingUp = Boolean(state.capability?.runtime && state.capability.runtime.state !== 'installed');
|
|
2147
|
+
ui.input.disabled = !state.chat || Boolean(state.chat?.archivedAt) || recovery || blocked;
|
|
2148
|
+
ui.send.disabled = state.loading || !state.chat || blocked || frozen || !ui.input.value.trim() || settingUp;
|
|
2149
|
+
ui.attach.disabled = state.loading || !state.chat || blocked || frozen;
|
|
2150
|
+
ui.stop.hidden = !active || Boolean(state.chat?.activeTurn?.local);
|
|
2151
|
+
ui.send.hidden = active;
|
|
2152
|
+
// Session recovery must remain available even while provider capability discovery is loading
|
|
2153
|
+
// or has failed; it is the escape hatch for that exact state.
|
|
2154
|
+
ui.refresh.disabled = !state.chat;
|
|
2155
|
+
clearReport();
|
|
2156
|
+
paintFloLessContext();
|
|
2157
|
+
}
|
|
2158
|
+
|
|
2159
|
+
function autosize() {
|
|
2160
|
+
ui.input.style.height = 'auto';
|
|
2161
|
+
ui.input.style.height = `${Math.min(132, ui.input.scrollHeight)}px`;
|
|
2162
|
+
}
|
|
2163
|
+
|
|
2164
|
+
function saveDraftSoon() {
|
|
2165
|
+
clearTimeout(state.draftTimer);
|
|
2166
|
+
if (!state.chat) return;
|
|
2167
|
+
const chatId = state.chat.chatId;
|
|
2168
|
+
const draft = ui.input.value;
|
|
2169
|
+
state.chat.draft = draft;
|
|
2170
|
+
state.draftTimer = setTimeout(async () => {
|
|
2171
|
+
if (state.chat?.chatId !== chatId) return;
|
|
2172
|
+
try {
|
|
2173
|
+
await request(`/api/chat/conversations/${encodeURIComponent(chatId)}/draft`, {
|
|
2174
|
+
method: 'PUT', body: JSON.stringify({ owner: state.scope.owner, draft }),
|
|
2175
|
+
});
|
|
2176
|
+
} catch (error) { report(error, 'Draft was not saved'); }
|
|
2177
|
+
}, 350);
|
|
2178
|
+
}
|
|
2179
|
+
|
|
2180
|
+
function paintSkills() {
|
|
2181
|
+
ui.skills.replaceChildren();
|
|
2182
|
+
const match = ui.input.value.slice(0, ui.input.selectionStart).match(/(?:^|\s)\/([A-Za-z0-9:_-]*)$/u);
|
|
2183
|
+
if (!match || !state.capability?.skills?.length) { ui.skills.hidden = true; return; }
|
|
2184
|
+
const query = match[1].toLowerCase();
|
|
2185
|
+
const skills = state.capability.skills.filter((skill) => skill.enabled && skill.name.toLowerCase().includes(query)).slice(0, 40);
|
|
2186
|
+
if (!skills.length) { ui.skills.hidden = true; return; }
|
|
2187
|
+
for (const skill of skills) {
|
|
2188
|
+
const row = button('', `shell.chat-skill#/${skill.name}`, 'ai-chat-choice'); row.setAttribute('role', 'option');
|
|
2189
|
+
const label = document.createElement('span'); label.textContent = `/${skill.name}`;
|
|
2190
|
+
const meta = document.createElement('small'); meta.className = 'ai-chat-skill-origin';
|
|
2191
|
+
meta.textContent = skill.scope === 'unknown' ? (providerLabels[state.chat?.provider] || 'Provider') : skill.scope;
|
|
2192
|
+
row.append(label, meta);
|
|
2193
|
+
row.addEventListener('click', () => {
|
|
2194
|
+
const caret = ui.input.selectionStart;
|
|
2195
|
+
const start = caret - match[0].length + (match[0].startsWith(' ') ? 1 : 0);
|
|
2196
|
+
ui.input.setRangeText(`/${skill.name} `, start, caret, 'end');
|
|
2197
|
+
ui.skills.hidden = true; autosize(); saveDraftSoon(); updateSendState(); ui.input.focus();
|
|
2198
|
+
});
|
|
2199
|
+
ui.skills.append(row);
|
|
2200
|
+
}
|
|
2201
|
+
ui.skills.hidden = false;
|
|
2202
|
+
}
|
|
2203
|
+
|
|
2204
|
+
async function sendTurn() {
|
|
2205
|
+
if (!state.chat || ui.send.disabled) return;
|
|
2206
|
+
const snapshot = captureChat();
|
|
2207
|
+
if (!snapshot) return;
|
|
2208
|
+
const text = ui.input.value.trim();
|
|
2209
|
+
const uiContext = currentFloLessContext();
|
|
2210
|
+
const chatId = snapshot.chatId;
|
|
2211
|
+
const attachmentIds = state.attachments.map((item) => item.attachmentId);
|
|
2212
|
+
const clientSubmissionId = crypto.randomUUID();
|
|
2213
|
+
const previousChat = state.chat;
|
|
2214
|
+
const previousAttachments = state.attachments;
|
|
2215
|
+
const optimisticEvent = {
|
|
2216
|
+
eventId: `local:${clientSubmissionId}`, sequence: Math.max(0, ...state.events.map((event) => Number(event.sequence) || 0)) + .5,
|
|
2217
|
+
chatId, turnId: clientSubmissionId, clientSubmissionId, providerItemId: null, type: 'user-message',
|
|
2218
|
+
payload: { text, attachmentIds }, createdAt: new Date().toISOString(), optimistic: true,
|
|
2219
|
+
};
|
|
2220
|
+
clearTimeout(state.draftTimer);
|
|
2221
|
+
state.pendingSubmissionId = clientSubmissionId;
|
|
2222
|
+
state.events.push(optimisticEvent);
|
|
2223
|
+
state.chat = { ...previousChat, state: 'starting', activeTurn: { turnId: clientSubmissionId, local: true } };
|
|
2224
|
+
ui.input.value = ''; autosize(); state.attachments = []; paintAttachments();
|
|
2225
|
+
setBusy(true); paintConversation(); announce('Message sent.');
|
|
2226
|
+
try {
|
|
2227
|
+
const result = await request(`/api/chat/conversations/${encodeURIComponent(chatId)}/turns`, {
|
|
2228
|
+
method: 'POST', body: JSON.stringify({
|
|
2229
|
+
// The server alone appends this context to the provider copy. The submitted text and
|
|
2230
|
+
// durable transcript must remain exactly what the user typed.
|
|
2231
|
+
owner: snapshot.scope.owner, clientSubmissionId, text, displayText: text, uiContext, attachmentIds,
|
|
2232
|
+
modifying: previousChat.settings.permissionProfile !== 'read-only',
|
|
2233
|
+
}),
|
|
2234
|
+
});
|
|
2235
|
+
if (!sameChat(snapshot)) return;
|
|
2236
|
+
state.pendingSubmissionId = null;
|
|
2237
|
+
state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
|
|
2238
|
+
state.chat = result.chat;
|
|
2239
|
+
for (const event of result.events || []) if (!state.events.some((item) => item.eventId === event.eventId)) state.events.push(event);
|
|
2240
|
+
paintConversation();
|
|
2241
|
+
// The server accepts a turn only from a ready provider, so a warning from an earlier check is stale.
|
|
2242
|
+
if (!providerReady()) void loadCapability().then(() => { if (sameChat(snapshot)) { paintSettings(); updateSendState(); } });
|
|
2243
|
+
} catch (error) {
|
|
2244
|
+
if (!sameChat(snapshot)) return;
|
|
2245
|
+
state.pendingSubmissionId = null;
|
|
2246
|
+
state.events = state.events.filter((event) => event.eventId !== optimisticEvent.eventId);
|
|
2247
|
+
state.chat = previousChat;
|
|
2248
|
+
state.attachments = previousAttachments;
|
|
2249
|
+
ui.input.value = text; autosize(); paintAttachments(); paintConversation();
|
|
2250
|
+
report(error, 'Message was not sent');
|
|
2251
|
+
} finally { if (sameChat(snapshot)) { setBusy(false); updateSendState(); } }
|
|
2252
|
+
}
|
|
2253
|
+
|
|
2254
|
+
async function stopTurn() {
|
|
2255
|
+
if (!state.chat?.activeTurn) return;
|
|
2256
|
+
const snapshot = captureChat();
|
|
2257
|
+
if (!snapshot) return;
|
|
2258
|
+
const chatId = snapshot.chatId;
|
|
2259
|
+
const owner = snapshot.scope.owner;
|
|
2260
|
+
const stop = () => request(`/api/chat/conversations/${encodeURIComponent(chatId)}/stop`, {
|
|
2261
|
+
method: 'POST', body: JSON.stringify({ owner }),
|
|
2262
|
+
});
|
|
2263
|
+
ui.stop.disabled = true;
|
|
2264
|
+
ui.recoveryStop.disabled = true;
|
|
2265
|
+
announce('Stopping the current response…');
|
|
2266
|
+
try {
|
|
2267
|
+
try { await stop(); }
|
|
2268
|
+
catch (error) {
|
|
2269
|
+
if (!sessionNeedsRenewal(error)) throw error;
|
|
2270
|
+
state.sessionReady = false;
|
|
2271
|
+
await ensureSession();
|
|
2272
|
+
await stop();
|
|
2273
|
+
}
|
|
2274
|
+
if (!sameChat(snapshot)) return;
|
|
2275
|
+
await refreshConversation(chatId, false);
|
|
2276
|
+
if (!sameChat(snapshot)) return;
|
|
2277
|
+
announce('The current response was stopped.');
|
|
2278
|
+
} catch (error) {
|
|
2279
|
+
if (!sameChat(snapshot)) return;
|
|
2280
|
+
if (error?.code === 'chat-stop-uncertain') {
|
|
2281
|
+
state.recoveryCanEnd = true;
|
|
2282
|
+
state.recoveryMessage = 'FloLess cannot stop this response remotely because the AI app no longer recognizes it. End recovery unlocks this chat; any late response will not appear here.';
|
|
2283
|
+
paintRecovery();
|
|
2284
|
+
announce('FloLess could not stop the response remotely. You can end its local recovery lock.');
|
|
2285
|
+
} else report(error, 'Could not stop the response');
|
|
2286
|
+
}
|
|
2287
|
+
finally { if (sameChat(snapshot)) { ui.stop.disabled = false; ui.recoveryStop.disabled = false; } }
|
|
2288
|
+
}
|
|
2289
|
+
|
|
2290
|
+
async function refreshChatSession() {
|
|
2291
|
+
const snapshot = captureChat();
|
|
2292
|
+
if (!snapshot) return;
|
|
2293
|
+
const chatId = snapshot.chatId;
|
|
2294
|
+
ui.refresh.disabled = true;
|
|
2295
|
+
announce('Refreshing this chat session…');
|
|
2296
|
+
try {
|
|
2297
|
+
// Re-read before stopping: the browser can retain an old activeTurn after a server restart.
|
|
2298
|
+
// That avoids sending a redundant stop for a response the durable conversation already completed.
|
|
2299
|
+
closeSource();
|
|
2300
|
+
state.sessionReady = false;
|
|
2301
|
+
await ensureSession();
|
|
2302
|
+
if (!sameChat(snapshot)) return;
|
|
2303
|
+
await refreshConversation(chatId, false);
|
|
2304
|
+
if (!sameChat(snapshot)) return;
|
|
2305
|
+
if (state.chat.activeTurn && !state.chat.activeTurn.local) {
|
|
2306
|
+
await stopTurn();
|
|
2307
|
+
if (!sameChat(snapshot) || state.chat.activeTurn) return;
|
|
2308
|
+
}
|
|
2309
|
+
await selectConversation(chatId, { focus: false });
|
|
2310
|
+
if (!sameChat(snapshot)) return;
|
|
2311
|
+
announce('Chat session refreshed.');
|
|
2312
|
+
} catch (error) { if (sameChat(snapshot)) report(error, 'Could not refresh this chat session'); }
|
|
2313
|
+
finally { if (sameChat(snapshot)) { ui.refresh.disabled = false; updateSendState(); } }
|
|
2314
|
+
}
|
|
2315
|
+
|
|
2316
|
+
async function endRecovery() {
|
|
2317
|
+
const snapshot = captureChat();
|
|
2318
|
+
if (!snapshot) return;
|
|
2319
|
+
ui.recoveryStop.disabled = true;
|
|
2320
|
+
announce('Ending recovery for this response…');
|
|
2321
|
+
try {
|
|
2322
|
+
const result = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/end-recovery`, {
|
|
2323
|
+
method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner }),
|
|
2324
|
+
});
|
|
2325
|
+
if (!sameChat(snapshot)) return;
|
|
2326
|
+
state.recoveryCanEnd = false;
|
|
2327
|
+
state.recoveryMessage = null;
|
|
2328
|
+
state.chat = result.chat;
|
|
2329
|
+
await refreshConversation(snapshot.chatId, false);
|
|
2330
|
+
if (!sameChat(snapshot)) return;
|
|
2331
|
+
announce('This unconfirmed response was ended. You can continue this chat.');
|
|
2332
|
+
} catch (error) { if (sameChat(snapshot)) report(error, 'Could not end recovery'); }
|
|
2333
|
+
finally { if (sameChat(snapshot)) ui.recoveryStop.disabled = false; }
|
|
2334
|
+
}
|
|
2335
|
+
|
|
2336
|
+
async function reconcile() {
|
|
2337
|
+
const snapshot = captureChat();
|
|
2338
|
+
if (!snapshot) return;
|
|
2339
|
+
const chatId = snapshot.chatId;
|
|
2340
|
+
const owner = snapshot.scope.owner;
|
|
2341
|
+
const check = () => request(`/api/chat/conversations/${encodeURIComponent(chatId)}/reconcile`, {
|
|
2342
|
+
method: 'POST', timeoutMs: 10_000, body: JSON.stringify({ owner }),
|
|
2343
|
+
});
|
|
2344
|
+
ui.reconcile.disabled = true;
|
|
2345
|
+
ui.reconcile.textContent = 'Checking…';
|
|
2346
|
+
state.recoveryMessage = null;
|
|
2347
|
+
state.recoveryCanEnd = false;
|
|
2348
|
+
ui.recoveryCopy.textContent = 'Checking the last AI response now. You can continue when FloLess confirms it is safe.';
|
|
2349
|
+
announce('Checking the last AI response…');
|
|
2350
|
+
try {
|
|
2351
|
+
let result;
|
|
2352
|
+
try { result = await check(); }
|
|
2353
|
+
catch (error) {
|
|
2354
|
+
if (!sessionNeedsRenewal(error)) throw error;
|
|
2355
|
+
state.sessionReady = false;
|
|
2356
|
+
await ensureSession();
|
|
2357
|
+
result = await check();
|
|
2358
|
+
}
|
|
2359
|
+
if (!sameChat(snapshot)) return;
|
|
2360
|
+
state.chat = result.chat;
|
|
2361
|
+
if (result.result?.state === 'not-found') {
|
|
2362
|
+
state.recoveryMessage = 'FloLess cannot find this AI response to confirm whether it finished. This can happen if FloLess or the AI app was restarted. Stop response to close it here, then continue.';
|
|
2363
|
+
}
|
|
2364
|
+
paintConversation();
|
|
2365
|
+
announce(result.result?.state === 'not-found'
|
|
2366
|
+
? 'FloLess could not confirm the last AI response. Stop it or try checking again.'
|
|
2367
|
+
: 'The last AI response was checked.');
|
|
2368
|
+
} catch (error) {
|
|
2369
|
+
if (!sameChat(snapshot)) return;
|
|
2370
|
+
const timeout = error?.code === 'local-timeout' || /timed out/i.test(error instanceof Error ? error.message : String(error));
|
|
2371
|
+
state.recoveryMessage = timeout
|
|
2372
|
+
? 'FloLess could not confirm the last AI response within 10 seconds. It may still be running. Try again in a moment, or stop it here.'
|
|
2373
|
+
: 'FloLess could not check the last AI response. Try again in a moment, or stop it here.';
|
|
2374
|
+
paintRecovery();
|
|
2375
|
+
report(timeout ? new Error(state.recoveryMessage) : error, timeout ? '' : 'Could not check the last AI response');
|
|
2376
|
+
}
|
|
2377
|
+
finally {
|
|
2378
|
+
if (!sameChat(snapshot)) return;
|
|
2379
|
+
ui.reconcile.disabled = false;
|
|
2380
|
+
if (state.chat?.state === 'recovery') {
|
|
2381
|
+
ui.reconcile.textContent = 'Check again';
|
|
2382
|
+
}
|
|
2383
|
+
}
|
|
2384
|
+
}
|
|
2385
|
+
|
|
2386
|
+
async function decideApproval(decision) {
|
|
2387
|
+
const approval = state.chat?.pendingApproval;
|
|
2388
|
+
if (!approval) return;
|
|
2389
|
+
const snapshot = captureChat();
|
|
2390
|
+
if (!snapshot) return;
|
|
2391
|
+
const approvalId = approval.approvalId;
|
|
2392
|
+
// The provider stays paused while this request reaches it, but the choice is already made.
|
|
2393
|
+
// Suppress any stale poll/SSE snapshot so the card disappears on the click itself instead of
|
|
2394
|
+
// looking like a frozen control until the provider acknowledges the decision.
|
|
2395
|
+
state.decidingApprovalIds.add(approvalId);
|
|
2396
|
+
state.chat = { ...state.chat, pendingApproval: null };
|
|
2397
|
+
paintConversation();
|
|
2398
|
+
announce('Applying your choice…');
|
|
2399
|
+
try {
|
|
2400
|
+
await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/approvals/${encodeURIComponent(approvalId)}`, {
|
|
2401
|
+
method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, decision }),
|
|
2402
|
+
});
|
|
2403
|
+
if (!sameChat(snapshot)) return;
|
|
2404
|
+
announce(decision === 'allow' ? 'Approved once.' : 'Action denied.');
|
|
2405
|
+
await refreshConversation(snapshot.chatId, false);
|
|
2406
|
+
} catch (error) {
|
|
2407
|
+
if (!sameChat(snapshot)) return;
|
|
2408
|
+
report(error, 'Could not apply your choice');
|
|
2409
|
+
await refreshConversation(snapshot.chatId, false);
|
|
2410
|
+
} finally { state.decidingApprovalIds.delete(approvalId); }
|
|
2411
|
+
}
|
|
2412
|
+
|
|
2413
|
+
function fileBase64(file) {
|
|
2414
|
+
return new Promise((resolve, reject) => {
|
|
2415
|
+
const reader = new FileReader();
|
|
2416
|
+
reader.onerror = () => reject(reader.error || new Error('Could not read the attachment'));
|
|
2417
|
+
reader.onload = () => resolve(String(reader.result).split(',', 2)[1] || '');
|
|
2418
|
+
reader.readAsDataURL(file);
|
|
2419
|
+
});
|
|
2420
|
+
}
|
|
2421
|
+
|
|
2422
|
+
async function attachFiles(files) {
|
|
2423
|
+
if (!state.chat || state.chat.activeTurn) return;
|
|
2424
|
+
const snapshot = captureChat();
|
|
2425
|
+
if (!snapshot) return;
|
|
2426
|
+
const incoming = [...files];
|
|
2427
|
+
const known = [...new Map([...(state.chat.attachments || []), ...state.attachments]
|
|
2428
|
+
.map((attachment) => [attachment.attachmentId, attachment])).values()];
|
|
2429
|
+
const existingBytes = known.reduce((sum, item) => sum + (item.bytes || 0), 0);
|
|
2430
|
+
if (known.length + incoming.length > 10) { report(new Error('You can attach up to 10 files to this conversation.')); return; }
|
|
2431
|
+
if (incoming.some((file) => !allowedTypes.has(file.type))) { report(new Error('Attach a PNG, JPEG, WebP, or PDF')); return; }
|
|
2432
|
+
if (incoming.some((file) => file.size > 20 * MB)) { report(new Error('Each attachment must be 20 MB or smaller')); return; }
|
|
2433
|
+
if (existingBytes + incoming.reduce((sum, file) => sum + file.size, 0) > 50 * MB) { report(new Error('Attachments must stay within 50 MB per conversation')); return; }
|
|
2434
|
+
ui.attach.disabled = true;
|
|
2435
|
+
try {
|
|
2436
|
+
for (const file of incoming) {
|
|
2437
|
+
const data = await fileBase64(file);
|
|
2438
|
+
if (!sameChat(snapshot)) return;
|
|
2439
|
+
const attachment = await request(`/api/chat/conversations/${encodeURIComponent(snapshot.chatId)}/attachments`, {
|
|
2440
|
+
method: 'POST', body: JSON.stringify({ owner: snapshot.scope.owner, fileName: file.name, mediaType: file.type, data }),
|
|
2441
|
+
});
|
|
2442
|
+
if (!sameChat(snapshot)) return;
|
|
2443
|
+
state.attachments.push(attachment);
|
|
2444
|
+
}
|
|
2445
|
+
if (!sameChat(snapshot)) return;
|
|
2446
|
+
paintAttachments(); announce(`${incoming.length} attachment${incoming.length === 1 ? '' : 's'} ready for the next message.`);
|
|
2447
|
+
} catch (error) { if (sameChat(snapshot)) report(error, 'Could not attach file'); }
|
|
2448
|
+
finally { if (sameChat(snapshot)) ui.attach.disabled = false; ui.file.value = ''; }
|
|
2449
|
+
}
|
|
2450
|
+
|
|
2451
|
+
async function pollChats() {
|
|
2452
|
+
if (!state.scope || document.hidden) return;
|
|
2453
|
+
const scope = state.scope;
|
|
2454
|
+
const generation = state.scopeGeneration;
|
|
2455
|
+
try {
|
|
2456
|
+
await ensureSession();
|
|
2457
|
+
if (!sameScope(scope, generation)) return;
|
|
2458
|
+
const path = `/api/chat/conversations?${ownerQuery(scope.owner)}`;
|
|
2459
|
+
let result;
|
|
2460
|
+
try {
|
|
2461
|
+
result = await request(path);
|
|
2462
|
+
} catch (error) {
|
|
2463
|
+
// A server restart expires the browser's in-memory session marker. Renew once so
|
|
2464
|
+
// polling can replace an old activeTurn with the saved completed conversation.
|
|
2465
|
+
if (!sessionNeedsRenewal(error)) throw error;
|
|
2466
|
+
state.sessionReady = false;
|
|
2467
|
+
await ensureSession();
|
|
2468
|
+
if (!sameScope(scope, generation)) return;
|
|
2469
|
+
result = await request(path);
|
|
2470
|
+
}
|
|
2471
|
+
if (!sameScope(scope, generation)) return;
|
|
2472
|
+
state.chats = result.chats || [];
|
|
2473
|
+
const active = state.chats.find((item) => item.chatId === state.chat?.chatId);
|
|
2474
|
+
if (active && state.chat) {
|
|
2475
|
+
// An event-stream completion can win the race against this list request. Never let a
|
|
2476
|
+
// response that started before that terminal event put its old activeTurn back and leave
|
|
2477
|
+
// the composer/dots stuck until another poll happens to repair it.
|
|
2478
|
+
const knownSequence = Number(state.chat.lastEventSequence) || 0;
|
|
2479
|
+
const fetchedSequence = Number(active.lastEventSequence) || 0;
|
|
2480
|
+
if (fetchedSequence >= knownSequence) Object.assign(state.chat, active);
|
|
2481
|
+
}
|
|
2482
|
+
// SSE delivers messages immediately, while this poll is what confirms that the provider has
|
|
2483
|
+
// finished. Keep the Rename chat control in step with that durable active-turn state.
|
|
2484
|
+
ui.rename.hidden = !state.chat || Boolean(state.chat.activeTurn) || Boolean(state.chat.archivedAt);
|
|
2485
|
+
// Polling can clear activeTurn after the feed was painted by SSE. Repaint the feed
|
|
2486
|
+
// so a completed turn removes any stale live activity indicator. With no conversation
|
|
2487
|
+
// selected the feed is the Claude/Codex chooser, which a repaint would erase.
|
|
2488
|
+
paintHistory(); paintUnread();
|
|
2489
|
+
if (state.chat) { paintSettings(); paintRecovery(); paintApproval(); paintEvents(); updateSendState(); }
|
|
2490
|
+
if (state.historyOpen && state.historyFilter === 'instructor-answers') refreshInstructorAnswers();
|
|
2491
|
+
} catch { /* SSE or the next poll will recover */ }
|
|
2492
|
+
}
|
|
2493
|
+
|
|
2494
|
+
function refreshActivity() {
|
|
2495
|
+
paintConversation();
|
|
2496
|
+
}
|
|
2497
|
+
|
|
2498
|
+
async function refreshIndex() {
|
|
2499
|
+
if (!state.scope?.owner) return;
|
|
2500
|
+
const scope = state.scope;
|
|
2501
|
+
const generation = state.scopeGeneration;
|
|
2502
|
+
const selectedId = state.chat?.chatId ?? null;
|
|
2503
|
+
const selectedSequence = state.chat?.lastEventSequence ?? 0;
|
|
2504
|
+
const listed = await request(`/api/chat/conversations?${ownerQuery(scope.owner)}`);
|
|
2505
|
+
if (!sameScope(scope, generation)) return;
|
|
2506
|
+
state.chats = listed.chats || [];
|
|
2507
|
+
const selected = selectedId ? state.chats.find((chat) => chat.chatId === selectedId) : null;
|
|
2508
|
+
if (selected && state.chat) {
|
|
2509
|
+
if ((selected.lastEventSequence || 0) > selectedSequence) await refreshConversation(selectedId, false);
|
|
2510
|
+
else Object.assign(state.chat, selected);
|
|
2511
|
+
}
|
|
2512
|
+
paintHistory(); paintUnread();
|
|
2513
|
+
}
|
|
2514
|
+
|
|
2515
|
+
async function startRequest(requestId, provider, mode = 'start') {
|
|
2516
|
+
if (!state.scope?.owner) throw new Error('Open the Request’s project or workflow before starting its chat.');
|
|
2517
|
+
if (provider !== 'claude' && provider !== 'codex') throw new Error('Choose Claude or Codex for this chat.');
|
|
2518
|
+
const scope = state.scope;
|
|
2519
|
+
const generation = state.scopeGeneration;
|
|
2520
|
+
await ensureSession();
|
|
2521
|
+
if (!sameScope(scope, generation)) {
|
|
2522
|
+
throw Object.assign(new Error('The project or workflow changed while FloLess was starting this request. Open it again and try once more.'), { code: 'request-chat-owner-mismatch' });
|
|
2523
|
+
}
|
|
2524
|
+
const currentChatId = state.chat && state.chat.provider === provider && !state.chat.activeTurn
|
|
2525
|
+
&& !state.chat.archivedAt && state.chat.state !== 'recovery' ? state.chat.chatId : undefined;
|
|
2526
|
+
const result = await request(`/api/chat/requests/${encodeURIComponent(requestId)}/start`, {
|
|
2527
|
+
method: 'POST', timeoutMs: 10000,
|
|
2528
|
+
body: JSON.stringify({ provider, mode, chatId: currentChatId, expectedOwner: scope.owner }),
|
|
2529
|
+
});
|
|
2530
|
+
if (!sameScope(scope, generation)) {
|
|
2531
|
+
throw Object.assign(new Error('The project or workflow changed while FloLess was starting this request. Open it again and try once more.'), { code: 'request-chat-owner-mismatch' });
|
|
2532
|
+
}
|
|
2533
|
+
if (scopeKey({ owner: result.owner }) !== scopeKey(scope)) {
|
|
2534
|
+
throw Object.assign(new Error('This request is linked to another project or workflow. Open the project or workflow shown on the request, then try again.'), { code: 'request-chat-owner-mismatch' });
|
|
2535
|
+
}
|
|
2536
|
+
window.flolessBridge?.revealAiChat?.();
|
|
2537
|
+
ui.tab.click();
|
|
2538
|
+
const listed = await request(`/api/chat/conversations?${ownerQuery(scope.owner)}`, { timeoutMs: 10000 });
|
|
2539
|
+
if (!sameScope(scope, generation)) {
|
|
2540
|
+
throw Object.assign(new Error('The project or workflow changed while FloLess was starting this request. Open it again and try once more.'), { code: 'request-chat-owner-mismatch' });
|
|
2541
|
+
}
|
|
2542
|
+
state.chats = listed.chats || [];
|
|
2543
|
+
paintHistory(); paintUnread();
|
|
2544
|
+
await selectConversation(result.chat.chatId, { focus: true, replaceProviderChoice: true });
|
|
2545
|
+
return result;
|
|
2546
|
+
}
|
|
2547
|
+
|
|
2548
|
+
async function openConversation(chatId) {
|
|
2549
|
+
await refreshScope();
|
|
2550
|
+
if (!state.scope?.owner) throw new Error('Open this conversation’s project or workflow, then try again.');
|
|
2551
|
+
window.flolessBridge?.revealAiChat?.();
|
|
2552
|
+
ui.tab.click();
|
|
2553
|
+
const listed = await request(`/api/chat/conversations?${ownerQuery()}`);
|
|
2554
|
+
state.chats = listed.chats || [];
|
|
2555
|
+
paintHistory(); paintUnread();
|
|
2556
|
+
await selectConversation(chatId, { focus: true, replaceProviderChoice: true });
|
|
2557
|
+
}
|
|
2558
|
+
|
|
2559
|
+
async function startProjectIntake(submissionId, payload) {
|
|
2560
|
+
await ensureSession();
|
|
2561
|
+
return request(`/api/chat/project-intakes/${encodeURIComponent(submissionId)}/start`, {
|
|
2562
|
+
method: 'POST', body: JSON.stringify(payload),
|
|
2563
|
+
});
|
|
2564
|
+
}
|
|
2565
|
+
|
|
2566
|
+
async function resumeProjectIntake(submissionId) {
|
|
2567
|
+
await ensureSession();
|
|
2568
|
+
return request(`/api/chat/project-intakes/${encodeURIComponent(submissionId)}/resume`, {
|
|
2569
|
+
method: 'POST', body: '{}',
|
|
2570
|
+
});
|
|
2571
|
+
}
|
|
2572
|
+
|
|
2573
|
+
ui.historyToggle.addEventListener('click', () => toggleHistory());
|
|
2574
|
+
ui.refresh.addEventListener('click', refreshChatSession);
|
|
2575
|
+
ui.history.addEventListener('keydown', (event) => {
|
|
2576
|
+
if (event.key === 'Escape') { event.preventDefault(); toggleHistory(false, { focusToggle: true }); }
|
|
2577
|
+
});
|
|
2578
|
+
ui.newChat.addEventListener('click', () => {
|
|
2579
|
+
// A prior async select can still be waiting for capability discovery. Invalidate it before
|
|
2580
|
+
// showing the provider choice, otherwise it can put the old conversation back over this view.
|
|
2581
|
+
state.selectionGeneration += 1;
|
|
2582
|
+
state.choosingProvider = true;
|
|
2583
|
+
closeSource(); clearLiveStream(true);
|
|
2584
|
+
state.chat = null; state.events = []; state.attachments = []; state.integrations = null; state.capability = null;
|
|
2585
|
+
toggleHistory(false); setBusy(false); providerChooser(); clearReport();
|
|
2586
|
+
});
|
|
2587
|
+
ui.rename.addEventListener('click', beginRename);
|
|
2588
|
+
ui.title.addEventListener('keydown', (event) => {
|
|
2589
|
+
if (!state.renaming) return;
|
|
2590
|
+
if (event.key === 'Enter') { event.preventDefault(); ui.title.blur(); }
|
|
2591
|
+
if (event.key === 'Escape') { event.preventDefault(); ui.title.textContent = state.renaming.original; ui.title.blur(); }
|
|
2592
|
+
});
|
|
2593
|
+
ui.title.addEventListener('blur', () => finishRename(ui.title.textContent?.trim() !== ''));
|
|
2594
|
+
ui.settingsToggle.addEventListener('click', () => {
|
|
2595
|
+
const open = ui.settings.hidden;
|
|
2596
|
+
if (open) toggleHistory(false);
|
|
2597
|
+
ui.settings.hidden = !open;
|
|
2598
|
+
ui.settingsToggle.setAttribute('aria-expanded', String(open));
|
|
2599
|
+
closePicker();
|
|
2600
|
+
});
|
|
2601
|
+
ui.model.addEventListener('click', () => openPicker('model', ui.model, modelChoices()));
|
|
2602
|
+
ui.effort.addEventListener('click', () => openPicker('effort', ui.effort, effortChoices()));
|
|
2603
|
+
ui.permission.addEventListener('click', () => openPicker('permission', ui.permission, permissionChoices()));
|
|
2604
|
+
ui.integrations.addEventListener('click', openIntegrations);
|
|
2605
|
+
ui.send.addEventListener('click', sendTurn);
|
|
2606
|
+
ui.stop.addEventListener('click', stopTurn);
|
|
2607
|
+
ui.recoveryStop.addEventListener('click', () => { void (state.recoveryCanEnd ? endRecovery() : stopTurn()); });
|
|
2608
|
+
ui.reconcile.addEventListener('click', reconcile);
|
|
2609
|
+
ui.attach.addEventListener('click', () => ui.file.click());
|
|
2610
|
+
ui.file.addEventListener('change', () => attachFiles(ui.file.files));
|
|
2611
|
+
ui.input.addEventListener('input', () => { autosize(); saveDraftSoon(); paintSkills(); updateSendState(); });
|
|
2612
|
+
ui.input.addEventListener('keydown', (event) => {
|
|
2613
|
+
if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { event.preventDefault(); sendTurn(); }
|
|
2614
|
+
else if (event.key === 'Escape') { ui.skills.hidden = true; closePicker(); }
|
|
2615
|
+
});
|
|
2616
|
+
shell.addEventListener('dragover', (event) => { if (event.dataTransfer?.types.includes('Files')) event.preventDefault(); });
|
|
2617
|
+
shell.addEventListener('drop', (event) => { if (event.dataTransfer?.files?.length) { event.preventDefault(); attachFiles(event.dataTransfer.files); } });
|
|
2618
|
+
ui.input.addEventListener('paste', (event) => {
|
|
2619
|
+
const files = [...(event.clipboardData?.items || [])].filter((item) => item.kind === 'file').map((item) => item.getAsFile()).filter(Boolean);
|
|
2620
|
+
if (files.length) { event.preventDefault(); attachFiles(files); }
|
|
2621
|
+
});
|
|
2622
|
+
ui.tab.addEventListener('click', () => markRead());
|
|
2623
|
+
document.addEventListener('visibilitychange', () => { if (!document.hidden) { markRead(); pollChats(); } });
|
|
2624
|
+
document.addEventListener('pointerdown', (event) => {
|
|
2625
|
+
if (!ui.picker.hidden && !ui.picker.contains(event.target) && !event.target.closest('.ai-chat-setting')) closePicker();
|
|
2626
|
+
});
|
|
2627
|
+
window.addEventListener('floless:chat-scope-changed', (event) => {
|
|
2628
|
+
const next = event.detail || null;
|
|
2629
|
+
// The workspace emits repeated scope notifications while its iframe finishes loading. A
|
|
2630
|
+
// same-scope notification must not reselect the first stored chat over a provider picker.
|
|
2631
|
+
if (scopeKey(next) === scopeKey(state.scope)) { refreshActivity(); return; }
|
|
2632
|
+
loadScope(next);
|
|
2633
|
+
});
|
|
2634
|
+
document.addEventListener('click', () => queueMicrotask(paintFloLessContext));
|
|
2635
|
+
const contextObserver = new MutationObserver(paintFloLessContext);
|
|
2636
|
+
for (const id of ['app', 'mode-switch', 'ws-step-tabs', 'dashboard', 'report-modal', 'contract-editor', 'stop-run', 'report-stop']) {
|
|
2637
|
+
const node = document.getElementById(id);
|
|
2638
|
+
if (node) contextObserver.observe(node, { attributes: true, childList: id === 'ws-step-tabs', subtree: id === 'ws-step-tabs' });
|
|
2639
|
+
}
|
|
2640
|
+
|
|
2641
|
+
state.refreshTimer = setInterval(pollChats, 5000);
|
|
2642
|
+
window.addEventListener('pagehide', () => { closeSource(); contextObserver.disconnect(); clearInterval(state.refreshTimer); clearTimeout(state.draftTimer); });
|
|
2643
|
+
window.flolessChat = {
|
|
2644
|
+
refreshScope, refreshActivity, refreshIndex, startRequest, openConversation,
|
|
2645
|
+
startProjectIntake, resumeProjectIntake,
|
|
2646
|
+
currentProvider: () => state.chat?.provider ?? null,
|
|
2647
|
+
};
|
|
2648
|
+
window.dispatchEvent(new CustomEvent('floless:chat-ready'));
|
|
2649
|
+
paintFloLessContext();
|
|
2650
|
+
refreshScope();
|
|
2651
|
+
})();
|