okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-027-web: the served web chat page for 0.2.75d9f47922

main
12.1 KiB222 linesraw
1// The chat history's logic (serve/web/history.js) and the browser store behind the saved-chats list (serve/web/chatstore.js),
2// 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
3// is on the request and not on the store; a write the browser refuses fires abort on the transaction; a blocked open never
4// resolves by itself; a database already at version 1 does not run onupgradeneeded; requests answer on a later tick.
5// (The stub and its cases are from PR #1787 by Scotty-Hudson, rebuilt for the split modules.)
6//   node serve/test_web_history.js      (serve/test_web_history.py runs it too and skips when node is missing)
7"use strict";
8const assert = require("node:assert/strict");
9const path = require("node:path");
10const H = require(path.join(__dirname, "web", "history.js"));
11const {createChatStore} = require(path.join(__dirname, "web", "chatstore.js"));
12
13const user = (text, extra = {}) => ({role: "user", text, time: 1, ...extra});
14const bot = (text, extra = {}) => ({role: "assistant", text, time: 2, ...extra});
15const tool = {id: "t1", name: "fs__read", result: "secret result", state: "done", round: 0, at: 0};
16const convo = () => [user("q1", {images: [{kind: "image", name: "a.png", url: "data:image/png;base64,AAA"}], files: [{kind: "file", name: "n.txt", text: "notes"}]}),
17                     bot("a1", {reasoning: "thoughts", tools: [tool], meta: "12 tokens", stopped: true, error: "x"}), user("q2"), bot("a2")];
18
19const cases = {
20  titles_and_groups() {
21    assert.equal(H.chatTitle({title: "Mine", messages: []}), "Mine");
22    assert.equal(H.chatTitle({title: "", messages: [user("  first line\nsecond")]}), "first line");
23    assert.equal(H.chatTitle({title: "", messages: [user("x".repeat(100))]}).length, H.TITLE_MAX);
24    assert.equal(H.chatTitle({title: "", messages: []}), "New chat");
25    assert.equal(H.chatTitle({title: "", messages: []}, "Neuer Chat"), "Neuer Chat", "the caller's word for an unnamed chat");
26    const now = Date.UTC(2026, 9, 26, 12), day = 86400000;
27    const keys = [0, 0.4, 1.5, 5, 20, 40].map((d) => H.groupKey(now - d * day, now));
28    assert.deepEqual(keys, ["today", "today", "yesterday", "week", "month", "older"]);
29    const a = H.newChat(1, 0.5), b = H.newChat(2, 0.5);
30    assert.notEqual(a.id, b.id); assert.deepEqual(a.messages, []);
31  },
32  filter_searches_titles_and_text() {
33    const chats = [{id: "a", title: "the garden", time: 3, messages: [user("watering the tomatoes")]},
34                   {id: "b", title: "a chat about code", time: 2, messages: [user("nothing here")]},
35                   {id: "c", title: "tomatoes again", time: 1, messages: [user("a different question")]}];
36    assert.deepEqual(H.filterChats(chats, "").map((c) => c.id), ["a", "b", "c"], "newest first");
37    assert.deepEqual(H.filterChats(chats, " TOMATOES ").map((c) => c.id), ["a", "c"], "title or text, any case");
38    assert.deepEqual(H.filterChats(chats, "nothing here").map((c) => c.id), ["b"]);
39    assert.deepEqual(H.filterChats(chats, "zzz"), []);
40    assert.deepEqual(chats.map((c) => c.id), ["a", "b", "c"], "the caller's list is not reordered");
41  },
42  clean_keeps_names_only() {
43    const clean = H.cleanMessages(convo());
44    assert.deepEqual(clean[0].images, [{name: "a.png"}]);
45    assert.deepEqual(clean[0].files, [{name: "n.txt"}]);
46    assert.ok(!JSON.stringify(clean).includes("data:image") && !JSON.stringify(clean).includes("notes"), "no contents in the browser's store");
47    assert.equal(clean[1].text, "a1", "the text stays");
48    assert.deepEqual(convo()[0].files, [{kind: "file", name: "n.txt", text: "notes"}], "a copy: the screen keeps its contents");
49  },
50  rewind_a_question() {
51    const m = convo();
52    const plan = H.rewind(m, 2);
53    assert.deepEqual(plan.keep.map((x) => x.text), ["q1", "a1"]);
54    assert.equal(plan.hidden, 2, "the question and its answer");
55    assert.equal(plan.draft.text, "q2"); assert.equal(plan.draft.lost, 0);
56    const first = H.rewind(m, 0);
57    assert.deepEqual(first.keep, [], "the first question: nothing stays, the question goes to the box");
58    assert.equal(first.draft.text, "q1"); assert.equal(first.hidden, 4);
59    assert.deepEqual(first.draft.images, [{kind: "image", name: "a.png", url: "data:image/png;base64,AAA"}], "attachments with contents come back");
60    assert.deepEqual(first.draft.files, [{kind: "file", name: "n.txt", text: "notes"}]);
61    assert.equal(m.length, 4, "the list itself is not changed");
62  },
63  rewind_an_answer() {
64    const plan = H.rewind(convo(), 1);
65    assert.deepEqual(plan.keep.map((x) => x.text), ["q1", "a1"], "the answer stays and the list ends with it");
66    assert.equal(plan.draft, null); assert.equal(plan.hidden, 2);
67    assert.equal(H.rewind(convo(), 3).hidden, 0, "the last answer: nothing to hide");
68    assert.equal(H.rewind(convo(), 9), null);
69  },
70  lost_attachments_are_counted() {
71    const reloaded = H.cleanMessages(convo());
72    assert.equal(H.lostAttachments(reloaded[0]), 2);
73    assert.equal(H.lostAttachments(convo()[0]), 0);
74    const plan = H.rewind(reloaded, 0);
75    assert.equal(plan.draft.lost, 2); assert.deepEqual(plan.draft.images, []); assert.deepEqual(plan.draft.files, []);
76    assert.equal(plan.draft.text, "q1", "the text still comes back");
77  },
78  regenerate_from_the_question() {
79    const m = convo();
80    assert.deepEqual(H.regenerate(m, 1).keep.map((x) => x.text), ["q1"]);
81    assert.equal(H.regenerate(m, 1).hidden, 3);
82    assert.deepEqual(H.regenerate(m, 3).keep.map((x) => x.text), ["q1", "a1", "q2"]);
83    assert.deepEqual(H.regenerate(m, 2).keep.map((x) => x.text), ["q1", "a1", "q2"], "on the last question itself");
84    assert.equal(H.regenerate([bot("orphan")], 0), null, "no question before it");
85  },
86  edit_an_answer() {
87    const plan = H.editAnswer(convo(), 1, "corrected", "Edited");
88    assert.equal(plan.keep.length, 2); assert.equal(plan.hidden, 2);
89    const a = plan.keep[1];
90    assert.deepEqual(a, {role: "assistant", text: "corrected", time: 2, meta: "Edited"}, "no thinking, tools, error, stop mark or stats");
91    assert.equal(H.editAnswer(convo(), 0, "x"), null, "only an answer can be edited");
92  },
93  branch_is_a_copy_with_a_title_that_stays() {
94    const original = {id: "c1", title: "", time: 1, messages: convo()};
95    const plan = H.rewind(original.messages, 2);
96    const b = H.branch(original, plan.keep, plan.keep.length, "Branch of q1", 5, 0.25);
97    assert.deepEqual(b.messages.map((x) => x.text), ["q1", "a1"]);
98    assert.equal(b.title, "Branch of q1"); assert.deepEqual(b.parent, {id: "c1", title: "q1"});
99    assert.notEqual(b.id, "c1");
100    b.messages[0].text = "changed"; b.messages[1].tools[0].result = "changed";
101    assert.equal(original.messages[0].text, "q1", "the original is untouched");
102    assert.equal(original.messages[1].tools[0].result, "secret result");
103    assert.equal(H.chatTitle(H.branch(original, [], 0, "Branch of q1"), "x"), "Branch of q1", "a branch at the first message keeps its title");
104  },
105};
106
107// ---------------------------------------------------------------- the stub IndexedDB
108function makeIdb(hooks = {}, seed = {}) {
109  const data = Object.assign({}, seed), stores = {}, calls = {upgradeneeded: 0, createObjectStore: 0};
110  let current = null;
111  const request = () => ({result: null, error: null, transaction: current, onsuccess: null, onerror: null});
112  const store = {
113    put(value) {
114      const req = request();
115      queueMicrotask(() => {
116        if (hooks.quota) { req.error = {name: "QuotaExceededError"}; req.onerror && req.onerror(); return; }
117        if (hooks.abort) return;
118        data[value.id] = value; req.result = value; req.onsuccess && req.onsuccess();
119      });
120      return req;
121    },
122    delete(key) {
123      const req = request();
124      queueMicrotask(() => { if (hooks.quota || hooks.abort) return; delete data[key]; req.result = true; req.onsuccess && req.onsuccess(); });
125      return req;
126    },
127    getAll() {
128      const req = request();
129      queueMicrotask(() => { if (hooks.abort) return; req.result = Object.values(data); req.onsuccess && req.onsuccess(); });
130      return req;
131    },
132  };
133  const transaction = () => {
134    const t = {error: null, oncomplete: null, onerror: null, onabort: null, objectStore: () => store};
135    current = t;
136    queueMicrotask(() => {
137      if (hooks.quota || hooks.abort) { t.error = {name: hooks.quota ? "QuotaExceededError" : hooks.abort}; t.onabort && t.onabort(); }
138      else if (t.oncomplete) t.oncomplete();
139    });
140    return t;
141  };
142  const db = {objectStoreNames: {contains: (n) => n in stores}, createObjectStore: (n) => { calls.createObjectStore++; stores[n] = store; }, transaction};
143  return {open: () => {
144    if (hooks.throws) throw new Error("private mode");
145    const r = {result: db, error: null, onupgradeneeded: null, onsuccess: null, onerror: null, onblocked: null};
146    queueMicrotask(() => {
147      if (hooks.blocked) { r.onblocked && r.onblocked(); return; }
148      if (hooks.newDatabase !== false) { calls.upgradeneeded++; r.onupgradeneeded && r.onupgradeneeded(); }
149      r.result = db; r.onsuccess && r.onsuccess();
150    });
151    return r;
152  }, records: data, calls};
153}
154const wait = () => new Promise((r) => setTimeout(r, 10));
155const mk = (hooks, seed) => {
156  const idb = makeIdb(hooks, seed), problems = [];
157  return {idb, problems, store: createChatStore({indexedDB: idb, onProblem: (k) => problems.push(k)})};
158};
159const chat = (id, extra = {}) => ({id, title: id, time: 1, messages: [user("hi " + id)], ...extra});
160
161Object.assign(cases, {
162  async store_fresh_database_creates_the_store_and_reads() {
163    const a = mk({}, {c0: chat("c0"), c1: chat("c1")});
164    assert.equal(await a.store.start(), true);
165    assert.equal(a.idb.calls.upgradeneeded, 1); assert.equal(a.idb.calls.createObjectStore, 1);
166    assert.deepEqual((await a.store.all()).map((c) => c.id).sort(), ["c0", "c1"], "the result is read from the request");
167    assert.deepEqual(a.problems, []);
168  },
169  async store_put_and_remove_touch_one_record() {
170    const a = mk({}, {c0: chat("c0")});
171    await a.store.start();
172    a.store.put(chat("c1", {title: "renamed"})); await wait();
173    assert.equal(a.idb.records.c1.title, "renamed"); assert.ok(a.idb.records.c0, "the other record is not rewritten");
174    a.store.remove("c0"); await wait();
175    assert.ok(!("c0" in a.idb.records));
176  },
177  async store_private_mode_is_memory_only_and_says_so_once() {
178    const a = mk({throws: true});
179    assert.equal(await a.store.start(), false);
180    assert.deepEqual(a.problems, ["memory"]);
181    assert.deepEqual(await a.store.all(), []);
182    a.store.put(chat("x")); a.store.remove("x");          // no store: nothing to do, nothing thrown
183    await a.store.start();
184    assert.deepEqual(a.problems, ["memory"], "told once, not on every try");
185  },
186  async store_missing_object_store_is_memory_only() {
187    const a = mk({newDatabase: false});                  // a database already at version 1: no upgrade, no store
188    assert.equal(await a.store.start(), false);
189    assert.equal(a.idb.calls.createObjectStore, 0);
190    assert.deepEqual(a.problems, ["memory"]);
191  },
192  async store_blocked_open_does_not_hang() {
193    const a = mk({blocked: true});
194    assert.equal(await a.store.start(), false);
195    assert.deepEqual(a.problems, ["memory"]);
196  },
197  async store_full_storage_warns_once_with_its_own_message() {
198    const a = mk({quota: true});
199    await a.store.start();
200    a.store.put(chat("big")); await wait();
201    a.store.put(chat("big2")); await wait();
202    assert.deepEqual(a.problems, ["quota"], "one warning, the quota one");
203  },
204  async store_another_failure_is_not_called_quota() {
205    const a = mk({abort: "DataError"});
206    await a.store.start();
207    a.store.put(chat("bad")); await wait();
208    assert.deepEqual(a.problems, ["failed"]);
209  },
210  async store_a_read_that_aborts_answers_empty() {
211    const a = mk({abort: "DataError"}, {c0: chat("c0")});
212    await a.store.start();
213    assert.deepEqual(await a.store.all(), [], "no hang, no records");
214  },
215});
216
217(async () => {
218  const name = process.argv[2];
219  const run = name ? [[name, cases[name]]] : Object.entries(cases);
220  if (name && !cases[name]) throw new Error("unknown test " + name);
221  for (const [n, fn] of run) { await fn(); console.log("ok " + n); }
222})().catch((e) => { console.error(e); process.exitCode = 1; });