diff-chat 0.1.0__py3-none-any.whl
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.
- adapters/README.md +28 -0
- adapters/__init__.py +48 -0
- adapters/_base.py +102 -0
- adapters/_cli.py +405 -0
- adapters/claude.py +141 -0
- adapters/gemini.py +323 -0
- adapters/gpt.py +217 -0
- adapters/local.py +146 -0
- adapters/registry.py +33 -0
- api_fallback.py +189 -0
- app.py +827 -0
- app_preferences.py +205 -0
- archive_schema.py +142 -0
- attachments.py +129 -0
- chat_titles.py +60 -0
- connection_handoff.py +64 -0
- context_engine.py +256 -0
- conversation_actions.py +160 -0
- diff_chat-0.1.0.dist-info/METADATA +101 -0
- diff_chat-0.1.0.dist-info/RECORD +91 -0
- diff_chat-0.1.0.dist-info/WHEEL +4 -0
- diff_chat-0.1.0.dist-info/entry_points.txt +2 -0
- diff_chat-0.1.0.dist-info/licenses/LICENSE +21 -0
- diff_chat_assets/memory.example.md +1 -0
- diff_chat_assets/prompts/about_you_export.md +19 -0
- diff_chat_assets/settings.json +6 -0
- diff_chat_assets/static/about-you-parser.js +46 -0
- diff_chat_assets/static/about-you.js +171 -0
- diff_chat_assets/static/actions.css +275 -0
- diff_chat_assets/static/actions.js +650 -0
- diff_chat_assets/static/app.css +345 -0
- diff_chat_assets/static/app.js +1344 -0
- diff_chat_assets/static/attachments.js +80 -0
- diff_chat_assets/static/brand/favicon-32.png +0 -0
- diff_chat_assets/static/brand/icon.svg +11 -0
- diff_chat_assets/static/brand/wordmark-dark.svg +15 -0
- diff_chat_assets/static/brand/wordmark-light.svg +13 -0
- diff_chat_assets/static/characters/CREDITS.md +7 -0
- diff_chat_assets/static/characters/characters.css +37 -0
- diff_chat_assets/static/characters/claude.json +507 -0
- diff_chat_assets/static/characters/claude.png +0 -0
- diff_chat_assets/static/characters/claude.webp +0 -0
- diff_chat_assets/static/characters/gemini.json +54 -0
- diff_chat_assets/static/characters/gemini.png +0 -0
- diff_chat_assets/static/characters/gemini.webp +0 -0
- diff_chat_assets/static/characters/gpt.json +507 -0
- diff_chat_assets/static/characters/gpt.png +0 -0
- diff_chat_assets/static/characters/gpt.webp +0 -0
- diff_chat_assets/static/characters/local.json +387 -0
- diff_chat_assets/static/characters/local.png +0 -0
- diff_chat_assets/static/characters/local.webp +0 -0
- diff_chat_assets/static/characters/player.js +318 -0
- diff_chat_assets/static/chat-filing.js +84 -0
- diff_chat_assets/static/controls.js +194 -0
- diff_chat_assets/static/corners.css +59 -0
- diff_chat_assets/static/craft.css +246 -0
- diff_chat_assets/static/drafts.js +41 -0
- diff_chat_assets/static/index.html +208 -0
- diff_chat_assets/static/library.css +30 -0
- diff_chat_assets/static/library.js +181 -0
- diff_chat_assets/static/memory.js +81 -0
- diff_chat_assets/static/preference-dialog.js +21 -0
- diff_chat_assets/static/preferences.css +56 -0
- diff_chat_assets/static/session.js +46 -0
- diff_chat_assets/static/settings.css +111 -0
- diff_chat_assets/static/settings.js +463 -0
- diff_chat_assets/static/setup.js +238 -0
- diff_chat_assets/static/utility.js +64 -0
- diff_chat_assets/static/vendor/LICENSES.txt +531 -0
- diff_chat_assets/static/vendor/highlight.min.js +1262 -0
- diff_chat_assets/static/vendor/markdown-it.min.js +13 -0
- diff_chat_assets/static/vendor/plex-mono.woff2 +0 -0
- diff_chat_assets/static/vendor/plex-sans.woff2 +0 -0
- diff_launcher.py +93 -0
- discussion.py +239 -0
- history_search.py +68 -0
- library_manager.py +251 -0
- model_options.py +132 -0
- plan_usage.py +72 -0
- private_store.py +71 -0
- probe.py +195 -0
- runtime_paths.py +195 -0
- server_security.py +100 -0
- setup_status.py +123 -0
- shared_memory.py +189 -0
- storage.py +185 -0
- usage_budget.py +77 -0
- usage_claude.py +110 -0
- usage_codex.py +170 -0
- usage_gemini.py +70 -0
- utility_models.py +104 -0
|
@@ -0,0 +1,1344 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
|
|
3
|
+
const byId = (id) => document.getElementById(id);
|
|
4
|
+
const names = {me: "You"};
|
|
5
|
+
const models = [];
|
|
6
|
+
const registry = new Map();
|
|
7
|
+
const participantList = new Intl.ListFormat(undefined, {style:"long", type:"conjunction"});
|
|
8
|
+
|
|
9
|
+
function participantStyle(node, id) {
|
|
10
|
+
const participant = registry.get(id);
|
|
11
|
+
if (participant) {
|
|
12
|
+
node.dataset.participant = id;
|
|
13
|
+
const tones = (light, dark) => "light-dark(" + light + ", " + dark + ")";
|
|
14
|
+
node.style.setProperty("--model", tones(participant.color, participant.dark_color));
|
|
15
|
+
node.style.setProperty("--model-fill", tones(participant.fill || participant.color, participant.dark_fill || participant.dark_color));
|
|
16
|
+
} else {
|
|
17
|
+
delete node.dataset.participant;
|
|
18
|
+
node.style.removeProperty("--model");
|
|
19
|
+
node.style.removeProperty("--model-fill");
|
|
20
|
+
}
|
|
21
|
+
return node;
|
|
22
|
+
}
|
|
23
|
+
const outcomeLabels = {
|
|
24
|
+
agreed: "Agreement reached",
|
|
25
|
+
limit: "No agreement",
|
|
26
|
+
revised: "Earlier discussion revised",
|
|
27
|
+
stopped: "Discussion stopped",
|
|
28
|
+
error: "Discussion ended early",
|
|
29
|
+
interrupted: "Discussion interrupted",
|
|
30
|
+
};
|
|
31
|
+
const reader = byId("reader");
|
|
32
|
+
const entries = byId("entries");
|
|
33
|
+
const draft = byId("draft");
|
|
34
|
+
const mobile = matchMedia("(max-width: 699px)");
|
|
35
|
+
const wideInspector = matchMedia("(min-width: 1101px)");
|
|
36
|
+
const clock = new Intl.DateTimeFormat(undefined, { hour: "2-digit", minute: "2-digit", hourCycle: "h23" });
|
|
37
|
+
const dateLabel = new Intl.DateTimeFormat(undefined, { day: "numeric", month: "short", year: "numeric" });
|
|
38
|
+
const number = new Intl.NumberFormat();
|
|
39
|
+
const percentNumber = new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 });
|
|
40
|
+
const resetDate = new Intl.DateTimeFormat(undefined, { month: "short", day: "numeric" });
|
|
41
|
+
const drafts = createDraftStore();
|
|
42
|
+
const enabled = new Set();
|
|
43
|
+
const fields = new Map();
|
|
44
|
+
const macKeyboard = /Mac|iPhone|iPad/i.test(navigator.platform);
|
|
45
|
+
byId("search-shortcut").textContent = macKeyboard ? "⌘K" : "Ctrl K";
|
|
46
|
+
byId("search-chats").setAttribute("aria-keyshortcuts", macKeyboard ? "Meta+K" : "Control+K");
|
|
47
|
+
const discussionOutcomes = new Map();
|
|
48
|
+
let catalog = {};
|
|
49
|
+
let preferences = {};
|
|
50
|
+
let savedPreferences = {};
|
|
51
|
+
let preferenceWrites = Promise.resolve();
|
|
52
|
+
let webSearch = true;
|
|
53
|
+
let savedWebSearch = true;
|
|
54
|
+
let searchRevision = 0;
|
|
55
|
+
let usage = {};
|
|
56
|
+
let usageRequest = null;
|
|
57
|
+
let usageAttempt = 0;
|
|
58
|
+
let usageDirty = true;
|
|
59
|
+
let chat = null;
|
|
60
|
+
let chatList = [];
|
|
61
|
+
let threshold = 60000;
|
|
62
|
+
let slots = [];
|
|
63
|
+
let runId = null;
|
|
64
|
+
let activeDiscussion = null;
|
|
65
|
+
let activeKind = null;
|
|
66
|
+
let retryIndex = null;
|
|
67
|
+
let exporting = false;
|
|
68
|
+
let source = null;
|
|
69
|
+
let stopping = false;
|
|
70
|
+
let starting = false;
|
|
71
|
+
let navigating = false;
|
|
72
|
+
let navigationVersion = 0;
|
|
73
|
+
let followNewText = true;
|
|
74
|
+
let visibleRecords = [];
|
|
75
|
+
|
|
76
|
+
function setting(key, fallback) {
|
|
77
|
+
try { return localStorage.getItem("transcript." + key) ?? fallback; }
|
|
78
|
+
catch { return fallback; }
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
function remember(key, value) {
|
|
82
|
+
try { localStorage.setItem("transcript." + key, value); }
|
|
83
|
+
catch { /* The interface also works without browser storage. */ }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function element(tag, className, content) {
|
|
87
|
+
const node = document.createElement(tag);
|
|
88
|
+
if (className) node.className = className;
|
|
89
|
+
if (content !== undefined) node.textContent = content;
|
|
90
|
+
return node;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const markdown = window.markdownit({ html: false, breaks: true, linkify: true, typographer: false });
|
|
94
|
+
markdown.linkify.set({ fuzzyLink: false, fuzzyEmail: false });
|
|
95
|
+
// markdown-it normally emits inline text-align styles, which the local CSP blocks.
|
|
96
|
+
function renderTableCell(tokens, index, options, environment, renderer) {
|
|
97
|
+
const token = tokens[index];
|
|
98
|
+
const style = token.attrIndex("style");
|
|
99
|
+
if (style >= 0) {
|
|
100
|
+
const alignment = /^text-align:\s*(left|center|right);?$/.exec(token.attrs[style][1]);
|
|
101
|
+
if (alignment) token.attrs[style] = ["class", "align-" + alignment[1]];
|
|
102
|
+
}
|
|
103
|
+
return renderer.renderToken(tokens, index, options);
|
|
104
|
+
}
|
|
105
|
+
markdown.renderer.rules.th_open = renderTableCell;
|
|
106
|
+
markdown.renderer.rules.td_open = renderTableCell;
|
|
107
|
+
markdown.renderer.rules.image = (tokens, index) => {
|
|
108
|
+
const alt = tokens[index].content;
|
|
109
|
+
return markdown.utils.escapeHtml(alt || "[image]");
|
|
110
|
+
};
|
|
111
|
+
const standardLink = markdown.renderer.rules.link_open;
|
|
112
|
+
markdown.renderer.rules.link_open = (tokens, index, options, env, renderer) => {
|
|
113
|
+
const token = tokens[index];
|
|
114
|
+
const href = token.attrGet("href") || "";
|
|
115
|
+
if (!/^(https?:\/\/|mailto:)/i.test(href)) {
|
|
116
|
+
token.attrs = token.attrs.filter(([name]) => name !== "href");
|
|
117
|
+
}
|
|
118
|
+
token.attrSet("target", "_blank");
|
|
119
|
+
token.attrSet("rel", "noreferrer noopener");
|
|
120
|
+
return standardLink ? standardLink(tokens, index, options, env, renderer) : renderer.renderToken(tokens, index, options);
|
|
121
|
+
};
|
|
122
|
+
|
|
123
|
+
const quantityCharacters = /^[\d\s.,:/$€£¥%‰°≈~<>≤≥±+−–—()'-]+(?:[a-zµμ]{1,5}(?:\/[a-z]{1,5})?)?$/iu;
|
|
124
|
+
const scrollableTables = new ResizeObserver((changes) => {
|
|
125
|
+
for (const { target: wrapper } of changes) {
|
|
126
|
+
if (!wrapper.isConnected) {
|
|
127
|
+
scrollableTables.unobserve(wrapper);
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
if (wrapper.scrollWidth > wrapper.clientWidth + 1) wrapper.tabIndex = 0;
|
|
131
|
+
else wrapper.removeAttribute("tabindex");
|
|
132
|
+
}
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
function wrapTable(table) {
|
|
136
|
+
const bodyRows = table.tBodies[0] ? Array.from(table.tBodies[0].rows) : [];
|
|
137
|
+
for (const row of bodyRows) {
|
|
138
|
+
for (const cell of row.cells) {
|
|
139
|
+
const text = cell.textContent.trim();
|
|
140
|
+
if (text.length <= 24 && /\d/.test(text) && quantityCharacters.test(text)) {
|
|
141
|
+
cell.classList.add("quantity");
|
|
142
|
+
} else if (text.length > 55 && /\s/.test(text)) {
|
|
143
|
+
cell.classList.add("narrative-cell");
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
const headers = Array.from(table.tHead?.rows[0]?.cells || []);
|
|
148
|
+
for (const [index, header] of headers.entries()) {
|
|
149
|
+
header.scope = "col";
|
|
150
|
+
const populated = bodyRows.map((row) => row.cells[index]).filter((cell) => cell?.textContent.trim());
|
|
151
|
+
if (populated.length && populated.every((cell) => cell.classList.contains("quantity"))) {
|
|
152
|
+
for (const cell of [header, ...populated]) cell.classList.add("numeric-column");
|
|
153
|
+
if (header.textContent.trim().length <= 24) header.classList.add("compact-heading");
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
const scroller = element("div", "table-scroll");
|
|
157
|
+
scroller.setAttribute("role", "region");
|
|
158
|
+
scroller.setAttribute("aria-label", "Table" + (headers.length ? " — " + headers.map((cell) => cell.textContent.trim()).join(", ") : ""));
|
|
159
|
+
table.replaceWith(scroller);
|
|
160
|
+
scroller.append(table);
|
|
161
|
+
scrollableTables.observe(scroller);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function fillProse(node, content) {
|
|
165
|
+
for (const oldTable of node.querySelectorAll(".table-scroll")) scrollableTables.unobserve(oldTable);
|
|
166
|
+
node.innerHTML = markdown.render(content);
|
|
167
|
+
for (const pre of node.querySelectorAll("pre")) {
|
|
168
|
+
const code = pre.querySelector("code");
|
|
169
|
+
if (!code) continue;
|
|
170
|
+
const languageClass = Array.from(code.classList).find((name) => name.startsWith("language-"));
|
|
171
|
+
const language = languageClass ? languageClass.slice(9) : "";
|
|
172
|
+
const text = code.textContent;
|
|
173
|
+
// A large pasted log can use the ordinary, unhighlighted code display.
|
|
174
|
+
if (language && text.length <= 100000 && window.hljs?.getLanguage(language)) {
|
|
175
|
+
code.innerHTML = window.hljs.highlight(text, { language, ignoreIllegals: true }).value;
|
|
176
|
+
}
|
|
177
|
+
const wrapper = element("div", "code-block");
|
|
178
|
+
const tools = element("div", "code-tools");
|
|
179
|
+
const copy = element("button", "copy", "copy");
|
|
180
|
+
copy.type = "button";
|
|
181
|
+
copy.setAttribute("aria-label", "Copy code");
|
|
182
|
+
tools.append(element("span", "", language), copy);
|
|
183
|
+
pre.replaceWith(wrapper);
|
|
184
|
+
wrapper.append(tools, pre);
|
|
185
|
+
}
|
|
186
|
+
for (const table of node.querySelectorAll("table")) wrapTable(table);
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
// Batch partial events into readable chunks. Completed Markdown blocks are typeset once.
|
|
190
|
+
function streamProse(record, text) {
|
|
191
|
+
if (!record.stream || !text.startsWith(record.stream.shown)) {
|
|
192
|
+
clearTimeout(record.stream?.timer);
|
|
193
|
+
record.prose.replaceChildren();
|
|
194
|
+
record.stream = {shown: "", pending: "", fixed: 0, tail: element("div", "stream-tail"), timer: 0};
|
|
195
|
+
record.prose.append(record.stream.tail);
|
|
196
|
+
}
|
|
197
|
+
const stream = record.stream;
|
|
198
|
+
stream.pending = text;
|
|
199
|
+
if (stream.timer) return;
|
|
200
|
+
function paint() {
|
|
201
|
+
stream.timer = 0;
|
|
202
|
+
if (record.stream !== stream || !record.article.isConnected) return;
|
|
203
|
+
const value = stream.pending;
|
|
204
|
+
// Keep an open code fence intact even when it contains blank lines.
|
|
205
|
+
const rest = value.slice(stream.fixed);
|
|
206
|
+
let boundary = rest.lastIndexOf("\n\n");
|
|
207
|
+
if (boundary >= 0 && (rest.slice(0, boundary).match(/^\s*(?:```|~~~)/gm) || []).length % 2 === 0) {
|
|
208
|
+
boundary += 2;
|
|
209
|
+
const block = element("div", "stream-block");
|
|
210
|
+
fillProse(block, rest.slice(0,boundary));
|
|
211
|
+
stream.tail.before(block);
|
|
212
|
+
stream.fixed += boundary;
|
|
213
|
+
stream.tail.replaceChildren();
|
|
214
|
+
stream.shown = value.slice(0, stream.fixed);
|
|
215
|
+
}
|
|
216
|
+
const piece = value.slice(stream.shown.length);
|
|
217
|
+
if (piece) stream.tail.append(element("span", "stream-piece", piece));
|
|
218
|
+
stream.shown = value;
|
|
219
|
+
if (followNewText) reader.scrollTop = reader.scrollHeight;
|
|
220
|
+
}
|
|
221
|
+
if (!stream.shown) paint();
|
|
222
|
+
else stream.timer = setTimeout(paint, 100);
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function copyMarkdownFallback(button, text) {
|
|
226
|
+
const article = button.closest(".message");
|
|
227
|
+
article.querySelector(".manual-copy")?.remove();
|
|
228
|
+
const panel = element("div", "manual-copy");
|
|
229
|
+
const field = document.createElement("textarea");
|
|
230
|
+
field.readOnly = true;
|
|
231
|
+
field.setAttribute("aria-label", "Answer Markdown to copy");
|
|
232
|
+
field.value = text;
|
|
233
|
+
const done = element("button", "quiet-button", "Done");
|
|
234
|
+
done.type = "button";
|
|
235
|
+
function close() { panel.remove(); button.focus({ preventScroll: true }); }
|
|
236
|
+
done.addEventListener("click", close);
|
|
237
|
+
field.addEventListener("keydown", (event) => { if (event.key === "Escape") close(); });
|
|
238
|
+
panel.append(field, done);
|
|
239
|
+
article.append(panel);
|
|
240
|
+
field.focus({ preventScroll: true });
|
|
241
|
+
field.select();
|
|
242
|
+
try {
|
|
243
|
+
if (document.execCommand("copy")) {
|
|
244
|
+
close();
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
} catch { /* Leave the raw Markdown selected for manual copying. */ }
|
|
248
|
+
field.scrollIntoView({ block: "nearest" });
|
|
249
|
+
return false;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
async function copyText(button, text, fallback, isAnswer) {
|
|
253
|
+
const subject = isAnswer ? "Answer" : "Code";
|
|
254
|
+
try {
|
|
255
|
+
await navigator.clipboard.writeText(text);
|
|
256
|
+
button.textContent = isAnswer ? "Copied" : "copied";
|
|
257
|
+
byId("announcement").textContent = subject + " copied.";
|
|
258
|
+
} catch {
|
|
259
|
+
if (isAnswer && copyMarkdownFallback(button, text)) {
|
|
260
|
+
byId("announcement").textContent = "Answer copied.";
|
|
261
|
+
button.textContent = "Copied";
|
|
262
|
+
} else {
|
|
263
|
+
if (!isAnswer) {
|
|
264
|
+
const range = document.createRange();
|
|
265
|
+
range.selectNodeContents(fallback);
|
|
266
|
+
const selection = window.getSelection();
|
|
267
|
+
selection.removeAllRanges();
|
|
268
|
+
selection.addRange(range);
|
|
269
|
+
}
|
|
270
|
+
byId("announcement").textContent = subject + " selected. Use your keyboard’s copy command.";
|
|
271
|
+
button.textContent = isAnswer ? "Selected" : "selected";
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
setTimeout(() => {
|
|
275
|
+
if (isAnswer && window.chatActions) button.replaceChildren(window.chatActions.icon("Copy"));
|
|
276
|
+
else button.textContent = "copy";
|
|
277
|
+
}, 1600);
|
|
278
|
+
}
|
|
279
|
+
entries.addEventListener("click", (event) => {
|
|
280
|
+
const button = event.target.closest("button.copy");
|
|
281
|
+
if (!button) return;
|
|
282
|
+
const code = button.closest(".code-block").querySelector("code");
|
|
283
|
+
copyText(button, code.textContent, code, false);
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
function feedback(message = "", retry = false) {
|
|
287
|
+
const node = byId("feedback");
|
|
288
|
+
node.textContent = message;
|
|
289
|
+
node.hidden = !message;
|
|
290
|
+
if (retry) {
|
|
291
|
+
const button = element("button", "", "Retry");
|
|
292
|
+
button.type = "button";
|
|
293
|
+
button.addEventListener("click", () => openChat());
|
|
294
|
+
node.append(" ", button);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
async function api(path, body, method = "POST") {
|
|
299
|
+
const options = body === undefined ? {} : {
|
|
300
|
+
method,
|
|
301
|
+
headers: { "Content-Type": "application/json" },
|
|
302
|
+
body: JSON.stringify(body),
|
|
303
|
+
};
|
|
304
|
+
let response;
|
|
305
|
+
try { response = await fetch(path, options); }
|
|
306
|
+
catch { throw new Error("Cannot reach the local app. Check the server terminal."); }
|
|
307
|
+
if (!response.ok) {
|
|
308
|
+
const result = await response.json().catch(() => ({}));
|
|
309
|
+
const error = new Error(typeof result.detail === "string" ? result.detail : "The local app returned error " + response.status + ".");
|
|
310
|
+
error.status = response.status;
|
|
311
|
+
throw error;
|
|
312
|
+
}
|
|
313
|
+
return response.json();
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function applyTheme(value) {
|
|
317
|
+
const media = {system: "(prefers-color-scheme: dark)", light: "not all", dark: "all", codex: "all"};
|
|
318
|
+
const selected = Object.hasOwn(media, value) ? value : "system";
|
|
319
|
+
document.documentElement.dataset.theme = selected;
|
|
320
|
+
byId("dark-wordmark").media = media[selected];
|
|
321
|
+
}
|
|
322
|
+
applyTheme(setting("theme", "system"));
|
|
323
|
+
document.documentElement.dataset.font = setting("font", "theme");
|
|
324
|
+
document.documentElement.dataset.accent = setting("accent", "neutral");
|
|
325
|
+
|
|
326
|
+
function showPanel(open, moveFocus = false) {
|
|
327
|
+
const desk = byId("desk");
|
|
328
|
+
desk.classList.toggle("panel-hidden", !open);
|
|
329
|
+
desk.classList.toggle("mobile-open", mobile.matches && open);
|
|
330
|
+
document.querySelector(".workspace").inert = mobile.matches && open;
|
|
331
|
+
byId("open-chats").setAttribute("aria-expanded", String(open));
|
|
332
|
+
if (!mobile.matches) remember("panel", open ? "open" : "closed");
|
|
333
|
+
if (moveFocus) byId(open ? "hide-chats" : "open-chats").focus();
|
|
334
|
+
}
|
|
335
|
+
function defaultPanel() { showPanel(!mobile.matches && setting("panel", "open") === "open"); }
|
|
336
|
+
defaultPanel();
|
|
337
|
+
mobile.addEventListener("change", defaultPanel);
|
|
338
|
+
byId("open-chats").addEventListener("click", () => showPanel(true, true));
|
|
339
|
+
byId("hide-chats").addEventListener("click", () => showPanel(false, true));
|
|
340
|
+
document.addEventListener("keydown", (event) => {
|
|
341
|
+
if (document.querySelector("dialog[open], :popover-open")) return;
|
|
342
|
+
if (event.key === "Escape" && mobile.matches && !byId("desk").classList.contains("panel-hidden")) showPanel(false, true);
|
|
343
|
+
});
|
|
344
|
+
document.addEventListener("pointerdown", (event) => {
|
|
345
|
+
if (document.querySelector("dialog[open]")) return;
|
|
346
|
+
if (mobile.matches && byId("desk").classList.contains("mobile-open") && !byId("library").contains(event.target)) showPanel(false, true);
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
function showInspector(open, moveFocus = false) {
|
|
350
|
+
byId("inspector").hidden = !open;
|
|
351
|
+
byId("stage").classList.toggle("inspector-open", open);
|
|
352
|
+
byId("inspect").setAttribute("aria-expanded", String(open));
|
|
353
|
+
if (wideInspector.matches) remember("inspector", open ? "open" : "closed");
|
|
354
|
+
if (moveFocus) byId(open ? "close-inspector" : "inspect").focus();
|
|
355
|
+
if (open && fields.size) refreshUsage();
|
|
356
|
+
}
|
|
357
|
+
function defaultInspector() { showInspector(wideInspector.matches && setting("inspector", "open") === "open"); }
|
|
358
|
+
defaultInspector();
|
|
359
|
+
wideInspector.addEventListener("change", defaultInspector);
|
|
360
|
+
byId("inspect").addEventListener("click", () => showInspector(byId("inspector").hidden, true));
|
|
361
|
+
byId("close-inspector").addEventListener("click", () => showInspector(false, true));
|
|
362
|
+
document.addEventListener("keydown", (event) => {
|
|
363
|
+
if (document.querySelector("dialog[open], :popover-open")) return;
|
|
364
|
+
if (event.key === "Escape" && !byId("inspector").hidden && (!wideInspector.matches || byId("inspector").contains(document.activeElement))) showInspector(false, true);
|
|
365
|
+
});
|
|
366
|
+
document.addEventListener("pointerdown", (event) => {
|
|
367
|
+
if (document.querySelector("dialog[open]") || event.target.closest("#reply-actions")) return;
|
|
368
|
+
if (!wideInspector.matches && !byId("inspector").hidden && !byId("inspector").contains(event.target) && !event.target.closest(".select-popover") && !byId("inspect").contains(event.target)) showInspector(false);
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
function effortLabel(value) {
|
|
372
|
+
if (!value) return "";
|
|
373
|
+
if (value === "xhigh") return "Extra high";
|
|
374
|
+
return value.charAt(0).toUpperCase() + value.slice(1);
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function resolveChoice(provider, choice = {}) {
|
|
378
|
+
const group = catalog[provider];
|
|
379
|
+
if (!group?.models.length) return null;
|
|
380
|
+
const model = group.models.find((item) => item.id === choice.model)
|
|
381
|
+
|| group.models.find((item) => item.id === group.default_model) || group.models[0];
|
|
382
|
+
const effort = model.efforts?.includes(choice.effort) ? choice.effort : model.default_effort || "";
|
|
383
|
+
return { model: model.id, effort };
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
function loadPreferences(next) {
|
|
387
|
+
preferences = {};
|
|
388
|
+
for (const provider of models) {
|
|
389
|
+
if (catalog[provider]?.disconnected) {
|
|
390
|
+
enabled.delete(provider);
|
|
391
|
+
remember("enable." + provider, "no");
|
|
392
|
+
fields.get(provider).section.open = false;
|
|
393
|
+
}
|
|
394
|
+
const choice = resolveChoice(provider, next?.[provider]);
|
|
395
|
+
if (choice) preferences[provider] = choice;
|
|
396
|
+
}
|
|
397
|
+
savedPreferences = { ...preferences };
|
|
398
|
+
renderPreferences();
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function choose(provider, value) {
|
|
402
|
+
if (!chat || navigating || starting) return;
|
|
403
|
+
const chatId = chat.id;
|
|
404
|
+
const choice = resolveChoice(provider, value);
|
|
405
|
+
if (!choice) return;
|
|
406
|
+
preferences[provider] = choice;
|
|
407
|
+
renderPreferences();
|
|
408
|
+
// Preserve edit order even when a slow write overlaps a model or effort change.
|
|
409
|
+
preferenceWrites = preferenceWrites.then(async () => {
|
|
410
|
+
try {
|
|
411
|
+
const saved = await api("/api/chats/" + chatId + "/preferences", { preferences: { [provider]: choice } }, "PATCH");
|
|
412
|
+
savedPreferences[provider] = saved.preferences[provider];
|
|
413
|
+
} catch (error) {
|
|
414
|
+
if (preferences[provider] === choice) preferences[provider] = savedPreferences[provider];
|
|
415
|
+
renderPreferences();
|
|
416
|
+
feedback("Could not save " + names[provider] + " settings. " + error.message);
|
|
417
|
+
}
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
byId("web-search").addEventListener("click", () => {
|
|
422
|
+
if (!chat || navigating || starting) return;
|
|
423
|
+
const chatId = chat.id;
|
|
424
|
+
const revision = ++searchRevision;
|
|
425
|
+
const enabled = !webSearch;
|
|
426
|
+
webSearch = enabled;
|
|
427
|
+
updateControls();
|
|
428
|
+
preferenceWrites = preferenceWrites.then(async () => {
|
|
429
|
+
try {
|
|
430
|
+
const result = await api("/api/chats/" + chatId + "/web-search", { enabled }, "PATCH");
|
|
431
|
+
savedWebSearch = result.web_search;
|
|
432
|
+
} catch (error) {
|
|
433
|
+
if (revision === searchRevision) webSearch = savedWebSearch;
|
|
434
|
+
updateControls();
|
|
435
|
+
feedback("Could not save web search settings. " + error.message);
|
|
436
|
+
}
|
|
437
|
+
});
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
function makeField(section, provider, key, labelText) {
|
|
441
|
+
const row = element("div", "model-field");
|
|
442
|
+
const label = element("label", "", labelText);
|
|
443
|
+
const wrap = element("span", "select-wrap");
|
|
444
|
+
const select = element("select");
|
|
445
|
+
select.id = key + "-" + provider;
|
|
446
|
+
label.htmlFor = select.id;
|
|
447
|
+
select.setAttribute("aria-label", names[provider] + " " + labelText.toLowerCase());
|
|
448
|
+
select.addEventListener("change", () => choose(provider, { ...preferences[provider], [key]: select.value }));
|
|
449
|
+
wrap.append(select);
|
|
450
|
+
row.append(label, wrap);
|
|
451
|
+
section.append(row);
|
|
452
|
+
return select;
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function createFields(provider) {
|
|
456
|
+
const section = participantStyle(element("details", "model-section " + provider), provider);
|
|
457
|
+
section.open = enabled.has(provider);
|
|
458
|
+
const heading = element("summary", "model-section-head");
|
|
459
|
+
heading.append(element("h3", "", names[provider]));
|
|
460
|
+
window.DiffCharacters?.panel(heading, provider);
|
|
461
|
+
heading.append(window.diffIcon("chevron"));
|
|
462
|
+
section.append(heading);
|
|
463
|
+
const model = makeField(section, provider, "model", "Model");
|
|
464
|
+
const effort = makeField(section, provider, "effort", "Reasoning");
|
|
465
|
+
const detail = element("p", "catalog-detail");
|
|
466
|
+
section.append(detail);
|
|
467
|
+
const plan = element("section", "account-usage");
|
|
468
|
+
const planHead = element("div", "plan-head");
|
|
469
|
+
const planTitle = element("h4", "", "Plan remaining");
|
|
470
|
+
planTitle.id = "plan-" + provider;
|
|
471
|
+
plan.setAttribute("aria-labelledby", planTitle.id);
|
|
472
|
+
const asOf = element("time", "usage-asof");
|
|
473
|
+
const readings = element("div", "readings");
|
|
474
|
+
planHead.append(planTitle, asOf);
|
|
475
|
+
readings.append(element("p", "usage-note", "Checking usage…"));
|
|
476
|
+
plan.append(planHead, readings);
|
|
477
|
+
section.append(plan);
|
|
478
|
+
byId("model-fields").append(section);
|
|
479
|
+
const summary = element("span", "choice-summary");
|
|
480
|
+
byId("toggle-" + provider).append(summary);
|
|
481
|
+
fields.set(provider, {section, model, effort, detail, summary, asOf, readings, planHead});
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
function localMoment(date) {
|
|
485
|
+
const today = new Date();
|
|
486
|
+
if (date.toDateString() === today.toDateString()) return "today at " + clock.format(date);
|
|
487
|
+
const tomorrow = new Date(today);
|
|
488
|
+
tomorrow.setDate(today.getDate() + 1);
|
|
489
|
+
if (date.toDateString() === tomorrow.toDateString()) return "tomorrow at " + clock.format(date);
|
|
490
|
+
const day = date.getFullYear() === today.getFullYear() ? resetDate.format(date) : dateLabel.format(date);
|
|
491
|
+
return day + " at " + clock.format(date);
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
function renderUsage(provider, transportFailed = false) {
|
|
495
|
+
const { readings, asOf, planHead } = fields.get(provider);
|
|
496
|
+
const note = catalog[provider]?.disconnected || usage[provider]?.status === "disconnected"
|
|
497
|
+
? "Disconnected from diff." : registry.get(provider).usage_note;
|
|
498
|
+
if (note) {
|
|
499
|
+
planHead.hidden = true;
|
|
500
|
+
readings.replaceChildren(element("p", "usage-note", note));
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
planHead.hidden = false;
|
|
504
|
+
const result = usage[provider];
|
|
505
|
+
const checked = Date.parse(result?.checked_at);
|
|
506
|
+
asOf.hidden = !Number.isFinite(checked);
|
|
507
|
+
if (!asOf.hidden) {
|
|
508
|
+
const date = new Date(checked);
|
|
509
|
+
asOf.dateTime = result.checked_at;
|
|
510
|
+
asOf.title = "Last checked " + date.toLocaleString();
|
|
511
|
+
asOf.textContent = "As of " + (date.toDateString() === new Date().toDateString() ? clock.format(date) : resetDate.format(date));
|
|
512
|
+
}
|
|
513
|
+
const fragment = document.createDocumentFragment();
|
|
514
|
+
const windows = Array.isArray(result?.windows) ? result.windows : [];
|
|
515
|
+
for (const item of windows) {
|
|
516
|
+
const value = item?.remaining_percent;
|
|
517
|
+
if (!Number.isFinite(value) || value < 0 || value > 100 || !item.label) continue;
|
|
518
|
+
const percentage = percentNumber.format(value) + "%";
|
|
519
|
+
const row = element("div", "usage-window");
|
|
520
|
+
const caption = element("div", "usage-caption");
|
|
521
|
+
caption.append(element("span", "", item.label), element("span", "percentage", percentage));
|
|
522
|
+
const bar = element("progress", "usage-bar");
|
|
523
|
+
bar.max = 100;
|
|
524
|
+
bar.value = value;
|
|
525
|
+
bar.setAttribute("aria-label", names[provider] + " " + item.label + " remaining");
|
|
526
|
+
bar.setAttribute("aria-valuetext", percentage + " remaining");
|
|
527
|
+
row.append(caption, bar);
|
|
528
|
+
const reset = Date.parse(item.reset_at);
|
|
529
|
+
if (Number.isFinite(reset)) {
|
|
530
|
+
const date = new Date(reset);
|
|
531
|
+
const note = element("time", "usage-reset", (reset < Date.now() ? "Reset due " : "Resets ") + localMoment(date));
|
|
532
|
+
note.dateTime = item.reset_at;
|
|
533
|
+
note.title = date.toLocaleString();
|
|
534
|
+
row.append(note);
|
|
535
|
+
}
|
|
536
|
+
fragment.append(row);
|
|
537
|
+
}
|
|
538
|
+
const hasWindows = Boolean(fragment.childElementCount);
|
|
539
|
+
let detail = result?.detail;
|
|
540
|
+
if (transportFailed) detail = hasWindows ? "Refresh failed. Showing the last reading." : "Could not reach the usage service.";
|
|
541
|
+
if (!detail && !hasWindows) detail = "Usage is unavailable.";
|
|
542
|
+
if (!detail && result?.status === "unavailable") detail = "Showing the last reading.";
|
|
543
|
+
if (detail) fragment.append(element("p", "usage-note", detail));
|
|
544
|
+
readings.replaceChildren(fragment);
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function refreshUsage(manual = false) {
|
|
548
|
+
if (document.hidden || byId("inspector").hidden || usageRequest) return;
|
|
549
|
+
if (!manual && !usageDirty && Date.now() - usageAttempt < (window.diffSettings?.usage_refresh || 120) * 1000) return;
|
|
550
|
+
usageDirty = false;
|
|
551
|
+
usageAttempt = Date.now();
|
|
552
|
+
const refresh = byId("refresh-usage");
|
|
553
|
+
refresh.disabled = true;
|
|
554
|
+
refresh.textContent = "Checking usage…";
|
|
555
|
+
usageRequest = api("/api/usage" + (manual ? "?refresh=true" : ""))
|
|
556
|
+
.then((result) => {
|
|
557
|
+
usage = result;
|
|
558
|
+
for (const provider of models) renderUsage(provider);
|
|
559
|
+
})
|
|
560
|
+
.catch(() => {
|
|
561
|
+
for (const provider of models) renderUsage(provider, true);
|
|
562
|
+
})
|
|
563
|
+
.finally(() => {
|
|
564
|
+
usageRequest = null;
|
|
565
|
+
refresh.disabled = false;
|
|
566
|
+
refresh.textContent = "Refresh usage";
|
|
567
|
+
if (usageDirty) refreshUsage();
|
|
568
|
+
});
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
byId("refresh-usage").addEventListener("click", () => refreshUsage(true));
|
|
572
|
+
document.addEventListener("visibilitychange", () => refreshUsage());
|
|
573
|
+
setInterval(() => refreshUsage(), 15000);
|
|
574
|
+
|
|
575
|
+
function fillOptions(select, options, value) {
|
|
576
|
+
select.replaceChildren(...options.map(([id, label]) => new Option(label, id)));
|
|
577
|
+
select.value = value;
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
function renderPreferences() {
|
|
581
|
+
for (const provider of models) {
|
|
582
|
+
const ui = fields.get(provider);
|
|
583
|
+
const group = catalog[provider];
|
|
584
|
+
const choice = preferences[provider];
|
|
585
|
+
const model = group?.models.find((item) => item.id === choice?.model);
|
|
586
|
+
const title = model ? [model.label, registry.get(provider).capabilities.reasoning_levels && effortLabel(choice.effort)].filter(Boolean).join(" · ") : "";
|
|
587
|
+
ui.summary.textContent = title;
|
|
588
|
+
byId("toggle-" + provider).title = [names[provider], title, "Include in the next turn"].filter(Boolean).join(" · ");
|
|
589
|
+
fillOptions(ui.model, model ? group.models.map((item) => [item.id, item.label]) : [["", "Unavailable"]], choice?.model || "");
|
|
590
|
+
fillOptions(ui.effort, model ? (model.efforts || []).map((value) => [value, effortLabel(value)]) : [["", "Unavailable"]], choice?.effort || "");
|
|
591
|
+
ui.effort.closest(".model-field").hidden = !registry.get(provider).capabilities.reasoning_levels || !ui.effort.options.length;
|
|
592
|
+
ui.detail.hidden = Boolean(model) || !chat;
|
|
593
|
+
ui.detail.textContent = model ? "" : group?.detail || "Model choices are unavailable.";
|
|
594
|
+
}
|
|
595
|
+
updateControls();
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
function dayGroup(date) {
|
|
599
|
+
const today = new Date();
|
|
600
|
+
if (date.toDateString() === today.toDateString()) return "Today";
|
|
601
|
+
today.setDate(today.getDate() - 1);
|
|
602
|
+
if (date.toDateString() === today.toDateString()) return "Yesterday";
|
|
603
|
+
return dateLabel.format(date);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
function renderChatList() {
|
|
607
|
+
const list = byId("chat-list");
|
|
608
|
+
const focusedId = list.contains(document.activeElement) && document.activeElement.dataset.id;
|
|
609
|
+
const fragment = document.createDocumentFragment();
|
|
610
|
+
let group, previous;
|
|
611
|
+
for (const item of [...chatList].sort((a, b) => Number(Boolean(b.pinned)) - Number(Boolean(a.pinned)))) {
|
|
612
|
+
const date = new Date(item.updated_at);
|
|
613
|
+
const validDate = Number.isFinite(date.getTime());
|
|
614
|
+
const label = item.pinned ? "Pinned" : validDate ? dayGroup(date) : "Unreadable";
|
|
615
|
+
if (label !== previous) {
|
|
616
|
+
group = element("section", "list-group");
|
|
617
|
+
group.append(element("h3", "list-heading", label));
|
|
618
|
+
fragment.append(group);
|
|
619
|
+
previous = label;
|
|
620
|
+
}
|
|
621
|
+
const button = element("button", "chat-link");
|
|
622
|
+
button.type = "button";
|
|
623
|
+
button.title = item.title;
|
|
624
|
+
button.dataset.id = item.id;
|
|
625
|
+
if (item.id === chat?.id) button.setAttribute("aria-current", "page");
|
|
626
|
+
button.append(element("span", "list-name", item.title));
|
|
627
|
+
if (validDate) {
|
|
628
|
+
const time = element("time", "list-time", clock.format(date));
|
|
629
|
+
time.dateTime = item.updated_at;
|
|
630
|
+
button.append(time);
|
|
631
|
+
}
|
|
632
|
+
const row = element("div", "chat-file-row");
|
|
633
|
+
row.append(button);
|
|
634
|
+
window.addChatMenu?.(row, item);
|
|
635
|
+
group.append(row);
|
|
636
|
+
}
|
|
637
|
+
list.replaceChildren(fragment);
|
|
638
|
+
if (focusedId) Array.from(list.querySelectorAll("button")).find((button) => button.dataset.id === focusedId)?.focus();
|
|
639
|
+
}
|
|
640
|
+
byId("chat-list").addEventListener("click", (event) => {
|
|
641
|
+
const button = event.target.closest("button[data-id]");
|
|
642
|
+
if (!button || starting) return;
|
|
643
|
+
if (mobile.matches) showPanel(false, true);
|
|
644
|
+
openChat(button.dataset.id);
|
|
645
|
+
});
|
|
646
|
+
|
|
647
|
+
function updateIndex() {
|
|
648
|
+
const brief = { id: chat.id, title: chat.title, updated_at: chat.updated_at, chars: chat.chars, pinned: !!chat.pinned };
|
|
649
|
+
const previous = chatList.find((item) => item.id === chat.id);
|
|
650
|
+
if (!previous || previous.updated_at !== brief.updated_at || previous.title !== brief.title) {
|
|
651
|
+
chatList = chatList.filter((item) => item.id !== chat.id);
|
|
652
|
+
chatList.push(brief);
|
|
653
|
+
chatList.sort((a, b) => b.updated_at.localeCompare(a.updated_at));
|
|
654
|
+
renderChatList();
|
|
655
|
+
}
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
function updateControls() {
|
|
659
|
+
const waiting = !chat || navigating || starting || Boolean(runId);
|
|
660
|
+
const recipients = models.filter(model => enabled.has(model)).map(model => names[model]);
|
|
661
|
+
byId("empty").textContent = recipients.length ? "Send a message to start the conversation." : "Choose a participant to start the conversation.";
|
|
662
|
+
draft.placeholder = recipients.length ? "Message " + participantList.format(recipients) + "…" : "Choose a participant…";
|
|
663
|
+
byId("new-chat").disabled = !chat || navigating || starting;
|
|
664
|
+
byId("open-memory").disabled = !chat || navigating;
|
|
665
|
+
byId("open-utility").disabled = !chat || navigating;
|
|
666
|
+
byId("export-chat").disabled = !chat?.messages.length || navigating || exporting;
|
|
667
|
+
draft.disabled = !chat || navigating;
|
|
668
|
+
byId("send").disabled = waiting || !enabled.size || !draft.value.trim();
|
|
669
|
+
window.chatActions?.refresh();
|
|
670
|
+
byId("carry").disabled = waiting;
|
|
671
|
+
byId("stop").hidden = !runId || activeKind === "discuss";
|
|
672
|
+
byId("stop").disabled = !runId || stopping || navigating;
|
|
673
|
+
byId("web-search").disabled = !chat || navigating || starting || !models.some(id => enabled.has(id) && registry.get(id).capabilities.web_search);
|
|
674
|
+
byId("web-search").setAttribute("aria-checked", String(webSearch));
|
|
675
|
+
byId("search-state").textContent = webSearch ? "On" : "Off";
|
|
676
|
+
for (const model of models) {
|
|
677
|
+
const on = enabled.has(model);
|
|
678
|
+
byId("toggle-" + model).setAttribute("aria-pressed", String(on));
|
|
679
|
+
const ui = fields.get(model);
|
|
680
|
+
ui.model.disabled = !preferences[model] || navigating || starting;
|
|
681
|
+
ui.effort.disabled = ui.model.disabled || ui.effort.options.length < 2;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
function roundLabel(discussion) {
|
|
686
|
+
return "Round " + discussion.round + " of " + discussion.max_rounds;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
function followupRequirement(mode) {
|
|
690
|
+
if ((mode === "stress" || mode === "synthesis") &&
|
|
691
|
+
!chat?.messages.some((entry) => models.includes(entry.speaker) && entry.text.trim() && !entry.error)) {
|
|
692
|
+
return "Get a completed model reply in this chat first.";
|
|
693
|
+
}
|
|
694
|
+
if (enabled.size < 2 && mode === "discuss") return "Turn on at least two participants to find agreement.";
|
|
695
|
+
if (enabled.size < 2 && ["stress", "challenge"].includes(mode)) return "Turn on at least two participants for a challenge.";
|
|
696
|
+
if (!enabled.size) return "Turn on a participant to start a turn.";
|
|
697
|
+
return "";
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
function workflowLabel(entry) {
|
|
701
|
+
if (entry.mode === "synthesis") return "Combined · by " + names[entry.speaker];
|
|
702
|
+
if (entry.mode === "challenge") return "Challenge";
|
|
703
|
+
if (entry.mode === "stress") return entry.phase === "critique" ? "Pressure test · Critique" : entry.phase === "evaluation" ? "Pressure test · Evaluation" : "Pressure test";
|
|
704
|
+
return "";
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
function configureParticipants(participants) {
|
|
708
|
+
for (const participant of participants) {
|
|
709
|
+
const id = participant.id;
|
|
710
|
+
if (registry.has(id)) continue;
|
|
711
|
+
registry.set(id, participant);
|
|
712
|
+
models.push(id);
|
|
713
|
+
names[id] = participant.label;
|
|
714
|
+
if (setting("enable." + id, participant.default_enabled ? "yes" : "no") === "yes") enabled.add(id);
|
|
715
|
+
window.DiffCharacters?.register(id, participant.character);
|
|
716
|
+
const chip = participantStyle(element("button", "model-toggle " + id), id);
|
|
717
|
+
chip.id = "toggle-" + id;
|
|
718
|
+
chip.type = "button";
|
|
719
|
+
chip.setAttribute("aria-label", names[id]);
|
|
720
|
+
chip.setAttribute("aria-pressed", String(enabled.has(id)));
|
|
721
|
+
const check = element("span", "check");
|
|
722
|
+
check.setAttribute("aria-hidden", "true");
|
|
723
|
+
chip.append(check, names[id]);
|
|
724
|
+
document.querySelector(".participants-tools").append(chip);
|
|
725
|
+
createFields(id);
|
|
726
|
+
chip.addEventListener("click", () => {
|
|
727
|
+
if (!enabled.has(id) && window.diffNeedsConnection?.(id)) {
|
|
728
|
+
window.openDiffConnections(id);
|
|
729
|
+
return;
|
|
730
|
+
}
|
|
731
|
+
if (enabled.has(id)) enabled.delete(id);
|
|
732
|
+
else enabled.add(id);
|
|
733
|
+
fields.get(id).section.open = enabled.has(id);
|
|
734
|
+
remember("enable." + id, enabled.has(id) ? "yes" : "no");
|
|
735
|
+
updateControls();
|
|
736
|
+
});
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
function resizeDraft() {
|
|
741
|
+
const count = Array.from(draft.value).length;
|
|
742
|
+
const counter = byId("char-count");
|
|
743
|
+
counter.hidden = count === 0;
|
|
744
|
+
counter.textContent = count ? number.format(count) + (count === 1 ? " character" : " characters") : "";
|
|
745
|
+
draft.style.height = "auto";
|
|
746
|
+
const limit = parseFloat(getComputedStyle(draft).maxHeight);
|
|
747
|
+
const height = Math.min(limit, draft.scrollHeight);
|
|
748
|
+
draft.style.height = height + "px";
|
|
749
|
+
draft.style.overflowY = draft.scrollHeight > height ? "auto" : "hidden";
|
|
750
|
+
}
|
|
751
|
+
draft.addEventListener("input", () => {
|
|
752
|
+
if (chat) drafts.set(chat.id, draft.value);
|
|
753
|
+
resizeDraft();
|
|
754
|
+
updateControls();
|
|
755
|
+
});
|
|
756
|
+
window.addEventListener("resize", resizeDraft);
|
|
757
|
+
document.fonts.ready.then(resizeDraft);
|
|
758
|
+
|
|
759
|
+
function createRecord() {
|
|
760
|
+
const article = element("article", "message");
|
|
761
|
+
const byline = element("div", "byline");
|
|
762
|
+
const name = element("span", "speaker");
|
|
763
|
+
const stamp = element("time", "stamp");
|
|
764
|
+
const elapsed = element("span", "elapsed");
|
|
765
|
+
const choice = element("span", "reply-choice");
|
|
766
|
+
const round = element("span", "round-stamp");
|
|
767
|
+
const workflow = element("span", "reply-workflow");
|
|
768
|
+
const copy = element("button", "copy-answer", "Copy answer");
|
|
769
|
+
copy.type = "button";
|
|
770
|
+
copy.hidden = true;
|
|
771
|
+
byline.append(name, workflow, stamp, elapsed, choice, round, copy);
|
|
772
|
+
const prose = element("div", "prose");
|
|
773
|
+
const citations = element("div", "sources");
|
|
774
|
+
const failure = element("div", "failure");
|
|
775
|
+
article.append(byline, prose, citations, failure);
|
|
776
|
+
entries.append(article);
|
|
777
|
+
const record = { article, name, workflow, stamp, elapsed, choice, round, copy, prose, citations, failure };
|
|
778
|
+
copy.addEventListener("click", () => copyText(copy, record.rawText, prose, true));
|
|
779
|
+
window.chatActions?.mountMessageTools(record);
|
|
780
|
+
return record;
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
function citationUrl(value) {
|
|
784
|
+
try {
|
|
785
|
+
const url = new URL(value);
|
|
786
|
+
return ["https:", "http:"].includes(url.protocol) && !url.username && !url.password ? url : null;
|
|
787
|
+
} catch { return null; }
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
function sourceLinks(sources, seen = new Set()) {
|
|
791
|
+
const links = [];
|
|
792
|
+
for (const source of Array.isArray(sources) ? sources : []) {
|
|
793
|
+
const url = citationUrl(source?.url);
|
|
794
|
+
if (!url || seen.has(url.href)) continue;
|
|
795
|
+
seen.add(url.href);
|
|
796
|
+
const title = typeof source.title === "string" && source.title.trim();
|
|
797
|
+
const label = title || url.host + (url.pathname === "/" ? "" : url.pathname) + url.search;
|
|
798
|
+
links.push({ href: url.href, label });
|
|
799
|
+
}
|
|
800
|
+
return links;
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
function renderSources(record, sources) {
|
|
804
|
+
const wasOpen = record.citations.querySelector("details")?.open;
|
|
805
|
+
record.citations.replaceChildren();
|
|
806
|
+
if (record.status === "thinking" || record.status === "queued") return;
|
|
807
|
+
if (record.searchedWeb) record.citations.append(element("span", "source-label", "Searched the web"));
|
|
808
|
+
if (!sources.length) return;
|
|
809
|
+
const linked = new Set(Array.from(record.prose.querySelectorAll("a[href]"), (link) => link.href));
|
|
810
|
+
const list = element("ul");
|
|
811
|
+
for (const { href, label } of sourceLinks(sources, linked)) {
|
|
812
|
+
const anchor = element("a", "", label);
|
|
813
|
+
anchor.href = href;
|
|
814
|
+
anchor.title = href;
|
|
815
|
+
anchor.target = "_blank";
|
|
816
|
+
anchor.rel = "noopener noreferrer";
|
|
817
|
+
const item = element("li");
|
|
818
|
+
item.append(anchor);
|
|
819
|
+
list.append(item);
|
|
820
|
+
}
|
|
821
|
+
if (list.childElementCount) {
|
|
822
|
+
const details = element("details", "source-results");
|
|
823
|
+
details.open = Boolean(wasOpen);
|
|
824
|
+
const label = record.entry.mode === "synthesis" ? "Conversation sources" : "Search results";
|
|
825
|
+
details.append(element("summary", "", label + " (" + list.childElementCount + ")"), list);
|
|
826
|
+
record.citations.append(details);
|
|
827
|
+
}
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
function renderElapsed(record) {
|
|
831
|
+
let label = "";
|
|
832
|
+
if (record.status === "queued") label = "queued";
|
|
833
|
+
else if (record.status === "thinking") {
|
|
834
|
+
const seconds = Math.max(0, Math.floor((Date.now() - record.started) / 1000));
|
|
835
|
+
label = (record.searchedWeb ? "Searching the web… " : "thinking… ") + seconds + "s";
|
|
836
|
+
} else if (record.speaker !== "me" && Number.isFinite(record.duration)) {
|
|
837
|
+
label = (record.duration / 1000).toFixed(1) + "s";
|
|
838
|
+
}
|
|
839
|
+
if (record.elapsed.textContent !== label) record.elapsed.textContent = label;
|
|
840
|
+
}
|
|
841
|
+
|
|
842
|
+
function updateRecord(record, entry) {
|
|
843
|
+
record.entry = entry;
|
|
844
|
+
const { speaker, text, error } = entry;
|
|
845
|
+
window.diffAttachments?.render(record.article, entry);
|
|
846
|
+
const timestamp = entry.timestamp || entry.started_at || "";
|
|
847
|
+
const round = entry.discussion_id && entry.round ? "Round " + entry.round : "";
|
|
848
|
+
if (record.round.textContent !== round) record.round.textContent = round;
|
|
849
|
+
const role = workflowLabel(entry);
|
|
850
|
+
if (record.workflow.textContent !== role) record.workflow.textContent = role;
|
|
851
|
+
if (record.speaker !== speaker || record.name.textContent !== names[speaker]) {
|
|
852
|
+
record.article.className = "message " + speaker;
|
|
853
|
+
participantStyle(record.article, speaker);
|
|
854
|
+
record.article.setAttribute("aria-label", names[speaker] + " message");
|
|
855
|
+
record.name.textContent = names[speaker];
|
|
856
|
+
record.speaker = speaker;
|
|
857
|
+
record.copy.setAttribute("aria-label", "Copy answer from " + names[speaker]);
|
|
858
|
+
}
|
|
859
|
+
if (entry.model !== record.model || entry.effort !== record.effort) {
|
|
860
|
+
record.model = entry.model;
|
|
861
|
+
record.effort = entry.effort;
|
|
862
|
+
const label = catalog[speaker]?.models.find((item) => item.id === entry.model)?.label || entry.model;
|
|
863
|
+
const summary = [label, registry.get(speaker)?.capabilities.reasoning_levels && entry.effort && effortLabel(entry.effort)].filter(Boolean).join(" · ");
|
|
864
|
+
record.choice.textContent = summary;
|
|
865
|
+
record.choice.title = [entry.model, entry.effort].filter(Boolean).join(" · ");
|
|
866
|
+
}
|
|
867
|
+
if (record.timestamp !== timestamp) {
|
|
868
|
+
record.timestamp = timestamp;
|
|
869
|
+
record.stamp.hidden = !timestamp;
|
|
870
|
+
if (timestamp) {
|
|
871
|
+
const date = new Date(timestamp);
|
|
872
|
+
record.stamp.dateTime = timestamp;
|
|
873
|
+
record.stamp.textContent = clock.format(date);
|
|
874
|
+
record.stamp.title = date.toLocaleString();
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
record.started = timestamp ? Date.parse(timestamp) : Date.now();
|
|
878
|
+
record.status = entry.status || (error ? "error" : "done");
|
|
879
|
+
window.DiffCharacters?.message(record, entry);
|
|
880
|
+
record.searchedWeb = entry.searched_web === true;
|
|
881
|
+
record.duration = entry.duration_ms;
|
|
882
|
+
renderElapsed(record);
|
|
883
|
+
const textChanged = text !== record.rawText;
|
|
884
|
+
const streaming = Boolean(entry.status === "thinking" && text && !error);
|
|
885
|
+
if (streaming && textChanged) {
|
|
886
|
+
streamProse(record, text);
|
|
887
|
+
} else if (!streaming && (textChanged || record.stream)) {
|
|
888
|
+
clearTimeout(record.stream?.timer);
|
|
889
|
+
record.stream = null;
|
|
890
|
+
fillProse(record.prose, text);
|
|
891
|
+
}
|
|
892
|
+
record.rawText = text;
|
|
893
|
+
const sources = Array.isArray(entry.sources) ? entry.sources : [];
|
|
894
|
+
const finished = record.status !== "thinking" && record.status !== "queued";
|
|
895
|
+
record.copy.hidden = !finished || speaker === "me" || !text.trim();
|
|
896
|
+
window.chatActions?.updateMessageTools(record, finished);
|
|
897
|
+
const sourceKey = finished ? JSON.stringify([record.searchedWeb, sources]) : "";
|
|
898
|
+
if (sourceKey !== record.sourceKey || (finished && textChanged && sources.length)) {
|
|
899
|
+
renderSources(record, sources);
|
|
900
|
+
record.sourceKey = sourceKey;
|
|
901
|
+
}
|
|
902
|
+
const errorKey = error ? JSON.stringify(error) : "";
|
|
903
|
+
if (record.errorKey !== errorKey) {
|
|
904
|
+
record.errorKey = errorKey;
|
|
905
|
+
record.failure.replaceChildren();
|
|
906
|
+
if (error) {
|
|
907
|
+
record.failure.append(element("p", "", error.message));
|
|
908
|
+
const details = element("details");
|
|
909
|
+
details.append(element("summary", "", "Show stderr"), element("pre", "error-log", error.stderr || "No stderr output."));
|
|
910
|
+
record.failure.append(details);
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
function outcomeText(item) {
|
|
916
|
+
return {
|
|
917
|
+
agreed: item.agreement || "",
|
|
918
|
+
limit: item.detail || "Participants did not endorse the same answer.",
|
|
919
|
+
revised: "A reply in this discussion was retried.",
|
|
920
|
+
stopped: "The discussion stopped before all participants confirmed agreement.",
|
|
921
|
+
error: item.detail || "The discussion ended before all participants confirmed agreement. See the latest replies for details.",
|
|
922
|
+
interrupted: "The discussion ended before all participants confirmed agreement.",
|
|
923
|
+
}[item.status] || "";
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
function markdownLabel(value) {
|
|
927
|
+
return String(value || "").replace(/\s+/g, " ").trim().replace(/[\\`*_#[\]<>]/g, "\\$&");
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
function exportMessage(entry) {
|
|
931
|
+
const author = markdownLabel(names[entry.speaker] || entry.speaker);
|
|
932
|
+
const mode = workflowLabel(entry);
|
|
933
|
+
const parts = ["## " + author + (mode ? " · " + mode : "")];
|
|
934
|
+
const model = catalog[entry.speaker]?.models.find((item) => item.id === entry.model);
|
|
935
|
+
const metadata = [
|
|
936
|
+
entry.timestamp,
|
|
937
|
+
model?.label || entry.model,
|
|
938
|
+
entry.effort && effortLabel(entry.effort) + " reasoning",
|
|
939
|
+
entry.speaker !== "me" && Number.isFinite(entry.duration_ms) && (entry.duration_ms / 1000).toFixed(1) + "s",
|
|
940
|
+
entry.discussion_id && entry.round && "Round " + entry.round,
|
|
941
|
+
entry.searched_web && "Searched the web",
|
|
942
|
+
].filter(Boolean);
|
|
943
|
+
if (metadata.length) parts.push(metadata.map(markdownLabel).join(" · "));
|
|
944
|
+
if (entry.text) parts.push(entry.text);
|
|
945
|
+
const links = sourceLinks(entry.sources);
|
|
946
|
+
if (links.length) {
|
|
947
|
+
const heading = entry.mode === "synthesis" ? "Conversation sources" : "Search results";
|
|
948
|
+
parts.push("**" + heading + "**\n\n" + links.map(({ href, label }) => "- [" + markdownLabel(label) + "](<" + href + ">)").join("\n"));
|
|
949
|
+
}
|
|
950
|
+
if (entry.error) {
|
|
951
|
+
parts.push("**Reply error**\n\n" + entry.error.message);
|
|
952
|
+
}
|
|
953
|
+
return parts.join("\n\n");
|
|
954
|
+
}
|
|
955
|
+
|
|
956
|
+
function exportMarkdown(saved) {
|
|
957
|
+
const parts = ["# " + markdownLabel(saved.title)];
|
|
958
|
+
const outcomes = new Map();
|
|
959
|
+
for (const item of saved.discussions || []) {
|
|
960
|
+
const label = item.status === "running" ? "Discussion in progress" : outcomeLabels[item.status];
|
|
961
|
+
if (!label) continue;
|
|
962
|
+
const end = Math.max(0, Math.min(saved.messages.length, item.end_index));
|
|
963
|
+
const block = ["## " + label, roundLabel(item), outcomeText(item)].filter(Boolean).join("\n\n");
|
|
964
|
+
if (!outcomes.has(end)) outcomes.set(end, []);
|
|
965
|
+
outcomes.get(end).push(block);
|
|
966
|
+
}
|
|
967
|
+
for (let index = 0; index <= saved.messages.length; index++) {
|
|
968
|
+
if (outcomes.has(index)) parts.push(...outcomes.get(index));
|
|
969
|
+
if (index < saved.messages.length) parts.push(exportMessage(saved.messages[index]));
|
|
970
|
+
}
|
|
971
|
+
return parts.join("\n\n") + "\n";
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
byId("export-chat").addEventListener("click", async () => {
|
|
975
|
+
if (!chat || exporting) return;
|
|
976
|
+
const id = chat.id;
|
|
977
|
+
exporting = true;
|
|
978
|
+
updateControls();
|
|
979
|
+
try {
|
|
980
|
+
const saved = await api("/api/chats/" + id);
|
|
981
|
+
const data = new Blob([exportMarkdown(saved)], { type: "text/markdown;charset=utf-8" });
|
|
982
|
+
const url = URL.createObjectURL(data);
|
|
983
|
+
const link = document.createElement("a");
|
|
984
|
+
const title = saved.title.replace(/[<>:"/\\|?*\u0000-\u001f]/g, " ").replace(/\s+/g, " ").trim().slice(0, 96);
|
|
985
|
+
link.download = "diff - " + (title || "Chat") + ".md";
|
|
986
|
+
link.href = url;
|
|
987
|
+
document.body.append(link);
|
|
988
|
+
link.click();
|
|
989
|
+
link.remove();
|
|
990
|
+
setTimeout(() => URL.revokeObjectURL(url), 30000);
|
|
991
|
+
byId("announcement").textContent = "Markdown download started.";
|
|
992
|
+
} catch (error) {
|
|
993
|
+
feedback("Could not export this chat. " + error.message);
|
|
994
|
+
} finally {
|
|
995
|
+
exporting = false;
|
|
996
|
+
updateControls();
|
|
997
|
+
}
|
|
998
|
+
});
|
|
999
|
+
|
|
1000
|
+
function renderDiscussionOutcomes() {
|
|
1001
|
+
const seen = new Set();
|
|
1002
|
+
const anchors = new Map();
|
|
1003
|
+
for (const item of chat.discussions || []) {
|
|
1004
|
+
if (!item?.id || !Object.hasOwn(outcomeLabels, item.status)) continue;
|
|
1005
|
+
seen.add(item.id);
|
|
1006
|
+
let record = discussionOutcomes.get(item.id);
|
|
1007
|
+
if (!record) {
|
|
1008
|
+
const node = element("aside", "discussion-outcome");
|
|
1009
|
+
node.setAttribute("aria-label", "Discussion outcome");
|
|
1010
|
+
const heading = element("div", "outcome-head");
|
|
1011
|
+
const label = element("strong");
|
|
1012
|
+
const round = element("span", "round-stamp");
|
|
1013
|
+
const position = element("p");
|
|
1014
|
+
heading.append(label, round);
|
|
1015
|
+
node.append(heading, position);
|
|
1016
|
+
record = { node, label, round, position };
|
|
1017
|
+
discussionOutcomes.set(item.id, record);
|
|
1018
|
+
}
|
|
1019
|
+
const text = outcomeText(item);
|
|
1020
|
+
const labelText = item.status === "limit" ? `No agreement after ${item.round} rounds` : outcomeLabels[item.status];
|
|
1021
|
+
if (record.label.textContent !== labelText) record.label.textContent = labelText;
|
|
1022
|
+
if (record.round.textContent !== roundLabel(item)) record.round.textContent = roundLabel(item);
|
|
1023
|
+
if (record.position.textContent !== text) record.position.textContent = text;
|
|
1024
|
+
record.position.hidden = !text;
|
|
1025
|
+
const end = Math.max(0, Math.min(item.end_index, visibleRecords.length));
|
|
1026
|
+
const anchor = anchors.get(end) || visibleRecords[end - 1]?.article;
|
|
1027
|
+
const outer = anchor?.closest(".diff-round") || anchor;
|
|
1028
|
+
const next = outer ? outer.nextElementSibling : entries.firstElementChild;
|
|
1029
|
+
if (record.node !== next) entries.insertBefore(record.node, next);
|
|
1030
|
+
anchors.set(end, record.node);
|
|
1031
|
+
}
|
|
1032
|
+
for (const [id, record] of discussionOutcomes) {
|
|
1033
|
+
if (!seen.has(id)) {
|
|
1034
|
+
record.node.remove();
|
|
1035
|
+
discussionOutcomes.delete(id);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
}
|
|
1039
|
+
|
|
1040
|
+
const summaryMarker = element("p", "summary-marker", "Earlier messages summarized.");
|
|
1041
|
+
const shortNumber = new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 1 });
|
|
1042
|
+
function renderContext() {
|
|
1043
|
+
const through = chat.context_summary?.through_index;
|
|
1044
|
+
const last = Number.isInteger(through) && through > 0 && through <= chat.messages.length ? visibleRecords[through - 1]?.article : null;
|
|
1045
|
+
if (!last) summaryMarker.remove();
|
|
1046
|
+
else {
|
|
1047
|
+
let anchor = last.closest(".diff-round") || last;
|
|
1048
|
+
while (anchor.nextElementSibling?.classList.contains("discussion-outcome")) anchor = anchor.nextElementSibling;
|
|
1049
|
+
if (anchor.nextElementSibling !== summaryMarker) anchor.after(summaryMarker);
|
|
1050
|
+
}
|
|
1051
|
+
const stats = byId("chat-stats");
|
|
1052
|
+
const traffic = chat.stats;
|
|
1053
|
+
const measured = Number.isFinite(traffic?.turns) && Number.isFinite(traffic?.chars_sent);
|
|
1054
|
+
stats.hidden = !measured;
|
|
1055
|
+
if (measured) {
|
|
1056
|
+
const turns = (traffic.legacy ? "≈" : "") + number.format(traffic.turns) + (traffic.turns === 1 ? " turn" : " turns");
|
|
1057
|
+
stats.textContent = turns + " · ≈" + shortNumber.format(traffic.chars_sent) + " chars sent" + (traffic.legacy ? " since update" : "");
|
|
1058
|
+
stats.title = turns + " · approximately " + number.format(traffic.chars_sent) + " characters sent." +
|
|
1059
|
+
(traffic.legacy ? " Earlier turns are estimated. Character tracking began with the update." : "");
|
|
1060
|
+
}
|
|
1061
|
+
const warning = byId("context-warning");
|
|
1062
|
+
warning.hidden = !chat.context_warning;
|
|
1063
|
+
warning.textContent = chat.context_warning || "";
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
function renderTranscript() {
|
|
1067
|
+
if (byId("chat-title").textContent !== chat.title) byId("chat-title").textContent = chat.title;
|
|
1068
|
+
byId("chat-title").title = chat.title;
|
|
1069
|
+
document.title = chat.title + " · diff";
|
|
1070
|
+
const messages = chat.messages.slice();
|
|
1071
|
+
if (retryIndex != null && slots.length) messages[retryIndex] = slots[0];
|
|
1072
|
+
else messages.push(...slots);
|
|
1073
|
+
byId("empty").hidden = Boolean(messages.length);
|
|
1074
|
+
for (let index = 0; index < messages.length; index++) {
|
|
1075
|
+
if (!visibleRecords[index]) visibleRecords[index] = createRecord();
|
|
1076
|
+
updateRecord(visibleRecords[index], messages[index]);
|
|
1077
|
+
}
|
|
1078
|
+
while (visibleRecords.length > messages.length) visibleRecords.pop().article.remove();
|
|
1079
|
+
window.chatActions?.renderDiffs();
|
|
1080
|
+
renderDiscussionOutcomes();
|
|
1081
|
+
renderContext();
|
|
1082
|
+
byId("history-notice").hidden = chat.chars <= threshold;
|
|
1083
|
+
updateIndex();
|
|
1084
|
+
updateControls();
|
|
1085
|
+
if (followNewText) reader.scrollTop = reader.scrollHeight;
|
|
1086
|
+
}
|
|
1087
|
+
reader.addEventListener("scroll", () => {
|
|
1088
|
+
followNewText = reader.scrollHeight - reader.clientHeight - reader.scrollTop < 65;
|
|
1089
|
+
}, { passive: true });
|
|
1090
|
+
setInterval(() => {
|
|
1091
|
+
if (!runId) return;
|
|
1092
|
+
for (const record of visibleRecords) if (record.status === "thinking") renderElapsed(record);
|
|
1093
|
+
}, 450);
|
|
1094
|
+
|
|
1095
|
+
const backgroundStreams = new Map();
|
|
1096
|
+
function watchBackground(stream, id, chatId) {
|
|
1097
|
+
backgroundStreams.set(id, stream);
|
|
1098
|
+
function finish() {
|
|
1099
|
+
stream.close();
|
|
1100
|
+
backgroundStreams.delete(id);
|
|
1101
|
+
}
|
|
1102
|
+
stream.addEventListener("state", event => {
|
|
1103
|
+
if (backgroundStreams.get(id) !== stream) return;
|
|
1104
|
+
const state = JSON.parse(event.data);
|
|
1105
|
+
if (state.done) {
|
|
1106
|
+
finish();
|
|
1107
|
+
document.dispatchEvent(new CustomEvent("diff:background-finished", {detail:{runId:id, chatId}}));
|
|
1108
|
+
}
|
|
1109
|
+
});
|
|
1110
|
+
stream.addEventListener("error", () => {
|
|
1111
|
+
if (stream.readyState === EventSource.CLOSED) finish();
|
|
1112
|
+
});
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
function disconnect(keepWatching = false) {
|
|
1116
|
+
if (keepWatching && source && runId && window.diffSettings?.notify_background) watchBackground(source, runId, chat.id);
|
|
1117
|
+
else source?.close();
|
|
1118
|
+
source = null;
|
|
1119
|
+
runId = null;
|
|
1120
|
+
activeKind = null;
|
|
1121
|
+
retryIndex = null;
|
|
1122
|
+
activeDiscussion = null;
|
|
1123
|
+
stopping = false;
|
|
1124
|
+
}
|
|
1125
|
+
|
|
1126
|
+
async function openChat(id, create = false, initialState = null) {
|
|
1127
|
+
const version = ++navigationVersion;
|
|
1128
|
+
navigating = true;
|
|
1129
|
+
feedback();
|
|
1130
|
+
updateControls();
|
|
1131
|
+
try {
|
|
1132
|
+
await preferenceWrites;
|
|
1133
|
+
const state = initialState || await api("/api/state");
|
|
1134
|
+
configureParticipants(state.participants);
|
|
1135
|
+
const savedId = setting("chat", "");
|
|
1136
|
+
const readable = state.chats.filter((item) => item.chars >= 0);
|
|
1137
|
+
const target = (id && readable.some((item) => item.id === id) && id) ||
|
|
1138
|
+
(readable.some((item) => item.id === savedId) && savedId) || readable[0]?.id;
|
|
1139
|
+
const next = create || !target ? await api(create ? "/api/chats?fresh=true" : "/api/chats", {}) : await api("/api/chats/" + target);
|
|
1140
|
+
if (navigationVersion !== version) return;
|
|
1141
|
+
disconnect(chat?.id !== next.id);
|
|
1142
|
+
slots = [];
|
|
1143
|
+
if (chat?.id !== next.id) {
|
|
1144
|
+
entries.replaceChildren();
|
|
1145
|
+
visibleRecords = [];
|
|
1146
|
+
discussionOutcomes.clear();
|
|
1147
|
+
}
|
|
1148
|
+
chat = next;
|
|
1149
|
+
names.me = state.settings.display_name || "You";
|
|
1150
|
+
savedWebSearch = chat.web_search !== false;
|
|
1151
|
+
webSearch = savedWebSearch;
|
|
1152
|
+
catalog = state.model_options || {};
|
|
1153
|
+
loadPreferences(chat.preferences);
|
|
1154
|
+
chatList = state.chats;
|
|
1155
|
+
threshold = state.settings.summary_threshold;
|
|
1156
|
+
remember("chat", chat.id);
|
|
1157
|
+
draft.value = drafts.get(chat.id) || "";
|
|
1158
|
+
followNewText = true;
|
|
1159
|
+
renderChatList();
|
|
1160
|
+
renderTranscript();
|
|
1161
|
+
resizeDraft();
|
|
1162
|
+
document.dispatchEvent(new CustomEvent("transcript:chat-opened", { detail: {
|
|
1163
|
+
chatId: chat.id, empty: chat.messages.length === 0, firstRun: !readable.some((item) => item.chars > 0)
|
|
1164
|
+
} }));
|
|
1165
|
+
if (state.active_runs[chat.id]) listen(state.active_runs[chat.id]);
|
|
1166
|
+
} catch (error) {
|
|
1167
|
+
if (version === navigationVersion) feedback(error.message, !chat);
|
|
1168
|
+
} finally {
|
|
1169
|
+
if (version === navigationVersion) {
|
|
1170
|
+
navigating = false;
|
|
1171
|
+
updateControls();
|
|
1172
|
+
}
|
|
1173
|
+
}
|
|
1174
|
+
}
|
|
1175
|
+
|
|
1176
|
+
function listen(id) {
|
|
1177
|
+
backgroundStreams.get(id)?.close();
|
|
1178
|
+
backgroundStreams.delete(id);
|
|
1179
|
+
disconnect();
|
|
1180
|
+
runId = id;
|
|
1181
|
+
const stream = new EventSource(window.diffSession.streamURL("/api/runs/" + id + "/events"));
|
|
1182
|
+
source = stream;
|
|
1183
|
+
let reconnecting = false;
|
|
1184
|
+
let saveError = "";
|
|
1185
|
+
stream.addEventListener("state", (event) => {
|
|
1186
|
+
if (source !== stream) return;
|
|
1187
|
+
const state = JSON.parse(event.data);
|
|
1188
|
+
if (reconnecting || saveError !== (state.save_error || "")) feedback(state.save_error || "");
|
|
1189
|
+
saveError = state.save_error || "";
|
|
1190
|
+
reconnecting = false;
|
|
1191
|
+
chat = state.chat;
|
|
1192
|
+
slots = state.slots;
|
|
1193
|
+
activeKind = state.kind;
|
|
1194
|
+
activeDiscussion = state.kind === "discuss" ? state.discussion : null;
|
|
1195
|
+
retryIndex = state.retry_index;
|
|
1196
|
+
const detail = { runId: id, chatId: chat.id, kind: state.kind, done: state.done, slots: state.slots,
|
|
1197
|
+
discussion: state.discussion, stopped: state.stopped, messages: chat.messages,
|
|
1198
|
+
finishedSlots: state.finished_slots };
|
|
1199
|
+
document.dispatchEvent(new CustomEvent("transcript:run-state", {detail}));
|
|
1200
|
+
if (state.done) {
|
|
1201
|
+
disconnect();
|
|
1202
|
+
usageDirty = true;
|
|
1203
|
+
refreshUsage();
|
|
1204
|
+
byId("announcement").textContent = state.kind === "discuss" ? "Discussion complete." :
|
|
1205
|
+
state.kind === "summary" ? "Summary round complete." : "Replies complete.";
|
|
1206
|
+
}
|
|
1207
|
+
renderTranscript();
|
|
1208
|
+
if (state.done) {
|
|
1209
|
+
document.dispatchEvent(new CustomEvent("transcript:turn-finished", { detail }));
|
|
1210
|
+
if (state.new_chat_id) openChat(state.new_chat_id);
|
|
1211
|
+
}
|
|
1212
|
+
});
|
|
1213
|
+
stream.addEventListener("error", () => {
|
|
1214
|
+
if (source !== stream) return;
|
|
1215
|
+
if (stream.readyState === EventSource.CLOSED) {
|
|
1216
|
+
disconnect();
|
|
1217
|
+
openChat(chat.id).then(() => {
|
|
1218
|
+
if (!runId) feedback("The connection ended. Showing the saved transcript.");
|
|
1219
|
+
});
|
|
1220
|
+
return;
|
|
1221
|
+
}
|
|
1222
|
+
reconnecting = true;
|
|
1223
|
+
feedback("Connection interrupted. Reconnecting to this turn…");
|
|
1224
|
+
});
|
|
1225
|
+
updateControls();
|
|
1226
|
+
}
|
|
1227
|
+
|
|
1228
|
+
async function startTurn(kind, extra = {}) {
|
|
1229
|
+
if (!chat || starting || navigating || runId) return;
|
|
1230
|
+
const text = extra.text ?? draft.value;
|
|
1231
|
+
if (kind === "send" && !text.trim()) return;
|
|
1232
|
+
const requirement = followupRequirement(kind);
|
|
1233
|
+
if (requirement) {
|
|
1234
|
+
feedback(requirement);
|
|
1235
|
+
return;
|
|
1236
|
+
}
|
|
1237
|
+
feedback();
|
|
1238
|
+
starting = true;
|
|
1239
|
+
updateControls();
|
|
1240
|
+
const chatId = chat.id;
|
|
1241
|
+
try {
|
|
1242
|
+
const selectedModels = models.filter((model) => enabled.has(model));
|
|
1243
|
+
const requested = { ...preferences };
|
|
1244
|
+
const requestedSearch = webSearch;
|
|
1245
|
+
await preferenceWrites;
|
|
1246
|
+
if (requestedSearch !== webSearch || models.some((model) => requested[model] !== preferences[model])) return;
|
|
1247
|
+
const participants = selectedModels;
|
|
1248
|
+
const target = chat.messages[extra.message_index];
|
|
1249
|
+
const configuredRounds = window.diffSettings?.agreement_rounds || 4;
|
|
1250
|
+
const replyCap = Math.min(configuredRounds * participants.length, window.diffSettings?.max_replies || 8);
|
|
1251
|
+
let expected = participants;
|
|
1252
|
+
if (kind === "discuss") expected = Array.from({length: replyCap}, (_, i) => participants[i % participants.length]);
|
|
1253
|
+
if (kind === "synthesis") expected = [extra.combiner || participants[0]];
|
|
1254
|
+
if (kind === "retry") expected = [target?.speaker];
|
|
1255
|
+
if (kind === "challenge") expected = [extra.challenger, target?.speaker];
|
|
1256
|
+
if (kind === "send" || kind === "edit") {
|
|
1257
|
+
const mention = /^@([a-z][a-z0-9_-]*)/i.exec(text.trim())?.[1].toLowerCase();
|
|
1258
|
+
if (models.includes(mention)) {
|
|
1259
|
+
if (!enabled.has(mention)) {
|
|
1260
|
+
feedback("Turn on " + names[mention] + " to address it.");
|
|
1261
|
+
return;
|
|
1262
|
+
}
|
|
1263
|
+
expected = [mention];
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
if (window.checkUsageBudget && !(await window.checkUsageBudget(expected))) return;
|
|
1267
|
+
// Usage checks can outlast a chip click. Never dispatch a stale roster.
|
|
1268
|
+
if (participants.length !== enabled.size || participants.some(id => !enabled.has(id))) {
|
|
1269
|
+
feedback("Participants changed. Start the turn again with your current selection.");
|
|
1270
|
+
return;
|
|
1271
|
+
}
|
|
1272
|
+
const turn = { ...extra, kind, models: participants, preferences: requested, web_search: requestedSearch };
|
|
1273
|
+
if (kind === "send") turn.attachments = window.diffAttachments?.forSend() || [];
|
|
1274
|
+
if (kind === "send") turn.text = text;
|
|
1275
|
+
const result = await api("/api/chats/" + chatId + "/runs", turn);
|
|
1276
|
+
if (kind === "send") window.diffAttachments?.didSend(chatId);
|
|
1277
|
+
if (kind === "send" && draft.value === text) {
|
|
1278
|
+
draft.value = "";
|
|
1279
|
+
drafts.delete(chatId, text);
|
|
1280
|
+
resizeDraft();
|
|
1281
|
+
}
|
|
1282
|
+
slots = [];
|
|
1283
|
+
followNewText = true;
|
|
1284
|
+
listen(result.run_id);
|
|
1285
|
+
if (!mobile.matches && kind === "send") draft.focus();
|
|
1286
|
+
return true;
|
|
1287
|
+
} catch (error) {
|
|
1288
|
+
if (error.status === 409) await openChat(chatId);
|
|
1289
|
+
feedback(error.message);
|
|
1290
|
+
} finally {
|
|
1291
|
+
starting = false;
|
|
1292
|
+
updateControls();
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
byId("compose-form").addEventListener("submit", (event) => {
|
|
1297
|
+
event.preventDefault();
|
|
1298
|
+
if (!window.chatActions?.submitSlash()) startTurn("send");
|
|
1299
|
+
});
|
|
1300
|
+
draft.addEventListener("keydown", (event) => {
|
|
1301
|
+
if (event.defaultPrevented || event.isComposing || event.keyCode === 229) return;
|
|
1302
|
+
const modOnly = window.diffSettings?.send_shortcut === "mod-enter";
|
|
1303
|
+
if (event.key === "Enter" && !event.shiftKey && (!modOnly || event.metaKey || event.ctrlKey)) {
|
|
1304
|
+
event.preventDefault();
|
|
1305
|
+
if (!window.chatActions?.submitSlash()) startTurn("send");
|
|
1306
|
+
}
|
|
1307
|
+
});
|
|
1308
|
+
byId("carry").addEventListener("click", () => startTurn("summary"));
|
|
1309
|
+
byId("new-chat").addEventListener("click", async () => {
|
|
1310
|
+
if (mobile.matches) showPanel(false, true);
|
|
1311
|
+
await openChat(null, true);
|
|
1312
|
+
if (chat && !mobile.matches) draft.focus();
|
|
1313
|
+
});
|
|
1314
|
+
byId("stop").addEventListener("click", async () => {
|
|
1315
|
+
if (!runId || stopping) return;
|
|
1316
|
+
const id = runId;
|
|
1317
|
+
stopping = true;
|
|
1318
|
+
updateControls();
|
|
1319
|
+
try { await api("/api/runs/" + id + "/stop", {}); }
|
|
1320
|
+
catch (error) {
|
|
1321
|
+
if (runId === id) {
|
|
1322
|
+
stopping = false;
|
|
1323
|
+
feedback(error.message);
|
|
1324
|
+
updateControls();
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
});
|
|
1328
|
+
|
|
1329
|
+
document.addEventListener("DOMContentLoaded", async () => {
|
|
1330
|
+
const url = new URL(location.href);
|
|
1331
|
+
const id = url.searchParams.get("chat");
|
|
1332
|
+
if (id !== null) {
|
|
1333
|
+
url.searchParams.delete("chat");
|
|
1334
|
+
history.replaceState(history.state, "", url);
|
|
1335
|
+
}
|
|
1336
|
+
try {
|
|
1337
|
+
const state = await api("/api/state");
|
|
1338
|
+
catalog = state.model_options || {};
|
|
1339
|
+
configureParticipants(state.participants);
|
|
1340
|
+
const rechecked = await window.diffFirstRun?.();
|
|
1341
|
+
await openChat(/^[0-9a-f]{32}$/.test(id || "") ? id : null, false, rechecked ? null : state);
|
|
1342
|
+
if (!byId("inspector").hidden) refreshUsage();
|
|
1343
|
+
} catch (error) { feedback(error.message, true); }
|
|
1344
|
+
}, { once: true });
|