okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
5d9f47922
main
1// The chat history's logic (serve/web/history.js) and the browser store behind the saved-chats list (serve/web/chatstore.js), 2// run in Node. The store runs against a small stub of IndexedDB that is faithful where the code depends on it: a read's result 3// is on the request and not on the store; a write the browser refuses fires abort on the transaction; a blocked open never 4// resolves by itself; a database already at version 1 does not run onupgradeneeded; requests answer on a later tick. 5// (The stub and its cases are from PR #1787 by Scotty-Hudson, rebuilt for the split modules.) 6// node serve/test_web_history.js (serve/test_web_history.py runs it too and skips when node is missing) 7"use strict" ; 8const assert = require ( "node:assert/strict" ); 9const path = require ( "node:path" ); 10const H = require ( path . join ( __dirname , "web" , "history.js" )); 11const { createChatStore} = require ( path . join ( __dirname , "web" , "chatstore.js" )); 12 13const user = ( text , extra = {}) => ({ role :"user" , text, time :1 , ...extra }); 14const bot = ( text , extra = {}) => ({ role :"assistant" , text, time :2 , ...extra }); 15const tool = { id :"t1" , name :"fs__read" , result :"secret result" , state :"done" , round :0 , at :0 }; 16const convo = () => [ user ( "q1" , { images :[{ kind :"image" , name :"a.png" , url :"data:image/png;base64,AAA" }], files :[{ kind :"file" , name :"n.txt" , text :"notes" }]}), 17bot ( "a1" , { reasoning :"thoughts" , tools :[ tool ], meta :"12 tokens" , stopped :true , error :"x" }), user ( "q2" ), bot ( "a2" )]; 18 19const cases = { 20titles_and_groups () { 21assert . equal ( H . chatTitle ({ title :"Mine" , messages :[]}), "Mine" ); 22assert . equal ( H . chatTitle ({ title :"" , messages :[ user ( " first line\nsecond" )]}), "first line" ); 23assert . equal ( H . chatTitle ({ title :"" , messages :[ user ( "x" . repeat ( 100 ))]}). length , H . TITLE_MAX ); 24assert . equal ( H . chatTitle ({ title :"" , messages :[]}), "New chat" ); 25assert . equal ( H . chatTitle ({ title :"" , messages :[]}, "Neuer Chat" ), "Neuer Chat" , "the caller's word for an unnamed chat" ); 26const now = Date . UTC ( 2026 , 9 , 26 , 12 ), day = 86400000 ; 27const keys = [ 0 , 0.4 , 1.5 , 5 , 20 , 40 ]. map (( d ) => H . groupKey ( now - d * day , now )); 28assert . deepEqual ( keys , [ "today" , "today" , "yesterday" , "week" , "month" , "older" ]); 29const a = H . newChat ( 1 , 0.5 ), b = H . newChat ( 2 , 0.5 ); 30assert . notEqual ( a . id , b . id ); assert . deepEqual ( a . messages , []); 31}, 32filter_searches_titles_and_text () { 33const chats = [{ id :"a" , title :"the garden" , time :3 , messages :[ user ( "watering the tomatoes" )]}, 34{ id :"b" , title :"a chat about code" , time :2 , messages :[ user ( "nothing here" )]}, 35{ id :"c" , title :"tomatoes again" , time :1 , messages :[ user ( "a different question" )]}]; 36assert . deepEqual ( H . filterChats ( chats , "" ). map (( c ) => c . id ), [ "a" , "b" , "c" ], "newest first" ); 37assert . deepEqual ( H . filterChats ( chats , " TOMATOES " ). map (( c ) => c . id ), [ "a" , "c" ], "title or text, any case" ); 38assert . deepEqual ( H . filterChats ( chats , "nothing here" ). map (( c ) => c . id ), [ "b" ]); 39assert . deepEqual ( H . filterChats ( chats , "zzz" ), []); 40assert . deepEqual ( chats . map (( c ) => c . id ), [ "a" , "b" , "c" ], "the caller's list is not reordered" ); 41}, 42clean_keeps_names_only () { 43const clean = H . cleanMessages ( convo ()); 44assert . deepEqual ( clean [ 0 ]. images , [{ name :"a.png" }]); 45assert . deepEqual ( clean [ 0 ]. files , [{ name :"n.txt" }]); 46assert . ok ( ! JSON . stringify ( clean ). includes ( "data:image" ) && ! JSON . stringify ( clean ). includes ( "notes" ), "no contents in the browser's store" ); 47assert . equal ( clean [ 1 ]. text , "a1" , "the text stays" ); 48assert . deepEqual ( convo ()[ 0 ]. files , [{ kind :"file" , name :"n.txt" , text :"notes" }], "a copy: the screen keeps its contents" ); 49}, 50rewind_a_question () { 51const m = convo (); 52const plan = H . rewind ( m , 2 ); 53assert . deepEqual ( plan . keep . map (( x ) => x . text ), [ "q1" , "a1" ]); 54assert . equal ( plan . hidden , 2 , "the question and its answer" ); 55assert . equal ( plan . draft . text , "q2" ); assert . equal ( plan . draft . lost , 0 ); 56const first = H . rewind ( m , 0 ); 57assert . deepEqual ( first . keep , [], "the first question: nothing stays, the question goes to the box" ); 58assert . equal ( first . draft . text , "q1" ); assert . equal ( first . hidden , 4 ); 59assert . deepEqual ( first . draft . images , [{ kind :"image" , name :"a.png" , url :"data:image/png;base64,AAA" }], "attachments with contents come back" ); 60assert . deepEqual ( first . draft . files , [{ kind :"file" , name :"n.txt" , text :"notes" }]); 61assert . equal ( m . length , 4 , "the list itself is not changed" ); 62}, 63rewind_an_answer () { 64const plan = H . rewind ( convo (), 1 ); 65assert . deepEqual ( plan . keep . map (( x ) => x . text ), [ "q1" , "a1" ], "the answer stays and the list ends with it" ); 66assert . equal ( plan . draft , null ); assert . equal ( plan . hidden , 2 ); 67assert . equal ( H . rewind ( convo (), 3 ). hidden , 0 , "the last answer: nothing to hide" ); 68assert . equal ( H . rewind ( convo (), 9 ), null ); 69}, 70lost_attachments_are_counted () { 71const reloaded = H . cleanMessages ( convo ()); 72assert . equal ( H . lostAttachments ( reloaded [ 0 ]), 2 ); 73assert . equal ( H . lostAttachments ( convo ()[ 0 ]), 0 ); 74const plan = H . rewind ( reloaded , 0 ); 75assert . equal ( plan . draft . lost , 2 ); assert . deepEqual ( plan . draft . images , []); assert . deepEqual ( plan . draft . files , []); 76assert . equal ( plan . draft . text , "q1" , "the text still comes back" ); 77}, 78regenerate_from_the_question () { 79const m = convo (); 80assert . deepEqual ( H . regenerate ( m , 1 ). keep . map (( x ) => x . text ), [ "q1" ]); 81assert . equal ( H . regenerate ( m , 1 ). hidden , 3 ); 82assert . deepEqual ( H . regenerate ( m , 3 ). keep . map (( x ) => x . text ), [ "q1" , "a1" , "q2" ]); 83assert . deepEqual ( H . regenerate ( m , 2 ). keep . map (( x ) => x . text ), [ "q1" , "a1" , "q2" ], "on the last question itself" ); 84assert . equal ( H . regenerate ([ bot ( "orphan" )], 0 ), null , "no question before it" ); 85}, 86edit_an_answer () { 87const plan = H . editAnswer ( convo (), 1 , "corrected" , "Edited" ); 88assert . equal ( plan . keep . length , 2 ); assert . equal ( plan . hidden , 2 ); 89const a = plan . keep [ 1 ]; 90assert . deepEqual ( a , { role :"assistant" , text :"corrected" , time :2 , meta :"Edited" }, "no thinking, tools, error, stop mark or stats" ); 91assert . equal ( H . editAnswer ( convo (), 0 , "x" ), null , "only an answer can be edited" ); 92}, 93branch_is_a_copy_with_a_title_that_stays () { 94const original = { id :"c1" , title :"" , time :1 , messages :convo ()}; 95const plan = H . rewind ( original . messages , 2 ); 96const b = H . branch ( original , plan . keep , plan . keep . length , "Branch of q1" , 5 , 0.25 ); 97assert . deepEqual ( b . messages . map (( x ) => x . text ), [ "q1" , "a1" ]); 98assert . equal ( b . title , "Branch of q1" ); assert . deepEqual ( b . parent , { id :"c1" , title :"q1" }); 99assert . notEqual ( b . id , "c1" ); 100b . messages [ 0 ]. text = "changed" ; b . messages [ 1 ]. tools [ 0 ]. result = "changed" ; 101assert . equal ( original . messages [ 0 ]. text , "q1" , "the original is untouched" ); 102assert . equal ( original . messages [ 1 ]. tools [ 0 ]. result , "secret result" ); 103assert . equal ( H . chatTitle ( H . branch ( original , [], 0 , "Branch of q1" ), "x" ), "Branch of q1" , "a branch at the first message keeps its title" ); 104}, 105}; 106 107// ---------------------------------------------------------------- the stub IndexedDB 108function makeIdb ( hooks = {}, seed = {}) { 109const data = Object . assign ({}, seed ), stores = {}, calls = { upgradeneeded :0 , createObjectStore :0 }; 110let current = null ; 111const request = () => ({ result :null , error :null , transaction :current , onsuccess :null , onerror :null }); 112const store = { 113put ( value ) { 114const req = request (); 115queueMicrotask (() => { 116if ( hooks . quota ) { req . error = { name :"QuotaExceededError" }; req . onerror && req . onerror (); return ; } 117if ( hooks . abort ) return ; 118data [ value . id ] = value ; req . result = value ; req . onsuccess && req . onsuccess (); 119}); 120return req ; 121}, 122delete ( key ) { 123const req = request (); 124queueMicrotask (() => { if ( hooks . quota || hooks . abort ) return ; delete data [ key ]; req . result = true ; req . onsuccess && req . onsuccess (); }); 125return req ; 126}, 127getAll () { 128const req = request (); 129queueMicrotask (() => { if ( hooks . abort ) return ; req . result = Object . values ( data ); req . onsuccess && req . onsuccess (); }); 130return req ; 131}, 132}; 133const transaction = () => { 134const t = { error :null , oncomplete :null , onerror :null , onabort :null , objectStore :() => store }; 135current = t ; 136queueMicrotask (() => { 137if ( hooks . quota || hooks . abort ) { t . error = { name :hooks . quota ?"QuotaExceededError" :hooks . abort }; t . onabort && t . onabort (); } 138else if ( t . oncomplete ) t . oncomplete (); 139}); 140return t ; 141}; 142const db = { objectStoreNames :{ contains :( n ) => n in stores }, createObjectStore :( n ) => { calls . createObjectStore ++ ; stores [ n ] = store ; }, transaction}; 143return { open :() => { 144if ( hooks . throws ) throw new Error ( "private mode" ); 145const r = { result :db , error :null , onupgradeneeded :null , onsuccess :null , onerror :null , onblocked :null }; 146queueMicrotask (() => { 147if ( hooks . blocked ) { r . onblocked && r . onblocked (); return ; } 148if ( hooks . newDatabase !== false ) { calls . upgradeneeded ++ ; r . onupgradeneeded && r . onupgradeneeded (); } 149r . result = db ; r . onsuccess && r . onsuccess (); 150}); 151return r ; 152}, records :data , calls}; 153} 154const wait = () => new Promise (( r ) => setTimeout ( r , 10 )); 155const mk = ( hooks , seed ) => { 156const idb = makeIdb ( hooks , seed ), problems = []; 157return { idb, problems, store :createChatStore ({ indexedDB :idb , onProblem :( k ) => problems . push ( k )})}; 158}; 159const chat = ( id , extra = {}) => ({ id, title :id , time :1 , messages :[ user ( "hi " + id )], ...extra }); 160 161Object . assign ( cases , { 162async store_fresh_database_creates_the_store_and_reads () { 163const a = mk ({}, { c0 :chat ( "c0" ), c1 :chat ( "c1" )}); 164assert . equal ( await a . store . start (), true ); 165assert . equal ( a . idb . calls . upgradeneeded , 1 ); assert . equal ( a . idb . calls . createObjectStore , 1 ); 166assert . deepEqual (( await a . store . all ()). map (( c ) => c . id ). sort (), [ "c0" , "c1" ], "the result is read from the request" ); 167assert . deepEqual ( a . problems , []); 168}, 169async store_put_and_remove_touch_one_record () { 170const a = mk ({}, { c0 :chat ( "c0" )}); 171await a . store . start (); 172a . store . put ( chat ( "c1" , { title :"renamed" })); await wait (); 173assert . equal ( a . idb . records . c1 . title , "renamed" ); assert . ok ( a . idb . records . c0 , "the other record is not rewritten" ); 174a . store . remove ( "c0" ); await wait (); 175assert . ok ( ! ( "c0" in a . idb . records )); 176}, 177async store_private_mode_is_memory_only_and_says_so_once () { 178const a = mk ({ throws :true }); 179assert . equal ( await a . store . start (), false ); 180assert . deepEqual ( a . problems , [ "memory" ]); 181assert . deepEqual ( await a . store . all (), []); 182a . store . put ( chat ( "x" )); a . store . remove ( "x" ); // no store: nothing to do, nothing thrown 183await a . store . start (); 184assert . deepEqual ( a . problems , [ "memory" ], "told once, not on every try" ); 185}, 186async store_missing_object_store_is_memory_only () { 187const a = mk ({ newDatabase :false }); // a database already at version 1: no upgrade, no store 188assert . equal ( await a . store . start (), false ); 189assert . equal ( a . idb . calls . createObjectStore , 0 ); 190assert . deepEqual ( a . problems , [ "memory" ]); 191}, 192async store_blocked_open_does_not_hang () { 193const a = mk ({ blocked :true }); 194assert . equal ( await a . store . start (), false ); 195assert . deepEqual ( a . problems , [ "memory" ]); 196}, 197async store_full_storage_warns_once_with_its_own_message () { 198const a = mk ({ quota :true }); 199await a . store . start (); 200a . store . put ( chat ( "big" )); await wait (); 201a . store . put ( chat ( "big2" )); await wait (); 202assert . deepEqual ( a . problems , [ "quota" ], "one warning, the quota one" ); 203}, 204async store_another_failure_is_not_called_quota () { 205const a = mk ({ abort :"DataError" }); 206await a . store . start (); 207a . store . put ( chat ( "bad" )); await wait (); 208assert . deepEqual ( a . problems , [ "failed" ]); 209}, 210async store_a_read_that_aborts_answers_empty () { 211const a = mk ({ abort :"DataError" }, { c0 :chat ( "c0" )}); 212await a . store . start (); 213assert . deepEqual ( await a . store . all (), [], "no hang, no records" ); 214}, 215}); 216 217( async () => { 218const name = process . argv [ 2 ]; 219const run = name ?[[ name , cases [ name ]]] :Object . entries ( cases ); 220if ( name && ! cases [ name ]) throw new Error ( "unknown test " + name ); 221for ( const [ n , fn ] of run ) { await fn (); console . log ( "ok " + n ); } 222})(). catch (( e ) => { console . error ( e ); process . exitCode = 1 ; });