okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
8667a3dbf
main
1import { useEffect , useSyncExternalStore } from 'react' ; 2import { api , ApiError } from './client' ; 3 4/** 5* A chat's /plan and its queued messages as the host reports them (notes-split-agent6.md, "Backend contract for the ui5 worker"). The plan 6* arrives whole every time it changes, in the chat stream as {type:'plan', event, plan} and as the SSE event 'plan' {chatId, event, plan}; the 7* queue as {type:'queued-message', queue} and the SSE event 'queue' {chatId, queue}. A snapshot replaces what was there; null or an empty 8* list clears it. The host owns both; every button asks it and draws the answer. 9*/ 10export type PlanState = 'proposed' | 'approved' | 'rejected' | 'running' | 'paused' | 'done' | 'stopped' ; 11export type StepState = 'pending' | 'running' | 'done' | 'failed' | 'skipped' ; 12export interface PlanStep { id :string ; text :string ; detail ?:string ; summary ?:string ; state :StepState } 13export interface Plan { id :string ; title :string ; source :'plan' | 'goal' ; state :PlanState ; steps :PlanStep []; /** A plain sentence (an interface string) when the app stopped the planning turn early. */ caution ?:string } 14export interface QueuedMessage { id :string ; text :string ; deliverAt :'step' | 'end' } 15 16const PLAN_STATES = [ 'proposed' , 'approved' , 'rejected' , 'running' , 'paused' , 'done' , 'stopped' ]; 17const STEP_STATES = [ 'pending' , 'running' , 'done' , 'failed' , 'skipped' ]; 18 19export function readPlan ( raw :unknown ) :Plan | null { 20if ( ! raw || typeof raw !== 'object' ) return null ; 21const p = raw as Record < string , unknown >; 22if ( typeof p . id !== 'string' || ! p . id || ! PLAN_STATES . includes ( String ( p . state )) || ! Array . isArray ( p . steps )) return null ; 23const steps :PlanStep [] = []; 24p . steps . forEach (( s , i ) => { 25if ( ! s || typeof s !== 'object' ) return ; 26const r = s as Record < string , unknown >; 27if ( typeof r . text !== 'string' || ! r . text . trim ()) return ; 28steps . push ({ 29id :typeof r . id === 'string' && r . id ?r . id :`s ${ i + 1 } ` , text :r . text , 30state :STEP_STATES . includes ( String ( r . state )) ?r . state as StepState :'pending' , 31 ...( typeof r . detail === 'string' && r . detail ?{ detail :r . detail } :{}), 32 ...( typeof r . summary === 'string' && r . summary ?{ summary :r . summary } :{}), 33}); 34}); 35if ( ! steps . length ) return null ; 36return { id :p . id , title :typeof p . title === 'string' ?p . title :'' , source :p . source === 'goal' ?'goal' :'plan' , state :p . state as PlanState , steps}; 37} 38 39export function readQueue ( raw :unknown ) :QueuedMessage [] { 40if ( ! Array . isArray ( raw )) return []; 41return raw . flatMap (( q ) :QueuedMessage [] => { 42if ( ! q || typeof q !== 'object' ) return []; 43const r = q as Record < string , unknown >; 44return typeof r . id === 'string' && r . id && typeof r . text === 'string' && r . text 45 ?[{ id :r . id , text :r . text , deliverAt :r . deliverAt === 'end' ?'end' :'step' }] :[]; 46}); 47} 48 49const plans = new Map < string , Plan >(); 50const queues = new Map < string , QueuedMessage []>(); 51const listeners = new Set <() => void >(); 52const emit = () => listeners . forEach ( fn => fn ()); 53const subscribe = ( fn :() => void ) => { listeners . add ( fn ); return () => { listeners . delete ( fn ); }; }; 54 55export function applyPlanFrame ( chatId :string , raw :unknown ) { 56const plan = readPlan ( raw ), before = plans . get ( chatId ); 57if ( ! plan ) { if ( plans . delete ( chatId )) emit (); return ; } 58if ( before && JSON . stringify ( before ) === JSON . stringify ( plan )) return ; 59plans . set ( chatId , plan ); 60emit (); 61} 62 63export function applyQueueFrame ( chatId :string , raw :unknown ) { 64const items = readQueue ( raw ), before = queues . get ( chatId ) ?? []; 65if ( JSON . stringify ( before ) === JSON . stringify ( items )) return ; 66if ( items . length ) queues . set ( chatId , items ); else queues . delete ( chatId ); 67emit (); 68} 69 70const NONE :QueuedMessage [] = []; 71export const planOf = ( chatId :string | null | undefined ) :Plan | null => ( chatId ?plans . get ( chatId ) ?? null :null ); 72export const queueOf = ( chatId :string | null | undefined ) :QueuedMessage [] => ( chatId ?queues . get ( chatId ) ?? NONE :NONE ); 73 74export function usePlan ( chatId :string | null | undefined ) :Plan | null { 75const plan = useSyncExternalStore ( subscribe , () => planOf ( chatId ), () => null ); 76useEffect (() => { if ( chatId ) void loadPlan ( chatId ); }, [ chatId ]); 77return plan ; 78} 79 80export function useQueue ( chatId :string | null | undefined ) :QueuedMessage [] { 81const items = useSyncExternalStore ( subscribe , () => queueOf ( chatId ), () => NONE ); 82useEffect (() => { if ( chatId ) void loadQueue ( chatId ); }, [ chatId ]); 83return items ; 84} 85 86export async function loadPlan ( chatId :string ) { 87try { applyPlanFrame ( chatId , ( await api . get <{ plan :unknown }>( `/api/plan?sessionId= ${ encodeURIComponent ( chatId )} ` )). plan ); } 88catch { /* an older host has no plan route: no plan */ } 89} 90 91/** The waiting messages. Without `release` this only reads; the host never sends them from here. */ 92export async function loadQueue ( chatId :string ) { 93try { applyQueueFrame ( chatId , ( await api . get <{ queue :unknown }>( `/api/chat/queue?sessionId= ${ encodeURIComponent ( chatId )} ` )). queue ); } 94catch { /* an older host has no queue route: nothing queued */ } 95} 96 97/** Save the edited steps. Each step keeps its grey detail line when its words did not change. */ 98export async function planEdit ( chatId :string , plan :Plan , texts :string []) { 99const steps = texts . map (( text , i ) => { const was = plan . steps [ i ]; return was && was . text === text && was . detail ?{ text, detail :was . detail } :text ; }); 100const result = await api . post <{ plan :unknown }>( '/api/plan/edit' , { sessionId :chatId , planId :plan . id , steps}); 101applyPlanFrame ( chatId , result . plan ); 102} 103 104export async function planReject ( chatId :string , planId :string ) { 105const result = await api . post <{ plan :unknown }>( '/api/plan/reject' , { sessionId :chatId , planId}); 106applyPlanFrame ( chatId , result . plan ); 107} 108 109/** Approve: the host answers with the plan and the message that carries it out; the caller sends that message as an ordinary turn. */ 110export async function planApprove ( chatId :string , planId :string ) :Promise <{ prompt :string }> { 111const result = await api . post <{ plan :unknown ; prompt :string }>( '/api/plan/approve' , { sessionId :chatId , planId}); 112applyPlanFrame ( chatId , result . plan ); 113return { prompt :String ( result . prompt ?? '' ) }; 114} 115 116/** Put a message behind the running goal. Returns false when no goal is running (409), so the caller can send it the normal way. */ 117export async function queueMessage ( chatId :string , message :string ) :Promise < boolean > { 118try { 119const result = await api . post <{ queue :unknown }>( '/api/chat/queue' , { sessionId :chatId , message}); 120applyQueueFrame ( chatId , result . queue ); 121return true ; 122} catch ( e ) { 123if ( e instanceof ApiError && e . status === 409 ) return false ; 124throw e ; 125} 126} 127 128/** Take a queued message back before it is sent. */ 129export async function cancelQueued ( chatId :string , id :string ) { 130const result = await api . post <{ queue :unknown }>( '/api/chat/queue/cancel' , { sessionId :chatId , id}); 131applyQueueFrame ( chatId , result . queue ); 132} 133 134/** The step the queued message waits for: the one running now, or the next that has not started. 1-based, 0 if there is none. */ 135export function currentStep ( plan :Plan | null ) :number { 136if ( ! plan ) return 0 ; 137const running = plan . steps . findIndex ( s => s . state === 'running' ); 138if ( running >= 0 ) return running + 1 ; 139const next = plan . steps . findIndex ( s => s . state === 'pending' ); 140return next >= 0 ?next + 1 :0 ; 141} 142 143/** The words under a queued message: when it will be sent. The first one goes out after the current step, the next ones after that. */ 144export function queuedWhen ( item :QueuedMessage , index :number , plan :Plan | null ) :{ id :string ; args ?:unknown [] } { 145if ( item . deliverAt === 'end' ) return { id :'Queued — sends when the goal finishes' }; 146if ( index > 0 ) return { id :'Queued — sends after that' }; 147const step = currentStep ( plan ); 148return step > 0 ?{ id :'Queued — sends when step {0} finishes' , args :[ step ] } :{ id :'Queued — sends when the goal finishes' }; 149} 150 151export const stepsDone = ( plan :Plan ) => plan . steps . filter ( s => s . state === 'done' ). length ; 152 153/** The stored plan of a chat without asking the host (the one that asks is usePlan, used once per chat). */ 154export function usePlanQuiet ( chatId :string | null | undefined ) :Plan | null { 155return useSyncExternalStore ( subscribe , () => planOf ( chatId ), () => null ); 156}