okami.mom/strata

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

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

main
8.0 KiB111 linesraw
1/** The chat routes of the real host: files in the profile's data folder, the page named by a header, other sites refused, a 12 MB chat, two hosts one after the other, an event for the other window. */
2import test from 'node:test';
3import assert from 'node:assert/strict';
4import { spawn } from 'node:child_process';
5import { mkdtemp, rm, readdir, stat } from 'node:fs/promises';
6import { tmpdir } from 'node:os';
7import { join } from 'node:path';
8import net from 'node:net';
9import { fileURLToPath } from 'node:url';
10
11const root = fileURLToPath(new URL('..', import.meta.url));
12const delay = ms => new Promise(r => setTimeout(r, ms));
13async function freePort() { const s = net.createServer(); await new Promise(r => s.listen(0, '127.0.0.1', r)); const p = s.address().port; await new Promise(r => s.close(r)); return p; }
14
15async function startHost(home) {
16  const port = await freePort();
17  const env = {
18    ...process.env, STRATA_HOME: home, STRATA_MODELS_DIR: join(home, 'models'), STRATA_PORT: String(port),
19    STRATA_SHARE_PORT: String(await freePort()), STRATA_TUNNEL_PORT: String(await freePort()), STRATA_REAL_ENGINE: '1',
20    STRATA_SETTINGS_FILE: join(home, 'app-settings.json'), STRATA_COMPONENTS_DIR: join(home, 'components'),
21    LOCALAPPDATA: join(home, 'Local'), APPDATA: join(home, 'Roaming'), XDG_DATA_HOME: join(home, 'xdg-data'),
22    XDG_STATE_HOME: join(home, 'xdg-state'), XDG_CONFIG_HOME: join(home, 'xdg-config'),
23  };
24  const host = spawn(process.execPath, ['server/index.mjs'], { cwd: root, stdio: 'ignore', env });
25  const exit = new Promise(r => host.once('exit', (code, signal) => r({ code, signal })));
26  let up = false;
27  for (let i = 0; i < 150 && !up; i++) { try { up = (await fetch(`http://127.0.0.1:${port}/api/health`)).ok; } catch { await delay(100); } }
28  assert.ok(up, 'host started');
29  const base = `http://127.0.0.1:${port}`;
30  return { base, stop: async () => { host.kill('SIGKILL'); await exit; } };
31}
32const named = (window, extra = {}) => ({ 'x-strata-client': 'ui', 'x-strata-window': window, ...extra });
33const chat = (id, n, len) => ({ id, title: `Chat ${id}`, createdAt: '2026-11-04T10:00:00.000Z', updatedAt: '2026-11-04T10:00:01.000Z', messages: Array.from({ length: n }, (_, i) => ({ id: `${id}-${i}`, role: i % 2 ? 'assistant' : 'user', content: String.fromCharCode(97 + (i % 26)).repeat(len) })) });
34
35test('the chat routes: named page only, other sites refused, save / read / list / delete, a 12 MB chat, and two hosts one after the other see the same files', async () => {
36  const home = await mkdtemp(join(tmpdir(), 'strata-chats-api-'));
37  let h = await startHost(home);
38  try {
39    // The page must name itself; a bare request (what another site's page can send without asking first) is refused.
40    assert.equal((await fetch(`${h.base}/api/chats`)).status, 403);
41    assert.equal((await fetch(`${h.base}/api/chats`, { headers: { 'x-strata-client': 'ui', origin: 'https://example.com' } })).status, 403, 'a page from another site is refused');
42    const empty = await (await fetch(`${h.base}/api/chats`, { headers: named('w1') })).json();
43    assert.deepEqual([empty.v, empty.chats], [1, []]);
44
45    const big = chat('s_big', 12, 1_000_000);   // 12 MB
46    const body = JSON.stringify(big);
47    assert.ok(body.length > 12_000_000);
48    const put = await fetch(`${h.base}/api/chats/s_big`, { method: 'PUT', headers: named('w1', { 'content-type': 'application/json' }), body });
49    assert.equal(put.status, 200);
50    assert.deepEqual(Object.keys(await put.json()).sort(), ['bytes', 'conflict', 'id', 'rev']);
51    const got = await (await fetch(`${h.base}/api/chats/s_big`, { headers: named('w1') })).json();
52    assert.equal(JSON.stringify(got.session), body, 'byte for byte');
53    assert.equal(got.rev, 1);
54
55    // a chat that is not a chat, and an id that climbs out of the folder
56    assert.equal((await fetch(`${h.base}/api/chats/s_x`, { method: 'PUT', headers: named('w1'), body: '{nope' })).status, 400);
57    assert.equal((await fetch(`${h.base}/api/chats/s_x`, { method: 'PUT', headers: named('w1'), body: JSON.stringify(chat('s_other', 1, 1)) })).status, 400);
58    assert.equal((await fetch(`${h.base}/api/chats/..%2Fevil`, { method: 'PUT', headers: named('w1'), body: JSON.stringify(chat('../evil', 1, 1)) })).status, 400);
59    assert.equal((await fetch(`${h.base}/api/chats/%E0%A4%A`, { headers: named('w1') })).status, 400, 'a malformed escape is a 400, not a crash');
60    assert.equal((await fetch(`${h.base}/api/chats/s_missing`, { headers: named('w1') })).status, 404);
61
62    await fetch(`${h.base}/api/chats/s_small`, { method: 'PUT', headers: named('w2'), body: JSON.stringify(chat('s_small', 2, 10)) });
63    await h.stop();
64    h = await startHost(home);   // the host restarted
65    const list = await (await fetch(`${h.base}/api/chats`, { headers: named('w1') })).json();
66    assert.deepEqual(list.chats.map(c => c.id).sort(), ['s_big', 's_small']);
67    assert.equal(JSON.stringify((await (await fetch(`${h.base}/api/chats/s_big`, { headers: named('w1') })).json()).session), body);
68
69    const dataFiles = (await readdir(join(home, 'data', 'chats'))).sort();
70    assert.deepEqual(dataFiles, ['index.json', 's_big.json', 's_small.json']);
71    if (process.platform !== 'win32') assert.equal((await stat(join(home, 'data', 'chats', 's_big.json'))).mode & 0o777, 0o600);
72
73    assert.deepEqual(await (await fetch(`${h.base}/api/chats/s_small`, { method: 'DELETE', headers: named('w2') })).json(), { id: 's_small', removed: true });
74    assert.equal((await (await fetch(`${h.base}/api/chats`, { headers: named('w1') })).json()).chats.length, 1);
75
76    // import: the browser's chats, the host keeps what it has
77    const imp = await (await fetch(`${h.base}/api/chats/import`, { method: 'POST', headers: named('w1'), body: JSON.stringify({ sessions: [chat('s_big', 1, 1), chat('s_old', 3, 10)] }) })).json();
78    assert.deepEqual([imp.imported, imp.skipped], [['s_old'], ['s_big']]);
79  } finally { await h.stop(); await rm(home, { recursive: true, force: true }).catch(() => {}); }
80});
81
82test('a save in one window is announced to the others on the event stream, with the name of the window that made it', async () => {
83  const home = await mkdtemp(join(tmpdir(), 'strata-chats-events-'));
84  const h = await startHost(home);
85  try {
86    const controller = new AbortController();
87    const res = await fetch(`${h.base}/api/events`, { signal: controller.signal });
88    const reader = res.body.getReader();
89    let seen = '';
90    const read = (async () => { const dec = new TextDecoder(); try { for (;;) { const { value, done } = await reader.read(); if (done) return; seen += dec.decode(value); } } catch { /* aborted */ } })();
91    await delay(200);
92    await fetch(`${h.base}/api/chats/s_ev`, { method: 'PUT', headers: named('window-A'), body: JSON.stringify(chat('s_ev', 1, 5)) });
93    for (let i = 0; i < 50 && !seen.includes('event: chats'); i++) await delay(50);
94    controller.abort(); await read;
95    const frame = /event: chats\ndata: (.*)\n/.exec(seen);
96    assert.ok(frame, 'a chats event arrived');
97    assert.deepEqual(JSON.parse(frame[1]), { id: 's_ev', rev: 1, from: 'window-A' });
98  } finally { await h.stop(); await rm(home, { recursive: true, force: true }).catch(() => {}); }
99});
100
101test('a page that comes back asks which chats have a turn running; with none, the answer is an empty list and "nothing to take over"', async () => {
102  const home = await mkdtemp(join(tmpdir(), 'strata-chats-active-'));
103  const h = await startHost(home);
104  try {
105    assert.deepEqual(await (await fetch(`${h.base}/api/chat/active`)).json(), { turns: [] });
106    const none = await fetch(`${h.base}/api/chat/attach`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ sessionId: 's_nothing', requestId: 'req-1' }) });
107    assert.equal(none.status, 404);
108    assert.equal((await none.json()).code, 'no-turn');
109    assert.equal((await fetch(`${h.base}/api/chat/attach`, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })).status, 400);
110  } finally { await h.stop(); await rm(home, { recursive: true, force: true }).catch(() => {}); }
111});