okami.mom/strata

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

Niko1221Merge f-0215-parked: chat: a parked message is sent only from the chat that is also the active one (#5806)7c11eb58b

main
36.3 KiB477 linesraw
1// The 0.2.10 interface changes (branch f-0291-ui): one section per issue. Source-level checks for what only a browser can show are
2// backed by scripts/ui-do-drive.mjs, which drives the built app.
3import test from 'node:test';
4import assert from 'node:assert/strict';
5import { readFileSync } from 'node:fs';
6import { build, transform } from 'esbuild';
7
8// a Windows checkout with core.autocrlf (GitHub's runners) has CRLF line ends: the source checks below match LF
9const src = name => readFileSync(new URL(`../src/${name}`, import.meta.url), 'utf8').replace(/\r\n/g, '\n');
10const locale = name => JSON.parse(readFileSync(new URL(`../src/locales/${name}.json`, import.meta.url), 'utf8'));
11const load = async name => {
12  const { code } = await transform(src(name), { loader: 'ts', format: 'esm' });
13  return import(`data:text/javascript;base64,${Buffer.from(code).toString('base64')}`);
14};
15const withI18n = async entry => {
16  const built = await build({ stdin: { contents: `export * from './src/lib/i18n'; export * from './src/lib/${entry}';`, resolveDir: process.cwd() }, bundle: true, write: false, format: 'esm', platform: 'node', loader: { '.json': 'json' } });
17  const mod = await import(`data:text/javascript;base64,${Buffer.from(built.outputFiles[0].text).toString('base64')}`);
18  for (const l of ['zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr']) await mod.loadCatalog(l);  // the non-English catalogs load on first use (src/lib/i18n.ts loadCatalog); load them before the first tr()
19  return mod;
20};
21
22const languages = ['en', 'zh', 'ja', 'de', 'es', 'ru', 'pt', 'ko', 'fr'];
23
24test('the ui catalogs have the same keys and placeholders in all nine languages, none still English, none in another catalog', () => {
25  const en = locale('ui-en');
26  const slots = text => [...text.matchAll(/\{\d+\}/g)].map(m => m[0]).sort();
27  const others = new Set();
28  for (const name of ['en', 'tune-en', 'tools-en', 'fix-en', 'gh-en']) for (const v of Object.values(locale(name))) others.add(v);
29  for (const l of languages) {
30    const catalog = locale(`ui-${l}`);
31    assert.deepEqual(Object.keys(catalog), Object.keys(en), l);
32    for (const [id, source] of Object.entries(en)) {
33      assert.ok(catalog[id].trim(), `${l}:${id} is empty`);
34      assert.deepEqual(slots(catalog[id]), slots(source), `${l}:${id}`);
35      if (l !== 'en') assert.notEqual(catalog[id], source, `${l}:${id} is still English`);
36    }
37  }
38  for (const [id, text] of Object.entries(en)) assert.ok(!others.has(text), `already in another catalog: ${id} ${text}`);
39});
40
41// ---------------------------------------------------------------------------------------------------------------- #4725
42test('#4725 the pending approvals of a chat are listed oldest first, and nothing else is', async () => {
43  const { pendingApprovals } = await load('lib/approvals.ts');
44  const tool = (id, state) => ({ id, name: 'write', state });
45  const session = { messages: [
46    { id: 'm1', tools: [tool('a', 'done'), tool('b', 'proposed')] },
47    { id: 'm2', tools: [tool('c', 'denied'), tool('d', 'running')] },
48    { id: 'm3' },
49    { id: 'm4', tools: [tool('e', 'proposed')] },
50  ] };
51  assert.deepEqual(pendingApprovals(session).map(x => [x.messageId, x.tool.id]), [['m1', 'b'], ['m4', 'e']]);
52  assert.deepEqual(pendingApprovals(null), []);
53  assert.deepEqual(pendingApprovals({ messages: [] }), []);
54});
55
56test('#4725 the Approve and Deny buttons live in the dock above the message box, and the reply only says that it waits', () => {
57  const chat = src('screens/Chat.tsx');
58  assert.match(chat, /<ApprovalDock sessionId=\{session\?\.id\}\/>/);
59  const toolCard = chat.slice(chat.indexOf('function ToolCard'));
60  assert.doesNotMatch(toolCard, /\{tr\("(Approve|Deny)"\)\}|resolveTool/,'the card in the reply no longer carries the buttons');
61  assert.match(toolCard, /Waiting for your answer below/);
62  const dock = src('components/ApprovalCard.tsx');
63  assert.match(dock, /resolveTool\(messageId, t\.id, true\)/);
64  assert.match(dock, /resolveTool\(messageId, t\.id, false\)/);
65  assert.equal((dock.match(/tr\("Approve"\)/g) ?? []).length, 2, 'one Approve and Deny pair per card style, nowhere else');
66});
67
68test('#4725 the dock and the waiting line are translated', async () => {
69  const { tr, setTranslationLanguage } = await withI18n('approvals.ts');
70  for (const l of languages.slice(1)) {
71    setTranslationLanguage(l);
72    for (const text of ['Waiting for your answer', 'Waiting for your answer below']) assert.notEqual(tr(text), text, `${l}: ${text}`);
73  }
74  setTranslationLanguage('en');
75});
76
77// ---------------------------------------------------------------------------------------------------------------------- #4748
78import { readdirSync, statSync } from 'node:fs';
79import { join } from 'node:path';
80const walk = dir => readdirSync(dir).flatMap(name => { const p = join(dir, name); return statSync(p).isDirectory() ? (name === 'locales' ? [] : walk(p)) : /\.tsx?$/.test(name) ? [p] : []; });
81
82test('#4748 every Copy control goes through one shared behaviour: no bare clipboard call, no copy icon button of its own', () => {
83  const files = walk(new URL('../src', import.meta.url).pathname.replace(/^\/([A-Za-z]:)/, '$1'));
84  const bare = [], own = [];
85  for (const file of files) {
86    if (/lib[\/]clipboard\.ts$/.test(file)) continue;
87    const text = readFileSync(file, 'utf8');
88    if (/navigator\.clipboard\.writeText/.test(text)) bare.push(file);
89    if (/<IconBtn name="copy"/.test(text)) own.push(file);
90  }
91  assert.deepEqual(bare, [], 'a bare clipboard call reports nothing when the clipboard is refused');
92  assert.deepEqual(own, [], 'a copy icon button that is not CopyBtn shows nothing on itself');
93});
94
95test('#4748 the shared copy shows its state on the control for about two seconds, then goes back; a menu item says Copied and then closes', () => {
96  const hook = src('lib/use-copy.ts');
97  assert.match(hook, /COPIED_MS = 1800/);
98  assert.match(hook, /COPIED_MENU_MS = 900/);
99  assert.match(hook, /if \(ok\) \{\s*setCopied\(true\);/, 'only a copy that worked is shown');
100  const btn = src('components/CopyBtn.tsx');
101  assert.match(btn, /data-copied=\{copied \|\| undefined\}/);
102  assert.match(btn, /name=\{copied \? 'check' : 'copy'\}/);
103  assert.match(btn, /role="status">\{copied \? tr\('Copied'\) : ''\}/, 'a screen reader hears Copied');
104  assert.match(btn, /e\.stopPropagation\(\)/, 'the menu does not close before the person sees it');
105  const css = src('styles/app.css');
106  assert.match(css, /\.st-msg__actions:has\(\[data-copied\]\)\s*\{\s*opacity:\s*1/, 'the hover-only action row stays while it says Copied');
107});
108
109test('#4748 Copied is translated in every language', async () => {
110  const { tr, setTranslationLanguage } = await withI18n('approvals.ts');
111  for (const l of languages.slice(1)) { setTranslationLanguage(l); assert.notEqual(tr('Copied'), 'Copied', l); }
112  setTranslationLanguage('en');
113});
114
115// ---------------------------------------------------------------------------------------------------------------------- #4804
116test('#4804 every condition that greys out Start tuning has a name, and the ones that last have a sentence', async () => {
117  const { tuneStartBlock, TUNE_BLOCK_TEXT } = await withI18n('native-tune.ts');
118  const status = { ok: true };
119  assert.equal(tuneStartBlock({ busy: false, otherRunning: false, status, error: '' }), null);
120  assert.equal(tuneStartBlock({ busy: true, otherRunning: false, status, error: '' }), 'busy', 'a click being carried out: a moment, no sentence');
121  assert.equal(tuneStartBlock({ busy: false, otherRunning: true, status, error: '' }), 'other');
122  assert.equal(tuneStartBlock({ busy: false, otherRunning: false, status: null, error: '' }), 'loading');
123  assert.equal(tuneStartBlock({ busy: false, otherRunning: false, status: null, error: 'HTTP 500' }), 'unreadable');
124  assert.equal(tuneStartBlock({ busy: true, otherRunning: true, status: null, error: '' }), 'other', 'the first reason in the order wins');
125  assert.deepEqual(Object.keys(TUNE_BLOCK_TEXT).sort(), ['loading', 'other', 'unreadable']);
126  // It is exactly the old rule: disabled when busy, another operation runs, or there is no status.
127  for (const busy of [false, true]) for (const otherRunning of [false, true]) for (const s of [null, status]) assert.equal(tuneStartBlock({ busy, otherRunning, status: s, error: '' }) !== null, busy || otherRunning || !s);
128});
129
130test('#4804 the dialog shows the sentence, and does not say "No saved tuning" while it is still reading', () => {
131  const dialog = src('components/NativeTune.tsx');
132  assert.match(dialog, /disabled=\{block !== null\}/);
133  assert.match(dialog, /tune-why/);
134  assert.match(dialog, /block === 'loading' \? <p className="small muted">\{tr\("Checking for saved tunings\\u2026"\)\}/);
135  assert.doesNotMatch(dialog, /disabled=\{busy \|\| !!other \|\| !status\}/);
136});
137
138test('#4804 the new sentences are translated, and the existing one is reused', async () => {
139  const { tr, setTranslationLanguage, TUNE_BLOCK_TEXT } = await withI18n('native-tune.ts');
140  for (const l of languages.slice(1)) { setTranslationLanguage(l); for (const text of Object.values(TUNE_BLOCK_TEXT)) assert.notEqual(tr(text), text, `${l}: ${text}`); assert.notEqual(tr('Checking for saved tunings\u2026'), 'Checking for saved tunings\u2026', l); }
141  setTranslationLanguage('en');
142});
143
144// ---------------------------------------------------------------------------------------------------------------------- #4721
145test('#4721 a plain click on a web address goes to the default browser; the app window asks the host, a browser tab opens it itself', async () => {
146  const { openExternal } = await withI18n('open-external.ts');
147  const seen = [];
148  const deps = mode => ({ known: () => mode, load: async () => mode, post: async (...a) => { seen.push(['post', ...a]); }, open: u => seen.push(['open', u]) });
149  await openExternal('https://example.com/a?b=1', deps({ mode: 'window' }));
150  assert.deepEqual(seen.splice(0), [['post', '/api/artifacts/open', { action: 'open', url: 'https://example.com/a?b=1' }]]);
151  await openExternal('https://example.com/a', deps({ mode: 'browser' }));
152  assert.deepEqual(seen.splice(0), [['open', 'https://example.com/a']]);
153  await openExternal('https://example.com/a', deps({ mode: null }));
154  assert.deepEqual(seen.splice(0), [['open', 'https://example.com/a']], 'a host that does not say: the browser way');
155  // The answer has not arrived yet: the click waits for it, so the app window is not left with a window.open it drops.
156  let release;
157  const late = { known: () => null, load: () => new Promise(r => { release = () => r({ mode: 'window' }); }), post: async (...a) => { seen.push(['post', ...a]); }, open: u => seen.push(['open', u]) };
158  const pending = openExternal('https://example.com/late', late);
159  release();
160  await pending;
161  assert.equal(seen.splice(0)[0][0], 'post');
162  // The host cannot open it: the page tries too.
163  await openExternal('https://example.com/x', { ...deps({ mode: 'window' }), post: async () => { throw new Error('no'); } });
164  assert.deepEqual(seen.splice(0), [['open', 'https://example.com/x']]);
165});
166
167test('#4721 only a website goes to the browser; a file keeps the side panel', async () => {
168  globalThis.location = { origin: 'http://127.0.0.1:1' };
169  const { artifactFromUrl } = await withI18n('artifacts.ts');
170  for (const url of ['https://example.com/docs', 'https://github.com/Niko1221/Strata/issues/4721', 'http://localhost:3000/']) assert.equal(artifactFromUrl(url).kind, 'website', url);
171  for (const [url, kind] of [['https://example.com/a.pdf', 'pdf'], ['https://example.com/a.png', 'image'], ['https://example.com/a.csv', 'table'], ['https://example.com/a.ts', 'code'], ['https://example.com/readme.md', 'markdown']]) assert.equal(artifactFromUrl(url).kind, kind, url);
172  assert.equal(artifactFromUrl('javascript:alert(1)'), null);
173  const chat = src('screens/Chat.tsx');
174  assert.match(chat, /if \(item\.kind === 'website'\) \{\s*void openExternal\(url\);\s*return;\s*\}\s*openPreview\(item\);/);
175});
176
177// ---------------------------------------------------------------------------------------------------------------------- #4802
178test('#4802 / GUI-FB2 item 3: the progress card shows the step and the numbers only, with Stop as a plain word', () => {
179  const models = src('components/NativeModels.tsx');
180  assert.match(models, /className="native-progress__ring"/, 'a soft ring beside the step, no spinner box');
181  assert.match(models, /className="native-progress__stop"/, 'Stop is a text button');
182  assert.doesNotMatch(models, /Still working for/, 'no clock sentence');
183  assert.doesNotMatch(models, /The buttons below wait until this finishes/, 'no sentence about the buttons');
184  assert.doesNotMatch(models, /native-wait-note/);
185  assert.match(models, /role="progressbar"/, 'the bar says its value to a screen reader');
186  const css = src('styles/app.css');
187  assert.match(css, /\.native-progress__bar > i \{[^}]*transform: scaleX\(0\)/, 'the bar fills by transform, not by layout');
188  assert.match(css, /@media \(prefers-reduced-motion: reduce\) \{\s*\.native-progress__ring/, 'reduced motion holds the ring and the bar still');
189  assert.match(css, /html\[data-motion='reduced'\] \.native-progress__ring/);
190  assert.match(css, /\.native-progress__stop \{[^}]*border: 0; background: transparent;/);
191});
192
193test('#4802 the elapsed time is counted from the job start and never goes below zero', async () => {
194  const hook = src('lib/use-elapsed.ts');
195  assert.match(hook, /Math\.max\(0, now - start\)/);
196  assert.match(hook, /setInterval\(\(\) => setNow\(Date\.now\(\)\), 1000\)/);
197  assert.match(hook, /return \(\) => clearInterval\(timer\)/);
198});
199
200test('#4802 the progress card has no new sentence of its own: Stop and Stopping are translated', async () => {
201  const { tr, setTranslationLanguage } = await withI18n('approvals.ts');
202  for (const l of languages.slice(1)) {
203    setTranslationLanguage(l);
204    assert.notEqual(tr('Stop'), 'Stop', l);
205    assert.notEqual(tr('Stopping…'), 'Stopping…', l);
206  }
207  setTranslationLanguage('en');
208});
209
210// ---------------------------------------------------------------------------------------------------------------------- #4798
211test('#4798 while sharing is on, Serving shows the address on this computer and the one for other devices, with one sentence', () => {
212  const page = src('screens/Serving.tsx');
213  assert.match(page, /const twoAddresses = !!serving\.sharing\?\.active && !!serving\.sharing\.url && !!serving\.localUrl && serving\.localUrl !== serving\.sharing\.url;/);
214  assert.match(page, /Address for other devices/);
215  assert.equal((page.match(/Other devices use this address\./g) ?? []).length, 1);
216  const host = readFileSync(new URL('../server/serving.mjs', import.meta.url), 'utf8');
217  assert.match(host, /localUrl: baseUrl\(\),/);
218  assert.match(host, /baseUrl: sharing\.active \? sharing\.url : baseUrl\(\),/, 'the existing field keeps its meaning for the connection guide');
219});
220
221test('#4798 the three new Serving sentences are translated', async () => {
222  const { tr, setTranslationLanguage } = await withI18n('approvals.ts');
223  for (const l of languages.slice(1)) {
224    setTranslationLanguage(l);
225    for (const text of ['API base URL on this computer', 'Address for other devices', "Other devices use this address. It has its own port, separate from the one Strata's window uses, because only the model's API is shared on the network, not the app."]) assert.notEqual(tr(text), text, `${l}: ${text}`);
226  }
227  setTranslationLanguage('en');
228});
229
230// ---------------------------------------------------------------------------------------------------------------------- #4722
231test('#4722 paragraphs, lists and quotes share one measure; tables and code blocks keep the full column', () => {
232  const css = src('styles/app.css');
233  assert.match(css, /\.st-msg--assistant \.st-bubble :is\(p, ul, ol, blockquote\) \{\s*max-width: var\(--st-measure\);\s*\}/);
234  assert.doesNotMatch(css, /\.st-bubble \.md-li/, 'no rule names the class that the renderer never emits');
235  assert.doesNotMatch(css, /\.st-bubble[^{]*(table|\.md-table|\.st-code)[^{]*\{[^}]*max-width: var\(--st-measure\)/);
236  // The renderer really emits bare lists, which is what the rule now targets.
237  const md = src('components/Markdown.tsx');
238  assert.match(md, /ordered \? <ol key=\{key\}>\{tr\(items\)\}<\/ol> : <ul key=\{key\}>/);
239  assert.doesNotMatch(md, /className="md-li"/);
240});
241
242// ---------------------------------------------------------------------------------------------------------------------- #3723
243test('#3723 a first start opens in the first of the computer\'s languages that Strata has', async () => {
244  const { detectLanguage } = await withI18n('language-detect.ts');
245  assert.equal(detectLanguage(['zh-CN', 'en']), 'zh');
246  assert.equal(detectLanguage(['zh-TW']), 'zh');
247  assert.equal(detectLanguage(['pt-BR']), 'pt');
248  assert.equal(detectLanguage(['sv-SE', 'de-DE', 'en']), 'de', 'the first one that is offered, not the first one');
249  assert.equal(detectLanguage(['ja']), 'ja');
250  assert.equal(detectLanguage(['sv-SE', 'fi']), null);
251  assert.equal(detectLanguage([]), null);
252  assert.equal(detectLanguage(undefined), null);
253  assert.equal(detectLanguage(['KO_kr']), 'ko');
254});
255
256test('#3723 only a first start is detected: a saved language, even English, is kept; the first screens carry the choice', () => {
257  const store = src('lib/store.ts');
258  assert.match(store, /language: validLanguage\(parsed\.language\) \? parsed\.language : 'en'/, 'a saved value is read as before');
259  assert.match(store, /return \{ \.\.\.PREFS_DEFAULTS, language: detectLanguage\(tags\) \?\? 'en' \};/);
260  assert.match(src('components/EngineFirstRun.tsx'), /<FirstRunLanguage\/>/);
261  assert.match(src('components/GuidedSetup.tsx'), /step === 1 \? <FirstRunLanguage\/> : null/);
262  assert.match(src('components/FirstRunLanguage.tsx'), /setLanguage\(value as Language\)/);
263});
264
265test('#3723 Context memory has one line per format, from the documented memory figures', () => {
266  const models = src('components/NativeModels.tsx');
267  assert.match(models, /KV_CHOICES\.map\(c => \(\{ value: c\.value, label: c\.label, title: c\.hint \}\)\)/);
268  for (const text of ['INT8 is the standard: good quality and a medium amount of memory.', 'Q4 uses about half the memory of INT8, but is less precise on very long documents.', 'K8 / V4 uses about a quarter less memory than INT8 and is more precise than Q4. Prompts are 2 to 5% slower.']) assert.ok(models.includes(text), text);
269  // The figures are the ones of docs/DETAILS.md and of native-fit.ts: q4_0 576 and k8v4 816 against int8 1056 bytes per token and layer.
270  const fit = src('lib/native-fit.ts');
271  assert.match(fit, /int8: 1056, q4_0: 576, k8v4: 816/);
272  assert.ok(Math.abs(576 / 1056 - 0.55) < 0.06 && Math.abs(1 - 816 / 1056 - 0.23) < 0.01);
273});
274
275test('#3723 a start that ran out of graphics memory says so, with the engine\'s own words under Details', async () => {
276  const { plainFailure } = await withI18n('plain-errors.ts');
277  const reported = "server_exited (exit code 1): EngineDied: the engine exited before it was ready | the engine process ended: exit code 1: \nthe engine log's last lines:\n  strata generate: expert cache auto: 1.92 GiB free, 2048 MiB reserved (+184 MiB for the draft head) -> 0 slots\n  strata generate: no VRAM is left for the expert cache: it needs at least 332 slots (737 MiB), about 1000 MiB more than this card has free.";
278  const r = plainFailure(reported);
279  assert.equal(r.kind, 'vram');
280  assert.equal(r.message, 'The model did not fit in your graphics card’s memory.');
281  assert.match(r.next, /Context memory to Q4/);
282  assert.equal(r.detail, reported, 'the original text stays for Details');
283  // Other stops are not taken for it.
284  assert.equal(plainFailure('server_exited (exit code 1): EngineDied: the engine exited before it was ready').kind, 'start-failed');
285  assert.equal(plainFailure('out of memory').kind, 'memory');
286  assert.equal(plainFailure('0xC0000135 DLL not found').kind, 'dll-missing');
287});
288
289test('#3723 the new sentences are translated in every language', async () => {
290  const { tr, setTranslationLanguage, plainFailure } = await withI18n('plain-errors.ts');
291  const lines = ['INT8 is the standard: good quality and a medium amount of memory.', 'Q4 uses about half the memory of INT8, but is less precise on very long documents.', 'K8 / V4 uses about a quarter less memory than INT8 and is more precise than Q4. Prompts are 2 to 5% slower.', 'The model did not fit in your graphics card’s memory.', 'Lower the conversation context, or set Context memory to Q4 in Expert settings, then try again.'];
292  for (const l of languages.slice(1)) { setTranslationLanguage(l); for (const text of lines) assert.notEqual(tr(text), text, `${l}: ${text}`); }
293  setTranslationLanguage('en');
294  void plainFailure;
295});
296
297// ---------------------------------------------------------------------------------------------------------------------- #4749
298import { mkdtempSync, rmSync } from 'node:fs';
299import { tmpdir } from 'node:os';
300import { createAgentBridge } from '../server/agent/agent-bridge.mjs';
301
302test('#4749 a message for a helper is checked before anything is sent, and an agent that is not running says so', async () => {
303  const dir = mkdtempSync(join(tmpdir(), 'strata-helper-msg-'));
304  try {
305    const bridge = createAgentBridge({ dataDir: dir, localInstances: () => [], connections: () => [], env: process.env });
306    const code = async args => { try { await bridge.messageHelper(args); return 'sent'; } catch (e) { return e.code; } };
307    assert.equal(await code({ chatId: 'c', helperId: 'child-1', text: '   ' }), 'helper-empty');
308    assert.equal(await code({ chatId: 'c', helperId: '', text: 'hi' }), 'helper-unknown');
309    assert.equal(await code({ chatId: 'c', helperId: 'a b; rm -rf /', text: 'hi' }), 'helper-unknown');
310    assert.equal(await code({ chatId: 'c', helperId: 'child-1', text: 'use ISO dates' }), 'helper-idle', 'no running agent, no live parent');
311  } finally { rmSync(dir, { recursive: true, force: true, maxRetries: 3 }); }
312});
313
314test('#4749 the bridge uses the Harness own subagents/prompt with the documented request, steer for a working helper, queue for a finished one', () => {
315  const bridge = readFileSync(new URL('../server/agent/agent-bridge.mjs', import.meta.url), 'utf8');
316  assert.match(bridge, /rt\.gw\.rpc\('subagents\/prompt', \{ request: \{ requestId: `helper-\$\{randomUUID\(\)\}`, parentSessionId: parent, childSessionId: String\(helperId\), mode: 'continuable', delivery: delivery === 'steer' \? 'steer' : 'queue', content: \[\{ type: 'text', text: clean \}\] \} \}\)/);
317  const index = readFileSync(new URL('../server/index.mjs', import.meta.url), 'utf8');
318  assert.match(index, /path === '\/api\/chat\/helper' && method === 'POST'/);
319  const row = src('components/SubagentRow.tsx');
320  assert.match(row, /delivery: a\.status === 'working' \? 'steer' : 'queue'/);
321  assert.match(row, /sessionId && a\.status !== 'queued' && a\.status !== 'cancelled'/);
322  assert.match(src('components/ChatToolbar.tsx'), /sessionId=\{session && !session\.showcase \? session\.id : undefined\}/, 'the example chat has no real helpers to write to');
323});
324
325test('#4749 the helper strings are translated', async () => {
326  const { tr, setTranslationLanguage } = await withI18n('approvals.ts');
327  for (const l of languages.slice(1)) {
328    setTranslationLanguage(l);
329    for (const [text, values] of [['Message this helper'], ['Message to {0}', ['X']], ['Write to {0}…', ['X']], ['Sent to {0}.', ['X']]]) { const out = tr(text, values); assert.notEqual(out, text.replace('{0}', 'X'), `${l}: ${text}`); }
330  }
331  setTranslationLanguage('en');
332});
333
334// ---------------------------------------------------------------------------------------------------------------------- #4783
335test('#4783 the three choices while an answer is written, as the web chat page has them, and only those three are valid', async () => {
336  const { busyPlan, validWhileBusy, WHILE_BUSY } = await load('lib/while-busy.ts');
337  assert.deepEqual([...WHILE_BUSY], ['wait', 'queue', 'interject']);
338  assert.equal(busyPlan('wait'), 'refuse');
339  assert.equal(busyPlan('queue'), 'goal', 'a running goal has its own queue in the host; with none, the message is parked');
340  assert.equal(busyPlan('interject'), 'interrupt');
341  assert.equal(validWhileBusy('queue'), true);
342  for (const bad of ['', 'steer', 'QUEUE', null, undefined, 3]) assert.equal(validWhileBusy(bad), false, String(bad));
343});
344
345test('#4783 the composer acts on the choice, the default keeps today\'s behaviour, and the parked message is sent when the chat is quiet', () => {
346  const chat = src('screens/Chat.tsx');
347  assert.match(chat, /if \(plan === 'interrupt'\) \{\s*updateDraft\(''\);\s*clearQuotes\(session\.id\);\s*parkMessage\(session\.id, out\);\s*stopStreaming\(\);\s*return;\s*\}/);
348  assert.match(chat, /if \(plan === 'goal'\) \{ clearQuotes\(session\.id\); parkMessage\(session\.id, out\); return; \}/);
349  assert.match(chat, /pushToast\('info', tr\('The assistant is still answering'\)/, 'Wait still says so');
350  assert.match(chat, /if \(!session \|\| !parkedReady\(session\.id, activeId, streaming, parked\?\.length \?\? 0\)\)\s*return;\s*const next = takeParked\(session\.id\);/);
351  const store = src('lib/store.ts');
352  assert.match(store, /whileBusy: validWhileBusy\(parsed\.whileBusy\) \? parsed\.whileBusy : 'wait'/, 'an old or invalid saved value reads as Wait');
353  assert.match(store, /\n  whileBusy: 'wait',\n/);
354  assert.match(src('screens/Settings.tsx'), /setWhileBusy\(value as typeof prefs\.whileBusy\)/);
355});
356
357test('#4783 the new sentences are translated', async () => {
358  const { tr, setTranslationLanguage } = await withI18n('approvals.ts');
359  const lines = ['While an answer is being written', 'What Enter does when you send a message while the assistant is still answering.', 'Wait for the answer', 'Send after the answer', 'Interrupt the answer', 'Enter sends it when the answer is done.', 'Enter stops the answer here and sends it now.', 'Waiting to send', 'Take back'];
360  for (const l of languages.slice(1)) { setTranslationLanguage(l); for (const text of lines) assert.notEqual(tr(text), text, `${l}: ${text}`); }
361  setTranslationLanguage('en');
362});
363
364// ---------------------------------------------------------------------------------------------------------------------- #4785
365test('#4785 a quoted message carries the quotes in one fixed form and reads back the same, apart from the reply', async () => {
366  const { composeQuoted, parseQuoted, cleanQuote, addToQuotes, MAX_QUOTES, MAX_QUOTE_CHARS } = await load('lib/quotes.ts');
367  const out = composeQuoted(['The first passage.', 'A second\npassage.'], 'my answer');
368  assert.equal(out, 'Quoting:\n「The first passage.」\n「A second\npassage.」\n→ Reply: my answer');
369  assert.deepEqual(parseQuoted(out), { quotes: ['The first passage.', 'A second\npassage.'], reply: 'my answer' });
370  // A reply that itself looks like the form is still the reply.
371  assert.deepEqual(parseQuoted(composeQuoted(['q'], '」\n→ Reply: x')), { quotes: ['q'], reply: '」\n→ Reply: x' });
372  // A quote cannot end itself early.
373  assert.equal(cleanQuote('he said 「hi」'), 'he said 『hi』');
374  assert.deepEqual(parseQuoted(composeQuoted(['he said 「hi」'], 'ok')).quotes, ['he said 『hi』']);
375  assert.equal(composeQuoted([], 'plain'), 'plain');
376  assert.equal(composeQuoted(['   '], 'plain'), 'plain');
377  assert.equal(parseQuoted('hello'), null);
378  assert.equal(parseQuoted('Quoting:\nnothing'), null);
379  assert.ok(cleanQuote('x'.repeat(MAX_QUOTE_CHARS + 50)).length <= MAX_QUOTE_CHARS);
380  // The list: no empty one, no repeat of the same passage, no more than the limit.
381  let list = [];
382  list = addToQuotes(list, { text: 'a', messageId: 'm1', role: 'assistant' });
383  list = addToQuotes(list, { text: 'a', messageId: 'm1', role: 'assistant' });
384  list = addToQuotes(list, { text: '  ', messageId: 'm1', role: 'assistant' });
385  assert.equal(list.length, 1);
386  list = addToQuotes(list, { text: 'a', messageId: 'm2', role: 'user' });
387  assert.equal(list.length, 2, 'the same words from another message is another quote');
388  for (let i = 0; i < 20; i++) list = addToQuotes(list, { text: `n${i}`, messageId: 'm3', role: 'assistant' });
389  assert.equal(list.length, MAX_QUOTES);
390});
391
392test('#4785 quoting is wired: the menu, the selection, the box above the composer, the sending and the sent bubble', () => {
393  const chat = src('screens/Chat.tsx');
394  assert.equal((chat.match(/addQuote\(activeSession, m\.content, m\.id, '(user|assistant)'\)/g) ?? []).length, 2, 'a Quote item in the menu of both kinds of message');
395  assert.match(chat, /document\.addEventListener\('selectionchange', read\)/);
396  assert.match(chat, /data-message-id=\{m\.id\}/);
397  assert.match(chat, /return quotes\.length && !text\.startsWith\('\/'\) \? composeQuoted\(quotes\.map\(q => q\.text\), text\) : text;/, 'a command goes out as typed');
398  assert.match(chat, /void sendMessage\(session \? quotedMessage\(quotes, text\) : text\);/);
399  assert.match(chat, /const sentQuote = m\.role === 'user' \? parseQuoted\(m\.content\) : null;/);
400});
401
402test('#4785 the new words are translated', async () => {
403  const { tr, setTranslationLanguage } = await withI18n('approvals.ts');
404  const lines = ['Quote', 'Quoting the assistant', 'Quoting you', 'Remove this quote', 'Go to the quoted message', 'Quoted', 'Show or hide the rest of the quote'];
405  for (const l of languages.slice(1)) { setTranslationLanguage(l); for (const text of lines) assert.notEqual(tr(text), text, `${l}: ${text}`); }
406  setTranslationLanguage('en');
407});
408
409// ---------------------------------------------------------------------------------------------------------------------- #4244
410test('#4244 the question of the Harness is read into something the card can draw, and what cannot be shown is left out', async () => {
411  const { parseQuestions, buildAnswer } = await import(new URL('../server/agent/user-questions.mjs', import.meta.url));
412  const raw = [
413    { id: 'q1', question: ' Which colour? ', detail: 'Why', header: 'Colour', options: [{ label: 'Red', description: 'Warm' }, { label: '' }, { label: 'Blue' }] },
414    { id: '', question: 'no id' }, { id: 'q3', question: '' }, null, 'x',
415    { id: 'q2', question: 'Extras?', multiSelect: true, options: [{ label: 'A' }, { label: 'B' }] },
416  ];
417  const items = parseQuestions(raw);
418  assert.deepEqual(items.map(q => q.id), ['q1', 'q2']);
419  assert.deepEqual(items[0].options, [{ label: 'Red', description: 'Warm' }, { label: 'Blue', description: undefined }]);
420  assert.equal(items[0].question, 'Which colour?'); assert.equal(items[1].multiSelect, true); assert.equal(items[0].multiSelect, false);
421  assert.deepEqual(parseQuestions(undefined), []);
422  assert.equal(parseQuestions(Array.from({ length: 20 }, (_, i) => ({ id: `q${i}`, question: 'x' }))).length, 6);
423  // The answer is checked against what was asked, and has the shape of AskUserQuestionAnswer.
424  assert.deepEqual(buildAnswer(items, [{ id: 'q1', selected: ['Blue'] }, { id: 'q2', selected: ['A', 'B', 'A'] }]), { answers: [{ id: 'q1', selected: ['Blue'] }, { id: 'q2', selected: ['A', 'B'] }] });
425  assert.deepEqual(buildAnswer(items, [{ id: 'q1', selected: [], custom: ' my own ' }, { id: 'q2', selected: ['B'], custom: 'and more' }]), { answers: [{ id: 'q1', selected: [], custom: 'my own' }, { id: 'q2', selected: ['B'], custom: 'and more' }] });
426  assert.throws(() => buildAnswer(items, [{ id: 'q1', selected: ['Blue'] }]), /Answer every question/, 'one question left open');
427  assert.throws(() => buildAnswer(items, [{ id: 'q1', selected: ['Green'] }, { id: 'q2', selected: ['A'] }]), /Answer every question/, 'a label that was not offered is no answer');
428  assert.throws(() => buildAnswer(items, [{ id: 'q1', selected: ['Red', 'Blue'] }, { id: 'q2', selected: ['A'] }]), /one answer/, 'single-select takes one');
429});
430
431test('#4244 the page side: the card needs every question answered, and sends the offered labels and the own words', async () => {
432  const { readAsk, answerComplete, toAnswers } = await load('lib/agent-ask.ts');
433  const ask = readAsk({ callId: 'c1', questions: [{ id: 'q1', question: 'Colour?', options: [{ label: 'Red' }], multiSelect: false }, { id: 'q2', question: 'Extras?', options: [{ label: 'A' }], multiSelect: true }, { id: '', question: 'bad' }] });
434  assert.equal(ask.questions.length, 2);
435  assert.equal(readAsk({ callId: '', questions: [{ id: 'q', question: 'x' }] }), null);
436  assert.equal(readAsk({ callId: 'c', questions: [] }), null);
437  assert.equal(answerComplete(ask.questions, {}), false);
438  assert.equal(answerComplete(ask.questions, { q1: { selected: ['Red'], custom: '' } }), false);
439  assert.equal(answerComplete(ask.questions, { q1: { selected: [], custom: '  ' }, q2: { selected: ['A'], custom: '' } }), false);
440  assert.equal(answerComplete(ask.questions, { q1: { selected: [], custom: 'mine' }, q2: { selected: ['A'], custom: '' } }), true);
441  assert.deepEqual(toAnswers(ask.questions, { q1: { selected: [], custom: ' mine ' }, q2: { selected: ['A'], custom: '' } }), [{ id: 'q1', selected: [], custom: 'mine' }, { id: 'q2', selected: ['A'] }]);
442});
443
444test('#4244 the tool is offered again, as the group "Questions for you", and the bridge answers through the Harness result', () => {
445  const preset = readFileSync(new URL('../server/agent/preset.mjs', import.meta.url), 'utf8');
446  assert.match(preset, /export const REMOVED_PLUGIN_IDS = \['tool-schedule', 'planning'\];/);
447  assert.match(preset, /\{ id: 'tool-ask-user', name: '@deepseek-ai\/dsh-tool-ask-user' \}/);
448  const catalog = readFileSync(new URL('../server/agent/tools-catalog.mjs', import.meta.url), 'utf8');
449  assert.match(catalog, /id: 'questions'[^\n]*plugins: \['tool-ask-user'\]/);
450  const bridge = readFileSync(new URL('../server/agent/agent-bridge.mjs', import.meta.url), 'utf8');
451  assert.match(bridge, /await rt\.gw\.answerEvent\(\{ clientId: entry\.clientId \?\? rt\.clientId, eventId: entry\.eventId, outcome \}\);/);
452  assert.match(bridge, /if \(!turn \|\| turn\.finished \|\| turn\.stopping \|\| turn\.goalRun \|\| turn\.plan \|\| !turn\.announceQuestion \|\| !items\.length\) \{\s*void runtime\.gw\.answerEvent\(\{ clientId: runtime\.clientId, eventId: value\.eventId, outcome: 'next' \}\)/, 'a helper question, a stopping chat or an empty request is still declared unanswerable');
453  const gateway = readFileSync(new URL('../server/agent/gateway-client.mjs', import.meta.url), 'utf8');
454  assert.match(gateway, /const wire = outcome === 'next' \? \{ kind: 'next' \} : \{ kind: 'result', value: outcome \};/, 'a structured answer travels as the result value');
455  assert.match(src('components/ApprovalCard.tsx'), /asks\.map\(a => <QuestionCard key=\{a\.callId\} sessionId=\{sessionId!\} ask=\{a\}\/>\)/);
456});
457
458test('#4244 the new words are translated', async () => {
459  const { tr, setTranslationLanguage } = await withI18n('approvals.ts');
460  const lines = ['The assistant has a question for you', 'Type your own answer', 'Send answer', 'Skip', 'Questions for you', 'Lets the assistant stop and ask you a question, with answers to pick from, when it needs your decision.'];
461  for (const l of languages.slice(1)) { setTranslationLanguage(l); for (const text of lines) assert.notEqual(tr(text), text, `${l}: ${text}`); }
462  setTranslationLanguage('en');
463});
464
465// ---------------------------------------------------------------------------------------------------------------------- #3818
466test('#3818 the transcript lets go of the newest token while the reader has words selected in it, and offers the way back', () => {
467  const chat = src('screens/Chat.tsx');
468  assert.match(chat, /function readerHasSelection\(scroller: HTMLElement\): boolean \{\s*const sel = window\.getSelection\(\);\s*return !!sel && !sel\.isCollapsed && !!sel\.anchorNode && scroller\.contains\(sel\.anchorNode\) && sel\.toString\(\)\.trim\(\)\.length > 0;/);
469  assert.match(chat, /if \(pinned\.current && readerHasSelection\(el\)\) \{\s*\/\/[^\n]*\n\s*pinned\.current = false;\s*setAwayFromBottom\(distanceFromBottom\(el\) > PILL_DISTANCE\);\s*\}\s*if \(pinned\.current\)\s*el\.scrollTop = el\.scrollHeight;/, 'the observer that follows a growing reply');
470  assert.match(chat, /if \(pinned\.current && !sent && readerHasSelection\(el\)\) \{\s*pinned\.current = false;/, 'and the effect that follows each token; sending a message still brings the reader to it');
471});
472
473test('#4244 a goal, a plan step and a loop run without anyone there, so a question is declined at once instead of waiting', () => {
474  const bridge = readFileSync(new URL('../server/agent/agent-bridge.mjs', import.meta.url), 'utf8');
475  assert.match(bridge, /if \(!turn \|\| turn\.finished \|\| turn\.stopping \|\| turn\.goalRun \|\| turn\.plan \|\| !turn\.announceQuestion \|\| !items\.length\) \{\s*void runtime\.gw\.answerEvent\(\{ clientId: runtime\.clientId, eventId: value\.eventId, outcome: 'next' \}\)/);
476  assert.match(src('lib/store.ts'), /if \(ask && loopScheduler\.isRunning\(sessionId\)\) \{ void answerAgentAsk\(sessionId, ask\.callId, null\)\.catch\(\(\) => \{\}\); return; \}/);
477});