okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
dca9770ef
main
1import type { Ask } from './ask' ; 2import type { Session , ToolCall } from './types' ; 3import type { Task } from './tasks' ; 4 5/** 6* The task board (Tasks screen, "Board"). One pure function turns what the app already knows (scheduled tasks from the host, chats and 7* their loops from the browser, the approvals the host is holding) into cards in four columns. Nothing here is stored as "board state": 8* a card is where the facts put it, and it moves when the facts change. It never touches the DOM, the store or the clock, so it is tested 9* like loop.ts. 10* 11* One card per thing: a chat shows once, in the first place that fits (waiting for you, running, needs attention, done), and a task 12* shows once. A task or chat the person dismissed stays off the board until a newer run or turn brings a problem back. 13*/ 14 15export type BoardColumn = 'running' | 'waiting' | 'attention' | 'done' ; 16 17/** What a button on a card does. The component maps each one to a call; the order of `menu` is the order shown. */ 18export type BoardAction = 'stop-task' | 'run-again' | 'open-task' | 'open-chat' | 'stop-chat' | 'stop-loop' | 'approve' | 'deny' | 'continue' | 'dismiss' | 'view-result' ; 19 20/** Why a card needs the person. `kind` names the sentence; the component writes it in the person's language. */ 21export interface BoardReason { 22tone :'bad' | 'warn' | 'ask' ; 23kind :'task-failed' | 'task-stopped' | 'task-closed' | 'task-needs-yes' | 'chat-failed' | 'loop-failed' | 'ask' ; 24/** The original error text, for the failures a person can open under Details. */ 25detail ?:string ; 26/** The approval question, for `ask`. */ 27ask ?:Ask ; 28/** What the tool wants to do, when the host sent no question. */ 29fallback ?:string ; 30params ?:( string | number )[]; 31} 32 33export interface BoardCard { 34/** Stable across refreshes: the source and its id. */ 35key :string ; 36column :BoardColumn ; 37source :'task' | 'chat' | 'loop' ; 38/** Task id for a task; chat id for a chat or a loop. */ 39id :string ; 40title :string ; 41/** Milliseconds. What the time on the card is about, and the sort key (newest first). */ 42at :number ; 43timeKind :'started' | 'waiting' | 'next' | 'stopped' | 'plain' ; 44/** For a loop that is running: when its next answer is due. */ 45nextAt ?:number ; 46/** A loop's rhythm in milliseconds, for "Loop · every 10 min". */ 47everyMs ?:number ; 48folder ?:string ; 49/** The muted part after the folder: "2 helpers working", "answer 3 of 6". */ 50meta ?:{ text :string ; params ?:( string | number )[] }; 51line ?:string ; 52reason ?:BoardReason ; 53/** Done cards: the chip beside the button. */ 54chip ?:{ text :string ; tone :'good' | 'plain' }; 55/** A card whose run is going on shows a moving bar. */ 56busy ?:boolean ; 57primary :BoardAction ; 58menu :BoardAction []; 59/** Set on a Waiting card that may be answered from the board (a file read or write inside the chat's folder). */ 60approve ?:{ messageId :string ; toolId :string }; 61} 62 63export interface BoardPending { chatId :string ; callIds :string []; at ?:number ; folder ?:string | null } 64 65export interface BoardInput { 66tasks :readonly Task []; 67sessions :readonly Session []; 68/** Chats with a turn going. */ 69liveChats :readonly string []; 70/** Chats with a /loop going. */ 71loopChats :readonly string []; 72/** What the host holds, per chat. `null` while it is not known (not asked yet or unreachable): the cards in the chats are trusted then. */ 73pending :readonly BoardPending [] | null ; 74activeSession :string | null ; 75now :number ; 76days ?:number ; 77} 78 79export interface BoardResult { 80columns :Record < BoardColumn , BoardCard []>; 81/** Waiting for you plus Needs attention: the number the sidebar shows. */ 82need :number ; 83/** The next scheduled runs. */ 84upcoming :{ id :string ; title :string ; at :number }[]; 85/** Task ids that have a problem the person has not dismissed (the sidebar's dot). */ 86problemTasks :string []; 87} 88 89export const BOARD_DAYS = 7 ; 90const DAY = 86_400_000 ; 91 92const time = ( iso ?:string | null ) => { const n = iso ?Date . parse ( iso ) :NaN ; return Number . isFinite ( n ) ?n :0 ; }; 93 94/** The last folder name of a path: how a chat's working folder is shown on a card. */ 95export function folderName ( path ?:string | null ) :string | undefined { 96const parts = String ( path ?? '' ). split ( / [\\/]+ / ). filter ( Boolean ); 97return parts . length ?parts [ parts . length - 1 ] :undefined ; 98} 99 100const normal = ( p :string ) => p . replace ( / \\ / g , '/' ). replace ( / \/+$ / , '' ); 101 102/** 103* Is `target` inside `folder`? Relative paths count (the agent works in the folder) unless they climb out with "..". Anything else 104* (another drive, another tree, a path that cannot be told) is not: those need the whole conversation in front of the person. 105*/ 106export function isInside ( target :string | undefined | null , folder :string | undefined | null ) :boolean { 107if ( ! target || ! folder ) return false ; 108const t = normal ( String ( target ). trim ()), f = normal ( String ( folder ). trim ()); 109if ( ! t || ! f || t . split ( '/' ). includes ( '..' )) return false ; 110const windows = / ^[a-z]: / i . test ( f ) || String ( folder ). includes ( '\\' ); 111const absolute = / ^([a-z]:)?\/ / i . test ( t ); 112if ( ! absolute ) return ! /^[a-z]: / i . test ( t ); 113const a = windows ?t . toLowerCase () :t , b = windows ?f . toLowerCase () :f ; 114return a === b || a . startsWith ( b + '/' ); 115} 116 117/** Can this waiting card be answered from the board? A file read or write inside the chat's folder; shell commands and connected tools open the chat. */ 118export function canApproveOnBoard ( tool :Pick < ToolCall , 'scope' | 'target' >, folder :string | undefined | null ) :boolean { 119return ( tool . scope === 'read' || tool . scope === 'write' ) && isInside ( tool . target , folder ); 120} 121 122/** One plain line from an answer: markdown off, first sentence (or two when the first is tiny), cut at 160 characters. */ 123export function plainLine ( text :string | undefined | null , max = 160 ) :string { 124let body = String ( text ?? '' ). replace ( / ```[\s\S]*?``` / g , ' ' ). replace ( / !?\[([^\]]*)\]\([^)]*\) / g , '$1' ). replace ( / ^\s*(#{1,6}|[-*+]|\d+[.)]|>)\s+ / gm , '' ). replace ( / [*_`~] / g , '' ); 125body = body . replace ( / \s+ / g , ' ' ). trim (); 126if ( ! body ) return '' ; 127const sentence = / ^.*?[.!?](?=\s|$) / . exec ( body )?.[ 0 ] ?? body ; 128const two = / ^.*?[.!?](?=\s|$)\s*.*?[.!?](?=\s|$) / . exec ( body )?.[ 0 ] ?? body ; 129const pick = sentence . length < 24 && body . length > sentence . length ?two :sentence ; 130return pick . length > max ?` ${ pick . slice ( 0 , max - 1 ). trimEnd ()} …` :pick ; 131} 132 133function lastAssistant ( s :Session ) { 134for ( let i = s . messages . length - 1 ; i >= 0 ; i -- ) { const m = s . messages [ i ]; if ( m . role === 'assistant' && ! ( m as { local ?:boolean }). local ) return m ; } 135return undefined ; 136} 137 138/** Dismissed: the person dismissed it at or after the moment of the thing shown. */ 139const dismissed = ( ackedAt :string | null | undefined , since :number ) => !! ackedAt && time ( ackedAt ) >= since ; 140 141export function boardCards ( input :BoardInput ) :BoardResult { 142const { now} = input , window = ( input . days ?? BOARD_DAYS ) * DAY ; 143const live = new Set ( input . liveChats ), loops = new Set ( input . loopChats ); 144const columns :Record < BoardColumn , BoardCard []> = { running :[], waiting :[], attention :[], done :[] }; 145const problemTasks :string [] = []; 146const upcoming :BoardResult [ 'upcoming' ] = []; 147 148/* ---- scheduled tasks ---- */ 149for ( const t of input . tasks ) { 150if ( t . archived || ! t . id ) continue ; 151const base = { key :`task: ${ t . id } ` , source :'task' as const , id :t . id , title :t . title }; 152const ran = time ( t . lastRunAt ), fin = time ( t . finishedAt ) || ran ; 153if ( t . enabled && t . nextRunAt ) upcoming . push ({ id :t . id , title :t . title , at :time ( t . nextRunAt ) }); 154if ( t . status === 'running' ) { columns . running . push ({ ...base , column :'running' , at :ran , timeKind :'started' , line :plainLine ( t . lastLine ?? '' ) || undefined , busy :true , primary :'stop-task' , menu :[ 'open-task' ] }); continue ; } 155if ( dismissed ( t . ackedAt , fin )) continue ; 156const failed = t . status === 'error' || t . status === 'cancelled' || t . status === 'interrupted' ; 157if ( failed ) { 158problemTasks . push ( t . id ); 159const kind = t . status === 'error' ?'task-failed' :t . status === 'cancelled' ?'task-stopped' :'task-closed' ; 160columns . attention . push ({ ...base , column :'attention' , at :fin || ran , timeKind :'plain' , reason :{ tone :'bad' , kind, ...( t . status === 'error' && t . error ?{ detail :t . error } :{}) }, primary :'run-again' , menu :[ 'open-task' , 'continue' , 'dismiss' ] }); 161} else if ( t . attention ) { 162problemTasks . push ( t . id ); 163// A run that was auto-denied: the useful next step is a chat that can carry on with the person's yes. 164columns . attention . push ({ ...base , column :'attention' , at :fin || ran , timeKind :'plain' , line :plainLine ( t . lastLine ?? t . output ) || undefined , reason :{ tone :'warn' , kind :'task-needs-yes' , detail :t . attention }, primary :'continue' , menu :[ 'open-task' , 'dismiss' ] }); 165} else if ( t . status === 'done' && fin && now - fin <= window ) { 166columns . done . push ({ ...base , column :'done' , at :fin , timeKind :'plain' , line :plainLine ( t . lastLine ?? t . output ) || undefined , chip :{ text :'Finished' , tone :'good' }, primary :'view-result' , menu :[ 'dismiss' ] }); 167} 168} 169 170/* ---- chats and loops ---- */ 171const pendingBy = new Map (( input . pending ?? []). map ( p => [ p . chatId , p ])); 172for ( const s of input . sessions ) { 173if ( s . archived || s . showcase ) continue ; 174const base = { id :s . id , title :s . title , folder :folderName ( s . workspace ) }; 175const answer = lastAssistant ( s ); 176 177// Waiting for you: a card the host still holds. 178const held = pendingBy . get ( s . id ); 179let proposed :{ messageId :string ; tool :ToolCall } | undefined ; 180for ( const m of s . messages ) for ( const tool of m . tools ?? []) if ( tool . live && tool . state === 'proposed' && ( input . pending === null || held ?. callIds . includes ( tool . id ))) { proposed = { messageId :m . id , tool}; break ; } 181if ( proposed ) { 182const { tool, messageId} = proposed ; 183const folder = held ?. folder ?? s . workspace ; 184const ok = canApproveOnBoard ( tool , folder ); 185columns . waiting . push ({ ...base , key :`chat: ${ s . id } ` , source :'chat' , column :'waiting' , at :held ?. at || time ( s . updatedAt ), timeKind :'waiting' , 186reason :{ tone :'ask' , kind :'ask' , ...( tool . ask ?{ ask :tool . ask } :{}), fallback :tool . effect || tool . preview || tool . name }, 187primary :ok ?'approve' :'open-chat' , menu :ok ?[ 'deny' , 'open-chat' ] :[], ...( ok ?{ approve :{ messageId, toolId :tool . id } } :{}) }); 188continue ; 189} 190 191// Running: a loop that is going, or a turn that is. 192if ( loops . has ( s . id ) && s . loop ) { 193const l = s . loop ; 194columns . running . push ({ ...base , key :`loop: ${ s . id } ` , source :'loop' , column :'running' , at :l . startedAt , timeKind :'next' , nextAt :live . has ( s . id ) ?undefined :l . nextAt , everyMs :l . everyMs , title :l . prompt || s . title , 195meta :{ text :l . maxRuns ?'answer {0} of {1}' :'answer {0}' , params :l . maxRuns ?[ l . answers + 1 , l . maxRuns ] :[ l . answers + 1 ] }, line :plainLine ( l . lastText ) || undefined , busy :live . has ( s . id ), primary :'stop-loop' , menu :[ 'open-chat' ] }); 196continue ; 197} 198if ( live . has ( s . id )) { 199const helpers = ( s . agents ?? []). filter ( a => a . status === 'working' ). length ; 200const lastUser = [ ...s . messages ]. reverse (). find ( m => m . role === 'user' ); 201columns . running . push ({ ...base , key :`chat: ${ s . id } ` , source :'chat' , column :'running' , at :time ( lastUser ?. at ) || time ( s . updatedAt ), timeKind :'started' , busy :true , 202 ...( helpers ?{ meta :{ text :helpers === 1 ?'1 helper working' :'{0} helpers working' , params :[ helpers ] } } :{}), line :plainLine ( answer ?. content ) || undefined , primary :'open-chat' , menu :[ 'stop-chat' ] }); 203continue ; 204} 205 206// A loop that ended (or that the window closed on) speaks for the whole chat. 207if ( s . loop ) { 208const l = s . loop ; 209const why = l . state === 'running' ?'closed' :l . endedWhy ?? 'closed' ; 210const when = l . endedAt ?? time ( s . updatedAt ); 211if ( dismissed ( s . ackedAt , when ) || now - when > window ) continue ; 212const common = { ...base , key :`loop: ${ s . id } ` , source :'loop' as const , at :when , timeKind :'stopped' as const , everyMs :l . everyMs , title :l . prompt || s . title , line :plainLine ( l . lastText ) || undefined }; 213if ( why === 'failures' ) columns . attention . push ({ ...common , column :'attention' , reason :{ tone :'bad' , kind :'loop-failed' }, primary :'open-chat' , menu :[ 'continue' , 'dismiss' ] }); 214else columns . done . push ({ ...common , column :'done' , chip :why === 'stopped' ?{ text :'Stopped by you' , tone :'plain' } :why === 'closed' ?{ text :'Stopped when Strata closed' , tone :'plain' } :{ text :'Ended on its own' , tone :'plain' }, primary :'open-chat' , menu :[ 'dismiss' ] }); 215continue ; 216} 217 218// Chats: only what has something to do, in the window. 219const when = time ( s . updatedAt ); 220if ( ! when || now - when > window || dismissed ( s . ackedAt , when ) || ! answer || answer . streaming ) continue ; 221if ( answer . error ) { 222columns . attention . push ({ ...base , key :`chat: ${ s . id } ` , source :'chat' , column :'attention' , at :when , timeKind :'plain' , reason :{ tone :'bad' , kind :'chat-failed' , detail :answer . error }, primary :'open-chat' , menu :[ 'continue' , 'dismiss' ] }); 223continue ; 224} 225const unread = s . id !== input . activeSession && ( s . lastReadAt ?s . updatedAt > s . lastReadAt :s . messages . length > 0 ); 226if ( unread && answer . content ?. trim () && s . messages [ s . messages . length - 1 ] === answer ) { 227columns . done . push ({ ...base , key :`chat: ${ s . id } ` , source :'chat' , column :'done' , at :when , timeKind :'plain' , line :plainLine ( answer . content ) || undefined , chip :{ text :'Finished' , tone :'good' }, primary :'open-chat' , menu :[ 'dismiss' ] }); 228} 229} 230 231for ( const list of Object . values ( columns )) list . sort (( a , b ) => b . at - a . at ); 232upcoming . sort (( a , b ) => a . at - b . at ); 233return { columns, need :columns . waiting . length + columns . attention . length , upcoming :upcoming . slice ( 0 , 5 ), problemTasks}; 234}