okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge f-0215-parked: chat: a parked message is sent only from the chat that is also the active one (#5806)7c11eb58b

main
57.6 KiB846 linesraw
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() {
59    const location = useLocation();
60    const sessions = useStore((s) => s.sessions);
61    const activeId = useStore((s) => s.activeSession);
62    const library = useStore((s) => s.library);
63    const streaming = useStore((s) => s.streaming);
64    const whileBusy = useStore(s => s.whileBusy);
65    const setup = useStore(s => s.setup);
66    const setupFlag = useStore(s => s.setupOpen);
67    const setupVisible = location.route === 'setup' || setupFlag || !!setup && !setup.complete && !setup.dismissed;
68    const session: Session | null = useMemo(() => {
69        const wanted = location.param ?? activeId;
70        return 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
73       reply streams into it. Without this, switching away from a session that
74       answered you would mark it unread. */
75    const messageCount = session?.messages.length ?? 0;
76    useEffect(() => {
77        if (session && session.id === activeId && !streaming)
78            markRead(session.id);
79        // eslint-disable-next-line react-hooks/exhaustive-deps
80    }, [session?.id, messageCount, streaming]);
81    const parked = useStore(s => (session ? s.parked[session.id] : undefined));
82    const quotes = useStore(s => (session ? s.quotes[session.id] : undefined)) ?? NO_QUOTES;
83    // Selecting words in a message offers to quote just them (#4785).
84    const [selection, setSelection] = useState<{ text: string; messageId: string; role: 'user' | 'assistant'; x: number; y: number } | null>(null);
85    useEffect(() => {
86        const read = () => {
87            const sel = window.getSelection();
88            const el = scroller.current;
89            if (!sel || sel.isCollapsed || !sel.rangeCount || !el) { setSelection(null); return; }
90            const range = sel.getRangeAt(0);
91            const node = range.commonAncestorContainer;
92            const host = (node instanceof Element ? node : node.parentElement)?.closest('.st-msg');
93            const text = sel.toString().trim();
94            if (!host || !el.contains(host) || text.length < 2) { setSelection(null); return; }
95            const 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)
97            const { scale, viewport } = measureFrame();
98            setSelection({ 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        };
100        document.addEventListener('selectionchange', read);
101        return () => 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).
105    useEffect(() => {
106        if (!session || !parkedReady(session.id, activeId, streaming, parked?.length ?? 0))
107            return;
108        const next = takeParked(session.id);
109        if (next !== undefined)
110            void sendMessage(next);
111    }, [streaming, parked?.length, session?.id, activeId]);
112    const [draft, setDraft] = useState('');
113    const draftKey = `strata.chat-draft.${session?.id ?? 'new'}`;
114    useEffect(() => {
115        setDraft(sessionStorage.getItem(draftKey) ?? '');
116        if (session && session.id !== activeId)
117            selectSession(session.id);
118    }, [draftKey]);
119    const updateDraft = (value: string) => { setDraft(value); sessionStorage.setItem(draftKey, value); };
120    const splitRef = useRef<HTMLDivElement>(null);
121    const [splitWidth, setSplitWidth] = useState(0);
122    const [previewFraction, setPreviewFraction] = useState(() => {
123        try {
124            const saved = localStorage.getItem(PREVIEW_SPLIT_KEY);
125            return saved && Number.isFinite(Number(saved)) ? Number(saved) : DEFAULT_PREVIEW_FRACTION;
126        }
127        catch {
128            return DEFAULT_PREVIEW_FRACTION;
129        }
130    });
131    useEffect(() => {
132        const timer = setTimeout(() => {
133            try {
134                localStorage.setItem(PREVIEW_SPLIT_KEY, String(previewFraction));
135            }
136            catch { }
137        }, 180);
138        return () => clearTimeout(timer);
139    }, [previewFraction]);
140    useEffect(() => {
141        if (!splitRef.current)
142            return;
143        const ro = new ResizeObserver(entries => setSplitWidth(entries[0].contentRect.width));
144        ro.observe(splitRef.current);
145        return () => ro.disconnect();
146    }, [session?.id]);
147    const [expanded, setExpanded] = useState(false);
148    useEffect(() => { setExpanded(false); }, [session?.id]);
149    useEffect(() => {
150        if (!expanded)
151            return;
152        const exit = (e: KeyboardEvent) => {
153            if (e.key === 'Escape')
154                setExpanded(false);
155        };
156        document.addEventListener('keydown', exit);
157        return () => document.removeEventListener('keydown', exit);
158    }, [expanded]);
159    const [previews, setPreviews] = useState<PreviewArtifact[]>([]);
160    const [selectedPreview, setSelectedPreview] = useState<string | null>(null);
161    const timeSkipRuns = (session?.timeSkips ?? []).filter(run => session?.messages.some(m => m.timeSkipId === run.id && m.role === 'assistant') && (!run.job || (run.job.files?.length ?? 0) > 0));
162    const 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));
163    const plan = usePlan(session?.id);
164    const planTabId = session ? `plan:${session.id}` : '';
165    const planTab = plan && plan.state !== 'rejected' && !session?.closedPreviews?.includes(planTabId) ? [{ id: planTabId, title: 'Plan', icon: 'check' as const, controls: 'plan-content' }] : [];
166    const planShown = planTab.length > 0 && selectedPreview === planTabId;
167    const planRunId = plan?.state === 'running' ? plan.id : '';
168    useEffect(() => { 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.
170    const allTimeSkipRuns = session?.timeSkips ?? [];
171    const extraTabs = [...runTabs, ...planTab];
172    const selectedRun = timeSkipRuns.find(run => timeSkipTabId(run.id) === selectedPreview);
173    const inlinePreview = splitWidth >= (selectedRun || planShown ? 760 : 1120);
174    const paneWidth = previewWidth(splitWidth, previewFraction);
175    const splitStyle = inlinePreview && selectedPreview && !expanded ? { gridTemplateColumns: `minmax(0,1fr) ${paneWidth}px` } : undefined;
176    const 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;
177    const runCount = timeSkipRuns.length;
178    const previewCount = session?.messages.reduce((n, m) => n + (m.artifacts?.length ?? 0), 0) ?? 0;
179    useEffect(() => { 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]);
180    useEffect(() => {
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.
182        const items = messageArtifacts(session?.messages);
183        if (items.length)
184            setPreviews(old => syncArtifacts(old, items, session?.closedPreviews));
185    }, [previewCount]);
186    const localUrls = useRef<string[]>([]);
187    useEffect(() => {
188        const id = session?.previewOpen;
189        if (id?.startsWith('time-skip:') && timeSkipRuns.some(r => timeSkipTabId(r.id) === id) && !session?.closedPreviews?.includes(id) && !(session && previewsDeferred(session.id)))
190            setSelectedPreview(id);
191    }, [session?.id, runCount]);
192    useEffect(() => () => localUrls.current.forEach(url => URL.revokeObjectURL(url)), []);
193    function openPreview(item: PreviewArtifact) {
194        endPreviewDeferral();
195        if (item.url?.startsWith('blob:'))
196            localUrls.current.push(item.url);
197        setPreviewTabClosed(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).
199        setPreviews(old => openItem(old, item));
200        setSelectedPreview(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
203       finishing here does it: opening an old chat shows nothing new. A file that cannot be read just stays a card with Open. */
204    const replyWasStreaming = useRef<Map<string, boolean>>(new Map());
205    const lastReply = [...(session?.messages ?? [])].reverse().find(m => m.role === 'assistant');
206    useEffect(() => {
207        if (!session || !lastReply) return;
208        const before = replyWasStreaming.current.get(lastReply.id);
209        replyWasStreaming.current.set(lastReply.id, !!lastReply.streaming);
210        if (before !== true || lastReply.streaming || lastReply.error) return;
211        const 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).
213        if (!main) { const page = lastReply.blocks?.some(b => b.kind === 'group') ? null : mainCodePreview(lastReply.id, lastReply.content); if (page) openPreview(page); return; }
214        const sessionId = session.id;
215        void previewOf(sessionId, main).then(item => { if (session.id === sessionId) openPreview(item); }, () => { });
216    }, [lastReply?.id, lastReply?.streaming]);
217    useEffect(() => { setSelectedPreviewId(setupVisible ? null : selectedPreview); return () => setSelectedPreviewId(null); }, [selectedPreview, setupVisible]);
218    function closeTab(id: string) {
219        const next = closePreviewTab([...previews.map(p => ({ id: p.id })), ...extraTabs], selectedPreview, id);
220        setPreviews(previews.filter(p => p.id !== id));
221        setSelectedPreview(next.selected);
222        setPreviewTabClosed(session?.id, id, true, next.selected);
223        if (!next.items.length) {
224            setExpanded(false);
225            requestAnimationFrame(() => textarea.current?.focus());
226        }
227    }
228    function selectPreview(id: string) {
229        endPreviewDeferral();
230        setSelectedPreview(id);
231        setPreviewTabClosed(session?.id, id, false, id);
232    }
233    function openTimeSkip(id: string) { selectPreview(timeSkipTabId(id)); }
234    function openLink(url: string) {
235        const item = artifactFromUrl(url);
236        if (!item)
237            return;
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).
239        if (item.kind === 'website') {
240            void openExternal(url);
241            return;
242        }
243        openPreview(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
246       re-render. These handlers keep one identity for the life of the screen and always call the newest functions above. */
247    const latestHandlers = useRef({ editPrompt, openPreview, closeTab, openTimeSkip, openLink });
248    latestHandlers.current = { editPrompt, openPreview, closeTab, openTimeSkip, openLink };
249    const messageHandlers = useMemo(() => ({
250        onEditPrompt: (text: string) => latestHandlers.current.editPrompt(text),
251        onPreview: (a: PreviewArtifact) => latestHandlers.current.openPreview(a),
252        onClosePreview: (id: string) => latestHandlers.current.closeTab(id),
253        onOpenTimeSkip: (id: string) => latestHandlers.current.openTimeSkip(id),
254        onOpenLink: (url: string) => latestHandlers.current.openLink(url),
255    }), []);
256    const scroller = useRef<HTMLDivElement>(null);
257    const focusMode = useStore((s) => s.focus);
258    /** Per-conversation scroll offsets, so returning to one restores the view. */
259    const scrollPositions = useRef<Map<string, number>>(new Map());
260    /* Scrolling back to reread something is normal; being stranded there while a
261       reply arrives is not. The pill only appears once you are far enough up that
262       the newest message is genuinely off screen. */
263    const [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
266       opacity alone, so the cue is noticed without anything moving. */
267    const [justFinished, setJustFinished] = useState(false);
268    const wasStreaming = useRef(false);
269    useEffect(() => {
270        if (wasStreaming.current && !streaming) {
271            setJustFinished(true);
272            const t = setTimeout(() => setJustFinished(false), 700);
273            wasStreaming.current = streaming;
274            return () => clearTimeout(t);
275        }
276        wasStreaming.current = streaming;
277        return undefined;
278    }, [streaming]);
279    /** Whether the reader is following the newest message rather than reading back. */
280    const pinned = useRef(true);
281    /** When the reader last used the wheel, a finger, a key or the scrollbar on the transcript. */
282    const readerInput = useRef(0);
283    const 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     */
293    const scrollToLatest = useCallback((smooth = true) => {
294        const el = scroller.current;
295        if (!el)
296            return;
297        pinned.current = true;
298        el.scrollTo({ top: el.scrollHeight, behavior: smooth ? scrollBehavior() : 'auto' });
299        setAwayFromBottom(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     */
310    useEffect(() => {
311        const el = scroller.current;
312        // The content, not the scroller's first child — which is the reading
313        // progress hairline, and never changes size.
314        const inner = el?.querySelector('.chat__inner');
315        if (!el || !inner)
316            return undefined;
317        const ro = new ResizeObserver(() => {
318            if (pinned.current && readerHasSelection(el)) {
319                // Words are selected: the view stays where they are (#3818); the way back to the newest message is offered.
320                pinned.current = false;
321                setAwayFromBottom(distanceFromBottom(el) > PILL_DISTANCE);
322            }
323            if (pinned.current)
324                el.scrollTop = el.scrollHeight;
325        });
326        ro.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.
328        ro.observe(el);
329        return () => ro.disconnect();
330    }, [session?.id, session?.messages.length === 0]);
331    const textarea = useRef<HTMLTextAreaElement>(null);
332    const remote = useStore(s => s.remoteModel), providers = useStore(s => s.providers);
333    const apiModel = providers?.connections.find(c => c.id === remote?.connectionId)?.models.find(m => m.id === remote?.modelId);
334    const 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     */
341    useEffect(() => {
342        const el = scroller.current;
343        if (!el || (session?.showcase && !streaming))
344            return;
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.
347        const count = session?.messages.length ?? 0;
348        const sent = count > seenMessages.current && session?.messages.at(-1)?.role === 'user';
349        seenMessages.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.
351        if (pinned.current && !sent && readerHasSelection(el)) {
352            pinned.current = false;
353            setAwayFromBottom(distanceFromBottom(el) > PILL_DISTANCE);
354        }
355        if (pinned.current || sent)
356            scrollToLatest();
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.
360    useEffect(() => {
361        const el = scroller.current;
362        if (!el || !session)
363            return;
364        const saved = scrollPositions.current.get(session.id);
365        el.scrollTop = saved ?? (session.showcase ? 0 : el.scrollHeight);
366        pinned.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).
372    useEffect(() => {
373        const fit = () => {
374            const el = textarea.current;
375            if (!el)
376                return;
377            el.style.height = 'auto';
378            el.style.height = `${Math.min(composerCap(window.innerHeight), el.scrollHeight)}px`;
379        };
380        fit();
381        window.addEventListener('resize', fit);
382        return () => window.removeEventListener('resize', fit);
383    }, [draft]);
384    /** Hands a rewound prompt back to the composer so it can be changed. */
385    function editPrompt(text: string) {
386        setDraft(text);
387        requestAnimationFrame(() => 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     */
397    useEffect(() => {
398        if (!focusMode)
399            return undefined;
400        const onKey = (e: KeyboardEvent) => {
401            const el = scroller.current;
402            if (!el)
403                return;
404            const atLatest = () => {
405                pinned.current = true;
406                el.scrollTo({ top: el.scrollHeight, behavior: scrollBehavior() });
407            };
408            if ((e.metaKey || e.ctrlKey) && e.key === 'ArrowDown') {
409                e.preventDefault();
410                atLatest();
411                return;
412            }
413            if (!e.altKey || (e.key !== 'ArrowUp' && e.key !== 'ArrowDown'))
414                return;
415            e.preventDefault();
416            const turns = [...el.querySelectorAll<HTMLElement>('.st-msg--user')];
417            if (!turns.length)
418                return;
419            const top = el.scrollTop;
420            /* The tolerance has to exceed TURN_OFFSET, or the key sticks on the turn
421               it just moved to: positioning a turn at `scrollTop + 16` leaves it
422               satisfying `offsetTop > scrollTop + 8` on the next press. */
423            const TURN_OFFSET = 16;
424            const seen = TURN_OFFSET + 24;
425            const next = e.key === 'ArrowDown'
426                ? turns.find((t) => t.offsetTop > top + seen)
427                : [...turns].reverse().find((t) => t.offsetTop < top - seen);
428            if (next) {
429                pinned.current = false;
430                el.scrollTo({ top: Math.max(0, next.offsetTop - TURN_OFFSET), behavior: scrollBehavior() });
431                setAwayFromBottom(true);
432            }
433            else if (e.key === 'ArrowDown') {
434                atLatest();
435            }
436        };
437        window.addEventListener('keydown', onKey);
438        return () => window.removeEventListener('keydown', onKey);
439    }, [focusMode]);
440    const chatNative = useNative(), queuedPhotos = useChatPhotos(session?.id);
441    const readyForChat = !!loaded || !!chatNative?.instances.some(i => i.status === 'ready');
442    useEffect(() => {
443        if (setupVisible || !readyForChat || messageCount)
444            return;
445        if (scroller.current?.querySelector('.first-chat-start'))
446            textarea.current?.focus({ preventScroll: true });
447    }, [setupVisible, readyForChat, session?.id, messageCount]);
448    function submit() {
449        const text = draft.trim();
450        if (!text && !queuedPhotos.length)
451            return;
452        if (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.
454            if (!text || !session)
455                return;
456            const plan = busyPlan(whileBusy);
457            const 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).
459            if (plan === 'interrupt') {
460                updateDraft('');
461                clearQuotes(session.id);
462                parkMessage(session.id, out);
463                stopStreaming();
464                return;
465            }
466            updateDraft('');
467            void 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); });
468            return;
469        }
470        const timeSkip = timeSkipPrompt(text);
471        if (timeSkip === '') {
472            pushToast('info', 'Add a prompt after /time-skip');
473            return;
474        }
475        if (timeSkip === null) {
476            // No model to answer: say so plainly (or show the download), and do not start a run.
477            const why = noModelNotice(chatNative ?? null, { libraryLoaded: !!loaded });
478            if (why) { pushToast('info', tr(why.title), tr(why.message)); return; }
479        }
480        updateDraft('');
481        if (session) clearQuotes(session.id);
482        void sendMessage(session ? quotedMessage(quotes, text) : text);
483    }
484    function onComposerKey(_e: React.KeyboardEvent) { }
485    if (!session) {
486        return (<>
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    }
504    return (<>
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
509                the context panel open, a full-width composer sat underneath the panel
510                and 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) => {
514            const el = e.currentTarget;
515            if (session)
516                scrollPositions.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.
521            const distance = distanceFromBottom(el);
522            pinned.current = followAfterScroll(distance, pinned.current, Date.now() - readerInput.current);
523            setAwayFromBottom(distance > PILL_DISTANCE);
524        }} onWheel={(e) => {
525            readerInput.current = Date.now();
526            if (wheelLeavesBottom(e.deltaY) && e.currentTarget.scrollTop > 0)
527                pinned.current = false;
528        }} onTouchMove={() => { readerInput.current = Date.now(); }} onPointerDown={() => { readerInput.current = Date.now(); }} onKeyDown={(e) => {
529            readerInput.current = Date.now();
530            if (KEYS_UP.has(e.key) && e.target === e.currentTarget && e.currentTarget.scrollTop > 0)
531                pinned.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 {
552    id: string;
553    label: string;
554    hint: string;
555    icon: IconName;
556    run: () => void;
557}
558function useSlashCommands(clear: () => void, setDraft: (value: string) => void): SlashCommand[] {
559    const demo = useStore(s => s.library?.mode === 'simulated');
560    return [
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, }: {
573    query: string;
574    commands: SlashCommand[];
575    cursor: number;
576    onPick: (c: SlashCommand) => void;
577    onHover: (i: number) => void;
578}) {
579    const matches = commands.filter((c) => c.label.slice(1).startsWith(query.toLowerCase()));
580    if (!matches.length) {
581        return (<div className="slashmenu">
582        <div className="slashmenu__empty small muted">{tr("No command matches \u201C/")}{query}”</div>
583      </div>);
584    }
585    return (<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 {
597    const sel = window.getSelection();
598    return !!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 {
603    return quotes.length && !text.startsWith('/') ? composeQuoted(quotes.map(q => q.text), text) : text;
604}
605function Composer({ draft, setDraft, loaded, streaming, onSubmit, onKey, session, onPreview, textareaRef, }: {
606    draft: string;
607    setDraft: (v: string) => void;
608    loaded: boolean;
609    streaming: boolean;
610    onSubmit: () => void;
611    onKey: (e: React.KeyboardEvent) => void;
612    session: Session | null;
613    onPreview: (a: PreviewArtifact) => void;
614    textareaRef: React.RefObject<HTMLTextAreaElement | null>;
615}) {
616    const clearDraft = useCallback(() => setDraft(''), [setDraft]);
617    const photos = useChatPhotos(session?.id), native = useNative();
618    const canChat = loaded || native?.instances.some(i => i.status === 'ready');
619    const whileBusy = useStore(s => s.whileBusy), parkedList = useStore(s => (session ? s.parked[session.id] : undefined)) ?? NO_PARKED;
620    const quoteList = useStore(s => (session ? s.quotes[session.id] : undefined)) ?? NO_QUOTES;
621    const commands = useSlashCommands(clearDraft, setDraft);
622    const [cursor, setCursor] = useState(0);
623    const [fileError, setFileError] = useState('');
624    const [slashOpen, setSlashOpen] = useState(false);
625    const [slashDismissed, setSlashDismissed] = useState(false);
626    const slashHostRef = useRef<HTMLDivElement>(null);
627    const ime = useRef(createImeGuard());
628    const slashQuery = slashDismissed ? null : slashOpen ? '' : draft.startsWith('/') && !/\s/.test(draft) ? draft.slice(1) : null;
629    const matches = slashQuery === null ? [] : commands.filter((c) => c.label.slice(1).startsWith(slashQuery.toLowerCase()));
630    useEffect(() => { setSlashDismissed(false); }, [draft, session?.id]);
631    useEffect(() => {
632        if (slashQuery === null)
633            return;
634        const outside = (event: PointerEvent) => {
635            if (slashHostRef.current?.contains(event.target as Node) || event.target === textareaRef.current)
636                return;
637            setSlashOpen(false);
638            setSlashDismissed(true);
639        };
640        document.addEventListener('pointerdown', outside);
641        return () => document.removeEventListener('pointerdown', outside);
642    }, [slashQuery, textareaRef]);
643    useEffect(() => {
644        setCursor(0);
645    }, [slashQuery]);
646    return (<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.
659            const files = pastedFiles(e.clipboardData);
660            if (!files.length)
661                return;
662            e.preventDefault();
663            window.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).
666            if (ime.current.keyDown({ key: e.key, isComposing: e.nativeEvent.isComposing, keyCode: e.nativeEvent.keyCode }, e.timeStamp))
667                return;
668            // The command menu owns the keyboard while it is open.
669            if (slashQuery !== null && e.key === 'Escape') {
670                e.preventDefault();
671                e.stopPropagation();
672                setSlashOpen(false);
673                setSlashDismissed(true);
674                return;
675            }
676            if (slashQuery !== null && matches.length) {
677                if (e.key === 'ArrowDown') {
678                    e.preventDefault();
679                    setCursor((c) => (c + 1) % matches.length);
680                    return;
681                }
682                if (e.key === 'ArrowUp') {
683                    e.preventDefault();
684                    setCursor((c) => (c - 1 + matches.length) % matches.length);
685                    return;
686                }
687                if (e.key === 'Enter' || e.key === 'Tab') {
688                    e.preventDefault();
689                    setSlashOpen(false);
690                    setSlashDismissed(true);
691                    matches[cursor].run();
692                    return;
693                }
694            }
695            onKey(e);
696            if (composerSends(e)) {
697                e.preventDefault();
698                onSubmit();
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
711                material blurs an already-blurred backdrop, which Liquid Glass
712                prohibits and which doubles the compositor cost for a muddier result.
713                The 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) => {
716                setSlashOpen(false);
717                setSlashDismissed(true);
718                c.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, }: {
725    message: ChatMessage;
726    isLast: boolean;
727    onEditPrompt: (text: string) => void;
728    onPreview: (a: PreviewArtifact) => void;
729    onClosePreview: (id: string) => void;
730    onOpenLink: (url: string) => void;
731    onOpenTimeSkip: (id: string) => void;
732    timeSkipDone: boolean;
733    timeSkipReal?: boolean;
734    timeSkipRun?: TimeSkipRun;
735}) {
736    const streaming = useStore(s => s.streaming);
737    const activeSession = useStore(s => s.activeSession);
738    const hostLive = useStore(s => s.connection !== 'offline');
739    const 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).
741    const storedPlan = usePlanQuiet(m.planId ? activeSession : null);
742    const 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.
744    const grouped = !!m.blocks?.some(b => b.kind === 'group');
745    const [sentTime, setSentTime] = useState(() => relTime(m.at));
746    const sentQuote = m.role === 'user' ? parseQuoted(m.content) : null;
747    if (m.role === 'user') {
748        return (<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={() => {
755                const prompt = rewindTo(m.id);
756                if (prompt !== null)
757                    onEditPrompt(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    }
764    return (<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
769          card 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[] }) {
813    const [open, setOpen] = useState(false);
814    return <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 }: {
817    label: string;
818    children: React.ReactNode;
819}) {
820    const [open, setOpen] = useState(false);
821    const trigger = useRef<HTMLButtonElement>(null);
822    return <><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 }: {
829    tool: ToolCall;
830}) {
831    const scope = SCOPE[t.scope];
832    const pending = t.state === 'proposed';
833    if (!pending && t.state !== 'running')
834        return <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). */
836    if (pending)
837        return <p className="approval-wait small muted" role="status"><Icon name="clock" size={14}/>{tr("Waiting for your answer below")}</p>;
838    return <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 };