okami.mom/strata

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

Niko1221Merge f-0213-qafix into f-0213-int64b48c0d0

main
4.9 KiB105 linesraw
1/**
2 * QAGUI 0213 #1: one start-up GET that never answers must not leave the app on "Connecting to the local engine" for good.
3 * Optional reads (hardware, monitor, skills, ...) fill in later; a hung essential read ends in the offline path within a bounded time.
4 */
5import test from 'node:test';
6import assert from 'node:assert/strict';
7import { build } from 'esbuild';
8import { fileURLToPath } from 'node:url';
9
10const here = (p) => fileURLToPath(new URL(p, import.meta.url));
11
12globalThis.window ??= globalThis;
13globalThis.document ??= { addEventListener() {}, querySelector: () => null, hasFocus: () => true, visibilityState: 'visible', documentElement: { dataset: {}, style: { setProperty() {}, removeProperty() {} }, classList: { toggle() {}, add() {}, remove() {} } } };
14const memory = new Map();
15globalThis.localStorage = {
16  get length() { return memory.size; }, key: (i) => [...memory.keys()][i] ?? null,
17  getItem: (k) => memory.get(k) ?? null, setItem: (k, v) => { memory.set(k, v); }, removeItem: (k) => memory.delete(k),
18};
19globalThis.navigator ??= { language: 'en' };
20globalThis.matchMedia ??= () => ({ matches: false, addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {} });
21globalThis.fetch = async () => { throw new Error('offline'); };   // the chat read falls to the browser copy
22
23const answers = {
24  '/api/setup': { complete: true, dismissed: false },
25  '/api/models': { mode: 'real', variants: [] },
26  '/api/engine': { beginner: { contextLength: 8192 }, expert: [] },
27  '/api/serving': { state: 'idle' },
28  '/api/workspaces': { workspaces: [] },
29  '/api/hardware': { gpus: [] },
30  '/api/monitor': { cpu: 1 },
31  '/api/skills': [],
32  '/api/model-providers': { providers: [] },
33  '/api/image-models': { models: [] },
34  '/api/runtime': { models: [] },
35};
36globalThis.__hang = new Set();
37globalThis.__calls = {};
38globalThis.__flaky = {};
39const mockClient = {
40  name: 'mock-client',
41  setup(b) {
42    b.onResolve({ filter: /\/client$/ }, () => ({ path: 'mock-client', namespace: 'mock' }));
43    b.onLoad({ filter: /.*/, namespace: 'mock' }, () => ({
44      loader: 'js',
45      contents: `
46        export class ApiError extends Error { constructor(m, status) { super(m); this.status = status; } }
47        const none = async () => ({});
48        export const api = {
49          get: (path) => {
50            globalThis.__calls[path] = (globalThis.__calls[path] ?? 0) + 1;
51            if (globalThis.__hang.has(path)) return new Promise(() => {});
52            if ((globalThis.__flaky[path] ?? 0) > 0) { globalThis.__flaky[path]--; return Promise.reject(new Error('socket hang up')); }
53            return Promise.resolve(structuredClone(globalThis.__answers[path]));
54          },
55          post: none, put: none, patch: none, del: none, delete: none,
56        };
57        export function onEvent() { return () => {}; }
58        export async function streamPost() {}`,
59    }));
60  },
61};
62globalThis.__answers = answers;
63const result = await build({
64  entryPoints: [here('../src/lib/store.ts')], bundle: true, format: 'esm', platform: 'node', write: false, logLevel: 'silent',
65  alias: { react: here('./helpers/react-stub.mjs') }, loader: { '.json': 'json' }, plugins: [mockClient],
66});
67const store = await import(`data:text/javascript;base64,${Buffer.from(result.outputFiles[0].text).toString('base64')}`);
68Object.assign(store.bootstrapTiming, { timeoutMs: 150, tries: 2, backoffMs: 20 });
69
70const reset = () => { globalThis.__hang.clear(); globalThis.__calls = {}; globalThis.__flaky = {}; };
71const snapshot = () => store.getState();
72
73test('an optional GET that never answers does not hold back live; the others still fill in', async () => {
74  reset();
75  globalThis.__hang.add('/api/skills');
76  const t0 = Date.now();
77  await store.bootstrap();
78  assert.ok(Date.now() - t0 < 140, 'live before the time limit of the hung read');
79  assert.equal(snapshot().connection, 'live');
80  await new Promise(r => setTimeout(r, 50));
81  assert.deepEqual(snapshot().hardware, answers['/api/hardware']);
82  assert.equal(globalThis.__calls['/api/skills'], 1, 'the hung read is still waiting for its first answer');
83  await new Promise(r => setTimeout(r, 400));
84  assert.equal(globalThis.__calls['/api/skills'], 2, 'and is tried again, then given up');
85});
86
87test('an essential GET that never answers ends offline within a bounded time', async () => {
88  reset();
89  globalThis.__hang.add('/api/engine');
90  const t0 = Date.now();
91  await store.bootstrap();
92  const took = Date.now() - t0;
93  assert.equal(snapshot().connection, 'offline');
94  assert.equal(snapshot().ready, true);
95  assert.ok(took < 1500, `bounded (took ${took} ms)`);
96  assert.equal(globalThis.__calls['/api/engine'], 2, 'tried the bounded number of times');
97});
98
99test('a read that fails once is tried again and the app still goes live', async () => {
100  reset();
101  globalThis.__flaky['/api/setup'] = 1;
102  await store.bootstrap();
103  assert.equal(snapshot().connection, 'live');
104  assert.equal(globalThis.__calls['/api/setup'], 2);
105});