okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
a1cc285fa
main
1import { tr } from '../lib/i18n' ; 2import { modelFamilyIcon } from '../lib/model-icons' ; 3import { useEffect , useRef , useState } from 'react' ; 4import { FloatingMenu } from './FloatingMenu' ; 5import { DictationControl } from './DictationControl' ; 6import { Btn , Dialog , Icon , ErrorNotice } from './ui' ; 7import { MOD } from '../lib/commands' ; 8import { pushToast , setChatPreferences , useStore } from '../lib/store' ; 9import { artifactFromUrl , type PreviewArtifact } from '../lib/artifacts' ; 10import type { ChatMode , Session } from '../lib/types' ; 11import { attachChatPhoto } from '../lib/chat-photos' ; 12import { uploadChatFile , FILE_ACCEPT } from '../lib/chat-attach-file' ; 13import { useNative } from '../lib/native' ; 14import { pictureStatus } from '../lib/pictures' ; 15const modes :{ 16value :ChatMode ; 17label :string ; 18hint :string ; 19}[] = [ 20{ value :'manual' , label :'Manual' , hint :'Ask before making changes' }, 21{ value :'plan' , label :'Plan' , hint :'Create a plan before making changes' }, 22{ value :'bypass' , label :'Bypass permissions' , hint :'Skip permission prompts' }, 23]; 24const efforts = [ 'Off' , 'Low' , 'Medium' , 'High' , 'Max' ]; 25/** The most tokens a reply may spend thinking (the server's reasoning_budget_tokens); 0 = no limit. */ 26const THINKING_BUDGETS :[ number , string ][] = [[ 0 , 'No limit' ], [ 2048 , '2K' ], [ 8192 , '8K' ], [ 32768 , '32K' ]]; 27const textTypes = / \.(txt|md|markdown|csv|tsx?|jsx?|py|json|css|rs|go|sh|html?|ya?ml|toml|xml|log)$ / i ; 28const photoTypes = / \.(png|jpe?g|webp|gif|svg)$ / i ; 29export function ComposerControls ({ session, onPreview, onAttach, onError, onSlash, streaming, draft, onDraft} :{ 30draft :string ; 31onDraft :( text :string ) => void ; 32session :Session | null ; 33onPreview :( a :PreviewArtifact ) => void ; 34streaming :boolean ; 35onAttach :( name :string , text :string ) => void ; 36onError :( error :string ) => void ; 37onSlash :() => void ; 38}) { 39const remoteModel = useStore ( s => s . remoteModel ); 40const native = useNative (); 41const nativeModel = native ?. instances . find ( i => i . id === native . defaultId ); 42const [ toolsOpen , setToolsOpen ] = useState ( false ); 43const library = useStore ( s => s . library ); 44const loaded = library ?. variants . find ( v => v . id === library . loaded ); 45const remote = useStore ( s => s . remoteModel ), providers = useStore ( s => s . providers ); 46const apiModel = providers ?. connections . find ( c => c . id === remote ?. connectionId )?. models . find ( m => m . id === remote ?. modelId ); 47const [ menu , setMenu ] = useState ( false ), [ preferences , setPreferences ] = useState < 'mode' | 'thinking' | null >( null ), [ reading , setReading ] = useState ( false ); 48 49// The mode menu prints 1–3 beside its rows. They were decoration: make those 50// keys pick the mode while the menu is open, and leave modified keys to the app. 51useEffect (() => { 52if ( preferences !== 'mode' ) 53return ; 54const onKey = ( event :KeyboardEvent ) => { 55if ( event . metaKey || event . ctrlKey || event . altKey ) 56return ; 57const option = modes [ Number ( event . key ) - 1 ]; 58if ( ! option ) 59return ; 60event . preventDefault (); 61setChatPreferences ( session ?. id , { mode :option . value }); 62setPreferences ( null ); 63}; 64window . addEventListener ( 'keydown' , onKey ); 65return () => window . removeEventListener ( 'keydown' , onKey ); 66}, [ preferences , session ?. id ]); 67const [ urlOpen , setUrlOpen ] = useState ( false ), [ url , setUrl ] = useState ( '' ), [ error , setError ] = useState ( '' ); 68const files = useRef < HTMLInputElement >( null ), folder = useRef < HTMLInputElement >( null ), previewFile = useRef < HTMLInputElement >( null ); 69const trigger = useRef < HTMLButtonElement >( null ), modeTrigger = useRef < HTMLButtonElement >( null ), thinkingTrigger = useRef < HTMLButtonElement >( null ); 70const attachLatest = useRef ( onAttach ); 71attachLatest . current = onAttach ; 72const addFilesLatest = useRef <( files :File []) => Promise < void >>( async () => { }); 73// A model on an API takes a reasoning effort when its provider says it can think (OpenRouter's model list); otherwise the provider decides. 74const apiOnlyDefault = !! apiModel && apiModel . thinks !== true ; 75const pictures = pictureStatus ( native , remoteModel , providers ); 76const mode = modes . find ( m => m . value === session ?. preferences ?. mode ) ?? modes [ 0 ]; 77const effort = efforts . includes ( session ?. preferences ?. thinking ?? '' ) ?session ! . preferences ! . thinking ! :'Medium' ; 78const budget = session ?. preferences ?. thinkingBudget ?? 0 ; 79const shortcut = MOD === '⌘' ?'⌘⇧A' :'Ctrl+Shift+A' ; 80async function openFile ( selected :File | undefined ) { 81if ( ! selected ) 82return ; 83if ( selected . size > 20 * 1024 * 1024 ) { 84onError ( 'Choose a file smaller than 20 MB.' ); 85return ; 86} 87const isPdf = / \.pdf$ / i . test ( selected . name ), isImage = photoTypes . test ( selected . name ), isTable = / \.csv$ / i . test ( selected . name ), isCode = / \.(tsx?|jsx?|py|json|css|rs|go|sh)$ / i . test ( selected . name ), isHtml = / \.html?$ / i . test ( selected . name ); 88try { 89onPreview ({ id :crypto . randomUUID (), kind :isPdf ?'pdf' :isImage ?'image' :isTable ?'table' :isCode ?'code' :isHtml ?'website' :'markdown' , title :selected . name , ...( isPdf || isImage ?{ url :URL . createObjectURL ( selected ) } :{ content :await selected . text () }) }); 90} 91catch { 92onError ( 'Could not read the file.' ); 93} 94} 95async function addFiles ( selected :File [], directory = false ) { 96if ( ! selected . length ) 97return ; 98setReading ( true ); 99onError ( '' ); 100const texts :string [] = []; 101let bytes = 0 ; 102let skipped = 0 ; 103try { 104for ( const file of selected . slice ( 0 , 64 )) { 105const path = file . webkitRelativePath || file . name ; 106if ( directory && / (^|\/)(node_modules|\.git|\.strata)(\/|$) / . test ( path )) { 107skipped ++ ; 108continue ; 109} 110if ( ! directory && photoTypes . test ( file . name ) && pictures . ok ) { 111await attachChatPhoto ( file , session ?. id ); 112continue ; 113} 114if ( ! directory && session ?. id && / \.pdf$ / i . test ( file . name ) && file . size <= 12 * 1024 * 1024 ) { 115// A PDF goes to the chat's folder and is named in the next message; "Open a file" still previews it. 116const saved = await uploadChatFile ( file , session . id ); 117pushToast ( 'success' , 'PDF added' , ` ${ saved . name } is in this chat. Ask about it in your next message.` ); 118continue ; 119} 120if ( ! directory && ( photoTypes . test ( file . name ) || / \.pdf$ / i . test ( file . name ))) { 121await openFile ( file ); 122if ( photoTypes . test ( file . name )) 123onError ( ` ${ pictures . ok ? '' : tr ( pictures . message )} ${ tr ( 'It is open in preview.' )} ` ); 124continue ; 125} 126if ( ! textTypes . test ( file . name ) || bytes + file . size > 256 * 1024 ) { 127skipped ++ ; 128continue ; 129} 130const text = await file . text (); 131if ( text . includes ( '\u0000' )) { 132skipped ++ ; 133continue ; 134} 135bytes += file . size ; 136texts . push ( `File: ${ path } \n\n ${ text } ` ); 137} 138if ( texts . length ) 139attachLatest . current ( directory ?( selected [ 0 ]. webkitRelativePath . split ( '/' )[ 0 ] || 'Folder' ) :selected . filter ( f => textTypes . test ( f . name )). map ( f => f . name ). join ( ', ' ), texts . join ( '\n\n' )); 140skipped += Math . max ( 0 , selected . length - 64 ); 141if ( skipped ) 142onError ( ` ${ skipped } file ${ skipped === 1 ? ' was' : 's were' } skipped. Add up to 64 text files, with 256 KB of text in total. Photos and PDFs can be opened separately.` ); 143} 144catch { 145onError ( 'Some files could not be read. Try adding them separately.' ); 146} 147finally { 148setReading ( false ); 149} 150} 151addFilesLatest . current = files => addFiles ( files ); 152useEffect (() => { 153folder . current ?. setAttribute ( 'webkitdirectory' , '' ); 154const key = ( e :KeyboardEvent ) => { 155if ( ! e . defaultPrevented && ( e . metaKey || e . ctrlKey ) && e . shiftKey && ! e . altKey && e . key . toLowerCase () === 'a' && ! document . querySelector ( '.dialog-layer' ) && ! streaming && ! reading ) { 156e . preventDefault (); 157files . current ?. click (); 158} 159}; 160const website = () => { setUrlOpen ( true ); setError ( '' ); }; 161const preview = () => previewFile . current ?. click (); 162const dropped = ( e :Event ) => { if ( ! streaming && ! reading ) void addFilesLatest . current (( e as CustomEvent < File []>). detail ?? []); }; 163window . addEventListener ( 'strata:drop-files' , dropped ); 164window . addEventListener ( 'keydown' , key ); 165window . addEventListener ( 'strata:open-website' , website ); 166window . addEventListener ( 'strata:open-preview' , preview ); 167return () => { window . removeEventListener ( 'strata:drop-files' , dropped ); window . removeEventListener ( 'keydown' , key ); window . removeEventListener ( 'strata:open-website' , website ); window . removeEventListener ( 'strata:open-preview' , preview ); }; 168}, [ streaming , reading ]); 169useEffect (() => { 170if ( preferences !== 'mode' ) 171return ; 172const key = ( e :KeyboardEvent ) => { 173const i = Number ( e . key ) - 1 ; 174if ( i >= 0 && i < modes . length && ! e . metaKey && ! e . ctrlKey && ! e . altKey ) { 175e . preventDefault (); 176setChatPreferences ( session ?. id , { mode :modes [ i ]. value }); 177setPreferences ( null ); 178} 179}; 180window . addEventListener ( 'keydown' , key ); 181return () => window . removeEventListener ( 'keydown' , key ); 182}, [ preferences , session ?. id ]); 183return <> 184{ tr ( ! remoteModel && nativeModel ?. metrics ?. mcp ?. servers ?. length ?< button className = "composer-choice" aria-label = { tr ( "Use connected MCP tools" )} aria-pressed = { session ?. preferences ?. useTools === true } onClick = {() => session ?. preferences ?. useTools ?setChatPreferences ( session . id , { useTools :false }) :setToolsOpen ( true )}>< Icon name = "skills" size = { 16 }/>{ tr ( "Tools" )}{ tr ( session ?. preferences ?. useTools ?' on' :'' )}</ button > :null )} 185< Dialog open = { toolsOpen } compact title = { tr ( "Enable connected tools?" )} onClose = {() => setToolsOpen ( false )} actions = {<>< Btn onClick = {() => setToolsOpen ( false )}>{ tr ( "Keep tools off" )}</ Btn >< Btn variant = "primary" onClick = {() => { setChatPreferences ( session ?. id , { useTools :true , mode :'bypass' }); setToolsOpen ( false ); }}>{ tr ( "Enable tools" )}</ Btn ></>}>< p >{ tr ( "Connected servers can act on the resources you configured. Calls run automatically when the model chooses them, and their results appear in chat." )}</ p >< p className = "small muted" >{ tr ( "This switches this conversation to Bypass permissions. Servers: " )}{ tr (( nativeModel ?. metrics ?. mcp ?. servers ?? []). map (( s :any ) => s . name ). join ( ', ' ))} . </ p ></ Dialog > 186< input ref = { files } type = "file" multiple hidden accept = { FILE_ACCEPT } onChange = { e => { void addFiles ( Array . from ( e . target . files ?? [])); e . target . value = '' ; }}/> 187< input ref = { folder } type = "file" multiple hidden onChange = { e => { void addFiles ( Array . from ( e . target . files ?? []), true ); e . target . value = '' ; }}/> 188< input ref = { previewFile } type = "file" hidden onChange = { e => { void openFile ( e . target . files ?.[ 0 ]); e . target . value = '' ; }}/> 189< button ref = { trigger } className = "composer-add" aria-label = { tr ( "Add or open" )} title = { tr ( "Add or open" )} disabled = { reading || streaming } aria-haspopup = "menu" aria-expanded = { menu } onClick = {() => { setPreferences ( null ); setMenu ( v => ! v ); }}>< Icon name = "plus" size = { 22 }/></ button > 190< DictationControl draft = { draft } onDraft = { onDraft } sessionId = { session ?. id } disabled = { streaming }/> 191< button ref = { modeTrigger } className = "composer-choice composer-mode" aria-label = { tr ( "Mode: {0}" , [ tr ( mode . label )])} aria-haspopup = "menu" aria-expanded = { preferences === 'mode' } onClick = {() => { setMenu ( false ); setPreferences ( v => v === 'mode' ?null :'mode' ); }}>< span >{ tr ( mode . label )}</ span >< Icon name = "chevron" size = { 13 }/></ button > 192< span className = "spacer" /> 193< button ref = { thinkingTrigger } className = "composer-choice composer-effort" disabled = { apiOnlyDefault } title = { tr ( apiOnlyDefault ?"Reasoning uses the API provider’s defaults." :undefined )} aria-label = { tr ( "Reasoning effort: {0}" , [ apiOnlyDefault ?tr ( 'Provider default' ) :effort ])} aria-haspopup = "menu" aria-expanded = { preferences === 'thinking' } onClick = {() => { setMenu ( false ); setPreferences ( v => v === 'thinking' ?null :'thinking' ); }}>< Icon name = "thinking" size = { 16 }/>< span >{ tr ( apiOnlyDefault ?'Default' :effort )}</ span >< Icon name = "chevron" size = { 13 }/></ button > 194{ tr ( menu ?< FloatingMenu anchor = { trigger . current } title = { tr ( "Add or open" )} width = { 292 } onClose = {() => setMenu ( false )}> 195< button role = "menuitem" className = "menu__item" onClick = {() => { setMenu ( false ); files . current ?. click (); }}>< Icon name = "attach" />< span >{ tr ( "Add files or photos" )}</ span >< kbd className = "menu-shortcut" >{ tr ( shortcut )}</ kbd ></ button > 196< button role = "menuitem" className = "menu__item" onClick = {() => { setMenu ( false ); folder . current ?. click (); }}>< Icon name = "folder-plus" />{ tr ( "Add folder" )}</ button > 197< button role = "menuitem" className = "menu__item" onClick = {() => { setMenu ( false ); onSlash (); }}>< span className = "slash-command-icon" aria-hidden = "true" > / </ span >{ tr ( "Slash commands" )}</ button > 198</ FloatingMenu > :null )} 199{ tr ( preferences ?< FloatingMenu anchor = { preferences === 'mode' ?modeTrigger . current :thinkingTrigger . current } title = { tr ( preferences === 'mode' ?'Mode' :'Reasoning effort' )} width = { preferences === 'mode' ?330 :280 } onClose = {() => setPreferences ( null )}> 200{ tr ( preferences === 'mode' ?<>{ tr ( modes . map (( option , index ) => < button key = { option . value } role = "menuitemradio" aria-checked = { mode . value === option . value } className = "menu__item composer-mode-option" onClick = {() => { setChatPreferences ( session ?. id , { mode :option . value }); setPreferences ( null ); }}>< span >< strong >{ tr ( option . label )}</ strong >< small >{ tr ( option . hint )}</ small ></ span >{ tr ( mode . value === option . value ?< Icon name = "check" size = { 16 }/> :null )}< kbd className = "menu-shortcut" >{ tr ( index + 1 )}</ kbd ></ button >))}</> :<>< div className = "reasoning-menu-model" >< Icon name = { apiModel ?'link' :modelFamilyIcon ( loaded ?. family ?? nativeModel ?. label )} size = { 18 }/>< strong >{ tr ( apiModel ?. name ?? ( nativeModel && nativeModel . status === 'ready' ?nativeModel . label :null ) ?? loaded ?. family ?? 'No model loaded' )}</ strong ></ div >< p className = "composer-menu-heading" >{ tr ( "Reasoning effort" )}</ p >{ tr ( efforts . map ( option => < button key = { option } role = "menuitemradio" aria-checked = { effort === option } className = "menu__item" onClick = {() => { setChatPreferences ( session ?. id , { thinking :option }); setPreferences ( null ); }}>{ tr ( option )}< span className = "spacer" />{ tr ( effort === option ?< Icon name = "check" size = { 16 }/> :null )}</ button >))}{ tr ( apiModel ?null :<>< p className = "composer-menu-heading" >{ tr ( "Thinking budget" )}</ p >{ tr ( THINKING_BUDGETS . map (([ value , label ]) => < button key = { value } role = "menuitemradio" aria-checked = { budget === value } disabled = { effort === 'Off' } className = "menu__item" onClick = {() => { setChatPreferences ( session ?. id , { thinkingBudget :value }); setPreferences ( null ); }}>{ tr ( label )}< span className = "spacer" />{ tr ( budget === value ?< Icon name = "check" size = { 16 }/> :null )}</ button >))}</>)}</>)} 201</ FloatingMenu > :null )} 202 203< Dialog open = { urlOpen } title = { tr ( "Open a website" )} onClose = {() => setUrlOpen ( false )} actions = {<>< Btn onClick = {() => setUrlOpen ( false )}>{ tr ( "Cancel" )}</ Btn >< Btn variant = "primary" disabled = { ! url . trim ()} onClick = {() => { 204const a = artifactFromUrl ( url . trim ()); 205if ( ! a || ! /^https?:\/\/ / i . test ( url . trim ())) { 206setError ( 'Enter a full http:// or https:// address.' ); 207return ; 208} 209onPreview ( a ); 210setUrlOpen ( false ); 211setUrl ( '' ); 212}}>{ tr ( "Open preview" )}</ Btn ></>}>< div className = "form-stack" >< label className = "input-field" >< span >{ tr ( "Website address" )}</ span >< input className = "st-input" type = "url" aria-invalid = { !! error } value = { url } onChange = { e => { setUrl ( e . target . value ); setError ( '' ); }} placeholder = { tr ( "https://example.com" )}/></ label >{ tr ( error ?< ErrorNotice message = { error }/> :null )}</ div ></ Dialog > 213</>; 214}