okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
7c11eb58b
main
1import { localeTag } from '../lib/i18n' ; 2import { tr } from '../lib/i18n' ; 3import { UsageDashboard } from '../components/UsageDashboard' ; 4import { FloatingMenu } from '../components/FloatingMenu' ; 5import { lazyScreen } from '../lib/lazy-screen' ; 6import { measureFrame } from '../lib/overlay-place' ; 7import { timeSkipPrompt , timeSkipTabId , type TimeSkipRun } from '../lib/time-skip' ; 8import { ChatToolbar } from '../components/ChatToolbar' ; 9import { ChatTelemetry } from '../components/TelemetryPopover' ; 10import { ArtifactCard } from '../components/ArtifactCard' ; 11import { ChatMedia } from '../components/ChatMedia' ; 12import { closePreviewTab } from '../lib/preview-tabs' ; 13import { endPreviewDeferral , previewsDeferred } from '../lib/recovery' ; 14import { messageArtifacts , openItem , syncArtifacts } from '../lib/preview-merge' ; 15import { createImeGuard } from '../lib/ime-enter' ; 16import { mainCodePreview , setSelectedPreviewId } from '../lib/code-preview' ; 17import { ArtifactPanel } from '../components/ArtifactPanel' ; 18import { PreviewResizeHandle } from '../components/PreviewResizeHandle' ; 19import { DEFAULT_PREVIEW_FRACTION , PREVIEW_SPLIT_KEY , previewWidth } from '../lib/preview-layout' ; 20import { ComposerControls } from '../components/ComposerControls' ; 21import { ChatPhotos } from '../components/ChatPhotos' ; 22import { useChatPhotos , removeChatPhoto } from '../lib/chat-photos' ; 23import { useNative } from '../lib/native' ; 24import { COMPACT_FILES_FROM , mainResult , previewOf } from '../lib/deliverables' ; 25import { noModelNotice } from '../lib/no-model' ; 26import { ReasoningBlock } from '../components/ReasoningBlock' ; 27import { StatusLine } from '../components/StatusLine' ; 28import { GoalBar } from '../components/GoalBar' ; 29import { PlanCard , PlanPanel , QueuedMessages } from '../components/PlanCard' ; 30import { FolderChip } from '../components/FolderChip' ; 31import { DropZone , DROP_EVENT , pastedFiles } from '../components/DropZone' ; 32import { ActivityLine , DraftLines , EditedFiles , FileCard , FilesSummary , SkillsUsed } from '../components/Deliverables' ; 33import { queueMessage , usePlan , usePlanQuiet } from '../lib/plan' ; 34import { plainFailureText } from '../lib/plain-errors' ; 35import { contextRecovery } from '../lib/context-recovery' ; 36import { useLiveStatus } from '../lib/live-status' ; 37import { ApprovalDock , SCOPE } from '../components/ApprovalCard' ; 38import { artifactFromUrl , type PreviewArtifact } from '../lib/artifacts' ; 39import { openExternal } from '../lib/open-external' ; 40import { busyPlan , parkedReady } from '../lib/while-busy' ; 41import { composeQuoted , parseQuoted , type Quote } from '../lib/quotes' ; 42/** Chat — talk to the one loaded model. */ 43import { memo , Suspense , useCallback , useEffect , useMemo , useRef , useState } from 'react' ; 44import { Markdown } from '../components/Markdown' ; 45import { Btn , Icon , IconBtn , ErrorNotice , type IconName } from '../components/ui' ; 46import { composerCap , scrollBehavior } from '../lib/responsive' ; 47import { relTime , cx , duration , tokens , tps } from '../lib/format' ; 48import { addQuote , clearQuotes , removeQuote , createSubagentExample , parkMessage , takeParked , pushToast , setPreviewTabClosed , branchFrom , continueLast , markRead , retryLast , selectSession , rewindTo , sendMessage , stopStreaming , useStore , } from '../lib/store' ; 49import { CopyBtn , CopyMenuItem , MenuCloseContext } from '../components/CopyBtn' ; 50import { KEYS_UP , PILL_DISTANCE , distanceFromBottom , followAfterScroll , wheelLeavesBottom } from '../lib/follow-scroll' ; 51import { getSlashCommands } from '../lib/commands' ; 52import { useLocation } from '../lib/router' ; 53import { composerSends } from '../lib/shortcut-bindings' ; 54import type { ChatMessage , Session , ToolCall } from '../lib/types' ; 55// The Time-skip panel and its progress card are only drawn in a chat that has a Time-skip run: their code loads then (and a few seconds after start, see main.tsx). 56const TimeSkipPanel = lazyScreen (() => import ( '../components/TimeSkipPanel' ), ( m ) => m . TimeSkipPanel ); 57const TimeSkipWorking = lazyScreen (() => import ( '../components/TimeSkipWorking' ), ( m ) => m . TimeSkipWorking ); 58export function ChatScreen () { 59const location = useLocation (); 60const sessions = useStore (( s ) => s . sessions ); 61const activeId = useStore (( s ) => s . activeSession ); 62const library = useStore (( s ) => s . library ); 63const streaming = useStore (( s ) => s . streaming ); 64const whileBusy = useStore ( s => s . whileBusy ); 65const setup = useStore ( s => s . setup ); 66const setupFlag = useStore ( s => s . setupOpen ); 67const setupVisible = location . route === 'setup' || setupFlag || !! setup && ! setup . complete && ! setup . dismissed ; 68const session :Session | null = useMemo (() => { 69const wanted = location . param ?? activeId ; 70return sessions . find (( s ) => s . id === wanted ) ?? sessions [ 0 ] ?? null ; 71}, [ sessions , activeId , location . param ]); 72/* A conversation you are watching is read by definition — including while a 73reply streams into it. Without this, switching away from a session that 74answered you would mark it unread. */ 75const messageCount = session ?. messages . length ?? 0 ; 76useEffect (() => { 77if ( session && session . id === activeId && ! streaming ) 78markRead ( session . id ); 79// eslint-disable-next-line react-hooks/exhaustive-deps 80}, [ session ?. id , messageCount , streaming ]); 81const parked = useStore ( s => ( session ?s . parked [ session . id ] :undefined )); 82const quotes = useStore ( s => ( session ?s . quotes [ session . id ] :undefined )) ?? NO_QUOTES ; 83// Selecting words in a message offers to quote just them (#4785). 84const [ selection , setSelection ] = useState <{ text :string ; messageId :string ; role :'user' | 'assistant' ; x :number ; y :number } | null >( null ); 85useEffect (() => { 86const read = () => { 87const sel = window . getSelection (); 88const el = scroller . current ; 89if ( ! sel || sel . isCollapsed || ! sel . rangeCount || ! el ) { setSelection ( null ); return ; } 90const range = sel . getRangeAt ( 0 ); 91const node = range . commonAncestorContainer ; 92const host = ( node instanceof Element ?node :node . parentElement )?. closest ( '.st-msg' ); 93const text = sel . toString (). trim (); 94if ( ! host || ! el . contains ( host ) || text . length < 2 ) { setSelection ( null ); return ; } 95const rect = range . getBoundingClientRect (); 96// screen units of this engine, written back in the page's own pixels (lib/overlay-place.ts: Interface size zooms the page) 97const { scale, viewport} = measureFrame (); 98setSelection ({ text, messageId :host . getAttribute ( 'data-message-id' ) ?? '' , role :host . classList . contains ( 'st-msg--user' ) ?'user' :'assistant' , x :Math . min ( viewport . width - 96 * scale , Math . max ( 8 , rect . left )) / scale , y :Math . max ( 8 , rect . top - 40 * scale ) / scale }); 99}; 100document . addEventListener ( 'selectionchange' , read ); 101return () => document . removeEventListener ( 'selectionchange' , read ); 102}, [ session ?. id ]); 103// Messages parked while an answer was written (Send after, Interrupt) go one by one, each when the chat is quiet again, 104// and only from the chat that is also the active one: sendMessage sends to that one (#5806, parkedReady). 105useEffect (() => { 106if ( ! session || ! parkedReady ( session . id , activeId , streaming , parked ?. length ?? 0 )) 107return ; 108const next = takeParked ( session . id ); 109if ( next !== undefined ) 110void sendMessage ( next ); 111}, [ streaming , parked ?. length , session ?. id , activeId ]); 112const [ draft , setDraft ] = useState ( '' ); 113const draftKey = `strata.chat-draft. ${ session ?. id ?? 'new' } ` ; 114useEffect (() => { 115setDraft ( sessionStorage . getItem ( draftKey ) ?? '' ); 116if ( session && session . id !== activeId ) 117selectSession ( session . id ); 118}, [ draftKey ]); 119const updateDraft = ( value :string ) => { setDraft ( value ); sessionStorage . setItem ( draftKey , value ); }; 120const splitRef = useRef < HTMLDivElement >( null ); 121const [ splitWidth , setSplitWidth ] = useState ( 0 ); 122const [ previewFraction , setPreviewFraction ] = useState (() => { 123try { 124const saved = localStorage . getItem ( PREVIEW_SPLIT_KEY ); 125return saved && Number . isFinite ( Number ( saved )) ?Number ( saved ) :DEFAULT_PREVIEW_FRACTION ; 126} 127catch { 128return DEFAULT_PREVIEW_FRACTION ; 129} 130}); 131useEffect (() => { 132const timer = setTimeout (() => { 133try { 134localStorage . setItem ( PREVIEW_SPLIT_KEY , String ( previewFraction )); 135} 136catch { } 137}, 180 ); 138return () => clearTimeout ( timer ); 139}, [ previewFraction ]); 140useEffect (() => { 141if ( ! splitRef . current ) 142return ; 143const ro = new ResizeObserver ( entries => setSplitWidth ( entries [ 0 ]. contentRect . width )); 144ro . observe ( splitRef . current ); 145return () => ro . disconnect (); 146}, [ session ?. id ]); 147const [ expanded , setExpanded ] = useState ( false ); 148useEffect (() => { setExpanded ( false ); }, [ session ?. id ]); 149useEffect (() => { 150if ( ! expanded ) 151return ; 152const exit = ( e :KeyboardEvent ) => { 153if ( e . key === 'Escape' ) 154setExpanded ( false ); 155}; 156document . addEventListener ( 'keydown' , exit ); 157return () => document . removeEventListener ( 'keydown' , exit ); 158}, [ expanded ]); 159const [ previews , setPreviews ] = useState < PreviewArtifact []>([]); 160const [ selectedPreview , setSelectedPreview ] = useState < string | null >( null ); 161const timeSkipRuns = ( session ?. timeSkips ?? []). filter ( run => session ?. messages . some ( m => m . timeSkipId === run . id && m . role === 'assistant' ) && ( ! run . job || ( run . job . files ?. length ?? 0 ) > 0 )); 162const runTabs = timeSkipRuns . map (( run , i ) => ({ id :timeSkipTabId ( run . id ), title :timeSkipRuns . length > 1 ?`Time-skip ${ i + 1 } ` :'Time-skip' , icon :'branch' as const , controls :'time-skip-content' })). filter ( tab => ! session ?. closedPreviews ?. includes ( tab . id )); 163const plan = usePlan ( session ?. id ); 164const planTabId = session ?`plan: ${ session . id } ` :'' ; 165const planTab = plan && plan . state !== 'rejected' && ! session ?. closedPreviews ?. includes ( planTabId ) ?[{ id :planTabId , title :'Plan' , icon :'check' as const , controls :'plan-content' }] :[]; 166const planShown = planTab . length > 0 && selectedPreview === planTabId ; 167const planRunId = plan ?. state === 'running' ?plan . id :'' ; 168useEffect (() => { if ( planRunId && planTabId && ! session ?. closedPreviews ?. includes ( planTabId )) setSelectedPreview ( planTabId ); }, [ planRunId ]); 169// The chat shows every run of this chat (a running one has no files yet, so no tab); the sidebar tabs only those with something to compare. 170const allTimeSkipRuns = session ?. timeSkips ?? []; 171const extraTabs = [ ...runTabs , ...planTab ]; 172const selectedRun = timeSkipRuns . find ( run => timeSkipTabId ( run . id ) === selectedPreview ); 173const inlinePreview = splitWidth >= ( selectedRun || planShown ?760 :1120 ); 174const paneWidth = previewWidth ( splitWidth , previewFraction ); 175const splitStyle = inlinePreview && selectedPreview && ! expanded ?{ gridTemplateColumns :`minmax(0,1fr) ${ paneWidth } px` } :undefined ; 176const resizeHandle = ! setupVisible && inlinePreview && selectedPreview && ! expanded ?< PreviewResizeHandle container = { splitRef } total = { splitWidth } fraction = { previewFraction } onChange = { setPreviewFraction } controls = { selectedRun ?'time-skip-content' :planShown ?'plan-content' :'artifact-content' }/> :null ; 177const runCount = timeSkipRuns . length ; 178const previewCount = session ?. messages . reduce (( n , m ) => n + ( m . artifacts ?. length ?? 0 ), 0 ) ?? 0 ; 179useEffect (() => { const items = [ ...new Map (( session ?. messages . flatMap ( m => m . artifacts ?? []) ?? []). map ( a => [ a . id , a ])). values ()]; setPreviews ( items . filter ( a => ! session ?. closedPreviews ?. includes ( a . id ))); setSelectedPreview ( session && previewsDeferred ( session . id ) || session ?. closedPreviews ?. includes ( session . previewOpen ?? '' ) ?null :session ?. previewOpen ?. startsWith ( 'time-skip:' ) && ! timeSkipRuns . some ( r => timeSkipTabId ( r . id ) === session . previewOpen ) ?null :session ?. previewOpen ?? null ); }, [ session ?. id ]); 180useEffect (() => { 181// A message's copy of a file never replaces one that was read later (lib/preview-merge.ts); nothing changed = the same array = no update. 182const items = messageArtifacts ( session ?. messages ); 183if ( items . length ) 184setPreviews ( old => syncArtifacts ( old , items , session ?. closedPreviews )); 185}, [ previewCount ]); 186const localUrls = useRef < string []>([]); 187useEffect (() => { 188const id = session ?. previewOpen ; 189if ( id ?. startsWith ( 'time-skip:' ) && timeSkipRuns . some ( r => timeSkipTabId ( r . id ) === id ) && ! session ?. closedPreviews ?. includes ( id ) && ! ( session && previewsDeferred ( session . id ))) 190setSelectedPreview ( id ); 191}, [ session ?. id , runCount ]); 192useEffect (() => () => localUrls . current . forEach ( url => URL . revokeObjectURL ( url )), []); 193function openPreview ( item :PreviewArtifact ) { 194endPreviewDeferral (); 195if ( item . url ?. startsWith ( 'blob:' )) 196localUrls . current . push ( item . url ); 197setPreviewTabClosed ( session ?. id , item . id , false , item . id ); 198// The file was read just now: it replaces the tab of the same id when its content differs (it used to be dropped, keeping the first copy). 199setPreviews ( old => openItem ( old , item )); 200setSelectedPreview ( item . id ); 201} 202/* A run that finishes with a file the sidebar can show opens its main result there by itself (one file, never several). Only a run seen 203finishing here does it: opening an old chat shows nothing new. A file that cannot be read just stays a card with Open. */ 204const replyWasStreaming = useRef < Map < string , boolean >>( new Map ()); 205const lastReply = [ ...( session ?. messages ?? [])]. reverse (). find ( m => m . role === 'assistant' ); 206useEffect (() => { 207if ( ! session || ! lastReply ) return ; 208const before = replyWasStreaming . current . get ( lastReply . id ); 209replyWasStreaming . current . set ( lastReply . id , !! lastReply . streaming ); 210if ( before !== true || lastReply . streaming || lastReply . error ) return ; 211const main = mainResult ( lastReply . deliverables , lastReply . content ); 212// No file to open: one whole HTML page in the answer goes to the sidebar too (a snippet keeps its preview button). 213if ( ! main ) { const page = lastReply . blocks ?. some ( b => b . kind === 'group' ) ?null :mainCodePreview ( lastReply . id , lastReply . content ); if ( page ) openPreview ( page ); return ; } 214const sessionId = session . id ; 215void previewOf ( sessionId , main ). then ( item => { if ( session . id === sessionId ) openPreview ( item ); }, () => { }); 216}, [ lastReply ?. id , lastReply ?. streaming ]); 217useEffect (() => { setSelectedPreviewId ( setupVisible ?null :selectedPreview ); return () => setSelectedPreviewId ( null ); }, [ selectedPreview , setupVisible ]); 218function closeTab ( id :string ) { 219const next = closePreviewTab ([ ...previews . map ( p => ({ id :p . id })), ...extraTabs ], selectedPreview , id ); 220setPreviews ( previews . filter ( p => p . id !== id )); 221setSelectedPreview ( next . selected ); 222setPreviewTabClosed ( session ?. id , id , true , next . selected ); 223if ( ! next . items . length ) { 224setExpanded ( false ); 225requestAnimationFrame (() => textarea . current ?. focus ()); 226} 227} 228function selectPreview ( id :string ) { 229endPreviewDeferral (); 230setSelectedPreview ( id ); 231setPreviewTabClosed ( session ?. id , id , false , id ); 232} 233function openTimeSkip ( id :string ) { selectPreview ( timeSkipTabId ( id )); } 234function openLink ( url :string ) { 235const item = artifactFromUrl ( url ); 236if ( ! item ) 237return ; 238// A web address opens in the person's own browser; only a file (a PDF, picture, table, code or Markdown) is shown in the side panel (#4721). 239if ( item . kind === 'website' ) { 240void openExternal ( url ); 241return ; 242} 243openPreview ( item ); 244} 245/* The message list is memoised (#4640 family: Out of Memory in a long chat): a streamed token changes one message, so the others must not 246re-render. These handlers keep one identity for the life of the screen and always call the newest functions above. */ 247const latestHandlers = useRef ({ editPrompt, openPreview, closeTab, openTimeSkip, openLink}); 248latestHandlers . current = { editPrompt, openPreview, closeTab, openTimeSkip, openLink}; 249const messageHandlers = useMemo (() => ({ 250onEditPrompt :( text :string ) => latestHandlers . current . editPrompt ( text ), 251onPreview :( a :PreviewArtifact ) => latestHandlers . current . openPreview ( a ), 252onClosePreview :( id :string ) => latestHandlers . current . closeTab ( id ), 253onOpenTimeSkip :( id :string ) => latestHandlers . current . openTimeSkip ( id ), 254onOpenLink :( url :string ) => latestHandlers . current . openLink ( url ), 255}), []); 256const scroller = useRef < HTMLDivElement >( null ); 257const focusMode = useStore (( s ) => s . focus ); 258/** Per-conversation scroll offsets, so returning to one restores the view. */ 259const scrollPositions = useRef < Map < string , number >>( new Map ()); 260/* Scrolling back to reread something is normal; being stranded there while a 261reply arrives is not. The pill only appears once you are far enough up that 262the newest message is genuinely off screen. */ 263const [ awayFromBottom , setAwayFromBottom ] = useState ( false ); 264/* A reply that finishes while you are reading further up has no way to say so 265— the text simply stops arriving off screen. The pill pulses once, on 266opacity alone, so the cue is noticed without anything moving. */ 267const [ justFinished , setJustFinished ] = useState ( false ); 268const wasStreaming = useRef ( false ); 269useEffect (() => { 270if ( wasStreaming . current && ! streaming ) { 271setJustFinished ( true ); 272const t = setTimeout (() => setJustFinished ( false ), 700 ); 273wasStreaming . current = streaming ; 274return () => clearTimeout ( t ); 275} 276wasStreaming . current = streaming ; 277return undefined ; 278}, [ streaming ]); 279/** Whether the reader is following the newest message rather than reading back. */ 280const pinned = useRef ( true ); 281/** When the reader last used the wheel, a finger, a key or the scrollbar on the transcript. */ 282const readerInput = useRef ( 0 ); 283const seenMessages = useRef ( 0 ); 284/** 285* Scrolls to the newest message and stays there. 286* 287* `content-visibility: auto` means the transcript's height is an estimate 288* until each turn renders, so a single `scrollTo(scrollHeight)` lands short 289* and the reader ends up above the reply they asked to see. Re-aiming until 290* the height stops growing settles it; the loop is bounded because a 291* transcript that never settles must not spin. 292*/ 293const scrollToLatest = useCallback (( smooth = true ) => { 294const el = scroller . current ; 295if ( ! el ) 296return ; 297pinned . current = true ; 298el . scrollTo ({ top :el . scrollHeight , behavior :smooth ?scrollBehavior () :'auto' }); 299setAwayFromBottom ( false ); 300}, []); 301/** 302* Keeps a pinned transcript pinned. 303* 304* With `content-visibility: auto`, an off-screen turn has an *estimated* 305* height until it renders, so the scroll height grows as you approach the 306* bottom and any single scroll lands short. Watching the content box and 307* re-aiming while the reader is pinned is what makes the two compatible — 308* and it fixes the same drift while a long reply streams in. 309*/ 310useEffect (() => { 311const el = scroller . current ; 312// The content, not the scroller's first child — which is the reading 313// progress hairline, and never changes size. 314const inner = el ?. querySelector ( '.chat__inner' ); 315if ( ! el || ! inner ) 316return undefined ; 317const ro = new ResizeObserver (() => { 318if ( pinned . current && readerHasSelection ( el )) { 319// Words are selected: the view stays where they are (#3818); the way back to the newest message is offered. 320pinned . current = false ; 321setAwayFromBottom ( distanceFromBottom ( el ) > PILL_DISTANCE ); 322} 323if ( pinned . current ) 324el . scrollTop = el . scrollHeight ; 325}); 326ro . observe ( inner ); 327// The scroller itself shrinks when a question appears above the message box (the approval dock): keep the end in view then too. 328ro . observe ( el ); 329return () => ro . disconnect (); 330}, [ session ?. id , session ?. messages . length === 0 ]); 331const textarea = useRef < HTMLTextAreaElement >( null ); 332const remote = useStore ( s => s . remoteModel ), providers = useStore ( s => s . providers ); 333const apiModel = providers ?. connections . find ( c => c . id === remote ?. connectionId )?. models . find ( m => m . id === remote ?. modelId ); 334const loaded = apiModel ?? library ?. variants . find (( v ) => v . id === library . loaded ) ?? null ; 335/** 336* Follow the stream only when the reader is already at the bottom. Scrolling 337* back through a long conversation should not be yanked forward by the next 338* token — which is the single most irritating thing a chat UI can do over a 339* long session. 340*/ 341useEffect (() => { 342const el = scroller . current ; 343if ( ! el || ( session ?. showcase && ! streaming )) 344return ; 345// The reader's own scrolling decides (#4014): a wheel notch is about 100 px and used to land inside a 120 px band that pulled 346// the view back on every token. `pinned` is set by the scroller's wheel, touch, key and scroll handlers below. 347const count = session ?. messages . length ?? 0 ; 348const sent = count > seenMessages . current && session ?. messages . at ( - 1 )?. role === 'user' ; 349seenMessages . current = count ; 350// Sending a message always brings the reader to it, as it did before; only the answer's growth waits for the reader. 351if ( pinned . current && ! sent && readerHasSelection ( el )) { 352pinned . current = false ; 353setAwayFromBottom ( distanceFromBottom ( el ) > PILL_DISTANCE ); 354} 355if ( pinned . current || sent ) 356scrollToLatest (); 357}, [ session ?. messages . length , session ?. messages . at ( - 1 )?. content , scrollToLatest ]); 358// Scroll position is remembered per conversation, so returning to one puts you 359// back where you were reading rather than at the top or the bottom. 360useEffect (() => { 361const el = scroller . current ; 362if ( ! el || ! session ) 363return ; 364const saved = scrollPositions . current . get ( session . id ); 365el . scrollTop = saved ?? ( session . showcase ?0 :el . scrollHeight ); 366pinned . current = ! session . showcase || saved !== undefined ; 367// Deliberately keyed on the conversation only: re-running on every message 368// would fight the follow-the-stream effect above. 369// eslint-disable-next-line react-hooks/exhaustive-deps 370}, [ session ?. id ]); 371// The box grows with the draft but never past 30% of the window, and scrolls inside after that, so Send and the toolbar stay on screen (QA F08). 372useEffect (() => { 373const fit = () => { 374const el = textarea . current ; 375if ( ! el ) 376return ; 377el . style . height = 'auto' ; 378el . style . height = ` ${ Math . min ( composerCap ( window . innerHeight ), el . scrollHeight )} px` ; 379}; 380fit (); 381window . addEventListener ( 'resize' , fit ); 382return () => window . removeEventListener ( 'resize' , fit ); 383}, [ draft ]); 384/** Hands a rewound prompt back to the composer so it can be changed. */ 385function editPrompt ( text :string ) { 386setDraft ( text ); 387requestAnimationFrame (() => textarea . current ?. focus ()); 388} 389/** 390* Turn navigation, for reading rather than writing. 391* 392* Focus mode is for reading a long conversation, and reading needs a next. 393* `Alt+↑`/`Alt+↓` step between your own turns — the boundaries a reader 394* actually navigates by, rather than by message — and `Cmd+↓` returns to the 395* latest. Only bound while focus mode is on, so the keys stay free elsewhere. 396*/ 397useEffect (() => { 398if ( ! focusMode ) 399return undefined ; 400const onKey = ( e :KeyboardEvent ) => { 401const el = scroller . current ; 402if ( ! el ) 403return ; 404const atLatest = () => { 405pinned . current = true ; 406el . scrollTo ({ top :el . scrollHeight , behavior :scrollBehavior () }); 407}; 408if (( e . metaKey || e . ctrlKey ) && e . key === 'ArrowDown' ) { 409e . preventDefault (); 410atLatest (); 411return ; 412} 413if ( ! e . altKey || ( e . key !== 'ArrowUp' && e . key !== 'ArrowDown' )) 414return ; 415e . preventDefault (); 416const turns = [ ...el . querySelectorAll < HTMLElement >( '.st-msg--user' )]; 417if ( ! turns . length ) 418return ; 419const top = el . scrollTop ; 420/* The tolerance has to exceed TURN_OFFSET, or the key sticks on the turn 421it just moved to: positioning a turn at `scrollTop + 16` leaves it 422satisfying `offsetTop > scrollTop + 8` on the next press. */ 423const TURN_OFFSET = 16 ; 424const seen = TURN_OFFSET + 24 ; 425const next = e . key === 'ArrowDown' 426 ?turns . find (( t ) => t . offsetTop > top + seen ) 427 :[ ...turns ]. reverse (). find (( t ) => t . offsetTop < top - seen ); 428if ( next ) { 429pinned . current = false ; 430el . scrollTo ({ top :Math . max ( 0 , next . offsetTop - TURN_OFFSET ), behavior :scrollBehavior () }); 431setAwayFromBottom ( true ); 432} 433else if ( e . key === 'ArrowDown' ) { 434atLatest (); 435} 436}; 437window . addEventListener ( 'keydown' , onKey ); 438return () => window . removeEventListener ( 'keydown' , onKey ); 439}, [ focusMode ]); 440const chatNative = useNative (), queuedPhotos = useChatPhotos ( session ?. id ); 441const readyForChat = !! loaded || !! chatNative ?. instances . some ( i => i . status === 'ready' ); 442useEffect (() => { 443if ( setupVisible || ! readyForChat || messageCount ) 444return ; 445if ( scroller . current ?. querySelector ( '.first-chat-start' )) 446textarea . current ?. focus ({ preventScroll :true }); 447}, [ setupVisible , readyForChat , session ?. id , messageCount ]); 448function submit () { 449const text = draft . trim (); 450if ( ! text && ! queuedPhotos . length ) 451return ; 452if ( streaming ) { 453// Typed while a goal runs: it waits in the queue, shown under the conversation. With no goal running there is nothing to queue behind. 454if ( ! text || ! session ) 455return ; 456const plan = busyPlan ( whileBusy ); 457const out = quotedMessage ( quotes , text ); 458// Interrupt: the answer stops where it is (what is written stays) and the message goes as soon as it has stopped (the effect below sends it). 459if ( plan === 'interrupt' ) { 460updateDraft ( '' ); 461clearQuotes ( session . id ); 462parkMessage ( session . id , out ); 463stopStreaming (); 464return ; 465} 466updateDraft ( '' ); 467void queueMessage ( session . id , out ). then ( ok => { if ( ok ) { clearQuotes ( session . id ); return ; } if ( ! ok ) { if ( plan === 'goal' ) { clearQuotes ( session . id ); parkMessage ( session . id , out ); return ; } updateDraft ( text ); pushToast ( 'info' , tr ( 'The assistant is still answering' ), tr ( 'Send your message when it has finished.' )); } }, e => { updateDraft ( text ); pushToast ( 'error' , tr ( 'The message was not queued' ), plainFailureText ( e instanceof Error ?e . message :String ( e )). message ); }); 468return ; 469} 470const timeSkip = timeSkipPrompt ( text ); 471if ( timeSkip === '' ) { 472pushToast ( 'info' , 'Add a prompt after /time-skip' ); 473return ; 474} 475if ( timeSkip === null ) { 476// No model to answer: say so plainly (or show the download), and do not start a run. 477const why = noModelNotice ( chatNative ?? null , { libraryLoaded :!! loaded }); 478if ( why ) { pushToast ( 'info' , tr ( why . title ), tr ( why . message )); return ; } 479} 480updateDraft ( '' ); 481if ( session ) clearQuotes ( session . id ); 482void sendMessage ( session ?quotedMessage ( quotes , text ) :text ); 483} 484function onComposerKey ( _e :React . KeyboardEvent ) { } 485if ( ! session ) { 486return (<> 487< ChatToolbar previewWidth = { paneWidth } extraTabs = { extraTabs } session = { session } items = { previews } onCloseTab = { closeTab } selected = { setupVisible ?null :selectedPreview } onSelect = { selectPreview } onClose = {() => { setSelectedPreview ( null ); setExpanded ( false ); }} inline = { inlinePreview } expanded = { expanded } onExpand = {() => setExpanded ( v => ! v )}/> 488< div className = "chatsplit" style = { splitStyle } data-timeskip = { !! selectedRun || undefined } ref = { splitRef } data-preview = { !! selectedPreview && inlinePreview || undefined } data-expanded = { expanded && !! selectedPreview && inlinePreview || undefined }> 489< DropZone className = "chatcol" > 490< div className = "main__body chat" ref = { scroller }> 491{ tr ( awayFromBottom ?(< button type = "button" className = "jumplatest" data-finished = { justFinished || undefined } aria-label = { tr ( "Scroll to the latest message" )} title = { tr ( "Scroll to the latest message" )} onClick = {() => scrollToLatest ()}> 492< Icon name = "chevron" size = { 18 }/></ button >) :null )} 493< div className = "chat__inner" > 494< UsageDashboard loaded = { !! loaded }/> 495</ div > 496</ div > 497< Composer draft = { draft } setDraft = { updateDraft } loaded = { !! loaded } streaming = { streaming } onSubmit = { submit } onKey = { onComposerKey } session = { session } onPreview = { openPreview } textareaRef = { textarea }/> 498</ DropZone > 499< ArtifactPanel items = { previews } onCloseTab = { closeTab } selected = { setupVisible ?null :selectedPreview } onSelect = { selectPreview } onClose = {() => setSelectedPreview ( null )} inline = { inlinePreview }/> 500{ tr ( resizeHandle )} 501</ div > 502</>); 503} 504return (<> 505{ tr ( selection && session ?< button type = "button" className = "quote-selection" style = {{ left :selection . x , top :selection . y }} onMouseDown = { e => e . preventDefault ()} onClick = {() => { addQuote ( session . id , selection . text , selection . messageId , selection . role ); window . getSelection ()?. removeAllRanges (); setSelection ( null ); }}>{ tr ( "Quote" )}</ button > :null )} 506< ChatToolbar previewWidth = { paneWidth } extraTabs = { extraTabs } session = { session } items = { previews } onCloseTab = { closeTab } selected = { setupVisible ?null :selectedPreview } onSelect = { selectPreview } onClose = {() => { setSelectedPreview ( null ); setExpanded ( false ); }} inline = { inlinePreview } expanded = { expanded } onExpand = {() => setExpanded ( v => ! v )}/> 507 508{ /* The composer belongs to the conversation column, not the window: with 509the context panel open, a full-width composer sat underneath the panel 510and drifted out of alignment with the transcript it belongs to. */ } 511< div className = "chatsplit" style = { splitStyle } data-timeskip = { !! selectedRun || undefined } ref = { splitRef } data-preview = { !! selectedPreview && inlinePreview || undefined } data-expanded = { expanded && !! selectedPreview && inlinePreview || undefined }> 512< DropZone className = "chatcol" > 513< div className = "main__body chat" ref = { scroller } onScroll = {( e ) => { 514const el = e . currentTarget ; 515if ( session ) 516scrollPositions . current . set ( session . id , el . scrollTop ); 517// How far you are from the newest message, which decides whether 518// the way back is worth offering. 519// The threshold has to tolerate the height estimate moving under 520// us, or the pill flickers as turns render during a scroll. 521const distance = distanceFromBottom ( el ); 522pinned . current = followAfterScroll ( distance , pinned . current , Date . now () - readerInput . current ); 523setAwayFromBottom ( distance > PILL_DISTANCE ); 524}} onWheel = {( e ) => { 525readerInput . current = Date . now (); 526if ( wheelLeavesBottom ( e . deltaY ) && e . currentTarget . scrollTop > 0 ) 527pinned . current = false ; 528}} onTouchMove = {() => { readerInput . current = Date . now (); }} onPointerDown = {() => { readerInput . current = Date . now (); }} onKeyDown = {( e ) => { 529readerInput . current = Date . now (); 530if ( KEYS_UP . has ( e . key ) && e . target === e . currentTarget && e . currentTarget . scrollTop > 0 ) 531pinned . current = false ; 532}}> 533 534< div className = "chat__inner" > 535{ tr ( session . messages . length === 0 ?( session . statsAvailable === false ?< p className = "small muted" >{ tr ( "Editing from an earlier message. Update the prompt below." )}</ p > : 536< UsageDashboard loaded = { !! loaded }/>) :( session . messages . map (( m , i ) => (< Message key = { m . id } message = { m } isLast = { i === session . messages . length - 1 } onEditPrompt = { messageHandlers . onEditPrompt } onPreview = { messageHandlers . onPreview } onClosePreview = { messageHandlers . onClosePreview } onOpenTimeSkip = { messageHandlers . onOpenTimeSkip } timeSkipDone = { !! allTimeSkipRuns . find ( r => r . id === m . timeSkipId )?. completedAt } timeSkipReal = { !! allTimeSkipRuns . find ( r => r . id === m . timeSkipId )?. job } timeSkipRun = { allTimeSkipRuns . find ( r => r . id === m . timeSkipId )} onOpenLink = { messageHandlers . onOpenLink }/>))))} 537< QueuedMessages chatId = { session . id }/> 538</ div > 539</ div > 540< div className = "jumplatest-row" >{ tr ( awayFromBottom ?(< button type = "button" className = "jumplatest" data-finished = { justFinished || undefined } aria-label = { tr ( "Scroll to the latest message" )} title = { tr ( "Scroll to the latest message" )} onClick = {() => scrollToLatest ()}> 541< Icon name = "chevron" size = { 18 }/></ button >) :null )}</ div > 542< Composer draft = { draft } setDraft = { updateDraft } loaded = { !! loaded } streaming = { streaming } onSubmit = { submit } onKey = { onComposerKey } session = { session } onPreview = { openPreview } textareaRef = { textarea }/> 543</ DropZone > 544{ tr ( ! setupVisible && selectedRun && session ?< Suspense fallback = { null }>< TimeSkipPanel key = { selectedRun . id } run = { selectedRun } sessionId = { session . id } inline = { inlinePreview } expanded = { expanded } onCompare = { setExpanded } onPreview = { openPreview } onClose = {() => { setSelectedPreview ( null ); setExpanded ( false ); }}/></ Suspense > :null )} 545{ tr ( ! setupVisible && planShown ?< PlanPanel chatId = { session ?. id }/> :null )} 546< ArtifactPanel items = { previews } onCloseTab = { closeTab } selected = { setupVisible || planShown ?null :selectedPreview } onSelect = { selectPreview } onClose = {() => setSelectedPreview ( null )} inline = { inlinePreview }/> 547{ tr ( resizeHandle )} 548</ div > 549</>); 550} 551interface SlashCommand { 552id :string ; 553label :string ; 554hint :string ; 555icon :IconName ; 556run :() => void ; 557} 558function useSlashCommands ( clear :() => void , setDraft :( value :string ) => void ) :SlashCommand [] { 559const demo = useStore ( s => s . library ?. mode === 'simulated' ); 560return [ 561{ id :'time-skip' , label :'/time-skip' , hint :'Try a change on a copy, check it, and keep it only if it is better' , icon :'branch' , run :() => setDraft ( '/time-skip ' ) }, 562{ id :'goal' , label :'/goal' , hint :'Set a goal and let the assistant keep working until it is done' , icon :'bolt' , run :() => setDraft ( '/goal ' ) }, 563{ id :'plan' , label :'/plan' , hint :'Have the assistant write a plan first; nothing runs until you approve it' , icon :'check' , run :() => setDraft ( '/plan ' ) }, 564{ id :'research' , label :'/research' , hint :'Search the web, read the pages and answer with sources' , icon :'search' , run :() => setDraft ( '/research ' ) }, 565{ id :'loop' , label :'/loop' , hint :'Repeat a message every few minutes while this chat is open' , icon :'refresh' , run :() => setDraft ( '/loop 10m ' ) }, 566{ id :'website' , label :'/website' , hint :'Open a website in the preview sidebar' , icon :'link' , run :() => { clear (); window . dispatchEvent ( new Event ( 'strata:open-website' )); } }, 567{ id :'preview' , label :'/preview' , hint :'Open a local file in the preview sidebar' , icon :'file' , run :() => { clear (); window . dispatchEvent ( new Event ( 'strata:open-preview' )); } }, 568 ...( demo ?[{ id :'subagents' , label :'/subagents' , hint :'Preview subagent statistics' , icon :'experts' as const , run :() => { clear (); createSubagentExample (); } }] :[]), 569 ...getSlashCommands (). map ( command => ({ ...command , run :() => { clear (); command . run (); } })) 570]; 571} 572function SlashMenu ({ query, commands, cursor, onPick, onHover, } :{ 573query :string ; 574commands :SlashCommand []; 575cursor :number ; 576onPick :( c :SlashCommand ) => void ; 577onHover :( i :number ) => void ; 578}) { 579const matches = commands . filter (( c ) => c . label . slice ( 1 ). startsWith ( query . toLowerCase ())); 580if ( ! matches . length ) { 581return (< div className = "slashmenu" > 582< div className = "slashmenu__empty small muted" >{ tr ( "No command matches \u201C/" )}{ query } ” </ div > 583</ div >); 584} 585return (< div className = "slashmenu" role = "listbox" aria-label = { tr ( "Commands" )}> 586< div className = "slashmenu__label" >{ tr ( "Commands" )}</ div > 587{ tr ( matches . map (( c , i ) => (< button key = { c . id } type = "button" role = "option" aria-selected = { i === cursor } className = "slashmenu__item" data-active = { i === cursor } onMouseEnter = {() => onHover ( i )} onMouseDown = { e => e . preventDefault ()} onClick = {() => onPick ( c )}> 588< Icon name = { c . icon } size = { 16 }/> 589< span className = "slashmenu__name" >{ tr ( c . label )}</ span > 590< span className = "slashmenu__hint" >{ tr ( c . hint )}</ span > 591</ button >)))} 592</ div >); 593} 594const NO_PARKED :string [] = []; 595/** Whether the reader has words selected inside the transcript: a view that moves under the pointer loses the selection (#3818). */ 596function readerHasSelection ( scroller :HTMLElement ) :boolean { 597const sel = window . getSelection (); 598return !! sel && ! sel . isCollapsed && !! sel . anchorNode && scroller . contains ( sel . anchorNode ) && sel . toString (). trim (). length > 0 ; 599} 600const NO_QUOTES :Quote [] = []; 601/** The message that goes out: the quoted passages in their fixed form, then the person's words. A command such as /plan goes out as typed. */ 602function quotedMessage ( quotes :readonly Quote [], text :string ) :string { 603return quotes . length && ! text . startsWith ( '/' ) ?composeQuoted ( quotes . map ( q => q . text ), text ) :text ; 604} 605function Composer ({ draft, setDraft, loaded, streaming, onSubmit, onKey, session, onPreview, textareaRef, } :{ 606draft :string ; 607setDraft :( v :string ) => void ; 608loaded :boolean ; 609streaming :boolean ; 610onSubmit :() => void ; 611onKey :( e :React . KeyboardEvent ) => void ; 612session :Session | null ; 613onPreview :( a :PreviewArtifact ) => void ; 614textareaRef :React . RefObject < HTMLTextAreaElement | null >; 615}) { 616const clearDraft = useCallback (() => setDraft ( '' ), [ setDraft ]); 617const photos = useChatPhotos ( session ?. id ), native = useNative (); 618const canChat = loaded || native ?. instances . some ( i => i . status === 'ready' ); 619const whileBusy = useStore ( s => s . whileBusy ), parkedList = useStore ( s => ( session ?s . parked [ session . id ] :undefined )) ?? NO_PARKED ; 620const quoteList = useStore ( s => ( session ?s . quotes [ session . id ] :undefined )) ?? NO_QUOTES ; 621const commands = useSlashCommands ( clearDraft , setDraft ); 622const [ cursor , setCursor ] = useState ( 0 ); 623const [ fileError , setFileError ] = useState ( '' ); 624const [ slashOpen , setSlashOpen ] = useState ( false ); 625const [ slashDismissed , setSlashDismissed ] = useState ( false ); 626const slashHostRef = useRef < HTMLDivElement >( null ); 627const ime = useRef ( createImeGuard ()); 628const slashQuery = slashDismissed ?null :slashOpen ?'' :draft . startsWith ( '/' ) && ! /\s / . test ( draft ) ?draft . slice ( 1 ) :null ; 629const matches = slashQuery === null ?[] :commands . filter (( c ) => c . label . slice ( 1 ). startsWith ( slashQuery . toLowerCase ())); 630useEffect (() => { setSlashDismissed ( false ); }, [ draft , session ?. id ]); 631useEffect (() => { 632if ( slashQuery === null ) 633return ; 634const outside = ( event :PointerEvent ) => { 635if ( slashHostRef . current ?. contains ( event . target as Node ) || event . target === textareaRef . current ) 636return ; 637setSlashOpen ( false ); 638setSlashDismissed ( true ); 639}; 640document . addEventListener ( 'pointerdown' , outside ); 641return () => document . removeEventListener ( 'pointerdown' , outside ); 642}, [ slashQuery , textareaRef ]); 643useEffect (() => { 644setCursor ( 0 ); 645}, [ slashQuery ]); 646return (< div className = "composerwrap" > 647< div className = "composer" > 648< div className = "composer__inner" > 649< ApprovalDock sessionId = { session ?. id }/> 650{ tr ( fileError ?< ErrorNotice message = { fileError } action = { tr ( "Dismiss" )} onRetry = {() => setFileError ( '' )}/> :null )} 651< FolderChip chatId = { session ?. id } disabled = { streaming }/> 652< GoalBar chatId = { session ?. id }/> 653{ tr ( quoteList . length ?< div className = "quotes" >{ tr ( quoteList . map ( q => < div className = "quote" key = { q . id }>< button type = "button" className = "quote__body" title = { tr ( "Go to the quoted message" )} onClick = {() => document . querySelector ( `[data-message-id=" ${ CSS . escape ( q . messageId )} "]` )?. scrollIntoView ({ block :'center' , behavior :scrollBehavior () })}>< span className = "xs muted" >{ tr ( q . role === 'user' ?"Quoting you" :"Quoting the assistant" )}</ span >< span className = "quote__text" >{ q . text }</ span ></ button >< IconBtn name = "x" size = { 14 } title = { tr ( "Remove this quote" )} onClick = {() => removeQuote ( session ! . id , q . id )}/></ div >))}</ div > :null )} 654{ tr ( parkedList . length ?< div className = "parked" role = "status" >{ tr ( parkedList . map (( text , i ) => < div className = "parked__item" key = { ` ${ i } - ${ text } ` }>< span className = "xs muted" >{ tr ( "Waiting to send" )}</ span >< span className = "parked__text" title = { text }>{ text }</ span >< IconBtn name = "x" size = { 14 } title = { tr ( "Take back" )} onClick = {() => { const back = takeParked ( session ! . id , i ); if ( back !== undefined && ! draft . trim ()) setDraft ( back ); }}/></ div >))}</ div > :null )} 655< div className = "st-composer" style = {{ boxShadow :'var(--st-sh-bar)' }}> 656{ tr ( photos . length ?< ChatPhotos photos = { photos } onRemove = { id => removeChatPhoto ( id , session ?. id )}/> :null )} 657< textarea ref = { textareaRef } rows = { 1 } value = { draft } aria-label = { tr ( "Message Strata" )} placeholder = { tr ( canChat ?'Message Strata…' :'Try /time-skip, or load a model to chat…' )} onFocus = {() => setSlashDismissed ( false )} onBlur = {() => ime . current . reset ()} onCompositionStart = {() => ime . current . compositionStart ()} onCompositionEnd = {( e ) => ime . current . compositionEnd ( e . timeStamp )} onPaste = {( e ) => { 658// A picture on the clipboard (a screenshot, a copied image) is attached like a dropped file; text pastes as usual. 659const files = pastedFiles ( e . clipboardData ); 660if ( ! files . length ) 661return ; 662e . preventDefault (); 663window . dispatchEvent ( new CustomEvent ( DROP_EVENT , { detail :files })); 664}} onChange = {( e ) => { setSlashOpen ( false ); setSlashDismissed ( false ); setDraft ( e . target . value ); e . currentTarget . style . height = "auto" ; e . currentTarget . style . height = ` ${ Math . min ( 180 , e . currentTarget . scrollHeight )} px` ; }} onKeyDown = {( e ) => { 665// A key that belongs to the IME (the Enter that commits a conversion, in the order each engine delivers it) is not ours (#5071). 666if ( ime . current . keyDown ({ key :e . key , isComposing :e . nativeEvent . isComposing , keyCode :e . nativeEvent . keyCode }, e . timeStamp )) 667return ; 668// The command menu owns the keyboard while it is open. 669if ( slashQuery !== null && e . key === 'Escape' ) { 670e . preventDefault (); 671e . stopPropagation (); 672setSlashOpen ( false ); 673setSlashDismissed ( true ); 674return ; 675} 676if ( slashQuery !== null && matches . length ) { 677if ( e . key === 'ArrowDown' ) { 678e . preventDefault (); 679setCursor (( c ) => ( c + 1 ) % matches . length ); 680return ; 681} 682if ( e . key === 'ArrowUp' ) { 683e . preventDefault (); 684setCursor (( c ) => ( c - 1 + matches . length ) % matches . length ); 685return ; 686} 687if ( e . key === 'Enter' || e . key === 'Tab' ) { 688e . preventDefault (); 689setSlashOpen ( false ); 690setSlashDismissed ( true ); 691matches [ cursor ]. run (); 692return ; 693} 694} 695onKey ( e ); 696if ( composerSends ( e )) { 697e . preventDefault (); 698onSubmit (); 699} 700}}/> 701< div className = "st-composer__bar" > 702< ComposerControls draft = { draft } onDraft = { setDraft } session = { session } onPreview = { onPreview } streaming = { streaming } onSlash = {() => { setSlashDismissed ( false ); setSlashOpen ( true ); requestAnimationFrame (() => textareaRef . current ?. focus ()); }} onError = { setFileError } onAttach = {( name , text ) => { setDraft ( ` ${ draft } ${ draft ? '\n\n' : '' } Attached ${ name } \n\n ${ text } ` ); requestAnimationFrame (() => textareaRef . current ?. focus ()); }}/> 703{ tr ( streaming ?(< Btn variant = "secondary" size = "sm" icon = "stop" onClick = { stopStreaming }>{ tr ( "Stop" )}</ Btn >) :(< Btn variant = "primary" size = "sm" icon = "send" disabled = {( ! draft . trim () && ! photos . length ) || draft . trim () === '/' || ( ! canChat && timeSkipPrompt ( draft ) === null )} onClick = { onSubmit }>{ tr ( "Send" )}</ Btn >))} 704</ div > 705</ div > 706{ tr ( streaming && draft . trim () && whileBusy !== 'wait' ?< p className = "xs muted composer__busy-hint" role = "status" >{ tr ( whileBusy === 'queue' ?"Enter sends it when the answer is done." :"Enter stops the answer here and sends it now." )}</ p > :null )} 707< ChatTelemetry session = { session }/> 708</ div > 709</ div > 710{ /* Outside the composer's glass on purpose: a material sampling another 711material blurs an already-blurred backdrop, which Liquid Glass 712prohibits and which doubles the compositor cost for a muddier result. 713The host repeats the composer's padding so the menu keeps its column. */ } 714{ tr ( slashQuery !== null ?(< div className = "slashmenu-host" ref = { slashHostRef }> 715< SlashMenu query = { slashQuery } commands = { commands } cursor = { cursor } onHover = { setCursor } onPick = {( c ) => { 716setSlashOpen ( false ); 717setSlashDismissed ( true ); 718c . run (); 719}}/> 720</ div >) :null )} 721</ div >); 722} 723const Message = memo ( MessageView ); 724function MessageView ({ message :m , isLast, onEditPrompt, onPreview, onClosePreview, onOpenLink, onOpenTimeSkip, timeSkipDone, timeSkipReal, timeSkipRun, } :{ 725message :ChatMessage ; 726isLast :boolean ; 727onEditPrompt :( text :string ) => void ; 728onPreview :( a :PreviewArtifact ) => void ; 729onClosePreview :( id :string ) => void ; 730onOpenLink :( url :string ) => void ; 731onOpenTimeSkip :( id :string ) => void ; 732timeSkipDone :boolean ; 733timeSkipReal ?:boolean ; 734timeSkipRun ?:TimeSkipRun ; 735}) { 736const streaming = useStore ( s => s . streaming ); 737const activeSession = useStore ( s => s . activeSession ); 738const hostLive = useStore ( s => s . connection !== 'offline' ); 739const liveStatus = useLiveStatus ( m . role === 'assistant' && m . streaming ?activeSession :null ); 740// A reply that proposed a plan shows the plan card in place of its closing text (which is the plan in prose). 741const storedPlan = usePlanQuiet ( m . planId ?activeSession :null ); 742const planCard = !! m . planId && storedPlan ?. id === m . planId ; 743// A reply with activity lines is drawn piece by piece in the order it came; one without is the plain text it always was. 744const grouped = !! m . blocks ?. some ( b => b . kind === 'group' ); 745const [ sentTime , setSentTime ] = useState (() => relTime ( m . at )); 746const sentQuote = m . role === 'user' ?parseQuoted ( m . content ) :null ; 747if ( m . role === 'user' ) { 748return (< div className = "st-msg st-msg--user" data-message-id = { m . id } onMouseEnter = {() => setSentTime ( relTime ( m . at ))} onFocus = {() => setSentTime ( relTime ( m . at ))}> 749< div className = "st-bubble" >{ tr ( m . photos ?. length ?< ChatPhotos photos = { m . photos }/> :null )}{ sentQuote ?<>< SentQuotes quotes = { sentQuote . quotes }/>< span className = "st-bubble__text" >{ sentQuote . reply }</ span ></> :m . markdown ?< Markdown text = { m . content } onOpenLink = { onOpenLink } imageSession = { activeSession }/> :< span className = "st-bubble__text" >{ m . content }</ span >}</ div > 750< div className = "st-msg__meta" > 751< time dateTime = { m . at } title = { tr ( new Date ( m . at ). toLocaleString ( localeTag ()))}>{ tr ( sentTime )}</ time > 752< span className = "st-msg__actions" > 753< CopyBtn text = { m . content } label = "Message" title = "Copy message" /> 754< IconBtn name = "refresh" title = { tr ( "Rewind to here" )} disabled = { streaming } onClick = {() => { 755const prompt = rewindTo ( m . id ); 756if ( prompt !== null ) 757onEditPrompt ( prompt ); 758}}/> 759< MessageMenu label = { tr ( "More message actions" )}>< button role = "menuitem" className = "menu__item" onClick = {() => activeSession && addQuote ( activeSession , m . content , m . id , 'user' )}>{ tr ( "Quote" )}</ button >< button role = "menuitem" className = "menu__item" onClick = {() => branchFrom ( m . id )}>< Icon name = "branch" />{ tr ( "Branch from here" )}</ button ></ MessageMenu > 760</ span > 761</ div > 762</ div >); 763} 764return (< div className = "st-msg st-msg--assistant" data-message-id = { m . id } data-error = { m . error ?'true' :undefined }> 765{ tr ( m . reasoning ?< ReasoningBlock message = { m }/> :null )} 766 767 768{ /* In a reply with activity lines the line is the one live cue for a running or finished tool (and the status line below says what it is doing now); the 769card stays only for what needs the person: a question waiting, a denied or failed call. A card that came and went above the text moved the whole reply. */ } 770{ tr (( m . tools ?? []). filter ( t => ! grouped || t . state === 'proposed' || t . state === 'denied' || t . state === 'error' ). map (( t ) => (< ToolCard key = { t . id } tool = { t }/>)))} 771 772{ tr ( ! ( m . timeSkipId && timeSkipReal && ! timeSkipDone ) && ( m . content || m . error || ! m . streaming || ! liveStatus || !! m . drafts ?. length ) ?< div className = "st-bubble" > 773{ tr ( planCard ?< PlanCard chatId = { activeSession } planId = { m . planId ! }/> :null )} 774{ tr ( m . error ?(< ErrorNotice message = { m . error } detail = { m . errorDetail } { ...contextRecovery ( m . errorCode )}/>) :null )} 775{ tr ( grouped && ! planCard && ! m . timeSkipId ?m . blocks ! . map (( b , i ) => b . kind === 'group' ?< ActivityLine key = { b . id } group = { b } sessionId = { activeSession ?? '' } onPreview = { onPreview }/> :< Markdown key = { i } text = { b . text } onOpenLink = { onOpenLink } imageSession = { activeSession } previewId = { ` ${ m . id } -b ${ i } ` } onPreview = { onPreview } onClosePreview = { onClosePreview }/>) :null )} 776{ tr ( m . content && ! planCard && ! grouped ?(< Markdown text = { m . timeSkipId && ! timeSkipReal ?hostLive ?tr ( 'This was a sample run made while the app could not reach its host.' ) :timeSkipDone ?tr ( 'The result is ready. Switch between Original and Updated, or compare them side by side. This example uses sample outputs and simulated checks.' ) :tr ( 'Revising the saved draft. Follow the result in the sidebar. This example uses sample outputs and simulated checks.' ) :m . content } onOpenLink = { onOpenLink } imageSession = { activeSession } previewId = { m . id } onPreview = { onPreview } onClosePreview = { onClosePreview }/>) :! m . error && m . streaming && ! liveStatus ?(< span className = "typing" aria-label = { tr ( "Generating" )}> 777< i /> 778< i /> 779< i /> 780</ span >) :null )} 781{ /* a file or command the model is writing right now: its name, growing size and the last lines of it (live data from the host, see ToolDraft) */ } 782{ tr ( m . streaming && m . drafts ?. length && ! planCard ?< DraftLines drafts = { m . drafts } sessionId = { activeSession ?? '' } onPreview = { onPreview }/> :null )} 783{ /* the caret follows the text being written; after an activity line it hung on a row of its own and the reply jumped when the text went on */ } 784{ tr ( m . streaming && m . content && ! m . drafts ?. length && ( ! grouped || m . blocks ! . at ( - 1 )?. kind === 'text' ) ?< span className = "caret" aria-hidden = "true" /> :null )} 785</ div > :null )} 786{ tr ( m . skills ?. length && ! m . streaming ?< SkillsUsed skills = { m . skills }/> :null )} 787{ tr ( m . deliverables ?. length && ! m . streaming ?< div className = "deliverables" >{ m . deliverables . length >= COMPACT_FILES_FROM ?< FilesSummary files = { m . deliverables } answer = { m . content } sessionId = { activeSession ?? '' } onPreview = { onPreview }/> :<>{ m . deliverables . map ( f => < FileCard key = { f . path } file = { f } sessionId = { activeSession ?? '' } onPreview = { onPreview }/>)}< EditedFiles files = { m . deliverables } sessionId = { activeSession ?? '' } onPreview = { onPreview }/></>}</ div > :null )} 788{ tr ( m . streaming && isLast && ! m . timeSkipId ?< StatusLine sessionId = { activeSession } startedAt = { Date . parse ( m . at ) || Date . now ()} tokens = { m . tokens }/> :null )} 789 790{ tr ( m . timeSkipId && timeSkipReal && ! timeSkipDone && timeSkipRun ?< Suspense fallback = { null }>< TimeSkipWorking run = { timeSkipRun } sessionId = { activeSession ?? '' }/></ Suspense > :m . timeSkipId && ( ! timeSkipReal || ( timeSkipRun ?. job ?. files ?. length ?? 0 ) > 0 ) ?< button className = "timeskip-chat-card" onClick = {() => onOpenTimeSkip ( m . timeSkipId ! )}>< Icon name = "branch" size = { 20 }/>< span >< strong >{ tr ( "Time-skip" )}</ strong >< span >{ tr ( timeSkipDone ?'Result ready · compare versions' :'Revising · follow progress' )}</ span ></ span >< Icon name = "chevron" size = { 16 } className = "timeskip-card-arrow" /></ button > :null )} 791{ tr ( m . media ?. length ?< ChatMedia items = { m . media } onPreview = { onPreview }/> :null )} 792{ tr ( m . artifacts ?. length ?< div className = "artifact-cards" >{ tr ( m . artifacts . map ( a => < ArtifactCard key = { a . id } artifact = { a } onPreview = { onPreview }/>))}</ div > :null )} 793 794{ tr ( ! m . streaming && ! m . timeSkipId && ( m . content || m . error ) ?(< div className = "st-msg__meta" > 795< span className = "st-msg__actions" > 796{ tr ( isLast ?<> 797< CopyBtn text = { m . content } label = "Response" title = "Copy response" /> 798< IconBtn name = "refresh" title = { tr ( "Ask again" )} onClick = {() => void retryLast ( m . id )}/> 799</> :null )} 800< MessageMenu label = { tr ( "More response actions" )}> 801{ tr ( ! isLast ?<>< CopyMenuItem text = { m . content } label = "Response" > Copy response </ CopyMenuItem >< button role = "menuitem" className = "menu__item" onClick = {() => void retryLast ( m . id )}>{ tr ( "Ask again" )}</ button ></> :null )} 802{ tr ( isLast ?< button role = "menuitem" className = "menu__item" onClick = {() => void continueLast ()}>{ tr ( "Continue" )}</ button > :null )} 803< button role = "menuitem" className = "menu__item" onClick = {() => activeSession && addQuote ( activeSession , m . content , m . id , 'assistant' )}>{ tr ( "Quote" )}</ button > 804< button role = "menuitem" className = "menu__item" onClick = {() => branchFrom ( m . id )}>{ tr ( "Branch from here" )}</ button > 805{ tr ( m . tokens || m . tps || m . durationMs ?< p className = "xs muted response-stats" >{ tr ( m . tokens ?` ${ tokens ( m . tokens )} tokens` :'' )}{ tr ( m . tps ?` · ${ tps ( m . tps )} tok/s` :'' )}{ tr ( m . durationMs ?` · ${ duration ( m . durationMs )} ` :'' )}{ tr ( m . demo ?' · Example' :'' )}</ p > :null )} 806</ MessageMenu > 807</ span > 808</ div >) :null )} 809</ div >); 810} 811/** The passages a sent message quoted, one or two lines each; a click shows the rest. */ 812function SentQuotes ({ quotes} :{ quotes :string [] }) { 813const [ open , setOpen ] = useState ( false ); 814return < div className = "sent-quotes" data-open = { open || undefined }>{ quotes . map (( q , i ) => < button type = "button" key = { i } className = "sent-quote" aria-expanded = { open } title = { tr ( "Show or hide the rest of the quote" )} onClick = {() => setOpen ( v => ! v )}>< span className = "xs muted" >{ tr ( "Quoted" )}</ span >< span className = "sent-quote__text" >{ q }</ span ></ button >)}</ div >; 815} 816function MessageMenu ({ label, children} :{ 817label :string ; 818children :React . ReactNode ; 819}) { 820const [ open , setOpen ] = useState ( false ); 821const trigger = useRef < HTMLButtonElement >( null ); 822return <>< button ref = { trigger } className = "st-btn st-btn--icon" aria-label = { tr ( label )} aria-haspopup = "menu" aria-expanded = { open } onClick = {() => setOpen ( v => ! v )}>< Icon name = "ellipsis" size = { 16 }/></ button >{ tr ( open ?< FloatingMenu anchor = { trigger . current } title = { tr ( label )} onClose = {() => setOpen ( false )}>< MenuCloseContext . Provider value = {() => setOpen ( false )}>< div onClick = {() => setOpen ( false )}>{ tr ( children )}</ div ></ MenuCloseContext . Provider ></ FloatingMenu > :null )}</>; 823} 824/** 825* A tool call, with the grant it needs. Approvals are per action and per turn — 826* the model never gets standing permission. 827*/ 828function ToolCard ({ tool :t } :{ 829tool :ToolCall ; 830}) { 831const scope = SCOPE [ t . scope ]; 832const pending = t . state === 'proposed' ; 833if ( ! pending && t . state !== 'running' ) 834return < details className = "disclosure tool-summary" >< summary >< Icon name = "chevron" size = { 14 }/>{ tr ( t . verb ?? t . name )}{ t . target ?<>< span > · </ span >< span className = "tool-summary__target" title = { t . target }>{ t . target }</ span ></> :null }< span > · </ span >< Icon name = { t . state === 'denied' || t . state === 'error' ?'x' :'check' } size = { 14 }/>{ tr ( t . state === 'denied' ?'Denied' :t . state === 'error' ?'Failed' :t . live && t . state === 'done' && t . approved ?'Approved' :'Done' )}</ summary >< div >< code >{ t . preview }</ code >< p className = "small muted" >{ tr ( t . result ?? t . effect )}</ p ></ div ></ details >; 835/* The question and its two buttons are in the dock above the message box (ApprovalDock), so a long reply cannot push them out of view (#4725). */ 836if ( pending ) 837return < p className = "approval-wait small muted" role = "status" >< Icon name = "clock" size = { 14 }/>{ tr ( "Waiting for your answer below" )}</ p >; 838return < section className = "toolcard toolcard--compact" data-state = { t . state } aria-label = { t . name }> 839< details className = "toolcard__disclosure" > 840< summary >< Icon name = { t . scope === 'shell' ?'bolt' :'tool' } size = { 17 }/>< span className = "toolcard__title" >{ tr ( t . verb ?? t . name )}</ span >< span className = "toolcard__scope xs muted" >{ tr ( scope . label )}</ span >< Icon name = "chevron" className = "toolcard__chevron" size = { 15 }/></ summary > 841< div className = "toolcard__body" >< code className = "toolcard__preview" >{ t . preview }</ code >< p className = "small muted" >{ tr ( t . effect )}</ p >{ tr ( t . result ?< p className = "small" >{ t . result }</ p > :null )}</ div > 842</ details > 843< span className = "xs muted toolcard__running" role = "status" >{ tr ( "Running\u2026" )}</ span > 844</ section >; 845} 846export { cx };