@skyphusion/create-prism 0.1.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/LICENSE +235 -0
- package/NOTICE +3 -0
- package/README.md +114 -0
- package/index.js +195 -0
- package/package.json +44 -0
- package/template/CONTRIBUTING.md +80 -0
- package/template/LICENSE +235 -0
- package/template/MIGRATIONS.md +197 -0
- package/template/NOTICE +3 -0
- package/template/README.md +875 -0
- package/template/docs/legal/INSTANCE-ACCEPTABLE-USE.md +98 -0
- package/template/docs/legal/INSTANCE-PRIVACY.md +112 -0
- package/template/docs/legal/README.md +11 -0
- package/template/docs/screenshot-desktop.jpg +0 -0
- package/template/docs/screenshot-mobile.jpg +0 -0
- package/template/gitignore +23 -0
- package/template/migrate-v0.164.0.sql +6 -0
- package/template/migrate-v0.167.0.sql +44 -0
- package/template/migrate-v0.20.0.sql +40 -0
- package/template/migrate-v0.20.2.sql +19 -0
- package/template/migrate-v0.20.3.sql +36 -0
- package/template/migrations/0001_init.sql +134 -0
- package/template/package.json +32 -0
- package/template/public/app.js +2778 -0
- package/template/public/apple-touch-icon.png +0 -0
- package/template/public/favicon-16.png +0 -0
- package/template/public/favicon-32.png +0 -0
- package/template/public/favicon.svg +5 -0
- package/template/public/icon-192.png +0 -0
- package/template/public/icon-512.png +0 -0
- package/template/public/index.html +329 -0
- package/template/public/manifest.webmanifest +14 -0
- package/template/public/streaming-client.js +207 -0
- package/template/public/stt.html +68 -0
- package/template/public/stt.js +16 -0
- package/template/public/styles.css +2068 -0
- package/template/public/voice-widget.js +195 -0
- package/template/schema.sql +283 -0
- package/template/src/ai-binding.ts +33 -0
- package/template/src/auth-kdf.ts +106 -0
- package/template/src/auth.ts +315 -0
- package/template/src/chunking.ts +161 -0
- package/template/src/discord.ts +353 -0
- package/template/src/env.ts +55 -0
- package/template/src/gateway-credentials.ts +97 -0
- package/template/src/health-schema.ts +25 -0
- package/template/src/index.ts +4180 -0
- package/template/src/longrun-params.ts +135 -0
- package/template/src/models.ts +214 -0
- package/template/src/output-extract.ts +128 -0
- package/template/src/parsers/anthropic-sse.ts +56 -0
- package/template/src/parsers/gemini-sse.ts +62 -0
- package/template/src/parsers/openai-sse.ts +60 -0
- package/template/src/parsers/sse-framer.ts +39 -0
- package/template/src/parsers/types.ts +16 -0
- package/template/src/parsers/workers-ai-sse.ts +43 -0
- package/template/src/parsers/xai-sse.ts +40 -0
- package/template/src/providers/anthropic.ts +208 -0
- package/template/src/providers/google.ts +150 -0
- package/template/src/providers/openai.ts +69 -0
- package/template/src/providers/workers-ai.ts +83 -0
- package/template/src/providers/xai.ts +159 -0
- package/template/src/proxied-image-params.ts +43 -0
- package/template/src/rate-limit.ts +77 -0
- package/template/src/searxng.ts +75 -0
- package/template/src/session.ts +114 -0
- package/template/src/stt-session.ts +206 -0
- package/template/src/stt-util.ts +19 -0
- package/template/src/types.ts +56 -0
- package/template/src/user-prefs.ts +63 -0
- package/template/src/utils.ts +73 -0
- package/template/src/zip.ts +137 -0
- package/template/tests/anthropic-sse.test.ts +149 -0
- package/template/tests/auth-kdf.test.ts +59 -0
- package/template/tests/auth-unit.test.ts +97 -0
- package/template/tests/chunking.test.ts +217 -0
- package/template/tests/discord.test.ts +184 -0
- package/template/tests/gateway-credentials.test.ts +65 -0
- package/template/tests/gemini-sse.test.ts +75 -0
- package/template/tests/google-gemini.test.ts +65 -0
- package/template/tests/health-schema.test.ts +35 -0
- package/template/tests/longrun-params.test.ts +128 -0
- package/template/tests/openai-sse.test.ts +71 -0
- package/template/tests/output-extract.test.ts +171 -0
- package/template/tests/proxied-image-params.test.ts +51 -0
- package/template/tests/rate-limit.test.ts +45 -0
- package/template/tests/searxng.test.ts +51 -0
- package/template/tests/sse-framer.test.ts +113 -0
- package/template/tests/stt-session.test.ts +35 -0
- package/template/tests/utils.test.ts +39 -0
- package/template/tests/workers-ai-sse.test.ts +67 -0
- package/template/tests/xai-sse.test.ts +60 -0
- package/template/tests/zip.test.ts +145 -0
- package/template/tests-integration/auth.test.ts +371 -0
- package/template/tests-integration/worker.test.ts +322 -0
- package/template/tsconfig.json +18 -0
- package/template/vitest.config.ts +18 -0
- package/template/vitest.node.config.ts +19 -0
- package/template/vitest.workers.config.ts +47 -0
- package/template/wrangler.example.toml +151 -0
|
@@ -0,0 +1,2778 @@
|
|
|
1
|
+
// skyphusion-llm-public frontend. Multi-turn conversations:
|
|
2
|
+
// - Each "conversation" is a sequence of turns sharing a conversation_id.
|
|
3
|
+
// - The output area renders a transcript: user turn, assistant turn, etc.
|
|
4
|
+
// - Submitting continues the current conversation; the "+ new" button
|
|
5
|
+
// starts a fresh one.
|
|
6
|
+
//
|
|
7
|
+
// For non-chat model types (image gen, TTS, video, etc), each row still
|
|
8
|
+
// shows in the sidebar as a single-turn conversation - the transcript
|
|
9
|
+
// view degrades to one user + one assistant turn, which is fine.
|
|
10
|
+
//
|
|
11
|
+
// Input artifacts are sent as data URLs and stored server-side in R2. Output
|
|
12
|
+
// artifacts (generated images, generated audio) are returned as R2 keys and
|
|
13
|
+
// rendered via /api/artifact/{key}.
|
|
14
|
+
|
|
15
|
+
const $ = (sel) => document.querySelector(sel);
|
|
16
|
+
|
|
17
|
+
// Collapsible model picker (v0.14.x+). Replaces the v0.1.0 flat <select>
|
|
18
|
+
// with a trigger button + popover panel containing <details> accordion
|
|
19
|
+
// groups per catalog `group` field. Items show the model label plus
|
|
20
|
+
// capability badges (vision, streaming) where relevant.
|
|
21
|
+
//
|
|
22
|
+
// Built as a shim so the rest of app.js doesn't change: `.value` getter
|
|
23
|
+
// and setter, plus addEventListener("change", fn), match the native
|
|
24
|
+
// <select> surface. Setting .value programmatically does NOT fire
|
|
25
|
+
// `change` (mirrors native behavior); user-driven clicks do.
|
|
26
|
+
const modelSelect = (function buildModelPicker() {
|
|
27
|
+
const root = document.getElementById("model");
|
|
28
|
+
if (!root) throw new Error("Model picker root #model not found");
|
|
29
|
+
|
|
30
|
+
const trigger = document.createElement("button");
|
|
31
|
+
trigger.type = "button";
|
|
32
|
+
trigger.className = "model-picker-trigger";
|
|
33
|
+
trigger.setAttribute("aria-haspopup", "listbox");
|
|
34
|
+
trigger.setAttribute("aria-expanded", "false");
|
|
35
|
+
trigger.innerHTML =
|
|
36
|
+
'<span class="model-picker-label">choose a model</span>' +
|
|
37
|
+
'<span class="model-picker-chevron" aria-hidden="true">\u25BE</span>';
|
|
38
|
+
|
|
39
|
+
const panel = document.createElement("div");
|
|
40
|
+
panel.className = "model-picker-panel";
|
|
41
|
+
panel.setAttribute("role", "listbox");
|
|
42
|
+
panel.hidden = true;
|
|
43
|
+
|
|
44
|
+
// v0.111.0: searchable. A filter input over a results container; populate()
|
|
45
|
+
// fills the results, and typing live-filters items + hides empty groups.
|
|
46
|
+
const search = document.createElement("input");
|
|
47
|
+
search.type = "search";
|
|
48
|
+
search.className = "model-picker-search";
|
|
49
|
+
search.placeholder = "search models…";
|
|
50
|
+
search.setAttribute("aria-label", "search models");
|
|
51
|
+
const results = document.createElement("div");
|
|
52
|
+
results.className = "model-picker-results";
|
|
53
|
+
panel.appendChild(search);
|
|
54
|
+
panel.appendChild(results);
|
|
55
|
+
|
|
56
|
+
root.appendChild(trigger);
|
|
57
|
+
root.appendChild(panel);
|
|
58
|
+
|
|
59
|
+
const labelEl = trigger.querySelector(".model-picker-label");
|
|
60
|
+
let currentValue = null;
|
|
61
|
+
const changeListeners = [];
|
|
62
|
+
|
|
63
|
+
function setOpen(open) {
|
|
64
|
+
panel.hidden = !open;
|
|
65
|
+
trigger.setAttribute("aria-expanded", open ? "true" : "false");
|
|
66
|
+
// Auto-focus the search box only on precise-pointer (desktop) devices; on
|
|
67
|
+
// touch this would pop the on-screen keyboard every time the picker opens.
|
|
68
|
+
if (open && window.matchMedia && window.matchMedia("(hover: hover) and (pointer: fine)").matches) {
|
|
69
|
+
setTimeout(() => search.focus(), 0);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function updateTriggerLabel() {
|
|
74
|
+
const m = currentValue ? state.modelsById[currentValue] : null;
|
|
75
|
+
labelEl.textContent = m ? m.label : "choose a model";
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function setValue(id, fireChange) {
|
|
79
|
+
if (currentValue === id) return;
|
|
80
|
+
currentValue = id;
|
|
81
|
+
updateTriggerLabel();
|
|
82
|
+
panel.querySelectorAll(".model-item").forEach((el) => {
|
|
83
|
+
el.classList.toggle("selected", el.dataset.modelId === id);
|
|
84
|
+
});
|
|
85
|
+
if (fireChange) {
|
|
86
|
+
const evt = { target: shim };
|
|
87
|
+
changeListeners.forEach((fn) => fn(evt));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function escAttr(s) {
|
|
92
|
+
return String(s).replace(/[&<>"']/g, (c) => ({
|
|
93
|
+
"&": "&", "<": "<", ">": ">", '"': """, "'": "'",
|
|
94
|
+
}[c]));
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function renderBadges(m) {
|
|
98
|
+
const badges = [];
|
|
99
|
+
if ((m.capabilities || []).includes("vision")) {
|
|
100
|
+
badges.push('<span class="model-badge badge-vision" title="accepts images">vision</span>');
|
|
101
|
+
}
|
|
102
|
+
if (m.streaming) {
|
|
103
|
+
badges.push('<span class="model-badge badge-stream" title="supports SSE streaming">stream</span>');
|
|
104
|
+
}
|
|
105
|
+
return badges.length ? '<span class="model-item-badges">' + badges.join("") + '</span>' : '';
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function populate(grouped) {
|
|
109
|
+
const groupNames = Object.keys(grouped);
|
|
110
|
+
results.innerHTML = groupNames.map((group, idx) => {
|
|
111
|
+
const items = grouped[group];
|
|
112
|
+
const openAttr = idx === 0 ? " open" : "";
|
|
113
|
+
const itemsHtml = items.map((m) =>
|
|
114
|
+
'<li><button type="button" class="model-item" role="option" data-model-id="' +
|
|
115
|
+
escAttr(m.id) + '"><span class="model-item-label">' + escAttr(m.label) +
|
|
116
|
+
'</span>' + renderBadges(m) + '</button></li>'
|
|
117
|
+
).join("");
|
|
118
|
+
return '<details class="model-group"' + openAttr +
|
|
119
|
+
'><summary class="model-group-header">' + escAttr(group) +
|
|
120
|
+
' <span class="model-group-count">' + items.length + '</span></summary>' +
|
|
121
|
+
'<ul class="model-group-list">' + itemsHtml + '</ul></details>';
|
|
122
|
+
}).join("");
|
|
123
|
+
|
|
124
|
+
// Re-apply highlight if currentValue is still in the catalog; otherwise
|
|
125
|
+
// pick the first model so .value is never null after populate completes.
|
|
126
|
+
if (currentValue && state.modelsById[currentValue]) {
|
|
127
|
+
const sel = panel.querySelector('.model-item[data-model-id="' + CSS.escape(currentValue) + '"]');
|
|
128
|
+
if (sel) sel.classList.add("selected");
|
|
129
|
+
} else if (groupNames.length && grouped[groupNames[0]].length) {
|
|
130
|
+
setValue(grouped[groupNames[0]][0].id, false);
|
|
131
|
+
}
|
|
132
|
+
updateTriggerLabel();
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
trigger.addEventListener("click", () => setOpen(panel.hidden));
|
|
136
|
+
panel.addEventListener("click", (e) => {
|
|
137
|
+
const item = e.target.closest(".model-item");
|
|
138
|
+
if (item) {
|
|
139
|
+
setValue(item.dataset.modelId, true);
|
|
140
|
+
setOpen(false);
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
document.addEventListener("click", (e) => {
|
|
144
|
+
if (!root.contains(e.target)) setOpen(false);
|
|
145
|
+
});
|
|
146
|
+
document.addEventListener("keydown", (e) => {
|
|
147
|
+
if (e.key === "Escape" && !panel.hidden) {
|
|
148
|
+
setOpen(false);
|
|
149
|
+
trigger.focus();
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
function applyFilter() {
|
|
154
|
+
const q = search.value.trim().toLowerCase();
|
|
155
|
+
results.querySelectorAll(".model-group").forEach((grp) => {
|
|
156
|
+
let any = false;
|
|
157
|
+
grp.querySelectorAll(".model-item").forEach((it) => {
|
|
158
|
+
const lbl = (it.querySelector(".model-item-label")?.textContent || "").toLowerCase();
|
|
159
|
+
const li = it.closest("li");
|
|
160
|
+
const match = !q || lbl.includes(q);
|
|
161
|
+
if (li) li.style.display = match ? "" : "none";
|
|
162
|
+
if (match) any = true;
|
|
163
|
+
});
|
|
164
|
+
grp.style.display = any ? "" : "none";
|
|
165
|
+
if (q) grp.open = any; // expand groups with matches while searching
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
search.addEventListener("input", applyFilter);
|
|
169
|
+
// Enter in the search picks the first visible match.
|
|
170
|
+
search.addEventListener("keydown", (e) => {
|
|
171
|
+
if (e.key !== "Enter") return;
|
|
172
|
+
const first = Array.from(results.querySelectorAll(".model-item"))
|
|
173
|
+
.find((it) => { const li = it.closest("li"); return li && li.style.display !== "none"; });
|
|
174
|
+
if (first) { setValue(first.dataset.modelId, true); setOpen(false); }
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
const shim = {
|
|
178
|
+
get value() { return currentValue; },
|
|
179
|
+
set value(v) { setValue(v, false); },
|
|
180
|
+
addEventListener(event, fn) {
|
|
181
|
+
if (event === "change") changeListeners.push(fn);
|
|
182
|
+
},
|
|
183
|
+
populate,
|
|
184
|
+
};
|
|
185
|
+
return shim;
|
|
186
|
+
})();
|
|
187
|
+
|
|
188
|
+
const systemPromptLabel = $("#system-prompt-label");
|
|
189
|
+
const systemPrompt = $("#system-prompt");
|
|
190
|
+
const userInputLabel = $("#user-input-label");
|
|
191
|
+
const userInput = $("#user-input");
|
|
192
|
+
const runBtn = $("#run");
|
|
193
|
+
const transcriptEl = $("#transcript");
|
|
194
|
+
const convTitleEl = $("#conv-title");
|
|
195
|
+
const outputMeta = $("#output-meta");
|
|
196
|
+
const historyList = $("#history-list");
|
|
197
|
+
const accountEmail = $("#account-email");
|
|
198
|
+
const accountToggle = $("#account-toggle");
|
|
199
|
+
const accountMenu = $("#account-menu");
|
|
200
|
+
const accountUserBtn = $("#account-user");
|
|
201
|
+
const gatewayBanner = $("#gateway-banner");
|
|
202
|
+
const gatewayBannerText = $("#gateway-banner-text");
|
|
203
|
+
const gatewayBannerBtn = $("#gateway-banner-btn");
|
|
204
|
+
const historySearch = $("#history-search");
|
|
205
|
+
const newChatBtn = $("#new-chat");
|
|
206
|
+
const fileInput = $("#file-input");
|
|
207
|
+
const attachBtn = $("#attach-btn");
|
|
208
|
+
const attachHint = $("#attach-hint");
|
|
209
|
+
const attachments = $("#attachments");
|
|
210
|
+
const attachRow = $("#attach-row");
|
|
211
|
+
const inputArea = document.querySelector(".input-area");
|
|
212
|
+
// v0.108.0: live "voice" (conversational STT) composer affordance.
|
|
213
|
+
const voicePanel = $("#voice-panel");
|
|
214
|
+
const voiceStartBtn = $("#voice-start");
|
|
215
|
+
const userInputField = $("#user-input-field");
|
|
216
|
+
const bottomRow = document.querySelector(".bottom-row");
|
|
217
|
+
const systemPromptField = systemPromptLabel ? systemPromptLabel.closest("label") : null;
|
|
218
|
+
let voiceWidget = null; // lazily mounted once a voice model is first selected
|
|
219
|
+
// v0.110.0: focus-mode redesign refs.
|
|
220
|
+
const composerEl = document.querySelector(".composer");
|
|
221
|
+
const settingsToggle = $("#settings-toggle");
|
|
222
|
+
const settingsPanel = $("#settings-panel");
|
|
223
|
+
// v0.118.0: voice-chat (talk to the model, hear the reply).
|
|
224
|
+
const voiceChatToggle = $("#voice-chat-toggle");
|
|
225
|
+
const voiceChatStatus = $("#voice-chat-status");
|
|
226
|
+
const useDocsRow = $("#use-docs-row");
|
|
227
|
+
const useDocsCheckbox = $("#use-docs");
|
|
228
|
+
const useWebSearchRow = $("#use-web-search-row");
|
|
229
|
+
const useWebSearchCheckbox = $("#use-web-search");
|
|
230
|
+
const sidebarToggle = $("#sidebar-toggle");
|
|
231
|
+
const sidebarBackdrop = $("#sidebar-backdrop");
|
|
232
|
+
const layout = document.querySelector(".layout");
|
|
233
|
+
|
|
234
|
+
const MAX_IMAGE_BYTES = 4 * 1024 * 1024;
|
|
235
|
+
const MAX_AUDIO_BYTES = 20 * 1024 * 1024;
|
|
236
|
+
const MAX_VIDEO_BYTES = 100 * 1024 * 1024;
|
|
237
|
+
// v0.24.0: inline text-file attachment cap. Read as text and folded into the
|
|
238
|
+
// prompt; the worker truncates very large files past its own char cap.
|
|
239
|
+
const MAX_DOC_ATTACHMENT_BYTES = 2 * 1024 * 1024;
|
|
240
|
+
const IMAGE_MAX_DIM = 1280;
|
|
241
|
+
const VIDEO_FRAMES = 8;
|
|
242
|
+
const VIDEO_FRAME_MAX_DIM = 1024;
|
|
243
|
+
// FLUX.2 reference image input (v0.16.0): each reference image must be
|
|
244
|
+
// <=512x512 per the Cloudflare model spec; the form takes up to 4 of them
|
|
245
|
+
// via input_image_0..input_image_3.
|
|
246
|
+
const FLUX2_REF_IMAGE_MAX_DIM = 512;
|
|
247
|
+
const MAX_FLUX2_REF_IMAGES = 4;
|
|
248
|
+
|
|
249
|
+
// Inline SVG icons for per-turn action buttons (v0.12.0+). Kept as raw strings
|
|
250
|
+
// rather than fetched assets to avoid an extra request and to inherit the
|
|
251
|
+
// surrounding text color via stroke="currentColor". Sized via CSS, not the
|
|
252
|
+
// width/height attributes.
|
|
253
|
+
const ICON_COPY = `<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="5" y="5" width="9" height="9" rx="1"/><path d="M11 5V3a1 1 0 0 0-1-1H3a1 1 0 0 0-1 1v7a1 1 0 0 0 1 1h2"/></svg>`;
|
|
254
|
+
const ICON_EDIT = `<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M11.5 1.5l3 3-8.5 8.5H3v-3z"/><path d="M9.5 3.5l3 3"/></svg>`;
|
|
255
|
+
const ICON_RETRY = `<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M13.5 8a5.5 5.5 0 1 1-1.6-3.9"/><polyline points="13.5 1.5 13.5 4.5 10.5 4.5"/></svg>`;
|
|
256
|
+
const ICON_CHECK = `<svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="3 8 7 12 13 4"/></svg>`;
|
|
257
|
+
|
|
258
|
+
const state = {
|
|
259
|
+
user: null,
|
|
260
|
+
gateway: null,
|
|
261
|
+
currentConversationId: null,
|
|
262
|
+
currentTurns: [],
|
|
263
|
+
modelsById: {},
|
|
264
|
+
pendingAttachments: [],
|
|
265
|
+
pollTimer: null,
|
|
266
|
+
pollChatId: null,
|
|
267
|
+
pollStartedAt: 0,
|
|
268
|
+
pollElapsedTimer: null,
|
|
269
|
+
documentCount: 0,
|
|
270
|
+
// v0.20.1: projects state.
|
|
271
|
+
// projects is the list as returned by GET /api/projects (each row has
|
|
272
|
+
// id, name, slug, description, system_prompt, created_at, updated_at,
|
|
273
|
+
// document_count). activeProjectId is the currently-selected project (or
|
|
274
|
+
// null), persisted across reloads in localStorage.
|
|
275
|
+
projects: [],
|
|
276
|
+
activeProjectId: null,
|
|
277
|
+
// #80 public-mode auth state, seeded by the boot probe (GET /api/models).
|
|
278
|
+
authMode: "access",
|
|
279
|
+
authenticated: true,
|
|
280
|
+
displayName: null,
|
|
281
|
+
};
|
|
282
|
+
|
|
283
|
+
// ---------- API helpers ----------
|
|
284
|
+
|
|
285
|
+
async function api(path, opts = {}) {
|
|
286
|
+
const res = await fetch(path, {
|
|
287
|
+
...opts,
|
|
288
|
+
headers: { "Content-Type": "application/json", ...(opts.headers || {}) },
|
|
289
|
+
});
|
|
290
|
+
if (!res.ok) {
|
|
291
|
+
const err = await res.json().catch(() => ({ error: res.statusText }));
|
|
292
|
+
// #80: public-mode session expiry. Any identity-required route answers 401
|
|
293
|
+
// when the session cookie is missing or stale; drop back to the auth gate
|
|
294
|
+
// so the user re-authenticates instead of hitting opaque failures. Access
|
|
295
|
+
// mode never 401s here (Cloudflare Access sits upstream), so this is inert
|
|
296
|
+
// for self-host deploys.
|
|
297
|
+
if (res.status === 401 && state.authMode === "public") {
|
|
298
|
+
showAuthScreen();
|
|
299
|
+
}
|
|
300
|
+
// Carry the status (and machine-readable code when present) on the thrown
|
|
301
|
+
// error so callers can pattern-match, e.g. the 412 fail-closed gateway gate.
|
|
302
|
+
const e = new Error(err.error || `HTTP ${res.status}`);
|
|
303
|
+
e.status = res.status;
|
|
304
|
+
e.code = err.code || null;
|
|
305
|
+
throw e;
|
|
306
|
+
}
|
|
307
|
+
return res.json();
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function escapeHtml(s) {
|
|
311
|
+
return String(s).replace(/[&<>"']/g, (c) => ({
|
|
312
|
+
"&": "&", "<": "<", ">": ">", '"': """, "'": "'",
|
|
313
|
+
}[c]));
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function artifactUrl(key) {
|
|
317
|
+
return `/api/artifact/${encodeURI(key)}`;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function fmtBytes(n) {
|
|
321
|
+
if (n < 1024) return `${n} B`;
|
|
322
|
+
if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`;
|
|
323
|
+
return `${(n / (1024 * 1024)).toFixed(1)} MB`;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
function fmtMeta(chat) {
|
|
327
|
+
const parts = [];
|
|
328
|
+
if (chat.tokens_in != null) parts.push(`in: ${chat.tokens_in}`);
|
|
329
|
+
if (chat.tokens_out != null) parts.push(`out: ${chat.tokens_out}`);
|
|
330
|
+
if (chat.latency_ms != null) parts.push(`${chat.latency_ms}ms`);
|
|
331
|
+
return parts.join(" \u00b7 ");
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// ---------- Models ----------
|
|
335
|
+
|
|
336
|
+
async function loadModels(prefetched) {
|
|
337
|
+
// #80: bootstrap() already fetched GET /api/models for the boot gate; accept
|
|
338
|
+
// that payload so the app hydrates from one call instead of refetching.
|
|
339
|
+
const { models, user, gateway } = prefetched || await api("/api/models");
|
|
340
|
+
state.user = user;
|
|
341
|
+
state.gateway = gateway || null;
|
|
342
|
+
// #80: in public mode show the chosen username, not the opaque usr_<id>
|
|
343
|
+
// identity; access/self-host mode keeps the email identity unchanged.
|
|
344
|
+
if (accountEmail) accountEmail.textContent = state.displayName || user;
|
|
345
|
+
renderGatewayBanner();
|
|
346
|
+
|
|
347
|
+
state.modelsById = {};
|
|
348
|
+
const grouped = {};
|
|
349
|
+
for (const m of models) {
|
|
350
|
+
state.modelsById[m.id] = m;
|
|
351
|
+
const g = m.group || "Other";
|
|
352
|
+
(grouped[g] ||= []).push(m);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
modelSelect.populate(grouped);
|
|
356
|
+
|
|
357
|
+
updateAffordance();
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function renderGatewayBanner() {
|
|
361
|
+
if (!gatewayBanner) return;
|
|
362
|
+
const g = state.gateway;
|
|
363
|
+
if (!g || g.configured) {
|
|
364
|
+
gatewayBanner.hidden = true;
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
gatewayBanner.hidden = false;
|
|
368
|
+
if (gatewayBannerText) {
|
|
369
|
+
gatewayBannerText.textContent =
|
|
370
|
+
"AI Gateway not configured. Set your gateway slug and a Cloudflare API token with AI Gateway Run permission to run models on your account.";
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function currentModel() {
|
|
375
|
+
return state.modelsById[modelSelect.value];
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function modelSupports(cap) {
|
|
379
|
+
const m = currentModel();
|
|
380
|
+
return !!m && (m.capabilities || []).includes(cap);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function isFlux2Model(m) {
|
|
384
|
+
return !!m && m.id.startsWith("@cf/black-forest-labs/flux-2-");
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
// v0.21.7: most recent artifact of a media type ("image" | "video") produced
|
|
388
|
+
// earlier in the current conversation. Returns its R2 key, or null. The basis
|
|
389
|
+
// of cross-model artifact reuse: carry a prior generated image/video forward
|
|
390
|
+
// to whatever model you switch to, by reference, without re-upload.
|
|
391
|
+
function latestArtifactKey(mediaType) {
|
|
392
|
+
for (let i = state.currentTurns.length - 1; i >= 0; i--) {
|
|
393
|
+
const a = state.currentTurns[i] && state.currentTurns[i].output_artifact;
|
|
394
|
+
if (a && a.key && (a.type === mediaType || (a.mime || "").startsWith(mediaType + "/"))) {
|
|
395
|
+
return a.key;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
return null;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// Does the selected model consume an image as input? vision chat, FLUX.2
|
|
402
|
+
// reference, or image-to-video (i2v). i2v uses the image_key field; the others
|
|
403
|
+
// take it as an image attachment.
|
|
404
|
+
function modelConsumesImage(m) {
|
|
405
|
+
if (!m) return false;
|
|
406
|
+
return (m.capabilities || []).includes("vision")
|
|
407
|
+
|| (m.capabilities || []).includes("image-input")
|
|
408
|
+
|| (m.type === "image" && isFlux2Model(m));
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
function updateAffordance() {
|
|
412
|
+
const m = currentModel();
|
|
413
|
+
if (!m) return;
|
|
414
|
+
|
|
415
|
+
// Default: hide the use-docs toggle. The chat branch turns it on when
|
|
416
|
+
// the user has uploaded at least one document.
|
|
417
|
+
// v0.17.0: also default-hide the web-search toggle; chat branch shows it.
|
|
418
|
+
useDocsRow.hidden = true;
|
|
419
|
+
useWebSearchRow.hidden = true;
|
|
420
|
+
fileInput.style.display = ""; // default shown; some branches set accept/visibility
|
|
421
|
+
|
|
422
|
+
// v0.108.0/v0.110.0: default to the normal composer; the "voice" branch swaps
|
|
423
|
+
// it for the live mic panel. Restoring here covers switching away from voice.
|
|
424
|
+
if (voicePanel) voicePanel.hidden = true;
|
|
425
|
+
if (composerEl) composerEl.style.display = "";
|
|
426
|
+
if (systemPromptField) systemPromptField.style.display = "";
|
|
427
|
+
if (voiceWidget && voiceWidget.isRunning()) voiceWidget.stop();
|
|
428
|
+
// The attach hint now sits in the composer foot (separate from the attach
|
|
429
|
+
// button), so clear it by default; branches that allow attachments set it.
|
|
430
|
+
attachHint.textContent = "";
|
|
431
|
+
// v0.118.0: the voice-chat mic is a chat-only affordance. Stop an active
|
|
432
|
+
// session if we switch away from a chat model.
|
|
433
|
+
if (voiceChatToggle) voiceChatToggle.hidden = m.type !== "chat";
|
|
434
|
+
if (m.type !== "chat" && vc.active) stopVoiceChat();
|
|
435
|
+
|
|
436
|
+
if (m.type === "image") {
|
|
437
|
+
systemPromptLabel.textContent = "negative prompt";
|
|
438
|
+
systemPrompt.placeholder = "things to avoid in the image (optional)";
|
|
439
|
+
userInputLabel.textContent = "image prompt";
|
|
440
|
+
userInput.placeholder = "describe the image";
|
|
441
|
+
|
|
442
|
+
// FLUX.2 (v0.16.0) accepts up to 4 reference images via input_image_0..3.
|
|
443
|
+
// For the rest of the image models, no attach UI.
|
|
444
|
+
const isFlux2 = m.id.startsWith("@cf/black-forest-labs/flux-2-");
|
|
445
|
+
if (isFlux2) {
|
|
446
|
+
attachRow.style.display = "flex";
|
|
447
|
+
fileInput.accept = "image/*";
|
|
448
|
+
attachHint.textContent = `optional: up to ${MAX_FLUX2_REF_IMAGES} reference images (downscaled to ${FLUX2_REF_IMAGE_MAX_DIM}px)`;
|
|
449
|
+
attachHint.classList.remove("warn");
|
|
450
|
+
} else {
|
|
451
|
+
attachRow.style.display = "none";
|
|
452
|
+
state.pendingAttachments = [];
|
|
453
|
+
renderAttachments();
|
|
454
|
+
}
|
|
455
|
+
} else if (m.type === "tts") {
|
|
456
|
+
systemPromptLabel.textContent = "system prompt";
|
|
457
|
+
systemPrompt.placeholder = "(unused for TTS)";
|
|
458
|
+
userInputLabel.textContent = "text to speak";
|
|
459
|
+
userInput.placeholder = "text to synthesize as speech";
|
|
460
|
+
attachRow.style.display = "none";
|
|
461
|
+
state.pendingAttachments = [];
|
|
462
|
+
renderAttachments();
|
|
463
|
+
} else if (m.type === "video") {
|
|
464
|
+
systemPromptLabel.textContent = "system prompt";
|
|
465
|
+
systemPrompt.placeholder = "(unused for video gen)";
|
|
466
|
+
userInputLabel.textContent = "video prompt";
|
|
467
|
+
userInput.placeholder = "describe the video (8s at 16:9, takes 1-3 min)";
|
|
468
|
+
attachRow.style.display = "none";
|
|
469
|
+
state.pendingAttachments = [];
|
|
470
|
+
renderAttachments();
|
|
471
|
+
// v0.21.7: image-to-video models can ALSO animate the most recent image
|
|
472
|
+
// generated earlier in this conversation. v0.21.9: but you can upload your
|
|
473
|
+
// own source image too (hiding the upload was a regression).
|
|
474
|
+
if ((m.capabilities || []).includes("image-input")) {
|
|
475
|
+
userInput.placeholder = "describe the motion (~1-3 min)";
|
|
476
|
+
const priorImageKey = latestArtifactKey("image");
|
|
477
|
+
attachRow.style.display = "flex";
|
|
478
|
+
fileInput.style.display = "";
|
|
479
|
+
fileInput.accept = "image/*";
|
|
480
|
+
attachHint.textContent = priorImageKey
|
|
481
|
+
? "upload an image to animate, or leave empty to animate the previous generated image in this conversation"
|
|
482
|
+
: "upload an image to animate";
|
|
483
|
+
attachHint.classList.remove("warn");
|
|
484
|
+
}
|
|
485
|
+
} else if (m.type === "stt") {
|
|
486
|
+
systemPromptLabel.textContent = "system prompt";
|
|
487
|
+
systemPrompt.placeholder = "(unused for STT)";
|
|
488
|
+
userInputLabel.textContent = "optional context";
|
|
489
|
+
userInput.placeholder = "optional context for the transcriber (e.g. domain-specific terms)";
|
|
490
|
+
attachRow.style.display = "flex";
|
|
491
|
+
fileInput.accept = "audio/*";
|
|
492
|
+
attachHint.textContent = "attach an audio file to transcribe (required)";
|
|
493
|
+
attachHint.classList.remove("warn");
|
|
494
|
+
} else if (m.type === "music") {
|
|
495
|
+
systemPromptLabel.textContent = "lyrics (optional)";
|
|
496
|
+
systemPrompt.placeholder = "song lyrics, optional. use [Verse] [Chorus] [Bridge] [Outro] tags for structure";
|
|
497
|
+
userInputLabel.textContent = "song description";
|
|
498
|
+
userInput.placeholder = "style/mood/genre, e.g. 'indie folk, melancholic, longing, solitary walk'";
|
|
499
|
+
attachRow.style.display = "none";
|
|
500
|
+
state.pendingAttachments = [];
|
|
501
|
+
renderAttachments();
|
|
502
|
+
} else if (m.type === "voice") {
|
|
503
|
+
// Conversational STT: swap the text composer for the live mic panel. The
|
|
504
|
+
// session streams to the SttSession DO over /api/stt/stream and persists the
|
|
505
|
+
// final transcript to history when you stop.
|
|
506
|
+
if (composerEl) composerEl.style.display = "none";
|
|
507
|
+
if (systemPromptField) systemPromptField.style.display = "none";
|
|
508
|
+
state.pendingAttachments = [];
|
|
509
|
+
renderAttachments();
|
|
510
|
+
if (voicePanel) voicePanel.hidden = false;
|
|
511
|
+
if (!voiceWidget && typeof window.createVoiceWidget === "function" && voiceStartBtn) {
|
|
512
|
+
voiceWidget = window.createVoiceWidget({
|
|
513
|
+
startBtn: voiceStartBtn,
|
|
514
|
+
statusEl: $("#voice-status"),
|
|
515
|
+
liveEl: $("#voice-live"),
|
|
516
|
+
turnsEl: $("#voice-turns"),
|
|
517
|
+
});
|
|
518
|
+
}
|
|
519
|
+
} else {
|
|
520
|
+
// chat
|
|
521
|
+
systemPromptLabel.textContent = "system prompt";
|
|
522
|
+
systemPrompt.placeholder = "optional";
|
|
523
|
+
userInputLabel.textContent = "your input";
|
|
524
|
+
userInput.placeholder = "enter to send, shift+enter for newline";
|
|
525
|
+
attachRow.style.display = "flex";
|
|
526
|
+
// v0.24.0: chat accepts any file (empty accept = no picker filter). Vision
|
|
527
|
+
// models also take images/video; non-vision get audio auto-transcribed +
|
|
528
|
+
// text files inlined. The paperclip button conveys "attach a file", so no
|
|
529
|
+
// verbose hint sentence (v0.114.0).
|
|
530
|
+
fileInput.accept = "";
|
|
531
|
+
attachHint.textContent = "";
|
|
532
|
+
attachHint.classList.remove("warn");
|
|
533
|
+
// RAG: show the toggle only when chat is selected AND the user has
|
|
534
|
+
// uploaded at least one document. Without docs there's nothing to retrieve.
|
|
535
|
+
useDocsRow.hidden = state.documentCount === 0;
|
|
536
|
+
// v0.17.0: web search is always available on chat (no docs dependency).
|
|
537
|
+
useWebSearchRow.hidden = false;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
// ---------- File handling ----------
|
|
542
|
+
|
|
543
|
+
function readAsDataUrl(file) {
|
|
544
|
+
return new Promise((resolve, reject) => {
|
|
545
|
+
const reader = new FileReader();
|
|
546
|
+
reader.onload = () => resolve(reader.result);
|
|
547
|
+
reader.onerror = () => reject(new Error("File read failed"));
|
|
548
|
+
reader.readAsDataURL(file);
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
async function downscaleImage(dataUrl, maxDim) {
|
|
553
|
+
const img = await loadImage(dataUrl);
|
|
554
|
+
if (img.width <= maxDim && img.height <= maxDim) return dataUrl;
|
|
555
|
+
const scale = maxDim / Math.max(img.width, img.height);
|
|
556
|
+
const canvas = document.createElement("canvas");
|
|
557
|
+
canvas.width = Math.round(img.width * scale);
|
|
558
|
+
canvas.height = Math.round(img.height * scale);
|
|
559
|
+
const ctx = canvas.getContext("2d");
|
|
560
|
+
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
|
|
561
|
+
return canvas.toDataURL("image/jpeg", 0.85);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
function loadImage(src) {
|
|
565
|
+
return new Promise((resolve, reject) => {
|
|
566
|
+
const img = new Image();
|
|
567
|
+
img.onload = () => resolve(img);
|
|
568
|
+
img.onerror = () => reject(new Error("Image decode failed"));
|
|
569
|
+
img.src = src;
|
|
570
|
+
});
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
async function extractVideoFrames(file, n, maxDim) {
|
|
574
|
+
const video = document.createElement("video");
|
|
575
|
+
video.preload = "auto";
|
|
576
|
+
video.muted = true;
|
|
577
|
+
video.playsInline = true;
|
|
578
|
+
// File via srcObject, not blob: URL on .src (CodeQL js/xss-through-dom).
|
|
579
|
+
video.srcObject = file;
|
|
580
|
+
|
|
581
|
+
try {
|
|
582
|
+
await new Promise((resolve, reject) => {
|
|
583
|
+
video.addEventListener("loadedmetadata", () => resolve(), { once: true });
|
|
584
|
+
video.addEventListener("error", () => reject(new Error("Video load failed")), { once: true });
|
|
585
|
+
});
|
|
586
|
+
|
|
587
|
+
const duration = video.duration;
|
|
588
|
+
if (!isFinite(duration) || duration <= 0) {
|
|
589
|
+
throw new Error("Video duration unavailable (file may be malformed)");
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
const w = video.videoWidth, h = video.videoHeight;
|
|
593
|
+
const scale = Math.min(1, maxDim / Math.max(w, h));
|
|
594
|
+
const cw = Math.max(1, Math.round(w * scale));
|
|
595
|
+
const ch = Math.max(1, Math.round(h * scale));
|
|
596
|
+
const canvas = document.createElement("canvas");
|
|
597
|
+
canvas.width = cw;
|
|
598
|
+
canvas.height = ch;
|
|
599
|
+
const ctx = canvas.getContext("2d");
|
|
600
|
+
|
|
601
|
+
const frames = [];
|
|
602
|
+
for (let i = 1; i <= n; i++) {
|
|
603
|
+
const t = (duration * i) / (n + 1);
|
|
604
|
+
video.currentTime = Math.min(t, Math.max(0, duration - 0.05));
|
|
605
|
+
await new Promise((resolve, reject) => {
|
|
606
|
+
const onSeeked = () => { video.removeEventListener("error", onError); resolve(); };
|
|
607
|
+
const onError = () => { video.removeEventListener("seeked", onSeeked); reject(new Error("Video seek failed")); };
|
|
608
|
+
video.addEventListener("seeked", onSeeked, { once: true });
|
|
609
|
+
video.addEventListener("error", onError, { once: true });
|
|
610
|
+
});
|
|
611
|
+
ctx.drawImage(video, 0, 0, cw, ch);
|
|
612
|
+
frames.push(canvas.toDataURL("image/jpeg", 0.85));
|
|
613
|
+
}
|
|
614
|
+
return { frames, duration, width: w, height: h };
|
|
615
|
+
} finally {
|
|
616
|
+
video.srcObject = null;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
async function handleFiles(files) {
|
|
621
|
+
const m = currentModel();
|
|
622
|
+
// The attach UI is shown for chat, STT, and FLUX-2 image gen (which accepts
|
|
623
|
+
// reference images). Other model types (TTS, video gen, music gen, non-FLUX-2
|
|
624
|
+
// image gen) hide the attach UI and don't reach this path. Prior to v0.19.5
|
|
625
|
+
// this guard was `m.type !== "chat"`, which silently dropped attachments on
|
|
626
|
+
// STT and FLUX-2 despite the affordance UI being shown.
|
|
627
|
+
const isFlux2 = m.id.startsWith("@cf/black-forest-labs/flux-2-");
|
|
628
|
+
// v0.21.10: image-input (i2v) models accept a source image too. Without this,
|
|
629
|
+
// the early guard dropped the file before the per-file branch ran — which
|
|
630
|
+
// killed BOTH the picker and drag/drop for i2v (the v0.21.9 fix patched
|
|
631
|
+
// downstream of this return and never reached).
|
|
632
|
+
const isImageInput = (m.capabilities || []).includes("image-input");
|
|
633
|
+
if (m.type !== "chat" && m.type !== "stt" && !isFlux2 && !isImageInput) return;
|
|
634
|
+
// Pegasus 1.2 (Bedrock) is a chat-type model but needs the FULL video file,
|
|
635
|
+
// not frame extraction. The model id starts with "bedrock/twelvelabs.pegasus".
|
|
636
|
+
const isPegasus = m.id.startsWith("bedrock/twelvelabs.pegasus");
|
|
637
|
+
|
|
638
|
+
for (const file of files) {
|
|
639
|
+
try {
|
|
640
|
+
if (file.type.startsWith("image/")) {
|
|
641
|
+
// FLUX.2 image-mode accepts reference images even though its catalog
|
|
642
|
+
// entry doesn't list the "vision" capability (the capability flag is
|
|
643
|
+
// for analyzing input, not for using images as gen references). For
|
|
644
|
+
// FLUX.2 specifically: cap at 4 attachments and downscale harder.
|
|
645
|
+
const m2 = currentModel();
|
|
646
|
+
const isFlux2 = !!m2 && m2.id.startsWith("@cf/black-forest-labs/flux-2-");
|
|
647
|
+
const isImageInput = !!m2 && (m2.capabilities || []).includes("image-input");
|
|
648
|
+
if (isFlux2) {
|
|
649
|
+
const existing = state.pendingAttachments.filter((a) => a.type === "image").length;
|
|
650
|
+
if (existing >= MAX_FLUX2_REF_IMAGES) {
|
|
651
|
+
throw new Error(`FLUX.2 accepts up to ${MAX_FLUX2_REF_IMAGES} reference images; skipping the rest`);
|
|
652
|
+
}
|
|
653
|
+
if (file.size > MAX_IMAGE_BYTES) throw new Error(`Image too large (${fmtBytes(file.size)} > ${fmtBytes(MAX_IMAGE_BYTES)})`);
|
|
654
|
+
const raw = await readAsDataUrl(file);
|
|
655
|
+
const data = await downscaleImage(raw, FLUX2_REF_IMAGE_MAX_DIM);
|
|
656
|
+
state.pendingAttachments.push({ type: "image", mime: file.type, filename: file.name, data });
|
|
657
|
+
} else if (isImageInput) {
|
|
658
|
+
// v0.21.9: image-to-video source. A single image to animate; replace
|
|
659
|
+
// any prior pick so re-selecting just swaps the source.
|
|
660
|
+
if (file.size > MAX_IMAGE_BYTES) throw new Error(`Image too large (${fmtBytes(file.size)} > ${fmtBytes(MAX_IMAGE_BYTES)})`);
|
|
661
|
+
const raw = await readAsDataUrl(file);
|
|
662
|
+
const data = await downscaleImage(raw, IMAGE_MAX_DIM);
|
|
663
|
+
state.pendingAttachments = state.pendingAttachments.filter((a) => a.type !== "image");
|
|
664
|
+
state.pendingAttachments.push({ type: "image", mime: file.type, filename: file.name, data });
|
|
665
|
+
} else {
|
|
666
|
+
if (!modelSupports("vision")) throw new Error("Current model doesn't support vision");
|
|
667
|
+
if (file.size > MAX_IMAGE_BYTES) throw new Error(`Image too large (${fmtBytes(file.size)} > ${fmtBytes(MAX_IMAGE_BYTES)})`);
|
|
668
|
+
const raw = await readAsDataUrl(file);
|
|
669
|
+
const data = await downscaleImage(raw, IMAGE_MAX_DIM);
|
|
670
|
+
state.pendingAttachments.push({ type: "image", mime: file.type, filename: file.name, data });
|
|
671
|
+
}
|
|
672
|
+
} else if (file.type.startsWith("audio/")) {
|
|
673
|
+
if (file.size > MAX_AUDIO_BYTES) throw new Error(`Audio too large (${fmtBytes(file.size)} > ${fmtBytes(MAX_AUDIO_BYTES)})`);
|
|
674
|
+
const data = await readAsDataUrl(file);
|
|
675
|
+
state.pendingAttachments.push({ type: "audio", mime: file.type, filename: file.name, data });
|
|
676
|
+
} else if (file.type.startsWith("video/")) {
|
|
677
|
+
if (isPegasus) {
|
|
678
|
+
// Pegasus: upload the full video file. Bedrock InvokeModel has a 25MB
|
|
679
|
+
// request limit (about 18MB binary after base64), so we cap here too.
|
|
680
|
+
const PEGASUS_MAX_VIDEO_BYTES = 18 * 1024 * 1024;
|
|
681
|
+
if (file.size > PEGASUS_MAX_VIDEO_BYTES) {
|
|
682
|
+
throw new Error(`Video too large for Pegasus (${fmtBytes(file.size)} > ${fmtBytes(PEGASUS_MAX_VIDEO_BYTES)}). Bedrock's request limit forces this. For larger videos, S3 integration would be needed.`);
|
|
683
|
+
}
|
|
684
|
+
const data = await readAsDataUrl(file);
|
|
685
|
+
state.pendingAttachments.push({ type: "video_full", mime: file.type, filename: file.name, data });
|
|
686
|
+
} else {
|
|
687
|
+
if (!modelSupports("vision")) throw new Error("Current model doesn't support vision (required for video frames)");
|
|
688
|
+
if (file.size > MAX_VIDEO_BYTES) throw new Error(`Video too large (${fmtBytes(file.size)} > ${fmtBytes(MAX_VIDEO_BYTES)})`);
|
|
689
|
+
const { frames, duration } = await extractVideoFrames(file, VIDEO_FRAMES, VIDEO_FRAME_MAX_DIM);
|
|
690
|
+
state.pendingAttachments.push({ type: "video_frames", filename: file.name, duration, frames });
|
|
691
|
+
}
|
|
692
|
+
} else if (m.type === "chat") {
|
|
693
|
+
// v0.24.0: any other file on a chat turn is treated as a text document
|
|
694
|
+
// and inlined into the prompt for analysis (yaml, json, csv, code,
|
|
695
|
+
// logs, etc.). The worker rejects it if the bytes aren't usable text.
|
|
696
|
+
if (file.size > MAX_DOC_ATTACHMENT_BYTES) {
|
|
697
|
+
throw new Error(`File too large (${fmtBytes(file.size)} > ${fmtBytes(MAX_DOC_ATTACHMENT_BYTES)})`);
|
|
698
|
+
}
|
|
699
|
+
const text = await file.text();
|
|
700
|
+
state.pendingAttachments.push({ type: "document", mime: file.type || "text/plain", filename: file.name, text });
|
|
701
|
+
} else {
|
|
702
|
+
throw new Error(`Unsupported file type: ${file.type || "(unknown)"}`);
|
|
703
|
+
}
|
|
704
|
+
} catch (err) {
|
|
705
|
+
alert(`${file.name}: ${err.message}`);
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
renderAttachments();
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
function renderAttachments() {
|
|
712
|
+
attachments.innerHTML = state.pendingAttachments
|
|
713
|
+
.map((att, idx) => renderPendingPreview(att, idx))
|
|
714
|
+
.join("");
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
function renderPendingPreview(att, idx) {
|
|
718
|
+
const remove = `<button class="remove" data-remove="${idx}" type="button" title="remove">\u00d7</button>`;
|
|
719
|
+
if (att.type === "image") {
|
|
720
|
+
return `
|
|
721
|
+
<div class="attachment">
|
|
722
|
+
<img class="thumb" src="${escapeHtml(att.data)}" alt="">
|
|
723
|
+
<div>
|
|
724
|
+
<div class="name">${escapeHtml(att.filename || "image")}</div>
|
|
725
|
+
<div class="size">${escapeHtml(att.mime || "image")}</div>
|
|
726
|
+
</div>
|
|
727
|
+
${remove}
|
|
728
|
+
</div>`;
|
|
729
|
+
}
|
|
730
|
+
if (att.type === "audio") {
|
|
731
|
+
return `
|
|
732
|
+
<div class="attachment">
|
|
733
|
+
<div class="audio-icon">\u266B</div>
|
|
734
|
+
<div>
|
|
735
|
+
<div class="name">${escapeHtml(att.filename || "audio")}</div>
|
|
736
|
+
<div class="size">will transcribe</div>
|
|
737
|
+
</div>
|
|
738
|
+
${remove}
|
|
739
|
+
</div>`;
|
|
740
|
+
}
|
|
741
|
+
if (att.type === "video_frames") {
|
|
742
|
+
const strip = (att.frames || []).slice(0, 4)
|
|
743
|
+
.map((f) => `<img src="${escapeHtml(f)}" alt="">`)
|
|
744
|
+
.join("");
|
|
745
|
+
const dur = att.duration ? `${att.duration.toFixed(1)}s` : "video";
|
|
746
|
+
return `
|
|
747
|
+
<div class="attachment">
|
|
748
|
+
<div class="video-strip">${strip}</div>
|
|
749
|
+
<div>
|
|
750
|
+
<div class="name">${escapeHtml(att.filename || "video")}</div>
|
|
751
|
+
<div class="size">${(att.frames || []).length} frames \u00b7 ${dur}</div>
|
|
752
|
+
</div>
|
|
753
|
+
${remove}
|
|
754
|
+
</div>`;
|
|
755
|
+
}
|
|
756
|
+
if (att.type === "video_full") {
|
|
757
|
+
return `
|
|
758
|
+
<div class="attachment">
|
|
759
|
+
<div class="audio-icon">\u{1F3AC}</div>
|
|
760
|
+
<div>
|
|
761
|
+
<div class="name">${escapeHtml(att.filename || "video")}</div>
|
|
762
|
+
<div class="size">full video \u00b7 ${escapeHtml(att.mime || "video")}</div>
|
|
763
|
+
</div>
|
|
764
|
+
${remove}
|
|
765
|
+
</div>`;
|
|
766
|
+
}
|
|
767
|
+
if (att.type === "document") {
|
|
768
|
+
return `
|
|
769
|
+
<div class="attachment">
|
|
770
|
+
<div class="audio-icon">\u{1F4C4}</div>
|
|
771
|
+
<div>
|
|
772
|
+
<div class="name">${escapeHtml(att.filename || "file")}</div>
|
|
773
|
+
<div class="size">${(att.text || "").length} chars \u00b7 inline text</div>
|
|
774
|
+
</div>
|
|
775
|
+
${remove}
|
|
776
|
+
</div>`;
|
|
777
|
+
}
|
|
778
|
+
return "";
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
function renderStoredAttachment(att) {
|
|
782
|
+
if (att.type === "image") {
|
|
783
|
+
return `
|
|
784
|
+
<div class="attachment">
|
|
785
|
+
<img class="thumb" src="${escapeHtml(artifactUrl(att.key))}" alt="">
|
|
786
|
+
<div>
|
|
787
|
+
<div class="name">${escapeHtml(att.filename || "image")}</div>
|
|
788
|
+
<div class="size">${escapeHtml(att.mime || "image")}</div>
|
|
789
|
+
</div>
|
|
790
|
+
</div>`;
|
|
791
|
+
}
|
|
792
|
+
if (att.type === "audio") {
|
|
793
|
+
return `
|
|
794
|
+
<div class="attachment audio-transcript">
|
|
795
|
+
<div class="audio-icon">\u266B</div>
|
|
796
|
+
<div>
|
|
797
|
+
<div class="name">${escapeHtml(att.filename || "audio")}</div>
|
|
798
|
+
<div class="size">transcript stored</div>
|
|
799
|
+
</div>
|
|
800
|
+
</div>`;
|
|
801
|
+
}
|
|
802
|
+
if (att.type === "video_frames") {
|
|
803
|
+
const keys = att.keys || [];
|
|
804
|
+
const strip = keys.slice(0, 4)
|
|
805
|
+
.map((k) => `<img src="${escapeHtml(artifactUrl(k))}" alt="">`)
|
|
806
|
+
.join("");
|
|
807
|
+
const dur = att.duration ? `${att.duration.toFixed(1)}s` : "video";
|
|
808
|
+
return `
|
|
809
|
+
<div class="attachment">
|
|
810
|
+
<div class="video-strip">${strip}</div>
|
|
811
|
+
<div>
|
|
812
|
+
<div class="name">${escapeHtml(att.filename || "video")}</div>
|
|
813
|
+
<div class="size">${keys.length} frames \u00b7 ${dur}</div>
|
|
814
|
+
</div>
|
|
815
|
+
</div>`;
|
|
816
|
+
}
|
|
817
|
+
if (att.type === "video_full") {
|
|
818
|
+
return `
|
|
819
|
+
<div class="attachment">
|
|
820
|
+
<video class="thumb" src="${escapeHtml(artifactUrl(att.key))}" controls preload="metadata"></video>
|
|
821
|
+
<div>
|
|
822
|
+
<div class="name">${escapeHtml(att.filename || "video")}</div>
|
|
823
|
+
<div class="size">full video \u00b7 ${escapeHtml(att.mime || "video")}</div>
|
|
824
|
+
</div>
|
|
825
|
+
</div>`;
|
|
826
|
+
}
|
|
827
|
+
if (att.type === "document") {
|
|
828
|
+
return `
|
|
829
|
+
<div class="attachment">
|
|
830
|
+
<div class="audio-icon">\u{1F4C4}</div>
|
|
831
|
+
<div>
|
|
832
|
+
<div class="name">${escapeHtml(att.filename || "file")}</div>
|
|
833
|
+
<div class="size">${att.chars ?? 0} chars \u00b7 inline text</div>
|
|
834
|
+
</div>
|
|
835
|
+
</div>`;
|
|
836
|
+
}
|
|
837
|
+
return "";
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
// Render an output artifact (image / audio / video) as an HTML fragment.
|
|
841
|
+
// Used inside an assistant turn block in the transcript.
|
|
842
|
+
function renderOutputArtifactHTML(oa) {
|
|
843
|
+
if (!oa) return "";
|
|
844
|
+
const url = artifactUrl(oa.key);
|
|
845
|
+
if (oa.type === "image") {
|
|
846
|
+
return `
|
|
847
|
+
<img class="output-image" src="${escapeHtml(url)}" alt="generated image">
|
|
848
|
+
<div class="output-actions"><a href="${escapeHtml(url)}" download>download</a></div>`;
|
|
849
|
+
} else if (oa.type === "audio") {
|
|
850
|
+
return `
|
|
851
|
+
<audio class="output-audio" controls src="${escapeHtml(url)}"></audio>
|
|
852
|
+
<div class="output-actions"><a href="${escapeHtml(url)}" download>download</a></div>`;
|
|
853
|
+
} else if (oa.type === "video") {
|
|
854
|
+
return `
|
|
855
|
+
<video class="output-video" controls muted preload="metadata" src="${escapeHtml(url)}"></video>
|
|
856
|
+
<div class="output-actions"><a href="${escapeHtml(url)}" download>download</a></div>`;
|
|
857
|
+
}
|
|
858
|
+
return "";
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
// Render retrieved chunks as an HTML fragment. Embedded inside a user turn
|
|
862
|
+
// when RAG and/or web search were used for that turn. Pass null/[] to get "".
|
|
863
|
+
// v0.17.0: items can be either RAG chunks (no source_type, or source_type:"rag")
|
|
864
|
+
// or web results (source_type:"web"). Renderer branches on source_type.
|
|
865
|
+
function renderRetrievedChunksHTML(chunks) {
|
|
866
|
+
if (!chunks || chunks.length === 0) return "";
|
|
867
|
+
const items = chunks
|
|
868
|
+
.map((c, i) => {
|
|
869
|
+
if (c.source_type === "web") {
|
|
870
|
+
const score = (typeof c.score === "number") ? ` \u00b7 score ${c.score.toFixed(3)}` : "";
|
|
871
|
+
const sourceLabel =
|
|
872
|
+
c.source === "searxng" ? "web" :
|
|
873
|
+
c.source === "wikipedia" ? "wikipedia" : "web";
|
|
874
|
+
return `
|
|
875
|
+
<details class="retrieved-chunk retrieved-web">
|
|
876
|
+
<summary>
|
|
877
|
+
<span class="rc-num">${i + 1}.</span>
|
|
878
|
+
<span class="rc-file">${escapeHtml(c.title || "?")}</span>
|
|
879
|
+
<span class="rc-meta">${escapeHtml(sourceLabel)}${score}</span>
|
|
880
|
+
</summary>
|
|
881
|
+
<pre class="rc-text"><a href="${escapeHtml(c.url || "#")}" target="_blank" rel="noopener noreferrer">${escapeHtml(c.url || "")}</a>
|
|
882
|
+
|
|
883
|
+
${escapeHtml(c.snippet || "")}</pre>
|
|
884
|
+
</details>`;
|
|
885
|
+
}
|
|
886
|
+
// RAG chunk (the default for missing source_type, for back-compat with
|
|
887
|
+
// rows written before v0.17.0).
|
|
888
|
+
const score = (typeof c.score === "number") ? c.score.toFixed(3) : "?";
|
|
889
|
+
const loc =
|
|
890
|
+
(c.page !== undefined && c.page !== null) ? ` \u00b7 page ${c.page}` :
|
|
891
|
+
c.sheet ? ` \u00b7 sheet "${escapeHtml(c.sheet)}"` :
|
|
892
|
+
"";
|
|
893
|
+
return `
|
|
894
|
+
<details class="retrieved-chunk">
|
|
895
|
+
<summary>
|
|
896
|
+
<span class="rc-num">${i + 1}.</span>
|
|
897
|
+
<span class="rc-file">${escapeHtml(c.filename || "?")}</span>
|
|
898
|
+
<span class="rc-meta">chunk ${c.chunk_index}${loc} \u00b7 score ${score}</span>
|
|
899
|
+
</summary>
|
|
900
|
+
<pre class="rc-text">${escapeHtml(c.text || "")}</pre>
|
|
901
|
+
</details>`;
|
|
902
|
+
})
|
|
903
|
+
.join("");
|
|
904
|
+
// Mixed-source label: when both RAG and web are present, count each.
|
|
905
|
+
const ragCount = chunks.filter((c) => c.source_type !== "web").length;
|
|
906
|
+
const webCount = chunks.filter((c) => c.source_type === "web").length;
|
|
907
|
+
let label;
|
|
908
|
+
if (ragCount && webCount) {
|
|
909
|
+
label = `retrieved context (${ragCount} doc${ragCount === 1 ? "" : "s"} + ${webCount} web)`;
|
|
910
|
+
} else if (webCount) {
|
|
911
|
+
label = `retrieved context (${webCount} web result${webCount === 1 ? "" : "s"})`;
|
|
912
|
+
} else {
|
|
913
|
+
label = `retrieved context (${ragCount} chunk${ragCount === 1 ? "" : "s"})`;
|
|
914
|
+
}
|
|
915
|
+
return `
|
|
916
|
+
<div class="retrieved-chunks">
|
|
917
|
+
<div class="rc-header">${escapeHtml(label)}</div>
|
|
918
|
+
${items}
|
|
919
|
+
</div>`;
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
function renderStoredAttachmentsHTML(atts) {
|
|
923
|
+
if (!atts || atts.length === 0) return "";
|
|
924
|
+
return `<div class="loaded-attachments">${atts.map(renderStoredAttachment).join("")}</div>`;
|
|
925
|
+
}
|
|
926
|
+
|
|
927
|
+
// ---------- Video job polling ----------
|
|
928
|
+
//
|
|
929
|
+
// When the worker returns status: "pending" from /api/chat (video models),
|
|
930
|
+
// we poll /api/job/:id every 5s until status is "done" or "failed".
|
|
931
|
+
// The pendingArea displays elapsed time and progress while polling.
|
|
932
|
+
|
|
933
|
+
function fmtElapsed(ms) {
|
|
934
|
+
const total = Math.floor(ms / 1000);
|
|
935
|
+
const min = Math.floor(total / 60);
|
|
936
|
+
const sec = total % 60;
|
|
937
|
+
return min > 0 ? `${min}m ${sec}s` : `${sec}s`;
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
// While an async job is running, update the last assistant turn in place
|
|
941
|
+
// to show elapsed time. The turn's status stays "pending" until the poll
|
|
942
|
+
// resolves with done or failed.
|
|
943
|
+
function renderPendingOutput(progress) {
|
|
944
|
+
const elapsed = fmtElapsed(Date.now() - state.pollStartedAt);
|
|
945
|
+
const pct = (typeof progress === "number" && progress > 0) ? ` (${progress}%)` : "";
|
|
946
|
+
const last = state.currentTurns[state.currentTurns.length - 1];
|
|
947
|
+
if (last && last.status === "pending") {
|
|
948
|
+
last.output = `Generating, this can take 1-3 minutes\u2026\n\nElapsed: ${elapsed}${pct}`;
|
|
949
|
+
renderTranscript(state.currentTurns);
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
function stopPolling() {
|
|
954
|
+
if (state.pollTimer) { clearTimeout(state.pollTimer); state.pollTimer = null; }
|
|
955
|
+
if (state.pollElapsedTimer) { clearInterval(state.pollElapsedTimer); state.pollElapsedTimer = null; }
|
|
956
|
+
state.pollChatId = null;
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
async function pollOnce() {
|
|
960
|
+
if (!state.pollChatId) return;
|
|
961
|
+
const id = state.pollChatId;
|
|
962
|
+
try {
|
|
963
|
+
const result = await api(`/api/job/${id}`);
|
|
964
|
+
// If the user navigated away during the request, drop the result.
|
|
965
|
+
if (state.pollChatId !== id) return;
|
|
966
|
+
|
|
967
|
+
if (result.status === "pending") {
|
|
968
|
+
renderPendingOutput(result.progress);
|
|
969
|
+
state.pollTimer = setTimeout(pollOnce, 5000);
|
|
970
|
+
return;
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
if (result.status === "done") {
|
|
974
|
+
stopPolling();
|
|
975
|
+
// Refetch the full conversation for the canonical resolved state.
|
|
976
|
+
if (state.currentConversationId) await loadConversation(state.currentConversationId);
|
|
977
|
+
await loadConversations();
|
|
978
|
+
return;
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
if (result.status === "failed") {
|
|
982
|
+
stopPolling();
|
|
983
|
+
// Update the last turn in place to a failed state.
|
|
984
|
+
const last = state.currentTurns[state.currentTurns.length - 1];
|
|
985
|
+
if (last) {
|
|
986
|
+
last.status = "failed";
|
|
987
|
+
last.job_error = result.job_error || "unknown error";
|
|
988
|
+
renderTranscript(state.currentTurns);
|
|
989
|
+
}
|
|
990
|
+
await loadConversations();
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
} catch (err) {
|
|
994
|
+
// Transient network error; keep polling.
|
|
995
|
+
state.pollTimer = setTimeout(pollOnce, 5000);
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
function startPolling(id, startedAtIso) {
|
|
1000
|
+
stopPolling();
|
|
1001
|
+
state.pollChatId = id;
|
|
1002
|
+
state.pollStartedAt = startedAtIso ? Date.parse(startedAtIso) : Date.now();
|
|
1003
|
+
renderPendingOutput();
|
|
1004
|
+
// Tick the elapsed-time display every second so the user sees progress
|
|
1005
|
+
// even between 5s polls.
|
|
1006
|
+
state.pollElapsedTimer = setInterval(() => renderPendingOutput(), 1000);
|
|
1007
|
+
// First poll immediately, then every 5s on success.
|
|
1008
|
+
state.pollTimer = setTimeout(pollOnce, 500);
|
|
1009
|
+
}
|
|
1010
|
+
|
|
1011
|
+
attachments.addEventListener("click", (e) => {
|
|
1012
|
+
const rm = e.target.closest("[data-remove]");
|
|
1013
|
+
if (rm) {
|
|
1014
|
+
const idx = Number(rm.dataset.remove);
|
|
1015
|
+
state.pendingAttachments.splice(idx, 1);
|
|
1016
|
+
renderAttachments();
|
|
1017
|
+
}
|
|
1018
|
+
});
|
|
1019
|
+
|
|
1020
|
+
attachBtn.addEventListener("click", () => fileInput.click());
|
|
1021
|
+
fileInput.addEventListener("change", async (e) => {
|
|
1022
|
+
await handleFiles(Array.from(e.target.files || []));
|
|
1023
|
+
fileInput.value = "";
|
|
1024
|
+
});
|
|
1025
|
+
|
|
1026
|
+
// ---------- Drag-and-drop + paste (v0.19.5) ----------
|
|
1027
|
+
//
|
|
1028
|
+
// Drag files onto the input area or paste an image from the clipboard
|
|
1029
|
+
// (Cmd/Ctrl-V). Both paths funnel into handleFiles(), which already owns
|
|
1030
|
+
// validation, size limits, image downscaling, video frame extraction,
|
|
1031
|
+
// Pegasus full-video routing, and FLUX-2 reference image caps. So
|
|
1032
|
+
// drag-drop and paste inherit all those behaviors without duplicating
|
|
1033
|
+
// any of the logic.
|
|
1034
|
+
//
|
|
1035
|
+
// dragenter/dragleave fire for every child element under the cursor, not
|
|
1036
|
+
// just the outer container. We use a counter to keep the visual state
|
|
1037
|
+
// stable across child-element traversal (textarea, attach button, etc.).
|
|
1038
|
+
|
|
1039
|
+
let dragCounter = 0;
|
|
1040
|
+
|
|
1041
|
+
// The drop zone is only active when the current model supports attachments
|
|
1042
|
+
// (attach button is shown). This mirrors the click-to-attach affordance:
|
|
1043
|
+
// drop targeting for TTS / video gen / music gen would just throw a
|
|
1044
|
+
// silent no-op, so we don't show the affordance.
|
|
1045
|
+
function dropZoneActive() {
|
|
1046
|
+
return attachRow.style.display !== "none";
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
inputArea.addEventListener("dragenter", (e) => {
|
|
1050
|
+
if (!dropZoneActive()) return;
|
|
1051
|
+
// Only handle drags that include files. dataTransfer.types includes
|
|
1052
|
+
// "Files" when the dragged data is files (vs. text selection from a page).
|
|
1053
|
+
if (!e.dataTransfer.types.includes("Files")) return;
|
|
1054
|
+
e.preventDefault();
|
|
1055
|
+
dragCounter++;
|
|
1056
|
+
inputArea.classList.add("drop-active");
|
|
1057
|
+
});
|
|
1058
|
+
|
|
1059
|
+
inputArea.addEventListener("dragover", (e) => {
|
|
1060
|
+
if (!dropZoneActive()) return;
|
|
1061
|
+
if (!e.dataTransfer.types.includes("Files")) return;
|
|
1062
|
+
// preventDefault on dragover is required to tell the browser this
|
|
1063
|
+
// element is a valid drop target.
|
|
1064
|
+
e.preventDefault();
|
|
1065
|
+
e.dataTransfer.dropEffect = "copy";
|
|
1066
|
+
});
|
|
1067
|
+
|
|
1068
|
+
inputArea.addEventListener("dragleave", () => {
|
|
1069
|
+
if (!dropZoneActive()) return;
|
|
1070
|
+
dragCounter = Math.max(0, dragCounter - 1);
|
|
1071
|
+
if (dragCounter === 0) inputArea.classList.remove("drop-active");
|
|
1072
|
+
});
|
|
1073
|
+
|
|
1074
|
+
inputArea.addEventListener("drop", async (e) => {
|
|
1075
|
+
if (!dropZoneActive()) return;
|
|
1076
|
+
e.preventDefault();
|
|
1077
|
+
dragCounter = 0;
|
|
1078
|
+
inputArea.classList.remove("drop-active");
|
|
1079
|
+
const files = Array.from(e.dataTransfer.files || []);
|
|
1080
|
+
if (files.length) await handleFiles(files);
|
|
1081
|
+
});
|
|
1082
|
+
|
|
1083
|
+
// Paste handler on the textarea: clipboard images (most common case:
|
|
1084
|
+
// Cmd/Ctrl-Shift-4 screenshots, "Copy image" from a browser) become
|
|
1085
|
+
// attachments. Pure-text pastes pass through to the textarea normally.
|
|
1086
|
+
userInput.addEventListener("paste", async (e) => {
|
|
1087
|
+
if (!dropZoneActive()) return;
|
|
1088
|
+
const items = Array.from(e.clipboardData?.items || []);
|
|
1089
|
+
const files = [];
|
|
1090
|
+
for (const item of items) {
|
|
1091
|
+
if (item.kind === "file") {
|
|
1092
|
+
const f = item.getAsFile();
|
|
1093
|
+
if (f) files.push(f);
|
|
1094
|
+
}
|
|
1095
|
+
}
|
|
1096
|
+
if (files.length === 0) return; // pure text paste; fall through to default behavior
|
|
1097
|
+
e.preventDefault(); // suppress default paste so filename text doesn't land in the textarea
|
|
1098
|
+
await handleFiles(files);
|
|
1099
|
+
});
|
|
1100
|
+
|
|
1101
|
+
modelSelect.addEventListener("change", updateAffordance);
|
|
1102
|
+
|
|
1103
|
+
// ---------- Conversations ----------
|
|
1104
|
+
|
|
1105
|
+
async function loadConversations() {
|
|
1106
|
+
const { conversations } = await api("/api/conversations");
|
|
1107
|
+
historyList.innerHTML = (conversations || [])
|
|
1108
|
+
.map((c) => {
|
|
1109
|
+
const preview = (c.first_input || "").slice(0, 60).replace(/\s+/g, " ");
|
|
1110
|
+
const date = new Date((c.last_created_at || "").includes("Z") ? c.last_created_at : c.last_created_at + "Z");
|
|
1111
|
+
const dateStr = date.toLocaleString(undefined, {
|
|
1112
|
+
month: "numeric", day: "numeric", hour: "numeric", minute: "2-digit",
|
|
1113
|
+
});
|
|
1114
|
+
|
|
1115
|
+
// Icons summarize the conversation: model type, turn count, artifacts.
|
|
1116
|
+
const icons = [];
|
|
1117
|
+
if (c.first_model_type === "image") icons.push(`<span title="image gen">\u{1F5BC}</span>`);
|
|
1118
|
+
else if (c.first_model_type === "tts") icons.push(`<span title="TTS">\u{1F50A}</span>`);
|
|
1119
|
+
else if (c.first_model_type === "video") icons.push(`<span title="video gen">\u{1F3AC}</span>`);
|
|
1120
|
+
else if (c.first_model_type === "music") icons.push(`<span title="music gen">\u{1F3B5}</span>`);
|
|
1121
|
+
else if (c.first_model_type === "stt") icons.push(`<span title="transcript">\u{1F4DD}</span>`);
|
|
1122
|
+
else if (c.first_model_type === "voice") icons.push(`<span title="voice session">\u{1F399}</span>`);
|
|
1123
|
+
if (c.turn_count > 1) icons.push(`<span class="turn-count" title="${c.turn_count} turns">${c.turn_count}\u00b7</span>`);
|
|
1124
|
+
const iconBlock = icons.length ? `<span class="attach-icon">${icons.join(" ")}</span>` : `<span></span>`;
|
|
1125
|
+
|
|
1126
|
+
// v0.20.2: project chip on conversation rows. Shows the project name
|
|
1127
|
+
// when the conversation has been assigned (or auto-tagged on creation).
|
|
1128
|
+
// Resolves project_id -> name via state.projects so we don't need an
|
|
1129
|
+
// extra API call per row. Stale ids (project deleted) render as a
|
|
1130
|
+
// muted placeholder rather than blowing up.
|
|
1131
|
+
let projChip = "";
|
|
1132
|
+
if (c.project_id) {
|
|
1133
|
+
const p = state.projects.find((x) => x.id === c.project_id);
|
|
1134
|
+
if (p) {
|
|
1135
|
+
projChip = `<span class="conv-proj-chip" title="project: ${escapeHtml(p.name)}">${escapeHtml(p.name)}</span>`;
|
|
1136
|
+
} else {
|
|
1137
|
+
projChip = `<span class="conv-proj-chip conv-proj-chip-stale" title="project (deleted)">project</span>`;
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
return `
|
|
1142
|
+
<li data-conv-id="${escapeHtml(c.conversation_id)}">
|
|
1143
|
+
<span class="preview" title="${escapeHtml(c.first_input || "")}">${escapeHtml(preview)}</span>
|
|
1144
|
+
${projChip}
|
|
1145
|
+
${iconBlock}
|
|
1146
|
+
<span class="meta">${dateStr}</span>
|
|
1147
|
+
<button class="conv-move" data-conv-move="${escapeHtml(c.conversation_id)}" type="button" title="move to project">\u2197</button>
|
|
1148
|
+
<button class="delete" data-conv-delete="${escapeHtml(c.conversation_id)}" type="button" title="delete conversation">\u00d7</button>
|
|
1149
|
+
</li>`;
|
|
1150
|
+
})
|
|
1151
|
+
.join("");
|
|
1152
|
+
filterHistory(); // re-apply an active history-search query after re-render
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
async function loadConversation(id) {
|
|
1156
|
+
stopPolling();
|
|
1157
|
+
const { turns } = await api(`/api/conversations/${encodeURIComponent(id)}`);
|
|
1158
|
+
state.currentConversationId = id;
|
|
1159
|
+
state.currentTurns = turns || [];
|
|
1160
|
+
|
|
1161
|
+
// Set the model picker to the most-recent turn's model so the user can
|
|
1162
|
+
// continue with the same model by default (they can switch before submitting).
|
|
1163
|
+
if (state.currentTurns.length) {
|
|
1164
|
+
const lastTurn = state.currentTurns[state.currentTurns.length - 1];
|
|
1165
|
+
if (state.modelsById[lastTurn.model]) {
|
|
1166
|
+
modelSelect.value = lastTurn.model;
|
|
1167
|
+
updateAffordance();
|
|
1168
|
+
}
|
|
1169
|
+
// Populate system_prompt from the first turn (it's typically conversation-wide intent).
|
|
1170
|
+
systemPrompt.value = state.currentTurns[0].system_prompt || "";
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
renderTranscript(state.currentTurns);
|
|
1174
|
+
updateConvTitle();
|
|
1175
|
+
|
|
1176
|
+
// If the latest turn is still pending (async video/music job), resume polling.
|
|
1177
|
+
const last = state.currentTurns[state.currentTurns.length - 1];
|
|
1178
|
+
if (last && last.status === "pending" && (last.model_type === "video" || last.model_type === "music")) {
|
|
1179
|
+
startPolling(last.id, last.job_started_at);
|
|
1180
|
+
}
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
async function deleteConversation(id) {
|
|
1184
|
+
await api(`/api/conversations/${encodeURIComponent(id)}`, { method: "DELETE" });
|
|
1185
|
+
if (state.currentConversationId === id) newChat();
|
|
1186
|
+
await loadConversations();
|
|
1187
|
+
}
|
|
1188
|
+
|
|
1189
|
+
function newChat() {
|
|
1190
|
+
stopPolling();
|
|
1191
|
+
state.currentConversationId = null;
|
|
1192
|
+
state.currentTurns = [];
|
|
1193
|
+
userInput.value = "";
|
|
1194
|
+
autoGrowUserInput();
|
|
1195
|
+
state.pendingAttachments = [];
|
|
1196
|
+
renderAttachments();
|
|
1197
|
+
renderTranscript([]);
|
|
1198
|
+
outputMeta.textContent = "";
|
|
1199
|
+
updateConvTitle();
|
|
1200
|
+
userInput.focus();
|
|
1201
|
+
}
|
|
1202
|
+
|
|
1203
|
+
function updateConvTitle() {
|
|
1204
|
+
if (!state.currentConversationId || state.currentTurns.length === 0) {
|
|
1205
|
+
convTitleEl.textContent = "new conversation";
|
|
1206
|
+
} else {
|
|
1207
|
+
const first = state.currentTurns[0]?.user_input || "";
|
|
1208
|
+
const preview = first.slice(0, 60).replace(/\s+/g, " ");
|
|
1209
|
+
const n = state.currentTurns.length;
|
|
1210
|
+
convTitleEl.textContent = `${preview || "conversation"} \u00b7 ${n} turn${n === 1 ? "" : "s"}`;
|
|
1211
|
+
}
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
// ---------- Transcript rendering ----------
|
|
1215
|
+
|
|
1216
|
+
function renderTranscript(turns) {
|
|
1217
|
+
if (!turns || turns.length === 0) {
|
|
1218
|
+
transcriptEl.innerHTML = "";
|
|
1219
|
+
transcriptEl.classList.add("empty");
|
|
1220
|
+
return;
|
|
1221
|
+
}
|
|
1222
|
+
transcriptEl.classList.remove("empty");
|
|
1223
|
+
transcriptEl.innerHTML = turns.map((t, i) => renderTurnHTML(t, i)).join("");
|
|
1224
|
+
transcriptEl.scrollTop = transcriptEl.scrollHeight;
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
function renderTurnHTML(turn, index) {
|
|
1228
|
+
// User side: prompt + attachments + retrieved chunks (if RAG was used this turn)
|
|
1229
|
+
const userBlock = `
|
|
1230
|
+
<div class="turn turn-user" data-turn="${index}">
|
|
1231
|
+
<div class="turn-role">you</div>
|
|
1232
|
+
<div class="turn-body">
|
|
1233
|
+
<div class="turn-text">${escapeHtml(turn.user_input || "")}</div>
|
|
1234
|
+
${renderStoredAttachmentsHTML(turn.attachments)}
|
|
1235
|
+
${renderRetrievedChunksHTML(turn.retrieved_context)}
|
|
1236
|
+
</div>
|
|
1237
|
+
</div>`;
|
|
1238
|
+
|
|
1239
|
+
// Assistant side: output text (chat/stt) and/or output artifact (image/audio/video/music)
|
|
1240
|
+
const isPending = turn.status === "pending";
|
|
1241
|
+
const isFailed = turn.status === "failed";
|
|
1242
|
+
let assistantContent = "";
|
|
1243
|
+
if (isPending) {
|
|
1244
|
+
assistantContent = `<div class="turn-text pending">generating\u2026</div>`;
|
|
1245
|
+
} else if (isFailed) {
|
|
1246
|
+
assistantContent = `<div class="turn-text error">failed: ${escapeHtml(turn.job_error || "unknown error")}</div>`;
|
|
1247
|
+
} else {
|
|
1248
|
+
if (turn.output) assistantContent += `<div class="turn-text">${escapeHtml(turn.output)}</div>`;
|
|
1249
|
+
if (turn.output_artifact) assistantContent += `<div class="turn-artifact">${renderOutputArtifactHTML(turn.output_artifact)}</div>`;
|
|
1250
|
+
}
|
|
1251
|
+
|
|
1252
|
+
// Per-turn action buttons (v0.12.0+):
|
|
1253
|
+
// - Copy: shown when there is output text to copy. Pure-artifact turns
|
|
1254
|
+
// (image/audio/video without a text output) hide it.
|
|
1255
|
+
// - Edit: populates the input textarea with this turn's user_input (and
|
|
1256
|
+
// switches the model picker and system prompt to match) so the user
|
|
1257
|
+
// can tweak before re-running. Does NOT submit.
|
|
1258
|
+
// - Retry: one-click resubmit. Switches model picker, system prompt,
|
|
1259
|
+
// and input to match this turn, then fires run() immediately.
|
|
1260
|
+
// Buttons are hidden while a turn is pending.
|
|
1261
|
+
let actionsBlock = "";
|
|
1262
|
+
if (!isPending) {
|
|
1263
|
+
const buttons = [];
|
|
1264
|
+
if (turn.output) {
|
|
1265
|
+
buttons.push(`<button class="turn-action" data-action="copy" data-turn="${index}" type="button" aria-label="Copy response" title="Copy">${ICON_COPY}</button>`);
|
|
1266
|
+
}
|
|
1267
|
+
if (turn.user_input) {
|
|
1268
|
+
buttons.push(`<button class="turn-action" data-action="edit" data-turn="${index}" type="button" aria-label="Edit this prompt and rerun" title="Edit">${ICON_EDIT}</button>`);
|
|
1269
|
+
buttons.push(`<button class="turn-action" data-action="retry" data-turn="${index}" type="button" aria-label="Retry: resubmit this prompt unchanged" title="Retry">${ICON_RETRY}</button>`);
|
|
1270
|
+
}
|
|
1271
|
+
if (buttons.length) {
|
|
1272
|
+
actionsBlock = `<div class="turn-actions">${buttons.join("")}</div>`;
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
const assistantBlock = `
|
|
1277
|
+
<div class="turn turn-assistant" data-turn="${index}">
|
|
1278
|
+
<div class="turn-role">${escapeHtml(turn.model || "?")}</div>
|
|
1279
|
+
<div class="turn-body">
|
|
1280
|
+
${assistantContent}
|
|
1281
|
+
${actionsBlock}
|
|
1282
|
+
<div class="turn-meta">${escapeHtml(fmtMeta(turn) || "")}</div>
|
|
1283
|
+
</div>
|
|
1284
|
+
</div>`;
|
|
1285
|
+
|
|
1286
|
+
return userBlock + assistantBlock;
|
|
1287
|
+
}
|
|
1288
|
+
|
|
1289
|
+
// ---------- Run ----------
|
|
1290
|
+
|
|
1291
|
+
async function run() {
|
|
1292
|
+
const m = currentModel();
|
|
1293
|
+
const model = modelSelect.value;
|
|
1294
|
+
const system_prompt = systemPrompt.value;
|
|
1295
|
+
const user_input = userInput.value.trim();
|
|
1296
|
+
if (!user_input && state.pendingAttachments.length === 0) return;
|
|
1297
|
+
|
|
1298
|
+
stopPolling();
|
|
1299
|
+
runBtn.disabled = true;
|
|
1300
|
+
attachBtn.disabled = true;
|
|
1301
|
+
|
|
1302
|
+
// Optimistic: append a user turn + a placeholder assistant turn to the
|
|
1303
|
+
// transcript immediately so the UI feels responsive. After the response
|
|
1304
|
+
// comes back we refetch the full conversation to get the canonical state.
|
|
1305
|
+
const placeholderText =
|
|
1306
|
+
m.type === "chat" ? "\u2026"
|
|
1307
|
+
: m.type === "video" ? "submitting video job\u2026"
|
|
1308
|
+
: m.type === "music" ? "submitting music job\u2026"
|
|
1309
|
+
: m.type === "stt" ? "transcribing\u2026"
|
|
1310
|
+
: `running ${m.type}\u2026`;
|
|
1311
|
+
|
|
1312
|
+
// Snapshot pending attachments for the optimistic user turn (re-render
|
|
1313
|
+
// after success uses persisted server data).
|
|
1314
|
+
const optimisticAttachments = (m.type === "chat" || m.type === "stt")
|
|
1315
|
+
? state.pendingAttachments.map((a) => ({
|
|
1316
|
+
type: a.type,
|
|
1317
|
+
filename: a.filename,
|
|
1318
|
+
mime: a.mime,
|
|
1319
|
+
transcript: null,
|
|
1320
|
+
}))
|
|
1321
|
+
: [];
|
|
1322
|
+
const optimisticUserTurn = {
|
|
1323
|
+
user_input: user_input || "(no text, attachments only)",
|
|
1324
|
+
attachments: optimisticAttachments,
|
|
1325
|
+
retrieved_context: null,
|
|
1326
|
+
};
|
|
1327
|
+
const optimisticAssistantTurn = {
|
|
1328
|
+
model, model_type: m.type, output: "",
|
|
1329
|
+
status: "pending",
|
|
1330
|
+
output_artifact: null,
|
|
1331
|
+
};
|
|
1332
|
+
state.currentTurns.push(optimisticUserTurn, optimisticAssistantTurn);
|
|
1333
|
+
renderTranscript(state.currentTurns);
|
|
1334
|
+
outputMeta.textContent = "";
|
|
1335
|
+
|
|
1336
|
+
try {
|
|
1337
|
+
const requestBody = {
|
|
1338
|
+
model,
|
|
1339
|
+
system_prompt,
|
|
1340
|
+
user_input: user_input || "(no text, attachments only)",
|
|
1341
|
+
attachments: (m.type === "chat" || m.type === "stt" || (m.type === "image" && isFlux2Model(m)) || (m.type === "video" && (m.capabilities || []).includes("image-input"))) ? state.pendingAttachments : [],
|
|
1342
|
+
conversation_id: state.currentConversationId || undefined,
|
|
1343
|
+
};
|
|
1344
|
+
// RAG: only send the flag for chat models when the user has it toggled on
|
|
1345
|
+
// AND has documents to retrieve from.
|
|
1346
|
+
if (m.type === "chat" && useDocsCheckbox.checked && state.documentCount > 0) {
|
|
1347
|
+
requestBody.use_docs = true;
|
|
1348
|
+
}
|
|
1349
|
+
// v0.17.0: web search. Chat models only; SearXNG + Wikipedia when toggled (v0.166.0).
|
|
1350
|
+
if (m.type === "chat" && useWebSearchCheckbox.checked) {
|
|
1351
|
+
requestBody.use_web_search = true;
|
|
1352
|
+
}
|
|
1353
|
+
// v0.20.1: project scoping. Chat models only. When a project is active,
|
|
1354
|
+
// include its id; the worker applies the project's system_prompt as
|
|
1355
|
+
// default (overridden by a per-turn system_prompt) and scopes RAG
|
|
1356
|
+
// retrieval to the project's attached documents.
|
|
1357
|
+
if (m.type === "chat" && state.activeProjectId) {
|
|
1358
|
+
requestBody.project_id = state.activeProjectId;
|
|
1359
|
+
}
|
|
1360
|
+
// v0.21.7: cross-model artifact reuse. Make the most recent image generated
|
|
1361
|
+
// earlier in THIS conversation available to whatever model you switched to,
|
|
1362
|
+
// by R2 reference (no download/re-upload), unless the user attached their
|
|
1363
|
+
// own image. i2v takes it via image_key (its param path differs); vision
|
|
1364
|
+
// chat and FLUX.2 reference take it as an image attachment-by-key, which
|
|
1365
|
+
// the worker hydrates at the request boundary.
|
|
1366
|
+
{
|
|
1367
|
+
const userHasImage = state.pendingAttachments.some((a) => a.type === "image");
|
|
1368
|
+
if (modelConsumesImage(m) && !userHasImage) {
|
|
1369
|
+
const priorImageKey = latestArtifactKey("image");
|
|
1370
|
+
if (priorImageKey) {
|
|
1371
|
+
if ((m.capabilities || []).includes("image-input")) {
|
|
1372
|
+
requestBody.image_key = priorImageKey;
|
|
1373
|
+
} else {
|
|
1374
|
+
requestBody.attachments = [
|
|
1375
|
+
...(requestBody.attachments || []),
|
|
1376
|
+
{ type: "image", key: priorImageKey },
|
|
1377
|
+
];
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
|
|
1383
|
+
const result = await api("/api/chat", {
|
|
1384
|
+
method: "POST",
|
|
1385
|
+
body: JSON.stringify(requestBody),
|
|
1386
|
+
});
|
|
1387
|
+
|
|
1388
|
+
// Pop the optimistic pair we appended above.
|
|
1389
|
+
state.currentTurns.pop();
|
|
1390
|
+
state.currentTurns.pop();
|
|
1391
|
+
|
|
1392
|
+
// Update conversation id from the response (may have been server-generated).
|
|
1393
|
+
state.currentConversationId = result.conversation_id;
|
|
1394
|
+
state.pendingAttachments = [];
|
|
1395
|
+
renderAttachments();
|
|
1396
|
+
|
|
1397
|
+
// Clear the input so the next prompt can be typed immediately.
|
|
1398
|
+
// The system prompt stays.
|
|
1399
|
+
userInput.value = "";
|
|
1400
|
+
autoGrowUserInput();
|
|
1401
|
+
userInput.focus();
|
|
1402
|
+
|
|
1403
|
+
// Refetch the full conversation from the server for canonical state
|
|
1404
|
+
// (correct attachment records, retrieved_context, etc).
|
|
1405
|
+
await loadConversation(state.currentConversationId);
|
|
1406
|
+
await loadConversations();
|
|
1407
|
+
|
|
1408
|
+
// If the assistant turn is pending (async video/music job), start polling.
|
|
1409
|
+
const last = state.currentTurns[state.currentTurns.length - 1];
|
|
1410
|
+
if (last && last.status === "pending" && (last.model_type === "video" || last.model_type === "music")) {
|
|
1411
|
+
startPolling(last.id, last.job_started_at);
|
|
1412
|
+
}
|
|
1413
|
+
} catch (err) {
|
|
1414
|
+
// Roll back optimistic turns; surface the error in a fresh assistant turn.
|
|
1415
|
+
state.currentTurns.pop();
|
|
1416
|
+
state.currentTurns.pop();
|
|
1417
|
+
state.currentTurns.push(optimisticUserTurn, {
|
|
1418
|
+
model, model_type: m.type, output: "",
|
|
1419
|
+
status: "failed",
|
|
1420
|
+
job_error: err.message,
|
|
1421
|
+
});
|
|
1422
|
+
renderTranscript(state.currentTurns);
|
|
1423
|
+
// #80 fail-closed BYOK gate: a 412 means no AI Gateway is configured (or the
|
|
1424
|
+
// Unified Billing token is missing). Route the user straight into the
|
|
1425
|
+
// gateway modal so the fix is one screen away, not a dead-end error. The
|
|
1426
|
+
// failed turn still shows the server message (which names Account > AI
|
|
1427
|
+
// Gateway). Match on the status; the worker also sends a code field.
|
|
1428
|
+
if (err.status === 412) {
|
|
1429
|
+
openGatewayModal();
|
|
1430
|
+
}
|
|
1431
|
+
} finally {
|
|
1432
|
+
runBtn.disabled = false;
|
|
1433
|
+
attachBtn.disabled = false;
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
|
|
1437
|
+
// ---------- Voice chat (v0.118.0): talk to any chat model, hear the reply ----
|
|
1438
|
+
//
|
|
1439
|
+
// Hands-free loop: mic -> STT (flux, via createMicStreamer) -> on each finished
|
|
1440
|
+
// turn (EndOfTurn) send the utterance to the selected chat model through the
|
|
1441
|
+
// normal run() path, then speak the reply via /api/tts (Aura-2). The mic is
|
|
1442
|
+
// muted while the model is thinking/speaking so it doesn't transcribe the
|
|
1443
|
+
// assistant's own voice. Works with whatever chat model is selected.
|
|
1444
|
+
const vc = { active: false, streamer: null, busy: false, player: null };
|
|
1445
|
+
|
|
1446
|
+
function setVoiceStatus(text) {
|
|
1447
|
+
if (voiceChatStatus) voiceChatStatus.textContent = text || "";
|
|
1448
|
+
}
|
|
1449
|
+
|
|
1450
|
+
function updateVoiceButton() {
|
|
1451
|
+
if (!voiceChatToggle) return;
|
|
1452
|
+
voiceChatToggle.classList.toggle("is-live", vc.active);
|
|
1453
|
+
voiceChatToggle.title = vc.active
|
|
1454
|
+
? "stop voice chat"
|
|
1455
|
+
: "voice chat (talk to the model, hear it reply)";
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
function startVoiceChat() {
|
|
1459
|
+
if (vc.active) return;
|
|
1460
|
+
const m = currentModel();
|
|
1461
|
+
if (!m || m.type !== "chat") return;
|
|
1462
|
+
if (typeof window.createMicStreamer !== "function") return;
|
|
1463
|
+
vc.active = true;
|
|
1464
|
+
updateVoiceButton();
|
|
1465
|
+
setVoiceStatus("\u{1F3A4} starting…");
|
|
1466
|
+
vc.streamer = window.createMicStreamer({
|
|
1467
|
+
onStatus: (s) => { if (!vc.busy) setVoiceStatus(s === "listening" ? "\u{1F3A4} listening… speak" : "\u{1F3A4} " + s); },
|
|
1468
|
+
onClose: () => stopVoiceChat(),
|
|
1469
|
+
onEvent: (ev) => {
|
|
1470
|
+
const type = window.fluxEventName(ev);
|
|
1471
|
+
if (type !== "EndOfTurn" || vc.busy) return;
|
|
1472
|
+
const text = (typeof ev.transcript === "string" ? ev.transcript : "").trim();
|
|
1473
|
+
if (text) handleUtterance(text);
|
|
1474
|
+
},
|
|
1475
|
+
});
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
function stopVoiceChat() {
|
|
1479
|
+
vc.active = false;
|
|
1480
|
+
if (vc.streamer) { vc.streamer.stop(); vc.streamer = null; }
|
|
1481
|
+
if (vc.player) { try { vc.player.pause(); } catch (_) {} vc.player = null; }
|
|
1482
|
+
vc.busy = false;
|
|
1483
|
+
updateVoiceButton();
|
|
1484
|
+
setVoiceStatus("");
|
|
1485
|
+
}
|
|
1486
|
+
|
|
1487
|
+
async function handleUtterance(text) {
|
|
1488
|
+
vc.busy = true;
|
|
1489
|
+
if (vc.streamer) vc.streamer.setMuted(true); // don't transcribe the spoken reply
|
|
1490
|
+
setVoiceStatus("\u{1F4AD} thinking…");
|
|
1491
|
+
try {
|
|
1492
|
+
userInput.value = text;
|
|
1493
|
+
autoGrowUserInput();
|
|
1494
|
+
await run();
|
|
1495
|
+
const last = state.currentTurns[state.currentTurns.length - 1];
|
|
1496
|
+
const reply = last && typeof last.output === "string" ? last.output.trim() : "";
|
|
1497
|
+
if (reply && vc.active) await speak(reply);
|
|
1498
|
+
} catch (_) {
|
|
1499
|
+
// run() surfaces its own errors in the transcript; just resume listening.
|
|
1500
|
+
} finally {
|
|
1501
|
+
vc.busy = false;
|
|
1502
|
+
if (vc.active && vc.streamer) {
|
|
1503
|
+
vc.streamer.setMuted(false);
|
|
1504
|
+
setVoiceStatus("\u{1F3A4} listening… speak");
|
|
1505
|
+
}
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
|
|
1509
|
+
async function speak(text) {
|
|
1510
|
+
setVoiceStatus("\u{1F50A} speaking…");
|
|
1511
|
+
let url = null;
|
|
1512
|
+
try {
|
|
1513
|
+
const resp = await fetch("/api/tts", {
|
|
1514
|
+
method: "POST",
|
|
1515
|
+
headers: { "content-type": "application/json" },
|
|
1516
|
+
body: JSON.stringify({ text }),
|
|
1517
|
+
});
|
|
1518
|
+
if (!resp.ok) return;
|
|
1519
|
+
const blob = await resp.blob();
|
|
1520
|
+
url = URL.createObjectURL(blob);
|
|
1521
|
+
vc.player = new Audio(url);
|
|
1522
|
+
await new Promise((res) => {
|
|
1523
|
+
vc.player.onended = res;
|
|
1524
|
+
vc.player.onerror = res;
|
|
1525
|
+
vc.player.play().catch(res);
|
|
1526
|
+
});
|
|
1527
|
+
} catch (_) {
|
|
1528
|
+
/* TTS failed; skip speaking but keep the conversation going */
|
|
1529
|
+
} finally {
|
|
1530
|
+
if (url) URL.revokeObjectURL(url);
|
|
1531
|
+
vc.player = null;
|
|
1532
|
+
}
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1535
|
+
if (voiceChatToggle) {
|
|
1536
|
+
voiceChatToggle.addEventListener("click", () => (vc.active ? stopVoiceChat() : startVoiceChat()));
|
|
1537
|
+
}
|
|
1538
|
+
|
|
1539
|
+
function closeSidebar() {
|
|
1540
|
+
layout.classList.remove("sidebar-open");
|
|
1541
|
+
}
|
|
1542
|
+
|
|
1543
|
+
function toggleSidebar() {
|
|
1544
|
+
layout.classList.toggle("sidebar-open");
|
|
1545
|
+
}
|
|
1546
|
+
|
|
1547
|
+
sidebarToggle.addEventListener("click", toggleSidebar);
|
|
1548
|
+
sidebarBackdrop.addEventListener("click", closeSidebar);
|
|
1549
|
+
|
|
1550
|
+
// v0.110.0/v0.111.0: top-right popovers - the ⚙ settings panel and the account
|
|
1551
|
+
// accordion. They are mutually exclusive and both close on outside-click/Escape.
|
|
1552
|
+
if (settingsToggle && settingsPanel) {
|
|
1553
|
+
settingsToggle.addEventListener("click", (e) => {
|
|
1554
|
+
e.stopPropagation();
|
|
1555
|
+
if (accountMenu) accountMenu.hidden = true;
|
|
1556
|
+
settingsPanel.hidden = !settingsPanel.hidden;
|
|
1557
|
+
});
|
|
1558
|
+
}
|
|
1559
|
+
if (accountToggle && accountMenu) {
|
|
1560
|
+
accountToggle.addEventListener("click", (e) => {
|
|
1561
|
+
e.stopPropagation();
|
|
1562
|
+
if (settingsPanel) settingsPanel.hidden = true;
|
|
1563
|
+
accountMenu.hidden = !accountMenu.hidden;
|
|
1564
|
+
accountToggle.setAttribute("aria-expanded", accountMenu.hidden ? "false" : "true");
|
|
1565
|
+
});
|
|
1566
|
+
}
|
|
1567
|
+
if (accountUserBtn) {
|
|
1568
|
+
accountUserBtn.addEventListener("click", (e) => {
|
|
1569
|
+
e.stopPropagation();
|
|
1570
|
+
if (accountMenu) accountMenu.hidden = true;
|
|
1571
|
+
if (accountToggle) accountToggle.setAttribute("aria-expanded", "false");
|
|
1572
|
+
openGatewayModal();
|
|
1573
|
+
});
|
|
1574
|
+
}
|
|
1575
|
+
if (gatewayBannerBtn) {
|
|
1576
|
+
gatewayBannerBtn.addEventListener("click", () => openGatewayModal());
|
|
1577
|
+
}
|
|
1578
|
+
document.addEventListener("click", (e) => {
|
|
1579
|
+
if (settingsPanel && !settingsPanel.hidden && !settingsPanel.contains(e.target) && !(settingsToggle && settingsToggle.contains(e.target))) {
|
|
1580
|
+
settingsPanel.hidden = true;
|
|
1581
|
+
}
|
|
1582
|
+
if (accountMenu && !accountMenu.hidden && !accountMenu.contains(e.target) && !(accountToggle && accountToggle.contains(e.target))) {
|
|
1583
|
+
accountMenu.hidden = true;
|
|
1584
|
+
if (accountToggle) accountToggle.setAttribute("aria-expanded", "false");
|
|
1585
|
+
}
|
|
1586
|
+
});
|
|
1587
|
+
document.addEventListener("keydown", (e) => {
|
|
1588
|
+
if (e.key !== "Escape") return;
|
|
1589
|
+
if (settingsPanel) settingsPanel.hidden = true;
|
|
1590
|
+
if (accountMenu) { accountMenu.hidden = true; if (accountToggle) accountToggle.setAttribute("aria-expanded", "false"); }
|
|
1591
|
+
});
|
|
1592
|
+
|
|
1593
|
+
// v0.111.0: client-side history search. Filters the rendered conversation rows
|
|
1594
|
+
// by their preview text. filterHistory() is re-applied after loadConversations
|
|
1595
|
+
// re-renders the list.
|
|
1596
|
+
function filterHistory() {
|
|
1597
|
+
if (!historySearch || !historyList) return;
|
|
1598
|
+
const q = historySearch.value.trim().toLowerCase();
|
|
1599
|
+
historyList.querySelectorAll("li").forEach((li) => {
|
|
1600
|
+
const hay = (li.textContent || "").toLowerCase();
|
|
1601
|
+
li.style.display = !q || hay.includes(q) ? "" : "none";
|
|
1602
|
+
});
|
|
1603
|
+
}
|
|
1604
|
+
if (historySearch) historySearch.addEventListener("input", filterHistory);
|
|
1605
|
+
|
|
1606
|
+
historyList.addEventListener("click", (e) => {
|
|
1607
|
+
const del = e.target.closest("[data-conv-delete]");
|
|
1608
|
+
if (del) {
|
|
1609
|
+
e.stopPropagation();
|
|
1610
|
+
if (confirm("Delete this entire conversation? All turns and artifacts will be removed.")) {
|
|
1611
|
+
deleteConversation(del.dataset.convDelete);
|
|
1612
|
+
}
|
|
1613
|
+
return;
|
|
1614
|
+
}
|
|
1615
|
+
const move = e.target.closest("[data-conv-move]");
|
|
1616
|
+
if (move) {
|
|
1617
|
+
e.stopPropagation();
|
|
1618
|
+
openMoveToProjectMenu(move, move.dataset.convMove);
|
|
1619
|
+
return;
|
|
1620
|
+
}
|
|
1621
|
+
const li = e.target.closest("li[data-conv-id]");
|
|
1622
|
+
if (li) {
|
|
1623
|
+
loadConversation(li.dataset.convId);
|
|
1624
|
+
closeSidebar();
|
|
1625
|
+
}
|
|
1626
|
+
});
|
|
1627
|
+
|
|
1628
|
+
runBtn.addEventListener("click", run);
|
|
1629
|
+
newChatBtn.addEventListener("click", () => {
|
|
1630
|
+
newChat();
|
|
1631
|
+
closeSidebar();
|
|
1632
|
+
});
|
|
1633
|
+
|
|
1634
|
+
// Per-turn action buttons (copy / retry). Delegated on transcriptEl because
|
|
1635
|
+
// the transcript is re-rendered via innerHTML on each turn change, which would
|
|
1636
|
+
// detach any directly-bound listeners.
|
|
1637
|
+
transcriptEl.addEventListener("click", handleTurnAction);
|
|
1638
|
+
|
|
1639
|
+
async function handleTurnAction(e) {
|
|
1640
|
+
const btn = e.target.closest(".turn-action");
|
|
1641
|
+
if (!btn) return;
|
|
1642
|
+
const action = btn.dataset.action;
|
|
1643
|
+
const turnIdx = Number(btn.dataset.turn);
|
|
1644
|
+
const turn = state.currentTurns[turnIdx];
|
|
1645
|
+
if (!turn) return;
|
|
1646
|
+
|
|
1647
|
+
if (action === "copy") {
|
|
1648
|
+
const text = turn.output || "";
|
|
1649
|
+
let ok = false;
|
|
1650
|
+
if (navigator.clipboard && window.isSecureContext) {
|
|
1651
|
+
try {
|
|
1652
|
+
await navigator.clipboard.writeText(text);
|
|
1653
|
+
ok = true;
|
|
1654
|
+
} catch {
|
|
1655
|
+
// Fall through to legacy path.
|
|
1656
|
+
}
|
|
1657
|
+
}
|
|
1658
|
+
if (!ok) {
|
|
1659
|
+
// Legacy clipboard fallback for non-secure contexts (rare; e.g. plain
|
|
1660
|
+
// HTTP local dev). Uses execCommand which is deprecated but still
|
|
1661
|
+
// universally supported.
|
|
1662
|
+
const ta = document.createElement("textarea");
|
|
1663
|
+
ta.value = text;
|
|
1664
|
+
ta.style.position = "fixed";
|
|
1665
|
+
ta.style.opacity = "0";
|
|
1666
|
+
document.body.appendChild(ta);
|
|
1667
|
+
ta.select();
|
|
1668
|
+
try { document.execCommand("copy"); ok = true; } catch { /* swallow */ }
|
|
1669
|
+
document.body.removeChild(ta);
|
|
1670
|
+
}
|
|
1671
|
+
if (ok) {
|
|
1672
|
+
// Brief visual confirmation.
|
|
1673
|
+
const orig = btn.innerHTML;
|
|
1674
|
+
btn.innerHTML = ICON_CHECK;
|
|
1675
|
+
btn.classList.add("turn-action-success");
|
|
1676
|
+
btn.disabled = true;
|
|
1677
|
+
setTimeout(() => {
|
|
1678
|
+
btn.innerHTML = orig;
|
|
1679
|
+
btn.classList.remove("turn-action-success");
|
|
1680
|
+
btn.disabled = false;
|
|
1681
|
+
}, 1200);
|
|
1682
|
+
}
|
|
1683
|
+
return;
|
|
1684
|
+
}
|
|
1685
|
+
|
|
1686
|
+
if (action === "edit") {
|
|
1687
|
+
loadTurnIntoComposer(turn);
|
|
1688
|
+
userInput.focus();
|
|
1689
|
+
// Move cursor to end so a quick edit is natural.
|
|
1690
|
+
const end = userInput.value.length;
|
|
1691
|
+
userInput.setSelectionRange(end, end);
|
|
1692
|
+
userInput.scrollIntoView({ behavior: "smooth", block: "center" });
|
|
1693
|
+
return;
|
|
1694
|
+
}
|
|
1695
|
+
|
|
1696
|
+
if (action === "retry") {
|
|
1697
|
+
// One-click resubmit: load this turn's settings into the composer, then
|
|
1698
|
+
// fire run() immediately. The new generation appends as a new turn in
|
|
1699
|
+
// the conversation. Attachments from the original turn are NOT carried
|
|
1700
|
+
// forward (multi-turn continuation is text-only across all paths), so
|
|
1701
|
+
// an attached-image retry will re-submit text only.
|
|
1702
|
+
loadTurnIntoComposer(turn);
|
|
1703
|
+
if (runBtn.disabled) return; // Already in-flight; don't double-fire.
|
|
1704
|
+
run();
|
|
1705
|
+
return;
|
|
1706
|
+
}
|
|
1707
|
+
}
|
|
1708
|
+
|
|
1709
|
+
// Shared by edit and retry. Restores the model picker, system prompt, and
|
|
1710
|
+
// user input to match the historical turn. Updates the affordance so the
|
|
1711
|
+
// composer's labels and visible fields (negative_prompt vs system, etc)
|
|
1712
|
+
// reflect the model type.
|
|
1713
|
+
function loadTurnIntoComposer(turn) {
|
|
1714
|
+
if (turn.model && state.modelsById[turn.model]) {
|
|
1715
|
+
modelSelect.value = turn.model;
|
|
1716
|
+
updateAffordance();
|
|
1717
|
+
}
|
|
1718
|
+
if (typeof turn.system_prompt === "string") {
|
|
1719
|
+
systemPrompt.value = turn.system_prompt;
|
|
1720
|
+
}
|
|
1721
|
+
userInput.value = turn.user_input || "";
|
|
1722
|
+
autoGrowUserInput();
|
|
1723
|
+
}
|
|
1724
|
+
|
|
1725
|
+
// Auto-grow the composer so the whole message is visible as it is typed,
|
|
1726
|
+
// instead of wrapping inside a fixed one-line box. CSS `field-sizing: content`
|
|
1727
|
+
// does this in newer browsers; this is the cross-browser fallback. The max
|
|
1728
|
+
// height (and overflow scroll past it) is still enforced by the CSS rule.
|
|
1729
|
+
function autoGrowUserInput() {
|
|
1730
|
+
userInput.style.height = "auto";
|
|
1731
|
+
userInput.style.height = `${userInput.scrollHeight}px`;
|
|
1732
|
+
}
|
|
1733
|
+
userInput.addEventListener("input", autoGrowUserInput);
|
|
1734
|
+
|
|
1735
|
+
userInput.addEventListener("keydown", (e) => {
|
|
1736
|
+
if (e.key === "Enter" && !e.shiftKey && !e.metaKey && !e.ctrlKey && !e.altKey) {
|
|
1737
|
+
e.preventDefault();
|
|
1738
|
+
run();
|
|
1739
|
+
}
|
|
1740
|
+
});
|
|
1741
|
+
|
|
1742
|
+
// ---------- #80 public-mode first-party auth ----------
|
|
1743
|
+
//
|
|
1744
|
+
// The app boots through bootstrap(), which probes GET /api/models first. That
|
|
1745
|
+
// route is the single unauthenticated boot entry point (exempt from the public-
|
|
1746
|
+
// mode session gate, so it never 401s) and its envelope carries the deploy mode
|
|
1747
|
+
// and session state alongside the catalog:
|
|
1748
|
+
// { models, mode: "public"|"access", authenticated, user, username, gateway }
|
|
1749
|
+
// Only mode=public AND authenticated=false raises the signup/login gate; every
|
|
1750
|
+
// other case (access mode, or an authenticated public session) boots the app
|
|
1751
|
+
// exactly as before. A probe failure fails OPEN to the app so self-host / access
|
|
1752
|
+
// deploys and older workers without the mode field keep working.
|
|
1753
|
+
const authScreen = $("#auth-screen");
|
|
1754
|
+
const authForm = $("#auth-form");
|
|
1755
|
+
const authTabLogin = $("#auth-tab-login");
|
|
1756
|
+
const authTabSignup = $("#auth-tab-signup");
|
|
1757
|
+
const authErrorBox = $("#auth-error");
|
|
1758
|
+
const authUsername = $("#auth-username");
|
|
1759
|
+
const authUsernameNote = $("#auth-username-note");
|
|
1760
|
+
const authUsernameErr = $("#auth-username-err");
|
|
1761
|
+
const authPassword = $("#auth-password");
|
|
1762
|
+
const authPasswordErr = $("#auth-password-err");
|
|
1763
|
+
const authConfirmField = $("#auth-confirm-field");
|
|
1764
|
+
const authPassword2 = $("#auth-password2");
|
|
1765
|
+
const authPassword2Err = $("#auth-password2-err");
|
|
1766
|
+
const authSubmit = $("#auth-submit");
|
|
1767
|
+
const accountLogout = $("#account-logout");
|
|
1768
|
+
|
|
1769
|
+
// Client-side validation mirrors the server rules as a UX nicety only; the
|
|
1770
|
+
// worker is the authority, so a 4xx from signup/login always shows the server
|
|
1771
|
+
// message verbatim. Keep these in step with the backend if it tightens them.
|
|
1772
|
+
const AUTH_USERNAME_RE = /^[A-Za-z0-9_-]{3,32}$/;
|
|
1773
|
+
const AUTH_PASSWORD_MIN = 10;
|
|
1774
|
+
let authTab = "signup"; // "signup" | "login"
|
|
1775
|
+
|
|
1776
|
+
function showAuthScreen() {
|
|
1777
|
+
if (!authScreen) return;
|
|
1778
|
+
authScreen.hidden = false;
|
|
1779
|
+
document.body.classList.add("auth-active");
|
|
1780
|
+
setTimeout(() => { if (authUsername) authUsername.focus(); }, 0);
|
|
1781
|
+
}
|
|
1782
|
+
function hideAuthScreen() {
|
|
1783
|
+
if (!authScreen) return;
|
|
1784
|
+
authScreen.hidden = true;
|
|
1785
|
+
document.body.classList.remove("auth-active");
|
|
1786
|
+
}
|
|
1787
|
+
function setAuthTab(tab) {
|
|
1788
|
+
authTab = tab === "login" ? "login" : "signup";
|
|
1789
|
+
const signup = authTab === "signup";
|
|
1790
|
+
if (authTabSignup) authTabSignup.setAttribute("aria-selected", signup ? "true" : "false");
|
|
1791
|
+
if (authTabLogin) authTabLogin.setAttribute("aria-selected", signup ? "false" : "true");
|
|
1792
|
+
if (authConfirmField) authConfirmField.hidden = !signup;
|
|
1793
|
+
if (authUsernameNote) authUsernameNote.hidden = !signup;
|
|
1794
|
+
if (authSubmit) authSubmit.textContent = signup ? "create account" : "log in";
|
|
1795
|
+
if (authPassword) authPassword.setAttribute("autocomplete", signup ? "new-password" : "current-password");
|
|
1796
|
+
if (authPassword2) authPassword2.value = "";
|
|
1797
|
+
clearAuthErrors();
|
|
1798
|
+
}
|
|
1799
|
+
function clearAuthErrors() {
|
|
1800
|
+
if (authErrorBox) { authErrorBox.hidden = true; authErrorBox.textContent = ""; }
|
|
1801
|
+
const pairs = [[authUsername, authUsernameErr], [authPassword, authPasswordErr], [authPassword2, authPassword2Err]];
|
|
1802
|
+
for (const [field, errEl] of pairs) {
|
|
1803
|
+
if (errEl) { errEl.hidden = true; errEl.textContent = ""; }
|
|
1804
|
+
if (field && field.parentElement) field.parentElement.classList.remove("invalid");
|
|
1805
|
+
}
|
|
1806
|
+
}
|
|
1807
|
+
function setFieldError(field, errEl, msg) {
|
|
1808
|
+
if (errEl) { errEl.textContent = msg; errEl.hidden = false; }
|
|
1809
|
+
if (field && field.parentElement) field.parentElement.classList.add("invalid");
|
|
1810
|
+
}
|
|
1811
|
+
function showAuthError(msg) {
|
|
1812
|
+
if (!authErrorBox) return;
|
|
1813
|
+
authErrorBox.textContent = msg;
|
|
1814
|
+
authErrorBox.hidden = false;
|
|
1815
|
+
}
|
|
1816
|
+
function validateAuth() {
|
|
1817
|
+
clearAuthErrors();
|
|
1818
|
+
let ok = true;
|
|
1819
|
+
const username = (authUsername ? authUsername.value : "").trim();
|
|
1820
|
+
const password = authPassword ? authPassword.value : "";
|
|
1821
|
+
if (!AUTH_USERNAME_RE.test(username)) {
|
|
1822
|
+
setFieldError(authUsername, authUsernameErr, "3 to 32 characters: letters, numbers, hyphen, underscore.");
|
|
1823
|
+
ok = false;
|
|
1824
|
+
}
|
|
1825
|
+
if (authTab === "signup") {
|
|
1826
|
+
if (password.length < AUTH_PASSWORD_MIN) {
|
|
1827
|
+
setFieldError(authPassword, authPasswordErr, `at least ${AUTH_PASSWORD_MIN} characters.`);
|
|
1828
|
+
ok = false;
|
|
1829
|
+
}
|
|
1830
|
+
const confirm = authPassword2 ? authPassword2.value : "";
|
|
1831
|
+
if (confirm !== password) {
|
|
1832
|
+
setFieldError(authPassword2, authPassword2Err, "passwords do not match.");
|
|
1833
|
+
ok = false;
|
|
1834
|
+
}
|
|
1835
|
+
} else if (!password) {
|
|
1836
|
+
setFieldError(authPassword, authPasswordErr, "enter your password.");
|
|
1837
|
+
ok = false;
|
|
1838
|
+
}
|
|
1839
|
+
return ok ? { username, password } : null;
|
|
1840
|
+
}
|
|
1841
|
+
async function submitAuth(ev) {
|
|
1842
|
+
if (ev) ev.preventDefault();
|
|
1843
|
+
const creds = validateAuth();
|
|
1844
|
+
if (!creds) return;
|
|
1845
|
+
const path = authTab === "signup" ? "/api/auth/signup" : "/api/auth/login";
|
|
1846
|
+
if (authSubmit) authSubmit.disabled = true;
|
|
1847
|
+
try {
|
|
1848
|
+
const res = await fetch(path, {
|
|
1849
|
+
method: "POST",
|
|
1850
|
+
headers: { "Content-Type": "application/json" },
|
|
1851
|
+
body: JSON.stringify(creds),
|
|
1852
|
+
});
|
|
1853
|
+
if (res.ok) {
|
|
1854
|
+
// The server sets the session cookie on success. Reload so the boot probe
|
|
1855
|
+
// renders the authenticated app with clean state (no partial-boot paths).
|
|
1856
|
+
location.reload();
|
|
1857
|
+
return;
|
|
1858
|
+
}
|
|
1859
|
+
const body = await res.json().catch(() => ({}));
|
|
1860
|
+
showAuthError(body.error || (authTab === "signup" ? "could not create account." : "could not log in."));
|
|
1861
|
+
} catch (err) {
|
|
1862
|
+
showAuthError("network error, please try again.");
|
|
1863
|
+
} finally {
|
|
1864
|
+
if (authSubmit) authSubmit.disabled = false;
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
async function doLogout() {
|
|
1868
|
+
try {
|
|
1869
|
+
await fetch("/api/auth/logout", { method: "POST", headers: { "Content-Type": "application/json" } });
|
|
1870
|
+
} catch (err) { /* best-effort; the reload drops to the auth gate regardless */ }
|
|
1871
|
+
location.reload();
|
|
1872
|
+
}
|
|
1873
|
+
if (authForm) authForm.addEventListener("submit", submitAuth);
|
|
1874
|
+
if (authTabSignup) authTabSignup.addEventListener("click", () => setAuthTab("signup"));
|
|
1875
|
+
if (authTabLogin) authTabLogin.addEventListener("click", () => setAuthTab("login"));
|
|
1876
|
+
if (accountLogout) accountLogout.addEventListener("click", () => {
|
|
1877
|
+
if (accountMenu) accountMenu.hidden = true;
|
|
1878
|
+
if (accountToggle) accountToggle.setAttribute("aria-expanded", "false");
|
|
1879
|
+
doLogout();
|
|
1880
|
+
});
|
|
1881
|
+
|
|
1882
|
+
function applyAuthShell(displayName) {
|
|
1883
|
+
// Public mode: show the username in the account chip and reveal the logout +
|
|
1884
|
+
// delete-account rows. Access / self-host mode keeps the email identity and
|
|
1885
|
+
// hides both (Cloudflare Access owns that lifecycle).
|
|
1886
|
+
const isPublic = state.authMode === "public";
|
|
1887
|
+
state.displayName = isPublic ? (displayName || null) : null;
|
|
1888
|
+
if (accountLogout) accountLogout.hidden = !isPublic;
|
|
1889
|
+
const delRow = document.getElementById("account-delete");
|
|
1890
|
+
if (delRow) delRow.hidden = !isPublic;
|
|
1891
|
+
}
|
|
1892
|
+
|
|
1893
|
+
async function bootApp(prefetchedModels) {
|
|
1894
|
+
try {
|
|
1895
|
+
await loadModels(prefetchedModels);
|
|
1896
|
+
await loadConversations();
|
|
1897
|
+
await loadDocuments();
|
|
1898
|
+
updateConvTitle();
|
|
1899
|
+
} catch (err) {
|
|
1900
|
+
transcriptEl.innerHTML = `<div class="turn turn-assistant"><div class="turn-role">error</div><div class="turn-body"><div class="turn-text error">Failed to initialize: ${escapeHtml(err.message)}</div></div></div>`;
|
|
1901
|
+
}
|
|
1902
|
+
}
|
|
1903
|
+
|
|
1904
|
+
async function bootstrap() {
|
|
1905
|
+
// #80 boot probe: GET /api/models is the single unauthenticated entry point.
|
|
1906
|
+
// Reachable without a session in both modes, it carries mode + authenticated +
|
|
1907
|
+
// username alongside the catalog, so one call gates the app AND hydrates the
|
|
1908
|
+
// picker in a single unauthenticated call. Fail OPEN: no data, or an
|
|
1909
|
+
// older worker with no mode field, behaves as access mode, so self-host and
|
|
1910
|
+
// pre-#80 deploys keep working; the signup gate can only appear when the
|
|
1911
|
+
// worker explicitly reports mode=public with no session.
|
|
1912
|
+
let data = null;
|
|
1913
|
+
try {
|
|
1914
|
+
const res = await fetch("/api/models", { headers: { "Content-Type": "application/json" } });
|
|
1915
|
+
if (res.ok) data = await res.json();
|
|
1916
|
+
} catch (err) { /* fail open to app boot */ }
|
|
1917
|
+
state.authMode = data && data.mode === "public" ? "public" : "access";
|
|
1918
|
+
state.authenticated = !data || data.authenticated !== false;
|
|
1919
|
+
if (state.authMode === "public" && !state.authenticated) {
|
|
1920
|
+
setAuthTab("signup");
|
|
1921
|
+
showAuthScreen();
|
|
1922
|
+
return;
|
|
1923
|
+
}
|
|
1924
|
+
applyAuthShell(data ? data.username : null);
|
|
1925
|
+
// Hand the already-fetched catalog to bootApp so loadModels does not refetch.
|
|
1926
|
+
await bootApp(data);
|
|
1927
|
+
}
|
|
1928
|
+
|
|
1929
|
+
bootstrap();
|
|
1930
|
+
|
|
1931
|
+
// ---------- Documents (RAG Pass 1) ----------
|
|
1932
|
+
|
|
1933
|
+
const documentsList = $("#documents-list");
|
|
1934
|
+
const docUploadBtn = $("#doc-upload-btn");
|
|
1935
|
+
const docFileInput = $("#doc-file-input");
|
|
1936
|
+
const docStatus = $("#doc-status");
|
|
1937
|
+
|
|
1938
|
+
function fmtDocSize(bytes) {
|
|
1939
|
+
if (bytes < 1024) return `${bytes}B`;
|
|
1940
|
+
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)}KB`;
|
|
1941
|
+
return `${(bytes / 1024 / 1024).toFixed(2)}MB`;
|
|
1942
|
+
}
|
|
1943
|
+
|
|
1944
|
+
async function loadDocuments() {
|
|
1945
|
+
try {
|
|
1946
|
+
const { documents } = await api("/api/documents");
|
|
1947
|
+
state.documentCount = (documents || []).length;
|
|
1948
|
+
documentsList.innerHTML = (documents || [])
|
|
1949
|
+
.map((d) => {
|
|
1950
|
+
const date = new Date(d.created_at.includes("Z") ? d.created_at : d.created_at + "Z");
|
|
1951
|
+
const dateStr = date.toLocaleString(undefined, { month: "numeric", day: "numeric" });
|
|
1952
|
+
return `
|
|
1953
|
+
<li data-id="${d.id}">
|
|
1954
|
+
<span class="doc-name" title="${escapeHtml(d.filename)}">${escapeHtml(d.filename)}</span>
|
|
1955
|
+
<span class="doc-meta">${d.chunk_count} chunks \u00b7 ${fmtDocSize(d.size_bytes)} \u00b7 ${dateStr}</span>
|
|
1956
|
+
<button class="delete" data-doc-delete="${d.id}" type="button" title="delete document">\u00d7</button>
|
|
1957
|
+
</li>`;
|
|
1958
|
+
})
|
|
1959
|
+
.join("");
|
|
1960
|
+
// Re-evaluate whether the "use my docs" toggle should be visible.
|
|
1961
|
+
updateAffordance();
|
|
1962
|
+
// If the user has zero docs, force the checkbox off so a stale check
|
|
1963
|
+
// from a previous session doesn't get sent on the next submit.
|
|
1964
|
+
if (state.documentCount === 0) useDocsCheckbox.checked = false;
|
|
1965
|
+
} catch (err) {
|
|
1966
|
+
docStatus.textContent = "Failed to load documents: " + err.message;
|
|
1967
|
+
docStatus.classList.add("error");
|
|
1968
|
+
}
|
|
1969
|
+
}
|
|
1970
|
+
|
|
1971
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
1972
|
+
|
|
1973
|
+
// v0.26.0: a .zip import runs durably in a background workflow. Poll its
|
|
1974
|
+
// status until done/failed, refreshing the document list as files land so the
|
|
1975
|
+
// user sees progress.
|
|
1976
|
+
async function pollImport(jobId, name) {
|
|
1977
|
+
for (let i = 0; i < 600; i++) { // ~20 min ceiling at 2s spacing
|
|
1978
|
+
await sleep(2000);
|
|
1979
|
+
let s;
|
|
1980
|
+
try {
|
|
1981
|
+
s = await api(`/api/import/${encodeURIComponent(jobId)}`);
|
|
1982
|
+
} catch {
|
|
1983
|
+
continue; // transient; keep polling
|
|
1984
|
+
}
|
|
1985
|
+
if (s.status === "done") {
|
|
1986
|
+
const skip = (s.skipped || []).length;
|
|
1987
|
+
docStatus.classList.remove("error");
|
|
1988
|
+
docStatus.textContent =
|
|
1989
|
+
`Imported ${s.imported_count} file${s.imported_count === 1 ? "" : "s"} ` +
|
|
1990
|
+
`(${s.total_chunks} chunks)${skip ? `, skipped ${skip}` : ""}`;
|
|
1991
|
+
await loadDocuments();
|
|
1992
|
+
setTimeout(() => {
|
|
1993
|
+
if (docStatus.textContent.startsWith("Imported ")) docStatus.textContent = "";
|
|
1994
|
+
}, 6000);
|
|
1995
|
+
return;
|
|
1996
|
+
}
|
|
1997
|
+
if (s.status === "failed") {
|
|
1998
|
+
docStatus.classList.add("error");
|
|
1999
|
+
docStatus.textContent = `Import of ${name} failed: ${s.error || "unknown error"}`;
|
|
2000
|
+
return;
|
|
2001
|
+
}
|
|
2002
|
+
// Still running: surface incremental progress via the document list.
|
|
2003
|
+
await loadDocuments();
|
|
2004
|
+
docStatus.textContent = `Importing ${name}\u2026 (${state.documentCount} files so far)`;
|
|
2005
|
+
}
|
|
2006
|
+
docStatus.textContent = `Import of ${name} still running; check back shortly.`;
|
|
2007
|
+
}
|
|
2008
|
+
|
|
2009
|
+
async function uploadDocument(file) {
|
|
2010
|
+
if (!file) return;
|
|
2011
|
+
// Any file type is accepted. The worker extracts PDF and XLSX/XLS natively
|
|
2012
|
+
// and decodes everything else as text, rejecting only unreadable binaries.
|
|
2013
|
+
// A .zip (v0.25.0) is expanded server-side; as of v0.26.0 that runs in a
|
|
2014
|
+
// background workflow and the client polls for the result.
|
|
2015
|
+
docStatus.classList.remove("error");
|
|
2016
|
+
const isZip = /\.zip$/i.test(file.name) || file.type === "application/zip" || file.type === "application/x-zip-compressed";
|
|
2017
|
+
docStatus.textContent = isZip ? `Importing ${file.name}\u2026` : `Uploading ${file.name}\u2026`;
|
|
2018
|
+
|
|
2019
|
+
try {
|
|
2020
|
+
const dataUrl = await readAsDataUrl(file);
|
|
2021
|
+
const result = await api("/api/documents", {
|
|
2022
|
+
method: "POST",
|
|
2023
|
+
body: JSON.stringify({
|
|
2024
|
+
filename: file.name,
|
|
2025
|
+
mime: file.type || "text/plain",
|
|
2026
|
+
data: dataUrl,
|
|
2027
|
+
}),
|
|
2028
|
+
});
|
|
2029
|
+
if (result.zip && result.async) {
|
|
2030
|
+
await pollImport(result.job_id, file.name);
|
|
2031
|
+
return;
|
|
2032
|
+
}
|
|
2033
|
+
docStatus.textContent = `Uploaded ${result.filename}: ${result.chunk_count} chunks embedded`;
|
|
2034
|
+
await loadDocuments();
|
|
2035
|
+
// Clear status after a few seconds.
|
|
2036
|
+
setTimeout(() => {
|
|
2037
|
+
if (docStatus.textContent.startsWith("Uploaded ")) docStatus.textContent = "";
|
|
2038
|
+
}, 5000);
|
|
2039
|
+
} catch (err) {
|
|
2040
|
+
docStatus.classList.add("error");
|
|
2041
|
+
docStatus.textContent = `${isZip ? "Import" : "Upload"} failed: ${err.message}`;
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
|
|
2045
|
+
async function deleteDocument(id) {
|
|
2046
|
+
try {
|
|
2047
|
+
await api(`/api/documents/${id}`, { method: "DELETE" });
|
|
2048
|
+
await loadDocuments();
|
|
2049
|
+
} catch (err) {
|
|
2050
|
+
docStatus.classList.add("error");
|
|
2051
|
+
docStatus.textContent = `Delete failed: ${err.message}`;
|
|
2052
|
+
}
|
|
2053
|
+
}
|
|
2054
|
+
|
|
2055
|
+
docUploadBtn.addEventListener("click", () => docFileInput.click());
|
|
2056
|
+
docFileInput.addEventListener("change", async (e) => {
|
|
2057
|
+
const file = e.target.files?.[0];
|
|
2058
|
+
if (file) await uploadDocument(file);
|
|
2059
|
+
docFileInput.value = ""; // allow re-uploading the same filename
|
|
2060
|
+
});
|
|
2061
|
+
|
|
2062
|
+
documentsList.addEventListener("click", (e) => {
|
|
2063
|
+
const btn = e.target.closest("[data-doc-delete]");
|
|
2064
|
+
if (btn) {
|
|
2065
|
+
const id = Number(btn.dataset.docDelete);
|
|
2066
|
+
if (confirm("Delete this document and all its chunks? This cannot be undone.")) {
|
|
2067
|
+
deleteDocument(id);
|
|
2068
|
+
}
|
|
2069
|
+
}
|
|
2070
|
+
});
|
|
2071
|
+
|
|
2072
|
+
// ---------- Projects (v0.20.1) ----------
|
|
2073
|
+
//
|
|
2074
|
+
// Projects group documents (and conversations, in v0.20.2+) under a shared
|
|
2075
|
+
// system prompt and retrieval scope. Frontend state:
|
|
2076
|
+
//
|
|
2077
|
+
// state.projects - cached array from GET /api/projects
|
|
2078
|
+
// state.activeProjectId - currently-selected project's id, or null
|
|
2079
|
+
//
|
|
2080
|
+
// Active project persists across reloads via localStorage. When active:
|
|
2081
|
+
// - The project chip appears next to the model picker
|
|
2082
|
+
// - Chat requests include project_id in the body (handled in run())
|
|
2083
|
+
// - The project row in the sidebar is visually highlighted
|
|
2084
|
+
//
|
|
2085
|
+
// Project CRUD goes through a single shared modal (project-modal); the
|
|
2086
|
+
// modal's title and Delete-button visibility differentiate create vs edit.
|
|
2087
|
+
// Document attachment uses a separate picker modal that shows all the user's
|
|
2088
|
+
// docs with checkboxes for project membership.
|
|
2089
|
+
|
|
2090
|
+
const projectsList = $("#projects-list");
|
|
2091
|
+
const projNewBtn = $("#proj-new-btn");
|
|
2092
|
+
const projStatus = $("#proj-status");
|
|
2093
|
+
const activeProjectChip = $("#active-project-chip");
|
|
2094
|
+
const activeProjectName = $("#active-project-name");
|
|
2095
|
+
const activeProjectClear = $("#active-project-clear");
|
|
2096
|
+
|
|
2097
|
+
const projectModal = $("#project-modal");
|
|
2098
|
+
const projectModalTitle = $("#project-modal-title");
|
|
2099
|
+
const projectModalName = $("#project-modal-name");
|
|
2100
|
+
const projectModalDesc = $("#project-modal-desc");
|
|
2101
|
+
const projectModalPrompt = $("#project-modal-prompt");
|
|
2102
|
+
const projectModalError = $("#project-modal-error");
|
|
2103
|
+
const projectModalSave = $("#project-modal-save");
|
|
2104
|
+
const projectModalCancel = $("#project-modal-cancel");
|
|
2105
|
+
const projectModalDelete = $("#project-modal-delete");
|
|
2106
|
+
|
|
2107
|
+
const gatewayModal = $("#gateway-modal");
|
|
2108
|
+
const gatewayModalId = $("#gateway-modal-id");
|
|
2109
|
+
const gatewayModalToken = $("#gateway-modal-token");
|
|
2110
|
+
const gatewayModalTokenHint= $("#gateway-modal-token-hint");
|
|
2111
|
+
const gatewayModalClear = $("#gateway-modal-clear-token");
|
|
2112
|
+
const gatewayModalError = $("#gateway-modal-error");
|
|
2113
|
+
const gatewayModalSave = $("#gateway-modal-save");
|
|
2114
|
+
const gatewayModalCancel = $("#gateway-modal-cancel");
|
|
2115
|
+
|
|
2116
|
+
const projectDocsModal = $("#project-docs-modal");
|
|
2117
|
+
const projectDocsModalList = $("#project-docs-modal-list");
|
|
2118
|
+
const projectDocsModalEmpty= $("#project-docs-modal-empty");
|
|
2119
|
+
const projectDocsModalClose= $("#project-docs-modal-close");
|
|
2120
|
+
const discordImportBtn = $("#discord-import-btn");
|
|
2121
|
+
const discordImportFile = $("#discord-import-file");
|
|
2122
|
+
const discordImportBots = $("#discord-import-bots");
|
|
2123
|
+
const discordImportStatus = $("#discord-import-status");
|
|
2124
|
+
|
|
2125
|
+
const ACTIVE_PROJECT_LS_KEY = "skyphusion.activeProjectId";
|
|
2126
|
+
|
|
2127
|
+
// Editing state for the project modal. null = create mode; a project row =
|
|
2128
|
+
// edit mode (Delete button visible, fields prefilled).
|
|
2129
|
+
let editingProjectId = null;
|
|
2130
|
+
// Document picker context: which project is being managed.
|
|
2131
|
+
let docsPickerProjectId = null;
|
|
2132
|
+
|
|
2133
|
+
// ---------- API helpers ----------
|
|
2134
|
+
|
|
2135
|
+
async function fetchProjects() {
|
|
2136
|
+
const { projects } = await api("/api/projects");
|
|
2137
|
+
state.projects = projects || [];
|
|
2138
|
+
return state.projects;
|
|
2139
|
+
}
|
|
2140
|
+
|
|
2141
|
+
async function fetchProject(id) {
|
|
2142
|
+
return await api(`/api/projects/${id}`);
|
|
2143
|
+
}
|
|
2144
|
+
|
|
2145
|
+
async function createProject(body) {
|
|
2146
|
+
return await api("/api/projects", { method: "POST", body: JSON.stringify(body) });
|
|
2147
|
+
}
|
|
2148
|
+
|
|
2149
|
+
async function patchProject(id, body) {
|
|
2150
|
+
return await api(`/api/projects/${id}`, { method: "PATCH", body: JSON.stringify(body) });
|
|
2151
|
+
}
|
|
2152
|
+
|
|
2153
|
+
async function deleteProjectApi(id) {
|
|
2154
|
+
return await api(`/api/projects/${id}`, { method: "DELETE" });
|
|
2155
|
+
}
|
|
2156
|
+
|
|
2157
|
+
async function attachDocumentToProject(projectId, docId) {
|
|
2158
|
+
return await api(`/api/projects/${projectId}/documents/${docId}`, { method: "POST" });
|
|
2159
|
+
}
|
|
2160
|
+
|
|
2161
|
+
async function detachDocumentFromProject(projectId, docId) {
|
|
2162
|
+
return await api(`/api/projects/${projectId}/documents/${docId}`, { method: "DELETE" });
|
|
2163
|
+
}
|
|
2164
|
+
|
|
2165
|
+
// ---------- Active-project persistence ----------
|
|
2166
|
+
|
|
2167
|
+
function loadActiveProjectFromStorage() {
|
|
2168
|
+
try {
|
|
2169
|
+
const raw = localStorage.getItem(ACTIVE_PROJECT_LS_KEY);
|
|
2170
|
+
if (!raw) return null;
|
|
2171
|
+
const n = Number(raw);
|
|
2172
|
+
return Number.isInteger(n) && n > 0 ? n : null;
|
|
2173
|
+
} catch {
|
|
2174
|
+
return null;
|
|
2175
|
+
}
|
|
2176
|
+
}
|
|
2177
|
+
|
|
2178
|
+
function saveActiveProjectToStorage(id) {
|
|
2179
|
+
try {
|
|
2180
|
+
if (id === null) localStorage.removeItem(ACTIVE_PROJECT_LS_KEY);
|
|
2181
|
+
else localStorage.setItem(ACTIVE_PROJECT_LS_KEY, String(id));
|
|
2182
|
+
} catch {
|
|
2183
|
+
/* private mode etc; non-fatal */
|
|
2184
|
+
}
|
|
2185
|
+
}
|
|
2186
|
+
|
|
2187
|
+
function setActiveProject(id) {
|
|
2188
|
+
// Validate: id must point to a project we know about. Stale ids (project
|
|
2189
|
+
// deleted in another tab) silently clear.
|
|
2190
|
+
if (id !== null && !state.projects.some((p) => p.id === id)) {
|
|
2191
|
+
id = null;
|
|
2192
|
+
}
|
|
2193
|
+
state.activeProjectId = id;
|
|
2194
|
+
saveActiveProjectToStorage(id);
|
|
2195
|
+
renderActiveProjectChip();
|
|
2196
|
+
renderProjectsList();
|
|
2197
|
+
}
|
|
2198
|
+
|
|
2199
|
+
// ---------- Renderers ----------
|
|
2200
|
+
|
|
2201
|
+
function renderActiveProjectChip() {
|
|
2202
|
+
if (!state.activeProjectId) {
|
|
2203
|
+
activeProjectChip.hidden = true;
|
|
2204
|
+
return;
|
|
2205
|
+
}
|
|
2206
|
+
const p = state.projects.find((x) => x.id === state.activeProjectId);
|
|
2207
|
+
if (!p) {
|
|
2208
|
+
// Stale id; treat as inactive.
|
|
2209
|
+
state.activeProjectId = null;
|
|
2210
|
+
saveActiveProjectToStorage(null);
|
|
2211
|
+
activeProjectChip.hidden = true;
|
|
2212
|
+
return;
|
|
2213
|
+
}
|
|
2214
|
+
activeProjectName.textContent = p.name;
|
|
2215
|
+
activeProjectChip.hidden = false;
|
|
2216
|
+
}
|
|
2217
|
+
|
|
2218
|
+
function renderProjectsList() {
|
|
2219
|
+
if (state.projects.length === 0) {
|
|
2220
|
+
projectsList.innerHTML = `<li class="proj-empty">no projects yet. click "+ new" to create one.</li>`;
|
|
2221
|
+
return;
|
|
2222
|
+
}
|
|
2223
|
+
projectsList.innerHTML = state.projects.map((p) => {
|
|
2224
|
+
const active = p.id === state.activeProjectId ? " active" : "";
|
|
2225
|
+
const docCount = p.document_count != null ? p.document_count : 0;
|
|
2226
|
+
const docLabel = docCount === 1 ? "1 doc" : `${docCount} docs`;
|
|
2227
|
+
return `
|
|
2228
|
+
<li class="${active.trim()}" data-proj-id="${p.id}" title="${escapeHtml(p.description || p.name)}">
|
|
2229
|
+
<span class="proj-name">${escapeHtml(p.name)}</span>
|
|
2230
|
+
<span class="proj-meta">${docLabel}</span>
|
|
2231
|
+
<span class="proj-actions">
|
|
2232
|
+
<button class="proj-action" data-proj-action="docs" data-proj-id="${p.id}" type="button" title="manage documents">docs</button>
|
|
2233
|
+
<button class="proj-action" data-proj-action="edit" data-proj-id="${p.id}" type="button" title="edit project">edit</button>
|
|
2234
|
+
</span>
|
|
2235
|
+
</li>`;
|
|
2236
|
+
}).join("");
|
|
2237
|
+
}
|
|
2238
|
+
|
|
2239
|
+
// ---------- Modal helpers ----------
|
|
2240
|
+
|
|
2241
|
+
function openProjectModal(project) {
|
|
2242
|
+
// project: null = create mode; a project row = edit mode.
|
|
2243
|
+
editingProjectId = project ? project.id : null;
|
|
2244
|
+
projectModalTitle.textContent = project ? `edit project: ${project.name}` : "new project";
|
|
2245
|
+
projectModalName.value = project ? project.name : "";
|
|
2246
|
+
projectModalDesc.value = project ? (project.description || "") : "";
|
|
2247
|
+
projectModalPrompt.value = project ? (project.system_prompt || "") : "";
|
|
2248
|
+
projectModalDelete.hidden = !project;
|
|
2249
|
+
projectModalError.hidden = true;
|
|
2250
|
+
projectModalError.textContent = "";
|
|
2251
|
+
projectModal.hidden = false;
|
|
2252
|
+
projectModalName.focus();
|
|
2253
|
+
}
|
|
2254
|
+
|
|
2255
|
+
function closeProjectModal() {
|
|
2256
|
+
projectModal.hidden = true;
|
|
2257
|
+
editingProjectId = null;
|
|
2258
|
+
}
|
|
2259
|
+
|
|
2260
|
+
async function openGatewayModal() {
|
|
2261
|
+
if (!gatewayModal) return;
|
|
2262
|
+
gatewayModalError.hidden = true;
|
|
2263
|
+
gatewayModalError.textContent = "";
|
|
2264
|
+
gatewayModalToken.value = "";
|
|
2265
|
+
gatewayModalClear.checked = false;
|
|
2266
|
+
try {
|
|
2267
|
+
const prefs = await api("/api/prefs");
|
|
2268
|
+
gatewayModalId.value = prefs.gateway_id || "";
|
|
2269
|
+
if (gatewayModalTokenHint) {
|
|
2270
|
+
gatewayModalTokenHint.textContent = prefs.cf_aig_token_set
|
|
2271
|
+
? `saved token: ${prefs.cf_aig_token_preview || "••••"}`
|
|
2272
|
+
: "no token saved yet";
|
|
2273
|
+
}
|
|
2274
|
+
state.gateway = {
|
|
2275
|
+
configured: !!prefs.configured,
|
|
2276
|
+
source: prefs.source,
|
|
2277
|
+
gateway_id: prefs.gateway_id,
|
|
2278
|
+
cf_aig_token_set: prefs.cf_aig_token_set,
|
|
2279
|
+
};
|
|
2280
|
+
renderGatewayBanner();
|
|
2281
|
+
} catch (err) {
|
|
2282
|
+
gatewayModalId.value = state.gateway?.gateway_id || "";
|
|
2283
|
+
if (gatewayModalTokenHint) gatewayModalTokenHint.textContent = "";
|
|
2284
|
+
gatewayModalError.textContent = err.message;
|
|
2285
|
+
gatewayModalError.hidden = false;
|
|
2286
|
+
}
|
|
2287
|
+
gatewayModal.hidden = false;
|
|
2288
|
+
gatewayModalId.focus();
|
|
2289
|
+
}
|
|
2290
|
+
|
|
2291
|
+
function closeGatewayModal() {
|
|
2292
|
+
if (gatewayModal) gatewayModal.hidden = true;
|
|
2293
|
+
}
|
|
2294
|
+
|
|
2295
|
+
function showGatewayModalError(msg) {
|
|
2296
|
+
gatewayModalError.textContent = msg;
|
|
2297
|
+
gatewayModalError.hidden = false;
|
|
2298
|
+
}
|
|
2299
|
+
|
|
2300
|
+
async function saveGatewayModal() {
|
|
2301
|
+
const gateway_id = gatewayModalId.value.trim();
|
|
2302
|
+
const body = {};
|
|
2303
|
+
if (gateway_id) body.gateway_id = gateway_id;
|
|
2304
|
+
else body.gateway_id = "";
|
|
2305
|
+
if (gatewayModalClear.checked) {
|
|
2306
|
+
body.clear_cf_aig_token = true;
|
|
2307
|
+
} else if (gatewayModalToken.value.trim()) {
|
|
2308
|
+
body.cf_aig_token = gatewayModalToken.value.trim();
|
|
2309
|
+
}
|
|
2310
|
+
if (!gateway_id && !body.cf_aig_token && !body.clear_cf_aig_token) {
|
|
2311
|
+
showGatewayModalError("enter a gateway slug and/or API token");
|
|
2312
|
+
return;
|
|
2313
|
+
}
|
|
2314
|
+
try {
|
|
2315
|
+
const prefs = await api("/api/prefs", { method: "PATCH", body: JSON.stringify(body) });
|
|
2316
|
+
state.gateway = {
|
|
2317
|
+
configured: !!prefs.configured,
|
|
2318
|
+
source: prefs.source,
|
|
2319
|
+
gateway_id: prefs.gateway_id,
|
|
2320
|
+
cf_aig_token_set: prefs.cf_aig_token_set,
|
|
2321
|
+
};
|
|
2322
|
+
renderGatewayBanner();
|
|
2323
|
+
closeGatewayModal();
|
|
2324
|
+
} catch (err) {
|
|
2325
|
+
showGatewayModalError(err.message);
|
|
2326
|
+
}
|
|
2327
|
+
}
|
|
2328
|
+
|
|
2329
|
+
function showProjectModalError(msg) {
|
|
2330
|
+
projectModalError.textContent = msg;
|
|
2331
|
+
projectModalError.hidden = false;
|
|
2332
|
+
}
|
|
2333
|
+
|
|
2334
|
+
async function saveProjectModal() {
|
|
2335
|
+
const name = projectModalName.value.trim();
|
|
2336
|
+
if (!name) {
|
|
2337
|
+
showProjectModalError("name is required");
|
|
2338
|
+
return;
|
|
2339
|
+
}
|
|
2340
|
+
if (name.length > 200) {
|
|
2341
|
+
showProjectModalError("name too long (max 200 chars)");
|
|
2342
|
+
return;
|
|
2343
|
+
}
|
|
2344
|
+
const description = projectModalDesc.value.trim();
|
|
2345
|
+
const system_prompt = projectModalPrompt.value.trim();
|
|
2346
|
+
|
|
2347
|
+
projectModalSave.disabled = true;
|
|
2348
|
+
try {
|
|
2349
|
+
if (editingProjectId) {
|
|
2350
|
+
await patchProject(editingProjectId, { name, description, system_prompt });
|
|
2351
|
+
} else {
|
|
2352
|
+
const result = await createProject({ name, description, system_prompt });
|
|
2353
|
+
// Auto-activate the newly-created project so the user sees the chip and
|
|
2354
|
+
// can start using it immediately.
|
|
2355
|
+
if (result.project) setActiveProject(result.project.id);
|
|
2356
|
+
}
|
|
2357
|
+
await fetchProjects();
|
|
2358
|
+
renderProjectsList();
|
|
2359
|
+
renderActiveProjectChip();
|
|
2360
|
+
closeProjectModal();
|
|
2361
|
+
} catch (err) {
|
|
2362
|
+
showProjectModalError(err.message || "save failed");
|
|
2363
|
+
} finally {
|
|
2364
|
+
projectModalSave.disabled = false;
|
|
2365
|
+
}
|
|
2366
|
+
}
|
|
2367
|
+
|
|
2368
|
+
async function deleteProjectFromModal() {
|
|
2369
|
+
if (!editingProjectId) return;
|
|
2370
|
+
const p = state.projects.find((x) => x.id === editingProjectId);
|
|
2371
|
+
if (!p) return;
|
|
2372
|
+
if (!confirm(`Delete project "${p.name}"? Its documents will stay; only the project and its memberships are removed.`)) {
|
|
2373
|
+
return;
|
|
2374
|
+
}
|
|
2375
|
+
projectModalDelete.disabled = true;
|
|
2376
|
+
try {
|
|
2377
|
+
await deleteProjectApi(editingProjectId);
|
|
2378
|
+
if (state.activeProjectId === editingProjectId) {
|
|
2379
|
+
setActiveProject(null);
|
|
2380
|
+
}
|
|
2381
|
+
await fetchProjects();
|
|
2382
|
+
renderProjectsList();
|
|
2383
|
+
renderActiveProjectChip();
|
|
2384
|
+
closeProjectModal();
|
|
2385
|
+
} catch (err) {
|
|
2386
|
+
showProjectModalError(err.message || "delete failed");
|
|
2387
|
+
} finally {
|
|
2388
|
+
projectModalDelete.disabled = false;
|
|
2389
|
+
}
|
|
2390
|
+
}
|
|
2391
|
+
|
|
2392
|
+
// ---------- Document picker modal ----------
|
|
2393
|
+
|
|
2394
|
+
async function openDocsPicker(projectId) {
|
|
2395
|
+
docsPickerProjectId = projectId;
|
|
2396
|
+
discordImportStatus.hidden = true;
|
|
2397
|
+
discordImportStatus.textContent = "";
|
|
2398
|
+
await renderDocsPickerList(projectId);
|
|
2399
|
+
projectDocsModal.hidden = false;
|
|
2400
|
+
}
|
|
2401
|
+
|
|
2402
|
+
// Fetch the full doc list + the project's attached set and render the
|
|
2403
|
+
// checkbox list. Extracted so it can be re-run after a Discord import
|
|
2404
|
+
// without closing/reopening the modal.
|
|
2405
|
+
async function renderDocsPickerList(projectId) {
|
|
2406
|
+
const [{ documents: allDocs }, { documents: projDocs }] = await Promise.all([
|
|
2407
|
+
api("/api/documents"),
|
|
2408
|
+
api(`/api/documents?project_id=${projectId}`),
|
|
2409
|
+
]);
|
|
2410
|
+
const attachedIds = new Set((projDocs || []).map((d) => d.id));
|
|
2411
|
+
|
|
2412
|
+
if (!allDocs || allDocs.length === 0) {
|
|
2413
|
+
projectDocsModalList.innerHTML = "";
|
|
2414
|
+
projectDocsModalEmpty.hidden = false;
|
|
2415
|
+
} else {
|
|
2416
|
+
projectDocsModalEmpty.hidden = true;
|
|
2417
|
+
projectDocsModalList.innerHTML = allDocs.map((d) => {
|
|
2418
|
+
const checked = attachedIds.has(d.id) ? "checked" : "";
|
|
2419
|
+
return `
|
|
2420
|
+
<li data-doc-id="${d.id}">
|
|
2421
|
+
<input type="checkbox" data-doc-toggle="${d.id}" ${checked} />
|
|
2422
|
+
<span class="pd-name">${escapeHtml(d.filename)}</span>
|
|
2423
|
+
<span class="pd-meta">${d.chunk_count} chunks</span>
|
|
2424
|
+
</li>`;
|
|
2425
|
+
}).join("");
|
|
2426
|
+
}
|
|
2427
|
+
}
|
|
2428
|
+
|
|
2429
|
+
function closeDocsPicker() {
|
|
2430
|
+
projectDocsModal.hidden = true;
|
|
2431
|
+
docsPickerProjectId = null;
|
|
2432
|
+
}
|
|
2433
|
+
|
|
2434
|
+
async function handleDocsPickerToggle(docId, checked) {
|
|
2435
|
+
if (!docsPickerProjectId) return;
|
|
2436
|
+
try {
|
|
2437
|
+
if (checked) {
|
|
2438
|
+
await attachDocumentToProject(docsPickerProjectId, docId);
|
|
2439
|
+
} else {
|
|
2440
|
+
await detachDocumentFromProject(docsPickerProjectId, docId);
|
|
2441
|
+
}
|
|
2442
|
+
// Refresh the project list so the doc count updates without closing the modal.
|
|
2443
|
+
await fetchProjects();
|
|
2444
|
+
renderProjectsList();
|
|
2445
|
+
} catch (err) {
|
|
2446
|
+
// Surface the error and revert the checkbox to its previous state.
|
|
2447
|
+
alert(`Failed to ${checked ? "attach" : "detach"} document: ${err.message}`);
|
|
2448
|
+
const cb = projectDocsModalList.querySelector(`[data-doc-toggle="${docId}"]`);
|
|
2449
|
+
if (cb) cb.checked = !checked;
|
|
2450
|
+
}
|
|
2451
|
+
}
|
|
2452
|
+
|
|
2453
|
+
// v0.20.4: Discord export import from the docs picker modal. Reads the
|
|
2454
|
+
// selected .json file as base64 and POSTs to the import-discord endpoint,
|
|
2455
|
+
// then refreshes the doc list + project counts in place.
|
|
2456
|
+
function setImportStatus(msg, kind) {
|
|
2457
|
+
discordImportStatus.hidden = false;
|
|
2458
|
+
discordImportStatus.textContent = msg;
|
|
2459
|
+
discordImportStatus.className = "discord-import-status" + (kind ? ` ${kind}` : "");
|
|
2460
|
+
}
|
|
2461
|
+
|
|
2462
|
+
async function handleDiscordImportFile(file) {
|
|
2463
|
+
if (!file || !docsPickerProjectId) return;
|
|
2464
|
+
const projectId = docsPickerProjectId;
|
|
2465
|
+
|
|
2466
|
+
// Read the file as base64 (strip the data: prefix the FileReader adds).
|
|
2467
|
+
setImportStatus(`reading ${file.name}...`, "");
|
|
2468
|
+
let base64;
|
|
2469
|
+
try {
|
|
2470
|
+
base64 = await new Promise((resolve, reject) => {
|
|
2471
|
+
const r = new FileReader();
|
|
2472
|
+
r.onload = () => {
|
|
2473
|
+
const result = String(r.result);
|
|
2474
|
+
const comma = result.indexOf(",");
|
|
2475
|
+
resolve(comma >= 0 ? result.slice(comma + 1) : result);
|
|
2476
|
+
};
|
|
2477
|
+
r.onerror = () => reject(new Error("file read failed"));
|
|
2478
|
+
r.readAsDataURL(file);
|
|
2479
|
+
});
|
|
2480
|
+
} catch (err) {
|
|
2481
|
+
setImportStatus(`Could not read file: ${err.message}`, "error");
|
|
2482
|
+
return;
|
|
2483
|
+
}
|
|
2484
|
+
|
|
2485
|
+
setImportStatus(`importing ${file.name} (parsing, chunking, embedding)...`, "");
|
|
2486
|
+
discordImportBtn.disabled = true;
|
|
2487
|
+
try {
|
|
2488
|
+
const result = await api(`/api/projects/${projectId}/import-discord`, {
|
|
2489
|
+
method: "POST",
|
|
2490
|
+
body: JSON.stringify({
|
|
2491
|
+
filename: file.name,
|
|
2492
|
+
data: base64,
|
|
2493
|
+
options: { includeBots: discordImportBots.checked },
|
|
2494
|
+
}),
|
|
2495
|
+
});
|
|
2496
|
+
const skipped = (result.raw_message_count ?? 0) - (result.imported_message_count ?? 0);
|
|
2497
|
+
const skipNote = skipped > 0 ? ` (${skipped} system/empty messages skipped)` : "";
|
|
2498
|
+
setImportStatus(
|
|
2499
|
+
`imported #${result.channel}: ${result.imported_message_count} messages -> ${result.chunk_count} chunks${skipNote}`,
|
|
2500
|
+
"ok",
|
|
2501
|
+
);
|
|
2502
|
+
// Refresh the doc list (the export shows as a new attached doc) and the
|
|
2503
|
+
// sidebar project counts.
|
|
2504
|
+
await renderDocsPickerList(projectId);
|
|
2505
|
+
await fetchProjects();
|
|
2506
|
+
renderProjectsList();
|
|
2507
|
+
} catch (err) {
|
|
2508
|
+
setImportStatus(`Import failed: ${err.message}`, "error");
|
|
2509
|
+
} finally {
|
|
2510
|
+
discordImportBtn.disabled = false;
|
|
2511
|
+
discordImportFile.value = ""; // reset so re-selecting the same file fires change
|
|
2512
|
+
}
|
|
2513
|
+
}
|
|
2514
|
+
|
|
2515
|
+
// ---------- Event wiring ----------
|
|
2516
|
+
|
|
2517
|
+
projNewBtn.addEventListener("click", () => openProjectModal(null));
|
|
2518
|
+
|
|
2519
|
+
projectsList.addEventListener("click", (e) => {
|
|
2520
|
+
const actionBtn = e.target.closest("[data-proj-action]");
|
|
2521
|
+
if (actionBtn) {
|
|
2522
|
+
e.stopPropagation();
|
|
2523
|
+
const id = Number(actionBtn.dataset.projId);
|
|
2524
|
+
const action = actionBtn.dataset.projAction;
|
|
2525
|
+
if (action === "edit") {
|
|
2526
|
+
const p = state.projects.find((x) => x.id === id);
|
|
2527
|
+
if (p) openProjectModal(p);
|
|
2528
|
+
} else if (action === "docs") {
|
|
2529
|
+
openDocsPicker(id);
|
|
2530
|
+
}
|
|
2531
|
+
return;
|
|
2532
|
+
}
|
|
2533
|
+
const li = e.target.closest("li[data-proj-id]");
|
|
2534
|
+
if (li) {
|
|
2535
|
+
const id = Number(li.dataset.projId);
|
|
2536
|
+
// Toggle: clicking the active project deactivates it; otherwise activate.
|
|
2537
|
+
setActiveProject(state.activeProjectId === id ? null : id);
|
|
2538
|
+
}
|
|
2539
|
+
});
|
|
2540
|
+
|
|
2541
|
+
activeProjectClear.addEventListener("click", () => setActiveProject(null));
|
|
2542
|
+
|
|
2543
|
+
projectModalSave.addEventListener("click", saveProjectModal);
|
|
2544
|
+
projectModalCancel.addEventListener("click", closeProjectModal);
|
|
2545
|
+
if (gatewayModalSave) gatewayModalSave.addEventListener("click", saveGatewayModal);
|
|
2546
|
+
if (gatewayModalCancel) gatewayModalCancel.addEventListener("click", closeGatewayModal);
|
|
2547
|
+
projectModalDelete.addEventListener("click", deleteProjectFromModal);
|
|
2548
|
+
|
|
2549
|
+
projectDocsModalClose.addEventListener("click", closeDocsPicker);
|
|
2550
|
+
|
|
2551
|
+
discordImportBtn.addEventListener("click", () => discordImportFile.click());
|
|
2552
|
+
discordImportFile.addEventListener("change", (e) => {
|
|
2553
|
+
const file = e.target.files && e.target.files[0];
|
|
2554
|
+
if (file) handleDiscordImportFile(file);
|
|
2555
|
+
});
|
|
2556
|
+
|
|
2557
|
+
projectDocsModalList.addEventListener("change", (e) => {
|
|
2558
|
+
const cb = e.target.closest("[data-doc-toggle]");
|
|
2559
|
+
if (cb) handleDocsPickerToggle(Number(cb.dataset.docToggle), cb.checked);
|
|
2560
|
+
});
|
|
2561
|
+
|
|
2562
|
+
// Click-outside-modal close (handled via modal-backdrop element).
|
|
2563
|
+
document.addEventListener("click", (e) => {
|
|
2564
|
+
const closer = e.target.closest("[data-modal-close]");
|
|
2565
|
+
if (!closer) return;
|
|
2566
|
+
const modalId = closer.dataset.modalClose;
|
|
2567
|
+
if (modalId === "project-modal") closeProjectModal();
|
|
2568
|
+
else if (modalId === "project-docs-modal") closeDocsPicker();
|
|
2569
|
+
else if (modalId === "gateway-modal") closeGatewayModal();
|
|
2570
|
+
else if (modalId === "account-delete-modal") closeAccountDeleteModal();
|
|
2571
|
+
});
|
|
2572
|
+
|
|
2573
|
+
// Escape key closes any open modal.
|
|
2574
|
+
document.addEventListener("keydown", (e) => {
|
|
2575
|
+
if (e.key !== "Escape") return;
|
|
2576
|
+
if (!projectModal.hidden) closeProjectModal();
|
|
2577
|
+
else if (!projectDocsModal.hidden) closeDocsPicker();
|
|
2578
|
+
else if (gatewayModal && !gatewayModal.hidden) closeGatewayModal();
|
|
2579
|
+
else if (accountDeleteModal && !accountDeleteModal.hidden) closeAccountDeleteModal();
|
|
2580
|
+
});
|
|
2581
|
+
|
|
2582
|
+
// Submit project modal on Cmd/Ctrl+Enter inside any of its text inputs.
|
|
2583
|
+
[projectModalName, projectModalDesc, projectModalPrompt].forEach((el) => {
|
|
2584
|
+
el.addEventListener("keydown", (e) => {
|
|
2585
|
+
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
|
|
2586
|
+
e.preventDefault();
|
|
2587
|
+
saveProjectModal();
|
|
2588
|
+
}
|
|
2589
|
+
});
|
|
2590
|
+
});
|
|
2591
|
+
|
|
2592
|
+
// Initial load: fetch projects, restore active selection from localStorage.
|
|
2593
|
+
// Wrapped in an IIFE so it doesn't block the existing init flow if it errors.
|
|
2594
|
+
(async () => {
|
|
2595
|
+
try {
|
|
2596
|
+
await fetchProjects();
|
|
2597
|
+
const savedId = loadActiveProjectFromStorage();
|
|
2598
|
+
if (savedId && state.projects.some((p) => p.id === savedId)) {
|
|
2599
|
+
state.activeProjectId = savedId;
|
|
2600
|
+
} else if (savedId) {
|
|
2601
|
+
// Saved id doesn't match any current project; clear stale storage.
|
|
2602
|
+
saveActiveProjectToStorage(null);
|
|
2603
|
+
}
|
|
2604
|
+
renderProjectsList();
|
|
2605
|
+
renderActiveProjectChip();
|
|
2606
|
+
} catch (err) {
|
|
2607
|
+
projStatus.textContent = `Failed to load projects: ${err.message}`;
|
|
2608
|
+
projStatus.classList.add("error");
|
|
2609
|
+
}
|
|
2610
|
+
})();
|
|
2611
|
+
|
|
2612
|
+
// ---------- Move conversation to project (v0.20.2) ----------
|
|
2613
|
+
//
|
|
2614
|
+
// Per-conversation dropdown menu. Hover/click reveals the arrow button on a
|
|
2615
|
+
// conversation row; clicking opens a small dropdown listing all projects +
|
|
2616
|
+
// "(no project)" + the current project highlighted. Picking an option
|
|
2617
|
+
// PATCHes /api/conversations/:id/project and refreshes the conversation list.
|
|
2618
|
+
//
|
|
2619
|
+
// The dropdown is appended to <body> with absolute positioning so it isn't
|
|
2620
|
+
// clipped by the sidebar's overflow. Closes on outside click or Escape.
|
|
2621
|
+
|
|
2622
|
+
let moveMenuEl = null;
|
|
2623
|
+
|
|
2624
|
+
function closeMoveToProjectMenu() {
|
|
2625
|
+
if (moveMenuEl) {
|
|
2626
|
+
moveMenuEl.remove();
|
|
2627
|
+
moveMenuEl = null;
|
|
2628
|
+
}
|
|
2629
|
+
}
|
|
2630
|
+
|
|
2631
|
+
async function moveConversationToProject(convId, projectId) {
|
|
2632
|
+
try {
|
|
2633
|
+
await api(`/api/conversations/${encodeURIComponent(convId)}/project`, {
|
|
2634
|
+
method: "PATCH",
|
|
2635
|
+
body: JSON.stringify({ project_id: projectId }),
|
|
2636
|
+
});
|
|
2637
|
+
await loadConversations();
|
|
2638
|
+
} catch (err) {
|
|
2639
|
+
alert(`Failed to move conversation: ${err.message}`);
|
|
2640
|
+
}
|
|
2641
|
+
}
|
|
2642
|
+
|
|
2643
|
+
function openMoveToProjectMenu(anchorEl, convId) {
|
|
2644
|
+
closeMoveToProjectMenu();
|
|
2645
|
+
|
|
2646
|
+
// Resolve the conversation's current project id from the existing list
|
|
2647
|
+
// markup so we can highlight the current selection. The cheapest read is
|
|
2648
|
+
// the chip element rendered on the row; otherwise null (no current).
|
|
2649
|
+
const li = anchorEl.closest("li[data-conv-id]");
|
|
2650
|
+
const chip = li?.querySelector(".conv-proj-chip");
|
|
2651
|
+
const currentProjectName = chip && !chip.classList.contains("conv-proj-chip-stale")
|
|
2652
|
+
? chip.textContent.trim()
|
|
2653
|
+
: null;
|
|
2654
|
+
|
|
2655
|
+
moveMenuEl = document.createElement("div");
|
|
2656
|
+
moveMenuEl.className = "move-menu";
|
|
2657
|
+
moveMenuEl.setAttribute("role", "menu");
|
|
2658
|
+
|
|
2659
|
+
const rect = anchorEl.getBoundingClientRect();
|
|
2660
|
+
// Position below the button by default; flip up if there's not enough room.
|
|
2661
|
+
const spaceBelow = window.innerHeight - rect.bottom;
|
|
2662
|
+
const isFlipped = spaceBelow < 240 && rect.top > 240;
|
|
2663
|
+
moveMenuEl.style.position = "fixed";
|
|
2664
|
+
moveMenuEl.style.left = `${Math.min(rect.left, window.innerWidth - 220)}px`;
|
|
2665
|
+
if (isFlipped) {
|
|
2666
|
+
moveMenuEl.style.bottom = `${window.innerHeight - rect.top + 4}px`;
|
|
2667
|
+
} else {
|
|
2668
|
+
moveMenuEl.style.top = `${rect.bottom + 4}px`;
|
|
2669
|
+
}
|
|
2670
|
+
|
|
2671
|
+
const items = [
|
|
2672
|
+
{ value: null, label: "(no project)", isCurrent: !currentProjectName },
|
|
2673
|
+
...state.projects.map((p) => ({
|
|
2674
|
+
value: p.id,
|
|
2675
|
+
label: p.name,
|
|
2676
|
+
isCurrent: p.name === currentProjectName,
|
|
2677
|
+
})),
|
|
2678
|
+
];
|
|
2679
|
+
|
|
2680
|
+
moveMenuEl.innerHTML = items.map((it) => {
|
|
2681
|
+
const cls = "move-menu-item" + (it.isCurrent ? " current" : "");
|
|
2682
|
+
const id = it.value === null ? "" : String(it.value);
|
|
2683
|
+
return `<button type="button" class="${cls}" data-move-target="${id}">${escapeHtml(it.label)}</button>`;
|
|
2684
|
+
}).join("");
|
|
2685
|
+
|
|
2686
|
+
moveMenuEl.addEventListener("click", async (e) => {
|
|
2687
|
+
const btn = e.target.closest("[data-move-target]");
|
|
2688
|
+
if (!btn) return;
|
|
2689
|
+
const raw = btn.dataset.moveTarget;
|
|
2690
|
+
const target = raw === "" ? null : Number(raw);
|
|
2691
|
+
closeMoveToProjectMenu();
|
|
2692
|
+
await moveConversationToProject(convId, target);
|
|
2693
|
+
});
|
|
2694
|
+
|
|
2695
|
+
document.body.appendChild(moveMenuEl);
|
|
2696
|
+
|
|
2697
|
+
// Defer the outside-click listener registration to the next tick so the
|
|
2698
|
+
// click that opened the menu doesn't immediately close it.
|
|
2699
|
+
setTimeout(() => {
|
|
2700
|
+
document.addEventListener("click", onMoveMenuOutsideClick, { once: true });
|
|
2701
|
+
document.addEventListener("keydown", onMoveMenuKeydown, { once: true });
|
|
2702
|
+
}, 0);
|
|
2703
|
+
}
|
|
2704
|
+
|
|
2705
|
+
function onMoveMenuOutsideClick(e) {
|
|
2706
|
+
if (moveMenuEl && !moveMenuEl.contains(e.target)) {
|
|
2707
|
+
closeMoveToProjectMenu();
|
|
2708
|
+
} else if (moveMenuEl) {
|
|
2709
|
+
// Inside-menu click; the menu's own handler runs first and closes it,
|
|
2710
|
+
// but we may also re-register the listener for nested clicks.
|
|
2711
|
+
document.addEventListener("click", onMoveMenuOutsideClick, { once: true });
|
|
2712
|
+
}
|
|
2713
|
+
}
|
|
2714
|
+
|
|
2715
|
+
function onMoveMenuKeydown(e) {
|
|
2716
|
+
if (e.key === "Escape") closeMoveToProjectMenu();
|
|
2717
|
+
}
|
|
2718
|
+
|
|
2719
|
+
// ---------- #80 in-app account deletion (DELETE /api/account) ----------
|
|
2720
|
+
//
|
|
2721
|
+
// The #82 requirement is IN-APP deletion; an API-only route is half-shipped, so
|
|
2722
|
+
// the account menu gets a Delete-account affordance (public mode only) that
|
|
2723
|
+
// opens a confirm modal requiring password re-entry, then calls DELETE
|
|
2724
|
+
// /api/account. On success the server clears the session cookie; a reload lands
|
|
2725
|
+
// on the signup gate.
|
|
2726
|
+
const accountDelete = $("#account-delete");
|
|
2727
|
+
const accountDeleteModal = $("#account-delete-modal");
|
|
2728
|
+
const accountDeletePassword = $("#account-delete-password");
|
|
2729
|
+
const accountDeleteError = $("#account-delete-error");
|
|
2730
|
+
const accountDeleteConfirm = $("#account-delete-confirm");
|
|
2731
|
+
const accountDeleteCancel = $("#account-delete-cancel");
|
|
2732
|
+
|
|
2733
|
+
function openAccountDeleteModal() {
|
|
2734
|
+
if (!accountDeleteModal) return;
|
|
2735
|
+
if (accountDeleteError) { accountDeleteError.hidden = true; accountDeleteError.textContent = ""; }
|
|
2736
|
+
if (accountDeletePassword) accountDeletePassword.value = "";
|
|
2737
|
+
accountDeleteModal.hidden = false;
|
|
2738
|
+
if (accountDeletePassword) setTimeout(() => accountDeletePassword.focus(), 0);
|
|
2739
|
+
}
|
|
2740
|
+
function closeAccountDeleteModal() {
|
|
2741
|
+
if (accountDeleteModal) accountDeleteModal.hidden = true;
|
|
2742
|
+
}
|
|
2743
|
+
async function submitAccountDelete() {
|
|
2744
|
+
const password = accountDeletePassword ? accountDeletePassword.value : "";
|
|
2745
|
+
if (!password) {
|
|
2746
|
+
if (accountDeleteError) { accountDeleteError.textContent = "enter your password to confirm."; accountDeleteError.hidden = false; }
|
|
2747
|
+
return;
|
|
2748
|
+
}
|
|
2749
|
+
if (accountDeleteConfirm) accountDeleteConfirm.disabled = true;
|
|
2750
|
+
try {
|
|
2751
|
+
const res = await fetch("/api/account", {
|
|
2752
|
+
method: "DELETE",
|
|
2753
|
+
headers: { "Content-Type": "application/json" },
|
|
2754
|
+
body: JSON.stringify({ password }),
|
|
2755
|
+
});
|
|
2756
|
+
if (res.ok) {
|
|
2757
|
+
// Session cookie cleared server-side; reload drops to the signup gate.
|
|
2758
|
+
location.reload();
|
|
2759
|
+
return;
|
|
2760
|
+
}
|
|
2761
|
+
const body = await res.json().catch(() => ({}));
|
|
2762
|
+
if (accountDeleteError) {
|
|
2763
|
+
accountDeleteError.textContent = body.error || (res.status === 403 ? "incorrect password." : "could not delete account.");
|
|
2764
|
+
accountDeleteError.hidden = false;
|
|
2765
|
+
}
|
|
2766
|
+
} catch (err) {
|
|
2767
|
+
if (accountDeleteError) { accountDeleteError.textContent = "network error, please try again."; accountDeleteError.hidden = false; }
|
|
2768
|
+
} finally {
|
|
2769
|
+
if (accountDeleteConfirm) accountDeleteConfirm.disabled = false;
|
|
2770
|
+
}
|
|
2771
|
+
}
|
|
2772
|
+
if (accountDelete) accountDelete.addEventListener("click", () => {
|
|
2773
|
+
if (accountMenu) accountMenu.hidden = true;
|
|
2774
|
+
if (accountToggle) accountToggle.setAttribute("aria-expanded", "false");
|
|
2775
|
+
openAccountDeleteModal();
|
|
2776
|
+
});
|
|
2777
|
+
if (accountDeleteConfirm) accountDeleteConfirm.addEventListener("click", submitAccountDelete);
|
|
2778
|
+
if (accountDeleteCancel) accountDeleteCancel.addEventListener("click", closeAccountDeleteModal);
|