codehaven 0.14.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 (57) hide show
  1. codehaven-0.14.0.dist-info/METADATA +686 -0
  2. codehaven-0.14.0.dist-info/RECORD +57 -0
  3. codehaven-0.14.0.dist-info/WHEEL +5 -0
  4. codehaven-0.14.0.dist-info/entry_points.txt +3 -0
  5. codehaven-0.14.0.dist-info/licenses/LICENSE +21 -0
  6. codehaven-0.14.0.dist-info/top_level.txt +1 -0
  7. offline_agent/__init__.py +2 -0
  8. offline_agent/__main__.py +4 -0
  9. offline_agent/agent.py +815 -0
  10. offline_agent/answers.py +438 -0
  11. offline_agent/arabic.py +106 -0
  12. offline_agent/changes.py +228 -0
  13. offline_agent/chats.py +121 -0
  14. offline_agent/cli.py +379 -0
  15. offline_agent/coder.py +199 -0
  16. offline_agent/dependencies.py +132 -0
  17. offline_agent/doctor.py +190 -0
  18. offline_agent/documents.py +189 -0
  19. offline_agent/edits.py +204 -0
  20. offline_agent/errors.py +41 -0
  21. offline_agent/evaluation.py +284 -0
  22. offline_agent/evidence.py +187 -0
  23. offline_agent/exclusions.py +95 -0
  24. offline_agent/export.py +27 -0
  25. offline_agent/gui.css +237 -0
  26. offline_agent/gui.html +177 -0
  27. offline_agent/gui.js +1213 -0
  28. offline_agent/gui.py +967 -0
  29. offline_agent/gui_arabic.js +226 -0
  30. offline_agent/guides.py +203 -0
  31. offline_agent/history.py +126 -0
  32. offline_agent/index_cache.py +78 -0
  33. offline_agent/insights.py +333 -0
  34. offline_agent/javascript.py +200 -0
  35. offline_agent/knowledge.py +569 -0
  36. offline_agent/languages.py +396 -0
  37. offline_agent/memory.py +192 -0
  38. offline_agent/messages.py +51 -0
  39. offline_agent/model.py +498 -0
  40. offline_agent/more_languages.py +253 -0
  41. offline_agent/ocr.py +204 -0
  42. offline_agent/prompts.py +130 -0
  43. offline_agent/references/langgraph-approvals.md +38 -0
  44. offline_agent/references/langgraph-checkpoints.md +37 -0
  45. offline_agent/references/langgraph-graphs.md +42 -0
  46. offline_agent/references/langgraph.md +49 -0
  47. offline_agent/review.py +205 -0
  48. offline_agent/scans.py +325 -0
  49. offline_agent/semantic.py +264 -0
  50. offline_agent/slash.py +53 -0
  51. offline_agent/study.py +210 -0
  52. offline_agent/symbols.py +201 -0
  53. offline_agent/tasks.py +164 -0
  54. offline_agent/test_runner.py +264 -0
  55. offline_agent/trace.py +239 -0
  56. offline_agent/tracebacks.py +98 -0
  57. offline_agent/workspace.py +419 -0
