okami.mom/strata

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

Niko1221Merge f-0213-guidata (final 1d5096beb) into f-0213-int85269ca15

main
21.6 KiB367 linesraw
1/**
2 * #3604 / #3603: the chat list is saved at most once a second and only the chats that changed are sent.
3 * #5192: nothing is ever cut out of a saved chat. Chats are files on the host (owner decision 11-04): big chats, restart, the move from the
4 * browser's two old layouts, a full disk, a host that is away, two windows.
5 */
6import test from 'node:test';
7import assert from 'node:assert/strict';
8import { build } from 'esbuild';
9import { fileURLToPath } from 'node:url';
10import { mkdtempSync, rmSync } from 'node:fs';
11import { tmpdir } from 'node:os';
12import { join } from 'node:path';
13import { createChatStore, realIo } from '../server/chat-store.mjs';
14import { storeTransport, installFakeHostFetch } from './helpers/fake-host-chats.mjs';
15
16const here = (p) => fileURLToPath(new URL(p, import.meta.url));
17
18async function bundle(entry, plugins = []) {
19  const result = await build({
20    entryPoints: [here(entry)], bundle: true, format: 'esm', platform: 'node', write: false, logLevel: 'silent',
21    alias: { react: here('./helpers/react-stub.mjs') }, loader: { '.json': 'json' }, plugins,
22  });
23  return import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`);
24}
25
26const persist = await bundle('../src/lib/session-persist.ts');
27const sync = await bundle('../src/lib/chat-sync.ts');
28const { createSessionWriter, serializeSession, readBrowserSessions, exportSessions, TransportError, LEGACY_SESSIONS_KEY, SESSION_INDEX_KEY, SESSION_KEY_PREFIX, HOST_FLAG_KEY, PENDING_KEY } = persist;
29const { hydrateChats, keepLastMomentCopy, takeLastMomentCopy } = sync;
30
31/** A Storage with a quota, like the browser's. */
32function fakeStorage(limit = Infinity) {
33  const map = new Map();
34  const used = () => [...map].reduce((n, [k, v]) => n + k.length + v.length, 0);
35  return {
36    map,
37    get length() { return map.size; },
38    key: (i) => [...map.keys()][i] ?? null,
39    getItem: (k) => (map.has(k) ? map.get(k) : null),
40    removeItem: (k) => { map.delete(k); },
41    setItem(k, v) {
42      const before = map.has(k) ? k.length + map.get(k).length : 0;
43      if (used() - before + k.length + String(v).length > limit) { const e = new Error('The quota has been exceeded.'); e.name = 'QuotaExceededError'; throw e; }
44      map.set(k, String(v));
45    },
46  };
47}
48const chat = (id, n, len, extra = {}) => ({
49  id, title: `Chat ${id}`, createdAt: `2026-11-0${(id.charCodeAt(0) % 8) + 1}`, updatedAt: id, workspace: 'C:/w', tokensIn: 0, tokensOut: 0,
50  messages: Array.from({ length: n }, (_, i) => ({ id: `${id}-m${i}`, role: i % 2 ? 'assistant' : 'user', content: `${id}:${i}:` + String.fromCharCode(97 + (i % 26)).repeat(len) })),
51  ...extra,
52});
53const host = (io = realIo) => {
54  const dir = mkdtempSync(join(tmpdir(), 'strata-persist-'));
55  const store = createChatStore({ dir, io });
56  const state = { offline: false };
57  const transport = storeTransport(store, TransportError, state);
58  return { dir, store, state, transport, reopen: () => createChatStore({ dir }), done: () => rmSync(dir, { recursive: true, force: true }) };
59};
60const writerOn = (h, opts = {}) => createSessionWriter({ transport: h.transport, ...opts });
61const saveAll = async (h, sessions, opts) => { const w = writerOn(h, opts); w.schedule(sessions); await w.flush(); return w; };
62const fromHost = async (h) => { const out = []; for (const e of h.reopen().list().chats) out.push(JSON.parse(await h.reopen().read(e.id)).session); return out; };
63
64test('2,000 schedules inside a second produce one save, and the newest state wins', async (t) => {
65  const h = host();
66  try {
67    t.mock.timers.enable({ apis: ['setTimeout'] });
68    let puts = 0;
69    const put = h.transport.put;
70    h.transport.put = (...a) => { puts++; return put(...a); };
71    const writer = writerOn(h, { delayMs: 1_000 });
72    for (let i = 0; i < 2_000; i++) writer.schedule([{ id: 's1', seq: i, messages: [] }]);
73    assert.equal(puts, 0, 'nothing is sent synchronously');
74    t.mock.timers.tick(1_000);
75    await writer.flush();
76    assert.equal(puts, 1);
77    assert.equal((await fromHost(h))[0].seq, 1_999);
78    writer.schedule([{ id: 's1', seq: 2_000, messages: [] }]);
79    await writer.flush();
80    assert.equal(puts, 2);
81    assert.equal((await fromHost(h))[0].seq, 2_000);
82    await writer.flush();
83    assert.equal(puts, 2, 'a flush with nothing pending sends nothing');
84  } finally { h.done(); }
85});
86
87test('only the chat that changed is serialised and sent again', async () => {
88  const h = host();
89  try {
90    const seen = [], sent = [];
91    const put = h.transport.put;
92    h.transport.put = (id, ...a) => { sent.push(id); return put(id, ...a); };
93    const writer = writerOn(h, { onSerialize: (s) => seen.push(s.id) });
94    const a = { id: 'a', updatedAt: '1', messages: [{ id: 'm', content: 'x'.repeat(1000) }] };
95    const b = { id: 'b', updatedAt: '2', messages: [] };
96    writer.schedule([a, b]); await writer.flush();
97    assert.deepEqual(seen.sort(), ['a', 'b']);
98    seen.length = 0; sent.length = 0;
99    for (let i = 0; i < 50; i++) { writer.schedule([a, { ...b, title: `t${i}` }]); await writer.flush(); }
100    assert.equal(seen.filter((id) => id === 'a').length, 0, 'the untouched chat is never stringified again');
101    assert.equal(sent.filter((id) => id === 'a').length, 0, 'the untouched chat is never sent again');
102    assert.equal(sent.filter((id) => id === 'b').length, 50);
103    assert.equal(h.reopen().list().chats.length, 2);
104  } finally { h.done(); }
105});
106
107/* #5192: the register's own numbers. Twelve messages of 140,000 characters went through the real serializer and six came back. */
108test('#5192: 12 messages of 140,000 characters are saved and restored whole, twice over (save, restart, save, restart)', async () => {
109  const h = host();
110  try {
111    const original = chat('s_a', 12, 140_000);
112    const before = JSON.stringify(original);
113    await saveAll(h, [original]);
114    const first = await hydrateChats({ transport: h.transport, browser: fakeStorage(), current: [] });
115    assert.equal(first.sessions.length, 1);
116    assert.equal(first.sessions[0].messages.length, 12, 'all twelve messages come back');
117    assert.equal(JSON.stringify(first.sessions[0]), before, 'byte for byte after one restart');
118    const w = createSessionWriter({ transport: h.transport, known: first.revs });
119    first.sessions.forEach((s) => w.adopt(s, first.revs.get(s.id)));
120    w.schedule([{ ...first.sessions[0], title: 'renamed' }]); await w.flush();
121    const second = await hydrateChats({ transport: h.transport, browser: fakeStorage(), current: [] });
122    assert.equal(JSON.stringify({ ...second.sessions[0], title: original.title }), before, 'byte for byte after two restarts (apart from the rename)');
123    assert.equal(JSON.stringify(original), before, 'the chat in memory was not changed');
124  } finally { h.done(); }
125});
126
127test('#5192: far more text than the browser could hold (over 10 MB) keeps every chat and every message', async () => {
128  const h = host();
129  try {
130    const chats = ['a', 'b', 'c', 'd', 'e', 'f', 'g'].map((id, i) => chat(`s_${id}`, 8, 100_000, { updatedAt: String(i) }));
131    const total = chats.reduce((n, c) => n + JSON.stringify(c).length, 0);
132    assert.ok(total > 5_000_000, `fixture is ${total} characters`);
133    chats.push({ id: 's_big', createdAt: '2026-11-01', updatedAt: 'z', messages: [{ id: '1', role: 'user', content: 'p'.repeat(250_000) }, { id: '2', role: 'assistant', content: 'ok', tools: [{ name: 'read', result: 'y'.repeat(6_000_000) }] }] });
134    await saveAll(h, chats);
135    const back = await fromHost(h);
136    assert.equal(back.length, chats.length);
137    for (const c of chats) assert.equal(JSON.stringify(back.find((s) => s.id === c.id)), JSON.stringify(c));
138    assert.equal(serializeSession(chats[0]), JSON.stringify(chats[0]));
139    assert.ok(!JSON.stringify(back).includes('shortened'));
140  } finally { h.done(); }
141});
142
143test('a full disk is reported as such: the chat keeps its last file, the others still save, the unsaved chat is offered whole, and it saves by itself when there is room', async () => {
144  let full = false;
145  const h = host({ ...realIo, async writeFile(path, data) { if (full && /s_b\.json/.test(path)) throw Object.assign(new Error('no space left on device'), { code: 'ENOSPC' }); return realIo.writeFile(path, data); } });
146  try {
147    const results = [];
148    const writer = writerOn(h, { onResult: (r) => results.push(r), retryMs: 5 });
149    const small = chat('s_s', 2, 100), big = chat('s_b', 4, 1_000);
150    writer.schedule([small, big]); await writer.flush();
151    assert.equal(results.at(-1).ok, true);
152    const goodCopy = await h.reopen().read('s_b');
153    full = true;
154    const grown = { ...big, messages: [...big.messages, { id: 'b-big', role: 'user', content: 'g'.repeat(5_000) }] };
155    const fresh = chat('s_n', 2, 100);
156    writer.schedule([fresh, small, grown]); const r = await writer.flush();
157    assert.equal(r.ok, false);
158    assert.deepEqual(r.failed.map((f) => [f.id, f.reason]), [['s_b', 'disk-full']]);
159    assert.equal(await h.reopen().read('s_b'), goodCopy, 'the last file of the chat is untouched');
160    assert.ok(await h.reopen().read('s_n'), 'the other chats are still saved');
161    assert.deepEqual(writer.unsaved().map((s) => s.id), ['s_b']);
162    assert.equal(JSON.parse(exportSessions(writer.unsaved()))[0].messages.length, 5, 'the unsaved chat is complete');
163    // room is made; the retry saves the chat without being asked again
164    full = false;
165    for (let i = 0; i < 200 && writer.unsaved().length; i++) await new Promise((res) => setTimeout(res, 10));
166    assert.equal(writer.unsaved().length, 0, 'saved by itself');
167    assert.equal(results.at(-1).ok, true);
168    assert.equal(JSON.parse(await h.reopen().read('s_b')).session.messages.length, 5);
169  } finally { h.done(); }
170});
171
172test('a refused write (no permission) is reported as permission; a host that is away is reported as offline and caught up when it is back', async () => {
173  let denied = true;
174  const h = host({ ...realIo, async writeFile(path, data) { if (denied) throw Object.assign(new Error('access denied'), { code: 'EACCES' }); return realIo.writeFile(path, data); } });
175  try {
176    const results = [];
177    const writer = writerOn(h, { onResult: (r) => results.push(r), retryMs: 5 });
178    writer.schedule([chat('s_p', 1, 5)]); await writer.flush();
179    assert.equal(results.at(-1).failed[0].reason, 'permission');
180    denied = false; h.state.offline = true;
181    for (let i = 0; i < 100 && results.length < 3; i++) await new Promise((res) => setTimeout(res, 10));
182    assert.equal(results.at(-1).failed[0].reason, 'offline', 'a host that does not answer is not a disk problem');
183    h.state.offline = false;
184    for (let i = 0; i < 200 && writer.unsaved().length; i++) await new Promise((res) => setTimeout(res, 10));
185    assert.equal(writer.unsaved().length, 0);
186    assert.equal(h.reopen().list().chats.length, 1);
187  } finally { h.done(); }
188});
189
190test('a chat removed from the list is removed on the host; chats this writer never saw are not; nothing is saved before the writer is enabled', async () => {
191  const h = host();
192  try {
193    await h.store.save('s_other_window', JSON.stringify(chat('s_other_window', 1, 5)));
194    const a = chat('s_a', 1, 5), b = chat('s_b', 1, 5);
195    const writer = writerOn(h, { enabled: false });
196    writer.schedule([a, b]); await writer.flush();
197    assert.deepEqual(h.reopen().list().chats.map((c) => c.id), ['s_other_window'], 'off: nothing is sent');
198    writer.enable(); await writer.flush();
199    assert.deepEqual(h.reopen().list().chats.map((c) => c.id).sort(), ['s_a', 's_b', 's_other_window']);
200    writer.schedule([a]); await writer.flush();
201    assert.deepEqual(h.reopen().list().chats.map((c) => c.id).sort(), ['s_a', 's_other_window']);
202    writer.schedule([]); await writer.flush();
203    assert.deepEqual(h.reopen().list().chats.map((c) => c.id), ['s_other_window'], 'an empty list removes the chats this window had, not the other window\'s');
204  } finally { h.done(); }
205});
206
207/* The move from the browser's storage */
208function browserWith({ legacy = [], perChat = [], order = [] } = {}) {
209  const storage = fakeStorage();
210  if (legacy.length) storage.setItem(LEGACY_SESSIONS_KEY, JSON.stringify(legacy));
211  for (const c of perChat) storage.setItem(`${SESSION_KEY_PREFIX}${c.id}`, JSON.stringify(c));
212  if (order.length) storage.setItem(SESSION_INDEX_KEY, JSON.stringify({ v: 2, ids: order }));
213  return storage;
214}
215const snapshot = (storage) => JSON.stringify([...storage.map].sort());
216
217test('the browser\'s chats move to the host from both old layouts (the 0.2.10 list and the per-chat entries), once, and the browser copy is left as it is', async () => {
218  const h = host();
219  try {
220    const legacyOnly = chat('s_old', 12, 140_000), both = chat('s_both', 3, 100, { title: 'old list' });
221    const bothNewer = chat('s_both', 5, 100, { title: 'per-chat entry' }), perChatOnly = chat('s_new', 2, 100);
222    const browser = browserWith({ legacy: [legacyOnly, both], perChat: [bothNewer, perChatOnly], order: ['s_new', 's_both'] });
223    const before = snapshot(browser);
224    const read = readBrowserSessions(browser);
225    assert.deepEqual(read.sessions.map((s) => s.id), ['s_new', 's_both', 's_old']);
226    assert.equal(read.sessions.find((s) => s.id === 's_both').title, 'per-chat entry', 'the per-chat entry wins where a chat is in both');
227    const result = await hydrateChats({ transport: h.transport, browser, current: read.sessions });
228    assert.equal(result.moved, 3);
229    assert.equal(result.failed.length, 0);
230    assert.equal(browser.getItem(HOST_FLAG_KEY), '1');
231    const onHost = Object.fromEntries((await fromHost(h)).map((s) => [s.id, s]));
232    assert.equal(JSON.stringify(onHost.s_old), JSON.stringify(legacyOnly), 'the big chat arrived whole');
233    assert.equal(onHost.s_both.title, 'per-chat entry');
234    assert.deepEqual(result.sessions.map((s) => s.id).sort(), ['s_both', 's_new', 's_old']);
235    const after = new Map(browser.map); after.delete(HOST_FLAG_KEY);
236    assert.equal(JSON.stringify([...after].sort()), before, 'the browser copy is untouched (it stays as a fallback for one release)');
237    // later: the person deletes a chat on the host; the next start does not bring it back from the browser copy
238    await h.store.remove('s_old');
239    const again = await hydrateChats({ transport: h.transport, browser, current: [] });
240    assert.equal(again.moved, 0);
241    assert.deepEqual(again.sessions.map((s) => s.id).sort(), ['s_both', 's_new']);
242  } finally { h.done(); }
243});
244
245test('a move that the host refuses (disk full) is not flagged as done, keeps the chats in the page, and is tried again at the next start', async () => {
246  let full = true;
247  const h = host({ ...realIo, async writeFile(path, data) { if (full && /s_x\.json/.test(path)) throw Object.assign(new Error('no space'), { code: 'ENOSPC' }); return realIo.writeFile(path, data); } });
248  try {
249    const browser = browserWith({ legacy: [chat('s_x', 3, 50), chat('s_y', 2, 50)] });
250    const current = readBrowserSessions(browser).sessions;
251    const first = await hydrateChats({ transport: h.transport, browser, current });
252    assert.equal(first.failed.length, 1);
253    assert.equal(browser.getItem(HOST_FLAG_KEY), null, 'not done');
254    assert.deepEqual(first.sessions.map((s) => s.id).sort(), ['s_x', 's_y'], 'the chat the host refused is still shown');
255    full = false;
256    const second = await hydrateChats({ transport: h.transport, browser, current: first.sessions });
257    assert.equal(second.failed.length, 0);
258    assert.equal(browser.getItem(HOST_FLAG_KEY), '1');
259    assert.deepEqual((await fromHost(h)).map((s) => s.id).sort(), ['s_x', 's_y']);
260  } finally { h.done(); }
261});
262
263test('a host that is not answering at start leaves the page with what it has and moves nothing', async () => {
264  const h = host();
265  try {
266    h.state.offline = true;
267    const browser = browserWith({ legacy: [chat('s_a', 1, 5)] });
268    const current = readBrowserSessions(browser).sessions;
269    const result = await hydrateChats({ transport: h.transport, browser, current });
270    assert.equal(result.offline, true);
271    assert.deepEqual(result.sessions, current);
272    assert.equal(browser.getItem(HOST_FLAG_KEY), null);
273  } finally { h.done(); }
274});
275
276test('the last-moment copy: chats the host had not confirmed come back at the next start when newer, and the copy is used up', async () => {
277  const h = host();
278  try {
279    const browser = fakeStorage();
280    await saveAll(h, [chat('s_a', 2, 10, { updatedAt: '2026-11-04T10:00:00Z' })]);
281    const unsaved = [chat('s_a', 4, 10, { updatedAt: '2026-11-04T10:05:00Z' }), chat('s_b', 1, 10, { updatedAt: '2026-11-04T10:06:00Z' })];
282    assert.equal(keepLastMomentCopy(browser, unsaved), true);
283    const result = await hydrateChats({ transport: h.transport, browser, current: [] });
284    assert.deepEqual(result.recovered.sort(), ['s_a', 's_b']);
285    assert.equal(result.sessions.find((s) => s.id === 's_a').messages.length, 4);
286    assert.equal(browser.getItem(PENDING_KEY), null);
287    // an older copy than the host's file is dropped
288    keepLastMomentCopy(browser, [chat('s_a', 1, 10, { updatedAt: '2026-11-01T00:00:00Z' })]);
289    const older = takeLastMomentCopy(browser, [chat('s_a', 4, 10, { updatedAt: '2026-11-04T10:05:00Z' })], new Map());
290    assert.deepEqual(older.ids, []);
291    // a copy that does not fit the browser is not an error
292    assert.equal(keepLastMomentCopy(fakeStorage(10), unsaved), false);
293  } finally { h.done(); }
294});
295
296test('two windows on one host: neither removes the other\'s chats; the same chat saved from an older copy keeps the displaced version on the host', async () => {
297  const h = host();
298  try {
299    const a = createSessionWriter({ transport: h.transport });
300    const b = createSessionWriter({ transport: h.transport });
301    const chatA = chat('s_a', 2, 10), chatB = chat('s_b', 2, 10);
302    a.schedule([chatA]); await a.flush();
303    b.schedule([chatB]); await b.flush();
304    assert.deepEqual(h.reopen().list().chats.map((c) => c.id).sort(), ['s_a', 's_b']);
305    // window B opens chat A (rev 1) and keeps its copy; window A then saves a longer chat A, then B saves from its older copy
306    const opened = await h.transport.get('s_a');
307    b.adopt(opened.session, opened.rev);
308    const longer = chat('s_a', 6, 10);
309    a.schedule([longer, chatB]); await a.flush();
310    b.schedule([{ ...opened.session, title: 'edited in window B' }, chatB]); const r = await b.flush();
311    assert.equal(r.ok, true);
312    assert.equal(JSON.parse(await h.reopen().read('s_a')).session.title, 'edited in window B');
313    const kept = await import('node:fs').then((fs) => fs.readdirSync(join(h.dir, 'chats', 'conflicts')));
314    assert.equal(kept.length, 1, 'window A\'s version is kept on the host');
315    assert.deepEqual(h.reopen().list().chats.map((c) => c.id).sort(), ['s_a', 's_b']);
316  } finally { h.done(); }
317});
318
319/* End to end through the real store: a 1,500-token streamed answer, the host's files, a restart. */
320test('a streamed answer of 1,500 tokens is a handful of saves to the host, the final text is on disk, and a restart brings it back', async () => {
321  const h = host();
322  const fake = installFakeHostFetch(h.store);
323  try {
324    globalThis.window ??= globalThis;
325    globalThis.document ??= { addEventListener() {}, hasFocus: () => true, visibilityState: 'visible', documentElement: { dataset: {}, style: { setProperty() {} }, classList: { toggle() {}, add() {}, remove() {} } } };
326    const memory = new Map();
327    globalThis.localStorage = {
328      get length() { return memory.size; }, key: (i) => [...memory.keys()][i] ?? null,
329      getItem: (k) => memory.get(k) ?? null, setItem: (k, v) => { memory.set(k, v); }, removeItem: (k) => memory.delete(k),
330    };
331    globalThis.navigator ??= { language: 'en' };
332    globalThis.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });
333    const TOKENS = 1_500;
334    const mockClient = {
335      name: 'mock-client',
336      setup(b) {
337        b.onResolve({ filter: /\/client$/ }, () => ({ path: 'mock-client', namespace: 'mock' }));
338        b.onLoad({ filter: /.*/, namespace: 'mock' }, () => ({
339          loader: 'js',
340          contents: `
341            export class ApiError extends Error {}
342            const reject = async () => { throw new Error('offline'); };
343            export const api = { get: reject, post: async () => ({}), put: reject, patch: reject, del: reject, delete: reject };
344            export function onEvent() { return () => {}; }
345            export async function streamPost(path, body, onFrame) {
346              onFrame({ type: 'start', model: 'm', contextMax: 8192, requestId: 'r1' });
347              for (let i = 0; i < ${TOKENS}; i++) onFrame({ type: 'delta', text: 'word ' });
348              onFrame({ type: 'done', tokensIn: 10, tokensOut: ${TOKENS}, durationMs: 100, usageSource: 'reported' });
349            }`,
350        }));
351      },
352    };
353    const store = await bundle('../src/lib/store.ts', [mockClient]);
354    await store.loadChatsFromHost();   // the first read of the host's chats (bootstrap does this first; here the rest of it is mocked away)
355    const before = fake.calls.filter((c) => c.method === 'PUT').length;
356    await store.sendMessage('Write a long answer');
357    await store.flushSessions();
358    const puts = fake.calls.filter((c) => c.method === 'PUT').length - before;
359    assert.ok(puts >= 1 && puts <= 6, `a 1,500-token answer sent the chat ${puts} times`);
360    assert.ok(fake.calls.filter((c) => c.method === 'PUT').every((c) => c.headers['x-strata-client'] && c.headers['x-strata-window']), 'every save names the page and the window');
361    const saved = (await fromHost(h)).find((s) => s.messages.some((m) => m.role === 'assistant'));
362    const answer = saved.messages.find((m) => m.role === 'assistant');
363    assert.ok(answer.content.length >= TOKENS * 5 - 10, 'the finished answer is what is on disk');
364    assert.equal(answer.streaming, false);
365    assert.equal([...memory.keys()].filter((k) => k.startsWith('strata.session')).length, 0, 'nothing is written to the browser storage any more');
366  } finally { fake.restore(); h.done(); }
367});