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.
Files changed (91) hide show
  1. adapters/README.md +28 -0
  2. adapters/__init__.py +48 -0
  3. adapters/_base.py +102 -0
  4. adapters/_cli.py +405 -0
  5. adapters/claude.py +141 -0
  6. adapters/gemini.py +323 -0
  7. adapters/gpt.py +217 -0
  8. adapters/local.py +146 -0
  9. adapters/registry.py +33 -0
  10. api_fallback.py +189 -0
  11. app.py +827 -0
  12. app_preferences.py +205 -0
  13. archive_schema.py +142 -0
  14. attachments.py +129 -0
  15. chat_titles.py +60 -0
  16. connection_handoff.py +64 -0
  17. context_engine.py +256 -0
  18. conversation_actions.py +160 -0
  19. diff_chat-0.1.0.dist-info/METADATA +101 -0
  20. diff_chat-0.1.0.dist-info/RECORD +91 -0
  21. diff_chat-0.1.0.dist-info/WHEEL +4 -0
  22. diff_chat-0.1.0.dist-info/entry_points.txt +2 -0
  23. diff_chat-0.1.0.dist-info/licenses/LICENSE +21 -0
  24. diff_chat_assets/memory.example.md +1 -0
  25. diff_chat_assets/prompts/about_you_export.md +19 -0
  26. diff_chat_assets/settings.json +6 -0
  27. diff_chat_assets/static/about-you-parser.js +46 -0
  28. diff_chat_assets/static/about-you.js +171 -0
  29. diff_chat_assets/static/actions.css +275 -0
  30. diff_chat_assets/static/actions.js +650 -0
  31. diff_chat_assets/static/app.css +345 -0
  32. diff_chat_assets/static/app.js +1344 -0
  33. diff_chat_assets/static/attachments.js +80 -0
  34. diff_chat_assets/static/brand/favicon-32.png +0 -0
  35. diff_chat_assets/static/brand/icon.svg +11 -0
  36. diff_chat_assets/static/brand/wordmark-dark.svg +15 -0
  37. diff_chat_assets/static/brand/wordmark-light.svg +13 -0
  38. diff_chat_assets/static/characters/CREDITS.md +7 -0
  39. diff_chat_assets/static/characters/characters.css +37 -0
  40. diff_chat_assets/static/characters/claude.json +507 -0
  41. diff_chat_assets/static/characters/claude.png +0 -0
  42. diff_chat_assets/static/characters/claude.webp +0 -0
  43. diff_chat_assets/static/characters/gemini.json +54 -0
  44. diff_chat_assets/static/characters/gemini.png +0 -0
  45. diff_chat_assets/static/characters/gemini.webp +0 -0
  46. diff_chat_assets/static/characters/gpt.json +507 -0
  47. diff_chat_assets/static/characters/gpt.png +0 -0
  48. diff_chat_assets/static/characters/gpt.webp +0 -0
  49. diff_chat_assets/static/characters/local.json +387 -0
  50. diff_chat_assets/static/characters/local.png +0 -0
  51. diff_chat_assets/static/characters/local.webp +0 -0
  52. diff_chat_assets/static/characters/player.js +318 -0
  53. diff_chat_assets/static/chat-filing.js +84 -0
  54. diff_chat_assets/static/controls.js +194 -0
  55. diff_chat_assets/static/corners.css +59 -0
  56. diff_chat_assets/static/craft.css +246 -0
  57. diff_chat_assets/static/drafts.js +41 -0
  58. diff_chat_assets/static/index.html +208 -0
  59. diff_chat_assets/static/library.css +30 -0
  60. diff_chat_assets/static/library.js +181 -0
  61. diff_chat_assets/static/memory.js +81 -0
  62. diff_chat_assets/static/preference-dialog.js +21 -0
  63. diff_chat_assets/static/preferences.css +56 -0
  64. diff_chat_assets/static/session.js +46 -0
  65. diff_chat_assets/static/settings.css +111 -0
  66. diff_chat_assets/static/settings.js +463 -0
  67. diff_chat_assets/static/setup.js +238 -0
  68. diff_chat_assets/static/utility.js +64 -0
  69. diff_chat_assets/static/vendor/LICENSES.txt +531 -0
  70. diff_chat_assets/static/vendor/highlight.min.js +1262 -0
  71. diff_chat_assets/static/vendor/markdown-it.min.js +13 -0
  72. diff_chat_assets/static/vendor/plex-mono.woff2 +0 -0
  73. diff_chat_assets/static/vendor/plex-sans.woff2 +0 -0
  74. diff_launcher.py +93 -0
  75. discussion.py +239 -0
  76. history_search.py +68 -0
  77. library_manager.py +251 -0
  78. model_options.py +132 -0
  79. plan_usage.py +72 -0
  80. private_store.py +71 -0
  81. probe.py +195 -0
  82. runtime_paths.py +195 -0
  83. server_security.py +100 -0
  84. setup_status.py +123 -0
  85. shared_memory.py +189 -0
  86. storage.py +185 -0
  87. usage_budget.py +77 -0
  88. usage_claude.py +110 -0
  89. usage_codex.py +170 -0
  90. usage_gemini.py +70 -0
  91. utility_models.py +104 -0
