okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7c11eb58b
main
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 => { 12const { code} = await transform ( src ( name ), { loader :'ts' , format :'esm' }); 13return import ( `data:text/javascript;base64, ${ Buffer . from ( code ). toString ( 'base64' )} ` ); 14}; 15const withI18n = async entry => { 16const 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' } }); 17const mod = await import ( `data:text/javascript;base64, ${ Buffer . from ( built . outputFiles [ 0 ]. text ). toString ( 'base64' )} ` ); 18for ( 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() 19return 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' , () => { 25const en = locale ( 'ui-en' ); 26const slots = text => [ ...text . matchAll ( / \{\d + \} / g )]. map ( m => m [ 0 ]). sort (); 27const others = new Set (); 28for ( const name of [ 'en' , 'tune-en' , 'tools-en' , 'fix-en' , 'gh-en' ]) for ( const v of Object . values ( locale ( name ))) others . add ( v ); 29for ( const l of languages ) { 30const catalog = locale ( `ui- ${ l } ` ); 31assert . deepEqual ( Object . keys ( catalog ), Object . keys ( en ), l ); 32for ( const [ id , source ] of Object . entries ( en )) { 33assert . ok ( catalog [ id ]. trim (), ` ${ l } : ${ id } is empty` ); 34assert . deepEqual ( slots ( catalog [ id ]), slots ( source ), ` ${ l } : ${ id } ` ); 35if ( l !== 'en' ) assert . notEqual ( catalog [ id ], source , ` ${ l } : ${ id } is still English` ); 36} 37} 38for ( 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 () => { 43const { pendingApprovals} = await load ( 'lib/approvals.ts' ); 44const tool = ( id , state ) => ({ id, name :'write' , state}); 45const 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] }; 51assert . deepEqual ( pendingApprovals ( session ). map ( x => [ x . messageId , x . tool . id ]), [[ 'm1' , 'b' ], [ 'm4' , 'e' ]]); 52assert . deepEqual ( pendingApprovals ( null ), []); 53assert . 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' , () => { 57const chat = src ( 'screens/Chat.tsx' ); 58assert . match ( chat , / <ApprovalDock sessionId=\{session\?\.id\}\/> / ); 59const toolCard = chat . slice ( chat . indexOf ( 'function ToolCard' )); 60assert . doesNotMatch ( toolCard , / \{tr\(" ( Approve | Deny ) "\)\} | resolveTool / , 'the card in the reply no longer carries the buttons' ); 61assert . match ( toolCard , / Waiting for your answer below / ); 62const dock = src ( 'components/ApprovalCard.tsx' ); 63assert . match ( dock , / resolveTool\(messageId, t\.id, true\) / ); 64assert . match ( dock , / resolveTool\(messageId, t\.id, false\) / ); 65assert . 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 () => { 69const { tr, setTranslationLanguage} = await withI18n ( 'approvals.ts' ); 70for ( const l of languages . slice ( 1 )) { 71setTranslationLanguage ( l ); 72for ( const text of [ 'Waiting for your answer' , 'Waiting for your answer below' ]) assert . notEqual ( tr ( text ), text , ` ${ l } : ${ text } ` ); 73} 74setTranslationLanguage ( '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' , () => { 83const files = walk ( new URL ( '../src' , import . meta. url ). pathname . replace ( / ^\/ ([ A - Za - z ] : ) / , '$1' )); 84const bare = [], own = []; 85for ( const file of files ) { 86if ( / lib [ \/ ] clipboard\.ts$ / . test ( file )) continue ; 87const text = readFileSync ( file , 'utf8' ); 88if ( / navigator\.clipboard\.writeText / . test ( text )) bare . push ( file ); 89if ( / <IconBtn name="copy" / . test ( text )) own . push ( file ); 90} 91assert . deepEqual ( bare , [], 'a bare clipboard call reports nothing when the clipboard is refused' ); 92assert . 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' , () => { 96const hook = src ( 'lib/use-copy.ts' ); 97assert . match ( hook , / COPIED_MS = 1800 / ); 98assert . match ( hook , / COPIED_MENU_MS = 900 / ); 99assert . match ( hook , / if \(ok\) \{\s * setCopied\(true\); / , 'only a copy that worked is shown' ); 100const btn = src ( 'components/CopyBtn.tsx' ); 101assert . match ( btn , / data-copied=\{copied \|\| undefined\} / ); 102assert . match ( btn , / name=\{copied \? 'check' : 'copy'\} / ); 103assert . match ( btn , / role="status">\{copied \? tr\('Copied'\) : ''\} / , 'a screen reader hears Copied' ); 104assert . match ( btn , / e\.stopPropagation\(\) / , 'the menu does not close before the person sees it' ); 105const css = src ( 'styles/app.css' ); 106assert . 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 () => { 110const { tr, setTranslationLanguage} = await withI18n ( 'approvals.ts' ); 111for ( const l of languages . slice ( 1 )) { setTranslationLanguage ( l ); assert . notEqual ( tr ( 'Copied' ), 'Copied' , l ); } 112setTranslationLanguage ( '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 () => { 117const { tuneStartBlock, TUNE_BLOCK_TEXT } = await withI18n ( 'native-tune.ts' ); 118const status = { ok :true }; 119assert . equal ( tuneStartBlock ({ busy :false , otherRunning :false , status, error :'' }), null ); 120assert . equal ( tuneStartBlock ({ busy :true , otherRunning :false , status, error :'' }), 'busy' , 'a click being carried out: a moment, no sentence' ); 121assert . equal ( tuneStartBlock ({ busy :false , otherRunning :true , status, error :'' }), 'other' ); 122assert . equal ( tuneStartBlock ({ busy :false , otherRunning :false , status :null , error :'' }), 'loading' ); 123assert . equal ( tuneStartBlock ({ busy :false , otherRunning :false , status :null , error :'HTTP 500' }), 'unreadable' ); 124assert . equal ( tuneStartBlock ({ busy :true , otherRunning :true , status :null , error :'' }), 'other' , 'the first reason in the order wins' ); 125assert . 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. 127for ( 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' , () => { 131const dialog = src ( 'components/NativeTune.tsx' ); 132assert . match ( dialog , / disabled=\{block !== null\} / ); 133assert . match ( dialog , / tune-why / ); 134assert . match ( dialog , / block === 'loading' \? <p className="small muted">\{tr\("Checking for saved tunings\\u2026"\)\} / ); 135assert . doesNotMatch ( dialog , / disabled=\{busy \|\| !!other \|\| !status\} / ); 136}); 137 138test ( '#4804 the new sentences are translated, and the existing one is reused' , async () => { 139const { tr, setTranslationLanguage, TUNE_BLOCK_TEXT } = await withI18n ( 'native-tune.ts' ); 140for ( 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 ); } 141setTranslationLanguage ( '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 () => { 146const { openExternal} = await withI18n ( 'open-external.ts' ); 147const seen = []; 148const deps = mode => ({ known :() => mode , load :async () => mode , post :async ( ...a ) => { seen . push ([ 'post' , ...a ]); }, open :u => seen . push ([ 'open' , u ]) }); 149await openExternal ( 'https://example.com/a?b=1' , deps ({ mode :'window' })); 150assert . deepEqual ( seen . splice ( 0 ), [[ 'post' , '/api/artifacts/open' , { action :'open' , url :'https://example.com/a?b=1' }]]); 151await openExternal ( 'https://example.com/a' , deps ({ mode :'browser' })); 152assert . deepEqual ( seen . splice ( 0 ), [[ 'open' , 'https://example.com/a' ]]); 153await openExternal ( 'https://example.com/a' , deps ({ mode :null })); 154assert . 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. 156let release ; 157const late = { known :() => null , load :() => new Promise ( r => { release = () => r ({ mode :'window' }); }), post :async ( ...a ) => { seen . push ([ 'post' , ...a ]); }, open :u => seen . push ([ 'open' , u ]) }; 158const pending = openExternal ( 'https://example.com/late' , late ); 159release (); 160await pending ; 161assert . equal ( seen . splice ( 0 )[ 0 ][ 0 ], 'post' ); 162// The host cannot open it: the page tries too. 163await openExternal ( 'https://example.com/x' , { ...deps ({ mode :'window' }), post :async () => { throw new Error ( 'no' ); } }); 164assert . 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 () => { 168globalThis . location = { origin :'http://127.0.0.1:1' }; 169const { artifactFromUrl} = await withI18n ( 'artifacts.ts' ); 170for ( const url of [ 'https://example.com/docs' , 'https://github.com/Niko1221/Strata/issues/4721' , 'http://localhost:3000/' ]) assert . equal ( artifactFromUrl ( url ). kind , 'website' , url ); 171for ( 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 ); 172assert . equal ( artifactFromUrl ( 'javascript:alert(1)' ), null ); 173const chat = src ( 'screens/Chat.tsx' ); 174assert . 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' , () => { 179const models = src ( 'components/NativeModels.tsx' ); 180assert . match ( models , / className="native-progress__ring" / , 'a soft ring beside the step, no spinner box' ); 181assert . match ( models , / className="native-progress__stop" / , 'Stop is a text button' ); 182assert . doesNotMatch ( models , / Still working for / , 'no clock sentence' ); 183assert . doesNotMatch ( models , / The buttons below wait until this finishes / , 'no sentence about the buttons' ); 184assert . doesNotMatch ( models , / native-wait-note / ); 185assert . match ( models , / role="progressbar" / , 'the bar says its value to a screen reader' ); 186const css = src ( 'styles/app.css' ); 187assert . match ( css , / \.native-progress__bar > i \{ [ ^ } ] * transform: scaleX\(0\) / , 'the bar fills by transform, not by layout' ); 188assert . match ( css , / @media \(prefers-reduced-motion: reduce\) \{\s * \.native-progress__ring / , 'reduced motion holds the ring and the bar still' ); 189assert . match ( css , / html\[data-motion='reduced'\] \.native-progress__ring / ); 190assert . 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 () => { 194const hook = src ( 'lib/use-elapsed.ts' ); 195assert . match ( hook , / Math\.max\(0, now - start\) / ); 196assert . match ( hook , / setInterval\(\(\) => setNow\(Date\.now\(\)\), 1000\) / ); 197assert . 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 () => { 201const { tr, setTranslationLanguage} = await withI18n ( 'approvals.ts' ); 202for ( const l of languages . slice ( 1 )) { 203setTranslationLanguage ( l ); 204assert . notEqual ( tr ( 'Stop' ), 'Stop' , l ); 205assert . notEqual ( tr ( 'Stopping…' ), 'Stopping…' , l ); 206} 207setTranslationLanguage ( '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' , () => { 212const page = src ( 'screens/Serving.tsx' ); 213assert . match ( page , / const twoAddresses = !!serving\.sharing\?\.active && !!serving\.sharing\.url && !!serving\.localUrl && serving\.localUrl !== serving\.sharing\.url; / ); 214assert . match ( page , / Address for other devices / ); 215assert . equal (( page . match ( / Other devices use this address\. / g ) ?? []). length , 1 ); 216const host = readFileSync ( new URL ( '../server/serving.mjs' , import . meta. url ), 'utf8' ); 217assert . match ( host , / localUrl: baseUrl\(\), / ); 218assert . 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 () => { 222const { tr, setTranslationLanguage} = await withI18n ( 'approvals.ts' ); 223for ( const l of languages . slice ( 1 )) { 224setTranslationLanguage ( l ); 225for ( 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} 227setTranslationLanguage ( 'en' ); 228}); 229 230// ---------------------------------------------------------------------------------------------------------------------- #4722 231test ( '#4722 paragraphs, lists and quotes share one measure; tables and code blocks keep the full column' , () => { 232const css = src ( 'styles/app.css' ); 233assert . match ( css , / \.st-msg--assistant \.st-bubble :is\(p, ul, ol, blockquote\) \{\s * max-width: var\(--st-measure\);\s * \} / ); 234assert . doesNotMatch ( css , / \.st-bubble \.md-li / , 'no rule names the class that the renderer never emits' ); 235assert . 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. 237const md = src ( 'components/Markdown.tsx' ); 238assert . match ( md , / ordered \? <ol key=\{key\}>\{tr\(items\)\}<\/ol> : <ul key=\{key\}> / ); 239assert . 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 () => { 244const { detectLanguage} = await withI18n ( 'language-detect.ts' ); 245assert . equal ( detectLanguage ([ 'zh-CN' , 'en' ]), 'zh' ); 246assert . equal ( detectLanguage ([ 'zh-TW' ]), 'zh' ); 247assert . equal ( detectLanguage ([ 'pt-BR' ]), 'pt' ); 248assert . equal ( detectLanguage ([ 'sv-SE' , 'de-DE' , 'en' ]), 'de' , 'the first one that is offered, not the first one' ); 249assert . equal ( detectLanguage ([ 'ja' ]), 'ja' ); 250assert . equal ( detectLanguage ([ 'sv-SE' , 'fi' ]), null ); 251assert . equal ( detectLanguage ([]), null ); 252assert . equal ( detectLanguage ( undefined ), null ); 253assert . 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' , () => { 257const store = src ( 'lib/store.ts' ); 258assert . match ( store , / language: validLanguage\(parsed\.language\) \? parsed\.language : 'en' / , 'a saved value is read as before' ); 259assert . match ( store , / return \{ \.\.\.PREFS_DEFAULTS, language: detectLanguage\(tags\) \?\? 'en' \}; / ); 260assert . match ( src ( 'components/EngineFirstRun.tsx' ), / <FirstRunLanguage\/> / ); 261assert . match ( src ( 'components/GuidedSetup.tsx' ), / step === 1 \? <FirstRunLanguage\/> : null / ); 262assert . 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' , () => { 266const models = src ( 'components/NativeModels.tsx' ); 267assert . match ( models , / KV_CHOICES\.map\(c => \(\{ value: c\.value, label: c\.label, title: c\.hint \}\)\) / ); 268for ( 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. 270const fit = src ( 'lib/native-fit.ts' ); 271assert . match ( fit , / int8: 1056, q4_0: 576, k8v4: 816 / ); 272assert . 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 () => { 276const { plainFailure} = await withI18n ( 'plain-errors.ts' ); 277const 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." ; 278const r = plainFailure ( reported ); 279assert . equal ( r . kind , 'vram' ); 280assert . equal ( r . message , 'The model did not fit in your graphics card’s memory.' ); 281assert . match ( r . next , / Context memory to Q4 / ); 282assert . equal ( r . detail , reported , 'the original text stays for Details' ); 283// Other stops are not taken for it. 284assert . equal ( plainFailure ( 'server_exited (exit code 1): EngineDied: the engine exited before it was ready' ). kind , 'start-failed' ); 285assert . equal ( plainFailure ( 'out of memory' ). kind , 'memory' ); 286assert . equal ( plainFailure ( '0xC0000135 DLL not found' ). kind , 'dll-missing' ); 287}); 288 289test ( '#3723 the new sentences are translated in every language' , async () => { 290const { tr, setTranslationLanguage, plainFailure} = await withI18n ( 'plain-errors.ts' ); 291const 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.' ]; 292for ( const l of languages . slice ( 1 )) { setTranslationLanguage ( l ); for ( const text of lines ) assert . notEqual ( tr ( text ), text , ` ${ l } : ${ text } ` ); } 293setTranslationLanguage ( 'en' ); 294void 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 () => { 303const dir = mkdtempSync ( join ( tmpdir (), 'strata-helper-msg-' )); 304try { 305const bridge = createAgentBridge ({ dataDir :dir , localInstances :() => [], connections :() => [], env :process . env }); 306const code = async args => { try { await bridge . messageHelper ( args ); return 'sent' ; } catch ( e ) { return e . code ; } }; 307assert . equal ( await code ({ chatId :'c' , helperId :'child-1' , text :' ' }), 'helper-empty' ); 308assert . equal ( await code ({ chatId :'c' , helperId :'' , text :'hi' }), 'helper-unknown' ); 309assert . equal ( await code ({ chatId :'c' , helperId :'a b; rm -rf /' , text :'hi' }), 'helper-unknown' ); 310assert . 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' , () => { 315const bridge = readFileSync ( new URL ( '../server/agent/agent-bridge.mjs' , import . meta. url ), 'utf8' ); 316assert . 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 \}\] \} \}\) / ); 317const index = readFileSync ( new URL ( '../server/index.mjs' , import . meta. url ), 'utf8' ); 318assert . match ( index , / path === '\/api\/chat\/helper' && method === 'POST' / ); 319const row = src ( 'components/SubagentRow.tsx' ); 320assert . match ( row , / delivery: a\.status === 'working' \? 'steer' : 'queue' / ); 321assert . match ( row , / sessionId && a\.status !== 'queued' && a\.status !== 'cancelled' / ); 322assert . 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 () => { 326const { tr, setTranslationLanguage} = await withI18n ( 'approvals.ts' ); 327for ( const l of languages . slice ( 1 )) { 328setTranslationLanguage ( l ); 329for ( 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} 331setTranslationLanguage ( '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 () => { 336const { busyPlan, validWhileBusy, WHILE_BUSY } = await load ( 'lib/while-busy.ts' ); 337assert . deepEqual ([ ...WHILE_BUSY ], [ 'wait' , 'queue' , 'interject' ]); 338assert . equal ( busyPlan ( 'wait' ), 'refuse' ); 339assert . equal ( busyPlan ( 'queue' ), 'goal' , 'a running goal has its own queue in the host; with none, the message is parked' ); 340assert . equal ( busyPlan ( 'interject' ), 'interrupt' ); 341assert . equal ( validWhileBusy ( 'queue' ), true ); 342for ( 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' , () => { 346const chat = src ( 'screens/Chat.tsx' ); 347assert . match ( chat , / if \(plan === 'interrupt'\) \{\s * updateDraft\(''\);\s * clearQuotes\(session\.id\);\s * parkMessage\(session\.id, out\);\s * stopStreaming\(\);\s * return;\s * \} / ); 348assert . match ( chat , / if \(plan === 'goal'\) \{ clearQuotes\(session\.id\); parkMessage\(session\.id, out\); return; \} / ); 349assert . match ( chat , / pushToast\('info', tr\('The assistant is still answering'\) / , 'Wait still says so' ); 350assert . match ( chat , / if \(!session \|\| !parkedReady\(session\.id, activeId, streaming, parked\?\.length \?\? 0\)\)\s * return;\s * const next = takeParked\(session\.id\); / ); 351const store = src ( 'lib/store.ts' ); 352assert . match ( store , / whileBusy: validWhileBusy\(parsed\.whileBusy\) \? parsed\.whileBusy : 'wait' / , 'an old or invalid saved value reads as Wait' ); 353assert . match ( store , / \n whileBusy: 'wait',\n / ); 354assert . match ( src ( 'screens/Settings.tsx' ), / setWhileBusy\(value as typeof prefs\.whileBusy\) / ); 355}); 356 357test ( '#4783 the new sentences are translated' , async () => { 358const { tr, setTranslationLanguage} = await withI18n ( 'approvals.ts' ); 359const 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' ]; 360for ( const l of languages . slice ( 1 )) { setTranslationLanguage ( l ); for ( const text of lines ) assert . notEqual ( tr ( text ), text , ` ${ l } : ${ text } ` ); } 361setTranslationLanguage ( '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 () => { 366const { composeQuoted, parseQuoted, cleanQuote, addToQuotes, MAX_QUOTES , MAX_QUOTE_CHARS } = await load ( 'lib/quotes.ts' ); 367const out = composeQuoted ([ 'The first passage.' , 'A second\npassage.' ], 'my answer' ); 368assert . equal ( out , 'Quoting:\n「The first passage.」\n「A second\npassage.」\n→ Reply: my answer' ); 369assert . 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. 371assert . deepEqual ( parseQuoted ( composeQuoted ([ 'q' ], '」\n→ Reply: x' )), { quotes :[ 'q' ], reply :'」\n→ Reply: x' }); 372// A quote cannot end itself early. 373assert . equal ( cleanQuote ( 'he said 「hi」' ), 'he said 『hi』' ); 374assert . deepEqual ( parseQuoted ( composeQuoted ([ 'he said 「hi」' ], 'ok' )). quotes , [ 'he said 『hi』' ]); 375assert . equal ( composeQuoted ([], 'plain' ), 'plain' ); 376assert . equal ( composeQuoted ([ ' ' ], 'plain' ), 'plain' ); 377assert . equal ( parseQuoted ( 'hello' ), null ); 378assert . equal ( parseQuoted ( 'Quoting:\nnothing' ), null ); 379assert . 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. 381let list = []; 382list = addToQuotes ( list , { text :'a' , messageId :'m1' , role :'assistant' }); 383list = addToQuotes ( list , { text :'a' , messageId :'m1' , role :'assistant' }); 384list = addToQuotes ( list , { text :' ' , messageId :'m1' , role :'assistant' }); 385assert . equal ( list . length , 1 ); 386list = addToQuotes ( list , { text :'a' , messageId :'m2' , role :'user' }); 387assert . equal ( list . length , 2 , 'the same words from another message is another quote' ); 388for ( let i = 0 ; i < 20 ; i ++ ) list = addToQuotes ( list , { text :`n ${ i } ` , messageId :'m3' , role :'assistant' }); 389assert . 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' , () => { 393const chat = src ( 'screens/Chat.tsx' ); 394assert . 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' ); 395assert . match ( chat , / document\.addEventListener\('selectionchange', read\) / ); 396assert . match ( chat , / data-message-id=\{m\.id\} / ); 397assert . match ( chat , / return quotes\.length && !text\.startsWith\('\/'\) \? composeQuoted\(quotes\.map\(q => q\.text\), text\) : text; / , 'a command goes out as typed' ); 398assert . match ( chat , / void sendMessage\(session \? quotedMessage\(quotes, text\) : text\); / ); 399assert . match ( chat , / const sentQuote = m\.role === 'user' \? parseQuoted\(m\.content\) : null; / ); 400}); 401 402test ( '#4785 the new words are translated' , async () => { 403const { tr, setTranslationLanguage} = await withI18n ( 'approvals.ts' ); 404const lines = [ 'Quote' , 'Quoting the assistant' , 'Quoting you' , 'Remove this quote' , 'Go to the quoted message' , 'Quoted' , 'Show or hide the rest of the quote' ]; 405for ( const l of languages . slice ( 1 )) { setTranslationLanguage ( l ); for ( const text of lines ) assert . notEqual ( tr ( text ), text , ` ${ l } : ${ text } ` ); } 406setTranslationLanguage ( '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 () => { 411const { parseQuestions, buildAnswer} = await import ( new URL ( '../server/agent/user-questions.mjs' , import . meta. url )); 412const 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]; 417const items = parseQuestions ( raw ); 418assert . deepEqual ( items . map ( q => q . id ), [ 'q1' , 'q2' ]); 419assert . deepEqual ( items [ 0 ]. options , [{ label :'Red' , description :'Warm' }, { label :'Blue' , description :undefined }]); 420assert . equal ( items [ 0 ]. question , 'Which colour?' ); assert . equal ( items [ 1 ]. multiSelect , true ); assert . equal ( items [ 0 ]. multiSelect , false ); 421assert . deepEqual ( parseQuestions ( undefined ), []); 422assert . 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. 424assert . deepEqual ( buildAnswer ( items , [{ id :'q1' , selected :[ 'Blue' ] }, { id :'q2' , selected :[ 'A' , 'B' , 'A' ] }]), { answers :[{ id :'q1' , selected :[ 'Blue' ] }, { id :'q2' , selected :[ 'A' , 'B' ] }] }); 425assert . 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' }] }); 426assert . throws (() => buildAnswer ( items , [{ id :'q1' , selected :[ 'Blue' ] }]), / Answer every question / , 'one question left open' ); 427assert . throws (() => buildAnswer ( items , [{ id :'q1' , selected :[ 'Green' ] }, { id :'q2' , selected :[ 'A' ] }]), / Answer every question / , 'a label that was not offered is no answer' ); 428assert . 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 () => { 432const { readAsk, answerComplete, toAnswers} = await load ( 'lib/agent-ask.ts' ); 433const 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' }] }); 434assert . equal ( ask . questions . length , 2 ); 435assert . equal ( readAsk ({ callId :'' , questions :[{ id :'q' , question :'x' }] }), null ); 436assert . equal ( readAsk ({ callId :'c' , questions :[] }), null ); 437assert . equal ( answerComplete ( ask . questions , {}), false ); 438assert . equal ( answerComplete ( ask . questions , { q1 :{ selected :[ 'Red' ], custom :'' } }), false ); 439assert . equal ( answerComplete ( ask . questions , { q1 :{ selected :[], custom :' ' }, q2 :{ selected :[ 'A' ], custom :'' } }), false ); 440assert . equal ( answerComplete ( ask . questions , { q1 :{ selected :[], custom :'mine' }, q2 :{ selected :[ 'A' ], custom :'' } }), true ); 441assert . 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' , () => { 445const preset = readFileSync ( new URL ( '../server/agent/preset.mjs' , import . meta. url ), 'utf8' ); 446assert . match ( preset , / export const REMOVED_PLUGIN_IDS = \['tool-schedule', 'planning'\]; / ); 447assert . match ( preset , / \{ id: 'tool-ask-user', name: '@deepseek-ai\/dsh-tool-ask-user' \} / ); 448const catalog = readFileSync ( new URL ( '../server/agent/tools-catalog.mjs' , import . meta. url ), 'utf8' ); 449assert . match ( catalog , / id: 'questions' [ ^ \n ] * plugins: \['tool-ask-user'\] / ); 450const bridge = readFileSync ( new URL ( '../server/agent/agent-bridge.mjs' , import . meta. url ), 'utf8' ); 451assert . match ( bridge , / await rt\.gw\.answerEvent\(\{ clientId: entry\.clientId \?\? rt\.clientId, eventId: entry\.eventId, outcome \}\); / ); 452assert . 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' ); 453const gateway = readFileSync ( new URL ( '../server/agent/gateway-client.mjs' , import . meta. url ), 'utf8' ); 454assert . match ( gateway , / const wire = outcome === 'next' \? \{ kind: 'next' \} : \{ kind: 'result', value: outcome \}; / , 'a structured answer travels as the result value' ); 455assert . 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 () => { 459const { tr, setTranslationLanguage} = await withI18n ( 'approvals.ts' ); 460const 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.' ]; 461for ( const l of languages . slice ( 1 )) { setTranslationLanguage ( l ); for ( const text of lines ) assert . notEqual ( tr ( text ), text , ` ${ l } : ${ text } ` ); } 462setTranslationLanguage ( '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' , () => { 467const chat = src ( 'screens/Chat.tsx' ); 468assert . 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; / ); 469assert . 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' ); 470assert . 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' , () => { 474const bridge = readFileSync ( new URL ( '../server/agent/agent-bridge.mjs' , import . meta. url ), 'utf8' ); 475assert . 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' \}\) / ); 476assert . match ( src ( 'lib/store.ts' ), / if \(ask && loopScheduler\.isRunning\(sessionId\)\) \{ void answerAgentAsk\(sessionId, ask\.callId, null\)\.catch\(\(\) => \{\}\); return; \} / ); 477});