offline_agent/gui.js ADDED
@@ -0,0 +1,1213 @@
1
+ "use strict";
2
+ // ---- Setup: shared state, limits, and suggested questions.
3
+ // The secret token from the link the server printed; every request sends it back, or the server refuses.
4
+ const TOKEN = new URLSearchParams(location.search).get("token") || "";
5
+ const $ = (id) => document.getElementById(id);
6
+ // busy: a request is running; indexed: something is open; uploaded: it is one uploaded file; browsing: the folder browser's folder.
7
+ // stoppable: the running request is an answer or flashcards, which Stop can end; stopping: Stop was clicked.
8
+ let busy = false, indexed = false, uploaded = false, browsing = "", stoppable = false, stopping = false;
9
+ // indexing: "index" or "clone" while a repository is being indexed or downloaded; that button then reads Stop.
10
+ let indexing = "";
11
+ // The folder of the open repository, for links that open a cited file in an editor; null for an uploaded file.
12
+ let repoRoot = null;
13
+ const UPLOAD_BYTES = 64000; // The same limit as every file CodeHaven reads.
14
+ const PICTURE_BYTES = 8000000; // A picture of code is read into text by Tesseract on this computer.
15
+ const isDocument = (file) => /\.(ipynb|pdf)$/i.test(file.name) || file.type === "application/pdf";
16
+ const isPicture = (file) => /^image\/(png|jpeg)$/.test(file.type) || /\.(png|jpe?g)$/i.test(file.name);
17
+ // ---- Language: English, or Arabic chosen with the button in the top bar and remembered in this browser only.
18
+ // The Arabic page is the same page: its English text is the key each Arabic sentence is looked up by.
19
+ let LANG = "en";
20
+ try { if (localStorage.getItem("codehaven.language") === "ar") LANG = "ar"; } catch {}
21
+ // The Arabic sentences, looked up by their English ones, are kept in gui_arabic.js and put here when the page is served.
22
+ /*__ARABIC__*/
23
+ // A sentence in the page's language, with {name} places filled from values.
24
+ function t(text, values) {
25
+ const found = LANG === "ar" && ARABIC[text] || text;
26
+ return values ? found.replace(/\{(\w+)\}/g, (place, name) => values[name] ?? place) : found;
27
+ }
28
+ // A count with its noun: "3 files". Arabic has its own form for one, for two, for 3 to 10, and for 11 or more.
29
+ function count(number, word) {
30
+ if (LANG !== "ar") return plural(number, word);
31
+ const forms = ARABIC_NOUNS[word];
32
+ if (number === 1 || number === 2) return forms[number - 1];
33
+ return `${number} ${number % 100 >= 3 && number % 100 <= 10 ? forms[2] : forms[3]}`;
34
+ }
35
+ // Put the page that was written in English into Arabic, and lay it out right to left. Runs once, before anything
36
+ // else reads text from the page.
37
+ function translatePage() {
38
+ document.documentElement.lang = "ar"; document.documentElement.dir = "rtl";
39
+ const texts = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
40
+ for (let node; (node = texts.nextNode());) {
41
+ const text = node.nodeValue.trim();
42
+ if (text && ARABIC[text] && !node.parentElement.closest("script, style")) node.nodeValue = node.nodeValue.replace(text, ARABIC[text]);
43
+ }
44
+ for (const element of document.querySelectorAll("[title], [placeholder], [aria-label], [data-drop]")) {
45
+ for (const name of ["title", "placeholder", "aria-label", "data-drop"]) {
46
+ const value = element.getAttribute(name);
47
+ if (value && ARABIC[value]) element.setAttribute(name, ARABIC[value]);
48
+ }
49
+ }
50
+ // The button offers the other language, written in that language.
51
+ Object.assign($("language"), {textContent: "English", title: "Show this page in English", lang: "en"});
52
+ }
53
+ if (LANG === "ar") translatePage();
54
+ $("language").addEventListener("click", () => {
55
+ if (busy) return;
56
+ // The empty state is hidden once a chat has messages; only then is there something to lose.
57
+ if ($("empty").hidden && !confirm(t("Switching the language reloads the page, which starts a new chat. Continue?"))) return;
58
+ try { localStorage.setItem("codehaven.language", LANG === "ar" ? "en" : "ar"); } catch { toast(t("This browser did not allow saving the language.")); return; }
59
+ location.reload();
60
+ });
61
+ // Suggested questions, as [button label, question] pairs. The Arabic ones are asked, and so answered, in Arabic.
62
+ const REPOSITORY_SUGGESTIONS = LANG === "ar" ? [
63
+ ["اشرح المشروع", "اشرح هذا المشروع"],
64
+ ["اشرح README.md", "اشرح README.md"],
65
+ ["الوحدات الرئيسية", "ما هي الوحدات الرئيسية وما وظيفة كل منها؟"],
66
+ ["الاختبارات", "ما هي الاختبارات الموجودة وماذا تفحص؟"],
67
+ ["جولة في المشروع", "أعطني جولة في المشروع: أي الملفات يجب أن أقرأ أولا؟"],
68
+ ["فجوات الاختبارات", "أي الدوال بدون اختبارات؟"],
69
+ ] : [
70
+ ["Explain this project", "Explain this project"],
71
+ ["Explain README.md", "Explain README.md"],
72
+ ["Main modules", "What are the main modules and what does each do?"],
73
+ ["Tests", "Which tests are there and what do they check?"],
74
+ ["Project tour", "Give me a project tour: which files should I read first?"],
75
+ ["Test gaps", "Which functions have no tests?"],
76
+ ];
77
+ const GIT_SUGGESTIONS = LANG === "ar" ? [
78
+ ["تغييراتي", "اشرح تغييراتي"],
79
+ ["آخر commit", "ماذا تغير في آخر commit؟"],
80
+ ] : [
81
+ ["My changes", "Explain my uncommitted changes"],
82
+ ["Last commit", "What changed in my last commit?"],
83
+ ];
84
+ // A short message that goes away by itself, for errors that do not belong to one part of the page.
85
+ let toastTimer = null;
86
+ // Show a short message at the bottom of the page for a few seconds.
87
+ function toast(message) {
88
+ const box = $("toast");
89
+ box.textContent = message; box.hidden = false;
90
+ clearTimeout(toastTimer);
91
+ toastTimer = setTimeout(() => { box.hidden = true; }, 6000);
92
+ }
93
+ // Search by meaning uses a second local model; say whether it is on, and how far along it is.
94
+ function meaningNote(meaning) {
95
+ if (!meaning) return "";
96
+ if (meaning.failed) return " " + t("Search by meaning stopped, so answers use key words.");
97
+ return " " + (meaning.ready >= meaning.total ? t("Search by meaning is on.")
98
+ : t("Search by meaning: {ready} of {total} passages ready, the rest are being prepared.", meaning));
99
+ }
100
+ // Suggested questions for one uploaded file, as [button label, question] pairs.
101
+ function fileSuggestions(name) {
102
+ return LANG === "ar" ? [
103
+ [`اشرح ${name}`, `اشرح ${name}`],
104
+ ["الأجزاء الرئيسية", `ما هي الدوال أو الأقسام الرئيسية في ${name} وما وظيفة كل منها؟`],
105
+ ["مراجعة", `راجع ${name}`],
106
+ ] : [
107
+ [`Explain ${name}`, `Explain ${name}`],
108
+ ["Main parts", `What are the main functions or sections in ${name}, and what does each do?`],
109
+ ["Review", `Review ${name}`],
110
+ ];
111
+ }
112
+ // Show the suggestions as buttons; clicking one asks its question.
113
+ function setSuggestions(items) {
114
+ $("suggestions").replaceChildren(...items.map(([label, question]) => {
115
+ const button = document.createElement("button");
116
+ button.textContent = label;
117
+ button.addEventListener("click", () => ask(question));
118
+ return button;
119
+ }));
120
+ }
121
+
122
+ // ---- Talking to the server.
123
+ // fetch, with a plain message when the local server cannot be reached instead of the browser's "Failed to fetch".
124
+ async function reach(path, options) {
125
+ try { return await fetch(path, options); }
126
+ catch (error) {
127
+ if (error.name === "AbortError") throw error;
128
+ throw new Error(t("CodeHaven's local server is not answering. Check that the terminal running codehaven --gui is still open, then reload this page."));
129
+ }
130
+ }
131
+ // One JSON request. A refused one throws the server's own error message.
132
+ async function api(path, options = {}) {
133
+ const response = await reach(path, {...options, headers: {"Content-Type": "application/json", "X-CodeHaven-Token": TOKEN}});
134
+ const data = await response.json().catch(() => ({}));
135
+ if (!response.ok) throw new Error(data.error || response.statusText);
136
+ return data;
137
+ }
138
+
139
+ // ---- Streaming answers from the server.
140
+ // Events of a streamed reply: the server sends one JSON object per line.
141
+ async function* streamEvents(path, body) {
142
+ const response = await reach(path, {method: "POST", headers: {"Content-Type": "application/json", "X-CodeHaven-Token": TOKEN},
143
+ body: JSON.stringify(body)});
144
+ if (!response.ok) { const data = await response.json().catch(() => ({})); throw new Error(data.error || response.statusText); }
145
+ const reader = response.body.getReader();
146
+ const decoder = new TextDecoder();
147
+ let buffer = "";
148
+ while (true) {
149
+ const {value, done} = await reader.read();
150
+ if (done) break;
151
+ buffer += decoder.decode(value, {stream: true});
152
+ let newline;
153
+ while ((newline = buffer.indexOf("\n")) >= 0) {
154
+ const raw = buffer.slice(0, newline); buffer = buffer.slice(newline + 1);
155
+ if (raw.trim()) yield JSON.parse(raw);
156
+ }
157
+ }
158
+ }
159
+
160
+ // ---- Safe rendering: escape everything first, then add a small set of markup.
161
+ function esc(text) {
162
+ return text.replace(/[&<>"']/g, (c) => ({"&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;"}[c]));
163
+ }
164
+ // A citation such as src/app.py:12 or src/app.py:12-20, with or without repo/ in front.
165
+ const CITE = /(^|[\s(\[>,;:،؛])((?:repo\/)?[\wء-ي./-]+\.[A-Za-z]\w*):(\d+)(?:-(\d+))?(?![\w/])/g;
166
+ // Arabic and Hebrew read right to left. Code and file names are left out when deciding, so an Arabic sentence
167
+ // that starts with store.py:12 or `add` is still laid out right to left.
168
+ const LETTER = /[A-Za-z֐-ࣿיִ-﷿ﹰ-ﻼ]/;
169
+ // "rtl" when the first real letter of text is Arabic or Hebrew, otherwise "ltr". Code and file names are skipped.
170
+ function direction(text) {
171
+ const first = text.replace(/`[^`]*`/g, " ").replace(/\S*[\w)]\.\w+(?::\d+(?:-\d+)?)?/g, " ").match(LETTER);
172
+ return first && !/[A-Za-z]/.test(first[0]) ? "rtl" : "ltr";
173
+ }
174
+ const dirAttr = (text) => ` dir="${direction(text)}"`;
175
+ // One line of text as safe HTML: code spans, bold, and clickable citations.
176
+ function inline(text) {
177
+ let html = esc(text);
178
+ html = html.replace(/`([^`]+)`/g, "<code>$1</code>");
179
+ html = html.replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>");
180
+ return html.replace(CITE, (m, pre, path, start, end) =>
181
+ `${pre}<a href="#" class="cite" data-path="${path}" data-start="${start}" data-end="${end || start}">${path}:${start}${end ? "-" + end : ""}</a>`);
182
+ }
183
+ // A whole answer as safe HTML: paragraphs, lists, headings, and fenced code blocks.
184
+ function render(text) {
185
+ const out = [];
186
+ let list = null, para = [];
187
+ const flushPara = () => { if (para.length) { out.push(`<p${dirAttr(para.join(" "))}>${para.map(inline).join("<br>")}</p>`); para = []; } };
188
+ const flushList = () => { if (list) { out.push(`<${list.tag}${dirAttr(list.first)}>${list.items.join("")}</${list.tag}>`); list = null; } };
189
+ const lines = text.replace(/\r/g, "").split("\n");
190
+ for (let i = 0; i < lines.length; i++) {
191
+ const line = lines[i];
192
+ if (/^\s*```/.test(line)) {
193
+ flushPara(); flushList();
194
+ const code = [];
195
+ while (++i < lines.length && !/^\s*```/.test(lines[i])) code.push(lines[i]);
196
+ out.push(`<pre><code>${esc(code.join("\n"))}</code></pre>`);
197
+ continue;
198
+ }
199
+ const bullet = line.match(/^\s*(?:[-*•]|(\d+)[.)])\s+(.*)$/);
200
+ if (bullet) {
201
+ flushPara();
202
+ const tag = bullet[1] ? "ol" : "ul";
203
+ if (!list || list.tag !== tag) { flushList(); list = {tag, items: [], first: bullet[2]}; }
204
+ list.items.push(`<li>${inline(bullet[2])}</li>`);
205
+ continue;
206
+ }
207
+ const heading = line.match(/^\s*#{1,6}\s+(.*)$/);
208
+ if (heading) { flushPara(); flushList(); out.push(`<h4${dirAttr(heading[1])}>${inline(heading[1])}</h4>`); continue; }
209
+ if (!line.trim()) { flushPara(); flushList(); continue; }
210
+ if (list && /^\s{2,}\S/.test(line)) { list.items[list.items.length - 1] = list.items[list.items.length - 1].replace(/<\/li>$/, `<br>${inline(line.trim())}</li>`); continue; }
211
+ flushList();
212
+ para.push(line);
213
+ }
214
+ flushPara(); flushList();
215
+ return out.join("");
216
+ }
217
+
218
+ // ---- Recent repositories live only in this browser.
219
+ function recent() { try { return JSON.parse(localStorage.getItem("codehaven.recent") || "[]"); } catch { return []; } }
220
+ // Put a repository at the top of the recent list (six at most), kept in this browser only.
221
+ function remember(path) {
222
+ try { localStorage.setItem("codehaven.recent", JSON.stringify([path, ...recent().filter((p) => p !== path)].slice(0, 6))); } catch {}
223
+ showRecent();
224
+ }
225
+ // Draw the recent repositories as buttons that reopen them.
226
+ function showRecent() {
227
+ const paths = recent();
228
+ $("recent-section").hidden = !paths.length;
229
+ $("recent").replaceChildren(...paths.map((path) => {
230
+ const button = document.createElement("button");
231
+ button.textContent = path.split("/").filter(Boolean).pop() || path;
232
+ button.title = path;
233
+ button.addEventListener("click", () => { $("path").value = path; indexRepository(); });
234
+ return button;
235
+ }));
236
+ }
237
+
238
+ // ---- Indexing.
239
+ const UPLOAD_HINT = $("upload-status").textContent;
240
+ // Update the whole page from the server's summary of what is open.
241
+ function setIndexed(summary) {
242
+ indexed = Boolean(summary.repository || summary.upload);
243
+ repoRoot = summary.repository || null;
244
+ uploaded = Boolean(summary.upload);
245
+ $("model-name").textContent = summary.model || t("a local model");
246
+ setClone(Boolean(summary.clone));
247
+ $("undo-change").hidden = !summary.edits;
248
+ setSaved(summary);
249
+ setChats(summary.chats);
250
+ if (!indexed) return;
251
+ $("start").hidden = true; $("suggest-label").hidden = false;
252
+ $("empty-title").textContent = t("Ask about your code");
253
+ document.body.classList.remove("menu-open"); $("overlay").classList.remove("open");
254
+ $("repo-label").classList.remove("empty");
255
+ $("index-pill").hidden = false;
256
+ const status = $("index-status"), upload = $("upload-status");
257
+ status.classList.remove("error"); upload.classList.remove("error");
258
+ if (summary.upload) {
259
+ $("repo-label").textContent = t("{name} · uploaded file", {name: summary.upload});
260
+ $("repo-label").title = "";
261
+ $("index-pill").textContent = count(1, "file");
262
+ status.textContent = t("Choose a folder, then index it to chat about a whole repository.");
263
+ upload.replaceChildren(t("Chatting about "), Object.assign(document.createElement("strong"), {textContent: summary.upload}),
264
+ t(". The copy CodeHaven reads is deleted when you open something else; your original is never touched."));
265
+ $("empty-text").textContent = t("Ask how something in {name} works. Answers cite the exact lines they rely on; click a citation to see the code.", {name: summary.upload});
266
+ setSuggestions(fileSuggestions(summary.upload));
267
+ setPicture(summary);
268
+ } else {
269
+ setPicture({});
270
+ $("repo-label").textContent = summary.repository.replace(/[\\/]+$/, "").split(/[\\/]/).pop() || summary.repository;
271
+ $("repo-label").title = summary.repository;
272
+ $("index-pill").textContent = t("{files} indexed", {files: count(summary.files, "file")});
273
+ status.innerHTML = t("<strong>{n}</strong> files indexed.", {n: Number(summary.files)}) +
274
+ (summary.limited ? " " + t("Index limits were reached, so some files are left out; answers can still search and read them.") : "") +
275
+ meaningNote(summary.meaning);
276
+ upload.textContent = UPLOAD_HINT;
277
+ $("path").value = summary.repository;
278
+ $("empty-text").textContent = t("Ask how something in this repository works. Answers cite the exact lines they rely on; click a citation to see the code.");
279
+ setSuggestions(REPOSITORY_SUGGESTIONS.concat(summary.git ? GIT_SUGGESTIONS : []));
280
+ }
281
+ $("suggestions").hidden = false;
282
+ updateComposer();
283
+ }
284
+ // Index the folder typed or chosen in the sidebar, and start an empty chat about it.
285
+ async function indexRepository() {
286
+ if (indexing === "index") return stopIndexing();
287
+ const path = $("path").value.trim();
288
+ if (!path || busy) return;
289
+ busy = true; indexing = "index"; updateComposer();
290
+ const status = $("index-status");
291
+ status.classList.remove("error");
292
+ status.textContent = t("Indexing… this usually takes a few seconds.");
293
+ try {
294
+ const summary = await api("/api/open", {method: "POST", body: JSON.stringify({path})});
295
+ if (summary.stopped) {
296
+ status.textContent = t(indexed ? "Stopped. Nothing new was indexed; the project open before is still open."
297
+ : "Stopped. Nothing was indexed.");
298
+ return;
299
+ }
300
+ clearChat(); resetStudy();
301
+ setIndexed(summary);
302
+ remember(summary.repository);
303
+ } catch (error) {
304
+ status.classList.add("error");
305
+ status.textContent = error.message;
306
+ } finally {
307
+ busy = stopping = false; indexing = ""; updateComposer();
308
+ }
309
+ }
310
+ // Stop the index or download in progress; the request that started it then returns with "stopped".
311
+ async function stopIndexing() {
312
+ if (!indexing || stopping) return;
313
+ stopping = true; updateComposer();
314
+ try { await api("/api/stop", {method: "POST", body: "{}"}); }
315
+ catch (error) { stopping = false; updateComposer(); toast(error.message); }
316
+ }
317
+
318
+ // ---- Long-term memory, unless the server was started with --no-remember: checked answers kept on this computer.
319
+ let remembering = false, savedCount = 0;
320
+ // Show how many answers are saved. kept is true when the answer just given was added.
321
+ function setSaved(summary, kept) {
322
+ remembering = Boolean(summary.remember ?? remembering);
323
+ savedCount = summary.saved || 0;
324
+ $("saved-section").hidden = !remembering;
325
+ if (!remembering) return;
326
+ $("privacy-saved").textContent = t(" Checked answers and your chats are saved on this computer only.");
327
+ $("saved-status").textContent = uploaded ? t("Uploaded files are never remembered.")
328
+ : !indexed ? t("Checked answers and chats are kept on this computer.")
329
+ : t("{answers} for this project{added}. An answer is used again only while the files it cites are unchanged.",
330
+ {answers: count(savedCount, "saved answer"), added: kept ? t(" (one just added)") : ""});
331
+ $("forget").disabled = busy || uploaded || !(savedCount || chatCount);
332
+ }
333
+ $("forget").addEventListener("click", async () => {
334
+ if (!confirm(t("Delete the {answers} and {chats} for this project? This cannot be undone.",
335
+ {answers: count(savedCount, "saved answer"), chats: count(chatCount, "saved chat")}))) return;
336
+ try { const summary = await api("/api/forget", {method: "POST", body: "{}"}); setSaved(summary); setChats(summary.chats); } catch (error) { toast(error.message); }
337
+ });
338
+
339
+ // ---- Saved chats: earlier conversations about this repository, kept on this computer and reopened with a click.
340
+ let chatCount = 0;
341
+ // Rebuild the sidebar's list of saved chats, each with a delete button.
342
+ function setChats(chats) {
343
+ chats = chats || [];
344
+ chatCount = chats.length;
345
+ $("forget").disabled = busy || uploaded || !(savedCount || chatCount);
346
+ $("chats-section").hidden = !chats.length || uploaded;
347
+ $("chats").replaceChildren(...chats.map((chat) => {
348
+ const row = document.createElement("div"); row.className = "chat-row";
349
+ const open = document.createElement("button");
350
+ open.textContent = chat.title; open.dir = "auto";
351
+ open.title = t("{questions} · last used {when}", {questions: count(chat.questions, "question"), when: chat.updated.replace("T", " ")});
352
+ open.addEventListener("click", () => openChat(chat.id));
353
+ const remove = document.createElement("button"); remove.className = "chat-delete"; remove.textContent = "×";
354
+ remove.title = t("Delete this saved chat"); remove.setAttribute("aria-label", t("Delete the saved chat {title}", chat));
355
+ remove.addEventListener("click", async () => {
356
+ if (busy || !confirm(t("Delete the saved chat \"{title}\"? This cannot be undone.", chat))) return;
357
+ try { setChats((await api("/api/chat/delete", {method: "POST", body: JSON.stringify({id: chat.id})})).chats); } catch (error) { toast(error.message); }
358
+ });
359
+ row.append(open, remove);
360
+ return row;
361
+ }));
362
+ }
363
+ // Reopen a saved chat: its questions and answers are shown again, and the server remembers them for follow-ups.
364
+ async function openChat(id) {
365
+ if (busy) return;
366
+ try {
367
+ const chat = await api("/api/chat", {method: "POST", body: JSON.stringify({id})});
368
+ setView("chat");
369
+ clearChat();
370
+ addMessage("note").textContent = t("Saved chat, last used {when}. The code may have changed since: cited lines open the files as they are now.", {when: chat.updated.replace("T", " ")});
371
+ for (const turn of chat.turns) {
372
+ keepTurn(turn.question, turn.answer, turn.issues);
373
+ addMessage("user").textContent = turn.question;
374
+ const card = addMessage("assistant");
375
+ const answer = document.createElement("div"); answer.className = "answer"; answer.innerHTML = render(turn.answer);
376
+ card.append(answer);
377
+ if (turn.issues.length) {
378
+ const checks = document.createElement("div"); checks.className = "checks";
379
+ const title = document.createElement("strong"); title.textContent = t("Unverified: check the cited lines before relying on this answer.");
380
+ const list = document.createElement("ul");
381
+ for (const issue of turn.issues) { const item = document.createElement("li"); item.dir = "auto"; item.textContent = issue; list.append(item); }
382
+ checks.append(title, list); card.append(checks);
383
+ }
384
+ }
385
+ $("memory-status").textContent = t("Reopened a saved chat. Follow-ups remember {remembered} of its questions.", chat);
386
+ scrollDown();
387
+ } catch (error) { toast(error.message); }
388
+ }
389
+
390
+ // ---- GitHub, only when the server was started with --allow-clone: git on this computer downloads it once.
391
+ let cloneOn = false;
392
+ // Show the GitHub section and change the offline wording, the first time the server says cloning is on.
393
+ function setClone(on) {
394
+ if (on === cloneOn) return;
395
+ cloneOn = on;
396
+ $("clone-section").hidden = !on;
397
+ if (!on) return;
398
+ $("offline-pill").textContent = t("Offline · GitHub download on");
399
+ $("offline-pill").title = t("CodeHaven connects to the internet only to download a GitHub repository you ask for. Nothing is uploaded.");
400
+ $("offline-text").textContent = t("Your code never leaves this computer. GitHub downloads are on: they run only when you click Download, and upload nothing.");
401
+ $("privacy-network").textContent = t("Only GitHub downloads you ask for use the internet; nothing is sent.");
402
+ }
403
+ // Download a GitHub repository by its address, then index the copy. Only offered with --allow-clone.
404
+ async function cloneRepository() {
405
+ if (indexing === "clone") return stopIndexing();
406
+ const address = $("github").value.trim();
407
+ if (!address || busy) return;
408
+ busy = true; indexing = "clone"; updateComposer();
409
+ const status = $("clone-status");
410
+ status.classList.remove("error");
411
+ status.textContent = t("Downloading from GitHub… this can take a minute for large repositories.");
412
+ try {
413
+ const summary = await api("/api/clone", {method: "POST", body: JSON.stringify({address})});
414
+ if (summary.stopped) {
415
+ status.textContent = t("Stopped. Nothing was downloaded or kept.");
416
+ return;
417
+ }
418
+ clearChat(); resetStudy();
419
+ setIndexed(summary);
420
+ remember(summary.repository);
421
+ status.replaceChildren(summary.cloned ? t("Downloaded ") : t("Opened the copy already on this computer of "),
422
+ Object.assign(document.createElement("strong"), {textContent: summary.source}),
423
+ summary.cloned ? t(". It is kept on this computer and opens offline from Recent.") : t(", without using the internet."));
424
+ $("github").value = "";
425
+ } catch (error) {
426
+ status.classList.add("error");
427
+ status.textContent = error.message;
428
+ } finally {
429
+ busy = stopping = false; indexing = ""; updateComposer();
430
+ }
431
+ }
432
+ $("clone").addEventListener("click", cloneRepository);
433
+ $("github").addEventListener("keydown", (event) => { if (event.key === "Enter") cloneRepository(); });
434
+
435
+ // ---- A picture of code: Tesseract on this computer read it into the uploaded file. Reading is never perfect,
436
+ // so the lines to compare with the picture are listed, and the text can be saved as a file.
437
+ function lineLink(name, number, text) { // Opened by the same click handler as the citations in answers.
438
+ const link = Object.assign(document.createElement("a"), {href: "#", className: "cite", textContent: text || String(number)});
439
+ link.dataset.path = name; link.dataset.start = link.dataset.end = number;
440
+ return link;
441
+ }
442
+ // What to say about a picture that was read: how many lines, which to compare, and whether it is valid Python.
443
+ function pictureNotes(summary) {
444
+ const picture = summary.picture, name = summary.upload;
445
+ const notes = [t("Read {lines} from the picture {image} into ", {lines: count(picture.lines, "line"), image: picture.image}), Object.assign(document.createElement("strong"), {textContent: name}),
446
+ t(". Reading a picture can get characters wrong, so check the text before you run it.")];
447
+ if (picture.check.length) notes.push(t(" Compare with the picture: line "), ...picture.check.flatMap((number, index) => [index ? ", " : "", lineLink(name, number)]), ".");
448
+ if (picture.syntax) notes.push(Object.assign(document.createElement("strong"), {textContent: t(" Not valid Python yet ({problem}).", {problem: picture.syntax})}));
449
+ else if (name.endsWith(".py")) notes.push(t(" It is valid Python."));
450
+ return notes;
451
+ }
452
+ // The sidebar note and Save button for a picture, notebook, or PDF that was read into text.
453
+ function setPicture(summary) {
454
+ $("picture-status").hidden = $("save-row").hidden = !(summary.picture || summary.document);
455
+ if (!summary.picture && !summary.document) return;
456
+ $("picture-status").replaceChildren(...(summary.picture ? pictureNotes(summary) : [summary.document.note]));
457
+ $("save-text").textContent = t("Save {name}…", {name: summary.upload});
458
+ }
459
+ // Save the text read from the upload as a file, through a download link that exists only for the click.
460
+ async function saveText(name) {
461
+ try {
462
+ const file = await api("/api/text");
463
+ if (name && file.name !== name) throw new Error(t("{name} is no longer open, so it cannot be saved. Attach the picture again.", {name}));
464
+ const link = Object.assign(document.createElement("a"), {href: URL.createObjectURL(new Blob([file.text], {type: "text/plain"})), download: file.name});
465
+ document.body.append(link); link.click(); link.remove();
466
+ setTimeout(() => URL.revokeObjectURL(link.href), 1000);
467
+ } catch (error) { toast(error.message); }
468
+ }
469
+ $("save-text").addEventListener("click", () => saveText());
470
+ // The note a file leaves in the chat when it is attached, pasted, or uploaded while a conversation is open.
471
+ function uploadNote(summary, chatting) {
472
+ const name = summary.upload;
473
+ const notes = summary.picture ? pictureNotes(summary)
474
+ : [summary.document ? summary.document.note + " " : "", t("Now chatting about "), Object.assign(document.createElement("strong"), {textContent: name}), "."];
475
+ if (chatting) notes.push(t(" The chat above is kept and follow-up questions still remember it, but its citations point to what was open before, so they no longer open."));
476
+ if (summary.picture || summary.document) {
477
+ const save = Object.assign(document.createElement("button"), {textContent: t("Save {name}…", {name})});
478
+ save.addEventListener("click", () => saveText(name));
479
+ notes.push(" ", lineLink(name, 1, t("View {name}", {name})), save);
480
+ }
481
+ return notes;
482
+ }
483
+
484
+ // ---- One uploaded file, for a quick question without a repository. The file goes only to this local server.
485
+ // The chat is kept: a file attached or pasted in the composer (fromChat) reports its progress there as well.
486
+ async function uploadFile(file, fromChat = false) {
487
+ if (!file || busy) return;
488
+ const status = $("upload-status"), picture = isPicture(file) || isDocument(file), chatting = $("empty").hidden;
489
+ let note = null;
490
+ const report = (text, failed = false) => {
491
+ status.classList.toggle("error", failed); status.textContent = text;
492
+ if (!fromChat) return;
493
+ note = note || addMessage("note");
494
+ note.classList.toggle("error", failed); note.textContent = text; scrollDown();
495
+ };
496
+ if (file.size > (picture ? PICTURE_BYTES : UPLOAD_BYTES)) {
497
+ const size = {name: file.name, size: Math.ceil(file.size / (picture ? 1000000 : 1000))};
498
+ report(isDocument(file) ? t("{name} is {size} MB; CodeHaven reads notebooks and PDFs up to 8 MB.", size)
499
+ : picture ? t("{name} is {size} MB; CodeHaven reads pictures up to 8 MB. Crop it to the code.", size)
500
+ : t("{name} is {size} KB; CodeHaven reads text files up to 64 KB. Index its folder instead to ask about part of it.", size), true);
501
+ return;
502
+ }
503
+ busy = true; updateComposer();
504
+ report(t(isDocument(file) ? "Reading {name} into text…" : picture ? "Reading the code in {name}… this takes a few seconds." : "Reading {name}…", {name: file.name}));
505
+ try {
506
+ const response = await reach("/api/upload?name=" + encodeURIComponent(file.name),
507
+ {method: "POST", headers: {"Content-Type": "application/octet-stream", "X-CodeHaven-Token": TOKEN}, body: file});
508
+ const summary = await response.json().catch(() => ({}));
509
+ if (!response.ok) throw new Error(summary.error || response.statusText);
510
+ resetStudy();
511
+ setIndexed(summary);
512
+ if (summary.picture || chatting || note) {
513
+ note = note || addMessage("note");
514
+ note.replaceChildren(...uploadNote(summary, chatting)); scrollDown();
515
+ }
516
+ } catch (error) {
517
+ report(error.message, true);
518
+ } finally {
519
+ busy = false; updateComposer();
520
+ }
521
+ }
522
+ let attaching = false; // Whether the file chooser was opened from the composer rather than the sidebar.
523
+ $("upload").addEventListener("click", () => { attaching = false; $("file-input").click(); });
524
+ $("attach").addEventListener("click", () => { attaching = true; $("file-input").click(); });
525
+ $("file-input").addEventListener("change", () => { const file = $("file-input").files[0]; $("file-input").value = ""; uploadFile(file, attaching); });
526
+ // A copied screenshot or file pasted anywhere on the page is attached. Pasted text is left alone, including text
527
+ // copied from an app that also puts a picture of it on the clipboard.
528
+ document.addEventListener("paste", (event) => {
529
+ const data = event.clipboardData;
530
+ if (!data || !data.files.length || data.getData("text/plain")) return;
531
+ event.preventDefault();
532
+ uploadFile(data.files[0], true);
533
+ });
534
+ // Dragging a file over the page. dragenter and dragleave fire for every element crossed, so a count tells when the
535
+ // file has really left the page.
536
+ let dragDepth = 0;
537
+ const dragsFiles = (event) => Array.from(event.dataTransfer?.types || []).includes("Files");
538
+ document.addEventListener("dragenter", (event) => { if (!dragsFiles(event)) return; event.preventDefault(); dragDepth++; if (!busy) document.body.classList.add("dropping"); });
539
+ document.addEventListener("dragover", (event) => { if (dragsFiles(event)) event.preventDefault(); });
540
+ document.addEventListener("dragleave", () => { if (--dragDepth <= 0) { dragDepth = 0; document.body.classList.remove("dropping"); } });
541
+ document.addEventListener("drop", (event) => {
542
+ if (!dragsFiles(event)) return;
543
+ event.preventDefault();
544
+ dragDepth = 0; document.body.classList.remove("dropping");
545
+ const files = event.dataTransfer.files;
546
+ if (files.length > 1) { $("upload-status").classList.add("error"); $("upload-status").textContent = t("Drop one file at a time, or index the folder that holds them."); return; }
547
+ uploadFile(files[0], true);
548
+ });
549
+
550
+ // ---- Folder browser.
551
+ // List the folders inside path in the folder browser; clicking one goes into it.
552
+ async function browse(path) {
553
+ try {
554
+ const data = await api("/api/dirs?path=" + encodeURIComponent(path || ""));
555
+ browsing = data.path;
556
+ $("browser-path").textContent = data.path + (data.repository ? t(" (Git repository)") : "");
557
+ $("up").disabled = !data.parent;
558
+ $("up").onclick = () => browse(data.parent);
559
+ const items = data.entries.map((entry) => {
560
+ const button = document.createElement("button");
561
+ const name = document.createElement("span");
562
+ name.textContent = "📁 " + entry.name;
563
+ button.append(name);
564
+ if (entry.repository) { const tag = document.createElement("span"); tag.className = "tag"; tag.textContent = t("Git repository"); button.append(tag); }
565
+ button.addEventListener("click", () => browse(entry.path));
566
+ return button;
567
+ });
568
+ if (!items.length) { const empty = document.createElement("div"); empty.className = "index-status"; empty.style.padding = "8px 10px"; empty.textContent = t("No folders here."); items.push(empty); }
569
+ $("browser-list").replaceChildren(...items);
570
+ } catch (error) {
571
+ $("browser-path").textContent = error.message;
572
+ }
573
+ }
574
+ // Opening and closing the dialogs, the drawer, and (on a small screen) the sidebar.
575
+ function openBrowser() { document.body.classList.remove("menu-open"); $("overlay").classList.add("open"); $("browser").classList.add("open"); browse($("path").value.trim()); }
576
+ // Close whatever is open on top of the page: the menu, the folder browser, the file picker, and the code drawer.
577
+ function closeOverlays() { document.body.classList.remove("menu-open"); for (const id of ["overlay", "browser", "picker", "drawer"]) $(id).classList.remove("open"); }
578
+ $("menu").addEventListener("click", () => { document.body.classList.add("menu-open"); $("overlay").classList.add("open"); });
579
+ $("start-folder").addEventListener("click", openBrowser);
580
+ $("start-file").addEventListener("click", () => { attaching = false; $("file-input").click(); });
581
+
582
+ // ---- Cited code.
583
+ // A link VS Code understands on its own, with no extension: vscode://file/<full path>:<line>.
584
+ function editorLink(path, line) {
585
+ const full = (repoRoot + "/" + path).replace(/\\/g, "/").replace(/\/{2,}/g, "/");
586
+ return "vscode://file" + (full.startsWith("/") ? "" : "/") + encodeURI(full) + ":" + line;
587
+ }
588
+ // Open the drawer on a file with the cited lines highlighted and a few lines around them.
589
+ async function showCitation(path, start, end) {
590
+ $("drawer-editor").hidden = true;
591
+ $("drawer-title").textContent = `${path}:${start}${end !== start ? "-" + end : ""}`;
592
+ $("drawer-code").textContent = t("Loading…");
593
+ $("overlay").classList.add("open"); $("drawer").classList.add("open");
594
+ try {
595
+ const data = await api(`/api/file?path=${encodeURIComponent(path)}&start=${start}&end=${end}`);
596
+ $("drawer-title").textContent = `${data.path}:${data.start}${data.end !== data.start ? "-" + data.end : ""} · ${LANG === "ar" ? t("{lines} in the file", {lines: data.total}) : data.total + " lines"}`;
597
+ if (repoRoot) { $("drawer-editor").href = editorLink(data.path, data.start); $("drawer-editor").hidden = false; }
598
+ $("drawer-code").replaceChildren(...data.lines.map((text, index) => {
599
+ const number = data.first + index;
600
+ const row = document.createElement("div");
601
+ row.className = "line" + (number >= data.start && number <= data.end ? " hit" : "");
602
+ const n = document.createElement("span"); n.className = "n"; n.textContent = number;
603
+ const code = document.createElement("span"); code.textContent = text || " ";
604
+ row.append(n, code);
605
+ return row;
606
+ }));
607
+ const hit = $("drawer-code").querySelector(".hit");
608
+ if (hit) hit.scrollIntoView({block: "center"});
609
+ } catch (error) {
610
+ $("drawer-code").textContent = error.message;
611
+ }
612
+ }
613
+ // A click on any citation link, wherever it is on the page, opens the drawer.
614
+ document.addEventListener("click", (event) => {
615
+ const link = event.target.closest("a.cite");
616
+ if (!link) return;
617
+ event.preventDefault();
618
+ showCitation(link.dataset.path.replace(/^repo\//, ""), Number(link.dataset.start), Number(link.dataset.end));
619
+ });
620
+
621
+ // ---- Model picker: models installed in Ollama on this computer; cloud and embedding models are not offered.
622
+ async function loadModels() {
623
+ try {
624
+ const data = await api("/api/models");
625
+ const select = $("model");
626
+ const models = data.models.length ? data.models : [{name: data.current}];
627
+ select.replaceChildren(...models.map((model) => {
628
+ const option = document.createElement("option");
629
+ option.value = model.name;
630
+ option.textContent = model.name + (model.parameters ? ` · ${model.parameters}` : "") + (model.name === data.default ? t(" · default") : "");
631
+ return option;
632
+ }));
633
+ select.value = data.current;
634
+ $("model-name").textContent = data.current;
635
+ $("model-status").textContent = data.current === data.default
636
+ ? t("The default, and the model CodeHaven is tested with.")
637
+ : t("Not the tested default ({name}), so answers may differ. The first answer is slower while it loads.", {name: data.default});
638
+ } catch (error) {
639
+ $("model-status").textContent = error.message;
640
+ }
641
+ }
642
+ // Choosing another model: the server checks it is installed before using it.
643
+ $("model").addEventListener("change", async () => {
644
+ const name = $("model").value;
645
+ busy = true; updateComposer();
646
+ $("model-status").textContent = t("Checking {name}…", {name});
647
+ try {
648
+ await api("/api/model", {method: "POST", body: JSON.stringify({name})});
649
+ } catch (error) {
650
+ toast(error.message);
651
+ } finally {
652
+ busy = false; updateComposer(); loadModels();
653
+ }
654
+ });
655
+
656
+ // ---- Changing code (--allow-edits): a proposed change is shown as a diff, and applied only on Apply.
657
+ function showDiff(card, event) {
658
+ const box = document.createElement("div"); box.className = "diff-box";
659
+ const title = document.createElement("strong"); title.dir = "auto"; title.textContent = t("Proposed change: ") + event.summary;
660
+ const pre = document.createElement("pre"); pre.className = "diff";
661
+ for (const line of event.diff.split("\n")) {
662
+ const row = document.createElement("span");
663
+ row.className = line.startsWith("+") && !line.startsWith("+++") ? "add" : line.startsWith("-") && !line.startsWith("---") ? "del" : "";
664
+ row.textContent = line + "\n"; pre.append(row);
665
+ }
666
+ const apply = document.createElement("button"); apply.textContent = t("Apply");
667
+ const decline = document.createElement("button"); decline.textContent = t("Decline");
668
+ const answer = async (yes) => {
669
+ apply.disabled = decline.disabled = true;
670
+ try { await api("/api/decide", {method: "POST", body: JSON.stringify({apply: yes})}); } catch (error) { toast(error.message); }
671
+ };
672
+ apply.addEventListener("click", () => answer(true)); decline.addEventListener("click", () => answer(false));
673
+ const row = document.createElement("div"); row.className = "diff-actions"; row.append(apply, decline);
674
+ box.append(title, pre, row); card.append(box); scrollDown();
675
+ }
676
+ $("undo-change").addEventListener("click", async () => {
677
+ if (busy) return;
678
+ try { toast(t("Undid: ") + (await api("/api/undo", {method: "POST", body: "{}"})).undone); } catch (error) { toast(error.message); }
679
+ });
680
+
681
+ // ---- Chat.
682
+ function clearChat() {
683
+ $("messages-inner").replaceChildren($("empty"));
684
+ $("empty").hidden = false;
685
+ transcript = []; $("save-chat").disabled = true;
686
+ }
687
+ // ---- Saving to a file: a download link that exists only for the click. Nothing is sent anywhere.
688
+ function saveFile(name, text, type) {
689
+ const link = Object.assign(document.createElement("a"), {href: URL.createObjectURL(new Blob([text], {type})), download: name});
690
+ document.body.append(link); link.click(); link.remove();
691
+ setTimeout(() => URL.revokeObjectURL(link.href), 1000);
692
+ }
693
+ // The chat on the page as questions and answers, kept so it can be saved as a file.
694
+ let transcript = [];
695
+ // Add one question and its answer to the transcript, and allow saving once there is something to save.
696
+ function keepTurn(question, answer, issues, stopped) {
697
+ transcript.push({question, answer, issues: issues || [], stopped: Boolean(stopped)});
698
+ $("save-chat").disabled = false;
699
+ }
700
+ // The chat as Markdown: a heading per question, the answer under it, and any warning as a quotation.
701
+ function chatMarkdown() { return turnsMarkdown(transcript); }
702
+ // Some questions and answers as Markdown; citations stay as path:line, so they can be checked in the repository.
703
+ function turnsMarkdown(turns) {
704
+ const about = $("repo-label").textContent.trim();
705
+ const parts = [`# CodeHaven: ${about}`, `${new Date().toISOString().slice(0, 16).replace("T", " ")} UTC · ${$("model").value}`];
706
+ for (const turn of turns) {
707
+ parts.push(`## ${turn.question.replace(/\s+/g, " ")}`, turn.answer || "—");
708
+ if (turn.stopped) parts.push(`> ${t("Stopped before it finished.")}`);
709
+ if (turn.issues.length) parts.push(`> **${t("Unverified")}**\n` + turn.issues.map((issue) => `> - ${issue}`).join("\n"));
710
+ }
711
+ return parts.join("\n\n") + "\n";
712
+ }
713
+ $("save-chat").addEventListener("click", () => {
714
+ if (!transcript.length) return;
715
+ const name = ($("repo-label").textContent.trim().replace(/[^\wء-ي.-]+/g, "-") || "chat") + "-chat.md";
716
+ saveFile(name, chatMarkdown(), "text/markdown");
717
+ });
718
+ // Add an empty message box of one kind (user, assistant, or note) and return it to be filled.
719
+ function addMessage(kind) {
720
+ $("empty").hidden = true;
721
+ const element = document.createElement("div");
722
+ element.className = "msg " + kind;
723
+ if (kind === "user") element.dir = "auto"; // An Arabic question is shown right to left.
724
+ $("messages-inner").append(element);
725
+ return element;
726
+ }
727
+ // Keep the newest message in view.
728
+ function scrollDown() { const box = $("messages"); box.scrollTop = box.scrollHeight; }
729
+ // Enable or disable every control to match the state: nothing open, busy, or ready.
730
+ function updateComposer() {
731
+ const ready = indexed && !busy;
732
+ $("question").disabled = !ready;
733
+ // While an answer or flashcards are being written, the button that started them stops them.
734
+ const stopLabel = t(stopping ? "Stopping…" : "Stop");
735
+ $("send").textContent = stoppable ? stopLabel : t("Ask");
736
+ $("send").classList.toggle("primary", !stoppable); $("send").classList.toggle("stop", stoppable);
737
+ $("send").disabled = stoppable ? stopping : !ready || !$("question").value.trim();
738
+ $("question").placeholder = t(!indexed ? "Open a project or upload a file first" : busy ? "CodeHaven is working…"
739
+ : uploaded ? "Ask about this file" : "Ask about this repository");
740
+ $("language").disabled = busy;
741
+ $("new-chat").disabled = !indexed || busy;
742
+ $("model").disabled = busy;
743
+ // While a repository is indexed or downloaded, the button that started it stops it.
744
+ $("index").textContent = indexing === "index" ? stopLabel : t("Index");
745
+ $("index").disabled = indexing === "index" ? stopping : busy;
746
+ $("upload").disabled = $("attach").disabled = busy;
747
+ $("clone").textContent = indexing === "clone" ? stopLabel : t("Download and index");
748
+ $("clone").disabled = indexing === "clone" ? stopping : busy;
749
+ $("forget").disabled = busy || uploaded || !(savedCount || chatCount);
750
+ $("tab-map").disabled = $("tab-cards").disabled = !indexed;
751
+ $("map-draw").disabled = !indexed;
752
+ $("cards-make").textContent = stoppable ? stopLabel : t("Make flashcards");
753
+ $("cards-make").classList.toggle("primary", !stoppable); $("cards-make").classList.toggle("stop", stoppable);
754
+ $("cards-make").disabled = stoppable ? stopping : !ready;
755
+ for (const button of document.querySelectorAll("[data-choose]")) button.hidden = uploaded;
756
+ showChosen();
757
+ for (const button of $("suggestions").querySelectorAll("button")) button.disabled = !ready;
758
+ }
759
+ // Shorten a step line from the server's log for the status shown while waiting.
760
+ function statusText(line) {
761
+ // The server's step lines are in English; the Arabic page shows only how far along the steps are.
762
+ const step = LANG === "ar" && line.match(/^\s*Step (\d+) \(max (\d+)\)/);
763
+ if (step) return t("Step {step} of at most {most}…", {step: step[1], most: step[2]});
764
+ return line.replace(/^\s+/, "").replace(/\s*\(loading and prompt processing can take time\)\.\.\.$/, "…");
765
+ }
766
+
767
+ // Stop the answer or flashcards being written. The request that is streaming them ends with a "stopped" event.
768
+ async function stopNow() {
769
+ if (!stoppable || stopping) return;
770
+ stopping = true; updateComposer();
771
+ try { await api("/api/stop", {method: "POST", body: "{}"}); }
772
+ catch (error) { stopping = false; updateComposer(); toast(error.message); }
773
+ }
774
+ // Send one question and show the answer as it streams in; then its checks, the steps taken, and a Copy button.
775
+ async function ask(question) {
776
+ question = question.trim();
777
+ if (!question || busy || !indexed) return;
778
+ // Two slash commands act on the page itself; the others are written out in full by the server (/help lists them).
779
+ if (question === "/undo" || question === "/export") {
780
+ $("question").value = ""; resize();
781
+ $(question === "/undo" ? "undo-change" : "save-chat").click();
782
+ return;
783
+ }
784
+ busy = stoppable = true;
785
+ $("question").value = ""; resize(); updateComposer();
786
+ addMessage("user").textContent = question;
787
+ const card = addMessage("assistant");
788
+ const status = document.createElement("div"); status.className = "status";
789
+ const dot = document.createElement("span"); dot.className = "dot";
790
+ const statusLabel = document.createElement("span"); statusLabel.textContent = t("Starting…");
791
+ status.append(dot, statusLabel);
792
+ const answer = document.createElement("div"); answer.className = "answer";
793
+ card.append(status, answer);
794
+ scrollDown();
795
+ const logs = [];
796
+ let streamed = "", phase = t("Starting…");
797
+ const started = Date.now();
798
+ const timer = setInterval(() => { statusLabel.textContent = `${phase} ${t("{seconds}s", {seconds: Math.round((Date.now() - started) / 1000)})}`; }, 1000);
799
+ const finish = () => { clearInterval(timer); busy = stoppable = stopping = false; updateComposer(); $("question").focus(); };
800
+ try {
801
+ let done = null;
802
+ for await (const event of streamEvents("/api/ask", {question})) {
803
+ if (event.type === "log") {
804
+ logs.push(event.text);
805
+ const step = event.text.trim().match(/^Step \d+ \(max \d+\): (.*)$/);
806
+ if (step) phase = statusText(step[0]);
807
+ } else if (event.type === "text") {
808
+ streamed += event.text;
809
+ answer.innerHTML = render(streamed);
810
+ phase = t("Writing the answer…");
811
+ scrollDown();
812
+ } else if (event.type === "diff") {
813
+ showDiff(card, event);
814
+ } else if (event.type === "done" || event.type === "error" || event.type === "stopped") {
815
+ done = event;
816
+ }
817
+ }
818
+ status.remove();
819
+ if (!done) throw new Error(t("The connection closed before the answer finished."));
820
+ if (done.type === "error") throw new Error(done.message);
821
+ if (done.type === "stopped") {
822
+ // What was written so far stays on the page, marked as unfinished.
823
+ const note = document.createElement("div"); note.className = "stopped";
824
+ note.textContent = t("Stopped. This question is not remembered in follow-ups.");
825
+ card.append(note);
826
+ if (streamed) keepTurn(question, streamed, [], true);
827
+ return;
828
+ }
829
+ answer.innerHTML = render(done.complete ? done.answer : (streamed || t("No final answer: the step limit was reached before CodeHaven finished.")));
830
+ if (done.issues.length) {
831
+ const checks = document.createElement("div"); checks.className = "checks";
832
+ const title = document.createElement("strong"); title.textContent = t("Unverified: check the cited lines before relying on this answer.");
833
+ const list = document.createElement("ul");
834
+ for (const issue of done.issues) { const item = document.createElement("li"); item.dir = "auto"; item.textContent = issue; list.append(item); }
835
+ checks.append(title, list); card.append(checks);
836
+ }
837
+ keepTurn(question, done.complete ? done.answer : streamed, done.issues);
838
+ setSaved({saved: done.saved}, done.kept);
839
+ setChats(done.chats);
840
+ $("memory-status").textContent = t("Follow-ups remember {remembered} of the last {memory} questions. Start a new chat when you change topic.", done);
841
+ const shownLines = new Set((done.answer || "").split("\n").map((line) => line.trim()).filter(Boolean));
842
+ const steps = logs.filter((line) => line.trim() && !shownLines.has(line.trim()) && !line.startsWith("Answer check:"));
843
+ const details = document.createElement("details"); details.className = "steps";
844
+ const summary = document.createElement("summary");
845
+ summary.textContent = t("{steps} · {seconds}s · show what CodeHaven did", {steps: count(done.steps, "step"), seconds: Math.round((Date.now() - started) / 1000)});
846
+ const pre = document.createElement("pre"); pre.textContent = steps.join("\n").replace(/\n{3,}/g, "\n\n").trim();
847
+ details.append(summary, pre);
848
+ const copy = document.createElement("button"); copy.className = "copy"; copy.textContent = t("Copy");
849
+ copy.title = t("Copy this answer as text");
850
+ copy.addEventListener("click", async () => {
851
+ try { await navigator.clipboard.writeText(done.answer || streamed); copy.textContent = t("Copied"); setTimeout(() => { copy.textContent = t("Copy"); }, 1500); }
852
+ catch { toast(t("This browser did not allow copying. Select the text and copy it instead.")); }
853
+ });
854
+ const save = document.createElement("button"); save.className = "copy"; save.textContent = t("Save .md");
855
+ save.title = t("Save this answer as a Markdown file, through your browser. Nothing leaves this computer.");
856
+ save.addEventListener("click", () => {
857
+ const turn = {question, answer: done.complete ? done.answer : streamed, issues: done.issues, stopped: false};
858
+ const name = (question.replace(/[^\wء-ي]+/g, "-").replace(/^-|-$/g, "").slice(0, 60) || "answer") + ".md";
859
+ saveFile(name, turnsMarkdown([turn]), "text/markdown");
860
+ });
861
+ const foot = document.createElement("div"); foot.className = "msg-foot";
862
+ foot.append(details, copy, save); card.append(foot);
863
+ } catch (error) {
864
+ status.remove();
865
+ const box = document.createElement("div"); box.className = "error-box"; box.dir = "auto"; box.textContent = error.message;
866
+ card.append(box);
867
+ } finally {
868
+ finish(); scrollDown();
869
+ }
870
+ }
871
+
872
+ // ---- Wiring: the question box, the sidebar buttons, the dialogs, and the Escape key.
873
+ // The question box grows with its text, up to its largest height.
874
+ function resize() { const box = $("question"); box.style.height = "auto"; box.style.height = Math.min(box.scrollHeight, 200) + "px"; }
875
+ $("question").addEventListener("input", () => { resize(); updateComposer(); });
876
+ $("question").addEventListener("keydown", (event) => {
877
+ if (event.key === "Enter" && !event.shiftKey && !event.isComposing) { event.preventDefault(); ask($("question").value); }
878
+ });
879
+ $("send").addEventListener("click", () => stoppable ? stopNow() : ask($("question").value));
880
+ $("index").addEventListener("click", indexRepository);
881
+ $("path").addEventListener("keydown", (event) => { if (event.key === "Enter") indexRepository(); });
882
+ $("browse").addEventListener("click", openBrowser);
883
+ $("browser-cancel").addEventListener("click", closeOverlays);
884
+ $("browser-use").addEventListener("click", () => { $("path").value = browsing; closeOverlays(); indexRepository(); });
885
+ $("drawer-close").addEventListener("click", closeOverlays);
886
+ $("overlay").addEventListener("click", closeOverlays);
887
+ document.addEventListener("keydown", (event) => { if (event.key === "Escape") closeOverlays(); });
888
+ $("new-chat").addEventListener("click", async () => {
889
+ try {
890
+ await api("/api/reset", {method: "POST", body: "{}"});
891
+ clearChat();
892
+ $("memory-status").textContent = t("New chat started. Follow-up questions remember the last 8 questions.");
893
+ } catch (error) { toast(error.message); }
894
+ });
895
+
896
+ // ---- Views: chat, and two study aids for one file or a group of files.
897
+ // Show one view and mark its tab as pressed.
898
+ function setView(name) {
899
+ for (const view of ["chat", "map", "cards"]) {
900
+ $("view-" + view).hidden = view !== name;
901
+ $("tab-" + view).setAttribute("aria-pressed", String(view === name));
902
+ }
903
+ }
904
+ for (const view of ["chat", "map", "cards"]) $("tab-" + view).addEventListener("click", () => setView(view));
905
+
906
+ // ---- The files a map or flashcards are about. An uploaded file is always the choice.
907
+ let selected = [], fileList = null, picking = new Set();
908
+ // Show the chosen files in the bar above the map and above the flashcards.
909
+ function showChosen() {
910
+ const text = uploaded ? $("repo-label").textContent : !selected.length ? t("No files chosen")
911
+ : selected.length === 1 ? selected[0] : `${count(selected.length, "file")}: ${selected.map((path) => path.split("/").pop()).join(", ")}`;
912
+ for (const label of document.querySelectorAll("[data-chosen]")) {
913
+ label.textContent = text;
914
+ label.title = selected.join("\n");
915
+ label.classList.toggle("none", !uploaded && !selected.length);
916
+ }
917
+ }
918
+ // Forget the chosen files, the map, and the cards when something else is opened.
919
+ function resetStudy() {
920
+ selected = []; fileList = null; mapData = null; cards = [];
921
+ drawGraph([], []);
922
+ $("map-back").hidden = true;
923
+ $("deck").hidden = true;
924
+ for (const id of ["map-status", "cards-status"]) { $(id).classList.remove("error"); $(id).textContent = STUDY_HINTS[id]; }
925
+ }
926
+ // List the files that match the filter, the first 300 at most, each with a checkbox.
927
+ function showPicker() {
928
+ const filter = $("picker-filter").value.trim().toLowerCase();
929
+ const shown = fileList.files.filter((path) => path.toLowerCase().includes(filter));
930
+ const rows = shown.slice(0, 300).map((path) => {
931
+ const row = document.createElement("label");
932
+ const box = Object.assign(document.createElement("input"), {type: "checkbox", checked: picking.has(path)});
933
+ box.addEventListener("change", () => { if (box.checked) picking.add(path); else picking.delete(path); showPickerNote(); });
934
+ row.append(box, path);
935
+ return row;
936
+ });
937
+ if (shown.length > rows.length) rows.push(Object.assign(document.createElement("div"), {className: "index-status", textContent: t("{count} more files: type in the filter to narrow the list.", {count: shown.length - rows.length})}));
938
+ if (!shown.length) rows.push(Object.assign(document.createElement("div"), {className: "index-status", textContent: t("No files match.")}));
939
+ $("picker-list").replaceChildren(...rows);
940
+ showPickerNote();
941
+ }
942
+ // Say how many files are ticked in the picker, and how many each study aid takes.
943
+ function showPickerNote() {
944
+ const limits = fileList.limits;
945
+ $("picker-note").textContent = t("{count} chosen. A map takes up to {map} files, flashcards up to {flashcards}.", {count: picking.size, ...limits});
946
+ }
947
+ // Open the file picker. The file list is fetched once and kept until something else is opened.
948
+ async function openPicker() {
949
+ $("overlay").classList.add("open"); $("picker").classList.add("open");
950
+ picking = new Set(selected);
951
+ try {
952
+ if (!fileList) { $("picker-list").textContent = t("Loading…"); fileList = await api("/api/files"); }
953
+ showPicker();
954
+ $("picker-filter").focus();
955
+ } catch (error) {
956
+ $("picker-list").textContent = error.message;
957
+ }
958
+ }
959
+ for (const button of document.querySelectorAll("[data-choose]")) button.addEventListener("click", openPicker);
960
+ $("picker-filter").addEventListener("input", () => { if (fileList) showPicker(); });
961
+ $("picker-clear").addEventListener("click", () => { picking.clear(); if (fileList) showPicker(); });
962
+ $("picker-done").addEventListener("click", () => { selected = [...picking]; closeOverlays(); showChosen(); });
963
+ const STUDY_HINTS = {"map-status": $("map-status").textContent, "cards-status": $("cards-status").textContent};
964
+ // Show an error in a study aid's status line.
965
+ function studyError(id, message) { $(id).classList.add("error"); $(id).textContent = message; }
966
+
967
+ // ---- Structure map: boxes and arrows drawn as SVG by this page; nothing is loaded from anywhere.
968
+ const SVG = $("map-svg").namespaceURI; // Taken from the page, so no web address is written anywhere in it.
969
+ const BOX = {width: 214, height: 46, gapX: 70, gapY: 14, pad: 8};
970
+ let mapData = null;
971
+ // Make one SVG element with its attributes and, if given, its text.
972
+ function svg(tag, attributes = {}, text) {
973
+ const element = document.createElementNS(SVG, tag);
974
+ for (const [name, value] of Object.entries(attributes)) element.setAttribute(name, value);
975
+ if (text !== undefined) element.textContent = text;
976
+ return element;
977
+ }
978
+ // A label that is too long keeps its end, which for a path is the file name.
979
+ function shorten(text, width = 27) { return text.length <= width ? text : "…" + text.slice(text.length - width + 1); }
980
+ // Columns from left to right: a box sits one column after the last box that points at it. Arrows that close a
981
+ // loop are drawn dashed and do not move anything, so two files that import each other still fit in a picture.
982
+ function layout(nodes, edges) {
983
+ const out = new Map(nodes.map((node) => [node.id, []]));
984
+ for (const edge of edges) out.get(edge.from).push(edge);
985
+ const state = new Map(), back = new Set();
986
+ const visit = (id) => {
987
+ state.set(id, 1);
988
+ for (const edge of out.get(id)) { if (state.get(edge.to) === 1) back.add(edge); else if (!state.get(edge.to)) visit(edge.to); }
989
+ state.set(id, 2);
990
+ };
991
+ for (const node of nodes) if (!state.get(node.id)) visit(node.id);
992
+ const column = new Map(nodes.map((node) => [node.id, 0]));
993
+ for (let round = 0, moved = true; moved && round <= nodes.length; round++) {
994
+ moved = false;
995
+ for (const edge of edges) {
996
+ if (!back.has(edge) && column.get(edge.to) < column.get(edge.from) + 1) { column.set(edge.to, column.get(edge.from) + 1); moved = true; }
997
+ }
998
+ }
999
+ const linked = new Set(edges.flatMap((edge) => [edge.from, edge.to]));
1000
+ const columns = [];
1001
+ for (const node of nodes) if (linked.has(node.id)) (columns[column.get(node.id)] ||= []).push(node);
1002
+ // Order each column by where its callers sit in the column before, which keeps most arrows from crossing.
1003
+ const row = new Map();
1004
+ columns.forEach((list, index) => {
1005
+ if (index) {
1006
+ const weight = (node) => {
1007
+ const rows = edges.filter((edge) => edge.to === node.id && row.has(edge.from)).map((edge) => row.get(edge.from));
1008
+ return rows.length ? rows.reduce((a, b) => a + b, 0) / rows.length : 1e9;
1009
+ };
1010
+ list.sort((a, b) => weight(a) - weight(b));
1011
+ }
1012
+ list.forEach((node, position) => row.set(node.id, position));
1013
+ });
1014
+ const place = new Map(), step = BOX.height + BOX.gapY;
1015
+ const tallest = Math.max(0, ...columns.map((list) => list.length));
1016
+ columns.forEach((list, index) => list.forEach((node, position) => place.set(node.id, {
1017
+ x: BOX.pad + index * (BOX.width + BOX.gapX), y: BOX.pad + position * step + (tallest - list.length) * step / 2})));
1018
+ // Boxes with no arrows go in a grid underneath.
1019
+ const loose = nodes.filter((node) => !linked.has(node.id));
1020
+ const across = Math.max(3, columns.length), top = BOX.pad + (tallest ? tallest * step + 18 : 0);
1021
+ loose.forEach((node, index) => place.set(node.id, {x: BOX.pad + (index % across) * (BOX.width + 16), y: top + Math.floor(index / across) * step}));
1022
+ return {place, back};
1023
+ }
1024
+ // Draw the boxes and arrows, and return how many arrows there are. Repeated arrows, arrows from a box to itself,
1025
+ // and arrows to a box that is not drawn are left out.
1026
+ function drawGraph(nodes, edges) {
1027
+ const picture = $("map-svg");
1028
+ const known = new Set(nodes.map((node) => node.id)), seen = new Set();
1029
+ edges = edges.filter((edge) => {
1030
+ const key = edge.from + "\n" + edge.to;
1031
+ if (edge.from === edge.to || !known.has(edge.from) || !known.has(edge.to) || seen.has(key)) return false;
1032
+ seen.add(key);
1033
+ return true;
1034
+ });
1035
+ const {place, back} = layout(nodes, edges);
1036
+ const marker = svg("marker", {id: "arrow", viewBox: "0 0 10 10", refX: 9, refY: 5, markerWidth: 7, markerHeight: 7, orient: "auto-start-reverse"});
1037
+ marker.append(svg("path", {d: "M0 0 10 5 0 10Z", class: "arrow"}));
1038
+ const defs = svg("defs"); defs.append(marker);
1039
+ const lines = edges.map((edge) => {
1040
+ const from = place.get(edge.from), to = place.get(edge.to);
1041
+ const y1 = from.y + BOX.height / 2, y2 = to.y + BOX.height / 2, x1 = from.x + BOX.width;
1042
+ const forward = to.x > from.x;
1043
+ // An arrow that goes back, or stays in its column, leaves and arrives on the right-hand side.
1044
+ const d = forward ? `M${x1} ${y1} C${x1 + 36} ${y1} ${to.x - 36} ${y2} ${to.x} ${y2}`
1045
+ : `M${x1} ${y1} C${x1 + 44} ${y1} ${to.x + BOX.width + 44} ${y2} ${to.x + BOX.width} ${y2}`;
1046
+ const line = svg("path", {d, class: "edge" + (back.has(edge) || !forward ? " back" : ""), "marker-end": "url(#arrow)"});
1047
+ line.append(svg("title", {}, `${edge.from} → ${edge.to}${edge.title ? ": " + edge.title : ""}`));
1048
+ line.dataset.from = edge.from; line.dataset.to = edge.to;
1049
+ return line;
1050
+ });
1051
+ const boxes = nodes.map((node) => {
1052
+ const {x, y} = place.get(node.id);
1053
+ const group = svg("g", {class: `node ${node.kind || ""}${node.ghost ? " ghost" : ""}`, transform: `translate(${x} ${y})`});
1054
+ group.append(svg("title", {}, node.title || node.id), svg("rect", {width: BOX.width, height: BOX.height, rx: 8}),
1055
+ svg("text", {x: 12, y: 19, class: "label"}, shorten(node.label)), svg("text", {x: 12, y: 36, class: "sub"}, node.sub));
1056
+ const near = new Set([node.id, ...edges.filter((edge) => edge.from === node.id || edge.to === node.id).flatMap((edge) => [edge.from, edge.to])]);
1057
+ const focus = (on) => {
1058
+ picture.classList.toggle("focus", on);
1059
+ for (const line of lines) line.classList.toggle("hot", on && (line.dataset.from === node.id || line.dataset.to === node.id));
1060
+ boxes.forEach((box, index) => box.classList.toggle("hot", on && near.has(nodes[index].id)));
1061
+ };
1062
+ group.addEventListener("mouseenter", () => focus(true));
1063
+ group.addEventListener("mouseleave", () => focus(false));
1064
+ if (node.open) {
1065
+ group.setAttribute("tabindex", "0"); group.setAttribute("role", "button");
1066
+ group.addEventListener("click", node.open);
1067
+ group.addEventListener("keydown", (event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); node.open(); } });
1068
+ }
1069
+ return group;
1070
+ });
1071
+ const places = [...place.values()];
1072
+ picture.setAttribute("width", places.length ? Math.max(...places.map((spot) => spot.x)) + BOX.width + 60 : 0);
1073
+ picture.setAttribute("height", places.length ? Math.max(...places.map((spot) => spot.y)) + BOX.height + BOX.pad : 0);
1074
+ picture.replaceChildren(defs, ...lines, ...boxes);
1075
+ return edges.length;
1076
+ }
1077
+ // An English count with its noun: "1 file", "3 files".
1078
+ function plural(count, word) { return `${count} ${word}${count === 1 ? "" : "s"}`; }
1079
+ // The map inside one file: its functions and classes, and which calls which.
1080
+ function showFileMap(file) {
1081
+ const nodes = file.parts.map((part) => ({id: part.name, label: part.name, kind: part.kind, title: t("{name} · click to see the code", part),
1082
+ sub: `${part.kind === "part" ? "" : part.kind + " · "}${t("lines {start}-{end}", part)}`, open: () => showCitation(file.path, part.start, part.end)}));
1083
+ const calls = drawGraph(nodes, file.parts.flatMap((part) => part.calls.map((name) => ({from: part.name, to: name, title: t("calls")}))));
1084
+ $("map-back").hidden = mapData.files.length < 2;
1085
+ $("map-status").textContent = !nodes.length ? t("{path} has {lines} but no functions or classes CodeHaven can name, so there is nothing to draw.", {path: file.path, lines: count(file.lines, "line")})
1086
+ : t("{path}: {parts}, {calls} between them{limited}. An arrow points from the caller to what it calls. Click a box to see its code.",
1087
+ {path: file.path, parts: count(nodes.length, "part"), calls: count(calls, "call"), limited: file.parts_limited ? t(" (only the first parts are shown)") : ""});
1088
+ }
1089
+ // The map of several files: which imports which. Clicking a file shows the map inside it.
1090
+ function showFilesMap() {
1091
+ const nodes = mapData.files.map((file) => ({id: file.path, label: file.path, kind: "file", title: t("{path} · click to see inside", file),
1092
+ sub: `${count(file.parts.length, "part")} · ${count(file.lines, "line")}`, open: () => showFileMap(file)}));
1093
+ nodes.push(...mapData.neighbours.map((path) => ({id: path, label: path, ghost: true, sub: t("not chosen"), title: t("{path} · linked to a chosen file, but not chosen", {path})})));
1094
+ const links = drawGraph(nodes, mapData.links.map((link) => ({from: link.from, to: link.to, title: link.names.length ? t("imports {names}", {names: link.names.join(", ")}) : t("imports it")})));
1095
+ $("map-back").hidden = true;
1096
+ $("map-status").textContent = t("{files}, {imports}{limited}. An arrow points from a file to the file it imports; dashed boxes are files you did not choose. Click a file to see inside it.",
1097
+ {files: count(mapData.files.length, "file"), imports: count(links, "import"), limited: mapData.limited ? t(" (limits reached, so some are left out)") : ""});
1098
+ }
1099
+ // Ask the server for the structure of the chosen files and draw it.
1100
+ async function drawMap() {
1101
+ if (!uploaded && !selected.length) { openPicker(); return; }
1102
+ $("map-status").classList.remove("error");
1103
+ $("map-status").textContent = t("Reading the code…");
1104
+ try {
1105
+ mapData = await api("/api/map", {method: "POST", body: JSON.stringify({paths: selected})});
1106
+ if (mapData.files.length === 1 && !mapData.neighbours.length) showFileMap(mapData.files[0]); else showFilesMap();
1107
+ } catch (error) {
1108
+ drawGraph([], []);
1109
+ studyError("map-status", error.message);
1110
+ }
1111
+ }
1112
+ $("map-draw").addEventListener("click", drawMap);
1113
+ $("map-back").addEventListener("click", showFilesMap);
1114
+
1115
+ // ---- Flashcards: the local model writes them one file at a time; the lines behind each answer are looked up, not guessed.
1116
+ let cards = [], cardAt = 0, cardAnswer = false;
1117
+ // Show the current card, on its question side or its answer side.
1118
+ function showCard() {
1119
+ $("deck").hidden = !cards.length;
1120
+ if (!cards.length) return;
1121
+ const card = cards[cardAt];
1122
+ $("flashcard").classList.toggle("answer", cardAnswer);
1123
+ $("card-side").textContent = t(cardAnswer ? "Answer" : "Question");
1124
+ $("card-text").innerHTML = inline(cardAnswer ? card.answer : card.question);
1125
+ $("card-text").dir = direction(cardAnswer ? card.answer : card.question);
1126
+ const where = card.start ? `${card.path}:${card.start}${card.end !== card.start ? "-" + card.end : ""}` : "";
1127
+ $("card-source").innerHTML = !cardAnswer ? esc(card.path) : where ? inline(t("See {where}", {where})) + (card.symbol ? ` (<code>${esc(card.symbol)}</code>)` : "")
1128
+ : esc(t("{path}: the part this answer names was not found, so check it against the file.", card));
1129
+ $("card-count").textContent = t("Card {at} of {total}", {at: cardAt + 1, total: cards.length});
1130
+ $("card-flip").textContent = t(cardAnswer ? "Show question" : "Show answer");
1131
+ $("card-prev").disabled = cardAt === 0;
1132
+ $("card-next").disabled = cardAt === cards.length - 1;
1133
+ }
1134
+ // Go to the next or previous flashcard, showing its question side.
1135
+ function moveCard(step) { cardAt = Math.min(cards.length - 1, Math.max(0, cardAt + step)); cardAnswer = false; showCard(); }
1136
+ // Turn the current flashcard over.
1137
+ function flipCard() { cardAnswer = !cardAnswer; showCard(); }
1138
+ // Ask the model for cards. They arrive one file at a time and are shown as they come.
1139
+ async function makeCards() {
1140
+ if (busy || !indexed) return;
1141
+ if (!uploaded && !selected.length) { openPicker(); return; }
1142
+ busy = stoppable = true; updateComposer();
1143
+ const status = $("cards-status"), failed = [], started = Date.now();
1144
+ status.classList.remove("error");
1145
+ cards = []; cardAt = 0; cardAnswer = false; showCard();
1146
+ let phase = t("Starting…"), finished = false, stopped = false;
1147
+ const tick = () => { status.textContent = `${phase} ${t("{seconds}s", {seconds: Math.round((Date.now() - started) / 1000)})}`; };
1148
+ const timer = setInterval(tick, 1000);
1149
+ tick();
1150
+ try {
1151
+ for await (const event of streamEvents("/api/flashcards", {paths: selected, count: Number($("cards-count").value), language: LANG})) {
1152
+ if (event.type === "file") { phase = t("Writing cards for {path} (file {index} of {of})…", event); tick(); }
1153
+ else if (event.type === "cards") { cards.push(...event.cards); showCard(); }
1154
+ else if (event.type === "error" && event.fatal) throw new Error(event.message);
1155
+ else if (event.type === "error") failed.push(`${event.path}: ${event.message}`);
1156
+ else if (event.type === "done") finished = true;
1157
+ else if (event.type === "stopped") stopped = true;
1158
+ }
1159
+ clearInterval(timer);
1160
+ if (stopped) { status.textContent = t("Stopped. ") + t("{cards} kept.", {cards: count(cards.length, "card")}); return; }
1161
+ if (!finished) throw new Error(t("The connection closed before the cards were finished."));
1162
+ status.classList.toggle("error", !cards.length);
1163
+ status.textContent = (cards.length ? t("{cards} in {seconds}s. Click the card, or press Space, to turn it over; the arrow keys move between cards. ",
1164
+ {cards: count(cards.length, "card"), seconds: Math.round((Date.now() - started) / 1000)})
1165
+ : t("No cards were made. "))
1166
+ + (failed.length ? t("Skipped {files}", {files: failed.join("; ")}) : "");
1167
+ } catch (error) {
1168
+ clearInterval(timer);
1169
+ studyError("cards-status", error.message);
1170
+ } finally {
1171
+ busy = stoppable = stopping = false; updateComposer();
1172
+ }
1173
+ }
1174
+ $("cards-make").addEventListener("click", () => stoppable ? stopNow() : makeCards());
1175
+ $("flashcard").addEventListener("click", (event) => { if (!event.target.closest("a")) flipCard(); });
1176
+ $("card-flip").addEventListener("click", flipCard);
1177
+ $("card-prev").addEventListener("click", () => moveCard(-1));
1178
+ $("card-next").addEventListener("click", () => moveCard(1));
1179
+ $("cards-shuffle").addEventListener("click", () => {
1180
+ for (let i = cards.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [cards[i], cards[j]] = [cards[j], cards[i]]; }
1181
+ cardAt = 0; cardAnswer = false; showCard();
1182
+ });
1183
+ $("cards-copy").addEventListener("click", async () => {
1184
+ const text = cards.map((card) => `Q: ${card.question}\nA: ${card.answer}\n${card.start ? `${card.path}:${card.start}-${card.end}` : card.path}`).join("\n\n");
1185
+ try { await navigator.clipboard.writeText(text); $("cards-copy").textContent = t("Copied"); }
1186
+ catch { $("cards-copy").textContent = t("Copying is blocked by the browser"); }
1187
+ setTimeout(() => { $("cards-copy").textContent = t("Copy all as text"); }, 2000);
1188
+ });
1189
+ // One card per line, question then answer, separated by a tab: the plain-text form Anki imports.
1190
+ $("cards-save").addEventListener("click", () => {
1191
+ const cell = (text) => text.replace(/[\t\r\n]+/g, " ").trim();
1192
+ const rows = cards.map((card) => `${cell(card.question)}\t${cell(card.answer)} (${card.start ? `${card.path}:${card.start}-${card.end}` : card.path})`);
1193
+ saveFile("codehaven-flashcards.txt", rows.join("\n") + "\n", "text/tab-separated-values");
1194
+ });
1195
+ // Keys in the flashcards view: Space or Enter turns the card over, the arrow keys move between cards.
1196
+ document.addEventListener("keydown", (event) => {
1197
+ if ($("view-cards").hidden || !cards.length || $("overlay").classList.contains("open") || event.target.closest("input, select, textarea, button")) return;
1198
+ if (event.key === " " || event.key === "Enter") { event.preventDefault(); flipCard(); }
1199
+ else if (event.key === "ArrowRight") moveCard(LANG === "ar" ? -1 : 1); // In the Arabic page, next is on the left.
1200
+ else if (event.key === "ArrowLeft") moveCard(LANG === "ar" ? 1 : -1);
1201
+ });
1202
+ // The choices for cards per file.
1203
+ $("cards-count").replaceChildren(...[3, 4, 5, 6].map((count) => Object.assign(document.createElement("option"), {value: count, textContent: count, selected: count === 5})));
1204
+
1205
+ // ---- Start-up: show what the server already has open.
1206
+ showRecent();
1207
+ loadModels();
1208
+ // A reloaded page shows no earlier messages, so the server forgets them too: follow-ups never use hidden context.
1209
+ api("/api/status").then((summary) => {
1210
+ setIndexed(summary);
1211
+ if (summary.repository) api("/api/reset", {method: "POST", body: "{}"}).catch(() => {});
1212
+ }).catch((error) => { $("index-status").textContent = error.message; });
1213
+ updateComposer();