@@ -0,0 +1,650 @@
1
+ "use strict";
2
+
3
+ (() => {
4
+ const row = byId("round-actions");
5
+ const commands = [
6
+ { name: "continue", title: "Continue", hint: "Each model replies once", kind: "respond", icon: "rotate-cw" },
7
+ { name: "agree", title: "Find agreement", hint: "Work toward a shared answer", kind: "discuss", icon: "arrow-right-left" },
8
+ {
9
+ name: "combine",
10
+ title: "Combine",
11
+ hint: "Turn replies into one answer",
12
+ icon: "git-merge",
13
+ kind: "synthesis"
14
+ },
15
+ {
16
+ name: "challenge",
17
+ title: "Challenge",
18
+ hint: "Choose a participant to question a reply",
19
+ kind: "challenge"
20
+ }
21
+ ];
22
+ let phase = "",
23
+ lastState = "",
24
+ lastChat = "";
25
+ let diffRecords = new Map();
26
+ let slashIndex = 0,
27
+ slashMatches = [],
28
+ slashDismissed = "";
29
+ const slashMenu = element("div", "command-options");
30
+ slashMenu.id = "slash-options";
31
+ slashMenu.role = "listbox";
32
+ slashMenu.setAttribute("aria-label", "Conversation commands");
33
+ slashMenu.hidden = true;
34
+ byId("compose-form").prepend(slashMenu);
35
+ draft.setAttribute("aria-controls", slashMenu.id);
36
+ draft.setAttribute("aria-autocomplete", "list");
37
+
38
+ function button(label, fn, className = "") {
39
+ const node = element("button", className, label);
40
+ node.type = "button";
41
+ node.addEventListener("click", fn);
42
+ return node;
43
+ }
44
+
45
+ function icon(action) {
46
+ if (window.diffIcon) return window.diffIcon(action.toLowerCase());
47
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
48
+ const use = document.createElementNS(svg.namespaceURI, "use");
49
+ use.setAttribute("href", "#i-" + action.toLowerCase());
50
+ svg.classList.add("icon");
51
+ svg.setAttribute("aria-hidden", "true");
52
+ svg.append(use);
53
+ return svg;
54
+ }
55
+
56
+ function selected(entry) {
57
+ return { message_index: chat.messages.indexOf(entry), message_id: entry.message_id };
58
+ }
59
+
60
+ function closePhase() {
61
+ phase = "";
62
+ refresh();
63
+ }
64
+
65
+ function cancelAgreement() {
66
+ closePhase();
67
+ row.querySelector(".round-agree")?.focus();
68
+ }
69
+
70
+ let openPicker = null;
71
+ function pickParticipant(trigger, caption, candidates, preferred, choose) {
72
+ if (openPicker?.trigger === trigger) { openPicker.pop.hidePopover(); return; }
73
+ openPicker?.pop.hidePopover();
74
+ if (!trigger || !candidates.length) return;
75
+ const pop = element("div", "combine-popover participant-menu");
76
+ pop.popover = "auto";
77
+ pop.role = "menu";
78
+ pop.setAttribute("aria-label", caption);
79
+ pop.append(element("p", "menu-caption", caption));
80
+ const close = () => pop.hidePopover();
81
+ const items = candidates.map(id => {
82
+ const item = participantStyle(button(names[id], () => {close(); choose(id);}), id);
83
+ item.setAttribute("role", "menuitemradio");
84
+ item.setAttribute("aria-checked", String(id === preferred));
85
+ item.setAttribute("aria-label", names[id]);
86
+ if (id === preferred) item.append(icon("check"));
87
+ item.tabIndex = -1;
88
+ pop.append(item);
89
+ return item;
90
+ });
91
+ const position = () => {
92
+ if (!trigger.isConnected) {close(); return;}
93
+ const r = trigger.getBoundingClientRect();
94
+ pop.style.left = Math.max(8, Math.min(r.left, innerWidth - pop.offsetWidth - 8)) + "px";
95
+ pop.style.top = (r.bottom + 4 + pop.offsetHeight > innerHeight && r.top >= pop.offsetHeight + 8
96
+ ? r.top - 4 - pop.offsetHeight : Math.min(r.bottom + 4, innerHeight - pop.offsetHeight - 8)) + "px";
97
+ };
98
+ pop.addEventListener("keydown", event => {
99
+ const i = items.indexOf(document.activeElement);
100
+ const movement = {ArrowDown:(i+1)%items.length, ArrowUp:(i-1+items.length)%items.length, Home:0, End:items.length-1};
101
+ if (event.key === "Escape" || event.key === "Tab") {
102
+ close(); trigger.focus({preventScroll:true});
103
+ if (event.key === "Escape") event.preventDefault();
104
+ } else if (Object.hasOwn(movement, event.key)) {
105
+ event.preventDefault(); items[movement[event.key]].focus();
106
+ } else if (event.key.length === 1 && !event.metaKey && !event.ctrlKey) {
107
+ const match = items.find(item => item.textContent.toLowerCase().startsWith(event.key.toLowerCase()));
108
+ if (match) {event.preventDefault(); match.focus();}
109
+ }
110
+ });
111
+ pop.addEventListener("toggle", () => {
112
+ if (pop.matches(":popover-open")) return;
113
+ window.removeEventListener("resize", position);
114
+ reader.removeEventListener("scroll", position);
115
+ trigger.setAttribute("aria-expanded", "false");
116
+ pop.remove();
117
+ if (openPicker?.pop === pop) openPicker = null;
118
+ });
119
+ document.body.append(pop);
120
+ trigger.setAttribute("aria-expanded", "true");
121
+ openPicker = {pop,trigger};
122
+ pop.showPopover();
123
+ position();
124
+ window.addEventListener("resize", position);
125
+ reader.addEventListener("scroll", position, {passive:true});
126
+ (items[candidates.indexOf(preferred)] || items[0]).focus({preventScroll:true});
127
+ }
128
+
129
+ function runCommand(name, entry) {
130
+ if (!chat || runId || starting || navigating) return;
131
+ if (!chat.messages.length) {
132
+ feedback("Send a message to start this chat.");
133
+ return;
134
+ }
135
+ const command = commands.find((c) => c.name === name);
136
+ if (!command) return;
137
+ if (name === "challenge") {
138
+ entry ||= chat.messages.findLast(
139
+ (item) => models.includes(item.speaker) && item.text.trim() && !item.error
140
+ );
141
+ if (!entry) {
142
+ feedback("Choose a completed reply to challenge.");
143
+ return;
144
+ }
145
+ }
146
+ const reason = followupRequirement(command.kind);
147
+ if (reason) {
148
+ feedback(reason);
149
+ return;
150
+ }
151
+ feedback();
152
+ if (name === "continue") {
153
+ closePhase();
154
+ startTurn("respond");
155
+ return;
156
+ }
157
+ if (name === "challenge") {
158
+ if (!enabled.has(entry.speaker)) { feedback("Turn on " + names[entry.speaker] + " to receive the challenge."); return; }
159
+ const candidates = models.filter(id => enabled.has(id) && id !== entry.speaker);
160
+ const after = models.indexOf(entry.speaker) + 1;
161
+ const next = [...models.slice(after), ...models.slice(0, after)].find(id => candidates.includes(id));
162
+ const record = visibleRecords.find(record => record.entry === entry);
163
+ const origin = record?.tools.querySelector('[data-action="Challenge"]');
164
+ if (!origin) return;
165
+ origin.scrollIntoView({block:"nearest"});
166
+ pickParticipant(origin, "Who challenges?", candidates, next, challenger => startTurn("challenge", {...selected(entry), challenger}));
167
+ return;
168
+ }
169
+ if (name === "combine") {
170
+ const candidates = models.filter(id => enabled.has(id));
171
+ const preferred = window.diffSettings?.default_combiner;
172
+ const origin = row.querySelector(".round-combine");
173
+ origin?.scrollIntoView({block:"nearest"});
174
+ pickParticipant(origin, "Who combines?", candidates, candidates.includes(preferred) ? preferred : candidates[0],
175
+ combiner => startTurn("synthesis", {combiner}));
176
+ return;
177
+ }
178
+ phase = name;
179
+ refresh();
180
+ row.scrollIntoView({ block: "nearest" });
181
+ row.querySelector("button")?.focus({preventScroll:true});
182
+ }
183
+
184
+ function refresh() {
185
+ for (const r of visibleRecords)
186
+ if (r.tools)
187
+ for (const b of r.tools.children) {
188
+ b.disabled = b.dataset.action !== "Copy" && Boolean(runId || starting || navigating);
189
+ }
190
+ if (lastChat !== chat?.id) {
191
+ phase = "";
192
+ lastChat = chat?.id;
193
+ closeSlash();
194
+ }
195
+ const maxReplies = Math.min(
196
+ (window.diffSettings?.agreement_rounds || 4) * enabled.size,
197
+ window.diffSettings?.max_replies || 8
198
+ );
199
+ const maxRounds = Math.ceil(maxReplies / Math.max(1, enabled.size));
200
+ const chosen = window.diffSettings?.default_combiner || models[0];
201
+ const last = chat?.messages.at(-1);
202
+ let hasReply = false;
203
+ if (last && last.speaker !== "me") {
204
+ for (let i = chat.messages.length - 1; i >= 0; i--) {
205
+ const item = chat.messages[i];
206
+ if (item.speaker === "me" || item.turn_id !== last.turn_id || item.round !== last.round) break;
207
+ if (models.includes(item.speaker) && item.text.trim() && !item.error) {hasReply = true; break;}
208
+ }
209
+ }
210
+ const live = Boolean(runId && activeDiscussion?.status === "running");
211
+ if (starting || runId || navigating) { phase = ""; openPicker?.pop.hidePopover(); }
212
+ const hide = !chat || navigating || (!live && (!hasReply || starting || Boolean(runId)));
213
+ if (hide) phase = "";
214
+ const state = [
215
+ lastChat,
216
+ hide,
217
+ live,
218
+ stopping,
219
+ activeDiscussion?.round,
220
+ enabled.size,
221
+ ...enabled,
222
+ phase,
223
+ maxReplies,
224
+ chosen
225
+ ].join("|");
226
+ if (state === lastState) return;
227
+ lastState = state;
228
+ row.hidden = hide;
229
+ row.replaceChildren();
230
+ if (hide) return;
231
+ if (live) {
232
+ const controls = element("div", "round-confirm");
233
+ const progress = element("span", "round-estimate", roundLabel(activeDiscussion));
234
+ progress.setAttribute("role", "status");
235
+ const stop = button(stopping ? "Stopping…" : "Stop", () => byId("stop").click(), "round-button");
236
+ stop.disabled = stopping;
237
+ controls.append(progress, stop);
238
+ row.append(controls);
239
+ return;
240
+ }
241
+ if (phase === "agree") {
242
+ const controls = element("div", "round-confirm");
243
+ controls.append(
244
+ element("span", "round-estimate", `Up to ${maxRounds} rounds · up to ${maxReplies} replies`),
245
+ button("Start discussion", () => {
246
+ closePhase();
247
+ startTurn("discuss");
248
+ }, "round-button round-primary"),
249
+ button("Cancel", cancelAgreement, "round-button")
250
+ );
251
+ controls.addEventListener("keydown", (event) => {
252
+ if (event.key === "Escape") {
253
+ event.preventDefault();
254
+ cancelAgreement();
255
+ }
256
+ });
257
+ row.append(controls);
258
+ return;
259
+ }
260
+ const choices = element("div", "round-choices");
261
+ row.append(choices);
262
+ commands.slice(0, 3).forEach((item, index) => {
263
+ const wrap = element("div", "round-anchor");
264
+ const control = button("", () => runCommand(item.name), "round-choice round-" + item.name);
265
+ control.setAttribute("aria-label", item.title);
266
+ const modifier = macKeyboard ? "⌘" : "Ctrl+";
267
+ const shortcut = modifier + (index + 1);
268
+ control.setAttribute("aria-keyshortcuts", (macKeyboard ? "Meta+" : "Control+") + (index + 1));
269
+ const reason = followupRequirement(item.kind);
270
+ const tip = element("span", "action-tooltip", [reason || item.hint, shortcut].join(" · "));
271
+ tip.role = "tooltip";
272
+ tip.id = "action-tip-" + item.name;
273
+ control.setAttribute("aria-describedby", tip.id);
274
+ control.disabled = Boolean(reason);
275
+ control.append(icon(item.icon), item.title);
276
+ if (item.name === "combine") {
277
+ control.setAttribute("aria-haspopup", "menu");
278
+ control.setAttribute("aria-expanded", "false");
279
+ control.append(icon("chevron"));
280
+ }
281
+ wrap.append(control, tip);
282
+ choices.append(wrap);
283
+ });
284
+ }
285
+
286
+ document.addEventListener("pointerdown", event => {
287
+ if (!slashMenu.contains(event.target) && event.target !== draft) closeSlash();
288
+ });
289
+ draft.addEventListener("keydown", event => {
290
+ const modifier = macKeyboard ? event.metaKey && !event.ctrlKey : event.ctrlKey && !event.metaKey;
291
+ if (!modifier || event.altKey || event.shiftKey || event.repeat || event.isComposing ||
292
+ draft.value || row.hidden || phase || !/^[123]$/.test(event.key)) return;
293
+ const item = commands[Number(event.key) - 1];
294
+ event.preventDefault();
295
+ runCommand(item.name);
296
+ });
297
+ document.addEventListener("diff:settings", () => {
298
+ lastState = "";
299
+ refresh();
300
+ });
301
+
302
+ function closeSlash() {
303
+ slashMenu.hidden = true;
304
+ draft.removeAttribute("aria-activedescendant");
305
+ }
306
+
307
+ function useSlash(command) {
308
+ if (!command) return false;
309
+ draft.value = "";
310
+ drafts.set(chat.id, "");
311
+ closeSlash();
312
+ resizeDraft();
313
+ updateControls();
314
+ runCommand(command.name);
315
+ return true;
316
+ }
317
+
318
+ function submitSlash() {
319
+ const value = draft.value.trim().toLowerCase();
320
+ return value.startsWith("/") && useSlash(commands.find((c) => "/" + c.name === value));
321
+ }
322
+
323
+ function displaySlash() {
324
+ const value = draft.value;
325
+ if (!/^\/[a-z]*$/i.test(value) || runId || !chat || value === slashDismissed) {
326
+ closeSlash();
327
+ return;
328
+ }
329
+ slashMatches = commands.filter((c) => ("/" + c.name).startsWith(value.toLowerCase()));
330
+ if (!slashMatches.length) {
331
+ closeSlash();
332
+ return;
333
+ }
334
+ slashMenu.replaceChildren();
335
+ slashMenu.hidden = false;
336
+ slashIndex = Math.max(0, Math.min(slashIndex, slashMatches.length - 1));
337
+ slashMatches.forEach((cmd, idx) => {
338
+ const item = button("", () => useSlash(cmd));
339
+ item.id = "slash-" + cmd.name;
340
+ item.role = "option";
341
+ item.tabIndex = -1;
342
+ item.setAttribute("aria-selected", String(idx === slashIndex));
343
+ item.append(element("span", "", "/" + cmd.name), element("span", "command-hint", cmd.hint));
344
+ slashMenu.append(item);
345
+ if (idx === slashIndex) draft.setAttribute("aria-activedescendant", item.id);
346
+ });
347
+ }
348
+ draft.addEventListener("input", () => {
349
+ slashIndex = 0;
350
+ slashDismissed = "";
351
+ displaySlash();
352
+ });
353
+ draft.addEventListener(
354
+ "keydown",
355
+ (e) => {
356
+ if (slashMenu.hidden || e.isComposing) return;
357
+ if (e.key === "Escape") {
358
+ e.preventDefault();
359
+ slashDismissed = draft.value;
360
+ closeSlash();
361
+ return;
362
+ }
363
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
364
+ e.preventDefault();
365
+ slashIndex =
366
+ (slashIndex + (e.key === "ArrowDown" ? 1 : -1) + slashMatches.length) % slashMatches.length;
367
+ displaySlash();
368
+ } else if ((e.key === "Enter" || e.key === "Tab") && !e.shiftKey) {
369
+ e.preventDefault();
370
+ useSlash(slashMatches[slashIndex]);
371
+ }
372
+ },
373
+ true
374
+ );
375
+
376
+ function edit(record) {
377
+ if (record.editor) return;
378
+ const original = record.entry;
379
+ const form = element("form", "message-edit");
380
+ const input = element("textarea");
381
+ input.setAttribute("aria-label", "Edit message");
382
+ input.value = original.text;
383
+ const save = element("button", "", "Save and rerun");
384
+ save.type = "submit";
385
+ const cancel = button("Cancel", close);
386
+ function close() {
387
+ record.editor = null;
388
+ form.remove();
389
+ record.prose.hidden = false;
390
+ record.tools.querySelector('[data-action="Edit"]')?.focus();
391
+ }
392
+ const explanation = element(
393
+ "p",
394
+ "edit-caption",
395
+ "Saving replaces this message and the conversation after it."
396
+ );
397
+ form.append(input, explanation, save, cancel);
398
+ form.addEventListener("submit", async (event) => {
399
+ event.preventDefault();
400
+ if (!input.value.trim()) return;
401
+ save.disabled = true;
402
+ const accepted = await startTurn("edit", { ...selected(original), text: input.value });
403
+ if (accepted) close();
404
+ else save.disabled = false;
405
+ });
406
+ input.addEventListener("keydown", (e) => {
407
+ if (e.key === "Escape") {
408
+ e.preventDefault();
409
+ close();
410
+ }
411
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
412
+ e.preventDefault();
413
+ form.requestSubmit();
414
+ }
415
+ });
416
+ form.dataset.id = original.message_id || "";
417
+ record.editor = form;
418
+ record.prose.hidden = true;
419
+ record.prose.after(form);
420
+ input.focus();
421
+ input.select();
422
+ }
423
+
424
+ function mountMessageTools(record) {
425
+ const tools = element("div", "message-tools");
426
+ tools.role = "group";
427
+ for (const action of ["Copy", "Challenge", "Retry", "Edit", "Branch"]) {
428
+ const control =
429
+ action === "Copy"
430
+ ? record.copy
431
+ : button("", async () => {
432
+ const item = record.entry;
433
+ if (runId || starting || navigating || !chat.messages.includes(item)) return;
434
+ if (action === "Challenge") runCommand("challenge", item);
435
+ else if (action === "Retry") {
436
+ if (!enabled.has(item.speaker)) {
437
+ feedback("Turn on " + names[item.speaker] + " to retry this reply.");
438
+ return;
439
+ }
440
+ startTurn("retry", selected(item));
441
+ } else if (action === "Edit") edit(record);
442
+ else {
443
+ try {
444
+ const result = await api("/api/chats/" + chat.id + "/branch", selected(item));
445
+ await openChat(result.id);
446
+ } catch (e) {
447
+ feedback(e.message);
448
+ }
449
+ }
450
+ });
451
+ control.dataset.action = action;
452
+ if (action === "Challenge") control.setAttribute("aria-haspopup", "menu");
453
+ control.title = action;
454
+ control.setAttribute("aria-label", action);
455
+ control.replaceChildren(icon(action));
456
+ tools.append(control);
457
+ }
458
+ record.article.querySelector(".byline").append(tools);
459
+ record.tools = tools;
460
+ }
461
+
462
+ function updateMessageTools(record, finished) {
463
+ const own = record.speaker === "me";
464
+ record.article.classList.toggle("combined", record.entry.mode === "synthesis");
465
+ if (record.editor && (!own || record.editor.dataset.id !== (record.entry.message_id || ""))) {
466
+ record.editor.remove();
467
+ record.editor = null;
468
+ record.prose.hidden = false;
469
+ }
470
+ for (const control of record.tools.children) {
471
+ const action = control.dataset.action;
472
+ control.hidden =
473
+ ["Edit", "Branch"].includes(action) !== own ||
474
+ !finished ||
475
+ (!own &&
476
+ ((action === "Copy" && !record.entry.text.trim()) ||
477
+ (action === "Challenge" && record.entry.error)));
478
+ control.disabled = action !== "Copy" && Boolean(runId || starting || navigating);
479
+ }
480
+ }
481
+
482
+ function comparisonGroups() {
483
+ const rounds = [];
484
+ let group = [], seen = new Set(), previous;
485
+ function finish() {
486
+ if (group.length >= 2) rounds.push(group);
487
+ group = []; seen = new Set();
488
+ }
489
+ chat.messages.forEach((item, index) => {
490
+ const key = [item.turn_id || item.discussion_id || "", item.round || 0].join("/");
491
+ if (key !== previous || item.speaker === "me" || seen.has(item.speaker) || item.mode === "synthesis") finish();
492
+ previous = key;
493
+ if (!models.includes(item.speaker) || item.error || !item.text.trim()) return;
494
+ seen.add(item.speaker);
495
+ group.push(index);
496
+ });
497
+ finish();
498
+ return rounds;
499
+ }
500
+
501
+ function comparisonBody(view, result) {
502
+ view.summary.replaceChildren();
503
+ for (const [key, title, empty] of [
504
+ ["both", "Both say", "No shared position identified."],
505
+ ["differ", "Where they differ", "No substantive difference identified."]
506
+ ]) {
507
+ const block = element("section", "diff-points");
508
+ block.append(element("h3", "", title));
509
+ if (result[key].length) {
510
+ const list = element("ul");
511
+ result[key].forEach((t) => list.append(element("li", "", t)));
512
+ block.append(list);
513
+ } else block.append(element("p", "", empty));
514
+ view.summary.append(block);
515
+ }
516
+ }
517
+
518
+ async function loadComparison(view) {
519
+ if (view.result || view.loading) return;
520
+ view.loading = true;
521
+ view.summary.textContent = "Comparing replies…";
522
+ try {
523
+ view.result = await api("/api/chats/" + view.chatId + "/comparison", {...view.ref, models:models.filter(id => enabled.has(id))});
524
+ comparisonBody(view, view.result);
525
+ } catch (e) {
526
+ view.summary.replaceChildren(
527
+ element("span", "", e.message),
528
+ button("Try again", () => loadComparison(view))
529
+ );
530
+ } finally {
531
+ view.loading = false;
532
+ }
533
+ }
534
+
535
+ function unfold(view) {
536
+ view.panel.hidden = !view.open;
537
+ view.toggle.setAttribute("aria-pressed", String(view.open));
538
+ if (!view.open) {
539
+ if (view.columns.firstElementChild) view.shell.after(...view.articles);
540
+ return;
541
+ }
542
+ const selected = view.selection.map(index => view.articles[index]);
543
+ view.unselected.replaceChildren(...view.articles.filter(node => !selected.includes(node)));
544
+ view.columns.replaceChildren(...selected);
545
+ loadComparison(view);
546
+ }
547
+
548
+ function installPairPicker(view) {
549
+ const bar = element("div", "diff-picker");
550
+ bar.append(element("span", "", "Compare"));
551
+ const picks = ["First participant", "Second participant"].map((name, side) => {
552
+ const select = element("select");
553
+ select.setAttribute("aria-label", name);
554
+ view.speakers.forEach((id, index) => select.add(new Option(names[id], index)));
555
+ select.value = String(view.selection[side]);
556
+ select.addEventListener("change", () => {
557
+ const next = Number(select.value), prior = view.selection[side], other = 1 - side;
558
+ if (view.selection[other] === next) {
559
+ view.selection[other] = prior;
560
+ picks[other].value = String(prior);
561
+ picks[other].dispatchEvent(new Event("diff-select-sync"));
562
+ }
563
+ view.selection[side] = next;
564
+ unfold(view);
565
+ });
566
+ if (side) bar.append(element("span", "", "and"));
567
+ bar.append(select);
568
+ return select;
569
+ });
570
+ view.panel.insertBefore(bar, view.columns);
571
+ }
572
+
573
+ function renderDiffs() {
574
+ const pending = comparisonGroups().map(indices => {
575
+ const key = JSON.stringify([chat.id, ...indices.map(index => [index, chat.messages[index].message_id || chat.messages[index].text])]);
576
+ return {indices, key};
577
+ });
578
+ const valid = new Set(pending.map((p) => p.key));
579
+ for (const [key, view] of diffRecords)
580
+ if (!valid.has(key)) {
581
+ for (const article of view.articles)
582
+ if (view.shell.contains(article) && visibleRecords.some((r) => r.article === article))
583
+ view.shell.before(article);
584
+ view.shell.remove();
585
+ diffRecords.delete(key);
586
+ }
587
+ for (const [round, { indices, key }] of pending.entries()) {
588
+ if (diffRecords.has(key)) continue;
589
+ const i = indices[0], one = chat.messages[i];
590
+ const articles = indices.map(index => visibleRecords[index].article);
591
+ const shell = element("section", "diff-round"),
592
+ head = element("div", "round-metadata");
593
+ const toggle = button(
594
+ "Compare replies",
595
+ () => {
596
+ view.open = !view.open;
597
+ unfold(view);
598
+ },
599
+ "diff-toggle"
600
+ );
601
+ toggle.prepend(icon("columns-2"));
602
+ toggle.setAttribute("aria-pressed", "false");
603
+ toggle.title = "Compare these replies";
604
+ const label = one.discussion_id
605
+ ? "Discussion · Round " + one.round
606
+ : one.mode === "challenge"
607
+ ? "Challenge"
608
+ : "Round " + (round + 1);
609
+ const marker = element("span", "", label);
610
+ head.append(marker, toggle);
611
+ const panel = element("div", "diff-panel"),
612
+ summary = element("div", "diff-summary"),
613
+ columns = element("div", "diff-columns");
614
+ summary.setAttribute("aria-live", "polite");
615
+ panel.hidden = true;
616
+ const unselected = element("div");
617
+ unselected.hidden = true;
618
+ if (indices.length > 2) panel.append(element("p", "comparison-scope", "Summary of all " + indices.length + " replies"));
619
+ panel.append(summary, columns, unselected);
620
+ shell.append(head, panel);
621
+ const view = {
622
+ shell,
623
+ panel,
624
+ summary,
625
+ columns,
626
+ toggle,
627
+ articles, unselected, selection:[0,1], speakers:indices.map(index => chat.messages[index].speaker),
628
+ open: false,
629
+ loading: false,
630
+ result: null,
631
+ chatId: chat.id,
632
+ ref: { message_index: i, message_id: one.message_id }
633
+ };
634
+ if (indices.length > 2) installPairPicker(view);
635
+ articles[0].before(shell);
636
+ diffRecords.set(key, view);
637
+ }
638
+ }
639
+
640
+ window.chatActions = {
641
+ commands,
642
+ runCommand,
643
+ refresh,
644
+ mountMessageTools,
645
+ updateMessageTools,
646
+ renderDiffs,
647
+ submitSlash,
648
+ icon
649
+ };
650
+ })();