okami.mom/strata

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

Niko1221Merge f-clean-7 (045843071): the app loads screens, languages, Prism and Time-skip on first use; main chunk 3,123,528 -> 755,418 B, start screen 248.5 -> 143.4 ms (p2006 Chrome, median of 10); nothing users see changes (cleanup step 7)1631a9fde

main
7.0 KiB110 linesraw
1/** The notice for chats the host could not write (owner wording 11-04): shown once, with a copy button, in every language, gone when the chats are saved. */
2import test from 'node:test';
3import assert from 'node:assert/strict';
4import { build } from 'esbuild';
5import { fileURLToPath } from 'node:url';
6import { mkdtempSync, rmSync, readFileSync } from 'node:fs';
7import { tmpdir } from 'node:os';
8import { join } from 'node:path';
9import { createChatStore, realIo } from '../server/chat-store.mjs';
10import { installFakeHostFetch } from './helpers/fake-host-chats.mjs';
11
12const here = (p) => fileURLToPath(new URL(p, import.meta.url));
13async function bundle(entry, plugins = []) {
14  const result = await build({
15    entryPoints: [here(entry)], bundle: true, format: 'esm', platform: 'node', write: false, logLevel: 'silent',
16    alias: { react: here('./helpers/react-stub.mjs') }, loader: { '.json': 'json' }, plugins,
17  });
18  return import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`);
19}
20
21const TITLE = 'Some chats could not be saved';
22const BODY = "Strata's chat storage is full, so the newest changes to {0} chat(s) are only in this window. Delete old chats to make room; they then save by themselves.";
23const BUTTON = 'Copy unsaved chats';
24
25test('the notice exists in all nine languages, with the placeholder kept', () => {
26  for (const lang of ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']) {
27    const file = JSON.parse(readFileSync(here(`../src/locales/sav-${lang}.json`), 'utf8'));
28    assert.deepEqual(Object.keys(file), ['sav01', 'sav02', 'sav03'], lang);
29    assert.ok(/\{0\}/.test(file.sav02), `${lang} keeps {0}`);
30    assert.ok(Object.values(file).every((t) => t.trim().length > 3), lang);
31    if (lang === 'en') assert.deepEqual(Object.values(file), [TITLE, BODY, BUTTON], 'the owner\'s exact wording');
32    else assert.notEqual(file.sav01, TITLE, `${lang} is translated`);
33  }
34});
35
36test('the catalog finds the notice: the German page shows it in German, with the number filled in', async () => {
37  const i18n = await bundle('../src/lib/i18n.ts');
38  await i18n.setTranslationLanguage('de');
39  assert.equal(i18n.tr(TITLE), 'Einige Chats konnten nicht gespeichert werden');
40  assert.equal(i18n.tr(BUTTON), 'Nicht gespeicherte Chats kopieren');
41  assert.match(i18n.tr(BODY, [3]), /^Der Chat-Speicher von Strata ist voll, daher gibt es die neuesten Änderungen an 3 Chat\(s\) nur in diesem Fenster/);
42  i18n.setTranslationLanguage('en');
43  assert.equal(i18n.tr(BODY, [3]), "Strata's chat storage is full, so the newest changes to 3 chat(s) are only in this window. Delete old chats to make room; they then save by themselves.");
44});
45
46test('a full disk raises the notice once with a working copy button; offline raises nothing; saving by itself takes the notice away', async () => {
47  const dir = mkdtempSync(join(tmpdir(), 'strata-notice-'));
48  let full = false;
49  const chatStore = createChatStore({ dir, io: { ...realIo, async writeFile(path, data) { if (full) throw Object.assign(new Error('no space left on device'), { code: 'ENOSPC' }); return realIo.writeFile(path, data); } } });
50  const fake = installFakeHostFetch(chatStore);
51  try {
52    globalThis.window ??= globalThis;
53    globalThis.document ??= { addEventListener() {}, hasFocus: () => true, visibilityState: 'visible', documentElement: { dataset: {}, style: { setProperty() {} }, classList: { toggle() {}, add() {}, remove() {} } } };
54    const memory = new Map();
55    globalThis.localStorage = { get length() { return memory.size; }, key: (i) => [...memory.keys()][i] ?? null, getItem: (k) => memory.get(k) ?? null, setItem: (k, v) => { memory.set(k, v); }, removeItem: (k) => memory.delete(k) };
56    globalThis.navigator ??= { language: 'en' };
57    const copied = [];
58    Object.defineProperty(globalThis, 'navigator', { value: { language: 'en', clipboard: { writeText: async (t) => { copied.push(t); } } }, configurable: true });
59    globalThis.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });
60    const mockClient = {
61      name: 'mock-client',
62      setup(b) {
63        b.onResolve({ filter: /\/client$/ }, () => ({ path: 'mock-client', namespace: 'mock' }));
64        b.onLoad({ filter: /.*/, namespace: 'mock' }, () => ({ loader: 'js', contents: `
65          export class ApiError extends Error {}
66          const reject = async () => { throw new Error('offline'); };
67          export const api = { get: reject, post: async () => ({}), put: reject, patch: reject, del: reject, delete: reject };
68          export function onEvent() { return () => {}; }
69          export async function streamPost(path, body, onFrame) { onFrame({ type: 'start', model: 'm', contextMax: 8192 }); onFrame({ type: 'delta', text: 'an answer' }); onFrame({ type: 'done', tokensIn: 1, tokensOut: 2, durationMs: 1, usageSource: 'reported' }); }` }));
70      },
71    };
72    const store = await bundle('../src/lib/store.ts', [mockClient]);
73    await store.loadChatsFromHost();
74    const toasts = () => store.useStore((s) => s.toasts);
75    const notice = () => store.useStore((s) => s.sessionSave);
76
77    store.newSession();
78    await store.flushSessions();
79    assert.equal(notice(), null);
80    full = true;
81    await store.sendMessage('a question that cannot be saved');
82    await store.flushSessions();
83    assert.equal(notice().reason, 'disk-full');
84    assert.equal(notice().failedIds.length, 1);
85    const shown = toasts().filter((t) => t.title === TITLE);
86    assert.equal(shown.length, 1, 'shown once');
87    assert.equal(shown[0].tone, 'error');
88    assert.equal(shown[0].body, "Strata's chat storage is full, so the newest changes to 1 chat(s) are only in this window. Delete old chats to make room; they then save by themselves.");
89    assert.equal(shown[0].action.label, BUTTON);
90    await store.flushSessions();
91    assert.equal(toasts().filter((t) => t.title === TITLE).length, 1, 'a second failed save does not show it again');
92
93    // the button copies the unsaved chats whole
94    assert.ok(store.unsavedSessionsJson().includes('a question that cannot be saved'));
95    shown[0].action.run();
96    for (let i = 0; i < 20 && !copied.length; i++) await new Promise((r) => setTimeout(r, 10));
97    assert.equal(copied.length, 1);
98    const copy = JSON.parse(copied[0]);
99    assert.equal(copy[0].messages.some((m) => m.content === 'a question that cannot be saved'), true);
100
101    // a host that does not answer is not a full disk: no new notice, nothing claimed
102    full = false;
103    store.dismissToast(shown[0].id);
104    await store.flushSessions();   // there is room now: the chat saves and the notice goes
105    assert.equal(notice(), null);
106    assert.equal(toasts().filter((t) => t.title === TITLE && !t.leaving).length, 0, 'the notice is taken away when the chats are saved');
107    const onDisk = JSON.parse(await chatStore.read(copy[0].id)).session;
108    assert.equal(onDisk.messages.some((m) => m.content === 'a question that cannot be saved'), true, 'and the chat is on disk after all');
109  } finally { fake.restore(); rmSync(dir, { recursive: true, force: true }); }
110});