okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
85269ca15
main
1/** 2* A reload does not stop an agent turn. The page that comes back takes the running turn over again: it shows as running (the Stop button), the 3* rest of the answer streams in, the tool card that waits for a yes is there to answer, and the failure the page wrote when it lost the stream 4* goes. A turn that ended while the page was away is shown whole. Nothing to take over leaves the reply as it was. 5*/ 6import test from 'node:test' ; 7import assert from 'node:assert/strict' ; 8import { build } from 'esbuild' ; 9import { fileURLToPath } from 'node:url' ; 10import { mkdtempSync , rmSync } from 'node:fs' ; 11import { tmpdir } from 'node:os' ; 12import { join } from 'node:path' ; 13import { createChatStore } from '../server/chat-store.mjs' ; 14import { installFakeHostFetch } from './helpers/fake-host-chats.mjs' ; 15 16const here = ( p ) => fileURLToPath ( new URL ( p , import . meta. url )); 17async function bundle ( entry , plugins = []) { 18const result = await build ({ 19entryPoints :[ here ( entry )], bundle :true , format :'esm' , platform :'node' , write :false , logLevel :'silent' , 20alias :{ react :here ( './helpers/react-stub.mjs' ) }, loader :{ '.json' :'json' }, plugins, 21}); 22// A different text each time: the same text would give the same module, with the first test's state in it. 23return import ( `data:text/javascript;base64, ${ Buffer . from ( ` ${ result . outputFiles [ 0 ]. text } 24// ${ Math . random ()} ` ). toString ( 'base64' )} ` ); 25} 26 27const NETWORK = 'Network error. Try sending the message again.' ; 28const chatWithCutOffReply = ( id , requestId , extra = {}) => ({ 29 id, title :`Chat ${ id } ` , createdAt :'2026-11-04T10:00:00.000Z' , updatedAt :'2026-11-04T10:01:00.000Z' , workspace :'C:/w' , tokensIn :0 , tokensOut :0 , 30messages :[ 31{ id :` ${ id } -u` , role :'user' , content :'build the thing' , at :'2026-11-04T10:00:00.000Z' }, 32{ id :` ${ id } -a` , role :'assistant' , content :'I will start by' , at :'2026-11-04T10:00:05.000Z' , requestId, streaming :false , error :NETWORK , ...extra }, 33], 34}); 35 36async function pageOn ( chatStore , { active= [], attach}) { 37const fake = installFakeHostFetch ( chatStore ); 38globalThis . window ??= globalThis ; 39globalThis . document ??= { addEventListener () {}, hasFocus :() => true , visibilityState :'visible' , documentElement :{ dataset :{}, style :{ setProperty () {} }, classList :{ toggle () {}, add () {}, remove () {} } } }; 40const memory = new Map (); 41globalThis . localStorage = { get length () { return memory . size ; }, key :( i ) => [ ...memory . keys ()][ i ] ?? null , getItem :( k ) => memory . get ( k ) ?? null , setItem :( k , v ) => { memory . set ( k , v ); }, removeItem :( k ) => memory . delete ( k ) }; 42globalThis . navigator ??= { language :'en' }; 43globalThis . matchMedia ??= () => ({ matches :false , addEventListener () {}, removeEventListener () {}, addListener () {}, removeListener () {} }); 44globalThis . __attach = attach ; 45globalThis . __active = active ; 46globalThis . __attachCalls = []; 47const mockClient = { 48name :'mock-client' , 49setup ( b ) { 50b . onResolve ({ filter :/ \/client$ / }, () => ({ path :'mock-client' , namespace :'mock' })); 51b . onLoad ({ filter :/ . */ , namespace :'mock' }, () => ({ loader :'js' , contents :` 52export class ApiError extends Error { constructor(m, status, body) { super(m); this.status = status; this.body = body; } } 53const reject = async () => { throw new Error('offline'); }; 54export const api = { get: async (path) => { if (path === '/api/chat/active') return { turns: globalThis.__active }; if (path.startsWith('/api/agent/pending')) return { pending: [] }; throw new Error('offline'); }, post: async () => ({}), put: reject, patch: reject, del: reject, delete: reject }; 55export function onEvent() { return () => {}; } 56export async function streamPost(path, body, onFrame, signal) { 57globalThis.__attachCalls.push({ path, body }); 58if (path !== '/api/chat/attach') return; 59await globalThis.__attach(body, onFrame, signal, ApiError); 60}` })); 61}, 62}; 63const store = await bundle ( '../src/lib/store.ts' , [ mockClient ]); 64return { store, fake}; 65} 66const until = async ( check , what ) => { for ( let i = 0 ; i < 300 ; i ++ ) { if ( check ()) return ; await new Promise (( r ) => setTimeout ( r , 10 )); } assert . fail ( `timed out waiting for ${ what } (attach calls: ${ JSON . stringify ( globalThis . __attachCalls )} )` ); }; 67 68test ( 'reload in the middle of an agent turn: the chat shows as running with a Stop button, streams the rest, keeps the approval card, and ends whole' , async () => { 69const dir = mkdtempSync ( join ( tmpdir (), 'strata-reattach-' )); 70const chatStore = createChatStore ({ dir}); 71let page ; 72try { 73// What the page saved before it went away: the question, a cut-off reply, the failure it wrote when the stream broke. 74await chatStore . save ( 's_run' , JSON . stringify ( chatWithCutOffReply ( 's_run' , 'req-run' ))); 75let release ; 76const finished = new Promise (( r ) => { release = r ; }); 77page = await pageOn ( chatStore , { 78active :[{ chatId :'s_run' , sessionId :'sess-1' , requestId :'req-run' , mode :'manual' , pending :[{ callId :'call-9' }] }], 79attach :async ( body , onFrame ) => { 80assert . deepEqual ( body , { sessionId :'s_run' }, 'a running turn is asked for by chat only' ); 81onFrame ({ type :'start' , model :'m' , contextMax :8192 , agent :true , resumed :true , requestId :'req-run' , sessionId :'sess-1' , mode :'manual' , skills :[] }); 82onFrame ({ type :'resync' , content :'I will start by reading the folder, then' , reasoning :'thinking so far' }); 83onFrame ({ type :'agent-tool' , tool :{ id :'call-9' , name :'write' , verb :'Write' , target :'out.txt' , args :{}, state :'proposed' , effect :'Needs your approval.' } }); 84await finished ; // the turn goes on after the page is back 85onFrame ({ type :'delta' , text :' writing the file.' }); 86onFrame ({ type :'agent-tool' , tool :{ id :'call-9' , name :'write' , verb :'Write' , target :'out.txt' , args :{}, state :'done' , result :'wrote out.txt' } }); 87onFrame ({ type :'done' , tokensIn :10 , tokensOut :20 , durationMs :684000 , usageSource :'reported' }); 88}, 89}); 90const { store} = page ; 91await store . loadChatsFromHost (); 92await until (() => page . fake . calls . length && globalThis . __attachCalls . length === 1 , 'the attach request' ); 93store . selectSession ( 's_run' ); 94const chat = () => store . useStore (( s ) => s . sessions ). find (( s ) => s . id === 's_run' ); 95const reply = () => chat (). messages . at ( - 1 ); 96 97// running again: this is what shows the Stop button (the page treats a chat with a live turn as streaming) 98assert . equal ( store . useStore (( s ) => s . streaming ), true , 'the Stop button is there' ); 99assert . equal ( reply (). streaming , true , 'the reply is running' ); 100await until (() => reply (). content . startsWith ( 'I will start by reading the folder' ), 'the catch-up text' ); 101assert . equal ( reply (). error , undefined , 'the failure the page wrote is gone' ); 102assert . equal ( reply (). reasoning , 'thinking so far' ); 103const card = reply (). tools . find (( t ) => t . id === 'call-9' ); 104assert . equal ( card . state , 'proposed' , 'the approval waiting on the host is there to answer' ); 105assert . equal ( chat (). messages . length , 2 , 'no second reply was added' ); 106 107// the rest of the turn streams into the same reply 108release (); 109await until (() => reply (). streaming === false , 'the end of the turn' ); 110assert . equal ( reply (). content , 'I will start by reading the folder, then writing the file.' ); 111assert . equal ( reply (). tools . find (( t ) => t . id === 'call-9' ). state , 'done' ); 112assert . equal ( store . useStore (( s ) => s . streaming ), false , 'the Stop button goes away when the turn ends' ); 113await store . flushSessions (); 114const saved = JSON . parse ( await chatStore . read ( 's_run' )). session . messages . at ( - 1 ); 115assert . equal ( saved . content , 'I will start by reading the folder, then writing the file.' , 'and the whole answer is what is saved' ); 116assert . equal ( saved . streaming , false ); 117} finally { page ?. fake . restore (); rmSync ( dir , { recursive :true , force :true }); } 118}); 119 120test ( 'a turn that ended while the page was away is shown whole; a chat with nothing to take over keeps its reply and gets no error' , async () => { 121const dir = mkdtempSync ( join ( tmpdir (), 'strata-reattach2-' )); 122const chatStore = createChatStore ({ dir}); 123let page ; 124try { 125await chatStore . save ( 's_done' , JSON . stringify ( chatWithCutOffReply ( 's_done' , 'req-done' ))); 126await chatStore . save ( 's_gone' , JSON . stringify ( chatWithCutOffReply ( 's_gone' , 'req-gone' , { error :'Response interrupted. Ask again to retry; the partial answer is kept.' }))); 127page = await pageOn ( chatStore , { 128active :[], 129attach :async ( body , onFrame , _signal , ApiError ) => { 130if ( body . requestId === 'req-done' ) { 131onFrame ({ type :'start' , model :'m' , contextMax :8192 , agent :true , resumed :true , requestId :'req-done' , sessionId :'sess-2' , skills :[] }); 132onFrame ({ type :'resync' , content :'I will start by reading the folder. Done: 3 files changed.' , reasoning :'' }); 133onFrame ({ type :'agent-tool' , tool :{ id :'c1' , name :'write' , verb :'Write' , target :'a.txt' , args :{}, state :'done' , result :'ok' } }); 134onFrame ({ type :'done' , tokensIn :1 , tokensOut :2 , durationMs :5000 , usageSource :'reported' }); 135return ; 136} 137throw new ApiError ( '{"error":"There is no turn to take over.","code":"no-turn"}' , 404 ); // the host holds nothing for this reply 138}, 139}); 140const { store} = page ; 141await store . loadChatsFromHost (); 142await until (() => globalThis . __attachCalls . length >= 2 , 'both asked about' ); 143const sessions = () => store . useStore (( s ) => s . sessions ); 144await until (() => sessions (). find (( s ) => s . id === 's_done' ). messages . at ( - 1 ). usageSource === 'reported' , 'the finished turn' ); 145const done = sessions (). find (( s ) => s . id === 's_done' ). messages . at ( - 1 ); 146assert . equal ( done . content , 'I will start by reading the folder. Done: 3 files changed.' ); 147assert . equal ( done . error , undefined ); 148assert . equal ( done . streaming , false ); 149assert . equal ( done . tools [ 0 ]. state , 'done' ); 150await until (() => ! store . useStore (( s ) => s . sessions ). find (( s ) => s . id === 's_gone' ). messages . at ( - 1 ). streaming , 'the unanswered one settles' ); 151const gone = sessions (). find (( s ) => s . id === 's_gone' ). messages . at ( - 1 ); 152assert . equal ( gone . content , 'I will start by' , 'its reply is as the page had it' ); 153assert . equal ( gone . error , 'Response interrupted. Ask again to retry; the partial answer is kept.' , 'its error stays' ); 154assert . equal ( store . useStore (( s ) => s . toasts ). length , 0 , 'no failure is announced' ); 155assert . deepEqual ( globalThis . __attachCalls . map (( c ) => c . body . requestId ). sort (), [ 'req-done' , 'req-gone' ], JSON . stringify ( globalThis . __attachCalls )); 156assert . equal ( store . useStore (( s ) => s . streaming ), false ); 157} finally { page ?. fake . restore (); rmSync ( dir , { recursive :true , force :true }); } 158});