okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
714ff8242
main
1/** 2* #5008: two chats, one workspace, a tool that writes a unique marker. 3* A folder shared by two chats is shared on purpose; what a chat shows as its own (messages, tool cards, "files this turn made") is private. 4*/ 5import test from 'node:test' ; 6import assert from 'node:assert/strict' ; 7import { build } from 'esbuild' ; 8import { fileURLToPath } from 'node:url' ; 9import { mkdtempSync , rmSync , writeFileSync , mkdirSync } from 'node:fs' ; 10import { tmpdir } from 'node:os' ; 11import { join } from 'node:path' ; 12import { DeliverableTracker , FolderClaims } from '../server/agent/deliverables.mjs' ; 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 )); 17 18/* ---------------------------------------------------------------- host side: files a turn made */ 19 20/** A "tool" of a chat: writes a file with a unique marker, then asks the chat's tracker about it (what the bridge does on a write/edit card). */ 21function tool ( dir , tracker , name , marker ) { 22writeFileSync ( join ( dir , name ), `marker: ${ marker } \n` ); 23return tracker . check ( name , { explicit :true }); 24} 25 26test ( 'two chats in one folder: each turn reports only the files its own tools wrote, interleaved, and a script file nobody can own is withheld' , () => { 27const dir = mkdtempSync ( join ( tmpdir (), 'strata-5008-' )); 28try { 29const claims = new FolderClaims (); 30const A = new DeliverableTracker ( dir , { claims, owner :'chat-A' }); 31const B = new DeliverableTracker ( dir , { claims, owner :'chat-B' }); 32A . snapshot (); claims . begin ( dir , 'chat-A' ); 33B . snapshot (); claims . begin ( dir , 'chat-B' ); 34const reportedA = [], reportedB = []; 35// alternate marked turns 36reportedA . push ( tool ( dir , A , 'a-1.txt' , 'A-one' )); 37reportedB . push ( tool ( dir , B , 'b-1.txt' , 'B-one' )); 38reportedA . push ( tool ( dir , A , 'a-2.txt' , 'A-two' )); 39reportedB . push ( tool ( dir , B , 'b-2.txt' , 'B-two' )); 40mkdirSync ( join ( dir , 'out' )); writeFileSync ( join ( dir , 'out' , 'script-made.csv' ), 'x,y\n1,2\n' ); // a script's output, while both run 41// A ends first: its sweep must not claim B's files 42const sweptA = A . sweep (); claims . end ( dir , 'chat-A' ); 43const sweptB = B . sweep (); claims . end ( dir , 'chat-B' ); 44assert . deepEqual ( reportedA . map ( d => d . path ), [ 'a-1.txt' , 'a-2.txt' ]); 45assert . deepEqual ( reportedB . map ( d => d . path ), [ 'b-1.txt' , 'b-2.txt' ]); 46assert . deepEqual ( sweptA . map ( d => d . path ), [], 'chat A is not given chat B\'s files, nor a file whose writer cannot be told' ); 47assert . deepEqual ( sweptB . map ( d => d . path ), [], 'and the other way round' ); 48} finally { rmSync ( dir , { recursive :true , force :true }); } 49}); 50 51test ( 'a chat working alone still gets the files its scripts made (nothing changes without a second chat)' , () => { 52const dir = mkdtempSync ( join ( tmpdir (), 'strata-5008b-' )); 53try { 54const claims = new FolderClaims (); 55const A = new DeliverableTracker ( dir , { claims, owner :'chat-A' }); 56A . snapshot (); claims . begin ( dir , 'chat-A' ); 57writeFileSync ( join ( dir , 'built.js' ), 'x\n' ); 58assert . deepEqual ( A . sweep (). map ( d => d . path ), [ 'built.js' ]); 59claims . end ( dir , 'chat-A' ); 60// a second chat that starts after the first has ended is not overlapped with it 61const B = new DeliverableTracker ( dir , { claims, owner :'chat-B' }); 62B . snapshot (); claims . begin ( dir , 'chat-B' ); 63writeFileSync ( join ( dir , 'later.js' ), 'y\n' ); 64assert . deepEqual ( B . sweep (). map ( d => d . path ), [ 'later.js' ]); 65claims . end ( dir , 'chat-B' ); 66} finally { rmSync ( dir , { recursive :true , force :true }); } 67}); 68 69test ( 'a chat that is stopped or fails still lets go of the folder, and another folder is never affected' , () => { 70const one = mkdtempSync ( join ( tmpdir (), 'strata-5008c-' )), two = mkdtempSync ( join ( tmpdir (), 'strata-5008d-' )); 71try { 72const claims = new FolderClaims (); 73const A = new DeliverableTracker ( one , { claims, owner :'chat-A' }); 74const B = new DeliverableTracker ( two , { claims, owner :'chat-B' }); 75A . snapshot (); claims . begin ( one , 'chat-A' ); 76B . snapshot (); claims . begin ( two , 'chat-B' ); 77writeFileSync ( join ( one , 'a.js' ), 'x\n' ); writeFileSync ( join ( two , 'b.js' ), 'y\n' ); 78assert . deepEqual ( A . sweep (). map ( d => d . path ), [ 'a.js' ], 'different folders are not overlapped' ); 79assert . deepEqual ( B . sweep (). map ( d => d . path ), [ 'b.js' ]); 80claims . end ( one , 'chat-A' ); claims . end ( one , 'chat-A' ); // ending twice (stop, then error) is harmless 81claims . end ( two , 'chat-B' ); 82assert . equal ( claims . ownerOf ( one , 'a.js' ), null ); 83assert . equal ( claims . overlapped ( one , 'chat-A' ), false ); 84} finally { rmSync ( one , { recursive :true , force :true }); rmSync ( two , { recursive :true , force :true }); } 85}); 86 87test ( 'a file both chats wrote with their file tools is reported to each chat that wrote it' , () => { 88const dir = mkdtempSync ( join ( tmpdir (), 'strata-5008e-' )); 89try { 90const claims = new FolderClaims (); 91const A = new DeliverableTracker ( dir , { claims, owner :'chat-A' }); 92const B = new DeliverableTracker ( dir , { claims, owner :'chat-B' }); 93A . snapshot (); claims . begin ( dir , 'chat-A' ); B . snapshot (); claims . begin ( dir , 'chat-B' ); 94assert . equal ( tool ( dir , A , 'shared.md' , 'A' ). status , 'created' ); 95assert . ok ( tool ( dir , B , 'shared.md' , 'B-longer-marker' ), 'the second chat\'s own write is its own deliverable' ); 96} finally { rmSync ( dir , { recursive :true , force :true }); } 97}); 98 99/* ---------------------------------------------------------------- app side: messages and tool cards of two live chats */ 100 101async function bundle ( entry , plugins = []) { 102const result = await build ({ 103entryPoints :[ here ( entry )], bundle :true , format :'esm' , platform :'node' , write :false , logLevel :'silent' , 104alias :{ react :here ( './helpers/react-stub.mjs' ) }, loader :{ '.json' :'json' }, plugins, 105}); 106return import ( `data:text/javascript;base64, ${ Buffer . from ( result . outputFiles [ 0 ]. text ). toString ( 'base64' )} ` ); 107} 108 109test ( 'two live chats in one workspace keep their messages, tool cards and saved copies apart, interleaved, and after a restart' , async () => { 110const hostDir = mkdtempSync ( join ( tmpdir (), 'strata-5008-host-' )); 111const chatStore = createChatStore ({ dir :hostDir }); 112const fakeHost = installFakeHostFetch ( chatStore ); 113try { 114globalThis . window ??= globalThis ; 115globalThis . document ??= { addEventListener () {}, hasFocus :() => true , visibilityState :'visible' , documentElement :{ dataset :{}, style :{ setProperty () {} }, classList :{ toggle () {}, add () {}, remove () {} } } }; 116const memory = new Map (); 117globalThis . localStorage = { 118get length () { return memory . size ; }, 119key :( i ) => [ ...memory . keys ()][ i ] ?? null , 120getItem :( k ) => memory . get ( k ) ?? null , 121setItem :( k , v ) => { memory . set ( k , v ); }, 122removeItem :( k ) => memory . delete ( k ), 123}; 124globalThis . navigator ??= { language :'en' }; 125globalThis . matchMedia ??= () => ({ matches :false , addEventListener () {}, removeEventListener () {}, addListener () {}, removeListener () {} }); 126globalThis . __streams = []; 127const mockClient = { 128name :'mock-client' , 129setup ( b ) { 130b . onResolve ({ filter :/ \/client$ / }, () => ({ path :'mock-client' , namespace :'mock' })); 131b . onLoad ({ filter :/ . */ , namespace :'mock' }, () => ({ 132loader :'js' , 133contents :` 134export class ApiError extends Error {} 135const reject = async () => { throw new Error('offline'); }; 136export const api = { get: reject, post: async () => ({}), put: reject, patch: reject, del: reject, delete: reject }; 137export function onEvent() { return () => {}; } 138export async function streamPost(path, body, onFrame) { 139await new Promise((release) => globalThis.__streams.push({ body, onFrame, release })); 140}` , 141})); 142}, 143}; 144const store = await bundle ( '../src/lib/store.ts' , [ mockClient ]); 145await store . loadChatsFromHost (); // the first read of the host's chats (the page's own start-up does this inside bootstrap) 146const wait = async ( n ) => { for ( let i = 0 ; i < 200 && globalThis . __streams . length < n ; i ++ ) await new Promise (( r ) => setTimeout ( r , 5 )); assert . ok ( globalThis . __streams . length >= n , `stream ${ n } started` ); }; 147 148const a = store . newSession (); 149const turnA = store . sendMessage ( 'question for chat A MARK-A' ); 150await wait ( 1 ); 151const b = store . newSession (); 152const turnB = store . sendMessage ( 'question for chat B MARK-B' ); 153await wait ( 2 ); 154const [ sa , sb ] = globalThis . __streams ; 155assert . equal ( sa . body . sessionId , a . id ); 156assert . equal ( sb . body . sessionId , b . id ); 157assert . notEqual ( sa . body . sessionId , sb . body . sessionId ); 158assert . ok ( ! JSON . stringify ( sb . body . history ). includes ( 'MARK-A' ), 'chat B\'s request carries none of chat A\'s history' ); 159 160const tool = ( id , marker ) => ({ type :'agent-tool' , tool :{ id, name :'write' , state :'done' , args :{ file_path :` ${ marker } .txt` }, result :`wrote marker ${ marker } ` } }); 161// interleave: A, B, A, B 162sa . onFrame ({ type :'start' , model :'m' , contextMax :8192 , requestId :'rA' , agent :true }); 163sb . onFrame ({ type :'start' , model :'m' , contextMax :8192 , requestId :'rB' , agent :true }); 164sa . onFrame ( tool ( 'call-1' , 'A-unique-1' )); 165sb . onFrame ( tool ( 'call-1' , 'B-unique-1' )); // the same call id in both chats: ids are only unique inside a chat 166sa . onFrame ({ type :'delta' , text :'answer A ' }); 167sb . onFrame ({ type :'delta' , text :'answer B ' }); 168sa . onFrame ({ type :'delta' , text :'ends A' }); 169sb . onFrame ({ type :'delta' , text :'ends B' }); 170sa . onFrame ({ type :'done' , tokensIn :5 , tokensOut :5 , durationMs :10 , usageSource :'reported' }); 171sb . onFrame ({ type :'done' , tokensIn :5 , tokensOut :5 , durationMs :10 , usageSource :'reported' }); 172sa . release (); sb . release (); 173await Promise . all ([ turnA , turnB ]); 174await store . flushSessions (); 175 176const saved = []; 177for ( const e of chatStore . list (). chats ) saved . push ( JSON . parse ( await chatStore . read ( e . id )). session ); 178assert . equal ( saved . length , 2 , JSON . stringify ( fakeHost . calls . map (( c ) => ` ${ c . method } ${ c . path } ` ))); 179const bodyOf = ( id ) => JSON . stringify ( saved . find (( s ) => s . id === id )); 180assert . ok ( bodyOf ( a . id ). includes ( 'MARK-A' ) && bodyOf ( a . id ). includes ( 'A-unique-1' ) && bodyOf ( a . id ). includes ( 'ends A' )); 181assert . ok ( ! /MARK-B | B-unique | ends B / . test ( bodyOf ( a . id )), 'chat A holds nothing of chat B' ); 182assert . ok ( bodyOf ( b . id ). includes ( 'MARK-B' ) && bodyOf ( b . id ). includes ( 'B-unique-1' ) && bodyOf ( b . id ). includes ( 'ends B' )); 183assert . ok ( ! /MARK-A | A-unique | ends A / . test ( bodyOf ( b . id )), 'chat B holds nothing of chat A' ); 184 185// A second window saves a chat of its own, and then one of this window's chats; this window takes the first over and keeps its own. 186const other = { id :'s_from_other_window' , title :'from window 2' , createdAt :'2026-12-01T00:00:00.000Z' , updatedAt :'2026-12-01T00:00:01.000Z' , messages :[{ id :'o1' , role :'user' , content :'MARK-OTHER-WINDOW' }] }; 187const saved2 = await chatStore . save ( other . id , JSON . stringify ( other )); 188await store . applyChatChange ( other . id , saved2 . rev , false ); 189assert . ok ( store . useStore (( s ) => s . sessions ). some (( s ) => s . id === other . id && s . messages [ 0 ]. content === 'MARK-OTHER-WINDOW' ), 'the chat saved by the other window appears here' ); 190// while a turn is running in chat A here, the other window's save of chat A does not replace it 191store . selectSession ( a . id ); 192const liveSend = store . sendMessage ( 'second question MARK-A2' ); 193await wait ( 3 ); 194const [, , sa2 ] = globalThis . __streams ; 195await chatStore . save ( a . id , JSON . stringify ({ ...JSON . parse ( JSON . stringify ( store . useStore (( s ) => s . sessions ). find (( s ) => s . id === a . id ))), title :'renamed in window 2' })); 196await store . applyChatChange ( a . id , 99 , false ); 197assert . notEqual ( store . useStore (( s ) => s . sessions ). find (( s ) => s . id === a . id ). title , 'renamed in window 2' , 'a chat with a turn running here is not replaced' ); 198sa2 . onFrame ({ type :'done' , tokensIn :1 , tokensOut :1 , durationMs :1 , usageSource :'reported' }); 199sa2 . release (); await liveSend ; 200// the other window deletes its chat 201await chatStore . remove ( other . id ); 202await store . applyChatChange ( other . id , null , true ); 203assert . ok ( ! store . useStore (( s ) => s . sessions ). some (( s ) => s . id === other . id ), 'a chat the other window deleted goes here too' ); 204} finally { fakeHost . restore (); rmSync ( hostDir , { recursive :true , force :true , maxRetries :10 , retryDelay :100 }); } // a save that lands while the folder is removed (ENOTEMPTY, seen on a macOS runner): try again 205});