okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
e9a1215f0
main
1import { workspaceIdForSession } from './session-workspace' ; 2import { shortTitle } from './title-text' ; 3import { DEFAULT_CONTENT_FS , DEFAULT_UI_SCALE , SIZE_DEFAULTS_VERSION , savedSizes } from './default-sizes' ; 4import { detectLanguage } from './language-detect' ; 5import { validWhileBusy , type WhileBusy } from './while-busy' ; 6import { addToQuotes , type Quote } from './quotes' ; 7import { readAsk , type AgentAnswer , type AgentAsk } from './agent-ask' ; 8import { plainFailure , plainFailureText } from './plain-errors' ; 9import { showcaseMessages , SHOWCASE_AGENTS } from './chat-showcase' ; 10import { settleAgents , updateAgent } from './agents' ; 11import { LOOP_USAGE , parseLoop , type LoopCommand } from './loop' ; 12import { LoopScheduler } from './loop-runner' ; 13import { applyStatusFrame , clearStatus } from './live-status' ; 14import { approvalNeeded , questionAsked , workFinished } from './attention' ; 15import { applyGoalFrame } from './goal' ; 16import { tidyAnswer } from './answer-text' ; 17import { appendText , mergeDeliverable , readDeliverable , readGroup , readSkills , upsertGroup } from './deliverables' ; 18import { applyPlanFrame , applyQueueFrame , planApprove , queueMessage } from './plan' ; 19import { forkFields , isForkJob , TIME_SKIP_DURATION , timeSkipPrompt , timeSkipTabId , withTimeSkipResult , type TimeSkipFile , type TimeSkipJob , type TimeSkipRun , type TimeSkipVersion } from './time-skip' ; 20import { PREVIEW_EXAMPLES , type PreviewArtifact } from './artifacts' ; 21import { lifecyclePolicy } from './lifecycle' ; 22import { newestServingState } from './serving-state' ; 23import { photoData , uploadChatPhotos , photoHistorySlots , pendingChatPhotos , takeChatPhotos } from './chat-photos' ; 24import { applyNativeEvent , nativeState } from './native' ; 25import { pictureStatus } from './pictures' ; 26import { noModelNotice } from './no-model' ; 27import { taskHandoverMessage , taskHandoverTitle , chatHandoverMessage , chatHandoverTitle } from './task-handover' ; 28import type { Task } from './tasks' ; 29import { postWithFolderFallback } from './folder-pick' ; 30import { createSessionWriter , exportSessions , readBrowserSessions , HOST_FLAG_KEY , PENDING_KEY , type SaveResult , type StorageLike } from './session-persist' ; 31import { createHttpTransport , hydrateChats , keepLastMomentCopy , WINDOW_ID } from './chat-sync' ; 32import { copyText } from './clipboard' ; 33import { catalogLoaded , loadCatalog , setTranslationLanguage , tr , validLanguage , type Language } from './i18n' ; 34/** 35* Strata app store. 36* 37* A single immutable state object + a tiny subscribe/emit pair, consumed through 38* useSyncExternalStore. Data comes from the engine host over /api; live updates 39* arrive on the event stream. No state library, no dependencies. 40*/ 41import { useSyncExternalStore } from 'react' ; 42import { api , ApiError , onEvent , streamPost , type StreamEvent } from './client' ; 43import type { 44Workspace , 45ChatMessage , 46ToolCall , 47EngineConfig , 48Hardware , 49ModelLibrary , 50RuntimeModels , 51ImageModelLibrary , 52ImageModelChoice , 53ModelProviders , 54ModelConnectionDraft , 55RemoteModelSelection , 56MonitorState , 57ServingState , 58Session , 59SetupState , 60Skill , 61WorkspaceFile , 62ToolDraft , 63} from './types' ; 64import { navigate , type Route } from './router' ; 65import { estimate , execution , contextTokens } from './experience' ; 66 67export interface Toast { 68id :string ; 69tone :'info' | 'success' | 'warn' | 'error' ; 70title :string ; 71body ?:string ; 72leaving ?:boolean ; 73/** A button under the text. A toast with one stays until it is dismissed. */ 74action ?:{ label :string ; run :() => void }; 75} 76 77export interface AppState { 78language :Language ; 79fontFamily :string ; 80configDraft :string | null ; 81navOpen :boolean ; 82ready :boolean ; 83connection :'connecting' | 'live' | 'offline' ; 84theme :'dark' | 'light' | 'system' ; 85contrast :'standard' | 'increased' ; 86rail :boolean ; 87/** Distraction-free reading: chrome recedes, the transcript narrows. */ 88focus :boolean ; 89/** Conversation prose size in px, 10–22. Does not touch the UI chrome. */ 90contentFontSize :number ; 91density :'comfortable' | 'compact' ; 92motion :'system' | 'full' | 'reduced' ; 93/** Translucent materials, or flat surfaces for anyone who prefers them. */ 94transparency :'translucent' | 'opaque' ; 95/** Chrome scale, independent of the conversation's reading size. */ 96uiScale :number ; 97/** Price of one kWh for the Monitor's cost line (0 = not set) and the currency the person picked instead of the detected one ('' = automatic) (#3628). */ 98electricityPrice :number ; 99electricityCurrency :string ; 100/** Opt-in: a short sound when a task finishes (#3586). */ 101doneSound :boolean ; 102/** Opt-in: a desktop notification when Manual mode waits for an approval (#3477). */ 103approvalNotify :boolean ; 104/** What Enter does while an answer is being written: wait, send after, or interrupt (#4783). */ 105whileBusy :WhileBusy ; 106/** Governs anonymous usage reporting. Nothing is sent in this build; the 107* choice is recorded so a version that does offer it starts from it. */ 108shareTelemetry :boolean ; 109paletteOpen :boolean ; 110shortcutsOpen :boolean ; 111settingsSection :'Appearance' | 'Models' | 'Tools' | 'Storage' | 'Engine' | 'About' ; 112hardware :Hardware | null ; 113library :ModelLibrary | null ; 114imageModels :ImageModelLibrary | null ; 115runtime :RuntimeModels | null ; 116providers :ModelProviders | null ; 117remoteModel :RemoteModelSelection | null ; 118engine :EngineConfig | null ; 119serving :ServingState | null ; 120monitor :MonitorState | null ; 121setup :SetupState | null ; 122skills :Skill []; 123files :WorkspaceFile []; 124workspacePath :string ; 125workspaces :Workspace []; 126/** Id of the workspace the file tree is scoped to. */ 127activeWorkspace :string | null ; 128/** First run, and "run setup again", both present the wizard as a modal. */ 129setupOpen :boolean ; 130sessions :Session []; 131activeSession :string | null ; 132streaming :boolean ; 133/** Messages the person sent while an answer was being written, waiting to go when it ends (Send after, Interrupt), by chat (#4783). */ 134parked :Record < string , string []>; 135/** The passages quoted into the message being written, by chat, in the order they were quoted (#4785). */ 136quotes :Record < string , Quote []>; 137/** The questions the agent asked the person and is waiting for, by chat (#4244). */ 138agentAsks :Record < string , AgentAsk []>; 139/** Chats with a turn in flight. `streaming` is about the open chat; this is about all of them. */ 140liveChats :number ; 141toasts :Toast []; 142/** Files the model has been granted read access to, and when. */ 143touchedPaths :Record < string , string >; 144/** The last action that failed, kept until it is retried or dismissed. 145* A toast disappears after five seconds; a failure the reader has not dealt 146* with should not. */ 147actionError :{ message :string ; label :string ; retry :() => void } | null ; 148busy :Record < string , boolean >; 149/** Set while the host cannot write some chats (disk full, no permission); null when every chat is saved (#5192). 150* The chats stay whole in memory and are tried again at every save; `unsavedSessionsJson()` gives them as text. 151* A host that does not answer is not this: those saves are simply retried. */ 152sessionSave :{ failedIds :string []; reason :'disk-full' | 'permission' | 'other' } | null ; 153} 154 155const PREFS_KEY = 'strata.prefs.v2' ; 156/** What the model has been allowed to read, kept across restarts. */ 157const TOUCHED_KEY = 'strata.touched.v1' ; 158/** Kept one release so downgrading does not lose the theme and sidebar state. */ 159const PREFS_KEY_V1 = 'strata.prefs.v1' ; 160 161const CONTENT_FS_MIN = 10 ; 162const CONTENT_FS_MAX = 22 ; 163 164export interface Prefs { 165/** Which default sizes this save was made with (see SIZE_DEFAULTS_VERSION). */ 166sizeDefaults ?:number ; 167language :Language ; 168fontFamily :string ; 169theme :'dark' | 'light' | 'system' ; 170contrast :'standard' | 'increased' ; 171rail :boolean ; 172focus :boolean ; 173contentFontSize :number ; 174density :'comfortable' | 'compact' ; 175motion :'system' | 'full' | 'reduced' ; 176transparency :'translucent' | 'opaque' ; 177uiScale :number ; 178electricityPrice :number ; 179electricityCurrency :string ; 180doneSound :boolean ; 181approvalNotify :boolean ; 182/** What Enter does while an answer is being written: wait, send after, or interrupt (#4783). */ 183whileBusy :WhileBusy ; 184/** Governs anonymous usage reporting. Nothing is sent in this build; the 185* choice is recorded so a version that does offer it starts from it. */ 186shareTelemetry :boolean ; 187} 188 189const PREFS_DEFAULTS :Prefs = { 190language :'en' , 191fontFamily :'' , 192theme :'system' , 193contrast :'standard' , 194rail :false , 195focus :false , 196contentFontSize :DEFAULT_CONTENT_FS , 197density :'comfortable' , 198motion :'system' , 199transparency :'translucent' , 200uiScale :DEFAULT_UI_SCALE , 201electricityPrice :0 , 202electricityCurrency :'' , 203doneSound :false , 204approvalNotify :false , 205whileBusy :'wait' , 206shareTelemetry :false , 207}; 208 209function uid ( prefix = 'id' ) :string { 210return ` ${ prefix } _ ${ Math . random (). toString ( 36 ). slice ( 2 , 10 )} ${ Date . now (). toString ( 36 ). slice ( - 4 )} ` ; 211} 212 213/** localStorage, looked up at each call (it may not exist when this file is loaded outside a browser). */ 214const browserStorage :StorageLike = { 215getItem :key => localStorage . getItem ( key ), 216setItem :( key , value ) => localStorage . setItem ( key , value ), 217removeItem :key => localStorage . removeItem ( key ), 218key :index => localStorage . key ( index ), 219get length () { return localStorage . length ; }, 220}; 221/** A chat as the page works with it: a reply that was streaming when the page went away is marked interrupted, not left running. */ 222function fixSession ( session :Session ) :Session { 223return { 224 ...session , 225 ...( session . showcase && ! session . showcaseAgentStates ?{ agents :SHOWCASE_AGENTS , showcaseAgentStates :true } :{}), 226 ...( ! session . showcase && session . agents ?{ agents :settleAgents ( session . agents ) } :{}), 227messages :( session . messages ?? []). map ( message => message . streaming ?{ 228 ...message , 229streaming :false , 230error :message . error ?? 'Response interrupted. Ask again to retry; the partial answer is kept.' , 231} :message ), 232}; 233} 234 235/** 236* The chats shown before the host has answered. Once the browser's chats were handed to the host (the flag) the host's files are the only 237* truth and the page starts empty until it has read them (the boot screen is up until then); before that, and when the host cannot be 238* asked, the browser's old copy is shown. It is only ever read. 239*/ 240function loadSessions () :Session [] { 241try { 242if ( browserStorage . getItem ( HOST_FLAG_KEY ) === '1' ) return []; 243return readBrowserSessions ( browserStorage ). sessions . map ( fixSession ); 244} catch { 245return []; 246} 247} 248 249/** 250* v2 adds focus, reading size, density and the motion override. A v1 blob (only 251* theme and rail) is read as-is and upgraded on the next write, so the first run 252* after this change keeps the user's theme instead of resetting it. 253*/ 254function loadPrefs () :Prefs { 255for ( const key of [ PREFS_KEY , PREFS_KEY_V1 ]) { 256try { 257const raw = localStorage . getItem ( key ); 258if ( ! raw ) continue ; 259const parsed = JSON . parse ( raw ) as Partial < Prefs >; 260return { 261 ...PREFS_DEFAULTS , 262 ...parsed , 263language :validLanguage ( parsed . language ) ?parsed . language :'en' , 264fontFamily :typeof parsed . fontFamily === 'string' ?parsed . fontFamily . slice ( 0 , 128 ). replace ( / [\x00-\x1f] / g , '' ) :'' , 265 ...savedSizes ( parsed , CONTENT_FS_MIN , CONTENT_FS_MAX ), 266sizeDefaults :SIZE_DEFAULTS_VERSION , 267electricityPrice :Number . isFinite ( Number ( parsed . electricityPrice )) && Number ( parsed . electricityPrice ) > 0 && Number ( parsed . electricityPrice ) < 1000 ?Number ( parsed . electricityPrice ) :0 , 268electricityCurrency :typeof parsed . electricityCurrency === 'string' && / ^[A-Za-z]{3}$ / . test ( parsed . electricityCurrency ) ?parsed . electricityCurrency . toUpperCase () :'' , 269doneSound :parsed . doneSound === true , 270approvalNotify :parsed . approvalNotify === true , 271whileBusy :validWhileBusy ( parsed . whileBusy ) ?parsed . whileBusy :'wait' , 272}; 273} catch { 274/* fall through to the next key */ 275} 276} 277// Nothing saved: a first start. It opens in the language of the computer; a choice made on the first screen is saved like any other. 278const tags = typeof navigator === 'undefined' ?[] :navigator . languages ?. length ?navigator . languages :[ navigator . language ]; 279return { ...PREFS_DEFAULTS , language :detectLanguage ( tags ) ?? 'en' }; 280} 281 282const prefs = loadPrefs (); 283// Use the saved language for the very first render, before host bootstrap (main.tsx waits for its strings before it draws). 284void setTranslationLanguage ( prefs . language ); 285 286/** The last approval question a notification was shown for, so one question is announced once. */ 287let lastApprovalNotice = '' ; 288 289let state :AppState = { 290language :prefs . language , 291fontFamily :prefs . fontFamily , 292configDraft :(() => { try { return sessionStorage . getItem ( 'strata.config-draft.v1' ); } catch { return null ; } })(), 293navOpen :false , 294ready :false , 295connection :'connecting' , 296shareTelemetry :prefs . shareTelemetry , 297theme :prefs . theme , 298contrast :prefs . contrast , 299rail :prefs . rail , 300focus :prefs . focus , 301contentFontSize :prefs . contentFontSize , 302density :prefs . density , 303motion :prefs . motion , 304transparency :prefs . transparency , 305uiScale :prefs . uiScale , 306electricityPrice :prefs . electricityPrice , 307electricityCurrency :prefs . electricityCurrency , 308doneSound :prefs . doneSound , 309approvalNotify :prefs . approvalNotify , 310whileBusy :prefs . whileBusy , 311parked :{}, 312quotes :{}, 313agentAsks :{}, 314paletteOpen :false , 315shortcutsOpen :false , 316settingsSection :'Appearance' , 317hardware :null , 318library :null , 319imageModels :null , 320runtime :null , 321providers :null , 322/** The open chat's API model, or null for the local model (the default for every chat). */ 323remoteModel :null , 324engine :null , 325serving :null , 326monitor :null , 327setup :null , 328skills :[], 329files :[], 330workspacePath :'' , 331workspaces :[], 332activeWorkspace :null , 333setupOpen :false , 334sessions :loadSessions (), 335sessionSave :null , 336activeSession :null , 337streaming :false , 338liveChats :0 , 339toasts :[], 340touchedPaths :(() => { 341try { 342return JSON . parse ( localStorage . getItem ( TOUCHED_KEY ) ?? '{}' ) as Record < string , string >; 343} catch { 344return {}; 345} 346})(), 347actionError :null , 348busy :{}, 349}; 350 351const listeners = new Set <() => void >(); 352 353/** Chats with a turn in flight: the abort handle, and whether the host is running it as an agent turn. */ 354const liveTurns = new Map < string , { abort :AbortController ; agent :boolean }>(); 355 356function set ( patch :Partial < AppState > | (( s :AppState ) => Partial < AppState >)) { 357const before = state . activeSession ; 358const next = typeof patch === 'function' ?patch ( state ) :patch ; 359state = { ...state , ...next }; 360// Opening another chat shows that chat's model choice and whether that chat is mid-turn. 361if ( state . activeSession !== before ) { 362const chosen = state . sessions . find ( s => s . id === state . activeSession )?. preferences ?. remoteModel ?? null ; 363state = { ...state , remoteModel :'remoteModel' in next ?state . remoteModel :chosen , streaming :!! state . activeSession && liveTurns . has ( state . activeSession ) }; 364} 365for ( const l of listeners ) l (); 366} 367 368function subscribe ( l :() => void ) { 369listeners . add ( l ); 370return () => listeners . delete ( l ); 371} 372 373export function getState () :AppState { 374return state ; 375} 376 377export function setConfigDraft ( configDraft :string | null ) { 378set ({ configDraft}); 379try { 380if ( configDraft === null ) sessionStorage . removeItem ( 'strata.config-draft.v1' ); 381else sessionStorage . setItem ( 'strata.config-draft.v1' , configDraft ); 382} catch { /* Keep the session draft even when browser storage is unavailable. */ } 383} 384 385export function setNavOpen ( navOpen :boolean ) { set ({ navOpen}); } 386export function setSettingsSection ( settingsSection :AppState [ 'settingsSection' ]) { set ({ settingsSection}); } 387 388/** Choose the open chat's model: an API model, or null for the local one. Other chats keep theirs. */ 389export function selectRemoteModel ( remoteModel :RemoteModelSelection | null ) { 390if ( state . streaming ) return ; 391if ( remoteModel && ! state . providers ?. connections . some ( c => c . id === remoteModel . connectionId && c . models . some ( m => m . id === remoteModel . modelId ))) return ; 392set ({ remoteModel}); 393const id = state . activeSession ; 394if ( id ) patchSession ( id , s => ({ ...s , preferences :{ ...s . preferences , remoteModel} })); 395try { localStorage . removeItem ( 'strata.remote-model.v1' ); } catch { /* The old global choice is retired. */ } 396} 397function applyProviders ( providers :ModelProviders ) { 398// A chat whose API model was removed keeps its choice: the next send says the model is gone, rather 399// than quietly answering from the local model. 400set ({ providers}); 401} 402export async function saveModelConnection ( draft :ModelConnectionDraft ) { 403applyProviders ( await api . post < ModelProviders >( '/api/model-providers' , draft )); 404} 405export async function removeModelConnection ( id :string ) { 406applyProviders ( await api . del < ModelProviders >( `/api/model-providers/ ${ encodeURIComponent ( id )} ` )); 407} 408 409function libraryResponse ( data :ModelLibrary ) :ModelLibrary { 410if ( ! data || ! Array . isArray ( data . variants )) throw new Error ( 'The engine returned an incomplete model list. Retry the operation.' ); 411return data ; 412} 413 414export function lifecycleStatus ( s = state ) { 415return lifecyclePolicy ({ connected :s . connection === 'live' , streaming :!! s . streaming || s . liveChats > 0 , stats :s . serving ?. stats , busy :s . busy }); 416} 417/** The lifecycle status without subscribing to the whole store: a screen that only needs this must not redraw on every monitor tick (round 8, item 13). */ 418export function useLifecycle () { 419const connected = useStore ( s => s . connection === 'live' ); 420const streaming = useStore ( s => !! s . streaming || s . liveChats > 0 ); 421const stats = useStore ( s => s . serving ?. stats ); 422const busy = useStore ( s => s . busy ); 423return lifecyclePolicy ({ connected, streaming, stats, busy}); 424} 425export function lifecycleAvailable () :boolean { 426const result = lifecycleStatus (); 427if ( ! result . allowed ) pushToast ( 'warn' , 'Model change unavailable' , result . reason ); 428return result . allowed ; 429} 430 431export function useStore < T > ( selector :( s :AppState ) => T ) :T { 432return useSyncExternalStore ( 433subscribe , 434() => selector ( state ), 435() => selector ( state ), 436); 437} 438 439/* ------------------------------------------------------------------ toasts */ 440 441/** Dismissal timers, held so a hovered toast can be paused rather than lost. */ 442const toastTimers = new Map < string , ReturnType < typeof setTimeout >>(); 443const TOAST_MS = 5200 ; 444 445export function pushToast ( tone :Toast [ 'tone' ], title :string , body ?:string , action ?:Toast [ 'action' ]) :string { 446const id = uid ( 'toast' ); 447// Cap the stack: past three, the oldest collapses rather than pushing the 448// rest off-screen. A toast nobody can read is not a notification. 449const next = [ ...state . toasts , { id, tone, title, body, ...( action ?{ action} :{}) }]; 450const overflow = next . length > 3 ?next . slice ( 0 , next . length - 3 ) :[]; 451for ( const gone of overflow ) { 452const t = toastTimers . get ( gone . id ); 453if ( t ) clearTimeout ( t ); 454toastTimers . delete ( gone . id ); 455} 456const kept = overflow . length ?next . slice ( - 3 ) :next ; 457set ({ toasts :kept }); 458if ( ! action ) toastTimers . set ( id , setTimeout (() => dismissToast ( id ), TOAST_MS )); 459return id ; 460} 461 462/** 463* Stops a toast's clock while the pointer is over it, so reading one does not 464* race its own dismissal. Restarting gives a full window rather than the 465* remainder — the intent is "I am reading this", and a resumed half-second is 466* not enough to act on. 467*/ 468export function holdToast ( id :string ) { 469const t = toastTimers . get ( id ); 470if ( t ) clearTimeout ( t ); 471toastTimers . delete ( id ); 472} 473 474export function releaseToast ( id :string ) { 475if ( toastTimers . has ( id )) return ; 476if ( ! state . toasts . some (( t ) => t . id === id && ! t . leaving )) return ; 477toastTimers . set ( id , setTimeout (() => dismissToast ( id ), TOAST_MS )); 478} 479 480export function dismissToast ( id :string ) { 481const t = toastTimers . get ( id ); 482if ( t ) clearTimeout ( t ); 483toastTimers . delete ( id ); 484set (( s ) => ({ toasts :s . toasts . map (( x ) => ( x . id === id ?{ ...x , leaving :true } :x )) })); 485setTimeout (() => set (( s ) => ({ toasts :s . toasts . filter (( x ) => x . id !== id ) })), 340 ); 486} 487 488/* ------------------------------------------------------------------- prefs */ 489 490/** 491* Preferences live on <html> as data attributes plus one custom property, so CSS 492* owns presentation and React owns state — the same split the theme already 493* used. Nothing here re-renders a screen: the attributes do the work. 494*/ 495function applyPrefs () { 496const root = document . documentElement ; 497void setTranslationLanguage ( state . language ); 498root . lang = state . language === 'zh' ?'zh-CN' :state . language ; 499if ( state . fontFamily ) root . style . setProperty ( '--st-font' , ` ${ JSON . stringify ( state . fontFamily )} ,system-ui,-apple-system,"Segoe UI",sans-serif` ); 500else root . style . removeProperty ( '--st-font' ); 501root . dataset . theme = state . theme === 'system' ?matchMedia ( '(prefers-color-scheme: dark)' ). matches ?'dark' :'light' :state . theme ; 502document . querySelector < HTMLMetaElement >( 'meta[name="theme-color"]' )?. setAttribute ( 'content' , root . dataset . theme === 'dark' ?'#0e1113' :'#f9fafb' ); 503root . dataset . contrast = state . contrast ; 504root . dataset . density = state . density ; 505root . style . setProperty ( '--st-content-fs' , ` ${ state . contentFontSize } px` ); 506// The interface size (#3970): the whole page is scaled, so every text, button, menu and dialog follows, not only the parts that were 507// written with the scale token. The token stays at 1 so nothing is scaled twice. The reading size stays separate: someone who needs 508// larger prose does not necessarily want larger buttons. 509root . style . setProperty ( '--st-ui-scale' , '1' ); 510root . style . setProperty ( 'zoom' , state . uiScale === 1 ?'' :String ( state . uiScale )); 511 512// "system" means the OS decides, so the attribute is absent rather than set 513// to a third value the stylesheet would have to special-case. 514if ( state . motion === 'system' ) delete root . dataset . motion ; 515else root . dataset . motion = state . motion ; 516 517if ( state . focus ) root . dataset . focus = 'true' ; 518else delete root . dataset . focus ; 519 520// "translucent" is the default, so the attribute only appears when it is off. 521if ( state . transparency === 'opaque' ) root . dataset . transparency = 'opaque' ; 522else delete root . dataset . transparency ; 523} 524 525function savePrefs () { 526const snapshot :Prefs = { 527sizeDefaults :SIZE_DEFAULTS_VERSION , 528language :state . language , 529fontFamily :state . fontFamily , 530theme :state . theme , 531contrast :state . contrast , 532rail :state . rail , 533focus :state . focus , 534contentFontSize :state . contentFontSize , 535density :state . density , 536motion :state . motion , 537transparency :state . transparency , 538uiScale :state . uiScale , 539electricityPrice :state . electricityPrice , 540electricityCurrency :state . electricityCurrency , 541doneSound :state . doneSound , 542approvalNotify :state . approvalNotify , 543whileBusy :state . whileBusy , 544shareTelemetry :state . shareTelemetry , 545}; 546try { 547localStorage . setItem ( PREFS_KEY , JSON . stringify ( snapshot )); 548} catch { 549/* a full quota must not break the UI */ 550} 551applyPrefs (); 552} 553 554export function setTheme ( theme :'dark' | 'light' | 'system' ) { 555set ({ theme}); 556savePrefs (); 557} 558 559export function toggleRail () { 560set ({ rail :! state . rail }); 561savePrefs (); 562} 563/** A language whose strings are already here switches at once; the first use of another one waits for its file (a moment), then switches everything together. The last pick wins. */ 564let languageRequest = 0 ; 565export function setLanguage ( language :Language ){ 566if ( ! validLanguage ( language )) return ; 567const request =++ languageRequest ; 568const apply = () => { if ( request !== languageRequest ) return ; setTranslationLanguage ( language ); set ({ language}); savePrefs (); rememberShellLanguage ( language );}; 569if ( catalogLoaded ( language )) apply (); else void loadCatalog ( language ). then ( apply ); 570} 571let shellAnnounced = false ; 572/** The desktop shell's tray menu follows the app's language; it reads it from a small file the host keeps (no effect in a browser). */ 573function rememberShellLanguage ( language :Language ){ api . post ( '/api/shell/prefs' ,{ language}). catch (() => undefined );} 574/** The shell started on another port than it wanted: the chats and settings saved on that port are not here, so say so once (#3402). */ 575async function announcePortNotice (){ 576try { 577const shell = await api . get <{ portNotice :{ wanted :number ; used :number } | null }>( '/api/shell' ); 578if ( shell . portNotice ) pushToast ( 'warn' , tr ( 'Strata could not use its port' ), tr ( 'Port {0} is used by another program, so Strata started on port {1}. Chats and settings saved on port {0} are not shown until Strata can use it again. Close the other program and restart Strata.' ,[ shell . portNotice . wanted , shell . portNotice . used ])); 579} catch { /* a browser or an older host has no shell */ } 580} 581export function setFontFamily ( fontFamily :string ){ set ({ fontFamily :fontFamily . trim (). slice ( 0 , 128 ). replace ( / [\x00-\x1f] / g , '' )}); savePrefs ();} 582 583export function setFocus ( focus :boolean ) { 584set ({ focus}); 585savePrefs (); 586} 587 588export function toggleFocus () { 589setFocus ( ! state . focus ); 590} 591 592/** 593* Puts every appearance and reading preference back to its shipped value. 594* 595* Deliberately excludes `shareTelemetry`: a privacy choice is not an appearance 596* setting, and re-enabling reporting as a side effect of resetting one's font 597* size would be exactly the kind of thing this control exists to prevent. 598* 599* Deliberately does **not** touch `rail` or `focus`: those are where you happen 600* to be working, not settings you chose, and collapsing the sidebar on someone 601* who asked to reset their font size would be a surprise. The engine has its own 602* reset, since an expert override and a font size have nothing to do with each 603* other. 604*/ 605export function resetAppearance () { 606set ({ 607fontFamily :PREFS_DEFAULTS . fontFamily , 608theme :PREFS_DEFAULTS . theme , 609contrast :PREFS_DEFAULTS . contrast , 610contentFontSize :PREFS_DEFAULTS . contentFontSize , 611density :PREFS_DEFAULTS . density , 612motion :PREFS_DEFAULTS . motion , 613transparency :PREFS_DEFAULTS . transparency , 614uiScale :PREFS_DEFAULTS . uiScale , 615}); 616savePrefs (); 617} 618 619/** 620* Records the standing privacy choice. 621* 622* The control was local component state that nothing persisted and nothing 623* read — it snapped back on every reload, so a reader who turned reporting off 624* had no way to know their choice had not been recorded. A privacy control that 625* silently forgets is worse than no control at all. 626*/ 627export function setShareTelemetry ( on :boolean ) { 628set ({ shareTelemetry :on }); 629savePrefs (); 630} 631 632export function setContentFontSize ( px :number ) { 633const clamped = Math . min ( CONTENT_FS_MAX , Math . max ( CONTENT_FS_MIN , Math . round ( px ))); 634set ({ contentFontSize :clamped }); 635savePrefs (); 636} 637 638export function setDensity ( density :'comfortable' | 'compact' ) { 639set ({ density}); 640savePrefs (); 641} 642 643export function setMotion ( motion :'system' | 'full' | 'reduced' ) { 644set ({ motion}); 645savePrefs (); 646} 647 648export function setTransparency ( transparency :'translucent' | 'opaque' ) { 649set ({ transparency}); 650savePrefs (); 651} 652 653/** The electricity price for the Monitor's cost line: a positive price per kWh; 0 turns the line off. The currency is the detected one unless a three-letter code is given (#3628). */ 654export function setElectricity ( price :number , currency :string ) { 655const ok = Number . isFinite ( price ) && price > 0 && price < 1000 ; 656set ({ electricityPrice :ok ?Math . round ( price * 10000 ) / 10000 :0 , electricityCurrency :/ ^[A-Za-z]{3}$ / . test ( currency ) ?currency . toUpperCase () :'' }); 657savePrefs (); 658} 659 660export function setWhileBusy ( whileBusy :WhileBusy ) { 661if ( ! validWhileBusy ( whileBusy )) return ; 662set ({ whileBusy}); 663savePrefs (); 664} 665 666/** A message sent while an answer is being written waits here; the chat sends it when the answer is done (it is also where Interrupt leaves it). */ 667export function parkMessage ( sessionId :string , text :string ) { 668const clean = text . trim (); 669if ( ! clean ) return ; 670set ({ parked :{ ...state . parked , [ sessionId ] :[ ...( state . parked [ sessionId ] ?? []), clean ] } }); 671} 672function setAsks ( sessionId :string , list :AgentAsk []) { 673const next = { ...state . agentAsks }; 674if ( list . length ) next [ sessionId ] = list ; else delete next [ sessionId ]; 675set ({ agentAsks :next }); 676} 677/** The agent asked the person something (a frame of the host), or the question ended without an answer. */ 678export function addAgentAsk ( sessionId :string , frame :{ callId ?:unknown ; questions ?:unknown }) { 679const ask = readAsk ( frame ); 680// A /loop runs without anyone there: the question is skipped at once, so the loop never waits for an answer. 681if ( ask && loopScheduler . isRunning ( sessionId )) { void answerAgentAsk ( sessionId , ask . callId , null ). catch (() => {}); return ; } 682if ( ! ask ) return ; 683const known = ( state . agentAsks [ sessionId ] ?? []). some ( a => a . callId === ask . callId ); 684setAsks ( sessionId , [ ...( state . agentAsks [ sessionId ] ?? []). filter ( a => a . callId !== ask . callId ), ask ]); 685// #5617: a question waits for the person like an approval does: the same opt-in notification, once per question 686if ( ! known ) void questionAsked ( state . approvalNotify ); 687} 688export function removeAgentAsk ( sessionId :string , callId ?:string ) { 689const rest = callId === undefined ?[] :( state . agentAsks [ sessionId ] ?? []). filter ( a => a . callId !== callId ); 690if (( state . agentAsks [ sessionId ]?. length ?? 0 ) !== rest . length ) setAsks ( sessionId , rest ); 691} 692/** Sends the person's answer to the agent, or a skip (answers null). A refusal comes back as an error for the card to say in words. */ 693export async function answerAgentAsk ( sessionId :string , callId :string , answers :AgentAnswer [] | null ) { 694await api . post ( '/api/chat/answer' , { sessionId, callId, ...( answers ?{ answers} :{ skip :true }) }); 695removeAgentAsk ( sessionId , callId ); 696} 697 698/** Puts a turn or a selected passage above the message box. */ 699export function addQuote ( sessionId :string , text :string , messageId :string , role :'user' | 'assistant' ) { 700const list = state . quotes [ sessionId ] ?? []; 701const next = addToQuotes ( list , { text, messageId, role}); 702if ( next . length !== list . length ) set ({ quotes :{ ...state . quotes , [ sessionId ] :next } }); 703} 704export function removeQuote ( sessionId :string , id :string ) { 705const rest = ( state . quotes [ sessionId ] ?? []). filter ( q => q . id !== id ); 706const next = { ...state . quotes }; 707if ( rest . length ) next [ sessionId ] = rest ; else delete next [ sessionId ]; 708set ({ quotes :next }); 709} 710export function clearQuotes ( sessionId :string ) { 711if ( ! state . quotes [ sessionId ]) return ; 712const next = { ...state . quotes }; 713delete next [ sessionId ]; 714set ({ quotes :next }); 715} 716 717/** The first parked message of a chat, taken out of the list (to send it, or to give it back to the box). */ 718export function takeParked ( sessionId :string , index = 0 ) :string | undefined { 719const list = state . parked [ sessionId ] ?? []; 720if ( index < 0 || index >= list . length ) return undefined ; 721const rest = list . filter (( _ , i ) => i !== index ); 722const next = { ...state . parked }; 723if ( rest . length ) next [ sessionId ] = rest ; else delete next [ sessionId ]; 724set ({ parked :next }); 725return list [ index ]; 726} 727 728export function setDoneSound ( doneSound :boolean ) { 729set ({ doneSound}); 730savePrefs (); 731} 732 733export function setApprovalNotify ( approvalNotify :boolean ) { 734set ({ approvalNotify}); 735savePrefs (); 736} 737 738export const UI_SCALES = [ 0.9 , 1 , 1.1 , 1.25 , 1.5 , 1.75 , 2 ] as const ; 739 740export function setUiScale ( uiScale :number ) { 741set ({ uiScale}); 742savePrefs (); 743} 744 745export const CONTENT_FONT_RANGE = { min :CONTENT_FS_MIN , max :CONTENT_FS_MAX }; 746 747/* -------------------------------------------------------------- workspaces */ 748 749/** Opens the system folder chooser. Returns null when it is dismissed. */ 750export async function pickWorkspace () :Promise < string | null > { 751const res = await postWithFolderFallback <{ path ?:string ; cancelled ?:boolean }>( '/api/workspaces/pick' ) as { path ?:string }; 752return res . path ?? null ; 753} 754 755export async function addWorkspace ( path :string ) { 756try { 757const ws = await api . post < Workspace >( '/api/workspaces' , { path}); 758set ({ workspaces :[ ...state . workspaces , ws ] }); 759pushToast ( 'success' , 'Workspace added' , `Strata can now read files in ${ ws . name } .` ); 760} catch ( err ) { 761pushToast ( 'error' , "Couldn't add that folder" , err instanceof Error ?err . message :String ( err )); 762} 763} 764 765/** The name the sidebar shows for a workspace; its folder is unchanged. */ 766export async function renameWorkspace ( id :string , name :string ) { 767try { 768const ws = await api . patch < Workspace >( `/api/workspaces/ ${ id } ` , { name}); 769set ({ workspaces :state . workspaces . map ( w => ( w . id === id ?{ ...w , name :ws . name } :w )) }); 770} catch ( err ) { 771pushToast ( 'error' , "Couldn't rename that workspace" , err instanceof Error ?err . message :String ( err )); 772} 773} 774 775export async function removeWorkspace ( id :string ) { 776const ws = state . workspaces . find (( w ) => w . id === id ); 777try { 778await api . del ( `/api/workspaces/ ${ id } ` ); 779set ({ workspaces :state . workspaces . filter (( w ) => w . id !== id ) }); 780if ( state . activeWorkspace === id ) set ({ activeWorkspace :state . workspaces [ 0 ]?. id ?? null }); 781} catch ( err ) { 782pushToast ( 'error' , "Couldn't remove that workspace" , err instanceof Error ?err . message :String ( err )); 783} 784void ws ; 785} 786 787/** 788* Pins a conversation to the top of its workspace. 789* 790* Sessions are currently ordered by recency, which is right until you have 791* thirty of them and two matter. `Session.pinned` has existed in the type since 792* the beginning and was never written to. 793*/ 794export function toggleArchive ( id :string ) { 795const sessions = state . sessions . map (( s ) => ( s . id === id ?{ ...s , archived :! s . archived } :s )); 796persistSessions ( sessions ); 797set ({ sessions}); 798} 799 800export function togglePin ( id :string ) { 801const sessions = state . sessions . map (( s ) => ( s . id === id ?{ ...s , pinned :! s . pinned } :s )); 802persistSessions ( sessions ); 803set ({ sessions}); 804} 805 806export function setActiveWorkspace ( id :string ) { 807set ({ activeWorkspace :id }); 808void loadWorkspaceFiles (); 809} 810 811export function openSetup ( open :boolean ) { 812set ({ setupOpen :open }); 813} 814 815export function setPalette ( open :boolean ) { 816set ({ paletteOpen :open }); 817} 818 819export function setShortcuts ( open :boolean ) { 820set ({ shortcutsOpen :open }); 821} 822 823/* --------------------------------------------------------------- transport */ 824 825function applyEvent ( e :StreamEvent ) { 826const data = e . data as Record < string , unknown >; 827switch ( e . event ) { 828case 'monitor' : 829set ({ monitor :data as unknown as MonitorState }); 830break ; 831case 'skills' : 832set ({ skills :data as unknown as Skill [] }); 833break ; 834case 'models' : 835if ( Array . isArray ( data . variants )) set ({ library :data as unknown as ModelLibrary }); 836break ; 837case 'runtime' : 838set ({ runtime :data as unknown as RuntimeModels }); 839break ; 840case 'native' : 841applyNativeEvent ( data ); 842break ; 843case 'image-models' : 844if ( Array . isArray ( data . variants )) set ({ imageModels :data as unknown as ImageModelLibrary }); 845break ; 846case 'providers' : 847applyProviders ( data as unknown as ModelProviders ); 848break ; 849case 'goal' : 850if ( typeof data . chatId === 'string' ) applyGoalFrame ( data . chatId , data . goal ); 851break ; 852case 'plan' : 853if ( typeof data . chatId === 'string' ) applyPlanFrame ( data . chatId , data . plan ); 854break ; 855case 'queue' : 856if ( typeof data . chatId === 'string' ) applyQueueFrame ( data . chatId , data . queue ); 857break ; 858case 'timeskip' : 859applyTimeSkipEvent ( data ); 860break ; 861case 'engine' : 862set ({ engine :data as unknown as EngineConfig }); 863break ; 864case 'serving' : 865set ({ serving :newestServingState ( state . serving , data as unknown as ServingState ) }); 866break ; 867case 'setup' : 868set ({ setup :data as unknown as SetupState }); 869break ; 870case 'task' :{ 871// A task finished on its own (the host ran it on schedule): say so, and say when it needs a person's yes or failed. 872const t = data as unknown as { title ?:string ; status ?:string ; attention ?:string | null ; error ?:string | null }; 873if ( t . status === 'error' ) pushToast ( 'error' , 'Task failed' , String ( t . title ?? '' )); 874else if ( t . attention ) { pushToast ( 'warn' , 'Task needs your yes' , String ( t . title ?? '' )); void approvalNeeded ( state . approvalNotify , String ( t . title ?? '' )); } 875else if ( t . status === 'done' ) { pushToast ( 'success' , 'Task finished' , String ( t . title ?? '' )); workFinished ( state . doneSound , Infinity ); } 876break ; 877} 878case 'chats' : 879// Another window saved or removed a chat (this window's own saves carry its name and are ignored). 880if ( typeof data . id === 'string' && data . from !== WINDOW_ID ) void applyChatChange ( data . id , typeof data . rev === 'number' ?data . rev :null , data . deleted === true ); 881break ; 882case 'agent' : 883if ( typeof data . sessionId === 'string' ) patchSession ( data . sessionId , s => ({ ...s , agents :updateAgent ( s . agents ?? [], data . agent ) })); 884break ; 885default : 886break ; 887} 888} 889 890/** QAGUI 0213: how long one start-up GET may take, how often it is tried, and the pause between tries (a test may shorten them). */ 891export const bootstrapTiming = { timeoutMs :8000 , tries :3 , backoffMs :400 }; 892 893/** One GET with a time limit, tried again after a timeout, a lost connection or a host error. A refusal (4xx) is final. */ 894export async function getWithRetry < T > ( path :string ) :Promise < T > { 895const { timeoutMs, tries, backoffMs} = bootstrapTiming ; 896let last :unknown ; 897for ( let attempt = 0 ; attempt < tries ; attempt ++ ) { 898if ( attempt ) await new Promise ( r => setTimeout ( r , backoffMs * 2 ** ( attempt - 1 ))); 899const abort = new AbortController (); 900let timer :ReturnType < typeof setTimeout > | undefined ; 901try { 902return await Promise . race ([ 903api . get < T >( path , abort . signal ), 904new Promise < never >(( _ , reject ) => { timer = setTimeout (() => { abort . abort (); reject ( new Error ( `No answer from ${ path } ` )); }, timeoutMs ); }), 905]); 906} catch ( err ) { 907last = err ; 908if ( err instanceof ApiError && err . status >= 400 && err . status < 500 ) throw err ; 909} finally { clearTimeout ( timer ); } 910} 911throw last ; 912} 913 914let closeEvents :(() => void ) | null = null ; 915export async function bootstrap () { 916applyPrefs (); 917try { 918let chatsTimer :ReturnType < typeof setTimeout > | undefined ; 919await Promise . race ([ 920loadChatsFromHost (), 921new Promise < never >(( _ , reject ) => { chatsTimer = setTimeout (() => reject ( new Error ( 'The chats did not load in time' )), bootstrapTiming . timeoutMs ); }), 922]). catch (() => { sessionWriter . enable (); }). finally (() => clearTimeout ( chatsTimer )); 923// Only what the first screen cannot do without holds up 'live'; the rest is read at the same time and fills in when it arrives. 924const soft = < T , > ( path :string ) => getWithRetry < T >( path ). catch (() => null ); 925const late = { 926hardware :soft < Hardware >( '/api/hardware' ), 927monitor :soft < MonitorState >( '/api/monitor' ), 928skills :soft < Skill []>( '/api/skills' ), 929providers :soft < ModelProviders >( '/api/model-providers' ), 930imageModels :soft < ImageModelLibrary >( '/api/image-models' ), 931runtime :soft < RuntimeModels >( '/api/runtime' ), 932}; 933const [ setup , library , engine , serving , workspaceState ] = await Promise . all ([ 934getWithRetry < SetupState >( '/api/setup' ), 935getWithRetry < ModelLibrary >( '/api/models' ), 936getWithRetry < EngineConfig >( '/api/engine' ), 937getWithRetry < ServingState >( '/api/serving' ), 938getWithRetry <{ workspaces :Workspace [] }>( '/api/workspaces' ), 939]); 940set ({ 941ready :true , 942 setup, 943library :libraryResponse ( library ), 944 engine, 945serving :newestServingState ( state . serving , serving ), 946workspacePath :workspaceState . workspaces [ 0 ]?. path ?? '' , 947workspaces :workspaceState . workspaces , 948activeWorkspace :workspaceState . workspaces . some ( w => w . id === state . activeWorkspace ) ?state . activeWorkspace :workspaceIdForSession ( workspaceState . workspaces , state . sessions . find ( s => s . id === state . activeSession )) ?? workspaceState . workspaces [ 0 ]?. id ?? null , 949connection :'live' , 950}); 951void late . hardware . then ( hardware => { if ( hardware ) set ({ hardware}); }); 952void late . monitor . then ( monitor => { if ( monitor ) set ({ monitor}); }); 953void late . skills . then ( skills => { if ( skills ) set ({ skills}); }); 954void late . providers . then ( providers => { if ( providers ) applyProviders ( providers ); }); 955void late . imageModels . then ( imageModels => { if ( imageModels ) set ({ imageModels}); }); 956void late . runtime . then ( runtime => { if ( runtime ) set ({ runtime}); }); 957if ( ! shellAnnounced ) { shellAnnounced = true ; void announcePortNotice (); rememberShellLanguage ( state . language ); } 958closeEvents ?.(); 959let reconnect = false ; 960closeEvents = onEvent ( applyEvent , ( status ) => { 961if ( status === 'offline' ) reconnect = true ; 962if ( status === 'live' && reconnect ) { 963reconnect = false ; 964// The restarted host may have new logs, config or readiness. Refresh 965// those facts in place while retaining conversations and unsent drafts. 966void bootstrap (); 967return ; 968} 969set ({ connection :status }); 970}); 971if ( ! setup . complete && ! setup . dismissed && ! window . location . hash . includes ( 'setup' )) navigate ( 'setup' ); 972} catch ( err ) { 973set ({ ready :true , connection :'offline' }); 974pushToast ( 975'error' , 976'Engine host unreachable' , 977err instanceof Error ?err . message :'Start it with `npm run host` and reload.' , 978); 979} 980} 981 982/* ------------------------------------------------------------- reads/writes */ 983 984export async function refreshHardware () { 985set (( s ) => ({ busy :{ ...s . busy , hardware :true } })); 986try { 987set ({ hardware :await api . get < Hardware >( '/api/hardware?reprobe=1' ) }); 988} finally { 989set (( s ) => ({ busy :{ ...s . busy , hardware :false } })); 990} 991} 992 993function modelFits ( id :string ) { 994const model = state . library ?. variants . find ( v => v . id === id ); 995if ( state . library ?. mode === 'real' && model && state . hardware && state . engine && [ 'too-large' , 'unsupported' ]. includes ( estimate ( model , state . hardware , execution ( Object . fromEntries ( state . engine . expert . map ( p => [ p . id , p . value ])), contextTokens ( state . engine . beginner . contextLength ))). fit )) { 996pushToast ( 'warn' , 'Choose a smaller model' , 'The estimated memory requirement exceeds this computer.' ); 997return false ; 998} 999return true ; 1000} 1001 1002export async function selectImageModel ( selected :ImageModelChoice ) { 1003set ( s => ({ busy :{ ...s . busy , 'image:select' :true } })); 1004try { set ({ imageModels :await api . patch < ImageModelLibrary >( '/api/image-models' , { selected}) }); } 1005finally { set ( s => ({ busy :{ ...s . busy , 'image:select' :false } })); } 1006} 1007export async function installImageModel ( id :Exclude < ImageModelChoice , 'off' >) { 1008set ({ imageModels :await api . post < ImageModelLibrary >( `/api/image-models/ ${ id } /install` ) }); 1009} 1010export async function cancelImageModel ( id :Exclude < ImageModelChoice , 'off' >) { 1011set ({ imageModels :await api . post < ImageModelLibrary >( `/api/image-models/ ${ id } /cancel` ) }); 1012} 1013export async function applyImageModel () { 1014set ({ imageModels :await api . post < ImageModelLibrary >( '/api/image-models/apply' ) }); 1015} 1016 1017export async function installVariant ( id :string ) { 1018// Download eligibility is checked against disk space by the host. Runtime fit 1019// is reviewed separately when the model is loaded. 1020if ( state . busy [ `install: ${ id } ` ]) return false ; 1021set (( s ) => ({ busy :{ ...s . busy , [ `install: ${ id } ` ] :true } })); 1022try { 1023const library = libraryResponse ( await api . post < ModelLibrary >( `/api/models/ ${ id } /install` )); 1024set ({ library}); 1025const complete = library . variants . find ( v => v . id === id )?. state === 'installed' ; 1026pushToast ( complete ?'success' :'info' , complete ?'Files installed' :library . mode === 'simulated' ?'Example installation started' :'Download started' , complete ?'Load the model to start a request.' :'Progress is shown in Models.' ); 1027return true ; 1028} catch ( err ) { 1029pushToast ( 'error' , 'Download failed' , err instanceof Error ?err . message :undefined ); 1030return false ; 1031} finally { 1032set (( s ) => ({ busy :{ ...s . busy , [ `install: ${ id } ` ] :false } })); 1033} 1034} 1035 1036export async function cancelInstall ( id :string ) { 1037try { set ({ library :libraryResponse ( await api . post < ModelLibrary >( `/api/models/ ${ id } /cancel` )) }); } catch ( e ) { pushToast ( 'error' , 'Cancel failed' , e instanceof Error ?e . message :String ( e )); } 1038} 1039 1040export async function loadVariant ( id :string ) { 1041if ( ! modelFits ( id )) return false ; 1042if ( ! lifecycleAvailable ()) return false ; 1043set (( s ) => ({ busy :{ ...s . busy , [ `load: ${ id } ` ] :true }, actionError :null })); 1044try { 1045const library = libraryResponse ( await api . post < ModelLibrary >( `/api/models/ ${ id } /load` )); 1046set ({ library}); 1047const model = library . variants . find ( v => v . id === id ); 1048if ( library . loaded !== id || model ?. state !== 'loaded' ) throw new Error ( model ?. error ?? 'The model did not finish loading.' ); 1049pushToast ( 'success' , library . mode === 'simulated' ?'Example model ready' :'Model loaded' , library . mode === 'simulated' ?'Answers are simulated samples, not from a real model.' :'Ready for a request.' ); 1050return true ; 1051} catch ( err ) { 1052const message = err instanceof Error ?err . message :'The model did not load.' ; 1053set ({ 1054actionError :{ 1055label :'Could not load model' , 1056 message, 1057retry :() => void loadVariant ( id ), 1058}, 1059}); 1060pushToast ( 'error' , 'Could not load model' , message ); 1061return false ; 1062} finally { 1063set (( s ) => ({ busy :{ ...s . busy , [ `load: ${ id } ` ] :false } })); 1064} 1065} 1066 1067export async function unloadModel () { 1068if ( ! lifecycleAvailable ()) return false ; 1069set ( s => ({ busy :{ ...s . busy , unload :true } })); 1070try { 1071const previousInstance = state . runtime ?. defaultId ; 1072const library = libraryResponse ( await api . post < ModelLibrary >( '/api/models/unload' )); 1073const runtime = await api . get < RuntimeModels >( '/api/runtime' ); 1074set ({ runtime}); 1075set ({ library}); 1076if ( previousInstance ?runtime . instances . some ( i => i . id === previousInstance ) :library . loaded !== null ) throw new Error ( 'The engine still reports this model instance as loaded.' ); 1077pushToast ( 'info' , 'Model unloaded' , library . mode === 'simulated' ?'Example load state cleared.' :'Model memory released.' ); 1078return true ; 1079} catch ( err ) { pushToast ( 'error' , 'Unload failed' , err instanceof Error ?err . message :String ( err )); return false ; } 1080finally { set ( s => ({ busy :{ ...s . busy , unload :false } })); } 1081} 1082 1083export async function removeVariant ( id :string ) { 1084if ( state . library ?. loaded === id && ! lifecycleAvailable ()) return false ; 1085const local = !! state . library ?. variants . find ( v => v . id === id )?. local ; 1086try { const library = libraryResponse ( await api . del < ModelLibrary >( `/api/models/ ${ id } ` )); set ({ library}); 1087const remaining = library . variants . find ( v => v . id === id ); 1088if ( remaining && remaining . state !== 'available' ) throw new Error ( 'The model files were not removed.' ); 1089pushToast ( 'success' , local ?'Local model removed' :'Files removed' , local ?'The original GGUF files are kept.' :library . mode === 'simulated' ?'Example install state cleared.' :'Model files removed from disk.' ); return true ; 1090} catch ( e ) { pushToast ( 'error' , 'Remove failed' , e instanceof Error ?e . message :String ( e )); return false ; } 1091} 1092 1093export async function waitForInstalled ( id :string ) { 1094const deadline = Date . now () + 60 * 60 * 1000 ; 1095while ( Date . now () < deadline ) { 1096const v = state . library ?. variants . find ( v => v . id === id ); 1097if ( v && [ 'installed' , 'loaded' ]. includes ( v . state )) return ; 1098if ( ! v || [ 'available' , 'error' ]. includes ( v . state )) throw new Error ( v ?. error ?? 'Download cancelled.' ); 1099await new Promise ( resolve => setTimeout ( resolve , 500 )); 1100} 1101throw new Error ( 'Download timed out. Try again from Models.' ); 1102} 1103 1104export async function saveEngine ( patch :Partial < EngineConfig > | Record < string , unknown >, silent = false , requireIdle = false ) { 1105if ( requireIdle ) { 1106const status = lifecycleStatus (); 1107if ( ! status . allowed ) throw new Error ( status . reason ); 1108} 1109const engine = await api . patch < EngineConfig >( '/api/engine' , patch ); 1110set ({ engine, actionError :null }); 1111if ( ! silent ) pushToast ( 'success' , 'Settings saved' , 'Load settings take effect on the next load. Sampling defaults affect the next request.' ); 1112return engine ; 1113} 1114 1115export async function restartEngine () { 1116if ( state . library ?. mode === 'simulated' ) { pushToast ( 'info' , 'Restart unavailable with the example engine' , 'Save settings for the next load.' ); return false ; } 1117if ( ! lifecycleAvailable ()) return false ; 1118set (( s ) => ({ busy :{ ...s . busy , restart :true }, actionError :null })); 1119try { 1120const engine = await api . post < EngineConfig >( '/api/engine/restart' ); 1121set ({ engine}); 1122if ( ! engine . engine . running ) throw new Error ( engine . engine . error ?? 'The engine is not running. Load a model before applying settings.' ); 1123pushToast ( 'success' , 'Engine restarted' , 'Warm-up takes a few seconds.' ); 1124return true ; 1125} catch ( err ) { 1126// Reported in place as well as in a toast: the toast is a summary, the 1127// surface that failed is where the retry belongs. 1128set ({ 1129actionError :{ 1130label :'Restart failed' , 1131message :err instanceof Error ?err . message :'The engine did not come back up.' , 1132retry :() => void restartEngine (), 1133}, 1134}); 1135pushToast ( 'error' , 'Restart failed' , err instanceof Error ?err . message :undefined ); 1136return false ; 1137} finally { 1138set (( s ) => ({ busy :{ ...s . busy , restart :false } })); 1139} 1140} 1141 1142export function dismissActionError () { 1143set ({ actionError :null }); 1144} 1145 1146export async function resetEngine () { 1147set ({ engine :await api . post < EngineConfig >( '/api/engine/reset' ) }); 1148pushToast ( 'info' , 'Back to recommended' , 'Every value returned to the safe default.' ); 1149} 1150 1151/** 1152* Checks an engine config — the saved one by default, or a draft to preview what 1153* a change would do before committing to it. 1154*/ 1155export async function validateEngine ( draft ?:unknown ) { 1156return api . post <{ 1157ok :boolean ; 1158issues :{ level :'warn' | 'error' ; message :string }[]; 1159predicted ?:EngineConfig [ 'predicted' ]; 1160}>( '/api/engine/validate' , draft ?? {}); 1161} 1162 1163export async function exportEngine () { 1164return api . get < Record < string , unknown >>( '/api/engine/export' ); 1165} 1166 1167export async function setCloudflare ( body :{ action :'start' | 'stop' | 'prepare' ; mode ?:'quick' | 'domain' ; hostname ?:string ; token ?:string }) { 1168const result = await api . post < ServingState >( '/api/serving/tunnel' , body ); 1169set ({ serving :newestServingState ( state . serving , result ) }); 1170} 1171 1172export async function setLocalSharing ( enabled :boolean ) { 1173const result = await api . post < ServingState >( '/api/serving/share' , { enabled}); 1174set ({ serving :newestServingState ( state . serving , result ) }); 1175} 1176 1177export async function setServingAccess ( patch :{ otherDevices ?:boolean ; apiKey ?:string | null }) { 1178const result = await api . patch < ServingState >( '/api/serving' , patch ); 1179set ({ serving :newestServingState ( state . serving , result ) }); 1180} 1181 1182export async function pauseServing ( paused :boolean ) { 1183const result = await api . patch < ServingState >( '/api/serving' , { pauseServing :paused }); 1184set ({ serving :newestServingState ( state . serving , result ) }); 1185} 1186 1187export async function cancelRequest ( id :string ) { 1188const result = await api . post < ServingState >( `/api/serving/requests/ ${ id } /cancel` ); 1189set ({ serving :newestServingState ( state . serving , result ) }); 1190} 1191 1192export async function completeSetupStep ( step :number , choices ?:SetupState [ 'choices' ], dismissed = false ) { 1193set ({ setup :await api . post < SetupState >( '/api/setup/step' , { step, choices, dismissed, flowVersion :2 }) }); 1194} 1195 1196export async function completeSetup () { 1197const setup = await api . post < SetupState >( '/api/setup/complete' ); 1198set ({ setup}); 1199} 1200 1201export async function setSkills ( skills :Skill []) { 1202set ({ skills}); 1203} 1204 1205/** 1206* Re-reads the skill list from the host. 1207* 1208* For the case where a skill was added to the workspace folder while the app was 1209* open — otherwise the only way to see it is to restart. 1210*/ 1211export async function loadSkills () { 1212set ({ skills :await api . get < Skill []>( '/api/skills' ) }); 1213} 1214 1215/** Re-reads the workspace tree from disk, for the same reason. */ 1216export async function loadWorkspaceFiles () { 1217const data = await api . get <{ path :string ; entries :WorkspaceFile [] }>( `/api/workspace ${ state . activeWorkspace ? '?root=' + encodeURIComponent ( state . activeWorkspace ) : '' } ` ); 1218set ({ files :data . entries , workspacePath :data . path }); 1219} 1220 1221export async function toggleSkill ( id :string , enabled :boolean ) { 1222set ({ skills :await api . patch < Skill []>( `/api/skills/ ${ encodeURIComponent ( id )} ` , { enabled}) }); 1223} 1224 1225export async function editSkill ( id :string , patch :Pick < Skill , 'name' | 'description' | 'body' | 'triggers' | 'enabled' | 'onlyIn' >) { 1226set ({ skills :await api . patch < Skill []>( `/api/skills/ ${ encodeURIComponent ( id )} ` , patch ) }); 1227} 1228 1229/** 1230* Narrows a skill to the workspace you are in, or widens it again. 1231* 1232* Passing null clears the narrowing. The host resolves `onlyIn` against the 1233* workspace the request came from, so the answer depends on where the reader 1234* is rather than on a single global switch. 1235*/ 1236export async function scopeSkill ( id :string , workspaceId :string | null ) { 1237set ({ skills :await api . patch < Skill []>( `/api/skills/ ${ encodeURIComponent ( id )} ` , { onlyIn :workspaceId }) }); 1238} 1239 1240/* ---------------------------------------------------------------- sessions */ 1241 1242const chatTransport = createHttpTransport (); 1243let saveToast :string | null = null ; 1244 1245const sessionWriter = createSessionWriter ({ 1246transport :chatTransport , 1247enabled :false , // on once the host's chats have been read (loadChatsFromHost), so an older copy here never replaces a newer file 1248// Nothing is trimmed to fit (#5192). A chat the host cannot write keeps its last file and stays whole here; it is reported and 1249// tried again. A host that does not answer is retried quietly: that is the app being down, not a full disk. 1250onResult :( result :SaveResult ) => { 1251if ( result . ok ) { 1252try { browserStorage . removeItem ( PENDING_KEY ); } catch { /* removed at the next start */ } 1253if ( state . sessionSave ) set ({ sessionSave :null }); 1254if ( saveToast ) { dismissToast ( saveToast ); saveToast = null ; } 1255return ; 1256} 1257const real = result . failed . filter ( f => f . reason !== 'offline' ); 1258if ( ! real . length ) return ; 1259const failedIds = sessionWriter . unsaved (). map ( s => s . id ); 1260const reason = real [ 0 ]. reason === 'offline' ?'other' :real [ 0 ]. reason ; 1261const was = state . sessionSave ; 1262if ( ! was || was . reason !== reason || was . failedIds . join () !== failedIds . join ()) set ({ sessionSave :{ failedIds, reason} }); 1263if ( ! was && ! saveToast ) { 1264saveToast = pushToast ( 'error' , 'Some chats could not be saved' , tr ( "Strata's chat storage is full, so the newest changes to {0} chat(s) are only in this window. Delete old chats to make room; they then save by themselves." , [ failedIds . length ]), { 1265label :'Copy unsaved chats' , 1266run :() => { const text = unsavedSessionsJson (); if ( text ) void copyText ( text , '' , { toast :( tone , title , body ) => { pushToast ( tone , title , body || undefined ); } }); }, 1267}); 1268} 1269}, 1270}); 1271 1272/** The chats the host could not write, as one JSON text (to keep a copy by hand), or null when all are saved. */ 1273export function unsavedSessionsJson () :string | null { 1274const unsaved = sessionWriter . unsaved (); 1275return unsaved . length ?exportSessions ( unsaved ) :null ; 1276} 1277 1278/** 1279* Save the chat list. A one-off change (new, rename, delete, pin) is sent now; `soon` is for the streaming 1280* path, where a write per token grew the renderer to gigabytes (#3604, #3603): those are coalesced to one a second. 1281*/ 1282function persistSessions ( sessions :Session [], soon = false ) { 1283sessionWriter . schedule ( sessions ); 1284if ( ! soon ) void sessionWriter . flush (); 1285} 1286 1287/** Send the newest chat list now: a turn ended, or the page is going away. */ 1288export function flushSessions () :Promise < SaveResult > { 1289return sessionWriter . flush (); 1290} 1291 1292/** The page is going away: send what can still be sent, and keep a last-moment copy of what the host has not confirmed (taken back at the next start). */ 1293function leavingPage () { 1294void sessionWriter . flush (); 1295const unconfirmed = sessionWriter . notOnHost (); 1296if ( unconfirmed . length ) keepLastMomentCopy ( browserStorage , unconfirmed ); 1297} 1298 1299if ( typeof window !== 'undefined' && typeof document !== 'undefined' && window . addEventListener ) { 1300window . addEventListener ( 'pagehide' , leavingPage ); 1301document . addEventListener ?.( 'visibilitychange' , () => { if ( document . visibilityState === 'hidden' ) leavingPage (); }); 1302} 1303 1304let chatsRead = false ; 1305/** 1306* The first read of the chats at start, and again after the host came back: the host's files become the chats shown (the browser's 1307* old chats are handed over first, once), then saving starts. A host that does not answer leaves the page as it is. 1308*/ 1309export async function loadChatsFromHost () { 1310if ( chatsRead ) { await syncChatsFromHost (); return ; } 1311const result = await hydrateChats ({ 1312transport :chatTransport , browser :browserStorage , current :state . sessions , 1313isLive :id => liveTurns . has ( id ), 1314}); 1315if ( result . offline ) { 1316// Show the browser's old copy so the person can still read; saves are retried until the host answers. 1317if ( ! state . sessions . length ) { try { set ({ sessions :readBrowserSessions ( browserStorage ). sessions . map ( fixSession ) }); } catch { /* none */ } } 1318for ( const s of state . sessions ) sessionWriter . adopt ( s , null ); 1319sessionWriter . enable (); 1320return ; 1321} 1322chatsRead = true ; 1323const sessions = result . sessions . map ( fixSession ); 1324for ( const s of sessions ) { const rev = result . revs . get ( s . id ); if ( rev !== undefined && ! result . recovered . includes ( s . id )) sessionWriter . adopt ( s , rev ); } 1325set ({ sessions}); 1326// Whatever the host does not have yet (a chat it refused during the move, a last-moment copy) is sent now; a refusal raises the notice. 1327sessionWriter . schedule ( sessions ); 1328sessionWriter . enable (); 1329void resumeSessions (); 1330} 1331 1332/** One chat that another window saved or removed: taken over unless this window is working in it. */ 1333export async function applyChatChange ( id :string , rev :number | null , deleted :boolean ) { 1334const here = state . sessions . find ( s => s . id === id ); 1335if ( deleted ) { 1336if ( here && ! liveTurns . has ( id ) && ! sessionWriter . dirty ( here )) { 1337sessionWriter . forget ( id ); 1338set ({ sessions :state . sessions . filter ( s => s . id !== id ), ...( state . activeSession === id ?{ activeSession :null } :{}) }); 1339} 1340return ; 1341} 1342if ( rev !== null && sessionWriter . rev ( id ) >= rev ) return ; 1343if ( here && ( liveTurns . has ( id ) || sessionWriter . dirty ( here ))) return ; // this window's own work wins; its next save keeps the displaced version on the host 1344const got = await chatTransport . get ( id ). catch (() => null ); 1345if ( ! got ) return ; 1346const fresh = state . sessions . find ( s => s . id === id ); 1347if ( fresh && ( liveTurns . has ( id ) || sessionWriter . dirty ( fresh ))) return ; 1348sessionWriter . adopt ( got . session , got . rev ); 1349const next = fresh ?state . sessions . map ( s => ( s . id === id ?got . session :s )) :[ ...state . sessions , got . session ]. sort (( a , b ) => ( a . createdAt < b . createdAt ?1 :- 1 )); 1350set ({ sessions :next }); 1351} 1352 1353/** After the host was away: take over what other windows saved or removed meanwhile. */ 1354async function syncChatsFromHost () { 1355const list = await chatTransport . list (). catch (() => null ); 1356if ( ! list ) return ; 1357const onHost = new Set ( list . chats . map ( c => c . id )); 1358for ( const entry of list . chats ) await applyChatChange ( entry . id , entry . rev , false ); 1359for ( const s of state . sessions ) if ( ! onHost . has ( s . id ) && sessionWriter . rev ( s . id ) > 0 ) await applyChatChange ( s . id , null , true ); 1360sessionWriter . enable (); 1361} 1362 1363export function newSession () :Session { 1364const session :Session = { 1365id :uid ( 's' ), 1366title :'New conversation' , 1367defaultTitle :true , 1368createdAt :new Date (). toISOString (), 1369updatedAt :new Date (). toISOString (), 1370messages :[], 1371workspace :state . workspaces . find ( w => w . id === state . activeWorkspace )?. path ?? state . workspacePath , 1372tokensIn :0 , 1373tokensOut :0 , 1374 ...( state . activeSession === null && state . remoteModel ?{ preferences :{ remoteModel :state . remoteModel } } :{}), 1375}; 1376const sessions = [ session , ...state . sessions ]; 1377persistSessions ( sessions ); 1378set ({ sessions, activeSession :session . id }); 1379return session ; 1380} 1381 1382export function setChatPreferences ( id :string | undefined , preferences :NonNullable < Session [ 'preferences' ]>) { 1383const sessionId = id ?? newSession (). id ; 1384patchSession ( sessionId , s => ({ ...s , preferences :{ ...s . preferences , ...preferences } })); 1385// A mode change applies to the very next tool call of a turn that is already running (a goal and its helpers included). 1386if ( preferences . mode && liveTurns . get ( sessionId )?. agent ) void api . post ( '/api/chat/mode' , { sessionId, mode :preferences . mode }). catch (() => undefined ); 1387} 1388export function setPreviewTabClosed ( sessionId :string | undefined , artifactId :string , closed :boolean , selected :string | null ) { 1389if ( ! sessionId ) return ; 1390patchSession ( sessionId , s => ({ ...s , closedPreviews :closed ?[ ...new Set ([ ...( s . closedPreviews ?? []), artifactId ])] :( s . closedPreviews ?? []). filter ( id => id !== artifactId ), previewOpen :selected ?? undefined })); 1391} 1392export function createChatShowcase () { 1393const session = newSession (); const at = new Date (). toISOString (); 1394patchSession ( session . id , s => ({ ...s , title :'Chat showcase · code, tools & media' , showcase :true , statsAvailable :true , tokensIn :28000000 , tokensOut :4000000 , messages :showcaseMessages ( at ), agents :SHOWCASE_AGENTS , showcaseAgentStates :true })); 1395go ( 'chat' , session . id ); 1396} 1397 1398/** A visible example for checking the subagent interface in the design build. */ 1399export function createSubagentExample () { 1400const session = newSession (); const now = Date . now (); 1401patchSession ( session . id , s => ({ ...s , title :'Subagent preview' , showcase :true , showcaseAgentStates :true , 1402agents :[ 1403{ id :'example-layout' , name :'Layout review' , description :'Checking spacing and component alignment.' , status :'working' , durationMs :39000 , tokens :12600 , updatedAt :now }, 1404{ id :'example-interactions' , name :'Interaction review' , description :'Checking menus, controls and keyboard navigation.' , status :'working' , durationMs :21000 , tokens :8400 , updatedAt :now }, 1405{ id :'example-copy' , name :'Copy review' , description :'Labels and descriptions reviewed.' , status :'completed' , durationMs :18000 , tokens :4200 , updatedAt :now }, 1406], messages :[{ id :uid ( 'm' ), role :'assistant' , at :new Date ( now ). toISOString (), example :true , content :'Open the subagent count above to inspect this example run. Each row shows status, token usage and elapsed time.' }] 1407})); 1408go ( 'chat' , session . id ); 1409} 1410 1411export function createPreviewExamples () { 1412const session = newSession (); 1413const at = new Date (). toISOString (); 1414patchSession ( session . id , s => ({ ...s , title :'Design review · six previews' , previewOpen :'sample-website' , messages :[ 1415{ id :uid ( 'm' ), role :'user' , at, content :'Open six different output types so I can iterate on the preview design.' }, 1416{ id :uid ( 'm' ), role :'assistant' , at, demo :true , content :'Here is a design-review workspace for Fieldnotes: a website, PDF, Markdown brief, cover image, TypeScript file and release table.\n\nAll six are loaded in the panel on the right. Switch tabs to explore each view while keeping this conversation in place.' , artifacts :PREVIEW_EXAMPLES }, 1417] })); 1418go ( 'chat' , session . id ); 1419} 1420 1421/** "Continue in a new chat" on a task: a new chat whose first message is the task's findings, what it did and its files (src/lib/task-handover.ts). */ 1422export function continueTaskInNewChat ( task :Task ) { 1423const session = newSession (); 1424go ( 'chat' , session . id ); 1425void sendMessage ( taskHandoverMessage ( task ), { title :taskHandoverTitle ( task ), markdown :true }); 1426} 1427 1428export function selectSession ( id :string ) { 1429// A chat comes back in the workspace it was made in, so its next turn runs in the same folder (#3754). 1430const workspace = workspaceIdForSession ( state . workspaces , state . sessions . find ( s => s . id === id )); 1431const change = workspace && workspace !== state . activeWorkspace ; 1432set ( change ?{ activeSession :id , activeWorkspace :workspace } :{ activeSession :id }); 1433if ( change ) void loadWorkspaceFiles (); 1434markRead ( id ); 1435} 1436 1437/** Records that a conversation has been looked at. */ 1438export function markRead ( id :string ) { 1439const at = new Date (). toISOString (); 1440const sessions = state . sessions . map (( s ) => ( s . id === id ?{ ...s , lastReadAt :at } :s )); 1441persistSessions ( sessions ); 1442set ({ sessions}); 1443} 1444 1445/** 1446* Whether a conversation has moved on since it was last looked at. 1447* 1448* The active conversation is never unread: you are looking at it, or its reply 1449* is arriving in front of you. 1450*/ 1451export function isUnread ( s :Session , activeSession :string | null ) :boolean { 1452if ( s . id === activeSession ) return false ; 1453if ( ! s . lastReadAt ) return s . messages . length > 0 ; 1454return s . updatedAt > s . lastReadAt ; 1455} 1456 1457export function deleteSession ( id :string ) { 1458const sessions = state . sessions . filter (( s ) => s . id !== id ); 1459persistSessions ( sessions ); 1460set ({ sessions, activeSession :state . activeSession === id ?( sessions [ 0 ]?. id ?? null ) :state . activeSession }); 1461} 1462 1463export function renameSession ( id :string , title :string ) { 1464const sessions = state . sessions . map (( s ) => ( s . id === id ?{ ...s , title, defaultTitle :false } :s )); 1465persistSessions ( sessions ); 1466set ({ sessions}); 1467} 1468 1469function patchSession ( id :string , fn :( s :Session ) => Session ) { 1470const sessions = state . sessions . map (( s ) => ( s . id === id ?fn ( s ) :s )); 1471persistSessions ( sessions , true ); 1472set ({ sessions}); 1473} 1474 1475// The demo clock belongs to the session, so hiding the sidebar or navigating 1476// away never pauses it. Only start and completion are written to storage. 1477const timeSkipTimers = new Map < string , ReturnType < typeof setTimeout >>(); 1478function scheduleTimeSkip ( sessionId :string , run :TimeSkipRun ) { 1479const timerId = ` ${ sessionId } : ${ run . id } ` ; 1480clearTimeout ( timeSkipTimers . get ( timerId )); 1481if ( run . completedAt || run . job ) return ; 1482timeSkipTimers . set ( timerId , setTimeout (() => { 1483timeSkipTimers . delete ( timerId ); 1484const session = state . sessions . find ( s => s . id === sessionId ); 1485const current = session ?. timeSkips ?. find ( r => r . id === run . id ); 1486if ( ! current || current . startedAt !== run . startedAt || ! session ?. messages . some ( m => m . timeSkipId === run . id && m . role === 'assistant' )) return ; 1487patchSession ( sessionId , s => ({ ...s , updatedAt :new Date (). toISOString (), 1488timeSkips :s . timeSkips ?. map ( r => r . id === run . id ?{ ...r , completedAt :run . startedAt + TIME_SKIP_DURATION } :r ), 1489messages :s . messages . map ( m => m . timeSkipId === run . id && m . role === 'assistant' ?{ ...m , content :'The updated result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.' } :m ), 1490})); 1491}, Math . max ( 0 , run . startedAt + TIME_SKIP_DURATION - Date . now ()))); 1492} 1493 1494export function replayTimeSkip ( sessionId :string , runId :string ) { 1495const run = state . sessions . find ( s => s . id === sessionId )?. timeSkips ?. find ( r => r . id === runId ); 1496if ( ! run ) return ; 1497const next = { ...run , startedAt :Date . now (), completedAt :undefined , retainedVersion :undefined }; 1498patchSession ( sessionId , s => ({ ...s , timeSkips :s . timeSkips ?. map ( r => r . id === runId ?next :r ), 1499messages :s . messages . map ( m => m . timeSkipId === runId && m . role === 'assistant' ?{ ...m , content :'Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.' } :m ), 1500})); 1501scheduleTimeSkip ( sessionId , next ); 1502} 1503 1504export function setTimeSkipResult ( sessionId :string , runId :string , version :TimeSkipVersion ) { 1505const run = state . sessions . find ( s => s . id === sessionId )?. timeSkips ?. find ( r => r . id === runId ); 1506if ( ! run ) return ; 1507if ( run . job ) { void keepTimeSkip ( sessionId , runId , version ); return ; } 1508const next = withTimeSkipResult ( run , version , Date . now ()); 1509if ( next === run ) return ; 1510patchSession ( sessionId , s => ({ ...s , timeSkips :s . timeSkips ?. map ( r => r . id === runId ?next :r ) })); 1511} 1512 1513/* ------------------------------------------------------- Time-skip, for real 1514The host copies the chat's folder, lets the assistant change the copy, checks it and keeps the original untouched until the 1515person chooses. The sidebar follows the job's own record; nothing here invents progress. */ 1516const TS_TERMINAL = [ 'completed' , 'cancelled' , 'failed' , 'interrupted' ]; 1517const TS_WORKING = () => tr ( 'Working on a copy of your files. Follow the progress in the sidebar.' ); 1518const TS_READY = () => tr ( 'The result is ready. Switch between Original and Updated, or compare them side by side.' ); 1519 1520function patchRun ( sessionId :string , runId :string , fn :( run :TimeSkipRun ) => TimeSkipRun , content ?:string ) { 1521patchSession ( sessionId , s => ({ ...s , updatedAt :new Date (). toISOString (), 1522timeSkips :s . timeSkips ?. map ( r => r . id === runId ?fn ( r ) :r ), 1523messages :content === undefined ?s . messages :s . messages . map ( m => m . timeSkipId === runId && m . role === 'assistant' ?{ ...m , content} :m ), 1524})); 1525} 1526 1527/** The job's error in a sentence a person can use. */ 1528export function plainTimeSkipError ( raw :string | null | undefined ) :string { 1529const text = String ( raw ?? '' ). trim (); 1530if ( ! text ) return tr ( 'Something went wrong.' ); 1531const afterExit = / \(exit \d+\):\s*([\s\S]*)$ / . exec ( text ); 1532const body = ( afterExit ?.[ 1 ] ?? text ). replace ( / ^\w*Error:\s* / , '' ). trim (); 1533if ( / destination changed|refusing to overwrite / i . test ( body )) return tr ( 'Your files changed after this trial started, so nothing was overwritten. Run Time-skip again.' ); 1534if ( / too big / i . test ( body )) return tr ( 'This folder is too big to try a change on a copy. Open a smaller folder for this chat, then try again.' ); 1535if ( / folder of your own / i . test ( body )) return tr ( 'Time-skip works on a folder of your own. Choose a workspace folder for this chat, then try again.' ); 1536if ( / Load a model|model first / i . test ( body )) return tr ( 'Load a model first, then try Time-skip again.' ); 1537if ( / needs the Strata app|could not be reached / i . test ( body )) return tr ( 'The assistant could not be reached. Try again.' ); 1538return body . length > 300 ?body . slice ( 0 , 299 ) + '…' :body ; 1539} 1540 1541/** The host says a Time-skip run moved on (phase, and what it is doing now): the working view shows the newest words. */ 1542function applyTimeSkipEvent ( data :Record < string , unknown >) { 1543const id = typeof data . id === 'string' ?data . id :'' ; 1544if ( ! id ) return ; 1545for ( const session of state . sessions ) { 1546const run = session . timeSkips ?. find ( r => r . job ?. id === id ); 1547if ( ! run || run . completedAt ) continue ; 1548patchRun ( session . id , run . id , r => ({ ...r , job :{ ...r . job ! , ...( typeof data . phase === 'string' ?{ phase :data . phase as TimeSkipJob [ 'phase' ] } :{}), activity :data . activity as TimeSkipJob [ 'activity' ], ...forkFields ( data ) } })); 1549} 1550} 1551 1552function timeSkipEnding ( job :TimeSkipJob , files :TimeSkipFile []) :string { 1553if ( job . phase === 'failed' ) return tr ( 'Time-skip stopped. {0} Your files were not changed.' , [ plainTimeSkipError ( job . error )]); 1554if ( job . phase === 'cancelled' || job . phase === 'interrupted' ) return tr ( 'Time-skip was stopped before it finished. Your files were not changed.' ); 1555if ( ! files . length ) return tr ( 'The assistant did not change anything, so there is nothing to compare. Your files were not changed.' ); 1556return isForkJob ( job ) ?tr ( 'Both versions are ready. Compare A and B, then keep one.' ) :TS_READY (); 1557} 1558 1559async function startTimeSkipReal ( prompt :string ) { 1560const sessionId = state . activeSession ?? newSession (). id ; 1561const run :TimeSkipRun = { id :uid ( 'ts' ), prompt, startedAt :Date . now (), 1562job :{ id :'' , phase :'queued' , attempts :[], checkpoints :[], selectedCheckpoint :null , decision :null , needsUserReview :false , error :null } }; 1563const at = new Date (). toISOString (); 1564patchSession ( sessionId , s => ({ ...s , 1565defaultTitle :false , 1566title :s . messages . length ?s . title :shortTitle ( prompt ), updatedAt :at , 1567// The comparison sidebar opens only when there is an update to compare (when the job ends with changed files), never while it works. 1568timeSkips :[ ...( s . timeSkips ?? []), run ], 1569messages :[ ...s . messages , 1570{ id :uid ( 'm' ), role :'user' , at, content :'/time-skip ' + prompt , timeSkipId :run . id }, 1571{ id :uid ( 'm' ), role :'assistant' , at, timeSkipId :run . id , content :TS_WORKING () }, 1572], 1573})); 1574go ( 'chat' , sessionId ); 1575markTurn ( sessionId , { abort :new AbortController (), agent :false }); 1576try { 1577const started = await api . post <{ run :TimeSkipJob }>( '/api/timeskip/start' , { prompt, sessionId, workspaceId :state . activeWorkspace , attempts :1 , ...( state . remoteModel ?{ remoteModel :state . remoteModel } :{}) }); 1578patchRun ( sessionId , run . id , r => ({ ...r , job :started . run })); 1579void followTimeSkip ( sessionId , run . id ); 1580} catch ( e ) { 1581const message = plainTimeSkipError ( e instanceof Error ?e . message :String ( e )); 1582patchRun ( sessionId , run . id , r => ({ ...r , completedAt :Date . now (), job :{ ...r . job ! , phase :'failed' , error :message } }), tr ( 'Time-skip could not start. {0}' , [ message ])); 1583markTurn ( sessionId , null ); 1584} 1585} 1586 1587const followingTimeSkips = new Set < string >(); 1588/** Read the job's record until it ends. Safe to call again for a run already being followed. */ 1589export async function followTimeSkip ( sessionId :string , runId :string ) { 1590const key = sessionId + ':' + runId ; 1591if ( followingTimeSkips . has ( key )) return ; 1592followingTimeSkips . add ( key ); 1593let misses = 0 ; 1594try { 1595for (;;) { 1596const run = state . sessions . find ( s => s . id === sessionId )?. timeSkips ?. find ( r => r . id === runId ); 1597if ( ! run ?. job ?. id || run . completedAt ) return ; 1598let job :TimeSkipJob | null = null ; 1599try { job = ( await api . get <{ run :TimeSkipJob }>( '/api/timeskip/status?id=' + encodeURIComponent ( run . job . id ))). run ; misses = 0 ; } 1600catch { misses += 1 ; } 1601if ( job && TS_TERMINAL . includes ( job . phase )) { 1602let files :TimeSkipFile [] = [], extra :Partial < TimeSkipJob > = {}; 1603// The changed files are what the person came for: ask again a few times before settling for "nothing to compare". 1604for ( let tryNo = 0 ; tryNo < 4 ; tryNo ++ ) { 1605try { 1606const found = await api . get <{ files :TimeSkipFile []; applyAttempt :number | null ; more :number }>( '/api/timeskip/files?id=' + encodeURIComponent ( job . id )); 1607files = found . files ; extra = { files :found . files , applyAttempt :found . applyAttempt , moreFiles :found . more }; 1608break ; 1609} catch { await new Promise ( r => setTimeout ( r , 700 * ( tryNo + 1 ))); } 1610} 1611const finished = { ...job , ...forkFields ( job as unknown as Record < string , unknown >) }; 1612patchRun ( sessionId , runId , r => ({ ...r , completedAt :Date . now (), job :{ ...r . job ! , ...finished , ...extra } }), timeSkipEnding ( finished , files )); 1613// A run that changed files opens the comparison; one that changed nothing, failed or was stopped has no sidebar tab. 1614if ( files . length > 0 && ! [ 'failed' , 'cancelled' , 'interrupted' ]. includes ( finished . phase )) patchSession ( sessionId , s => ({ ...s , previewOpen :timeSkipTabId ( runId ) })); 1615markTurn ( sessionId , null ); 1616return ; 1617} 1618if ( job ) { const live = { ...job , ...forkFields ( job as unknown as Record < string , unknown >) }; patchRun ( sessionId , runId , r => ({ ...r , job :{ ...r . job ! , ...live } })); } 1619if ( misses >= 6 ) { 1620patchRun ( sessionId , runId , r => ({ ...r , completedAt :Date . now (), job :{ ...r . job ! , phase :'interrupted' } }), tr ( 'Time-skip lost contact with the app and stopped. Your files were not changed.' )); 1621markTurn ( sessionId , null ); 1622return ; 1623} 1624await new Promise ( r => setTimeout ( r , 2000 )); 1625} 1626} finally { followingTimeSkips . delete ( key ); } 1627} 1628 1629/** Ask the host to stop a running trial. The saved version stays. */ 1630export async function stopTimeSkip ( sessionId :string , runId :string ) { 1631const id = state . sessions . find ( s => s . id === sessionId )?. timeSkips ?. find ( r => r . id === runId )?. job ?. id ; 1632if ( id ) await api . post ( '/api/timeskip/stop' , { id}). catch (() => undefined ); 1633} 1634 1635/** Put the update into the person's files, or put the original back. Both are checked and undoable. */ 1636export async function keepTimeSkip ( sessionId :string , runId :string , version :TimeSkipVersion ) { 1637const run = state . sessions . find ( s => s . id === sessionId )?. timeSkips ?. find ( r => r . id === runId ); 1638const job = run ?. job ; 1639if ( ! run || ! job ?. id || ! job . phase || ! TS_TERMINAL . includes ( job . phase )) return ; 1640if (( run . retainedVersion ?? 'original' ) === version && ! ( isForkJob ( job ) && run . retainedVersion === undefined )) { patchRun ( sessionId , runId , r => ({ ...r , retainedVersion :version })); return ; } 1641try { 1642if ( isForkJob ( job )) await api . post ( '/api/timeskip/apply' , { id :job . id , which :version === 'original' ?'a' :'b' }); 1643else if ( version === 'updated' ) await api . post ( '/api/timeskip/apply' , { id :job . id , attempt :job . applyAttempt ?? null }); 1644else await api . post ( '/api/timeskip/apply' , { id :job . id , restore :true }); 1645patchRun ( sessionId , runId , r => ({ ...r , retainedVersion :version })); 1646pushToast ( 'success' , version === 'updated' ?tr ( 'The update is now in your files' ) :tr ( 'Your original files are back' )); 1647} catch ( e ) { 1648pushToast ( 'error' , tr ( 'Your files were not changed' ), plainTimeSkipError ( e instanceof Error ?e . message :String ( e ))); 1649} 1650} 1651 1652function startTimeSkipDemo ( prompt :string ) { 1653if ( ! prompt ) { pushToast ( 'info' , 'Add a prompt after /time-skip' , 'For example: /time-skip Make a launch plan for my app' ); return ; } 1654const sessionId = state . activeSession ?? newSession (). id ; 1655const run :TimeSkipRun = { id :uid ( 'ts' ), prompt, startedAt :Date . now () }; 1656const at = new Date (). toISOString (); 1657patchSession ( sessionId , s => ({ ...s , 1658defaultTitle :false , 1659title :s . messages . length ?s . title :shortTitle ( prompt ), updatedAt :at , 1660timeSkips :[ ...( s . timeSkips ?? []), run ], previewOpen :timeSkipTabId ( run . id ), 1661messages :[ ...s . messages , 1662{ id :uid ( 'm' ), role :'user' , at, content :`/time-skip ${ prompt } ` , timeSkipId :run . id }, 1663{ id :uid ( 'm' ), role :'assistant' , at, example :true , timeSkipId :run . id , content :'Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks; it doesn’t run your model.' }, 1664], 1665})); 1666scheduleTimeSkip ( sessionId , run ); 1667go ( 'chat' , sessionId ); 1668} 1669 1670function markTurn ( sessionId :string , turn :{ abort :AbortController ; agent :boolean } | null ) { 1671if ( turn ) liveTurns . set ( sessionId , turn ); else liveTurns . delete ( sessionId ); 1672set ({ streaming :!! state . activeSession && liveTurns . has ( state . activeSession ), liveChats :liveTurns . size }); 1673document . documentElement . dataset . streaming = liveTurns . size ?'true' :'false' ; 1674} 1675 1676/** 1677* Stop the open chat's turn. The host is asked first: for an agent turn it cancels exactly this chat's 1678* Harness session and answers only once the turn has ended, and the stream then closes by itself with 1679* what was produced. For any other turn the host reports nothing to stop and the request is aborted. 1680*/ 1681export function stopStreaming () { 1682const id = state . activeSession ; 1683const turn = id ?liveTurns . get ( id ) :undefined ; 1684if ( ! id || ! turn ) return ; 1685const abort = () => { turn . abort . abort (); }; 1686void api . post <{ stopped :boolean }>( '/api/chat/stop' , { sessionId :id }). then ( 1687result => { 1688if ( ! result . stopped ) abort (); 1689// An agent turn that was told to stop but is slow to end must not leave the chat stuck. 1690else setTimeout (() => { if ( liveTurns . get ( id ) === turn ) abort (); }, 30000 ); 1691}, 1692abort , 1693); 1694} 1695 1696/** 1697* Re-runs the last exchange: drops the assistant reply and asks again. 1698* 1699* Kept in the store rather than the screen because it has to touch the message 1700* list, and every attempt to do this from a component ends up duplicating the 1701* stream handling that already lives here. 1702*/ 1703export async function retryLast ( messageId ?:string ) { 1704const source = state . sessions . find ( s => s . id === state . activeSession ); 1705if ( ! source || state . streaming ) return ; 1706const end = messageId ?source . messages . findIndex ( m => m . id === messageId ) :source . messages . length - 1 ; 1707const user = source . messages . slice ( 0 , end + 1 ). reverse (). find ( m => m . role === 'user' ); 1708if ( ! user ) return ; 1709const prompt = rewindTo ( user . id ); 1710if ( prompt !== null ) { 1711// Retry sends immediately; only Edit should leave the prompt in the composer. 1712sessionStorage . setItem ( `strata.chat-draft. ${ state . activeSession } ` , '' ); 1713await sendMessage ( prompt ); 1714} 1715} 1716 1717/** The open chat's last question and the answer that failed under it (null when the chat does not end that way). */ 1718function failedExchange () :{ prompt :string ; sessionId :string } | null { 1719const sessionId = state . activeSession ; 1720const chat = state . sessions . find ( s => s . id === sessionId ); 1721if ( ! sessionId || ! chat || state . streaming ) return null ; 1722const reply = chat . messages [ chat . messages . length - 1 ], ask = chat . messages [ chat . messages . length - 2 ]; 1723return reply ?. role === 'assistant' && reply . error && ask ?. role === 'user' ?{ prompt :ask . content , sessionId} :null ; 1724} 1725/** Takes the failed question and its error out of the transcript, so asking again does not show the question twice. */ 1726function dropFailedExchange ( sessionId :string ) { 1727patchSession ( sessionId , s => ({ ...s , messages :s . messages . slice ( 0 , - 2 ) })); 1728} 1729 1730/** 1731* The error card of a conversation that no longer fits the model's window: summarise the older messages (the same as typing /compact), then 1732* ask the assistant to answer. The refused question is already in the assistant's conversation (it is the newest message, and a summary keeps 1733* the newest message as it is), so it is not sent a second time: a large one twice would not fit either. 1734*/ 1735export async function summarizeAndContinue () { 1736if ( ! failedExchange ()) return ; 1737await sendMessage ( '/compact' ); 1738await sendMessage ( 'Please answer my last message now.' ); 1739} 1740 1741/** 1742* The error card of a message that is too large to send: the host makes it small enough (its text as a file in the chat's folder that the 1743* assistant reads in parts, or a shortened preview), and that is sent in its place. 1744*/ 1745export async function sendOversized ( mode :'file' | 'preview' ) { 1746const failed = failedExchange (); 1747if ( ! failed ) return ; 1748let reply :{ message ?:string }; 1749try { 1750reply = await api . post <{ message ?:string }>( '/api/chat/oversize' , { sessionId :failed . sessionId , mode, text :failed . prompt , nativeModelId :nativeState ()?. instances . length ?nativeState ()?. defaultId :undefined }); 1751} catch { 1752pushToast ( 'error' , 'The message could not be prepared. Try a shorter message.' ); 1753return ; 1754} 1755if ( ! reply . message ) return ; 1756dropFailedExchange ( failed . sessionId ); 1757await sendMessage ( reply . message ); 1758} 1759 1760/** A new, empty chat, opened. */ 1761export function startNewChat () { 1762const session = newSession (); 1763go ( 'chat' , session . id ); 1764} 1765 1766/** 1767* Forks a conversation at a message, leaving the original untouched. 1768* 1769* The alternative people reach for is duplicating the whole session and 1770* deleting messages by hand, which loses the original. Branching keeps both: 1771* the new session carries the history up to the chosen turn and diverges there. 1772*/ 1773export function branchFrom ( messageId :string ) :string | null { 1774const sessionId = state . activeSession ; 1775if ( ! sessionId ) return null ; 1776const source = state . sessions . find (( s ) => s . id === sessionId ); 1777if ( ! source ) return null ; 1778const at = source . messages . findIndex (( m ) => m . id === messageId ); 1779if ( at < 0 ) return null ; 1780 1781const now = new Date (). toISOString (); 1782const branch :Session = { 1783 ...source , 1784id :uid ( 's' ), 1785title :` ${ source . title } (branch)` , 1786defaultTitle :false , 1787createdAt :now , 1788updatedAt :now , 1789messages :source . messages . slice ( 0 , at + 1 ). map (( m ) => ({ ...m , id :uid ( 'm' ) })), 1790tokensIn :0 , 1791tokensOut :source . messages . slice ( 0 , at + 1 ). reduce (( n , m ) => n + ( m . tokens ?? 0 ), 0 ), 1792statsAvailable :false , 1793}; 1794const sessions = [ branch , ...state . sessions ]; 1795persistSessions ( sessions ); 1796set ({ sessions, activeSession :branch . id }); 1797for ( const run of branch . timeSkips ?? []) scheduleTimeSkip ( branch . id , run ); 1798// The URL wins over `activeSession` when it names a session, so a programmatic 1799// switch has to move the route too — otherwise the sidebar shows the branch 1800// while the transcript still shows the original, which reads as a broken 1801// button rather than a created branch. 1802navigate ( 'chat' , branch . id ); 1803return branch . id ; 1804} 1805 1806/** 1807* Asks the model to keep going from where it stopped. 1808* 1809* Sent as an ordinary user turn rather than a special mode, because that is 1810* what it is: a continuation is a request, and the transcript should show it. 1811*/ 1812export async function continueLast () { 1813const sessionId = state . activeSession ; 1814if ( ! sessionId || state . streaming ) return ; 1815const session = state . sessions . find (( s ) => s . id === sessionId ); 1816const last = session ?. messages [ session . messages . length - 1 ]; 1817if ( ! last || last . role !== 'assistant' || ! last . content . trim ()) return ; 1818await sendMessage ( 'Continue from where you left off. Do not repeat what you have already written.' ); 1819} 1820 1821/** 1822* Rewinds the transcript to just before a turn so it can be re-asked with a 1823* different prompt. Returns the text so the composer can be filled with it. 1824*/ 1825export function rewindTo ( messageId :string ) :string | null { 1826if ( state . streaming ) return null ; 1827const source = state . sessions . find ( s => s . id === state . activeSession ); 1828const at = source ?. messages . findIndex ( m => m . id === messageId ) ?? - 1 ; 1829if ( ! source || at < 0 ) return null ; 1830const prompt = source . messages [ at ]. content ; 1831const branchId = branchFrom ( messageId ); 1832if ( ! branchId ) return null ; 1833patchSession ( branchId , s => ({ ...s , messages :s . messages . slice ( 0 , - 1 ), tokensIn :0 , tokensOut :s . messages . slice ( 0 , - 1 ). reduce (( n , m ) => n + ( m . tokens ?? 0 ), 0 ) })); 1834sessionStorage . setItem ( `strata.chat-draft. ${ branchId } ` , prompt ); 1835return prompt ; 1836} 1837 1838export function exportConversation () { 1839const session = state . sessions . find ( s => s . id === state . activeSession ); 1840if ( ! session ) return ; 1841const text = '# ' + session . title + '\n\n' + session . messages . map ( m => '## ' + m . role + '\n\n' + ( m . role === 'assistant' ?tidyAnswer ( m . content ) :m . content )). join ( '\n\n' ); 1842const url = URL . createObjectURL ( new Blob ([ text ], { type :'text/markdown' })); 1843const a = document . createElement ( 'a' ); a . href = url ; a . download = session . title . replace ( / [^a-z0-9 -] / gi , '' ). slice ( 0 , 60 ) + '.md' ; 1844document . body . append ( a ); a . click (); a . remove (); 1845// Keep the Blob alive until browsers have started consuming the download. 1846setTimeout (() => URL . revokeObjectURL ( url ), 1000 ); 1847} 1848 1849/* ---------------------------------------------------------------- /loop 1850The same message, again and again, while the chat is open. The scheduler (count, time, "the answer says it is done") is 1851lib/loop-runner.ts; this is the part that talks to the chat. See lib/loop.ts. */ 1852 1853/** A line from the app itself (not the model) in the transcript. It is never sent to the model. */ 1854function addNote ( sessionId :string , content :string ) { 1855const at = new Date (). toISOString (); 1856patchSession ( sessionId , s => ({ ...s , updatedAt :at , messages :[ ...s . messages , { id :uid ( 'm' ), role :'assistant' , at, content, local :true }] })); 1857} 1858 1859const lastAnswer = ( sessionId :string ) => [ ...( state . sessions . find ( s => s . id === sessionId )?. messages ?? [])]. reverse (). find ( m => m . role === 'assistant' && ! m . local ); 1860 1861const loopScheduler = new LoopScheduler ({ 1862async send ( sessionId , { text, shown}) { 1863const before = lastAnswer ( sessionId )?. id ; 1864await sendMessage ( text , { fromLoop :true , shown, title :shortTitle ( shown ) }); 1865const answer = lastAnswer ( sessionId ); 1866if ( ! answer || answer . id === before || answer . streaming ) return { answered :false , text :'' , failed :false }; 1867return { answered :true , text :answer . content ?? '' , failed :!! answer . error }; 1868}, 1869note :addNote , 1870exists :sessionId => state . sessions . some ( s => s . id === sessionId ), 1871ready :sessionId => state . activeSession === sessionId && ! state . streaming , 1872now :() => Date . now (), 1873setTimer :( fn , ms ) => setTimeout ( fn , ms ), 1874clearTimer :handle => clearTimeout ( handle as ReturnType < typeof setTimeout >), 1875track :( sessionId , loop ) => patchSession ( sessionId , s => ({ ...s , loop})), 1876}); 1877 1878export function loopIsRunning ( sessionId :string | null ) :boolean { return loopScheduler . isRunning ( sessionId ); } 1879 1880/* ------------------------------------------------------------- task board */ 1881 1882/** The chats with a turn going, and the chats with a loop going: what the board needs besides the sessions themselves. */ 1883export function liveChatIds () :string [] { return [ ...liveTurns . keys ()]; } 1884export function loopChatIds () :string [] { return loopScheduler . ids (); } 1885 1886/** Stop any chat's turn, not only the open one (the board's Stop). Same two-step as stopStreaming. */ 1887export function stopChat ( id :string ) { 1888const turn = liveTurns . get ( id ); 1889if ( ! turn ) return ; 1890const abort = () => { turn . abort . abort (); }; 1891void api . post <{ stopped :boolean }>( '/api/chat/stop' , { sessionId :id }). then ( 1892result => { if ( ! result . stopped ) abort (); else setTimeout (() => { if ( liveTurns . get ( id ) === turn ) abort (); }, 30000 ); }, 1893abort , 1894); 1895} 1896 1897/** Stop a chat's loop from the board. The chat gets the same line /loop stop writes. */ 1898export function stopLoop ( id :string ) { 1899if ( loopScheduler . stop ( id )) addNote ( id , tr ( 'The loop is stopped.' )); 1900} 1901 1902/** Dismiss a chat's (or its loop's) card: it leaves the board until something newer goes wrong. The chat itself is untouched. */ 1903export function dismissChat ( id :string ) { 1904const sessions = state . sessions . map ( s => ( s . id === id ?{ ...s , ackedAt :new Date (). toISOString () } :s )); 1905persistSessions ( sessions ); 1906set ({ sessions}); 1907} 1908 1909/** Answer a waiting tool card in any chat (the board's Approve and Deny). Only a live card has an approval behind it. */ 1910export function answerChatTool ( sessionId :string , messageId :string , toolId :string , approved :boolean ) { 1911const tool = state . sessions . find ( s => s . id === sessionId )?. messages . find ( m => m . id === messageId )?. tools ?. find ( t => t . id === toolId ); 1912if ( tool ?. live && tool . state === 'proposed' ) answerAgentTool ( sessionId , messageId , tool , approved ); 1913} 1914 1915/** "Continue in a new chat" on a chat or a loop that went wrong: a new chat that starts from what happened (src/lib/task-handover.ts). */ 1916export function continueChatInNewChat ( sessionId :string ) { 1917const old = state . sessions . find ( s => s . id === sessionId ); 1918if ( ! old ) return ; 1919const session = newSession (); 1920go ( 'chat' , session . id ); 1921void sendMessage ( chatHandoverMessage ( old ), { title :chatHandoverTitle ( old ), markdown :true }); 1922} 1923 1924async function runLoopCommand ( command :LoopCommand ) { 1925const sessionId = state . activeSession ?? newSession (). id ; 1926const say = ( content :string ) => { addNote ( sessionId , content ); go ( 'chat' , sessionId ); }; 1927if ( command . kind === 'help' ) { say ( tr ( command . problem ) + '\n\n' + tr ( LOOP_USAGE )); return ; } 1928if ( command . kind === 'status' ) { say ( loopScheduler . describe ( sessionId ) ?? tr ( 'No loop is running in this chat.' ) + '\n\n' + tr ( LOOP_USAGE )); return ; } 1929if ( command . kind === 'stop' ) { say ( loopScheduler . stop ( sessionId ) ?tr ( 'The loop is stopped.' ) :tr ( 'No loop is running in this chat.' )); return ; } 1930go ( 'chat' , sessionId ); 1931await loopScheduler . start ( sessionId , command ); 1932} 1933 1934/** Carry on a paused goal: the host runs its rounds again. No message is sent and no bubble is added. */ 1935export async function resumeGoal () { await sendMessage ( '' , { goalAction :'resume' }); } 1936 1937/** Approve a proposed plan and carry it out: the host answers with the message that does the work, which goes out as an ordinary turn. */ 1938export async function approvePlan ( sessionId :string , planId :string ) { 1939const { prompt} = await planApprove ( sessionId , planId ); 1940// A chat in Plan mode only reads; carrying the plan out needs a mode that may act. 1941if ( state . sessions . find ( s => s . id === sessionId )?. preferences ?. mode === 'plan' ) setChatPreferences ( sessionId , { mode :'manual' }); 1942if ( prompt ) await sendMessage ( prompt , { shown :tr ( 'Approved the plan.' ) }); 1943} 1944 1945/** "Start as goal" (and Resume on a paused plan): the host streams the run like any chat turn. */ 1946export async function startPlanGoal ( planId :string ) { await sendMessage ( '' , { planId}); } 1947 1948export async function sendMessage ( text :string , options :{ fromLoop ?:boolean ; goalAction ?:'resume' ; planId ?:string ; shown ?:string ; title ?:string ; markdown ?:boolean ; reattach ?:string ; requestId ?:string } = {}) { 1949// `reattach`: a turn the host is still running for this chat (or finished while the page was away) is taken over again after a reload, not started. 1950const reattach = options . reattach ; 1951if ( state . streaming && ! reattach ) { 1952// Typed while the assistant works: behind a running goal it waits in the queue; otherwise there is nothing to do but wait. 1953const waiting = state . activeSession , line = text . trim (); 1954if ( waiting && line && ! options . planId && ! options . goalAction ) { 1955try { if ( ! ( await queueMessage ( waiting , line ))) pushToast ( 'info' , 'The assistant is still answering' , 'Send your message when it has finished.' ); } 1956catch ( e ) { pushToast ( 'error' , 'The message was not queued' , plainFailureText ( e instanceof Error ?e . message :String ( e )). message ); } 1957} 1958return ; 1959} 1960const resume = options . goalAction === 'resume' ; 1961const planStart = options . planId ; 1962const loopCommand = options . fromLoop || resume || planStart || reattach ?null :parseLoop ( text . trim ()); 1963if ( loopCommand ) { await runLoopCommand ( loopCommand ); return ; } 1964const demoPrompt = resume || planStart || reattach ?null :timeSkipPrompt ( text . trim ()); 1965if ( demoPrompt !== null ) { 1966if ( demoPrompt && ( state . remoteModel || nativeState ()?. instances . some ( i => i . status === 'ready' ))) void startTimeSkipReal ( demoPrompt ); else if ( state . connection === 'live' && demoPrompt ) pushToast ( 'info' , 'Load a model first' , 'Time-skip works on a loaded model. Choose one on the Models tab, then try again.' ); 1967else if ( state . connection === 'connecting' && demoPrompt ) pushToast ( 'info' , 'Still starting up' , 'Time-skip needs the app to finish starting. Try again in a moment.' ); 1968else startTimeSkipDemo ( demoPrompt ); 1969return ; 1970} 1971// Whatever sent this (the box, a loop, a plan): with no model to answer, say so in plain words and start nothing. 1972if ( state . connection === 'live' && ! reattach ) { 1973// The first read of the engine's state has not come back yet: do not say "no model" about something not known yet, and do not send. 1974if ( ! nativeState () && ! state . remoteModel && ! state . library ?. loaded ) { pushToast ( 'info' , 'Still starting up' , 'Strata is still checking your models. Try again in a moment.' ); return ; } 1975const why = noModelNotice ( nativeState (), { remote :!! state . remoteModel , libraryLoaded :!! state . library ?. loaded }); 1976if ( why ) { pushToast ( 'info' , why . title , why . message ); return ; } 1977} 1978const pictureCheck = pictureStatus ( nativeState (), state . remoteModel , state . providers ); 1979if ( ! reattach && pendingChatPhotos ( state . activeSession ). length &&! pictureCheck . ok ){ pushToast ( 'error' , 'This model cannot read pictures' , tr ( pictureCheck . message )); return ;} 1980const pictures = reattach ?[] :takeChatPhotos ( state . activeSession ); 1981const body = text . trim () || ( pictures . length ?'Describe this picture.' :'' ); 1982if ( ! body &&! resume &&! planStart &&! reattach ) return ; 1983 1984let sessionId = reattach ?? state . activeSession ; 1985if ( ! sessionId ) sessionId = newSession (). id ; 1986 1987const userMsg :ChatMessage = { id :uid ( 'm' ), role :'user' , content :options . shown ?? body , at :new Date (). toISOString (), ...( pictures . length ?{ photos :pictures } :{}), ...( options . markdown ?{ markdown :true } :{}) }; 1988// A taken-over turn goes on in the reply the page already has (the last one, if it is the assistant's). 1989const lastReply = reattach ?[ ...( state . sessions . find ( s => s . id === sessionId )?. messages ?? [])]. reverse ()[ 0 ] :undefined ; 1990const resumedReply = lastReply ?. role === 'assistant' ?lastReply :undefined ; 1991let assistantId = resumedReply ?. id ?? uid ( 'm' ); 1992const assistantMsg :ChatMessage = { 1993id :assistantId , 1994role :'assistant' , 1995content :'' , 1996at :new Date (). toISOString (), 1997streaming :true , 1998}; 1999 2000/* Everything said before this turn, which the model needs in order to have a 2001conversation at all. 2002 2003It was never sent. The real-engine path builds its prompt as 2004`[...history, message]`, and `history` was always empty, so each message 2005arrived as the first thing the model had ever heard — no memory of the 2006turns above it in the transcript. The demo path hides this, because its 2007replies are canned. 2008 2009The context meter was reading the same empty array, which is why it sat at 2010~350 tokens however long the conversation grew. */ 2011const prior = ( state . sessions . find (( s ) => s . id === sessionId )?. messages ?? []) 2012. filter ( m => ! m . timeSkipId && ! m . local ) 2013. filter (( m ) => m . role === 'user' || m . role === 'assistant' ) 2014. filter (( m ) => m . content . trim ()) 2015. map (( m ) => ({ role :m . role , content :m . content , photos :m . photos })) 2016// Bounded so a long conversation cannot send an unbounded body. 2017. slice ( - 40 ); 2018 2019patchSession ( sessionId , ( s ) => reattach ?({ 2020 ...s , 2021messages :resumedReply 2022 ?s . messages . map ( m => m . id === resumedReply . id ?{ ...m , streaming :true } :m ) 2023 :[ ...s . messages , assistantMsg ], 2024}) :({ 2025 ...s , 2026defaultTitle :false , 2027title :s . messages . length === 0 && ! resume && ! planStart ?( options . title ?? ( shortTitle ( body ))) :s . title , 2028updatedAt :new Date (). toISOString (), 2029messages :[ ...s . messages , ...( resume || planStart ?[] :[ userMsg ]), assistantMsg ], 2030})); 2031 2032const turnAbort = new AbortController (); 2033markTurn ( sessionId , { abort :turnAbort , agent :false }); 2034// Read by the router to skip view transitions mid-stream, and by CSS to keep 2035// the transcript still while tokens arrive. 2036 2037const patchAssistant = ( fn :( m :ChatMessage ) => ChatMessage ) => 2038patchSession ( sessionId , ( s ) => ({ 2039 ...s , 2040updatedAt :new Date (). toISOString (), 2041messages :s . messages . map (( m ) => ( m . id === assistantId ?fn ( m ) :m )), 2042})); 2043 2044const started = performance . now (); 2045 2046const imageSlots = photoHistorySlots ( prior , pictures . length ); 2047/* Text and reasoning arrive token by token (90 a second or more). Drawing the whole answer again for each one made the page do more work for every 2048word the longer the answer grew (measured: 15.7 s of main-thread time for 24 s of a 40,000-token answer), until the page stopped answering 2049and ran out of memory. The pieces are gathered and applied together about ten times a second; any other frame, the end and a failure 2050apply what is waiting first, so the order the person sees is the order it was written. */ 2051const waiting :[ 'reasoning' | 'delta' , string ][] = []; 2052let waitingTimer :ReturnType < typeof setTimeout > | null = null ; 2053const applyReasoning = ( text :string ) => patchAssistant (( m ) => ({ ...m , reasoning :( m . reasoning ?? '' ) + text , reasoningStartedAt :m . reasoningStartedAt ?? Date . now () })); 2054const applyDelta = ( text :string ) => patchAssistant (( m ) => { const content = tidyAnswer ( m . content + text ); if ( m . reasoningStartedAt && m . reasoningMs === undefined ) m = { ...m , reasoningMs :Date . now () - m . reasoningStartedAt }; const count = Math . max ( 1 , Math . ceil (( content . length + ( m . reasoning ?. length ?? 0 )) / 4 )); return { ...m , content, ...( m . blocks ?{ blocks :appendText ( m . blocks , text )} :{}), tokens :m . usageSource === 'estimated' && m . tps ?m . tokens :count , inputTokens :m . inputTokens ?? Math . ceil (( body . length + prior . reduce (( n , p ) => n + p . content . length , 0 )) / 4 ), usageSource :'estimated' }; }); 2055const flushWaiting = () => { 2056if ( waitingTimer !== null ) { clearTimeout ( waitingTimer ); waitingTimer = null ; } 2057for ( const [ kind , text ] of waiting . splice ( 0 )) if ( kind === 'delta' ) applyDelta ( text ); else applyReasoning ( text ); 2058}; 2059const queueText = ( kind :'reasoning' | 'delta' , text :string ) => { 2060const last = waiting [ waiting . length - 1 ]; 2061if ( last && last [ 0 ] === kind ) last [ 1 ] += text ; else waiting . push ([ kind , text ]); 2062waitingTimer ??= setTimeout ( flushWaiting , 90 ); 2063}; 2064try { 2065await streamPost ( 2066reattach ?'/api/chat/attach' :planStart ?'/api/plan/start-goal' :'/api/chat/stream' , 2067reattach ?{ sessionId, ...( options . requestId ?{ requestId :options . requestId } :{}) } :{ 2068 sessionId, 2069 ...( planStart ?{ planId :planStart } :{}), 2070 ...( resume ?{ goalAction :'resume' } :planStart ?{} :{ message :options . shown ?body :body }), 2071history :await Promise . all ( prior . map ( async ( m , index ) => { const included = pictureCheck . ok ?( m . photos ?? []). filter (( _ , p ) => imageSlots . has ( ` ${ index } : ${ p } ` )) :[]; const omitted = ( m . photos ?? []). filter ( p =>! included . includes ( p )); const text = m . content + ( omitted . length ?`\n[Earlier pictures: ${ omitted . map ( p => p . name ). join ( ', ' )} . Their pixels are outside this model's image context; ask to reattach them if needed.]` :'' ); return { role :m . role , content :included . length ?[{ type :'text' , text}, ...await Promise . all ( included . map ( async photo => ({ type :'image_url' , image_url :{ url :( await photoData ( photo )). url }})))] :text };})), 2072model :state . library ?. loaded ?? state . library ?. current ?? null , 2073remoteModel :state . remoteModel , 2074nativeModelId :nativeState ()?. instances . length ?nativeState ()?. defaultId :undefined , 2075 ...( pictures . length ?{ imageIds :await uploadChatPhotos ( pictures , sessionId ) } :{}), 2076useTools :state . sessions . find ( s => s . id === sessionId )?. preferences ?. useTools === true , 2077// A chat set to plain talk (preferences.agent === false) never runs a tool: the host answers it directly. 2078 ...( state . sessions . find ( s => s . id === sessionId )?. preferences ?. agent === false ?{ agent :false } :{}), 2079thinking :state . sessions . find ( s => s . id === sessionId )?. preferences ?. thinking ?? 'Medium' , 2080thinkingBudget :state . sessions . find ( s => s . id === sessionId )?. preferences ?. thinkingBudget ?? 0 , 2081// The Mode menu's choice for this chat, read when the turn starts; the host applies it to the agent. 2082mode :state . sessions . find ( s => s . id === sessionId )?. preferences ?. mode ?? 'manual' , 2083// So a skill narrowed to another workspace does not fire here. 2084workspaceId :workspaceIdForSession ( state . workspaces , state . sessions . find ( s => s . id === sessionId )) ?? state . activeWorkspace , 2085}, 2086( frame ) => { 2087// A line from the app itself carries `key` (the English sentence): shown in the person's language. 2088if ( frame . type === 'delta' && typeof frame . key === 'string' ) frame = { ...frame , text :tr ( frame . key , Array . isArray ( frame . values ) ?frame . values :undefined ) }; 2089const type = frame . type as string ; 2090if ( type === 'delta' || type === 'reasoning' ) { queueText ( type , String ( frame . text ?? '' )); return ; } 2091flushWaiting (); 2092if ( type === 'start' && frame . agent === true ) { const turn = liveTurns . get ( sessionId ); if ( turn ) turn . agent = true ; } 2093// The host has a turn to take over: the failure the page wrote when it lost the stream no longer applies. 2094if ( type === 'start' && frame . resumed === true ) patchAssistant ( m => ({ ...m , error :undefined , errorCode :undefined })); 2095if ( type === 'queued' ) { 2096patchAssistant ( m => ({ ...m , requestId :String ( frame . requestId ) })); 2097} else if ( type === 'start' ) { 2098patchAssistant (( m ) => ({ ...m , demo :frame . demo === true , remoteModel :frame . remoteModel === true , requestId :typeof frame . requestId === 'string' ?frame . requestId :m . requestId , model :String ( frame . model ), contextMax :Number ( frame . contextMax ), skillsUsed :Array . isArray ( frame . skills ) ?frame . skills . map ( String ) :[] })); 2099} else if ( type === 'resync' ) { 2100// A taken-over turn: what was said while no page was here. The reply continues from what the page had; where the two disagree the host's text stands. 2101const said = String ( frame . content ?? '' ), thought = String ( frame . reasoning ?? '' ); 2102patchAssistant ( m => { 2103let next = m ; 2104if ( said ) next = said . startsWith ( next . content ) ?{ ...next , content :tidyAnswer ( said ), ...( next . blocks && said . length > next . content . length ?{ blocks :appendText ( next . blocks , said . slice ( next . content . length )) } :{}) } :{ ...next , content :tidyAnswer ( said ), blocks :undefined }; 2105if ( thought && thought . length >= ( next . reasoning ?? '' ). length ) next = { ...next , reasoning :thought , reasoningStartedAt :next . reasoningStartedAt ?? Date . now () }; 2106return next ; 2107}); 2108} else if ( type === 'status' ) { 2109applyStatusFrame ( sessionId , frame as Record < string , unknown >); 2110// Manual mode waits for the person: a notification when they have opted in and Strata is in the background (#3477), once per question. 2111if ( frame . code === 'waiting-approval' && lastApprovalNotice !== ` ${ sessionId } : ${ String ( frame . seq )} ` ) { 2112lastApprovalNotice = ` ${ sessionId } : ${ String ( frame . seq )} ` ; 2113const tool = ( frame . args as { tool ?:unknown } | undefined )?. tool ; 2114void approvalNeeded ( state . approvalNotify , typeof tool === 'string' ?tool :'' ); 2115} 2116} else if ( type === 'goal' ) { 2117applyGoalFrame ( sessionId , frame . goal ); 2118} else if ( type === 'plan' ) { 2119applyPlanFrame ( sessionId , frame . plan ); 2120// A proposed plan is shown as the plan card in place of this turn's closing text (that text is the plan in prose). 2121const planned = frame . plan as { id ?:unknown } | null ; 2122if ( frame . event === 'proposed' && planned && typeof planned . id === 'string' ) { const pid = planned . id ; patchAssistant ( m => ({ ...m , planId :pid })); } 2123} else if ( type === 'queued-message' ) { 2124applyQueueFrame ( sessionId , frame . queue ); 2125const sent = frame . message as { text ?:unknown } | undefined ; 2126if ( frame . state === 'delivered' && sent && typeof sent . text === 'string' ) { 2127// The host has just sent it into the run: it becomes an ordinary message here, and the answer to it starts a new reply. 2128const before = assistantId ; assistantId = uid ( 'm' ); 2129const next :ChatMessage = { id :assistantId , role :'assistant' , content :'' , at :new Date (). toISOString (), streaming :true }; 2130patchSession ( sessionId , sess => ({ ...sess , messages :[ ...sess . messages . map ( m => m . id === before ?{ ...m , streaming :false } :m ), { id :uid ( 'm' ), role :'user' , content :sent . text as string , at :new Date (). toISOString () }, next ] })); 2131} 2132} else if ( type === 'queued-release' ) { 2133// The goal ended with messages left: they go out now, in order, as ordinary messages once this turn has finished. 2134const left = Array . isArray ( frame . messages ) ?frame . messages . flatMap ( q => ( q && typeof ( q as { text ?:unknown }). text === 'string' ?[ String (( q as { text :string }). text )] :[])) :[]; 2135if ( left . length ) releasedMessages . set ( sessionId , [ ...( releasedMessages . get ( sessionId ) ?? []), ...left ]); 2136} else if ( type === 'plan-step' ) { 2137/* the whole plan follows in a plan frame; the live status already says which step is running */ 2138} else if ( type === 'reasoning' ) { 2139/* applied through queueText above */ 2140} else if ( type === 'notice' ) { 2141// The host says why this chat is not using the agent. One toast per reason per page load. 2142const code = String ( frame . code ?? 'notice' ); 2143if ( ! noticed . has ( code )) { noticed . add ( code ); pushToast ( 'info' , 'Agent' , plainFailureText ( String ( frame . message ?? '' )). message ); } 2144} else if ( type === 'agent-question' ) { 2145addAgentAsk ( sessionId , frame as { callId ?:unknown ; questions ?:unknown }); 2146} else if ( type === 'agent-question-end' ) { 2147removeAgentAsk ( sessionId , String ( frame . callId ?? '' )); 2148} else if ( type === 'agent-tool-draft' ) { 2149// A tool call (a whole file, say) is being written: keep its name, size and the tail of its text on the reply until the call is whole or lost. 2150const d = frame . draft as ( ToolDraft & { done ?:boolean }) | undefined ; 2151if ( d && typeof d . id === 'string' ) { 2152const { done, ...view } = d ; 2153patchAssistant ( m => { 2154const rest = ( m . drafts ?? []). filter ( x => x . id !== d . id ); 2155return { ...m , drafts :done ?( rest . length ?rest :undefined ) :[ ...rest , view ] }; 2156}); 2157} 2158} else if ( type === 'agent-tool' ) { 2159const tool = frame . tool as ToolCall ; 2160patchAssistant ( m => { 2161const existing = m . tools ?. find ( t => t . id === tool . id ); 2162const next :ToolCall = { ...existing , ...tool , live :true }; 2163return { ...m , tools :existing ?m . tools ! . map ( t => t . id === tool . id ?next :t ) :[ ...( m . tools ?? []), next ] }; 2164}); 2165} else if ( type === 'agent' ) { 2166patchSession ( sessionId , s => ({ ...s , agents :updateAgent ( s . agents ?? [], frame . agent ) })); 2167} else if ( type === 'delta' ) { 2168/* applied through queueText above */ 2169} else if ( type === 'deliverable' ) { 2170const file = readDeliverable ( frame ); 2171if ( file ) patchAssistant ( m => ({ ...m , deliverables :mergeDeliverable ( m . deliverables , file ) })); 2172} else if ( type === 'skills-used' ) { 2173const skills = readSkills ( frame ); 2174if ( skills . length ) patchAssistant ( m => ({ ...m , skills})); 2175} else if ( type === 'activity-group' ) { 2176const group = readGroup ( frame ); 2177if ( group ) patchAssistant ( m => ({ ...m , blocks :upsertGroup ( m . blocks ?? ( m . content ?appendText ( undefined , m . content ) :undefined ), group ) })); 2178} else if ( type === 'artifacts' && Array . isArray ( frame . artifacts )) { 2179patchAssistant ( m => ({ ...m , artifacts :frame . artifacts as PreviewArtifact [] })); 2180} else if ( type === 'native-tool' ){ 2181const event = frame . event as { event :string ; id :string ; name ?:string ; arguments ?:Record < string , unknown >; text ?:string ; ok ?:boolean ; ms ?:number }; 2182if ( event . id ) patchAssistant ( m => { const existing = m . tools ?. find ( t => t . id === event . id ); const tool = { id :event . id , name :event . name ?? existing ?. name ?? 'Connected tool' , args :event . arguments ?? existing ?. args ?? {}, preview :'Authorized connected tool' , effect :'Access configured in the MCP server' , scope :'connected' as const , state :event . event === 'result' ?event . ok ?'done' as const :'error' as const :'running' as const , result :event . text , durationMs :event . ms }; return { ...m , tools :[ ...( m . tools ?? []). filter ( t => t . id !== tool . id ),{ ...existing , ...tool }]};}); 2183} else if ( type === 'tool' ) { 2184const tool = frame . tool as ChatMessage [ 'tools' ] extends ( inferT )[] | undefined ?T :never ; 2185patchAssistant (( m ) => ({ ...m , tools :[ ...( m . tools ?? []), { ...tool , state :'proposed' }] })); 2186} else if ( type === 'stats' ) { 2187patchAssistant (( m ) => ({ 2188 ...m , 2189tokens :typeof frame . tokensOut === 'number' ?frame . tokensOut :m . tokens , 2190tps :typeof frame . tps === 'number' ?frame . tps :m . tps , 2191promptTps :typeof frame . promptTps === 'number' ?frame . promptTps :m . promptTps , 2192})); 2193} else if ( type === 'context' ) { 2194// What the context holds after each model request of an agent turn: the meter follows the turn instead of waiting for its end. 2195const used = Number ( frame . contextTokens ), max = Number ( frame . contextMax ); 2196if ( Number . isFinite ( used ) && used > 0 ) patchAssistant (( m ) => ({ ...m , contextUsed :used , ...( Number . isFinite ( max ) && max > 0 ?{ contextMax :max } :{}) })); 2197} else if ( type === 'error' ) { 2198clearStatus ( sessionId ); 2199// A sentence the host wrote for the person (it carries its catalog key) is shown in their language as it is; anything else is made plain here. 2200const said = typeof frame . key === 'string' ?tr ( frame . key , Array . isArray ( frame . values ) ?frame . values :undefined ) :plainFailure ( String ( frame . message ?? 'Engine error' )). message ; 2201patchAssistant (( m ) => ({ ...m , drafts :undefined , error :said , streaming :false , ...( typeof frame . code === 'string' ?{ errorCode :frame . code } :{}), ...( typeof frame . details === 'string' && frame . details ?{ errorDetail :frame . details } :{}) })); 2202} else if ( type === 'done' ) { 2203clearStatus ( sessionId ); 2204workFinished ( state . doneSound , Number ( frame . durationMs ?? performance . now () - started )); 2205patchSession ( sessionId , ( sess ) => ({ 2206 ...sess , 2207tokensIn :sess . tokensIn + Number ( frame . tokensIn ?? 0 ), 2208tokensOut :sess . tokensOut + Number ( frame . tokensOut ?? 0 ), 2209statsAvailable :typeof frame . tokensIn === 'number' && typeof frame . tokensOut === 'number' && sess . messages . filter ( m => m . role === 'assistant' &&! m . streaming ). every ( m => typeof m . inputTokens === 'number' ), 2210})); 2211patchAssistant (( m ) => ({ 2212 ...m , 2213streaming :false , 2214drafts :undefined , 2215durationMs :Number ( frame . durationMs ?? performance . now () - started ), 2216tokens :typeof frame . tokensOut === 'number' ?frame . tokensOut :undefined , 2217ttftMs :typeof frame . ttftMs === 'number' ?frame . ttftMs :undefined , 2218inputTokens :typeof frame . tokensIn === 'number' ?frame . tokensIn :undefined , 2219contextUsed :typeof frame . contextTokens === 'number' ?frame . contextTokens :undefined , 2220usageSource :frame . usageSource === 'reported' || frame . usageSource === 'demo' ?frame . usageSource :'unavailable' , 2221tps :typeof frame . tps === 'number' ?frame . tps :m . tps , 2222promptTps :typeof frame . promptTps === 'number' ?frame . promptTps :m . promptTps , 2223})); 2224// The final text is in `state`: write it once now instead of waiting for the coalescing timer. 2225flushSessions (); 2226} 2227}, 2228turnAbort . signal , 2229); 2230} catch ( err ) { 2231flushWaiting (); 2232if ( reattach && ( err as { status ?:number } | null )?. status === 404 ) { 2233// Nothing to take over (the turn ended and the host no longer holds it): the reply stays as the page had it. 2234patchAssistant (( m ) => ({ ...m , streaming :false })); 2235} else if (( err as Error ). name !== 'AbortError' ) { 2236patchAssistant (( m ) => ({ 2237 ...m , 2238streaming :false , 2239error :err instanceof Error ?err . message :'Engine error' , 2240})); 2241pushToast ( 'error' , 'Generation failed' , err instanceof Error ?err . message :undefined ); 2242} else { 2243patchAssistant (( m ) => ({ ...m , streaming :false })); 2244} 2245} finally { 2246flushWaiting (); 2247// A cancelled or failed turn is still worth keeping. 2248flushSessions (); 2249clearStatus ( sessionId ); 2250markTurn ( sessionId , null ); 2251removeAgentAsk ( sessionId ); 2252const next = releasedMessages . get ( sessionId )?. shift (); 2253if ( next !== undefined ) { if ( ! releasedMessages . get ( sessionId )?. length ) releasedMessages . delete ( sessionId ); setTimeout (() => void sendMessage ( next ), 0 ); } 2254} 2255} 2256 2257/** Messages the host handed back when a goal ended with some still waiting; sent one after another. */ 2258const releasedMessages = new Map < string , string []>(); 2259 2260/* -------------------------------------------------------------- tool grants */ 2261 2262const noticed = new Set < string >(); 2263 2264/** 2265* Approve or deny a tool the agent asked about. The answer goes to the host, which hands it to the 2266* Harness approval for exactly this chat and call; the card then follows what the Harness reports 2267* (running, done, denied). The card shows the choice straight away and goes back if the host refuses. 2268*/ 2269function answerAgentTool ( sessionId :string , messageId :string , tool :ToolCall , approved :boolean ) { 2270const setState = ( state_ :ToolCall [ 'state' ], result ?:string ) => patchSession ( sessionId , s => ({ 2271 ...s , messages :s . messages . map ( m => m . id === messageId ?{ ...m , tools :( m . tools ?? []). map ( t => t . id === tool . id ?{ ...t , state :state_ , ...( result !== undefined ?{ result} :{}) } :t ) } :m ), 2272})); 2273setState ( approved ?'running' :'denied' ); 2274api . post ( '/api/chat/approval' , { sessionId, toolId :tool . id , decision :approved ?'approve' :'deny' }). catch ( error => { 2275setState ( 'proposed' ); 2276pushToast ( 'error' , 'That answer was not delivered' , error instanceof Error ?error . message :undefined ); 2277}); 2278} 2279 2280/** 2281* Approving a tool in the design build resolves locally: there is no tool 2282* runtime behind it yet, so the result is a labelled stand-in. The interaction — 2283* what is asked, what is shown, what needs a grant — is the real deliverable. 2284*/ 2285export function resolveTool ( messageId :string , toolId :string , approved :boolean ) { 2286const sessionId = state . activeSession ; 2287if ( ! sessionId ) return ; 2288const tool = state . sessions . find ( s => s . id === sessionId )?. messages . find ( m => m . id === messageId )?. tools ?. find ( t => t . id === toolId ); 2289if ( tool ?. live ) { answerAgentTool ( sessionId , messageId , tool , approved ); return ; } 2290 2291patchSession ( sessionId , ( s ) => ({ 2292 ...s , 2293messages :s . messages . map (( m ) => 2294m . id === messageId 2295 ?{ 2296 ...m , 2297tools :( m . tools ?? []). map (( t ) => 2298t . id === toolId 2299 ?{ 2300 ...t , 2301state :approved ?'done' :'denied' , 2302durationMs :undefined , 2303result :approved ?'Approval recorded. Nothing was executed.' :'Denied. Nothing ran.' , 2304} 2305 :t , 2306), 2307} 2308 :m , 2309), 2310})); 2311 2312} 2313 2314/* ------------------------------------------------------------------- routes */ 2315 2316export function go ( route :Route , param ?:string ) { 2317navigate ( route , param ); 2318// Focus mode is a reading mode for the conversation. Leaving it to work on 2319// something else leaves the mode, rather than stranding a bare shell. 2320if ( state . focus && route !== 'chat' && route !== 'settings' ) setFocus ( false ); 2321set ({ paletteOpen :false , navOpen :false }); 2322} 2323 2324/* ---------------------------------------------------------------- bootstrap */ 2325 2326export function bootOnce () { 2327if (( globalThis as { __strataBooted ?:boolean }). __strataBooted ) return ; 2328( globalThis as { __strataBooted ?:boolean }). __strataBooted = true ; 2329void bootstrap (); 2330} 2331 2332let sessionsResumed = false ; 2333/** 2334* Once, after the chats were first read from the host: what a chat can still have going on. Time-skip runs are followed again, a loop the last 2335* window left "running" has ended, a turn the host is still running is taken over (or one that ended while the page was away is shown whole), 2336* and tool cards the browser remembers as waiting for a turn that no longer exists are marked interrupted. 2337*/ 2338async function resumeSessions () { 2339if ( sessionsResumed ) return ; 2340sessionsResumed = true ; 2341for ( const session of state . sessions ) for ( const run of session . timeSkips ?? []) { scheduleTimeSkip ( session . id , run ); if ( run . job && ! run . completedAt ) { markTurn ( session . id , { abort :new AbortController (), agent :false }); void followTimeSkip ( session . id , run . id ); } } 2342// A loop lives in the window: one the last window left "running" has ended, and the board says so. 2343if ( state . sessions . some ( s => s . loop ?. state === 'running' )) { 2344const sessions = state . sessions . map ( s => s . loop ?. state === 'running' ?{ ...s , loop :{ ...s . loop , state :'ended' as const , endedWhy :'closed' as const , endedAt :Date . parse ( s . updatedAt ) || Date . now () } } :s ); 2345persistSessions ( sessions ); 2346set ({ sessions}); 2347} 2348await takeOverTurns (); 2349void reconcileAgentTools (); 2350} 2351 2352/** 2353* A reload does not stop an agent turn: the host keeps it going. The page asks which chats have a turn running and takes each one over again 2354* (the catch-up, then the rest as it is written, the Stop button and the approvals waiting). A chat whose last reply was cut off by the page 2355* going away is asked about too: if its turn ended meanwhile, the host still holds the end of it and shows it whole; if not, nothing changes. 2356*/ 2357async function takeOverTurns () { 2358let running :{ chatId :string }[] = []; 2359try { running = ( await api . get <{ turns :{ chatId :string }[] }>( '/api/chat/active' )). turns ; } catch { /* an older host, or none reachable: nothing to take over */ } 2360const live = new Set ( running . map ( t => t . chatId )); 2361for ( const id of live ) if ( state . sessions . some ( s => s . id === id ) && ! liveTurns . has ( id )) void sendMessage ( '' , { reattach :id }); 2362// Cut-off replies of chats with no turn running: the most recent few, asked once each. 2363const cut = state . sessions . filter ( s => ! live . has ( s . id ) && ! liveTurns . has ( s . id )). slice (). sort (( a , b ) => ( a . updatedAt < b . updatedAt ?1 :- 1 )). slice ( 0 , 12 ). flatMap ( s => { 2364const last = s . messages [ s . messages . length - 1 ]; 2365return last ?. role === 'assistant' && last . requestId && last . usageSource === undefined && ! last . local ?[{ id :s . id , requestId :last . requestId }] :[]; 2366}); 2367await Promise . allSettled ( cut . map ( c => sendMessage ( '' , { reattach :c . id , requestId :c . requestId }))); 2368} 2369 2370/** 2371* After a reload, a tool card the browser remembers as waiting or running may belong to a turn that no 2372* longer exists. Cards whose approval the host still holds stay answerable; the rest are marked as 2373* interrupted so nothing looks like it is still working. 2374*/ 2375async function reconcileAgentTools () { 2376const open = ( t :ToolCall ) => t . live && ( t . state === 'proposed' || t . state === 'running' ); 2377for ( const session of state . sessions ) { 2378if ( liveTurns . has ( session . id )) continue ; // a turn taken over again reports its own cards 2379if ( ! session . messages . some ( m => m . tools ?. some ( open ))) continue ; 2380let waiting = new Set < string >(); 2381try { 2382const r = await api . get <{ pending :{ callId :string }[] }>( `/api/agent/pending?chatId= ${ encodeURIComponent ( session . id )} ` ); 2383waiting = new Set ( r . pending . map ( p => p . callId )); 2384} catch { /* The host is unreachable; leave the cards for the next load. */ continue ; } 2385patchSession ( session . id , sess => ({ ...sess , messages :sess . messages . map ( m => m . tools ?. some ( open ) ?{ ...m , tools :m . tools . map ( t => open ( t ) && ! waiting . has ( t . id ) ?{ ...t , state :'error' as const , result :'The page closed before this finished. Check the workspace to see what it did.' } :t ) } :m ) })); 2386} 2387} 2388 2389 2390export function setContrast ( contrast :'standard' | 'increased' ) { set ({ contrast}); savePrefs (); } 2391matchMedia ( '(prefers-color-scheme: dark)' ). addEventListener ( 'change' , () => { if ( state . theme === 'system' ) applyPrefs (); }); 2392 2393export async function loadRuntimeModel ( body :unknown ){ 2394const result = await api . post <{ state :RuntimeModels ; instance :{ id :string }}>( '/api/runtime/load' , body ); 2395set ({ runtime :result . state }); return result . instance . id ; 2396} 2397export async function runtimeModelAction ( id :string , action :'unload' | 'default' ){ 2398set ({ runtime :await api . post < RuntimeModels >( `/api/runtime/ ${ id } / ${ action } ` )}); 2399} 2400 2401export async function changeModelDirectory ( directory :string , unload :boolean ) { 2402set ( s => ({ busy :{ ...s . busy , modelDirectory :true } })); 2403try { 2404const result = await api . post <{ library :ModelLibrary ; imageModels :ImageModelLibrary ; runtime :RuntimeModels ; hardware :Hardware ; setup :SetupState }>( '/api/storage/models-directory' , { directory, unload}); 2405set ( result ); 2406return result ; 2407} finally { 2408set ( s => ({ busy :{ ...s . busy , modelDirectory :false } })); 2409} 2410} 2411 2412export async function addLocalModel ( path :string , name ?:string ) { 2413const result = await api . post <{ library :ModelLibrary ; variantId :string }>( '/api/local-models' , { path, name}); 2414set ({ library :result . library }); 2415return result . variantId ; 2416}