Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

Web chat: one chat-history design - saved chats, edit and rewind, branch, send while answering (#1787, #2615, #3823, #4004)

Niko1221fcd3cdbcd7cd
diff --git a/serve/test_web_history.js b/serve/test_web_history.js
new file mode 100644
index 000000000..74658c24c
--- /dev/null
+++ b/serve/test_web_history.js
@@ -0,0 +1,222 @@
+// The chat history's logic (serve/web/history.js) and the browser store behind the saved-chats list (serve/web/chatstore.js),
+// run in Node. The store runs against a small stub of IndexedDB that is faithful where the code depends on it: a read's result
+// is on the request and not on the store; a write the browser refuses fires abort on the transaction; a blocked open never
+// resolves by itself; a database already at version 1 does not run onupgradeneeded; requests answer on a later tick.
+// (The stub and its cases are from PR #1787 by Scotty-Hudson, rebuilt for the split modules.)
+// node serve/test_web_history.js (serve/test_web_history.py runs it too and skips when node is missing)
+"use strict";
+const assert = require("node:assert/strict");
+const path = require("node:path");
+const H = require(path.join(__dirname, "web", "history.js"));
+const {createChatStore} = require(path.join(__dirname, "web", "chatstore.js"));
+
+const user = (text, extra = {}) => ({role: "user", text, time: 1, ...extra});
+const bot = (text, extra = {}) => ({role: "assistant", text, time: 2, ...extra});
+const tool = {id: "t1", name: "fs__read", result: "secret result", state: "done", round: 0, at: 0};
+const convo = () => [user("q1", {images: [{kind: "image", name: "a.png", url: "data:image/png;base64,AAA"}], files: [{kind: "file", name: "n.txt", text: "notes"}]}),
+ bot("a1", {reasoning: "thoughts", tools: [tool], meta: "12 tokens", stopped: true, error: "x"}), user("q2"), bot("a2")];
+
+const cases = {
+ titles_and_groups() {
+ assert.equal(H.chatTitle({title: "Mine", messages: []}), "Mine");
+ assert.equal(H.chatTitle({title: "", messages: [user(" first line\nsecond")]}), "first line");
+ assert.equal(H.chatTitle({title: "", messages: [user("x".repeat(100))]}).length, H.TITLE_MAX);
+ assert.equal(H.chatTitle({title: "", messages: []}), "New chat");
+ assert.equal(H.chatTitle({title: "", messages: []}, "Neuer Chat"), "Neuer Chat", "the caller's word for an unnamed chat");
+ const now = Date.UTC(2026, 9, 26, 12), day = 86400000;
+ const keys = [0, 0.4, 1.5, 5, 20, 40].map((d) => H.groupKey(now - d * day, now));
+ assert.deepEqual(keys, ["today", "today", "yesterday", "week", "month", "older"]);
+ const a = H.newChat(1, 0.5), b = H.newChat(2, 0.5);
+ assert.notEqual(a.id, b.id); assert.deepEqual(a.messages, []);
+ },
+ filter_searches_titles_and_text() {
+ const chats = [{id: "a", title: "the garden", time: 3, messages: [user("watering the tomatoes")]},
+ {id: "b", title: "a chat about code", time: 2, messages: [user("nothing here")]},
+ {id: "c", title: "tomatoes again", time: 1, messages: [user("a different question")]}];
+ assert.deepEqual(H.filterChats(chats, "").map((c) => c.id), ["a", "b", "c"], "newest first");
+ assert.deepEqual(H.filterChats(chats, " TOMATOES ").map((c) => c.id), ["a", "c"], "title or text, any case");
+ assert.deepEqual(H.filterChats(chats, "nothing here").map((c) => c.id), ["b"]);
+ assert.deepEqual(H.filterChats(chats, "zzz"), []);
+ assert.deepEqual(chats.map((c) => c.id), ["a", "b", "c"], "the caller's list is not reordered");
+ },
+ clean_keeps_names_only() {
+ const clean = H.cleanMessages(convo());
+ assert.deepEqual(clean[0].images, [{name: "a.png"}]);
+ assert.deepEqual(clean[0].files, [{name: "n.txt"}]);
+ assert.ok(!JSON.stringify(clean).includes("data:image") && !JSON.stringify(clean).includes("notes"), "no contents in the browser's store");
+ assert.equal(clean[1].text, "a1", "the text stays");
+ assert.deepEqual(convo()[0].files, [{kind: "file", name: "n.txt", text: "notes"}], "a copy: the screen keeps its contents");
+ },
+ rewind_a_question() {
+ const m = convo();
+ const plan = H.rewind(m, 2);
+ assert.deepEqual(plan.keep.map((x) => x.text), ["q1", "a1"]);
+ assert.equal(plan.hidden, 2, "the question and its answer");
+ assert.equal(plan.draft.text, "q2"); assert.equal(plan.draft.lost, 0);
+ const first = H.rewind(m, 0);
+ assert.deepEqual(first.keep, [], "the first question: nothing stays, the question goes to the box");
+ assert.equal(first.draft.text, "q1"); assert.equal(first.hidden, 4);
+ assert.deepEqual(first.draft.images, [{kind: "image", name: "a.png", url: "data:image/png;base64,AAA"}], "attachments with contents come back");
+ assert.deepEqual(first.draft.files, [{kind: "file", name: "n.txt", text: "notes"}]);
+ assert.equal(m.length, 4, "the list itself is not changed");
+ },
+ rewind_an_answer() {
+ const plan = H.rewind(convo(), 1);
+ assert.deepEqual(plan.keep.map((x) => x.text), ["q1", "a1"], "the answer stays and the list ends with it");
+ assert.equal(plan.draft, null); assert.equal(plan.hidden, 2);
+ assert.equal(H.rewind(convo(), 3).hidden, 0, "the last answer: nothing to hide");
+ assert.equal(H.rewind(convo(), 9), null);
+ },
+ lost_attachments_are_counted() {
+ const reloaded = H.cleanMessages(convo());
+ assert.equal(H.lostAttachments(reloaded[0]), 2);
+ assert.equal(H.lostAttachments(convo()[0]), 0);
+ const plan = H.rewind(reloaded, 0);
+ assert.equal(plan.draft.lost, 2); assert.deepEqual(plan.draft.images, []); assert.deepEqual(plan.draft.files, []);
+ assert.equal(plan.draft.text, "q1", "the text still comes back");
+ },
+ regenerate_from_the_question() {
+ const m = convo();
+ assert.deepEqual(H.regenerate(m, 1).keep.map((x) => x.text), ["q1"]);
+ assert.equal(H.regenerate(m, 1).hidden, 3);
+ assert.deepEqual(H.regenerate(m, 3).keep.map((x) => x.text), ["q1", "a1", "q2"]);
+ assert.deepEqual(H.regenerate(m, 2).keep.map((x) => x.text), ["q1", "a1", "q2"], "on the last question itself");
+ assert.equal(H.regenerate([bot("orphan")], 0), null, "no question before it");
+ },
+ edit_an_answer() {
+ const plan = H.editAnswer(convo(), 1, "corrected", "Edited");
+ assert.equal(plan.keep.length, 2); assert.equal(plan.hidden, 2);
+ const a = plan.keep[1];
+ assert.deepEqual(a, {role: "assistant", text: "corrected", time: 2, meta: "Edited"}, "no thinking, tools, error, stop mark or stats");
+ assert.equal(H.editAnswer(convo(), 0, "x"), null, "only an answer can be edited");
+ },
+ branch_is_a_copy_with_a_title_that_stays() {
+ const original = {id: "c1", title: "", time: 1, messages: convo()};
+ const plan = H.rewind(original.messages, 2);
+ const b = H.branch(original, plan.keep, plan.keep.length, "Branch of q1", 5, 0.25);
+ assert.deepEqual(b.messages.map((x) => x.text), ["q1", "a1"]);
+ assert.equal(b.title, "Branch of q1"); assert.deepEqual(b.parent, {id: "c1", title: "q1"});
+ assert.notEqual(b.id, "c1");
+ b.messages[0].text = "changed"; b.messages[1].tools[0].result = "changed";
+ assert.equal(original.messages[0].text, "q1", "the original is untouched");
+ assert.equal(original.messages[1].tools[0].result, "secret result");
+ assert.equal(H.chatTitle(H.branch(original, [], 0, "Branch of q1"), "x"), "Branch of q1", "a branch at the first message keeps its title");
+ },
+};
+
+// ---------------------------------------------------------------- the stub IndexedDB
+function makeIdb(hooks = {}, seed = {}) {
+ const data = Object.assign({}, seed), stores = {}, calls = {upgradeneeded: 0, createObjectStore: 0};
+ let current = null;
+ const request = () => ({result: null, error: null, transaction: current, onsuccess: null, onerror: null});
+ const store = {
+ put(value) {
+ const req = request();
+ queueMicrotask(() => {
+ if (hooks.quota) { req.error = {name: "QuotaExceededError"}; req.onerror && req.onerror(); return; }
+ if (hooks.abort) return;
+ data[value.id] = value; req.result = value; req.onsuccess && req.onsuccess();
+ });
+ return req;
+ },
+ delete(key) {
+ const req = request();
+ queueMicrotask(() => { if (hooks.quota || hooks.abort) return; delete data[key]; req.result = true; req.onsuccess && req.onsuccess(); });
+ return req;
+ },
+ getAll() {
+ const req = request();
+ queueMicrotask(() => { if (hooks.abort) return; req.result = Object.values(data); req.onsuccess && req.onsuccess(); });
+ return req;
+ },
+ };
+ const transaction = () => {
+ const t = {error: null, oncomplete: null, onerror: null, onabort: null, objectStore: () => store};
+ current = t;
+ queueMicrotask(() => {
+ if (hooks.quota || hooks.abort) { t.error = {name: hooks.quota ? "QuotaExceededError" : hooks.abort}; t.onabort && t.onabort(); }
+ else if (t.oncomplete) t.oncomplete();
+ });
+ return t;
+ };
+ const db = {objectStoreNames: {contains: (n) => n in stores}, createObjectStore: (n) => { calls.createObjectStore++; stores[n] = store; }, transaction};
+ return {open: () => {
+ if (hooks.throws) throw new Error("private mode");
+ const r = {result: db, error: null, onupgradeneeded: null, onsuccess: null, onerror: null, onblocked: null};
+ queueMicrotask(() => {
+ if (hooks.blocked) { r.onblocked && r.onblocked(); return; }
+ if (hooks.newDatabase !== false) { calls.upgradeneeded++; r.onupgradeneeded && r.onupgradeneeded(); }
+ r.result = db; r.onsuccess && r.onsuccess();
+ });
+ return r;
+ }, records: data, calls};
+}
+const wait = () => new Promise((r) => setTimeout(r, 10));
+const mk = (hooks, seed) => {
+ const idb = makeIdb(hooks, seed), problems = [];
+ return {idb, problems, store: createChatStore({indexedDB: idb, onProblem: (k) => problems.push(k)})};
+};
+const chat = (id, extra = {}) => ({id, title: id, time: 1, messages: [user("hi " + id)], ...extra});
+
+Object.assign(cases, {
+ async store_fresh_database_creates_the_store_and_reads() {
+ const a = mk({}, {c0: chat("c0"), c1: chat("c1")});
+ assert.equal(await a.store.start(), true);
+ assert.equal(a.idb.calls.upgradeneeded, 1); assert.equal(a.idb.calls.createObjectStore, 1);
+ assert.deepEqual((await a.store.all()).map((c) => c.id).sort(), ["c0", "c1"], "the result is read from the request");
+ assert.deepEqual(a.problems, []);
+ },
+ async store_put_and_remove_touch_one_record() {
+ const a = mk({}, {c0: chat("c0")});
+ await a.store.start();
+ a.store.put(chat("c1", {title: "renamed"})); await wait();
+ assert.equal(a.idb.records.c1.title, "renamed"); assert.ok(a.idb.records.c0, "the other record is not rewritten");
+ a.store.remove("c0"); await wait();
+ assert.ok(!("c0" in a.idb.records));
+ },
+ async store_private_mode_is_memory_only_and_says_so_once() {
+ const a = mk({throws: true});
+ assert.equal(await a.store.start(), false);
+ assert.deepEqual(a.problems, ["memory"]);
+ assert.deepEqual(await a.store.all(), []);
+ a.store.put(chat("x")); a.store.remove("x"); // no store: nothing to do, nothing thrown
+ await a.store.start();
+ assert.deepEqual(a.problems, ["memory"], "told once, not on every try");
+ },
+ async store_missing_object_store_is_memory_only() {
+ const a = mk({newDatabase: false}); // a database already at version 1: no upgrade, no store
+ assert.equal(await a.store.start(), false);
+ assert.equal(a.idb.calls.createObjectStore, 0);
+ assert.deepEqual(a.problems, ["memory"]);
+ },
+ async store_blocked_open_does_not_hang() {
+ const a = mk({blocked: true});
+ assert.equal(await a.store.start(), false);
+ assert.deepEqual(a.problems, ["memory"]);
+ },
+ async store_full_storage_warns_once_with_its_own_message() {
+ const a = mk({quota: true});
+ await a.store.start();
+ a.store.put(chat("big")); await wait();
+ a.store.put(chat("big2")); await wait();
+ assert.deepEqual(a.problems, ["quota"], "one warning, the quota one");
+ },
+ async store_another_failure_is_not_called_quota() {
+ const a = mk({abort: "DataError"});
+ await a.store.start();
+ a.store.put(chat("bad")); await wait();
+ assert.deepEqual(a.problems, ["failed"]);
+ },
+ async store_a_read_that_aborts_answers_empty() {
+ const a = mk({abort: "DataError"}, {c0: chat("c0")});
+ await a.store.start();
+ assert.deepEqual(await a.store.all(), [], "no hang, no records");
+ },
+});
+
+(async () => {
+ const name = process.argv[2];
+ const run = name ? [[name, cases[name]]] : Object.entries(cases);
+ if (name && !cases[name]) throw new Error("unknown test " + name);
+ for (const [n, fn] of run) { await fn(); console.log("ok " + n); }
+})().catch((e) => { console.error(e); process.exitCode = 1; });
diff --git a/serve/test_web_history.py b/serve/test_web_history.py
new file mode 100644
index 000000000..15854f2e4
--- /dev/null
+++ b/serve/test_web_history.py
@@ -0,0 +1,119 @@
+"""The web page's chat history: saved chats in the browser (#1787), edit / regenerate / rewind with an Undo (#2615), the rewind
+choice between "here" and a branch (#3823), and sending while an answer is written (#4004). One design, opt-in, off by default.
+
+The logic runs in Node (serve/test_web_history.js); what the page does in a real browser is in tools/webtest/browser_test.mjs
+(run here when WEBTEST_MODULES is set). These checks read the sources for what must hold whatever the code looks like:
+off is the page from before, and nothing about a chat goes to the server."""
+from __future__ import annotations
+
+import os
+import re
+import shutil
+import subprocess
+import unittest
+import urllib.error
+import urllib.request
+from pathlib import Path
+
+from serve.frontend import ChatTemplate
+from serve.server import ByteTokenizer, MockEngine, Service, serve
+
+ROOT = Path(__file__).resolve().parents[1]
+WEB = Path(__file__).parent / "web"
+
+
[email protected](shutil.which("node"), "node is not installed")
+class HistoryInNode(unittest.TestCase):
+ def test_messages_titles_branches_and_the_browser_store(self):
+ r = subprocess.run([shutil.which("node"), str(Path(__file__).with_name("test_web_history.js"))],
+ capture_output=True, text=True, timeout=60)
+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
+
+
+class OffIsThePageFromBefore(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ cls.html = (WEB / "index.html").read_text(encoding="utf-8")
+ cls.app = (WEB / "app.js").read_text(encoding="utf-8")
+ cls.ui = (WEB / "chats-ui.js").read_text(encoding="utf-8")
+ cls.store = (WEB / "chatstore.js").read_text(encoding="utf-8")
+
+ def test_the_three_switches_start_off(self):
+ self.assertIn('chatList: false, chatEdit: false, whileBusy: "wait"', self.app)
+ for el in ("s-list", "s-edit"):
+ self.assertIn('aria-checked="false"', re.search(rf'<button[^>]*id="{el}"[^>]*>', self.html).group(0))
+ self.assertIn('data-v="wait"', self.html)
+ self.assertRegex(self.html, r'<aside class="chat-sidebar"[^>]*\bhidden>') # no list until it is switched on
+
+ def test_the_browser_store_is_opened_only_for_the_list(self):
+ self.assertEqual(self.ui.count("chatStore.start()"), 1)
+ self.assertRegex(self.ui, r"async function openChats\(fromScreen\) \{\s*await chatStore\.start\(\);")
+ self.assertEqual(len(re.findall(r"\bopenChats\(", self.ui)), 2) # its definition and the one call, in setChatList
+ self.assertNotIn("indexedDB", self.app, "the page's main script never touches the store")
+ self.assertIn("if (settings.chatList) await setChatList(true, false);", self.app)
+
+ def test_with_the_list_off_one_chat_is_kept_as_before(self):
+ self.assertIn('if (!listOn) { store.set("chat", H.cleanMessages(messages)); return; }', self.ui)
+ self.assertIn('$("new-btn").hidden = on;', self.ui) # only the list's own New chat shows while it is on
+
+ def test_pictures_and_files_are_kept_as_names_only(self):
+ self.assertIn("chatStore.put(H.cleanChat(chat))", self.ui)
+ self.assertNotIn("chatStore.put(chat)", self.ui)
+
+ def test_nothing_about_a_chat_goes_to_the_server(self):
+ for name, src in (("app.js", self.app), ("chats-ui.js", self.ui), ("chatstore.js", self.store)):
+ for call in re.findall(r'fetch\(\s*([^,)]+)', src):
+ if call != '"v1/chat/completions"': # the question itself, as ever
+ self.assertNotRegex(call, r"chat|histor", f"{name}: {call}")
+
+ def test_the_edit_controls_wait_for_a_finished_answer(self):
+ self.assertIn("const historyLocked = () => !!busy || !!panel || !!pending;", self.ui)
+ self.assertIn("$(\"s-list\").disabled = $(\"s-edit\").disabled = !!busy || !!panel;", self.app)
+
+ def test_an_interrupted_answer_keeps_what_was_written(self):
+ self.assertIn("if (cut) m.interrupted = true;", self.app)
+ self.assertIn("busy.cutAfterTool = true; return; } // let the tool finish", self.app)
+ self.assertIn("settlePending(cut, !m.stopped && !m.error);", self.app)
+
+ def test_sending_while_busy_parks_nothing_unless_asked(self):
+ self.assertIn('const parksWhileBusy = () => settings.whileBusy === "queue" || settings.whileBusy === "interject";', self.app)
+ self.assertIn("if (!parksWhileBusy()) return;", self.app)
+
+
+class NothingOnTheServer(unittest.TestCase):
+ @classmethod
+ def setUpClass(cls):
+ tok = ByteTokenizer()
+ cls.svc = Service(MockEngine(tok, "ok"), tok, ChatTemplate(ROOT / "serve" / "chat_template.jinja"))
+ cls.httpd = serve(cls.svc, port=0)
+ cls.base = f"http://127.0.0.1:{cls.httpd.server_address[1]}"
+
+ @classmethod
+ def tearDownClass(cls):
+ cls.httpd.shutdown()
+ cls.httpd.server_close()
+
+ def test_the_scripts_are_served_and_there_is_no_chat_endpoint(self):
+ for name in ("history.js", "chatstore.js", "chats-ui.js"):
+ with urllib.request.urlopen(f"{self.base}/web/{name}", timeout=10) as r:
+ self.assertEqual(r.status, 200)
+ for path in ("/chats", "/api/chats", "/history", "/api/history"):
+ with self.subTest(path=path):
+ with self.assertRaises(urllib.error.HTTPError) as e:
+ urllib.request.urlopen(self.base + path, timeout=10)
+ self.assertEqual(e.exception.code, 404)
+
+
[email protected](os.environ.get("WEBTEST_MODULES") and shutil.which("node"),
+ "set WEBTEST_MODULES (a folder with node_modules/puppeteer-core) to run the browser tests")
+class InABrowser(unittest.TestCase):
+ def test_history_in_chrome(self):
+ for name in ("history", "list", "rewind", "branch", "regenerate", "edit answer", "while answering"):
+ with self.subTest(name=name):
+ r = subprocess.run([shutil.which("node"), str(ROOT / "tools" / "webtest" / "browser_test.mjs"), name],
+ capture_output=True, text=True, timeout=300)
+ self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/serve/web/app.css b/serve/web/app.css
index 9c40e4205..0873b2694 100644
--- a/serve/web/app.css
+++ b/serve/web/app.css
@@ -257,3 +257,81 @@ main { flex: 1; min-height: 0; display: flex; }
.st-code .st-btn--icon[data-preview-scripts][aria-pressed="true"] { background: var(--st-warn-tint); color: var(--st-warn-text); }
.st-code--run .st-code__preview { outline: 2px solid var(--st-warn-text); outline-offset: -2px; }
.st-code__preview iframe { display: block; width: 100%; height: 100%; border: 0; background: transparent; }
+
+/* ---------------------------------------------------------------- chat history (chats-ui.js)
+ The saved-chats list (PR #1787 by Scotty-Hudson), edit / regenerate / rewind (PR #2615 by uppet) and the Chat settings button. */
+.view--chat { flex-direction: row; }
+.chat-main { flex: 1; min-width: 0; display: flex; flex-direction: column; }
+.chat-sidebar { flex: none; width: 260px; display: flex; flex-direction: column; gap: var(--st-s-3);
+ padding: var(--st-s-4); background: var(--st-surface); border-right: 1px solid var(--st-line); }
+.sidebar-head { display: flex; align-items: center; gap: var(--st-s-2); }
+.sidebar-head .card-title { flex: 1; }
+#sidebar-toggle .st-icon { transform: rotate(90deg); transition: transform var(--st-dur) var(--st-ease); }
+.chat-sidebar[data-open="false"] { width: 60px; }
+.chat-sidebar[data-open="false"] .sidebar-head { flex-direction: column; }
+.chat-sidebar[data-open="false"] #sidebar-toggle .st-icon { transform: rotate(-90deg); }
+.chat-sidebar[data-open="false"] .sidebar-title, .chat-sidebar[data-open="false"] .sidebar-search,
+.chat-sidebar[data-open="false"] .sidebar-list, .chat-sidebar[data-open="false"] .sidebar-foot { display: none; }
+.sidebar-search { height: 36px; font-size: var(--st-fs-sm); }
+.sidebar-list { flex: 1; min-height: 0; overflow-y: auto; display: flex; flex-direction: column; }
+.sidebar-group { margin: 0; padding: var(--st-s-3) 8px var(--st-s-1); font-size: var(--st-fs-xs);
+ font-weight: var(--st-fw-bold); letter-spacing: .04em; text-transform: uppercase; color: var(--st-ink-muted); }
+.chat-item { display: flex; align-items: center; gap: 2px; border-radius: var(--st-r-md); }
+.chat-item.on { background: var(--st-surface-2); }
+.chat-item__title { flex: 1; min-width: 0; border: 0; background: transparent; cursor: pointer; text-align: left;
+ padding: 8px; color: var(--st-ink-soft); font: 500 var(--st-fs-sm)/1.35 var(--st-font);
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.chat-item:hover .chat-item__title { color: var(--st-ink); }
+.chat-item.on .chat-item__title { color: var(--st-ink); font-weight: var(--st-fw-bold); }
+.chat-item__actions { display: flex; gap: 2px; flex: none; opacity: 0; } /* the buttons come up on hover or focus */
+.chat-item:hover .chat-item__actions, .chat-item:focus-within .chat-item__actions { opacity: 1; }
+.chat-item__actions .st-btn--icon { width: 30px; height: 30px; }
+.chat-item__actions .st-btn--icon .st-icon { width: 16px; height: 16px; }
+.chat-item__input { flex: 1; min-width: 0; height: 34px; font-size: var(--st-fs-sm); }
+.sidebar-empty { margin: 0; padding: var(--st-s-2) 8px; }
+.sidebar-foot { margin: 0; }
+.chat-parent { display: flex; align-items: center; justify-content: center; gap: var(--st-s-3); flex-wrap: wrap; padding: var(--st-s-2) var(--st-s-4);
+ border-bottom: 1px solid var(--st-line-soft); font-size: var(--st-fs-sm); }
+.chat-parent .st-btn { height: 30px; padding: 0 12px; font-size: var(--st-fs-xs); }
+
+/* the buttons under a message, the open panel / editor, and the bars above the box (Undo, a waiting message) */
+.history-actions, .history-editor__actions, .history-undo, .pending { display: flex; flex-wrap: wrap; gap: var(--st-s-2); align-items: center; }
+.history-actions .st-btn, .history-undo .st-btn, .pending .st-btn, .history-panel .st-btn { height: 30px; padding: 0 10px; font-size: var(--st-fs-xs); }
+.history-actions { margin-top: var(--st-s-1); }
+.st-msg--user .history-actions { justify-content: flex-end; }
+.history-panel, .history-editor { width: 100%; display: flex; flex-direction: column; gap: var(--st-s-2); padding: var(--st-s-3);
+ border: 1px solid var(--st-line); border-radius: var(--st-r-md); background: var(--st-surface-2); }
+.history-choice { display: flex; align-items: center; gap: var(--st-s-3); flex-wrap: wrap; }
+.history-choice > .muted { flex: 1 1 14rem; min-width: 0; }
+.history-panel > .st-btn { align-self: flex-start; }
+.history-editor textarea { width: 100%; min-height: 140px; max-height: 50vh; resize: vertical; font: inherit; height: auto; padding: 10px 14px; }
+.history-editor p, .history-panel p { margin: 0; }
+.st-msg[data-editing="true"] > .st-bubble { display: none; }
+.history-undo, .pending { max-width: min(100%, 1100px); margin: 0 auto var(--st-s-2); color: var(--st-ink-muted); font-size: var(--st-fs-sm); }
+.pending { justify-content: space-between; padding: 6px 10px; border: 1px solid var(--st-line); border-radius: var(--st-r-md); background: var(--st-surface); }
+.pending__text { flex: 1 1 12rem; min-width: 0; overflow-wrap: anywhere; color: var(--st-ink-soft); }
+.pending__actions { display: flex; gap: var(--st-s-2); }
+
+/* Chat settings: the button says what it is, and the drawer groups the chat switches */
+.chat-settings-button { height: 36px; padding: 0 10px; gap: 6px; white-space: nowrap; font-size: var(--st-fs-sm); }
+.chat-settings-short { display: none; }
+.drawer-group { display: flex; flex-direction: column; gap: var(--st-s-4); padding-top: var(--st-s-4); border-top: 1px solid var(--st-line); }
+.drawer-group__title { margin: 0; font-size: var(--st-fs-base); font-weight: var(--st-fw-bold); color: var(--st-ink); }
+.seg--3 { grid-template-columns: repeat(3, 1fr); }
+.seg--3 button { padding: 0 4px; }
+#lang { width: 100%; }
+@media (max-width: 640px) {
+ .chat-settings-label, .composer-hint { display: none; }
+ .chat-settings-short { display: inline; }
+ .st-btn--send { margin-left: auto; }
+}
+@media (max-width: 760px) {
+ /* the list is an overlay here: the chat keeps the whole width when it is closed to its rail */
+ .view--chat { position: relative; }
+ .chat-sidebar[data-open="true"] { position: absolute; top: 0; left: 0; bottom: 0; z-index: 30; box-shadow: var(--st-sh-pop); }
+ .chat-sidebar { padding: var(--st-s-3); }
+}
+
+/* a message may use the room a wide window gives the chat column (#3176 widened the column; the kit's 720px kept the messages narrow in it) */
+.st-msg { max-width: min(100%, 900px); }
+.st-toast .st-btn { white-space: nowrap; }
diff --git a/serve/web/app.js b/serve/web/app.js
index 4b0477fd9..e0ad80aa8 100644
--- a/serve/web/app.js
+++ b/serve/web/app.js
@@ -781,7 +781,8 @@ function markdown(text) {
// fields: the server picks the card's set for the request's thinking state (thinking 1.0 / 0.95 / 20, not thinking
// 0.7 / 0.8 / 20 with a presence penalty). Before 0.1.45 the page sent 0.6 itself; a stored 0.6 with the other two
// values untouched counts as "not set" too.
-const DEFAULTS = {thinking: "high", temperature: 1.0, top_p: 0.95, top_k: 20, max: "", seed: "", show: true, esp: true, mcp: true, math: false};
+const DEFAULTS = {thinking: "high", temperature: 1.0, top_p: 0.95, top_k: 20, max: "", seed: "", show: true, esp: true, mcp: true, math: false,
+ chatList: false, chatEdit: false, whileBusy: "wait"};
const OLD_DEFAULT_TEMPERATURE = 0.6;
function samplingUntouched(s) {
const t = +s.temperature;
@@ -789,14 +790,10 @@ function samplingUntouched(s) {
}
let settings = {...DEFAULTS, ...store.get("sampling", {})};
if (samplingUntouched(settings)) settings.temperature = DEFAULTS.temperature;
-let messages = store.get("chat", []);
+let messages = store.get("chat", []); // the open chat's messages (chats-ui.js: with the saved-chats list on, also that chat's own)
let attachments = []; // {name, url}
-let busy = null; // {controller, msg}
-
-function saveChat() {
- store.set("chat", messages.map((m) => ({...m, images: (m.images || []).map((i) => ({name: i.name})),
- files: (m.files || []).map((f) => ({name: f.name}))})));
-}
+let busy = null; // {controller, msg, cut, cutAfterTool}
+let pending = null; // a message parked while an answer is written: {text, images, files, mode}
function timeStr(t) { return new Date(t).toLocaleTimeString([], {hour: "2-digit", minute: "2-digit"}); }
function msgEl(m, i) {
@@ -840,6 +837,8 @@ function msgEl(m, i) {
`<button class="st-btn st-btn--icon" data-msg-copy aria-label="Copy the answer" title="Copy">${icon("copy")}</button></div>`;
updateAssistant(el, m, false);
}
+ const actions = msgActions(m, i); // edit / regenerate / rewind (chats-ui.js), when switched on
+ if (actions) el.appendChild(actions);
return el;
}
// One MCP tool call in the answer: a compact block (name, state, a one-line preview) that opens to the arguments and
@@ -927,6 +926,9 @@ function renderChat() {
chat.querySelectorAll(".st-msg").forEach((e) => e.remove());
$("chat-empty").hidden = messages.length > 0;
messages.forEach((m, i) => chat.appendChild(msgEl(m, i)));
+ renderSidebar();
+ renderParent();
+ renderUndoBar();
scrollDown(true);
}
function nearBottom() { const s = $("chat-scroll"); return s.scrollHeight - s.scrollTop - s.clientHeight < 120; }
@@ -1018,27 +1020,122 @@ function assistantMessages(m) {
return out;
}
+function busyHint() {
+ const mode = settings.whileBusy;
+ return mode === "queue" ? tr("composer.hintQueue", "Enter sends when the answer is done")
+ : mode === "interject" ? tr("composer.hintInterject", "Enter stops the answer here and sends now") : "";
+}
+// While an answer is written, Send is off ("wait", as always) or parks the message ("queue", "interject": Chat settings)
+const parksWhileBusy = () => settings.whileBusy === "queue" || settings.whileBusy === "interject";
function setBusy(on) {
$("stop-btn").hidden = !on;
- $("send-btn").disabled = on;
- $("composer-hint").textContent = on ? "" : "Shift+Enter: new line";
+ $("send-btn").disabled = (on && !parksWhileBusy()) || !!panel;
+ $("input").disabled = !!panel;
+ $("composer-hint").textContent = panel ? tr("composer.finishOpen", "Save or cancel what is open above to continue")
+ : on ? busyHint() : tr("composer.newline", "Shift+Enter: new line");
+ if (settings.chatEdit) syncActions(); // the buttons follow the state: none under the answer being written
+ $("s-list").disabled = $("s-edit").disabled = !!busy || !!panel; // they change the messages on the screen
+ renderUndoBar();
+ renderPending();
+}
+
+// A message sent while an answer is being written (#4004). "queue": it waits and goes when the answer is done. "interject": the
+// answer stops where it is (what is written stays, marked interrupted) and the message goes at once; if a tool is running, the
+// tool finishes first. Only one message waits. Off by default: with "wait" the page does nothing, as before.
+function park(p, own) {
+ if (!parksWhileBusy()) return;
+ if (pending) { toast("warn", tr("pending.one", "A message is already waiting"), tr("pending.oneText", "Take it back or wait until it is sent.")); return; }
+ pending = {...p, mode: settings.whileBusy};
+ if (own) { attachments = []; renderAttachments(); $("input").value = ""; autosize(); }
+ if (pending.mode === "interject") requestCut();
+ setBusy(!!busy);
+}
+function requestCut() {
+ if (!busy || busy.cut) return;
+ if ((busy.msg.tools || []).some((t) => t.state === "running")) { busy.cutAfterTool = true; return; } // let the tool finish
+ busy.cut = true;
+ busy.controller.abort();
+}
+function renderPending() {
+ let el = $("pending");
+ if (!pending) { if (el) el.remove(); return; }
+ if (!el) {
+ el = node("div", "pending");
+ el.id = "pending";
+ el.setAttribute("role", "status");
+ el.innerHTML = "<span class=\"pending__text\"></span><span class=\"pending__actions\"><button type=\"button\" class=\"st-btn st-btn--secondary\" data-pending-now></button>" +
+ "<button type=\"button\" class=\"st-btn st-btn--secondary\" data-pending-back></button></span>";
+ el.querySelector("[data-pending-now]").onclick = pendingNow;
+ el.querySelector("[data-pending-back]").onclick = releasePending;
+ $("composer").before(el);
+ }
+ const quote = (pending.text || (pending.files[0] || pending.images[0] || {}).name || "").replace(/\s+/g, " ").slice(0, 70);
+ const text = !busy ? tr("pending.ready", "Not sent yet: “{text}”", {text: quote})
+ : pending.mode === "queue" ? tr("pending.queued", "Sends when this answer is done: “{text}”", {text: quote})
+ : busy.cutAfterTool ? tr("pending.afterTool", "Waiting for the tool to finish, then sending: “{text}”", {text: quote})
+ : tr("pending.cutting", "Stopping the answer, then sending: “{text}”", {text: quote});
+ el.querySelector(".pending__text").textContent = text;
+ const now = el.querySelector("[data-pending-now]");
+ now.textContent = busy ? tr("pending.sendNow", "Send now") : tr("pending.send", "Send");
+ now.hidden = !!busy && pending.mode === "interject"; // already on its way
+ el.querySelector("[data-pending-back]").textContent = tr("pending.takeBack", "Take back");
+}
+function pendingNow() {
+ if (!pending) return;
+ if (busy) { pending.mode = "interject"; requestCut(); setBusy(true); return; }
+ const p = pending;
+ pending = null;
+ setBusy(false);
+ send(p);
+}
+// the waiting message goes back into the message box (a chat switch or a new chat must not lose it)
+function releasePending() {
+ if (!pending) return;
+ const p = pending;
+ pending = null;
+ if (!$("input").value.trim()) $("input").value = p.text;
+ else $("input").value = `${p.text}\n\n${$("input").value}`;
+ attachments = [...p.images, ...p.files, ...attachments];
+ renderAttachments(); autosize();
+ setBusy(!!busy);
+}
+// after an answer: an interrupted one sends an interjection, a finished one sends a queued message
+function settlePending(cut, finished) {
+ if (!pending) return;
+ if ((pending.mode === "interject" && cut) || (pending.mode === "queue" && finished)) {
+ const p = pending;
+ pending = null;
+ setBusy(false);
+ send(p);
+ }
}
-async function send() {
- const text = $("input").value.trim();
- if ((!text && !attachments.length) || busy) return;
- messages.push({role: "user", text, images: attachments.filter((a) => a.kind !== "file"),
- files: attachments.filter((a) => a.kind === "file"), time: Date.now()});
- attachments = [];
- renderAttachments();
- $("input").value = "";
- autosize();
+// the message box (or a parked message, `payload`) becomes a user turn and a reply is asked for
+async function send(payload) {
+ const own = !payload;
+ const p = payload || {text: $("input").value.trim(), images: attachments.filter((a) => a.kind !== "file"),
+ files: attachments.filter((a) => a.kind === "file")};
+ if (!p.text && !p.images.length && !p.files.length) return;
+ if (panel) return; // something is open above (an edit): finish it first
+ if (busy) { park(p, own); return; }
+ clearUndo();
+ messages.push({role: "user", text: p.text, images: p.images, files: p.files, time: Date.now()});
+ if (own) {
+ attachments = [];
+ renderAttachments();
+ $("input").value = "";
+ autosize();
+ }
+ return generateReply();
+}
+// an answer for the messages as they are: the last one is a user turn
+async function generateReply() {
const m = {role: "assistant", text: "", reasoning: "", time: Date.now()};
messages.push(m);
renderChat();
const el = $("chat").lastElementChild;
const controller = new AbortController();
- busy = {controller, msg: m};
+ busy = {controller, msg: m, cut: false, cutAfterTool: false};
setBusy(true);
paintLive();
@@ -1062,7 +1159,7 @@ async function send() {
if (!r.ok) {
let msg = `HTTP ${r.status}`;
try { msg = (await r.json()).error.message || msg; } catch (e) { /* not json */ }
- if (r.status === 401) msg = "This server needs an API key: add it under About > Settings.";
+ if (r.status === 401) msg = tr("toast.keyNeeded", "This server needs an API key: add it under About > Settings.");
throw new Error(msg);
}
const reader = r.body.getReader(), dec = new TextDecoder();
@@ -1080,9 +1177,13 @@ async function send() {
if (data === "[DONE]") continue;
let j;
try { j = JSON.parse(data); } catch (e) { continue; }
- if (j.error) throw new Error(j.error.message || "the engine reported an error");
+ if (j.error) throw new Error(j.error.message || tr("toast.engineError", "the engine reported an error"));
if (j.usage) usage = j.usage;
- if (j.strata_mcp) onTool(m, j.strata_mcp);
+ if (j.strata_mcp) {
+ onTool(m, j.strata_mcp);
+ // an interjection waited for a running tool: it has its result now, so the answer can stop
+ if (busy.cutAfterTool && !busy.cut && !(m.tools || []).some((t) => t.state === "running")) { busy.cut = true; controller.abort(); }
+ }
const d = (j.choices && j.choices[0] && j.choices[0].delta) || {};
const lastTool = m.tools && m.tools.length ? m.tools[m.tools.length - 1] : null; // a new round after a tool
if (d.reasoning_content) {
@@ -1102,21 +1203,24 @@ async function send() {
}
} catch (e) {
if (e.name === "AbortError") m.stopped = true;
- else { m.error = e.message || String(e); toast("error", "The request failed", m.error, 6000); }
+ else { m.error = e.message || String(e); toast("error", tr("toast.requestFailed", "The request failed"), m.error, 6000); }
}
+ const cut = busy.cut; // an interjection ended it: kept as written, marked interrupted
+ if (cut) m.interrupted = true;
if (thinkStart && m.thinkSecs == null) m.thinkSecs = (performance.now() - thinkStart) / 1000;
const n = usage ? usage.completion_tokens : null;
+ const ended = cut ? tr("chat.interruptedLower", "interrupted") : tr("chat.stoppedLower", "stopped");
if (n && firstAt) {
const secs = (performance.now() - firstAt) / 1000;
- m.meta = `${fmt(n)} tokens${secs > 0.25 ? ` · ${fmt(n / secs, 1)} tok/s` : ""}${m.stopped ? " · stopped" : ""}` +
- (projectionLoaded() ? (settings.esp ? " · projection on" : " · projection off") : "");
+ m.meta = tr("chat.tokens", "{n} tokens", {n: fmt(n)}) + (secs > 0.25 ? ` · ${fmt(n / secs, 1)} tok/s` : "") + (m.stopped ? ` · ${ended}` : "") +
+ (projectionLoaded() ? (settings.esp ? ` · ${tr("chat.projectionOn", "projection on")}` : ` · ${tr("chat.projectionOff", "projection off")}`) : "");
} else if (m.stopped) {
- m.meta = "Stopped";
+ m.meta = cut ? tr("chat.interrupted", "Interrupted") : tr("chat.stopped", "Stopped");
}
for (const t of m.tools || []) if (t.state === "writing" || t.state === "running") { t.state = "skipped"; t.ms = null; }
const ran = (m.tools || []).filter((t) => t.state === "done" || t.state === "error").length;
- if (ran) m.meta = `${m.meta ? `${m.meta} · ` : ""}${ran} tool call${ran > 1 ? "s" : ""}`;
- if (m.limit) m.meta = `${m.meta || ""} · stopped at the limit of ${m.limit} tool rounds (mcp.max_rounds)`;
+ if (ran) m.meta = `${m.meta ? `${m.meta} · ` : ""}${tr("chat.toolCalls", {one: "{n} tool call", other: "{n} tool calls"}, {n: ran})}`;
+ if (m.limit) m.meta = `${m.meta || ""} · ${tr("chat.toolLimit", "stopped at the limit of {n} tool rounds (mcp.max_rounds)", {n: m.limit})}`;
busy = null;
setBusy(false);
paintLive();
@@ -1124,6 +1228,7 @@ async function send() {
updateAssistant(el, m, false);
saveChat();
scrollDown();
+ settlePending(cut, !m.stopped && !m.error);
}
$("composer").onsubmit = (e) => { e.preventDefault(); send(); };
@@ -1134,14 +1239,21 @@ $("input").addEventListener("keydown", (e) => {
function autosize() { const t = $("input"); t.style.height = "auto"; t.style.height = `${Math.min(t.scrollHeight, innerHeight * 0.4)}px`; }
$("input").addEventListener("input", autosize);
+// one chat, as before: New chat clears it, with an Undo (with the saved-chats list on, its own New chat button does this job)
$("new-btn").onclick = () => {
- if (busy) { toast("warn", "Still writing", "Stop the answer first."); return; }
+ if (busy) { stillWriting(); return; }
+ if (panel) { closePanel(); }
+ clearUndo();
+ releasePending();
if (!messages.length) return;
const backup = messages;
messages = [];
saveChat();
renderChat();
- toast("info", "New chat", "The last one was cleared.", 6000, {label: "Undo", run: () => { messages = backup; saveChat(); renderChat(); }});
+ toast("info", tr("chat.newToast", "New chat"), tr("chat.clearedToast", "The last one was cleared."), 6000, {label: tr("undo", "Undo"), run: () => {
+ if (busy || messages.length) return; // a new question since: the cleared chat is not put back over it
+ messages = backup; saveChat(); renderChat();
+ }});
};
$("export-btn").onclick = () => {
if (!messages.length) { toast("info", "Nothing to save yet"); return; }
@@ -1238,13 +1350,15 @@ $("input").addEventListener("paste", (e) => {
if (files.length) { e.preventDefault(); addFiles(files); }
});
-// ------------------------------------------------------------------ the sampling drawer
+// ------------------------------------------------------------------ the chat settings drawer
function openDrawer(open) {
$("drawer").dataset.open = String(open);
$("drawer").setAttribute("aria-hidden", String(!open));
$("scrim").hidden = !open;
if (open) { loadDrawer(); loadShared(); loadMcp(); }
}
+const checked = (id) => $(id).getAttribute("aria-checked") === "true";
+const segValue = (id) => { const b = [...$(id).children].find((x) => x.getAttribute("aria-checked") === "true"); return b ? b.dataset.v : null; };
function loadDrawer(s = settings) {
for (const b of $("s-thinking").children) b.setAttribute("aria-checked", String(b.dataset.v === s.thinking));
$("s-temp").value = s.temperature; $("s-topp").value = s.top_p; $("s-topk").value = s.top_k;
@@ -1255,6 +1369,9 @@ function loadDrawer(s = settings) {
$("esp-row").hidden = !projectionLoaded();
$("s-mcp").setAttribute("aria-checked", String(s.mcp !== false));
$("s-share").setAttribute("aria-checked", String(sharedOn));
+ $("s-list").setAttribute("aria-checked", String(!!s.chatList));
+ $("s-edit").setAttribute("aria-checked", String(!!s.chatEdit));
+ for (const b of $("s-busy").children) b.setAttribute("aria-checked", String(b.dataset.v === (s.whileBusy || "wait")));
outputs();
}
// "Use for other apps too": the server keeps these settings as every client's defaults (GET/POST /settings)
@@ -1292,48 +1409,57 @@ function projectionLoaded() {
}
function outputs() {
const t = +$("s-temp").value;
- $("o-temp").textContent = t === 0 ? "0 · greedy" : t.toFixed(2);
+ $("o-temp").textContent = t === 0 ? tr("drawer.greedy", "0 · greedy") : t.toFixed(2);
$("o-topp").textContent = (+$("s-topp").value).toFixed(2);
$("o-topk").textContent = $("s-topk").value;
- const sel = [...$("s-thinking").children].find((b) => b.getAttribute("aria-checked") === "true");
- $("o-thinking").textContent = sel ? {none: "answers right away", low: "short", medium: "medium", high: "thorough (default)"}[sel.dataset.v] : "";
+ const sel = segValue("s-thinking");
+ $("o-thinking").textContent = sel ? {none: tr("drawer.thinkNone", "answers right away"), low: tr("drawer.thinkLow", "short"),
+ medium: tr("drawer.thinkMedium", "medium"), high: tr("drawer.thinkHigh", "thorough (default)")}[sel] : "";
+ const busyMode = segValue("s-busy");
+ $("o-busy").textContent = {wait: tr("drawer.busyWaitNote", "Send is off until the answer is done, as before."),
+ queue: tr("drawer.busyQueueNote", "Your message waits and goes as soon as the answer is done."),
+ interject: tr("drawer.busyInterjectNote", "The answer stops where it is (what is written stays) and your message goes at once. A tool that is running finishes first.")}[busyMode] || "";
for (const id of ["s-topp", "s-topk"]) $(id).disabled = t === 0;
}
for (const b of $("s-thinking").children) b.onclick = () => { for (const x of $("s-thinking").children) x.setAttribute("aria-checked", String(x === b)); outputs(); };
+for (const b of $("s-busy").children) b.onclick = () => { for (const x of $("s-busy").children) x.setAttribute("aria-checked", String(x === b)); outputs(); };
for (const id of ["s-temp", "s-topp", "s-topk"]) $(id).oninput = outputs;
-$("s-math").onclick = () => $("s-math").setAttribute("aria-checked", String($("s-math").getAttribute("aria-checked") !== "true"));
-$("s-show").onclick = () => $("s-show").setAttribute("aria-checked", String($("s-show").getAttribute("aria-checked") !== "true"));
-$("s-esp").onclick = () => $("s-esp").setAttribute("aria-checked", String($("s-esp").getAttribute("aria-checked") !== "true"));
-$("s-mcp").onclick = () => $("s-mcp").setAttribute("aria-checked", String($("s-mcp").getAttribute("aria-checked") !== "true"));
-$("s-share").onclick = () => $("s-share").setAttribute("aria-checked", String($("s-share").getAttribute("aria-checked") !== "true"));
+for (const id of ["s-math", "s-show", "s-esp", "s-mcp", "s-share", "s-list", "s-edit"]) {
+ $(id).onclick = () => $(id).setAttribute("aria-checked", String($(id).getAttribute("aria-checked") !== "true"));
+}
$("s-reset").onclick = () => loadDrawer(DEFAULTS);
$("s-apply").onclick = async () => {
- const sel = [...$("s-thinking").children].find((b) => b.getAttribute("aria-checked") === "true");
- settings = {thinking: sel ? sel.dataset.v : "high", temperature: +$("s-temp").value, top_p: +$("s-topp").value,
+ const prev = settings;
+ // the list and the edit controls change the messages on the screen: not while an answer is written or something is open
+ const locked = !!busy || !!panel;
+ settings = {thinking: segValue("s-thinking") || "high", temperature: +$("s-temp").value, top_p: +$("s-topp").value,
top_k: +$("s-topk").value, max: $("s-max").value.trim(), seed: $("s-seed").value.trim(),
- math: $("s-math").getAttribute("aria-checked") === "true",
- show: $("s-show").getAttribute("aria-checked") === "true",
- esp: $("s-esp").getAttribute("aria-checked") === "true",
- mcp: $("s-mcp").getAttribute("aria-checked") === "true"};
+ math: checked("s-math"), show: checked("s-show"), esp: checked("s-esp"), mcp: checked("s-mcp"),
+ chatList: locked ? !!prev.chatList : checked("s-list"), chatEdit: locked ? !!prev.chatEdit : checked("s-edit"),
+ whileBusy: segValue("s-busy") || "wait"};
store.set("sampling", settings);
StrataMath.reset(); // math on or off: every answer is drawn again
+ if (settings.chatList !== !!prev.chatList) await setChatList(settings.chatList, true);
+ if (settings.chatEdit !== !!prev.chatEdit) { clearUndo(); syncActions(); }
+ if (settings.whileBusy === "wait" && pending) releasePending(); // "wait" parks nothing: a waiting message goes back to the box
+ setBusy(!!busy);
for (const el of $("chat").querySelectorAll(".st-msg--assistant")) {
const m = messages[+el.dataset.i];
updateAssistant(el, m, !!busy && busy.msg === m); // the element send() holds stays the same while an answer streams
}
- const share = $("s-share").getAttribute("aria-checked") === "true";
+ const share = checked("s-share");
openDrawer(false);
if (share || sharedOn) {
try {
await saveShared(share, settings);
- toast("success", "Sampling saved", share ? "Other apps (omp, API clients) use these settings from their next request."
- : "Other apps use their own settings again.");
+ toast("success", tr("drawer.saved", "Chat settings saved"), share ? tr("drawer.savedShared", "Other apps (omp, API clients) use these settings from their next request.")
+ : tr("drawer.savedOwn", "Other apps use their own settings again."));
} catch (e) {
- toast("error", "Saved here, but not for other apps", e.message, 6000);
+ toast("error", tr("drawer.savedHere", "Saved here, but not for other apps"), e.message, 6000);
}
return;
}
- toast("success", "Sampling saved", settings.temperature === 0 ? "Greedy: the same question gives the same answer." : "");
+ toast("success", tr("drawer.saved", "Chat settings saved"), settings.temperature === 0 ? tr("drawer.savedGreedy", "Greedy: the same question gives the same answer.") : "");
};
$("sampling-btn").onclick = () => openDrawer(true);
$("drawer-close").onclick = () => openDrawer(false);
@@ -1360,6 +1486,8 @@ $("lang").onchange = async () => {
async function start() {
await StrataI18n.setLanguage(urlLang || store.get("lang", "en"));
$("lang").value = StrataI18n.lang;
+ initChats();
+ if (settings.chatList) await setChatList(true, false); // the saved-chats list is read before the first draw
setBusy(false);
renderChat();
const startQuestion = new URLSearchParams(location.search).get("q"); // /?q=... starts a chat (a shortcut)
diff --git a/serve/web/chats-ui.js b/serve/web/chats-ui.js
new file mode 100644
index 000000000..f15d78690
--- /dev/null
+++ b/serve/web/chats-ui.js
@@ -0,0 +1,450 @@
+// serve/web/chats-ui.js - the chat history on the page: the saved-chats list, and edit / regenerate / go back / branch / undo.
+// One design for the proposals in PRs #1787 (list), #2615 (edit, regenerate, undo) and issue #3823 (rewind asks: here or a branch);
+// the pure part is serve/web/history.js, the browser store is serve/web/chatstore.js.
+//
+// Both are opt-in (Chat settings > Chats) and off by default: off, the page keeps the one chat it always had, with "New chat"
+// clearing it (and an Undo). Nothing here goes to the server.
+//
+// This file is loaded before app.js and uses its globals when its functions run: $, esc, icon, node, toast, store, settings,
+// messages, attachments, busy, pending, setBusy, renderChat, renderAttachments, autosize, generateReply, releasePending.
+// app.js calls initChats() once, from start().
+"use strict";
+
+const H = StrataHistory;
+const untitled = () => tr("chat.untitled", "New chat");
+const node = (tag, cls, text) => {
+ const n = document.createElement(tag);
+ if (cls) n.className = cls;
+ if (text != null) n.textContent = text;
+ return n;
+};
+
+// ------------------------------------------------------------------ state
+let listOn = false; // the saved-chats list is on
+let chats = [], chat = null, chatId = "";
+let sidebarQuery = "", sidebarOpen = true;
+let undoState = null; // one change, in memory until a new question, another chat or a reload
+let panel = null; // the open "Rewind to here" panel or answer editor: {kind, index, el}
+const chatStore = StrataChatStore.createChatStore({
+ onProblem(kind) {
+ toast("warn", tr("store.title", "Chat list not saved"), kind === "memory"
+ ? tr("store.memory", "This browser will not keep the chat list. It stays in memory until you close the page.")
+ : kind === "quota" ? tr("store.quota", "This browser cannot keep more. The chats on the screen are still there.")
+ : tr("store.failed", "The chat list could not be saved. The chats on the screen are still there."), 6000);
+ },
+});
+
+// the open chat's messages are the page's `messages`; with the list on they are also the chat's, the same array
+function setMessages(next) {
+ messages = next;
+ if (chat) chat.messages = next;
+}
+function saveChat() {
+ if (!listOn) { store.set("chat", H.cleanMessages(messages)); return; } // off: one chat, as before
+ chat.time = Date.now();
+ chatStore.put(H.cleanChat(chat));
+ renderSidebar();
+}
+function stillWriting() { toast("warn", tr("busy.stillWriting", "Still writing"), tr("busy.stopFirst", "Stop the answer first.")); }
+
+// ------------------------------------------------------------------ the saved-chats list (#1787)
+// Turning the list on: the chat on the screen becomes the first record. Only when the switch is flipped in this visit: on a page
+// load the list is the list, so a fresh chat stays empty and the single chat of before ("strata.chat") is read once, when the
+// store is empty.
+async function openChats(fromScreen) {
+ await chatStore.start();
+ chats = await chatStore.all();
+ if (!chats.length) {
+ const old = fromScreen ? messages : store.get("chat", []);
+ if (old.length) {
+ const c = {...H.newChat(), messages: old, time: old[old.length - 1].time || Date.now()};
+ chats = [c];
+ chatStore.put(H.cleanChat(c)); // the migrated chat is a record like the others
+ }
+ }
+ chat = chats.find((c) => c.id === store.get("chatId", "")) || chats[0] || H.newChat();
+ if (!chats.includes(chat)) chats.push(chat);
+ chatId = chat.id;
+ setMessages(chat.messages);
+}
+async function setChatList(on, fromScreen) {
+ listOn = on;
+ $("sidebar").hidden = !on;
+ $("new-btn").hidden = on; // the list has its own New chat
+ if (!on) { // off writes the single chat, so a reload shows the chat you were in
+ if (chat) messages = chat.messages;
+ chat = null;
+ store.set("chat", H.cleanMessages(messages));
+ renderChat();
+ return;
+ }
+ await openChats(fromScreen);
+ renderChat();
+}
+
+function groupName(key) {
+ return {today: tr("group.today", "Today"), yesterday: tr("group.yesterday", "Yesterday"), week: tr("group.week", "Previous 7 days"),
+ month: tr("group.month", "Previous 30 days"), older: tr("group.older", "Older")}[key];
+}
+function chatItem(c) {
+ const t = H.chatTitle(c, untitled());
+ const row = node("div", `chat-item${c.id === chatId ? " on" : ""}`);
+ row.dataset.id = c.id;
+ row.innerHTML = `<button class="chat-item__title" data-open-chat title="${esc(t)}">${esc(t)}</button>` +
+ `<span class="chat-item__actions">` +
+ `<button class="st-btn st-btn--icon" data-rename aria-label="${esc(tr("sidebar.rename", "Rename this chat"))}" title="${esc(tr("sidebar.renameShort", "Rename"))}">${icon("edit")}</button>` +
+ `<button class="st-btn st-btn--icon" data-delete aria-label="${esc(tr("sidebar.delete", "Delete this chat"))}" title="${esc(tr("sidebar.deleteShort", "Delete"))}">${icon("trash")}</button>` +
+ `</span>`;
+ return row;
+}
+function renderSidebar() {
+ if (!listOn) return;
+ // the search reads every chat's message text, so the whole store is in memory after the first load
+ const list = H.filterChats(chats, sidebarQuery, untitled());
+ const box = $("sidebar-list");
+ box.innerHTML = "";
+ if (!list.length) {
+ box.appendChild(node("p", "muted small sidebar-empty", sidebarQuery.trim() ? tr("sidebar.noMatch", "No chat matches") : tr("sidebar.none", "No chats yet")));
+ } else {
+ let group = "";
+ for (const c of list) {
+ const g = H.groupKey(c.time);
+ if (g !== group) { group = g; box.appendChild(node("p", "sidebar-group", groupName(g))); }
+ box.appendChild(chatItem(c));
+ }
+ }
+ $("sidebar-foot").textContent = tr("sidebar.foot", {one: "{n} chat · kept in this browser", other: "{n} chats · kept in this browser"}, {n: chats.length});
+}
+
+function showChat(c) {
+ clearUndo();
+ chat = c; chatId = c.id; messages = c.messages;
+ store.set("chatId", chatId);
+ chatStore.put(H.cleanChat(chat)); // renderChat renders the list, so the write here does not render it again
+ renderChat();
+}
+function openChat(id) {
+ if (busy) { stillWriting(); return; }
+ const c = chats.find((x) => x.id === id);
+ if (!c || c === chat) return;
+ releasePending();
+ closePanel();
+ showChat(c);
+}
+function startChat() {
+ if (busy) { stillWriting(); return; }
+ if (!messages.length && !chat.parent) { $("input").focus(); return; } // already a fresh chat
+ releasePending();
+ closePanel();
+ const prev = chatId, c = H.newChat();
+ chats.push(c);
+ showChat(c);
+ $("input").focus();
+ toast("info", tr("chat.newToast", "New chat"), tr("chat.newToastText", "The one you were in is in the list on the left."), 6000,
+ {label: tr("undo", "Undo"), run: () => openChat(prev)});
+}
+function deleteChat(c) {
+ if (busy && c.id === chatId) { stillWriting(); return; }
+ const i = chats.indexOf(c), wasOpen = c.id === chatId;
+ if (i < 0) return; // the list only ever passes a chat it holds
+ chats.splice(i, 1);
+ chatStore.remove(c.id); // the record; the Undo puts it back
+ if (wasOpen) {
+ releasePending();
+ closePanel();
+ const next = chats[0] || H.newChat();
+ if (!chats.includes(next)) chats.push(next);
+ showChat(next);
+ } else renderSidebar();
+ toast("info", tr("chat.deleted", "Chat deleted"), H.chatTitle(c, untitled()), 6000, {label: tr("undo", "Undo"), run: () => {
+ if (chats.includes(c)) return; // already put back
+ chats.splice(Math.min(i, chats.length), 0, c); // the display is sorted by time, so only the index matters
+ if (wasOpen) showChat(c); else { chatStore.put(H.cleanChat(c)); renderSidebar(); }
+ }});
+}
+// rename: the row turns into a field; Enter or a click outside keeps the name, Escape gives it up
+function renameChat(row, c) {
+ const title = row.querySelector(".chat-item__title");
+ const input = node("input", "st-input chat-item__input");
+ input.value = H.chatTitle(c, untitled());
+ input.setAttribute("aria-label", tr("sidebar.nameFor", "Name for this chat"));
+ title.replaceWith(input);
+ input.focus(); input.select();
+ let done = false;
+ const finish = (keep) => {
+ if (done) return;
+ done = true;
+ if (keep) { c.title = input.value.trim(); chatStore.put(H.cleanChat(c)); }
+ renderSidebar();
+ };
+ input.addEventListener("keydown", (e) => {
+ if (e.key === "Enter") { e.preventDefault(); finish(true); }
+ else if (e.key === "Escape") { e.preventDefault(); finish(false); }
+ });
+ input.addEventListener("blur", () => finish(true));
+}
+function setSidebar(open, save) {
+ sidebarOpen = open;
+ $("sidebar").dataset.open = String(open);
+ const t = open ? tr("sidebar.collapse", "Collapse the chat list") : tr("sidebar.expand", "Open the chat list");
+ $("sidebar-toggle").title = t; $("sidebar-toggle").setAttribute("aria-label", t);
+ $("sidebar-toggle").setAttribute("aria-expanded", String(open));
+ if (save) store.set("sidebar", open);
+}
+
+// a chat that was branched from another says so, and links back while the original is still in the list
+function renderParent() {
+ const bar = $("chat-parent");
+ const p = listOn && chat ? chat.parent : null;
+ bar.hidden = !p;
+ if (!p) return;
+ const alive = chats.some((c) => c.id === p.id);
+ bar.innerHTML = "";
+ bar.appendChild(node("span", "muted", tr("branch.from", "Branched from “{title}”", {title: p.title})));
+ if (alive) {
+ const b = node("button", "st-btn st-btn--secondary", tr("branch.open", "Open the original"));
+ b.type = "button";
+ b.onclick = () => openChat(p.id);
+ bar.appendChild(b);
+ }
+}
+
+// ------------------------------------------------------------------ edit, regenerate, go back (#2615, #3823)
+// Every change keeps the messages it replaced for one Undo: a new question, another chat or a reload ends it. The controls
+// are off while an answer is written (stop it first), while something is open, and while a message waits to be sent.
+const historyLocked = () => !!busy || !!panel || !!pending;
+function clearUndo() { undoState = null; renderUndoBar(); }
+function renderUndoBar() {
+ let el = $("history-undo");
+ if (!settings.chatEdit || !undoState) { if (el) el.remove(); return; }
+ if (!el) {
+ el = node("div", "history-undo");
+ el.id = "history-undo";
+ el.setAttribute("role", "status");
+ el.innerHTML = "<span></span><button type=\"button\" class=\"st-btn st-btn--secondary\"></button>";
+ el.querySelector("button").onclick = undoHistory;
+ $("composer").before(el);
+ }
+ el.querySelector("span").textContent = undoState.text;
+ el.querySelector("button").textContent = tr("undo", "Undo");
+ el.querySelector("button").disabled = historyLocked();
+}
+// replace the messages with `next`; text says what happened, for the Undo bar
+function commit(next, text) {
+ undoState = {messages, text, inserted: undefined, draftBefore: null};
+ setMessages(next);
+ saveChat();
+ renderChat();
+ return undoState;
+}
+function undoHistory() {
+ if (!settings.chatEdit || !undoState || historyLocked()) return false;
+ const u = undoState;
+ setMessages(u.messages);
+ if (u.inserted !== undefined && $("input").value === u.inserted && u.draftBefore) { // the box still holds what the rewind put there
+ $("input").value = u.draftBefore.text;
+ attachments = u.draftBefore.attachments;
+ renderAttachments(); autosize();
+ }
+ undoState = null;
+ saveChat();
+ renderChat();
+ $("input").focus();
+ return true;
+}
+const hiddenText = (n) => tr("hist.hidden", {one: "{n} message hidden", other: "{n} messages hidden"}, {n});
+
+function msgActions(m, i) {
+ if (!settings.chatEdit) return null;
+ if (busy && busy.msg === m) return null; // the answer being written has no buttons until it is done
+ const row = node("div", "history-actions");
+ const lock = historyLocked();
+ const add = (label, title, run) => {
+ const b = node("button", "st-btn st-btn--secondary", label);
+ b.type = "button"; b.title = title; b.disabled = lock; b.onclick = run;
+ row.appendChild(b);
+ };
+ const last = i === messages.length - 1;
+ if (m.role === "assistant" || last) {
+ add(tr("hist.regenerate", "Regenerate"), tr("hist.regenerateTitle", "Ask for a new answer to this question. Tools may run again."), () => regenerateAt(i));
+ }
+ if (m.role === "assistant") add(tr("hist.editAnswer", "Edit answer"), tr("hist.editAnswerTitle", "Correct the answer's text. No request is sent."), () => editAnswerAt(i));
+ add(tr("hist.rewind", "Rewind to here"), tr("hist.rewindTitle", "Go back to this point in the chat"), () => openRewind(i));
+ return row;
+}
+// true when a history change may start now (and says why not when it may not)
+function historyReady() {
+ if (!settings.chatEdit) return false;
+ if (busy) { stillWriting(); return false; }
+ if (panel) { toast("warn", tr("hist.finishFirst", "Finish what is open first"), tr("hist.finishFirstText", "Save it or press Cancel.")); return false; }
+ if (pending) { toast("warn", tr("hist.pendingFirst", "A message is waiting"), tr("hist.pendingFirstText", "Send it or take it back first.")); return false; }
+ return true;
+}
+// the action rows under the messages follow the switch, without replacing any message (an answer may be streaming into one)
+function syncActions() {
+ for (const el of $("chat").querySelectorAll(".st-msg")) {
+ const i = +el.dataset.i;
+ const old = el.querySelector(".history-actions");
+ if (old) old.remove();
+ const row = messages[i] ? msgActions(messages[i], i) : null;
+ if (row) el.appendChild(row);
+ }
+}
+function closePanel() {
+ if (!panel) return;
+ const {el} = panel;
+ const open = el.querySelector(".history-panel, .history-editor");
+ if (open) open.remove();
+ delete el.dataset.editing;
+ panel = null;
+ setBusy(!!busy);
+}
+function regenerateAt(i) {
+ if (!historyReady()) return false;
+ const plan = H.regenerate(messages, i);
+ if (!plan) return false;
+ if (H.lostAttachments(messages[plan.keep.length - 1])) {
+ toast("warn", tr("hist.lostTitle", "Attachments need to be added again"), tr("hist.lostText", "This browser kept their names, not their contents. Start a new chat and attach them again."), 7000);
+ return false;
+ }
+ commit(plan.keep, tr("hist.replaced", "The answer was replaced"));
+ return generateReply();
+}
+
+// edit an answer: its text, in place. The old thinking and tool calls go, and so do the messages after it.
+function editAnswerAt(i) {
+ if (!historyReady() || !messages[i]) return false;
+ const m = messages[i], el = $("chat").querySelector(`[data-i="${i}"]`);
+ const later = messages.length - i - 1;
+ const box = node("div", "history-editor");
+ box.innerHTML = "<label></label><textarea class=\"st-input\" rows=\"6\"></textarea><p class=\"muted small\"></p>" +
+ "<div class=\"history-editor__actions\"><button type=\"button\" class=\"st-btn st-btn--primary\" data-edit-save></button>" +
+ "<button type=\"button\" class=\"st-btn st-btn--secondary\" data-edit-cancel></button></div>";
+ const label = tr("hist.editLabel", "Edit the answer");
+ box.querySelector("label").textContent = label;
+ const input = box.querySelector("textarea");
+ input.setAttribute("aria-label", label);
+ input.value = m.text || "";
+ box.querySelector("p").textContent = (later ? tr("hist.editRemoves", {one: "Saving hides the {n} message after it. ", other: "Saving hides the {n} messages after it. "}, {n: later}) : "") +
+ tr("hist.editNote", "The answer's old thinking and tool calls are removed. No request is sent.");
+ const save = box.querySelector("[data-edit-save]");
+ save.textContent = tr("hist.save", "Save");
+ box.querySelector("[data-edit-cancel]").textContent = tr("cancel", "Cancel");
+ save.onclick = () => saveAnswerEdit(i, input.value);
+ box.querySelector("[data-edit-cancel]").onclick = closePanel;
+ input.onkeydown = (e) => {
+ if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); closePanel(); }
+ if (e.key === "Enter" && (e.ctrlKey || e.metaKey) && !e.isComposing) { e.preventDefault(); save.click(); }
+ };
+ el.dataset.editing = "true";
+ el.appendChild(box);
+ panel = {kind: "edit", index: i, el};
+ setBusy(!!busy);
+ input.focus();
+ input.scrollIntoView({block: "nearest"});
+ return true;
+}
+function saveAnswerEdit(i, text) {
+ if (busy || !panel || panel.kind !== "edit" || panel.index !== i) return false;
+ if (typeof text !== "string" || !text.trim()) { toast("warn", tr("hist.empty", "The answer is empty"), tr("hist.emptyText", "Write something before saving.")); return false; }
+ const plan = H.editAnswer(messages, i, text, tr("hist.edited", "Edited"));
+ if (!plan) return false;
+ closePanel();
+ commit(plan.keep, plan.hidden ? tr("hist.editedHidden", {one: "Answer edited, {n} message hidden", other: "Answer edited, {n} messages hidden"}, {n: plan.hidden})
+ : tr("hist.editedOnly", "Answer edited"));
+ return true;
+}
+
+// "Rewind to here" asks what to do (#3823): go back HERE (this chat, with an Undo) or BRANCH (a new chat, this one stays)
+function openRewind(i) {
+ if (!historyReady() || !messages[i]) return false;
+ const m = messages[i], el = $("chat").querySelector(`[data-i="${i}"]`);
+ const user = m.role === "user";
+ const box = node("div", "history-panel");
+ box.setAttribute("role", "group");
+ box.setAttribute("aria-label", tr("rewind.title", "Rewind to here"));
+ const choice = (label, text, run, primary) => {
+ const row = node("div", "history-choice");
+ const b = node("button", `st-btn ${primary ? "st-btn--primary" : "st-btn--secondary"}`, label);
+ b.type = "button"; b.onclick = run;
+ row.appendChild(b);
+ row.appendChild(node("span", "muted small", text));
+ box.appendChild(row);
+ };
+ choice(user ? tr("rewind.hereUser", "Edit and send again here") : tr("rewind.hereAnswer", "Continue from here"),
+ user ? tr("rewind.hereUserText", "Hides this message and the ones after it, and puts your message in the box below. Undo brings them back.")
+ : tr("rewind.hereAnswerText", "Hides the messages after this answer. Undo brings them back."),
+ () => rewindHere(i), true);
+ if (listOn) {
+ choice(tr("rewind.branch", "Branch from here"),
+ user ? tr("rewind.branchUserText", "Starts a new chat with the messages before this one, and puts your message in its box. This chat stays as it is.")
+ : tr("rewind.branchAnswerText", "Starts a new chat with the messages up to this answer. This chat stays as it is."),
+ () => branchHere(i), false);
+ } else {
+ box.appendChild(node("p", "muted small", tr("rewind.noList", "To start a new chat from here instead, turn on Saved chats in Chat settings.")));
+ }
+ const cancel = node("button", "st-btn st-btn--secondary", tr("cancel", "Cancel"));
+ cancel.type = "button"; cancel.onclick = closePanel;
+ box.appendChild(cancel);
+ box.onkeydown = (e) => { if (e.key === "Escape") { e.preventDefault(); closePanel(); } };
+ el.appendChild(box);
+ panel = {kind: "rewind", index: i, el};
+ setBusy(!!busy);
+ box.querySelector("button").focus();
+ box.scrollIntoView({block: "nearest"});
+ return true;
+}
+function fillBox(draft) {
+ $("input").value = draft.text;
+ attachments = [...draft.images, ...draft.files];
+ renderAttachments();
+ autosize();
+ if (draft.lost) toast("warn", tr("hist.lostTitle", "Attachments need to be added again"), tr("hist.lostText2", "This browser kept their names, not their contents. Attach them again."), 7000);
+}
+function rewindHere(i) {
+ if (!settings.chatEdit || busy || pending || !panel || panel.kind !== "rewind") return false; // called from the open panel
+ const plan = H.rewind(messages, i);
+ if (!plan) return false;
+ const draftBefore = {text: $("input").value, attachments: attachments.slice()};
+ closePanel();
+ const u = commit(plan.keep, plan.hidden ? hiddenText(plan.hidden) : tr("hist.nothingHidden", "Back at this message"));
+ if (plan.draft) { u.draftBefore = draftBefore; fillBox(plan.draft); u.inserted = $("input").value; }
+ $("input").focus();
+ return true;
+}
+function branchHere(i) {
+ if (!listOn || busy || pending || !panel || panel.kind !== "rewind") return false;
+ const plan = H.rewind(messages, i);
+ if (!plan) return false;
+ closePanel();
+ const prev = chatId;
+ const c = H.branch(chat, plan.keep, plan.keep.length, tr("branch.title", "Branch of {title}", {title: H.chatTitle(chat, untitled())}));
+ chats.push(c);
+ showChat(c);
+ if (plan.draft) fillBox(plan.draft);
+ $("input").focus();
+ toast("info", tr("branch.started", "Branch started"), tr("branch.startedText", "The chat you were in is unchanged, in the list on the left."), 8000,
+ {label: tr("branch.back", "Back to it"), run: () => openChat(prev)});
+ return true;
+}
+
+// ------------------------------------------------------------------ wiring (called once by app.js)
+function initChats() {
+ $("sidebar-toggle").onclick = () => setSidebar(!sidebarOpen, true);
+ $("sidebar-new").onclick = startChat;
+ $("sidebar-search").addEventListener("input", () => { sidebarQuery = $("sidebar-search").value; renderSidebar(); });
+ $("sidebar-list").addEventListener("click", (e) => {
+ // a click inside the rename field is caret placement, not a click on the row: the row's handler would open the chat,
+ // which re-renders the list and takes the field away mid-click
+ if (e.target.closest(".chat-item__input")) return;
+ const row = e.target.closest(".chat-item");
+ if (!row) return;
+ const c = chats.find((x) => x.id === row.dataset.id);
+ if (!c) return;
+ if (e.target.closest("[data-delete]")) { deleteChat(c); return; }
+ if (e.target.closest("[data-rename]")) { renameChat(row, c); return; }
+ openChat(c.id);
+ });
+ // a narrow screen starts with the list closed so the chat has room
+ setSidebar(store.get("sidebar", true) && !matchMedia("(max-width: 760px)").matches, false);
+}
diff --git a/serve/web/chatstore.js b/serve/web/chatstore.js
new file mode 100644
index 000000000..fc5b682d2
--- /dev/null
+++ b/serve/web/chatstore.js
@@ -0,0 +1,66 @@
+// serve/web/chatstore.js - the saved chats, kept in this browser (IndexedDB, database "strata", store "chats", one record per
+// chat). Ported from PR #1787 by Scotty-Hudson. A chat can be several megabytes and localStorage holds about 5 MB for the whole
+// page, so the chats live here and only small keys (which chat is open, the settings) stay in localStorage. Nothing goes to the
+// server: the server has no endpoint for chats and never sees a title.
+//
+// Where the browser will not keep it (a private window, a blocked or full store) the list lives in memory for the visit, and
+// onProblem(kind) tells the page once: "memory" (no store), "quota" (full), "failed" (a write the browser refused).
+"use strict";
+(function (root) {
+ function createChatStore({indexedDB: idb = root.indexedDB, onProblem = () => {}} = {}) {
+ let db = null, told = false;
+ const problem = (kind) => { if (!told) { told = true; onProblem(kind); } };
+
+ function open() {
+ return new Promise((resolve) => {
+ let r;
+ try { r = idb.open("strata", 1); } catch (e) { resolve(null); return; } // private mode: memory only
+ r.onupgradeneeded = () => {
+ const d = r.result;
+ if (!d.objectStoreNames.contains("chats")) d.createObjectStore("chats", {keyPath: "id"});
+ };
+ // a database already at version 1 does not run onupgradeneeded, so the store may not be there
+ r.onsuccess = () => resolve(r.result.objectStoreNames.contains("chats") ? r.result : null);
+ r.onerror = () => resolve(null);
+ r.onblocked = () => resolve(null); // another tab holds an older version of the database
+ });
+ }
+ // true when the store is there; false: memory only (and the page has been told)
+ async function start() {
+ db = await open();
+ if (!db) problem("memory");
+ return !!db;
+ }
+ function all() {
+ return new Promise((resolve) => {
+ if (!db) { resolve([]); return; }
+ // the result is on the request, not on the store: reading it at oncomplete gives nothing
+ const req = db.transaction("chats", "readonly").objectStore("chats").getAll();
+ req.onsuccess = () => resolve(req.result || []);
+ req.onerror = () => resolve([]);
+ req.transaction.onabort = () => resolve([]); // an aborted read fires abort, not error: do not hang
+ });
+ }
+ // a request that fails because the storage is full aborts the transaction, so it fires abort rather than error
+ function watch(t) {
+ const warn = () => problem(t.error && t.error.name === "QuotaExceededError" ? "quota" : "failed");
+ t.onerror = warn; t.onabort = warn;
+ }
+ function put(chat) { // one record per chat: not the whole list for one message
+ if (!db) return;
+ const t = db.transaction("chats", "readwrite");
+ t.objectStore("chats").put(chat);
+ watch(t);
+ }
+ function remove(id) {
+ if (!db) return;
+ const t = db.transaction("chats", "readwrite");
+ t.objectStore("chats").delete(id);
+ watch(t);
+ }
+ return {start, all, put, remove, get usable() { return !!db; }};
+ }
+ const api = {createChatStore};
+ root.StrataChatStore = api;
+ if (typeof module !== "undefined" && module.exports) module.exports = api;
+})(typeof globalThis !== "undefined" ? globalThis : this);
diff --git a/serve/web/history.js b/serve/web/history.js
new file mode 100644
index 000000000..8e5428d59
--- /dev/null
+++ b/serve/web/history.js
@@ -0,0 +1,90 @@
+// serve/web/history.js - what the chat history does to a list of messages. Pure functions: no page, no storage, no clock of
+// their own, so they can be tested alone (serve/test_web_history.js). app.js draws the controls and keeps the state.
+//
+// One design for five proposals (see docs/DETAILS.md, "The web page"):
+// #2615 (uppet) edit your question, correct an answer, regenerate, go back, undo
+// #1787 (Scotty-Hudson) saved chats in a list, kept in this browser (IndexedDB), renamed, deleted, searched
+// #3823 (xvcezrqpbxtpzblrt) "Rewind to here" asks: edit and send again HERE, or BRANCH into a new chat
+// #3550 / #4004 the header's Load / Unload; sending while an answer is being written (app.js)
+// A message list is an array of {role, text, time, images, files, reasoning, tools, meta, ...}; an attachment that was read
+// in this page has its contents (image url, file text), one that came back from the browser's store has its name only.
+"use strict";
+(function (root) {
+ const TITLE_MAX = 60;
+
+ const newChatId = (now, rnd) => `c${now.toString(36)}${Math.floor(rnd * 1e6).toString(36)}`;
+ function newChat(now = Date.now(), rnd = Math.random()) {
+ return {id: newChatId(now, rnd), title: "", time: now, messages: []};
+ }
+ // the name in the list: what the user called it, else the first line of their first question, else the caller's word for "new"
+ function chatTitle(c, untitled = "New chat") {
+ if (c.title) return c.title;
+ const first = (c.messages.find((m) => m.role === "user") || {}).text || "";
+ return first.split("\n")[0].trim().slice(0, TITLE_MAX) || untitled;
+ }
+
+ // pictures and files are kept as their names only: a data URL would fill the browser's storage
+ const cleanMessages = (list) => list.map((m) => ({...m, images: (m.images || []).map((i) => ({name: i.name})),
+ files: (m.files || []).map((f) => ({name: f.name}))}));
+ const cleanChat = (c) => ({...c, messages: cleanMessages(c.messages)});
+
+ // "today" | "yesterday" | "week" | "month" | "older", by calendar days back from now
+ function groupKey(t, now = Date.now()) {
+ const days = Math.floor((now - t) / 86400000);
+ if (!days) return "today";
+ if (days === 1) return "yesterday";
+ if (days <= 7) return "week";
+ if (days <= 30) return "month";
+ return "older";
+ }
+ // the list for a search box: titles and message text, newest first
+ function filterChats(chats, query, untitled) {
+ const q = String(query || "").trim().toLowerCase();
+ return chats.filter((c) => !q || chatTitle(c, untitled).toLowerCase().includes(q) ||
+ c.messages.some((m) => (m.text || "").toLowerCase().includes(q)))
+ .sort((a, b) => b.time - a.time);
+ }
+
+ // Can a user turn be sent again as it was? A picture or file that came back from the browser's store has only its name.
+ const lostAttachments = (m) => ((m.images || []).filter((x) => !x.url).length + (m.files || []).filter((x) => typeof x.text !== "string").length);
+ // what goes back into the message box when a user turn is edited: its text and the attachments that still have contents
+ function draftOf(m) {
+ return {text: m.text || "",
+ images: (m.images || []).filter((x) => x.url).map((x) => ({kind: "image", name: x.name, url: x.url})),
+ files: (m.files || []).filter((x) => typeof x.text === "string").map((x) => ({kind: "file", name: x.name, text: x.text})),
+ lost: lostAttachments(m)};
+ }
+
+ // "Rewind to here" on message i. A user turn goes back into the box and leaves the list; an answer stays and the list ends
+ // with it. {keep, draft, hidden}: the messages that stay, the draft for the box (null for an answer), how many are hidden.
+ function rewind(messages, i) {
+ const m = messages[i];
+ if (!m) return null;
+ if (m.role === "user") return {keep: messages.slice(0, i), draft: draftOf(m), hidden: messages.length - i};
+ return {keep: messages.slice(0, i + 1), draft: null, hidden: messages.length - i - 1};
+ }
+ // Regenerate the answer at i (or the last user turn): the list up to and including the user turn before it
+ function regenerate(messages, i) {
+ let u = i;
+ while (u >= 0 && messages[u] && messages[u].role !== "user") u--;
+ if (u < 0 || !messages[u]) return null;
+ return {keep: messages.slice(0, u + 1), hidden: messages.length - u - 1};
+ }
+ // Edit the answer at i: its text replaced, its thinking, tool calls, error and stats dropped, everything after it hidden
+ function editAnswer(messages, i, text, meta = "Edited") {
+ const m = messages[i];
+ if (!m || m.role !== "assistant") return null;
+ return {keep: [...messages.slice(0, i), {role: "assistant", text, time: m.time, meta}], hidden: messages.length - i - 1};
+ }
+ // A branch: a new chat that starts with a copy of the first `end` messages. The original is not touched. The title says
+ // where it came from and stays: the first question does not rename it (the first-message case of #3823).
+ function branch(chat, messages, end, title, now = Date.now(), rnd = Math.random()) {
+ const copy = JSON.parse(JSON.stringify(messages.slice(0, end)));
+ return {...newChat(now, rnd), title, parent: {id: chat.id, title: chatTitle(chat)}, messages: copy};
+ }
+
+ const api = {TITLE_MAX, newChat, chatTitle, cleanMessages, cleanChat, groupKey, filterChats, lostAttachments, draftOf, rewind,
+ regenerate, editAnswer, branch};
+ root.StrataHistory = api;
+ if (typeof module !== "undefined" && module.exports) module.exports = api;
+})(typeof globalThis !== "undefined" ? globalThis : this);
diff --git a/serve/web/index.html b/serve/web/index.html
index be6f6d365..0511153d1 100644
--- a/serve/web/index.html
+++ b/serve/web/index.html
@@ -41,36 +41,54 @@
<main>
<!-- ============================ Chat ============================ -->
<section class="view view--chat" id="view-chat" role="tabpanel" aria-labelledby="tab-btn-chat">
- <div class="chat-scroll" id="chat-scroll">
- <div class="chat" id="chat">
- <div class="chat-empty" id="chat-empty">
- <div class="chat-empty__title">Ask anything</div>
- <div class="chat-empty__sub" id="chat-empty-sub">The model runs on this PC. Nothing leaves it.</div>
- </div>
+ <!-- the chats kept in this browser (Chat settings > Chats): the open one is the chat on the right -->
+ <aside class="chat-sidebar" id="sidebar" data-open="true" aria-label="Chats" data-i18n-label="sidebar.title" hidden>
+ <div class="sidebar-head">
+ <button class="st-btn st-btn--icon" id="sidebar-toggle" type="button" title="Collapse the chat list" aria-label="Collapse the chat list" aria-expanded="true">
+ <svg class="st-icon"><use href="web/sprite.svg#i-chevron"/></svg></button>
+ <span class="card-title sidebar-title" data-i18n="sidebar.title">Chats</span>
+ <button class="st-btn st-btn--icon" id="sidebar-new" type="button" title="New chat" aria-label="New chat" data-i18n-title="chat.new" data-i18n-label="chat.new">
+ <svg class="st-icon"><use href="web/sprite.svg#i-new-chat"/></svg></button>
</div>
- </div>
- <div class="composer-wrap">
- <form class="st-composer" id="composer">
- <div class="attachments" id="attachments" hidden></div>
- <textarea id="input" rows="2" placeholder="Ask anything&hellip;" aria-label="Message"></textarea>
- <div class="st-composer__bar">
- <button type="button" class="st-btn st-btn--icon" id="attach-btn" title="Attach a text file (or drop it here)" aria-label="Attach a file">
- <svg class="st-icon"><use href="web/sprite.svg#i-attach"/></svg></button>
- <input type="file" id="file" multiple hidden>
- <button type="button" class="st-btn st-btn--icon" id="new-btn" title="New chat" aria-label="New chat">
- <svg class="st-icon"><use href="web/sprite.svg#i-new-chat"/></svg></button>
- <button type="button" class="st-btn st-btn--icon" id="export-btn" title="Save this chat as Markdown" aria-label="Save this chat">
- <svg class="st-icon"><use href="web/sprite.svg#i-download"/></svg></button>
- <button type="button" class="st-btn st-btn--icon" id="sampling-btn" title="Sampling and thinking" aria-label="Sampling and thinking">
- <svg class="st-icon"><use href="web/sprite.svg#i-settings"/></svg></button>
- <span class="spacer"></span>
- <span class="composer-hint" id="composer-hint"></span>
- <button type="button" class="st-btn st-btn--secondary" id="stop-btn" hidden>
- <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-stop"/></svg>Stop</button>
- <button type="submit" class="st-btn st-btn--primary st-btn--send" id="send-btn" aria-label="Send">
- <svg class="st-icon"><use href="web/sprite.svg#i-send"/></svg></button>
+ <input class="st-input sidebar-search" id="sidebar-search" type="search" placeholder="Search chats"
+ autocomplete="off" aria-label="Search chats" data-i18n-placeholder="sidebar.search" data-i18n-label="sidebar.search">
+ <div class="sidebar-list" id="sidebar-list"></div>
+ <p class="muted small sidebar-foot" id="sidebar-foot"></p>
+ </aside>
+ <div class="chat-main">
+ <div class="chat-parent" id="chat-parent" hidden></div>
+ <div class="chat-scroll" id="chat-scroll">
+ <div class="chat" id="chat">
+ <div class="chat-empty" id="chat-empty">
+ <div class="chat-empty__title" data-i18n="chat.empty">Ask anything</div>
+ <div class="chat-empty__sub" id="chat-empty-sub" data-i18n="chat.emptySub">The model runs on this PC. Nothing leaves it.</div>
+ </div>
</div>
- </form>
+ </div>
+ <div class="composer-wrap">
+ <form class="st-composer" id="composer">
+ <div class="attachments" id="attachments" hidden></div>
+ <textarea id="input" rows="2" placeholder="Ask anything&hellip;" aria-label="Message" data-i18n-placeholder="composer.placeholder" data-i18n-label="composer.message"></textarea>
+ <div class="st-composer__bar">
+ <button type="button" class="st-btn st-btn--icon" id="attach-btn" title="Attach a text file (or drop it here)" aria-label="Attach a file" data-i18n-label="composer.attach">
+ <svg class="st-icon"><use href="web/sprite.svg#i-attach"/></svg></button>
+ <input type="file" id="file" multiple hidden>
+ <button type="button" class="st-btn st-btn--icon" id="new-btn" title="New chat" aria-label="New chat" data-i18n-title="chat.new" data-i18n-label="chat.new">
+ <svg class="st-icon"><use href="web/sprite.svg#i-new-chat"/></svg></button>
+ <button type="button" class="st-btn st-btn--icon" id="export-btn" title="Save this chat as Markdown" aria-label="Save this chat" data-i18n-title="composer.save" data-i18n-label="composer.saveLabel">
+ <svg class="st-icon"><use href="web/sprite.svg#i-download"/></svg></button>
+ <button type="button" class="st-btn st-btn--secondary chat-settings-button" id="sampling-btn" title="Chat settings" aria-label="Chat settings" data-i18n-title="drawer.title" data-i18n-label="drawer.title">
+ <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-settings"/></svg>
+ <span class="chat-settings-label" data-i18n="drawer.title">Chat settings</span><span class="chat-settings-short" aria-hidden="true" data-i18n="drawer.short">Settings</span></button>
+ <span class="spacer"></span>
+ <span class="composer-hint" id="composer-hint"></span>
+ <button type="button" class="st-btn st-btn--secondary" id="stop-btn" hidden>
+ <svg class="st-icon st-icon--sm"><use href="web/sprite.svg#i-stop"/></svg><span data-i18n="composer.stop">Stop</span></button>
+ <button type="submit" class="st-btn st-btn--primary st-btn--send" id="send-btn" aria-label="Send" data-i18n-label="composer.send">
+ <svg class="st-icon"><use href="web/sprite.svg#i-send"/></svg></button>
+ </div>
+ </form>
+ </div>
</div>
</section>
@@ -216,23 +234,23 @@
</section>
</main>
-<!-- ============================ Sampling drawer ============================ -->
-<aside class="st-drawer" id="drawer" data-open="false" aria-label="Sampling and thinking" aria-hidden="true">
- <div class="st-drawer__head"><span class="card-title">Sampling</span>
- <button class="st-btn st-btn--icon" id="drawer-close" aria-label="Close">
+<!-- ============================ Chat settings drawer ============================ -->
+<aside class="st-drawer" id="drawer" data-open="false" aria-label="Chat settings" data-i18n-label="drawer.title" aria-hidden="true">
+ <div class="st-drawer__head"><span class="card-title" data-i18n="drawer.title">Chat settings</span>
+ <button class="st-btn st-btn--icon" id="drawer-close" aria-label="Close" data-i18n-label="close">
<svg class="st-icon"><use href="web/sprite.svg#i-chevron"/></svg></button></div>
<div class="st-drawer__body">
<div class="st-field">
- <label class="st-label" for="s-thinking">Thinking <output id="o-thinking"></output></label>
- <div class="seg" id="s-thinking" role="radiogroup" aria-label="Thinking">
- <button type="button" role="radio" data-v="none">Off</button><button type="button" role="radio" data-v="low">Low</button>
- <button type="button" role="radio" data-v="medium">Medium</button><button type="button" role="radio" data-v="high">High</button>
+ <label class="st-label" for="s-thinking"><span data-i18n="drawer.thinking">Thinking</span> <output id="o-thinking"></output></label>
+ <div class="seg" id="s-thinking" role="radiogroup" aria-label="Thinking" data-i18n-label="drawer.thinking">
+ <button type="button" role="radio" data-v="none" data-i18n="drawer.off">Off</button><button type="button" role="radio" data-v="low" data-i18n="drawer.low">Low</button>
+ <button type="button" role="radio" data-v="medium" data-i18n="drawer.medium">Medium</button><button type="button" role="radio" data-v="high" data-i18n="drawer.high">High</button>
</div>
</div>
<div class="st-field">
- <label class="st-label" for="s-temp">Temperature <output id="o-temp"></output></label>
+ <label class="st-label" for="s-temp"><span data-i18n="drawer.temperature">Temperature</span> <output id="o-temp"></output></label>
<input class="st-slider" type="range" id="s-temp" min="0" max="1.5" step="0.05">
- <span class="muted small">0 = always the most likely word (exact, repeatable)</span>
+ <span class="muted small" data-i18n="drawer.temperatureNote">0 = always the most likely word (exact, repeatable)</span>
</div>
<div class="st-field">
<label class="st-label" for="s-topp">Top-p <output id="o-topp"></output></label>
@@ -243,30 +261,49 @@
<input class="st-slider" type="range" id="s-topk" min="1" max="64" step="1">
</div>
<div class="st-field">
- <label class="st-label" for="s-max">Max tokens <output>empty = until done</output></label>
- <input class="st-input" id="s-max" type="number" min="1" step="1" placeholder="Until done">
+ <label class="st-label" for="s-max"><span data-i18n="drawer.maxTokens">Max tokens</span> <output data-i18n="drawer.maxTokensNote">empty = until done</output></label>
+ <input class="st-input" id="s-max" type="number" min="1" step="1" placeholder="Until done" data-i18n-placeholder="drawer.untilDone">
</div>
<div class="st-field">
- <label class="st-label" for="s-seed">Seed <output>empty = random</output></label>
- <input class="st-input" id="s-seed" type="number" min="1" step="1" placeholder="Random">
+ <label class="st-label" for="s-seed"><span data-i18n="drawer.seed">Seed</span> <output data-i18n="drawer.seedNote">empty = random</output></label>
+ <input class="st-input" id="s-seed" type="number" min="1" step="1" placeholder="Random" data-i18n-placeholder="drawer.random">
</div>
+ <div class="toggle-row"><span><span data-i18n="drawer.showThinking">Show thinking</span><br><span class="muted small" data-i18n="drawer.showThinkingNote">expanded while it streams</span></span>
+ <button class="st-toggle" id="s-show" role="switch" aria-checked="true" aria-label="Show thinking" data-i18n-label="drawer.showThinking"></button></div>
<div class="toggle-row"><span><span data-i18n="drawer.math">Render math</span><br><span class="muted small"
data-i18n="drawer.mathNote">draw equations in answers as formulas (works offline)</span></span>
<button class="st-toggle" id="s-math" role="switch" aria-checked="false" aria-label="Render math" data-i18n-label="drawer.math"></button></div>
- <div class="toggle-row"><span>Show thinking<br><span class="muted small">expanded while it streams</span></span>
- <button class="st-toggle" id="s-show" role="switch" aria-checked="true" aria-label="Show thinking"></button></div>
- <div class="toggle-row" id="mcp-row" hidden><span>Use tools from MCP servers<br><span class="muted small"
+ <div class="toggle-row" id="mcp-row" hidden><span><span data-i18n="drawer.mcp">Use tools from MCP servers</span><br><span class="muted small"
id="mcp-row-sub">the model may call them while it answers</span></span>
- <button class="st-toggle" id="s-mcp" role="switch" aria-checked="true" aria-label="Use tools from MCP servers"></button></div>
+ <button class="st-toggle" id="s-mcp" role="switch" aria-checked="true" aria-label="Use tools from MCP servers" data-i18n-label="drawer.mcp"></button></div>
<div class="toggle-row" id="esp-row" hidden><span>Experimental speed projection<br><span class="muted small">the
engine's control vector; off = the stock model. Switching reads the chat again once</span></span>
<button class="st-toggle" id="s-esp" role="switch" aria-checked="true" aria-label="Experimental speed projection"></button></div>
- <div class="toggle-row"><span>Use for other apps too<br><span class="muted small">omp and other API clients get
- these settings for anything they don't set themselves</span></span>
- <button class="st-toggle" id="s-share" role="switch" aria-checked="false" aria-label="Use for other apps too"></button></div>
+ <div class="toggle-row"><span><span data-i18n="drawer.share">Use for other apps too</span><br><span class="muted small" data-i18n="drawer.shareNote">omp and other API clients get
+ these settings for anything they do not set themselves</span></span>
+ <button class="st-toggle" id="s-share" role="switch" aria-checked="false" aria-label="Use for other apps too" data-i18n-label="drawer.share"></button></div>
+
+ <div class="drawer-group" role="group" aria-labelledby="g-chats">
+ <h3 class="drawer-group__title" id="g-chats" data-i18n="drawer.chats">Chats</h3>
+ <div class="toggle-row"><span><span data-i18n="drawer.list">Saved chats list</span><br><span class="muted small"
+ data-i18n="drawer.listNote">keeps every chat in a list on the left, in this browser only. Off: one chat, as before</span></span>
+ <button class="st-toggle" id="s-list" role="switch" aria-checked="false" aria-label="Saved chats list" data-i18n-label="drawer.list"></button></div>
+ <div class="toggle-row"><span><span data-i18n="drawer.edit">Edit and rewind messages</span><br><span class="muted small"
+ data-i18n="drawer.editNote">edit an answer, ask for a new one, or go back to an earlier message (with an Undo)</span></span>
+ <button class="st-toggle" id="s-edit" role="switch" aria-checked="false" aria-label="Edit and rewind messages" data-i18n-label="drawer.edit"></button></div>
+ <div class="st-field">
+ <label class="st-label" for="s-busy"><span data-i18n="drawer.busy">When you send while it is answering</span></label>
+ <div class="seg seg--3" id="s-busy" role="radiogroup" aria-label="When you send while it is answering" data-i18n-label="drawer.busy">
+ <button type="button" role="radio" data-v="wait" data-i18n="drawer.busyWait">Wait</button><button type="button" role="radio" data-v="queue" data-i18n="drawer.busyQueue">Send after</button>
+ <button type="button" role="radio" data-v="interject" data-i18n="drawer.busyInterject">Interrupt</button>
+ </div>
+ <span class="muted small" id="o-busy"></span>
+ </div>
+ </div>
+
<div class="drawer-actions">
- <button class="st-btn st-btn--secondary" id="s-reset" type="button">Reset</button>
- <button class="st-btn st-btn--primary" id="s-apply" type="button">Apply</button>
+ <button class="st-btn st-btn--secondary" id="s-reset" type="button" data-i18n="drawer.reset">Reset</button>
+ <button class="st-btn st-btn--primary" id="s-apply" type="button" data-i18n="drawer.apply">Apply</button>
</div>
</div>
</aside>
@@ -276,6 +313,9 @@
<script src="web/preview.js"></script>
<script src="web/math.js"></script>
<script src="web/math-adapter.js"></script>
+<script src="web/history.js"></script>
+<script src="web/chatstore.js"></script>
+<script src="web/chats-ui.js"></script>
<script src="web/app.js"></script>
</body>
</html>
diff --git a/serve/web/sprite.svg b/serve/web/sprite.svg
index 598f6234a..1298c13e5 100644
--- a/serve/web/sprite.svg
+++ b/serve/web/sprite.svg
@@ -21,6 +21,7 @@
<symbol id="i-check" viewBox="0 0 24 24" fill="none"><path d="M4.5 12.5L9.5 17.5L19.5 6.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></symbol>
<symbol id="i-trash" viewBox="0 0 24 24" fill="none"><path opacity="0.12" d="M5 6L6 19C6.08 20.1 7 21 8.1 21H15.9C17 21 17.92 20.1 18 19L19 6H5Z" fill="currentColor"></path><path d="M5 6L6 19C6.08 20.1 7 21 8.1 21H15.9C17 21 17.92 20.1 18 19L19 6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path><path d="M3 6H21" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path><path d="M9 6V4.5C9 3.672 9.672 3 10.5 3H13.5C14.328 3 15 3.672 15 4.5V6" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path><path d="M10 10.5V16.5M14 10.5V16.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></symbol>
<symbol id="i-new-chat" viewBox="0 0 24 24" fill="none"><path opacity="0.12" d="M21 11.5C21 16.194 16.971 20 12 20C10.8 20 9.65 19.78 8.6 19.37L4 20.5L5.2 16.8C3.83 15.34 3 13.5 3 11.5C3 6.806 7.029 3 12 3C16.971 3 21 6.806 21 11.5Z" fill="currentColor"></path><path d="M21 11.5C21 16.194 16.971 20 12 20C10.8 20 9.65 19.78 8.6 19.37L4 20.5L5.2 16.8C3.83 15.34 3 13.5 3 11.5C3 6.806 7.029 3 12 3C16.971 3 21 6.806 21 11.5Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path><path d="M12 8.5V14.5M9 11.5H15" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></symbol>
+<symbol id="i-edit" viewBox="0 0 24 24" fill="none"><path opacity="0.12" d="M17.66 6.34L19.07 7.75A2 2 0 0 1 19.07 10.57L7.5 22.14L3.86 22.97L4.69 19.33L16.26 7.76A2 2 0 0 1 17.66 6.34Z" fill="currentColor"></path><path d="M17.66 6.34L19.07 7.75A2 2 0 0 1 19.07 10.57L7.5 22.14L3.86 22.97L4.69 19.33L16.26 7.76A2 2 0 0 1 17.66 6.34Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path><path d="M14.83 9.17L16.24 10.58" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></symbol>
<symbol id="i-chevron" viewBox="0 0 24 24" fill="none"><path d="M6 9L12 15L18 9" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></symbol>
<symbol id="i-thinking" viewBox="0 0 24 24" fill="none"><path opacity="0.12" d="M12 2.5C8.41 2.5 5.5 5.41 5.5 9C5.5 11.3 6.7 13.3 8.5 14.5V16.5C8.5 17.05 8.95 17.5 9.5 17.5H14.5C15.05 17.5 15.5 17.05 15.5 16.5V14.5C17.3 13.3 18.5 11.3 18.5 9C18.5 5.41 15.59 2.5 12 2.5Z" fill="currentColor"></path><path d="M12 2.5C8.41 2.5 5.5 5.41 5.5 9C5.5 11.3 6.7 13.3 8.5 14.5V16.5C8.5 17.05 8.95 17.5 9.5 17.5H14.5C15.05 17.5 15.5 17.05 15.5 16.5V14.5C17.3 13.3 18.5 11.3 18.5 9C18.5 5.41 15.59 2.5 12 2.5Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path><path d="M9.5 20.5H14.5" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></symbol>
<symbol id="i-tool" viewBox="0 0 24 24" fill="none"><path opacity="0.12" d="M14.7 6.3A1 1 0 0 0 14.7 7.7L16.3 9.3A1 1 0 0 0 17.7 9.3L21.47 5.53A6 6 0 0 1 13.53 13.47L6.62 20.38A2.12 2.12 0 0 1 3.62 17.38L10.53 10.47A6 6 0 0 1 18.47 2.53L14.71 6.29Z" fill="currentColor"></path><path d="M14.7 6.3A1 1 0 0 0 14.7 7.7L16.3 9.3A1 1 0 0 0 17.7 9.3L21.47 5.53A6 6 0 0 1 13.53 13.47L6.62 20.38A2.12 2.12 0 0 1 3.62 17.38L10.53 10.47A6 6 0 0 1 18.47 2.53L14.71 6.29Z" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path></symbol>
diff --git a/tools/webtest/browser_test.mjs b/tools/webtest/browser_test.mjs
index 5949db2ec..9b2ec42fb 100644
--- a/tools/webtest/browser_test.mjs
+++ b/tools/webtest/browser_test.mjs
@@ -253,6 +253,354 @@ test("load/unload: the header fits a phone", async ({ browser, mock }) => {
}
});
+// ------------------------------------------------------------------------------------------------ chat history (#1787, #2615, #3823, #4004)
+const on = (extra = {}) => ({ sampling: { chatList: true, chatEdit: true, ...extra } });
+const texts = (page) => page.evaluate(() => messages.map((m) => m.role[0] + ":" + (m.text || "")));
+const sidebarTitles = (page) => page.$$eval(".chat-item__title", (e) => e.map((x) => x.textContent));
+const ask = async (page, text) => { await say(page, text); await idle(page); await sleep(80); };
+const requestTexts = (mock, n = -1) => mock.state.requests.at(n).messages.map((m) => m.role[0] + ":" + (typeof m.content === "string" ? m.content : m.content[0].text));
+const clickAction = async (page, i, label) => {
+ const handle = await page.evaluateHandle((n, text) => [...document.querySelector(`[data-i="${n}"] .history-actions`).querySelectorAll("button")].find((b) => b.textContent === text), i, label);
+ await handle.asElement().click();
+};
+const reset = (mock) => { mock.state.requests.length = 0; mock.state.aborted = 0; mock.state.completed = 0; mock.state.answers = 0; };
+const htest = (name, fn) => test(name, async (ctx) => { reset(ctx.mock); await fn(ctx); });
+// (a toast sits over the drawer's Apply button for a few seconds: clear it, as a person would wait for it)
+const openSettings = async (page) => { await page.click("#sampling-btn"); await page.waitForSelector('#drawer[data-open="true"]'); await sleep(320); await page.evaluate(() => document.querySelectorAll(".st-toast").forEach((t) => t.remove())); };
+
+htest("history: everything is off by default - the page is the page it was", async ({ browser, mock }) => {
+ reset(mock);
+ const page = await openPage(browser, mock);
+ assert.equal(await page.$eval("#sidebar", (e) => e.hidden), true, "no list");
+ assert.equal(await page.$eval("#new-btn", (e) => e.hidden), false, "the New chat button is there");
+ await ask(page, "hello");
+ assert.equal(await page.$$eval(".history-actions", (e) => e.length), 0, "no edit buttons");
+ assert.deepEqual(mock.state.requests[0].messages, [{ role: "user", content: "hello" }]);
+ assert.equal(Object.keys(mock.state.requests[0]).sort().join(), "messages,model,reasoning_effort,stream", "the request has no new field");
+ assert.equal(await page.evaluate(() => settings.whileBusy), "wait");
+ const dbs = await page.evaluate(async () => (indexedDB.databases ? (await indexedDB.databases()).map((d) => d.name) : []));
+ assert.ok(!dbs.includes("strata"), "the browser store is never opened while the list is off");
+ assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("strata.chat")).length), 2, "one chat in localStorage, as before");
+ // Enter while an answer is being written does nothing
+ await say(page, "#hold one");
+ await page.waitForFunction(() => busy !== null);
+ await page.type("#input", "second");
+ await page.keyboard.press("Enter");
+ await sleep(300);
+ assert.equal(await page.$eval("#input", (e) => e.value), "second", "the text stays in the box");
+ assert.equal(await page.$("#pending"), null);
+ assert.equal(await page.$eval("#send-btn", (b) => b.disabled), true);
+ assert.equal(mock.state.requests.length, 2);
+ await page.click("#stop-btn");
+ await idle(page);
+ await page.close();
+});
+
+htest("list: chats are kept, found, renamed, deleted with an Undo, and survive a reload", async ({ browser, mock }) => {
+ const page = await openPage(browser, mock, { seed: on() });
+ assert.equal(await page.$eval("#sidebar", (e) => e.hidden), false);
+ assert.equal(await page.$eval("#new-btn", (e) => e.hidden), true, "the list has its own New chat");
+ await ask(page, "alpha question");
+ await page.click("#sidebar-new");
+ await ask(page, "beta question");
+ assert.deepEqual((await sidebarTitles(page)).sort(), ["alpha question", "beta question"]);
+ assert.equal(await page.$$eval(".sidebar-group", (e) => e.map((x) => x.textContent).join()), "Today");
+ assert.equal(await page.$eval("#sidebar-foot", (e) => e.textContent), "2 chats · kept in this browser");
+ // search: titles and message text
+ await page.type("#sidebar-search", "alpha");
+ assert.deepEqual(await sidebarTitles(page), ["alpha question"]);
+ await page.$eval("#sidebar-search", (e) => { e.value = "Mock answer"; e.dispatchEvent(new Event("input")); });
+ assert.equal((await sidebarTitles(page)).length, 2, "the search reads the answers too");
+ await page.$eval("#sidebar-search", (e) => { e.value = ""; e.dispatchEvent(new Event("input")); });
+ // rename: Enter keeps, Escape gives up, a click inside the field does not end it
+ const row = async (title) => (await page.evaluateHandle((t) => [...document.querySelectorAll(".chat-item")].find((r) => r.querySelector(".chat-item__title") && r.querySelector(".chat-item__title").textContent === t), title)).asElement();
+ await (await row("alpha question")).hover();
+ await (await (await row("alpha question")).$("[data-rename]")).click();
+ await page.click(".chat-item__input"); // a click in the field
+ assert.ok(await page.$(".chat-item__input"), "the rename is still open");
+ await page.keyboard.down("Control"); await page.keyboard.press("a"); await page.keyboard.up("Control");
+ await page.keyboard.type("Garden plan");
+ await page.keyboard.press("Enter");
+ assert.ok((await sidebarTitles(page)).includes("Garden plan"));
+ // delete (not the open one), then Undo
+ await (await row("Garden plan")).hover();
+ await (await (await row("Garden plan")).$("[data-delete]")).click();
+ assert.deepEqual(await sidebarTitles(page), ["beta question"]);
+ await page.evaluate(() => { const b = document.querySelectorAll(".st-toast .st-btn"); b[b.length - 1].click(); });
+ await sleep(100);
+ assert.deepEqual((await sidebarTitles(page)).sort(), ["Garden plan", "beta question"], "the chat is back");
+ // a reload: both chats, the open one is the same, the answers are there
+ await page.reload({ waitUntil: "networkidle0" });
+ assert.deepEqual((await sidebarTitles(page)).sort(), ["Garden plan", "beta question"]);
+ assert.deepEqual(await texts(page), ["u:beta question", "a:Mock answer 2."]);
+ await (await row("Garden plan")).click();
+ assert.deepEqual(await texts(page), ["u:alpha question", "a:Mock answer 1."]);
+ assert.deepEqual(page.errors, []);
+ await page.close();
+});
+
+htest("list: switching it on keeps the chat on the screen; off keeps it as the single chat", async ({ browser, mock }) => {
+ const page = await openPage(browser, mock);
+ await ask(page, "before the list");
+ await openSettings(page);
+ await page.click("#s-list");
+ await page.click("#s-apply");
+ await page.waitForFunction(() => document.querySelectorAll(".chat-item").length === 1);
+ assert.deepEqual(await sidebarTitles(page), ["before the list"], "the chat on the screen is the first one in the list");
+ await page.click("#sidebar-new");
+ await openSettings(page);
+ await page.click("#s-list");
+ await page.click("#s-apply");
+ await page.waitForFunction(() => document.getElementById("sidebar").hidden);
+ assert.equal(await page.evaluate(() => JSON.parse(localStorage.getItem("strata.chat")).length), 0, "the empty chat you were in is the single chat now");
+ await page.close();
+});
+
+htest("rewind: edit and send again here, with an Undo that brings everything back", async ({ browser, mock }) => {
+ reset(mock);
+ const page = await openPage(browser, mock, { seed: on() });
+ await ask(page, "q1"); await ask(page, "q2");
+ await page.type("#input", "a draft");
+ await clickAction(page, 2, "Rewind to here");
+ assert.equal(await page.$$eval(".history-panel .st-btn", (e) => e.map((x) => x.textContent).join("|")), "Edit and send again here|Branch from here|Cancel");
+ assert.equal(await page.$eval("#send-btn", (b) => b.disabled), true, "nothing can be sent while the panel is open");
+ await page.$eval(".history-panel .st-btn--primary", (b) => b.click());
+ assert.deepEqual(await texts(page), ["u:q1", "a:Mock answer 1."]);
+ assert.equal(await page.$eval("#input", (e) => e.value), "q2", "the question is in the box");
+ assert.equal(await page.$eval("#history-undo span", (e) => e.textContent), "2 messages hidden");
+ await page.click("#history-undo button");
+ assert.deepEqual(await texts(page), ["u:q1", "a:Mock answer 1.", "u:q2", "a:Mock answer 2."]);
+ assert.equal(await page.$eval("#input", (e) => e.value), "a draft", "the draft that was in the box is back");
+ assert.equal(await page.$("#history-undo"), null);
+ // go back again, change the question, send: the request has only what is left, and the Undo is gone
+ await clickAction(page, 2, "Rewind to here");
+ await page.$eval(".history-panel .st-btn--primary", (b) => b.click());
+ await page.click("#input");
+ await page.keyboard.down("Control"); await page.keyboard.press("a"); await page.keyboard.up("Control");
+ await page.keyboard.type("q2 better");
+ await page.keyboard.press("Enter");
+ await idle(page);
+ assert.deepEqual(requestTexts(mock), ["u:q1", "a:Mock answer 1.", "u:q2 better"]);
+ assert.equal(await page.$("#history-undo"), null, "a new question ends the Undo");
+ await page.close();
+});
+
+htest("rewind: an answer - continue from here; the box is untouched", async ({ browser, mock }) => {
+ const page = await openPage(browser, mock, { seed: on() });
+ await ask(page, "q1"); await ask(page, "q2");
+ await page.type("#input", "keep me");
+ await clickAction(page, 1, "Rewind to here");
+ assert.equal(await page.$eval(".history-panel .st-btn--primary", (b) => b.textContent), "Continue from here");
+ await page.$eval(".history-panel .st-btn--primary", (b) => b.click());
+ assert.deepEqual(await texts(page), ["u:q1", "a:Mock answer 1."]);
+ assert.equal(await page.$eval("#input", (e) => e.value), "keep me");
+ await page.click("#history-undo button");
+ assert.equal((await texts(page)).length, 4);
+ await page.close();
+});
+
+htest("rewind: with the list off there is no branch, only a hint", async ({ browser, mock }) => {
+ const page = await openPage(browser, mock, { seed: { sampling: { chatEdit: true } } });
+ await ask(page, "q1");
+ await clickAction(page, 0, "Rewind to here");
+ assert.equal(await page.$$eval(".history-panel .st-btn", (e) => e.map((x) => x.textContent).join("|")), "Edit and send again here|Cancel");
+ assert.match(await page.$eval(".history-panel p", (e) => e.textContent), /turn on Saved chats/);
+ await page.keyboard.press("Escape");
+ assert.equal(await page.$(".history-panel"), null, "Escape closes it");
+ await page.close();
+});
+
+htest("branch: a new chat from here; the original stays; the title stays; a link back", async ({ browser, mock }) => {
+ const page = await openPage(browser, mock, { seed: on() });
+ await ask(page, "q1"); await ask(page, "q2");
+ await clickAction(page, 2, "Rewind to here");
+ await page.evaluate(() => [...document.querySelectorAll(".history-panel .st-btn")].find((b) => b.textContent === "Branch from here").click());
+ assert.deepEqual(await texts(page), ["u:q1", "a:Mock answer 1."]);
+ assert.equal(await page.$eval("#input", (e) => e.value), "q2");
+ assert.equal(await page.$eval("#chat-parent", (e) => e.textContent), "Branched from “q1”Open the original");
+ assert.deepEqual((await sidebarTitles(page)).sort(), ["Branch of q1", "q1"]);
+ await ask(page, "a new second question");
+ assert.deepEqual((await sidebarTitles(page)).sort(), ["Branch of q1", "q1"], "sending does not rename the branch");
+ await page.click("#chat-parent .st-btn");
+ assert.deepEqual(await texts(page), ["u:q1", "a:Mock answer 1.", "u:q2", "a:Mock answer 2."], "the original is untouched");
+ assert.equal(await page.$("#chat-parent:not([hidden])"), null);
+ // a branch at the very first message: an empty chat that keeps its name after the first send
+ await clickAction(page, 0, "Rewind to here");
+ await page.evaluate(() => [...document.querySelectorAll(".history-panel .st-btn")].find((b) => b.textContent === "Branch from here").click());
+ assert.deepEqual(await texts(page), []);
+ assert.equal(await page.$eval("#input", (e) => e.value), "q1");
+ await ask(page, "something else entirely");
+ assert.ok((await sidebarTitles(page)).filter((t) => t === "Branch of q1").length === 2, "both branches keep their names: " + (await sidebarTitles(page)));
+ await page.close();
+});
+
+htest("regenerate: a new answer to the same question; Undo brings the old one back", async ({ browser, mock }) => {
+ reset(mock);
+ const page = await openPage(browser, mock, { seed: on() });
+ await ask(page, "q1"); await ask(page, "q2");
+ await clickAction(page, 3, "Regenerate");
+ await idle(page);
+ assert.deepEqual(requestTexts(mock), ["u:q1", "a:Mock answer 1.", "u:q2"], "the old answer is not sent");
+ assert.deepEqual(await texts(page), ["u:q1", "a:Mock answer 1.", "u:q2", "a:Mock answer 3."]);
+ await page.click("#history-undo button");
+ assert.deepEqual(await texts(page), ["u:q1", "a:Mock answer 1.", "u:q2", "a:Mock answer 2."]);
+ await page.close();
+});
+
+htest("edit answer: the text is saved, thinking and tools go, later messages are hidden, no request", async ({ browser, mock }) => {
+ reset(mock);
+ const page = await openPage(browser, mock, { seed: on() });
+ await ask(page, "#think q1"); await ask(page, "q2");
+ const before = mock.state.requests.length;
+ await clickAction(page, 1, "Edit answer");
+ assert.match(await page.$eval(".history-editor p", (e) => e.textContent), /Saving hides the 2 messages after it\./);
+ await page.$eval(".history-editor textarea", (e) => { e.value = "The corrected answer"; });
+ await page.click("[data-edit-save]");
+ assert.deepEqual(await texts(page), ["u:#think q1", "a:The corrected answer"]);
+ assert.equal(mock.state.requests.length, before, "no request");
+ assert.equal(await page.evaluate(() => messages[1].reasoning), undefined, "the old thinking is gone");
+ assert.equal(await page.$eval("#history-undo span", (e) => e.textContent), "Answer edited, 2 messages hidden");
+ await ask(page, "q3");
+ assert.deepEqual(requestTexts(mock), ["u:#think q1", "a:The corrected answer", "u:q3"], "the corrected text is what the model reads");
+ await page.close();
+});
+
+htest("history: the buttons wait while an answer is written, and while something is open", async ({ browser, mock }) => {
+ const page = await openPage(browser, mock, { seed: on() });
+ await ask(page, "q1");
+ await say(page, "#hold q2");
+ await page.waitForFunction(() => busy !== null);
+ assert.equal(await page.$$eval(".history-actions button:not([disabled])", (e) => e.length), 0);
+ assert.equal(await page.$eval("#s-list", (e) => e.disabled), true, "the list switch waits too");
+ await page.click("#stop-btn");
+ await idle(page);
+ assert.ok((await page.$$eval(".history-actions button:not([disabled])", (e) => e.length)) > 0);
+ await clickAction(page, 1, "Edit answer");
+ assert.equal(await page.$$eval(".history-actions button:not([disabled])", (e) => e.length), 0, "while an editor is open");
+ await page.keyboard.press("Escape");
+ assert.equal(await page.$(".history-editor"), null);
+ await page.close();
+});
+
+htest("history: an attachment that was only kept by name is not sent as if it were whole", async ({ browser, mock }) => {
+ reset(mock);
+ const lost = [{ role: "user", text: "see file", time: 1, files: [{ name: "notes.txt" }], images: [] }, { role: "assistant", text: "ok", time: 2 }];
+ const page = await openPage(browser, mock, { seed: { ...on(), chat: lost, sampling: { chatEdit: true } } });
+ await clickAction(page, 1, "Regenerate");
+ await sleep(200);
+ assert.equal(mock.state.requests.length, 0, "no request with a missing file");
+ assert.match(await page.$eval(".st-toast__title", (e) => e.textContent), /Attachments need to be added again/);
+ await clickAction(page, 0, "Rewind to here");
+ await page.$eval(".history-panel .st-btn--primary", (b) => b.click());
+ assert.equal(await page.$eval("#input", (e) => e.value), "see file");
+ assert.equal(await page.$$eval("#attachments .chip", (e) => e.length), 0);
+ await page.close();
+});
+
+// ---- sending while an answer is written (#4004)
+htest("while answering - send after: the message waits and goes when the answer is done", async ({ browser, mock }) => {
+ reset(mock);
+ const page = await openPage(browser, mock, { seed: on({ whileBusy: "queue" }) });
+ await say(page, "#long first");
+ await page.waitForFunction(() => busy !== null);
+ assert.equal(await page.$eval("#send-btn", (b) => b.disabled), false);
+ assert.match(await page.$eval("#composer-hint", (e) => e.textContent), /sends when the answer is done/);
+ await say(page, "second");
+ assert.match(await page.$eval("#pending .pending__text", (e) => e.textContent), /Sends when this answer is done: “second”/);
+ assert.equal(await page.$eval("#input", (e) => e.value), "", "the box is empty: the message is parked");
+ await page.waitForFunction(() => messages.length === 4 && busy === null, { timeout: 20000 });
+ assert.equal(await page.$("#pending"), null);
+ assert.equal(mock.state.requests.length, 2);
+ assert.deepEqual(requestTexts(mock).map((t) => t.slice(0, 10)), ["u:#long fi", "a:This is ", "u:second"], "the first answer is whole, then the second question");
+ assert.equal(mock.state.aborted, 0, "nothing was cut");
+ await page.close();
+});
+
+htest("while answering - interrupt: the answer stops where it is and the message goes at once", async ({ browser, mock }) => {
+ reset(mock);
+ const page = await openPage(browser, mock, { seed: on({ whileBusy: "interject" }) });
+ await say(page, "#long first");
+ await page.waitForFunction(() => busy && busy.msg.text.length > 12);
+ await say(page, "actually, second");
+ await page.waitForFunction(() => messages.length === 4 && busy === null, { timeout: 20000 });
+ assert.equal(mock.state.aborted, 1, "the first stream was cut");
+ const got = await page.evaluate(() => messages.map((m) => ({ r: m.role, t: m.text, i: !!m.interrupted, meta: m.meta })));
+ assert.equal(got[1].i, true); assert.ok(got[1].t.length > 12 && got[1].t.length < 200, "what was written stays: " + got[1].t.length);
+ assert.match(got[1].meta, /nterrupted/);
+ assert.deepEqual(requestTexts(mock).map((t) => t.slice(0, 10)), ["u:#long fi", "a:This is ", "u:actually"], "the partial answer and the new message go to the model, in that order");
+ assert.equal(requestTexts(mock)[1], "a:" + got[1].t.trim() || true);
+ assert.equal(await page.$("#pending"), null);
+ assert.equal(await page.$eval(".st-msg--assistant .meta-text", (e) => /nterrupted/.test(e.textContent)), true);
+ await page.close();
+});
+
+htest("while answering - interrupt waits for a running tool, then stops", async ({ browser, mock }) => {
+ reset(mock);
+ // the mock engine here has an MCP server for the page to offer
+ const page = await openPage(browser, mock, { seed: on({ whileBusy: "interject" }) });
+ await say(page, "#tool find it");
+ await page.waitForFunction(() => busy && (busy.msg.tools || []).some((t) => t.state === "running"));
+ await say(page, "never mind, second");
+ assert.match(await page.$eval("#pending .pending__text", (e) => e.textContent), /Waiting for the tool to finish, then sending: “never mind, second”/);
+ assert.equal(await page.evaluate(() => busy.cut), false, "the tool is not killed");
+ await page.waitForFunction(() => messages.length === 4 && busy === null, { timeout: 20000 });
+ const tool = await page.evaluate(() => messages[1].tools[0]);
+ assert.equal(tool.state, "done"); assert.equal(tool.result, "The file says hello.", "the tool finished and its result is kept");
+ assert.equal(mock.state.aborted, 1);
+ assert.equal(requestTexts(mock).at(-1), "u:never mind, second");
+ await page.close();
+});
+
+htest("while answering - a waiting message can be taken back, or sent now", async ({ browser, mock }) => {
+ reset(mock);
+ const page = await openPage(browser, mock, { seed: on({ whileBusy: "queue" }) });
+ await say(page, "#hold one");
+ await page.waitForFunction(() => busy !== null);
+ await say(page, "later");
+ await page.click("[data-pending-back]");
+ assert.equal(await page.$eval("#input", (e) => e.value), "later", "back in the box");
+ assert.equal(await page.$("#pending"), null);
+ await page.$eval("#input", (e) => { e.value = ""; });
+ await say(page, "now");
+ await page.click("[data-pending-now]"); // queue -> interrupt
+ await page.waitForFunction(() => messages.length === 4 && busy === null || (busy && busy.msg.text === "Working on it" && messages.length === 4), { timeout: 20000 });
+ assert.equal(requestTexts(mock).at(-1), "u:now");
+ await page.click("#stop-btn").catch(() => {});
+ await page.close();
+});
+
+htest("while answering - Stop keeps a waiting message for you to decide", async ({ browser, mock }) => {
+ reset(mock);
+ const page = await openPage(browser, mock, { seed: on({ whileBusy: "queue" }) });
+ await say(page, "#hold one");
+ await page.waitForFunction(() => busy !== null);
+ await say(page, "later");
+ await page.click("#stop-btn");
+ await idle(page);
+ await sleep(300);
+ assert.equal(mock.state.requests.length, 1, "a stopped answer does not send the queued message by itself");
+ assert.match(await page.$eval("#pending .pending__text", (e) => e.textContent), /Not sent yet: “later”/);
+ await page.click("[data-pending-now]");
+ await idle(page);
+ await page.waitForFunction(() => messages.length === 4);
+ assert.equal(requestTexts(mock).at(-1), "u:later");
+ await page.close();
+});
+
+htest("history: another chat or New chat does not lose a waiting message", async ({ browser, mock }) => {
+ const page = await openPage(browser, mock, { seed: on({ whileBusy: "queue" }) });
+ await ask(page, "first chat");
+ await say(page, "#hold running");
+ await page.waitForFunction(() => busy !== null);
+ await say(page, "parked");
+ await page.click("#stop-btn");
+ await idle(page);
+ await page.click("#sidebar-new");
+ assert.equal(await page.$eval("#input", (e) => e.value), "parked", "back in the box");
+ assert.equal(await page.$("#pending"), null);
+ await page.close();
+});
+
const mock = await startMock();
const browser = await launch();
await run(async () => ({ browser, mock, close: async () => { await browser.close(); await mock.stop(); } }));
diff --git a/tools/webtest/shots.mjs b/tools/webtest/shots.mjs
new file mode 100644
index 000000000..5c00ca8e6
--- /dev/null
+++ b/tools/webtest/shots.mjs
@@ -0,0 +1,142 @@
+// Screenshots of the served web page (serve/web) in its new states, against the mock server (no model):
+// WEBTEST_MODULES=<folder with node_modules/puppeteer-core> node tools/webtest/shots.mjs <out folder> [name-substring]
+import { startMock } from "./mock.mjs";
+import { launch, openPage, say, idle, sleep, shot } from "./lib.mjs";
+
+const out = process.argv[2] || "shots";
+const only = process.argv[3];
+const mock = await startMock();
+const browser = await launch();
+const turn = (role, text, extra = {}) => ({ role, text, time: Date.now(), ...extra });
+const fence = (lang, code) => "```" + lang + "\n" + code + "\n```\n";
+const on = (extra = {}) => ({ sampling: { chatList: true, chatEdit: true, ...extra } });
+const day = 86400000;
+
+const LONG = "Here is a short plan.\n\n1. Read the notes the user attached.\n2. Write the summary in plain words.\n3. List the open questions.\n\n" +
+ "The summary is **short** on purpose: three sentences, no jargon, and one next step.\n\n| Step | Who | When |\n|---|---|---|\n| Read | You | Today |\n| Summary | Me | Now |\n";
+const CHAT = [turn("user", "Can you plan how to summarise my notes?"), turn("assistant", LONG, { meta: "212 tokens · 41.3 tok/s" }),
+ turn("user", "Make it shorter, please."), turn("assistant", "Sure. Read the notes, write three sentences, list what is still open.", { meta: "24 tokens · 40.8 tok/s" })];
+
+// the saved-chats list with chats from different days (put into the page's own store, then the page is reloaded)
+async function seedChats(page) {
+ await page.evaluate(async (base, d) => {
+ const mk = (id, title, days, text) => ({ id, title, time: Date.now() - days * d, messages: [{ role: "user", text, time: 1 }, { role: "assistant", text: "Sure.", time: 2 }] });
+ for (const c of [mk("s1", "", 0.1, "Plan my week"), mk("s2", "Garden plan", 0.2, "Which tomatoes grow in shade?"), mk("s3", "", 1.5, "Translate this letter"),
+ mk("s4", "Branch of Recipe ideas", 3, "Recipe ideas"), mk("s5", "", 12, "Explain compound interest"), mk("s6", "", 50, "Old question about the printer")]) {
+ chatStore.put(StrataHistory.cleanChat(c));
+ }
+ }, null, day);
+ await sleep(300);
+ await page.reload({ waitUntil: "networkidle0" });
+}
+
+const shots = [
+ ["01-wide-window", async () => {
+ const p = await openPage(browser, mock, { width: 2560, height: 1300, seed: { chat: CHAT, ...on() } });
+ await seedChats(p);
+ return p;
+ }],
+ ["02-saved-chats-list", async () => {
+ const p = await openPage(browser, mock, { width: 1280, height: 800, seed: { chat: CHAT, ...on() } });
+ await seedChats(p);
+ return p;
+ }],
+ ["03-rewind-choice", async () => {
+ const p = await openPage(browser, mock, { width: 1280, height: 800, seed: { chat: CHAT, ...on() } });
+ await p.evaluate(() => { const i = 2; openRewind(i); });
+ await sleep(200);
+ return p;
+ }],
+ ["04-undo-bar", async () => {
+ const p = await openPage(browser, mock, { width: 1280, height: 800, seed: { chat: CHAT, ...on() } });
+ await p.evaluate(() => { openRewind(2); });
+ await p.$eval(".history-panel .st-btn--primary", (b) => b.click());
+ await sleep(200);
+ return p;
+ }],
+ ["05-edit-answer", async () => {
+ const p = await openPage(browser, mock, { width: 1280, height: 800, seed: { chat: CHAT, ...on() } });
+ await p.evaluate(() => { editAnswerAt(3); });
+ await sleep(200);
+ return p;
+ }],
+ ["06-branch-from-here", async () => {
+ const p = await openPage(browser, mock, { width: 1280, height: 800, seed: { chat: CHAT, ...on() } });
+ await p.evaluate(() => { openRewind(2); });
+ await p.evaluate(() => [...document.querySelectorAll(".history-panel .st-btn")].find((b) => b.textContent === "Branch from here").click());
+ await sleep(300);
+ return p;
+ }],
+ ["07-math", async () => {
+ const p = await openPage(browser, mock, { width: 1100, height: 760, seed: { sampling: { math: true } } });
+ await say(p, "#math show me"); await idle(p); await sleep(900);
+ return p;
+ }],
+ ["08-math-dark", async () => {
+ const p = await openPage(browser, mock, { width: 1100, height: 760, dark: true, seed: { sampling: { math: true } } });
+ await say(p, "#math show me"); await idle(p); await sleep(900);
+ return p;
+ }],
+ ["09-svg-preview", async () => {
+ const p = await openPage(browser, mock, { width: 1100, height: 760 });
+ await say(p, "#svg draw a circle"); await idle(p); await sleep(200);
+ await p.click("[data-preview-toggle]"); await sleep(400);
+ return p;
+ }],
+ ["10-html-preview-and-scripts", async () => {
+ const p = await openPage(browser, mock, { width: 1100, height: 760 });
+ await say(p, "#html make a page"); await idle(p); await sleep(200);
+ await p.click("[data-preview-toggle]"); await sleep(300);
+ await p.click("[data-preview-scripts]"); await sleep(500);
+ return p;
+ }],
+ ["11-narrow-chat", async () => {
+ const p = await openPage(browser, mock, { width: 390, height: 780, seed: { chat: CHAT, ...on() } });
+ await sleep(200);
+ return p;
+ }],
+ ["12-narrow-saved-chats-open", async () => {
+ const p = await openPage(browser, mock, { width: 390, height: 780, seed: { chat: CHAT, ...on() } });
+ await seedChats(p);
+ await p.click("#sidebar-toggle"); await sleep(300);
+ return p;
+ }],
+ ["13-narrow-header-320", async () => openPage(browser, mock, { width: 320, height: 640, seed: { chat: CHAT } })],
+ ["14-chat-settings", async () => {
+ const p = await openPage(browser, mock, { width: 1280, height: 900, seed: { chat: CHAT } });
+ await p.click("#sampling-btn"); await sleep(500);
+ await p.$eval(".st-drawer__body", (e) => { e.scrollTop = e.scrollHeight; });
+ await sleep(200);
+ return p;
+ }],
+ ["15-send-while-answering", async () => {
+ const p = await openPage(browser, mock, { width: 1100, height: 760, seed: on({ whileBusy: "queue" }) });
+ await say(p, "#hold start a long answer");
+ await p.waitForFunction(() => busy !== null);
+ await sleep(500);
+ await say(p, "And then summarise it for me");
+ await sleep(300);
+ return p;
+ }],
+ ["16-load-unload", async () => {
+ mock.state.loaded = false;
+ const p = await openPage(browser, mock, { width: 1100, height: 520 });
+ await sleep(1500);
+ return p;
+ }],
+ ["17-narrow-wide-mid-900", async () => openPage(browser, mock, { width: 900, height: 700, seed: { chat: CHAT, ...on() } })],
+];
+
+try {
+ for (const [name, make] of shots) {
+ if (only && !name.includes(only)) continue;
+ mock.state.loaded = true;
+ const page = await make();
+ await sleep(300);
+ console.log(await shot(page, out, name), page.errors.length ? "ERRORS " + page.errors.join(" | ") : "");
+ await page.close();
+ }
+} finally {
+ await browser.close();
+ await mock.stop();
+}