okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
4fb068a8c
main
1import { useRef , useState , type ReactNode } from 'react' ; 2import { tr , localeTag } from '../lib/i18n' ; 3import { api } from '../lib/client' ; 4import { go , answerChatTool , continueChatInNewChat , continueTaskInNewChat , dismissChat , selectSession , stopChat , stopLoop } from '../lib/store' ; 5import { pushToast } from '../lib/store' ; 6import { askQuestion } from '../lib/ask' ; 7import { LOOP_MAX_FAILURES , loopEvery } from '../lib/loop' ; 8import { plainFailure } from '../lib/plain-errors' ; 9import { userError } from '../lib/format' ; 10import { type BoardAction , type BoardCard , type BoardColumn , type BoardReason } from '../lib/board' ; 11import { useBoard , refreshBoard } from '../lib/use-board' ; 12import { Btn , Icon , IconBtn , type IconName } from './ui' ; 13import { FloatingMenu } from './FloatingMenu' ; 14 15/** 16* The task board: what is running, what waits for a yes, what found a problem and what finished, in four columns. The cards come from 17* src/lib/board.ts; this file only draws them and calls the same endpoints and store functions the rest of the app uses. Cards are not 18* dragged: they move by themselves when the facts change. 19*/ 20 21const COLUMNS :{ id :BoardColumn ; name :string ; hint ?:string ; tone :'run' | 'wait' | 'bad' | 'done' }[] = [ 22{ id :'running' , name :'Running' , tone :'run' }, 23{ id :'waiting' , name :'Waiting for you' , hint :'Stopped at a question only you can answer.' , tone :'wait' }, 24{ id :'attention' , name :'Needs attention' , hint :'Found a problem. Stays here until you deal with it.' , tone :'bad' }, 25{ id :'done' , name :'Done' , hint :'Finished cleanly in the last 7 days.' , tone :'done' }, 26]; 27 28const ACTION :Record < BoardAction , { label :string ; icon ?:IconName }> = { 29'stop-task' :{ label :'Stop' , icon :'stop' }, 30'run-again' :{ label :'Run again' , icon :'refresh' }, 31'open-task' :{ label :'Open task' , icon :'pencil' }, 32'open-chat' :{ label :'Open chat' , icon :'chat' }, 33'stop-chat' :{ label :'Stop chat' , icon :'stop' }, 34'stop-loop' :{ label :'Stop loop' , icon :'stop' }, 35approve :{ label :'Approve' , icon :'check' }, 36deny :{ label :'Deny' }, 37continue :{ label :'Continue in a new chat' , icon :'chat' }, 38dismiss :{ label :'Dismiss' , icon :'x' }, 39'view-result' :{ label :'View result' }, 40}; 41 42/* ------------------------------------------------------------------ words */ 43 44/** "every 10 min": short enough for a card; whole hours keep the loop's own words ("every hour"). */ 45const everyShort = ( ms :number ) => ( ms % 3_600_000 === 0 || ms < 60_000 ?loopEvery ( ms ) :tr ( 'every {0} min' , [ Math . round ( ms / 60_000 )])); 46 47const span = ( ms :number ) => { 48const min = Math . floor ( ms / 60_000 ); 49if ( min < 1 ) return tr ( 'under 1 min' ); 50if ( min < 60 ) return tr ( '{0} min' , [ min ]); 51if ( min < 48 * 60 ) return tr ( '{0} h' , [ Math . floor ( min / 60 )]); 52return tr ( '{0} d' , [ Math . floor ( min / 1440 )]); 53}; 54const ago = ( ms :number ) => ( ms < 60_000 ?tr ( 'just now' ) :tr ( '{0} ago' , [ span ( ms )])); 55const clock = ( at :number ) => new Date ( at ). toLocaleTimeString ( localeTag (), { hour :'2-digit' , minute :'2-digit' }); 56/** "today 07:00", "yesterday", "Mon 07:00" for a day that has a time on it. */ 57function day ( at :number , now :number ) { 58const d = new Date ( at ), n = new Date ( now ); 59const midnight = ( x :Date ) => new Date ( x . getFullYear (), x . getMonth (), x . getDate ()). getTime (); 60const days = Math . round (( midnight ( n ) - midnight ( d )) / 86_400_000 ); 61if ( days <= 0 ) return tr ( 'today {0}' , [ clock ( at )]); 62if ( days === 1 ) return tr ( 'yesterday' ); 63return d . toLocaleDateString ( localeTag (), { weekday :'short' , day :'numeric' , month :'short' }); 64} 65 66export function cardTime ( card :BoardCard , now :number ) :string { 67switch ( card . timeKind ) { 68case 'started' :return tr ( 'started {0}' , [ ago ( now - card . at )]); 69case 'waiting' :return tr ( 'waiting {0}' , [ span ( now - card . at )]); 70case 'next' :return card . nextAt && card . nextAt > now ?tr ( 'next in {0}' , [ span ( card . nextAt - now )]) :tr ( 'answering now' ); 71case 'stopped' :return tr ( 'stopped {0}' , [ now - card . at < 86_400_000 ?clock ( card . at ) :day ( card . at , now )]); 72default :return card . source === 'task' ?day ( card . at , now ) :now - card . at < 86_400_000 ?ago ( now - card . at ) :day ( card . at , now ); 73} 74} 75 76function ReasonText ({ reason} :{ reason :BoardReason }) { 77let text = '' , raw :string | undefined ; 78switch ( reason . kind ) { 79case 'task-failed' :case 'chat-failed' :{ 80const plain = plainFailure ( reason . detail ?? '' ); 81const known = plain . kind !== 'plain' ; 82text = known ?tr ( plain . message ) :tr ( userError ( String ( reason . detail ?? '' ). slice ( 0 , 240 )) || 'It did not finish.' ); 83// The words a person reads are the sentence; the original text stays one click away for experts. 84raw = known ?( plain . detail ?? reason . detail ) :undefined ; 85if ( ! known && ! reason . detail ) text = tr ( 'It did not finish.' ); 86break ; 87} 88case 'task-stopped' :text = tr ( 'This run was stopped before it finished.' ); break ; 89case 'task-closed' :text = tr ( 'Strata closed while this was running, so it did not finish.' ); break ; 90case 'task-needs-yes' :text = tr ( 'Finished, but wanted to change something and could not ask. Nothing was changed.' ); break ; 91case 'loop-failed' :text = tr ( 'Stopped: {0} runs in a row did not work.' , [ LOOP_MAX_FAILURES ]); break ; 92default :text = reason . ask ?askQuestion ( reason . ask ) :reason . fallback ?? '' ; 93} 94return < span >{ text }{ raw ?< details className = "bcard__detail" >< summary >{ tr ( 'Details' )}</ summary >< pre >{ raw }</ pre ></ details > :null }</ span >; 95} 96 97/* ------------------------------------------------------------------- card */ 98 99function Card ({ card, now, busy, canRun, run, openMenu} :{ card :BoardCard ; now :number ; busy :boolean ; canRun :boolean ; run :( card :BoardCard , action :BoardAction ) => void ; openMenu :( card :BoardCard , anchor :HTMLElement ) => void }) { 100const titleId = `bcard- ${ card . key . replace ( / [^a-z0-9]+ / gi , '-' )} ` ; 101const source = card . source === 'task' ?<>< Icon name = "clock" size = { 14 }/>{ tr ( 'Scheduled task' )}</> :card . source === 'chat' ?<>< Icon name = "chat" size = { 14 }/>{ tr ( 'Chat' )}</> :<>< Icon name = "refresh" size = { 14 }/>{ tr ( 'Loop · {0}' , [ everyShort ( card . everyMs ?? 0 )])}</>; 102const where = card . folder || card . meta ?< div className = "bcard__where" >{ card . folder ?<>< Icon name = "folder" size = { 14 }/>{ card . folder }</> :null }{ card . folder && card . meta ?' · ' :'' }{ card . meta ?tr ( card . meta . text , card . meta . params ) :null }</ div > :null ; 103const button = ( action :BoardAction , variant :'primary' | 'secondary' | 'ghost' ) => { 104const a = ACTION [ action ]; 105const off = busy || ( action === 'run-again' && ! canRun ); 106return < Btn key = { action } size = "sm" variant = { variant } icon = { variant === 'ghost' ?undefined :a . icon } disabled = { off } title = { action === 'run-again' && ! canRun ?tr ( 'Load a model first' ) :undefined } onClick = {() => run ( card , action )}>{ tr ( a . label )}</ Btn >; 107}; 108const iconFor = ( action :BoardAction , label ?:string ) => < IconBtn key = { action } name = { ACTION [ action ]. icon ?? 'x' } title = { tr ( label ?? ACTION [ action ]. label )} disabled = { busy } onClick = {() => run ( card , action )}/>; 109 110let actions :ReactNode ; 111if ( card . column === 'waiting' ) { 112actions = card . approve 113 ?<>{ button ( 'approve' , 'primary' )}{ button ( 'deny' , 'secondary' )}< span className = "spacer" />{ iconFor ( 'open-chat' )}</> 114 :<>{ button ( card . primary , 'secondary' )}</>; 115} else if ( card . column === 'done' ) { 116actions = <>{ card . chip ?< span className = { `bchip ${ card . chip . tone === 'good' ? ' bchip--good' : '' } ` }>< Icon name = "check" size = { 12 }/>{ tr ( card . chip . text )}</ span > :null }< span className = "spacer" />{ button ( card . primary , 'ghost' )}{ iconFor ( 'dismiss' )}</>; 117} else { 118const variant = card . column === 'attention' ?'primary' :'secondary' ; 119actions = <>{ button ( card . primary , variant )}< span className = "spacer" /> 120{ card . menu . length === 1 ?iconFor ( card . menu [ 0 ]) :card . menu . length > 1 121 ?< button type = "button" className = "st-btn st-btn--icon" aria-haspopup = "menu" aria-label = { tr ( 'More actions for {0}' , [ card . title ])} title = { tr ( 'More actions' )} disabled = { busy } onClick = { e => openMenu ( card , e . currentTarget )}>< Icon name = "ellipsis" size = { 19 }/></ button > :null }</>; 122} 123 124return < article className = "bcard" aria-labelledby = { titleId } data-source = { card . source }> 125< div className = "bcard__top" >< span className = "bsrc" >{ source }</ span >< span className = "btime" >{ cardTime ( card , now )}</ span ></ div > 126< h3 className = "bcard__title" id = { titleId }>{ card . title }</ h3 > 127{ where } 128{ card . line ?< p className = "bcard__line" >{ card . line }</ p > :null } 129{ card . reason ?< div className = { `bcard__why bcard__why-- ${ card . reason . tone } ` }>< Icon name = { card . reason . tone === 'bad' ?'error' :card . reason . tone === 'warn' ?'warning' :'shield' } size = { 16 }/>< ReasonText reason = { card . reason }/></ div > :null } 130{ card . busy ?< div className = "bcard__bar bcard__bar--busy" aria-hidden = "true" >< i /></ div > :null } 131< div className = "bcard__actions" >{ actions }</ div > 132</ article >; 133} 134 135/* ------------------------------------------------------------------ board */ 136 137export function TaskBoard ({ query, canRun, onViewResult} :{ query :string ; canRun :boolean ; onViewResult :( taskId :string ) => void }) { 138const { board, ready, tasks} = useBoard (); 139const [ busy , setBusy ] = useState < Record < string , boolean >>({}); 140const [ menu , setMenu ] = useState <{ card :BoardCard ; anchor :HTMLElement } | null >( null ); 141const now = Date . now (); 142const q = query . trim (). toLowerCase (); 143const shown = ( list :BoardCard []) => ( q ?list . filter ( c => ` ${ c . title } ${ c . line ?? '' } ${ c . folder ?? '' } ` . toLowerCase (). includes ( q )) :list ); 144const guard = useRef ( new Set < string >()); 145 146async function run ( card :BoardCard , action :BoardAction ) { 147if ( guard . current . has ( card . key )) return ; 148const task = card . source === 'task' ?tasks . find ( t => t . id === card . id ) :undefined ; 149const local = () => { 150if ( action === 'open-chat' ) { selectSession ( card . id ); go ( 'chat' , card . id ); } 151else if ( action === 'open-task' ) go ( 'tasks' , card . id ); 152else if ( action === 'view-result' ) onViewResult ( card . id ); 153else if ( action === 'stop-chat' ) stopChat ( card . id ); 154else if ( action === 'stop-loop' ) stopLoop ( card . id ); 155else if ( action === 'approve' || action === 'deny' ) { if ( card . approve ) answerChatTool ( card . id , card . approve . messageId , card . approve . toolId , action === 'approve' ); } 156else if ( action === 'continue' ) { if ( task ) continueTaskInNewChat ( task ); else continueChatInNewChat ( card . id ); } 157else if ( action === 'dismiss' && card . source !== 'task' ) dismissChat ( card . id ); 158else return false ; 159return true ; 160}; 161if ( local ()) return ; 162guard . current . add ( card . key ); 163setBusy ( b => ({ ...b , [ card . key ] :true })); 164try { 165if ( action === 'stop-task' ) await api . post ( `/api/tasks/ ${ card . id } /stop` ); 166else if ( action === 'run-again' ) await api . post ( `/api/tasks/ ${ card . id } /run` ); 167else if ( action === 'dismiss' ) await api . patch ( `/api/tasks/ ${ card . id } ` , { ackedAt :new Date (). toISOString () }); 168window . dispatchEvent ( new Event ( 'strata:tasks' )); 169} catch ( e ) { 170pushToast ( 'error' , 'That did not work' , e instanceof Error ?e . message :String ( e )); 171} finally { 172guard . current . delete ( card . key ); 173setBusy ( b => ({ ...b , [ card . key ] :false })); 174refreshBoard (); 175} 176} 177 178const openMenu = ( card :BoardCard , anchor :HTMLElement ) => setMenu ( m => ( m ?. card . key === card . key ?null :{ card, anchor})); 179const total = Object . values ( board . columns ). reduce (( n , c ) => n + c . length , 0 ); 180 181return < div className = "board-wrap" > 182< p className = "sr-only" role = "status" aria-live = "polite" >{ board . need ?tr ( '{0} need your attention' , [ board . need ]) :tr ( 'Nothing needs you right now.' )}</ p > 183< div className = "board" > 184{ COLUMNS . map ( col => { 185const cards = shown ( board . columns [ col . id ]); 186const headId = `bcol- ${ col . id } ` ; 187return < section key = { col . id } className = { `bcol bcol-- ${ col . id } ` } data-tone = { col . tone } aria-labelledby = { headId }> 188< div className = "bcol__head" >< span className = "bcol__dot" aria-hidden = "true" />< h2 className = "bcol__name" id = { headId }>{ tr ( col . name )}</ h2 >< span className = "bcol__count" aria-label = { tr ( '{0} cards' , [ cards . length ])}>{ cards . length }</ span ></ div > 189{ col . hint ?< p className = "bcol__hint" >{ tr ( col . hint )}</ p > :null } 190{ cards . map ( card => < Card key = { card . key } card = { card } now = { now } busy = { !! busy [ card . key ]} canRun = { canRun } run = { run } openMenu = { openMenu }/>)} 191{ ! cards . length ?< p className = "bcol__empty" >{ ready ?tr ( q && total ?'No matching cards.' :'Nothing here right now.' ) :tr ( 'Loading tasks…' )}</ p > :null } 192</ section >; 193})} 194</ div > 195{ board . upcoming . length ?< div className = "upnext" role = "region" aria-label = { tr ( 'Coming up' )}>< Icon name = "clock" size = { 18 }/>< span className = "navgroup__label" >{ tr ( 'Coming up' )}</ span > 196{ board . upcoming . map (( u , i ) => < span className = "upnext__item" key = { u . id }>{ i ?< span className = "sep" aria-hidden = "true" /> :null }< a href = { `#/tasks/ ${ u . id } ` }>{ u . title }</ a > < span className = "i" >{ day ( u . at , now )}</ span ></ span >)}</ div > :null } 197{ menu ?< FloatingMenu anchor = { menu . anchor } title = { tr ( 'More actions for {0}' , [ menu . card . title ])} width = { 230 } onClose = {() => setMenu ( null )}> 198{ menu . card . menu . map ( action => < div key = { action }>{ action === 'dismiss' && menu . card . menu . length > 1 ?< hr className = "board-menu-sep" /> :null }< button type = "button" role = "menuitem" className = "menu__item" onClick = {() => { const card = menu . card ; setMenu ( null ); void run ( card , action ); }}>< Icon name = { ACTION [ action ]. icon ?? 'x' }/>{ tr ( ACTION [ action ]. label )}</ button ></ div >)} 199</ FloatingMenu > :null } 200</ div >; 201}