/** An agent task as an editor tab: the conversation, a composer and the task's changed files. */ import { createContext, Fragment, memo, startTransition, useCallback, useContext, useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type ReactElement, type ReactNode, type RefObject, } from "react"; import clsx from "clsx"; import { useShallow } from "zustand/react/shallow"; import type { AgentChange, AgentCommit, AgentEntry, AgentImage, AgentLimit, AgentQuestion, AgentRetry, AgentTask, AgentUsage, } from "@/bindings"; import { executeAction } from "@/platform/actions"; import { call, commands, onIdeEvent } from "@/platform/ipc"; import { isSameOrInside } from "@/platform/paths"; import { basename, relativeDir, useProject } from "@/platform/project"; import { notifications, useEditorShown, type EditorInput } from "@/workbench/contributions"; import { confirm } from "@/workbench/messages"; import { Button, Checkbox, Chip, EmptyState, Icon, IconButton, Input, Radio, SearchField, Spinner, T, Tabs, Tree, copyMenuFor, copyText, fileIconName, selectableText, useSelectionBoundary, showContextMenu, type IconName, } from "@/ui"; import { useTx, tx } from "@/platform/i18n"; import { isImeKey } from "@/platform/ime"; import { commitFileDiffData, openDiff, withChain, type DiffData } from "@/features/vcs/diffInput"; import { repositoryPath } from "@/features/vcs/repositoryPaths"; import { setChangesOptions, useChangesOptions } from "./changesOptions"; import { ChangesResizer, useChangesWidthStyle } from "./ChangesResizer"; import { Composer } from "./Composer"; import { ReferencedText } from "./ReferenceChip"; import { selectionIn } from "./selection"; import { SelectionToolbar } from "./SelectionToolbar"; import { SubmitButton } from "./SubmitButton"; import { canSend, costLabel, emptyDraft, limitLabel, messageTokens, parseMention, retryParts, usageLabel, workTime, } from "./composerModel"; import { ConfigPickers } from "./ConfigPickers"; import { useEffortFocus } from "./effortFocus"; import { useAgentFontZoomSurface } from "./fontZoom"; import { findRanges, formatDuration, formatSentAt, isFindRangeShown } from "./conversation"; import { ImagePreview, imageSrc } from "./ImagePreview"; import { useAgentSettings } from "./agentSettings"; import { foldedTurns, summarizeWork, workParts, type FoldedTurn, type WorkSummary } from "./timeline"; import { useRevealedText } from "./reveal"; import { ACTIVITY_STATUS, PLAYFUL_MIN_MS, PLAYFUL_WORD_MS, PLAYFUL_WORDS, activityOf, playfulIndex, progressKey, type Activity, } from "./workingStatus"; import { AgentReply, MessageActions, ReplyActions } from "./AgentReply"; import { FormCard } from "./FormCard"; import { asksInCard, commandPrefix, permissionDetails, permissionOption, permissionResult, type PermissionEntry, } from "./permission"; import { Markdown } from "./Markdown"; import { useAgentErrorText } from "./loginHint"; import { branchLabel, entriesKey, findSubagent, hasTaskTerminal, isBusy, providerIcon, sessionKey, statusLabel, subagentStatusLabel, subagentTitle, subagentWorking, turnNumbers, replyTurns, replyTimes, type ReplyTimes, type ReplyTurn, type SubagentEntry, } from "./model"; import { acceptChanges, cancelTask, stopBackgroundTask, loadEntries, markVisible, refreshChanges, rollbackChanges, scheduleChanges, discardEphemeral, editQueued, forkTask, rerunFrom, removeQueued, resendMessage, respond, sendMessage, sendQueuedNow, setTaskConfig, useAgentCommands, useAgents, } from "./store"; import { setFocusedSession, focusedSession, type FocusedSession } from "./sessionFocus"; import { taskMenu } from "./taskActions"; import styles from "./Session.module.css"; export function SessionEditor({ input, docked = false }: { input: EditorInput; docked?: boolean }) { const id = (input.data as { task: string }).task; return ; } function TaskSession({ id, docked }: { id: string; docked: boolean }) { const task = useAgents((s) => s.tasks.get(id)); const entries = useAgents((s) => s.entries.get(id)); // Grouping needs commits of the task's own: local checkouts keep the flat list. const isolation = useAgents((s) => s.tasks.get(id)?.isolation); const ephemeral = useAgents((s) => s.ephemeral.has(id)); const grouped = useChangesOptions((s) => s.groupByCommit) && isolation === "worktree"; const sinceStart = useAgents((s) => s.changes.get(id)); const review = useAgents((s) => s.groupedChanges.get(id)); const changes = grouped ? (review?.uncommitted ?? null) : (sinceStart ?? null); const commits = grouped ? (review?.commits ?? []) : []; const project = useProject((s) => s.project); const head = useLocalHead( task?.isolation === "local" ? task.status : null, project?.workspace ? (task?.projectRoot ?? project.root) : null, ); const [changesOpen, setChangesOpen] = useChangesOpen(id, changes ?? null, docked); const changesWidth = useChangesWidthStyle(); // The subagent conversation shown, with the subagents that lead to it (empty: the task's own). const [path, setPath] = useState([]); const view = path.at(-1) ?? null; const viewEntries = useAgents((s) => s.entries.get(entriesKey(id, view))); const loadError = useAgents((s) => s.entryLoads.get(entriesKey(id, view))?.error); // Each subagent's card, from its parent's conversation. const cards = useAgents( useShallow((s) => path.map((sub, i) => findSubagent(s.entries.get(entriesKey(id, path[i - 1] ?? null)), sub))), ); // Connecting to the project's agents clears what was loaded before: a tab restored with the // project reads its conversation once that is done, not before (#2414). const connected = useAgents((s) => s.loaded); useEffect(() => { if (!connected) return; // Loaded entries are kept current by the task's events: reopening the tab needn't fetch them again. if (!useAgents.getState().entries.has(id)) void loadEntries(id).catch(() => undefined); void refreshChanges(id); }, [id, connected]); // A commit in the task's checkout moves its HEAD: pick it up without waiting for the agent. // The watcher reports every repository under the project, so the main checkout and other // tasks' worktrees would otherwise re-read this task's changes for nothing. A worktree's // gitdir is `/.git/worktrees/`, outside the worktree itself: the watcher only // reports the project there, so that is the root its events match. const refreshRoot = task?.isolation === "worktree" ? (task.projectRoot ?? project?.root ?? null) : (task?.cwd ?? null); useEffect(() => { if (!connected) return; return onIdeEvent("vcsChanged", (e) => { if (!refreshRoot || !isSameOrInside(refreshRoot, e.root)) return; scheduleChanges(id); }); }, [id, connected, refreshRoot]); // A kept-alive tab stays mounted behind the shown one: it isn't read there, nor searched. const shown = useEditorShown(); useEffect(() => { if (shown && (!docked || !changesOpen)) return markVisible(id); }, [id, docked, changesOpen, shown]); useEffect(() => { if (connected && view && !useAgents.getState().entries.has(entriesKey(id, view))) { void loadEntries(id, view).catch(() => undefined); } }, [id, view, connected]); const openSubagent = useCallback((sub: string) => setPath((p) => [...p, sub]), []); const [finding, setFinding] = useState(false); const [findFocus, setFindFocus] = useState(0); const [inputFocus, setInputFocus] = useState(0); const { fitWindowWidth } = useAgentSettings(); const sessionRoot = useRef(null); const { fontZoom, zoomStyle } = useAgentFontZoomSurface(sessionRoot, sessionKey(id), docked, !!task); const canFocusInput = shown && !!task && task.status !== "archived" && !view; const session = useMemo( () => ({ openFind: () => { setFinding(true); setFindFocus((n) => n + 1); }, focusInput: canFocusInput ? () => { if (docked) setChangesOpen(false); setInputFocus((n) => n + 1); } : undefined, }), [canFocusInput, docked, setChangesOpen], ); useLayoutEffect(() => { if (shown && sessionRoot.current?.contains(document.activeElement)) setFocusedSession(session); return () => { if (focusedSession() === session) setFocusedSession(null); }; }, [session, shown]); if (!task) return ; return (
shown && setFocusedSession(session)} onBlurCapture={(e) => { if (!e.currentTarget.contains(e.relatedTarget as Node | null) && focusedSession() === session) { setFocusedSession(null); } }} > {ephemeral && (
Side conversation Temporary and read-only: closing it discards the conversation and its context. void discardEphemeral(id).catch(() => undefined)} />
)} {changesOpen && ( setChangesOpen(false)} /> )}
); } function providerName(id: string) { return useAgents.getState().providers.find((p) => p.id === id)?.name ?? id; } /** * Current branch of the project's repository for a local-checkout task (`status` is * `null` otherwise); followed as git changes, since the agent or the user may switch it. */ function useLocalHead(status: AgentTask["status"] | null, root: string | null): string | null { const [head, setHead] = useState(null); const local = status !== null; useEffect(() => { if (!local) return; let live = true; const load = () => void call(commands.vcsBranchInfo(root)).then( (b) => live && setHead(b.head ?? b.headCommit?.slice(0, 8) ?? null), () => live && setHead(null), ); load(); const off = onIdeEvent("vcsChanged", load); return () => { live = false; off(); }; }, [local, status, root]); return local ? head : null; } /** The task's terminal, at the end of its status line. */ function StatusActions({ task }: { task: AgentTask }) { return ( void executeAction("terminal.openAt", task.cwd)} /> ); } /** The task's agent, model, checkout and state, just above the composer. */ function SessionStatus({ task, entries, head, changes, commits, changesOpen, effortAnnouncement, onToggleChanges, }: { task: AgentTask; entries: AgentEntry[] | null; head: string | null; changes: AgentChange[] | null; commits: readonly AgentCommit[]; changesOpen: boolean; effortAnnouncement: string | null; onToggleChanges: () => void; }) { const tx = useTx(); const project = useProject((s) => s.project); const projectRoot = task.projectRoot ?? project?.root ?? null; const projectName = project?.workspace && projectRoot ? basename(projectRoot) : project?.name; const local = task.isolation !== "worktree"; const branch = local ? head : branchLabel(task.branch) || null; const pickedModel = task.status !== "archived" && task.config.some((o) => o.category === "model"); const added = changes?.reduce((n, c) => n + c.added, 0) ?? 0; const removed = changes?.reduce((n, c) => n + c.removed, 0) ?? 0; return (
{ e.preventDefault(); showContextMenu(e, taskMenu([task])); }} > {providerName(task.provider)} {/* The composer's model picker shows the model when the agent offers one. */} {task.model && !pickedModel ? ` · ${task.model}` : ""} {/* The same three facts as the new-task composer: project, checkout, branch. */} {projectName && ( {projectName} )} {local ? "Local checkout" : "New worktree"} {branch && ( <> {local && ( on )} {branch} )} {statusLabel(task.status)} {task.status === "limited" && task.resetsMs != null && ` · ${tx`resets ${formatSentAt(task.resetsMs)}`}`} {effortAnnouncement ? tx("Effort: {level}").replace("{level}", effortAnnouncement) : ""} {/* What changed sits before the meter, time and terminal, or above them when the row is full. */} {(!!changes?.length || !!commits.length) && ( {!!changes?.length && ( )} {!!commits.length && ( )} )} {hasTaskTerminal(task, projectRoot) && }
); } /** * Context use, usage limits and cost (when the agent reports them) and the time spent on * the task, each as Settings › Agents › Chat allows. */ function Meters({ task, entries }: { task: AgentTask; entries: AgentEntry[] | null }) { const tx = useTx(); const show = useProject((s) => s.settings?.agents); const busy = isBusy(task.status); const now = useNow(busy ? 1000 : 60_000); const usage = show?.showContextUsage !== false ? task.usage : null; const reported = useAgents((s) => s.limits.get(task.provider)); const limits = show?.showUsageLimits !== false ? (reported ?? []) : []; const cost = show?.showCost === true ? task.usage?.cost : null; const work = show?.showWorkTime !== false && entries ? workTime(entries, busy ? now : null) : 0; return ( {usage && } {limits.map((l) => ( ))} {cost && {costLabel(cost)}} {work >= 1000 && {formatDuration(work)}} ); } /** A usage-limit window: "5h 19%", when it resets in the tooltip. */ function Limit({ limit, now }: { limit: AgentLimit; now: number }) { const label = limitLabel(limit, now); return ( {label.short} ); } /** Context window use: "167k/1M (17%)", the exact counts in the tooltip. */ function Usage({ usage }: { usage: AgentUsage }) { const label = usageLabel(usage); return ( {label.short} ); } /** `Date.now()`, updated every `interval` ms. */ function useNow(interval: number): number { const [now, setNow] = useState(() => Date.now()); useEffect(() => { const t = setInterval(() => setNow(Date.now()), interval); return () => clearInterval(t); }, [interval]); return now; } /** Where a subagent conversation sits: the way back to the task, and the subagent's state. */ function SubagentBar({ task, path, cards, onNavigate, }: { task: AgentTask; path: string[]; cards: Array; onNavigate: (path: string[]) => void; }) { const tx = useTx(); const card = cards.at(-1); return (
onNavigate(path.slice(0, -1))} /> {card && ( {subagentStatusLabel(card.status)} )} {card && subagentWorking(card.status) && card.cancellable && ( void cancelTask(task.id, card.id)} /> )}
); } /** * Lets the rows of a long conversation skip rendering while off screen (`data-measured`, see * the CSS), so showing the tab again or restyling it costs what is on screen, not the whole * history. A row skips only once it was laid out: it keeps its real height, and scrolling up * doesn't jump (WebKit has no scroll anchoring). A new width lays them out again once it * settles; Find in Conversation (`enabled` false) needs every row laid out. */ function useOffscreenRows( ref: RefObject, visible: boolean, enabled: boolean, fitWindowWidth: boolean, fontZoom: number, ) { // The container width, column mode and font zoom the marked rows were laid out at. const measured = useRef<{ width: number; fitWindowWidth: boolean; fontZoom: number } | null>(null); useLayoutEffect(() => { const el = ref.current; if (!el) return; const unmark = () => { for (const row of el.querySelectorAll(`:scope > .${styles.conversationRow}[data-measured]`)) { row.removeAttribute("data-measured"); } }; if (!enabled) { measured.current = null; unmark(); return; } if (!visible) return; if ( measured.current?.width === el.clientWidth && measured.current.fitWindowWidth === fitWindowWidth && measured.current.fontZoom === fontZoom ) return; measured.current = { width: el.clientWidth, fitWindowWidth, fontZoom }; unmark(); }, [ref, visible, enabled, fitWindowWidth, fontZoom]); useEffect(() => { const el = ref.current; if (!el || !enabled || !visible) return; let frame = 0; let timer: number | undefined; const unmark = () => { for (const row of el.querySelectorAll(`:scope > .${styles.conversationRow}[data-measured]`)) { row.removeAttribute("data-measured"); } }; const mark = () => { cancelAnimationFrame(frame); // The next frame lays the new rows out (and remembers their size); mark them after it. frame = requestAnimationFrame(() => { frame = requestAnimationFrame(() => { for (const row of el.querySelectorAll(`:scope > .${styles.conversationRow}:not([data-measured])`)) { row.setAttribute("data-measured", ""); } }); }); }; const remeasure = () => { if ( measured.current?.width === el.clientWidth && measured.current.fitWindowWidth === fitWindowWidth && measured.current.fontZoom === fontZoom ) return; measured.current = { width: el.clientWidth, fitWindowWidth, fontZoom }; unmark(); }; remeasure(); mark(); const rows = new MutationObserver(mark); rows.observe(el, { childList: true }); const resize = new ResizeObserver(() => { window.clearTimeout(timer); timer = window.setTimeout(() => { remeasure(); mark(); }, 200); }); resize.observe(el); return () => { cancelAnimationFrame(frame); window.clearTimeout(timer); rows.disconnect(); resize.disconnect(); }; }, [ref, visible, enabled, fitWindowWidth, fontZoom]); } interface StreamProps { task: AgentTask; entries: AgentEntry[] | null; loadError?: string | null; /** The card of the subagent whose conversation this is; `null`: the task's own. */ subagent: SubagentEntry | null; onOpenSubagent: (id: string) => void; finding: boolean; /** Bumped by Find in Conversation: focus the find field again. */ findFocus: number; fontZoom: number; onCloseFind: () => void; } /** Entries rendered at a time when a conversation opens at its end. */ const ENTRY_BATCH = 40; function scrollsInside(target: EventTarget | null, root: HTMLElement): boolean { for (let el = target instanceof Element ? target : null; el && el !== root; el = el.parentElement) { if (el.scrollTop <= 0) continue; const overflow = getComputedStyle(el).overflowY; if (overflow === "auto" || overflow === "scroll") return true; } return false; } function Stream({ loadError, task, entries, subagent, onOpenSubagent, finding, findFocus, fontZoom, onCloseFind, }: StreamProps) { const ref = useRef(null); useSelectionBoundary(ref); const [openFolds] = useState(() => new Map()); const key = entriesKey(task.id, subagent?.id ?? null); const positions = useAgents.getState().scrollPositions; const position = useRef(positions.get(key) ?? { top: 0, stick: true }); const restored = useRef(false); const previousLength = useRef(entries?.length ?? 0); /** Scrolled away from the end: offer one click back to the latest message. */ const [away, setAway] = useState(() => positions.get(key)?.stick === false); // Opened at the end, the last entries come first and the earlier ones follow in batches: // reopening a long conversation paints at once. A kept offset needs them all. const [shown, setShown] = useState(() => (positions.get(key)?.stick === false ? Infinity : ENTRY_BATCH)); let start = finding || !entries ? 0 : Math.max(0, entries.length - shown); // Keep a process run intact so prepending never replaces the anchored row. while (entries && start > 0 && isProcessEntry(entries[start]!) && isProcessEntry(entries[start - 1]!)) start--; const dragging = useRef(false); // When the user last scrolled the conversation (wheel, touch, keys, the scrollbar, Find): // that leaves the end. WebKit also moves the offset back on its own while rows lay out, // which comes with a change of the content height, and pulls it back to the end when the view // grows taller (the composer shrinks after a send); a scroll without either is meant too (the // scrollbar thumb, a jump), whatever moved it. const userScrolled = useRef(-Infinity); const seenHeight = useRef({ content: 0, view: 0 }); const markUserScroll = useCallback(() => { userScrolled.current = performance.now(); }, []); const touchY = useRef(null); const scrollingUp = useRef(false); // Release before the browser scrolls: a streamed chunk can arrive before its scroll event. const stopFollowing = useCallback( (target: EventTarget | null) => { const el = ref.current; if (!el || el.scrollHeight <= el.clientHeight || scrollsInside(target, el)) return; scrollingUp.current = true; if (!position.current.stick) return; position.current = { top: el.scrollTop, stick: false }; positions.set(key, position.current); setAway(true); }, [key, positions], ); // Earlier entries are prepended above the view: remember where the first painted row is // so the content stays put and the scrollbar doesn't jump under the pointer. const anchor = useRef<{ el: Element; top: number } | null>(null); const loadEarlier = useCallback(() => { const el = ref.current; if (!el || start <= 0 || dragging.current || anchor.current) return; const first = el.firstElementChild; if (!position.current.stick && first) anchor.current = { el: first, top: first.getBoundingClientRect().top }; startTransition(() => setShown((n) => n + ENTRY_BATCH)); }, [start]); const loadTimer = useRef(null); /** Load the next batch once the user stops scrolling near the top. */ const loadWhenStill = useCallback(() => { if (loadTimer.current !== null) window.clearTimeout(loadTimer.current); loadTimer.current = window.setTimeout(() => { loadTimer.current = null; loadEarlier(); }, 120); }, [loadEarlier]); useEffect(() => { const down = (event: PointerEvent) => { if (!ref.current?.contains(event.target as Node)) return; dragging.current = true; if (loadTimer.current !== null) window.clearTimeout(loadTimer.current); }; const up = () => { if (!dragging.current) return; dragging.current = false; if (ref.current && (position.current.stick || ref.current.scrollTop < 120)) loadWhenStill(); }; window.addEventListener("pointerdown", down, true); window.addEventListener("pointerup", up, true); window.addEventListener("pointercancel", up, true); window.addEventListener("blur", up); return () => { window.removeEventListener("pointerdown", down, true); window.removeEventListener("pointerup", up, true); window.removeEventListener("pointercancel", up, true); window.removeEventListener("blur", up); if (loadTimer.current !== null) window.clearTimeout(loadTimer.current); }; }, [loadWhenStill]); useEffect(() => { // Following the end, paint the rest in the background. A user who scrolled away // gets them only after stopping near the top (`loadWhenStill`), so the scrollbar // is not resized mid-drag. if (start > 0 && position.current.stick && !dragging.current) startTransition(() => setShown((n) => n + ENTRY_BATCH)); }, [start]); // Hidden behind another tab, it has no layout to scroll; shown again, it follows the end again. const visible = useEditorShown(); const { foldTurns, toolCalls, fitWindowWidth } = useAgentSettings(); useOffscreenRows(ref, visible, !finding, fitWindowWidth, fontZoom); /** A diagram that drew after the last streamed chunk grows the conversation: keep following. */ const onDiagramDrawn = useCallback(() => { const el = ref.current; if (el && position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight; }, []); useLayoutEffect(() => { const el = ref.current; if (!el || entries === null || !visible) return; const truncated = entries.length < previousLength.current; // A message the user just sent: back to the end, where it shows, wherever they had scrolled. const sent = previousLength.current > 0 && entries.slice(previousLength.current).some((e) => e.type === "user"); previousLength.current = entries.length; if (sent && !position.current.stick) { scrollingUp.current = false; position.current = { top: el.scrollTop, stick: true }; positions.set(key, position.current); setAway(false); return; } if ((truncated || entries.length === 0) && el.scrollHeight - el.scrollTop - el.clientHeight < 40) { scrollingUp.current = false; position.current = { top: el.scrollTop, stick: true }; positions.set(key, position.current); setAway(false); } }, [entries, visible, key, positions]); useLayoutEffect(() => { const el = ref.current; if (!el || entries === null || !visible) return; if (position.current.stick) { if (!dragging.current) el.scrollTop = el.scrollHeight; } else if (!restored.current) el.scrollTop = position.current.top; restored.current = true; }); useLayoutEffect(() => { // Prepending earlier entries moved the first painted row down: follow it, so the same // text stays on screen. Rows appended below leave it in place and shift nothing. const scroller = ref.current; const from = anchor.current; if (!scroller || !from) return; anchor.current = null; if (position.current.stick || !from.el.isConnected) return; scroller.scrollTop += from.el.getBoundingClientRect().top - from.top; }); useLayoutEffect(() => { const el = ref.current; if (!el) return; const observer = new ResizeObserver(() => { if (position.current.stick && !dragging.current) el.scrollTop = el.scrollHeight; }); observer.observe(el); return () => { observer.disconnect(); if (restored.current) positions.set(key, { ...position.current, top: el.scrollTop }); }; }, [key, positions]); // How far the end was below the view when a section was toggled, before its content renders. const gapAtToggle = useRef(Infinity); useEffect(() => { const el = ref.current; if (!el) return; const toggled = () => { gapAtToggle.current = el.scrollHeight - el.scrollTop - el.clientHeight; }; el.addEventListener("toggle", toggled, true); return () => el.removeEventListener("toggle", toggled, true); }, []); /** * An opened section grew the conversation below its header: with the end in view, stay at * it; otherwise bring what it shows into view. Either way its header stays on screen, and * following stops when that leaves the end out of view. */ const revealFold = useCallback( (fold: HTMLElement) => { const el = ref.current; if (!el || dragging.current) return; const view = el.getBoundingClientRect(); const box = fold.getBoundingClientRect(); const atEnd = position.current.stick || gapAtToggle.current < 40; gapAtToggle.current = Infinity; const below = atEnd ? el.scrollHeight - el.scrollTop - el.clientHeight : box.bottom - view.bottom; if (below > 0) el.scrollTop += Math.max(0, Math.min(below, box.top - view.top)); if (atEnd && el.scrollHeight - el.scrollTop - el.clientHeight >= 40) { position.current = { top: el.scrollTop, stick: false }; positions.set(key, position.current); setAway(true); } }, [key, positions], ); /** Back to the end of the stream; following resumes from there. */ const jumpToLatest = useCallback(() => { const el = ref.current; if (!el) return; scrollingUp.current = false; position.current = { top: el.scrollTop, stick: true }; if (typeof el.scrollTo === "function") el.scrollTo({ top: el.scrollHeight, behavior: "smooth" }); else el.scrollTop = el.scrollHeight; setAway(false); el.focus({ preventScroll: true }); }, []); // Forks and undo apply to the task's own turns, not a subagent's conversation. const turns = useMemo(() => (entries && !subagent ? turnNumbers(entries) : null), [entries, subagent]); const replies = useMemo(() => (entries && !subagent ? replyTurns(entries) : null), [entries, subagent]); const times = useMemo(() => (entries && !subagent ? replyTimes(entries) : null), [entries, subagent]); const busy = subagent ? subagentWorking(subagent.status) : isBusy(task.status); const lastIndex = entries ? entries.length - 1 : -1; // Keep the row stable when earlier history is prepended; its author can move with the work. const rows = useMemo(() => { if (!entries) return []; const rows = conversationRows(entries, start, toolCalls === "grouped"); return foldTurns && !finding ? foldTurnRows(rows, foldedTurns(entries, start, busy)) : rows; }, [entries, start, busy, foldTurns, toolCalls, finding]); const authorHeaders = useMemo(() => { const headers = new Set(); const byAgent = (row: ConversationRow) => row.kind !== "entry" || (row.entry.type !== "user" && row.entry.type !== "subagent" && !(row.entry.type === "message" && row.entry.incoming)); rows.forEach((row, i) => { const previous = rows[i - 1]; if (byAgent(row) && (!previous || !byAgent(previous))) headers.add(row.index); }); return headers; }, [rows]); const renderRow = useCallback( (row: EntryRow) => ( ), [task, turns, replies, times, lastIndex, busy, onOpenSubagent, onDiagramDrawn], ); const renderConversationRow = (row: ConversationRow): ReactNode => row.kind === "turn" ? ( {row.rows.map((inner) => (
{renderConversationRow(inner)}
))}
) : row.kind === "process" ? ( ) : ( renderRow(row) ); return (
{finding && }
{ if (e.defaultPrevented) return; markUserScroll(); if (e.deltaY < 0 && !e.ctrlKey && !e.metaKey) stopFollowing(e.target); else if (e.deltaY > 0 && !e.ctrlKey && !e.metaKey) scrollingUp.current = false; }} onTouchStart={(e) => { touchY.current = e.touches.length === 1 ? e.touches[0]!.clientY : null; }} onTouchMove={(e) => { markUserScroll(); const y = e.touches.length === 1 ? e.touches[0]!.clientY : null; if (y !== null && touchY.current !== null && y > touchY.current) stopFollowing(e.target); else if (y !== null && touchY.current !== null && y < touchY.current) scrollingUp.current = false; touchY.current = y; }} onKeyDown={(e) => { markUserScroll(); if (e.defaultPrevented || (e.target as Element).closest("input, textarea, [contenteditable]")) return; if (e.key === "ArrowUp" || e.key === "PageUp" || e.key === "Home" || (e.key === " " && e.shiftKey)) stopFollowing(e.target); else if ( e.key === "ArrowDown" || e.key === "PageDown" || e.key === "End" || (e.key === " " && !e.shiftKey) ) scrollingUp.current = false; }} onPointerDown={() => { markUserScroll(); scrollingUp.current = false; }} onScroll={(e) => { const el = e.currentTarget; const atEnd = el.scrollHeight - el.scrollTop - el.clientHeight < 40; const laidOut = el.scrollHeight !== seenHeight.current.content || el.clientHeight !== seenHeight.current.view; seenHeight.current = { content: el.scrollHeight, view: el.clientHeight, }; const byUser = dragging.current || performance.now() - userScrolled.current < 500 || !laidOut; const movedDown = el.scrollTop > position.current.top; const stayedAtEnd = position.current.stick && el.scrollTop === position.current.top; const stick = (atEnd && !scrollingUp.current && (movedDown || stayedAtEnd)) || (position.current.stick && !byUser); // Still following: back to the end the offset was moved away from. if (stick && !atEnd && !dragging.current) el.scrollTop = el.scrollHeight; position.current = { top: el.scrollTop, stick }; positions.set(key, position.current); setAway(!position.current.stick); // Reached the top of what is painted: fetch the earlier entries, but only // once the drag has settled. if (loadTimer.current !== null) window.clearTimeout(loadTimer.current); if (!position.current.stick && el.scrollTop < 120 && !dragging.current) loadWhenStill(); }} // Copy, plus Quote for a selection: replies to it in the composer. onContextMenu={(e) => { const text = selectionIn(e.currentTarget); const items = copyMenuFor(e.target) ?? []; if (text.trim() && task.status !== "archived") { items.push({ kind: "action", action: "agents.quoteReply", label: "Quote", arg: { task: task.id, text }, }); } if (!items.length) return; e.preventDefault(); showContextMenu(e, items); }} > {loadError && (
void executeAction("agents.retryConversation", { task: task.id, subagent: subagent?.id ?? null, }) } > Retry } />
)} {entries === null ? ( !loadError && ) : entries.length === 0 && !busy && !loadError ? ( ) : ( rows.map((row) => (
{authorHeaders.has(row.index) && (
{providerName(task.provider)}
)} {renderConversationRow(row)}
)) )}
{away && !!entries?.length && }
); } type UserEntry = Extract; /** When a message was sent, or when the turn behind a reply finished, and how long it took. */ function MessageTime({ sentMs, doneMs, at = "sent", }: { sentMs: number | null; doneMs: number | null; /** Replies show when they finished; messages show when they were sent. */ at?: "sent" | "done"; }) { const shown = at === "done" ? doneMs : sentMs; if (shown == null) return null; return ( {formatSentAt(shown)} {sentMs != null && doneMs != null && ` · ${formatDuration(Math.max(0, doneMs - sentMs))}`} ); } /** One click back to the stream's end. */ function JumpToLatest({ onJump }: { onJump: () => void }) { return ( ); } /** The agent lost its API connection (or was refused) and retries on its own. */ function Retrying({ retry }: { retry: AgentRetry }) { const tx = useTx(); const now = useNow(1000); const { attempt, wait } = retryParts(retry, now); return ( {wait > 0 ? tx`API request failed, retrying in ${wait}s (attempt ${attempt})` : tx`API request failed, retrying (attempt ${attempt})`} ); } function Elapsed({ since }: { since: number }) { const now = useNow(1000); return {formatDuration(now - since)}; } interface RangeSet { clear(): void; add(range: Range): void; } function setHighlight(name: string, ranges: Range[]) { const highlights = (globalThis as { CSS?: { highlights?: Map } }).CSS?.highlights; const HighlightCtor = (globalThis as { Highlight?: new () => RangeSet }).Highlight; if (!highlights || !HighlightCtor) return; let set = highlights.get(name); if (!set) { set = new HighlightCtor(); highlights.set(name, set); } set.clear(); for (const r of ranges) set.add(r); } /** Scrolls `range` into view in `stream`, opening the collapsed tool output or thought holding it. */ function revealRange(range: Range, stream: HTMLElement) { for (let el = range.startContainer.parentElement; el && el !== stream; el = el.parentElement) { if (el instanceof HTMLDetailsElement) el.open = true; } const r = range.getBoundingClientRect(); const box = stream.getBoundingClientRect(); if (r.top < box.top + 24 || r.bottom > box.bottom - 24) { stream.scrollTop += r.top - box.top - box.height / 3; } } /** Find in Conversation: every match highlighted, Enter / ⇧Enter step through them. */ function FindBar({ streamRef, focus, onClose, }: { streamRef: RefObject; focus: number; onClose: () => void; }) { const tx = useTx(); const input = useRef(null); const [query, setQuery] = useState(""); const [ranges, setRanges] = useState([]); const [current, setCurrent] = useState(0); useEffect(() => { input.current?.focus(); input.current?.select(); }, [focus]); // Matches follow the conversation as it streams in (and as code gets highlighted). useEffect(() => { const stream = streamRef.current; if (!stream) return; let frame = 0; const update = () => { cancelAnimationFrame(frame); frame = requestAnimationFrame(() => setRanges(findRanges(stream, query.trim()))); }; update(); const observer = new MutationObserver(update); observer.observe(stream, { subtree: true, childList: true, characterData: true, }); return () => { cancelAnimationFrame(frame); observer.disconnect(); }; }, [query, streamRef]); const index = ranges.length ? Math.min(current, ranges.length - 1) : -1; // Expanding or collapsing a tool output shows or hides its matches. const [shown, setShown] = useState(0); useEffect(() => { const stream = streamRef.current; const toggled = () => setShown((n) => n + 1); stream?.addEventListener("toggle", toggled, true); return () => stream?.removeEventListener("toggle", toggled, true); }, [streamRef]); useEffect(() => { const stream = streamRef.current; if (!stream) return; // Only rendered selectable matches outside closed
: WebKit paints unrendered // or user-select:none ranges in CSS.highlights over the next selectable row instead. const visible = (r: Range) => isFindRangeShown(r, stream); const current = index >= 0 ? ranges[index]! : null; setHighlight("agent-find", ranges.filter(visible)); setHighlight("agent-find-current", current && visible(current) ? [current] : []); }, [ranges, index, shown, streamRef]); useEffect( () => () => { setHighlight("agent-find", []); setHighlight("agent-find-current", []); }, [], ); const step = (dir: 1 | -1) => { const stream = streamRef.current; if (!ranges.length || !stream) return; const next = (index + dir + ranges.length) % ranges.length; setCurrent(next); revealRange(ranges[next]!, stream); }; const close = () => { onClose(); streamRef.current?.focus(); }; return (
{ setQuery(v); setCurrent(0); }} aria-label={tx("Find in Conversation")} placeholder={tx("Find in conversation")} className={styles.findField} trailing={ query.trim() ? ( {ranges.length ? `${index + 1}/${ranges.length}` : tx("0 results")} ) : null } onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); step(e.shiftKey ? -1 : 1); } else if (e.key === "Escape") { e.preventDefault(); e.stopPropagation(); close(); } }} /> step(-1)} /> step(1)} />
); } const TOOL_ICONS: Record = { read: "file", edit: "edit", delete: "minus", move: "edit", search: "search", execute: "terminal", fetch: "web", think: "todo", }; /** Memoized: the earlier entries rendered behind a reopened conversation leave the rest alone. */ function AgentMessage({ task, text, turnCount, reply, time, working, onDiagramDrawn, }: { task: AgentTask; text: string; turnCount: number; reply?: ReplyTurn; time?: ReplyTimes | null; /** The reply streams: its text is revealed at a pace. */ working: boolean; onDiagramDrawn: () => void; }) { const { smoothText } = useAgentSettings(); const shown = useRevealedText(text, working && smoothText); // The revealed text grows the conversation between its renders: keep following the end. useLayoutEffect(() => { if (working) onDiagramDrawn(); }, [shown, working, onDiagramDrawn]); return (
{/* Only a turn's final reply carries its time and actions, once the turn has ended. */} {reply && !(isBusy(task.status) && reply.turn === turnCount - 1) && (
)}
); } /** The first line of reasoning, without its Markdown emphasis: what a folded thought was about. */ export function thoughtPreview(text: string): string { const line = text.split("\n").find((l) => l.trim()) ?? ""; return line .replace(/^\s*(#+\s*|[-*]\s+)?/, "") .replace(/[*_`]+/g, "") .trim(); } /** The agent's reasoning: open while it streams, folded after, as Settings › Agents › Chat says. */ function ThoughtEntry({ task, text, working, onDiagramDrawn, }: { task: AgentTask; text: string; working: boolean; onDiagramDrawn: () => void; }) { const { thinking, smoothText } = useAgentSettings(); const open = thinking === "expanded" || (thinking === "auto" && working); // Streaming reasoning in view is revealed at the reply's pace; folded, nothing is painted. const shown = useRevealedText(text, working && smoothText && open); useLayoutEffect(() => { if (working && open) onDiagramDrawn(); }, [shown, working, open, onDiagramDrawn]); return (
{working ? ( Thinking ) : ( {thoughtPreview(text) || Reasoning} )} } >
); } const Entry = memo(function Entry({ task, entry, turn, turnCount, reply, time, working, onOpenSubagent, onDiagramDrawn, }: { task: AgentTask; entry: AgentEntry; /** Number of the turn this message started (from 0), when it started one. */ turn: number | null; turnCount: number; reply?: ReplyTurn; /** When the turn this reply answered was asked and finished. */ time?: ReplyTimes | null; working: boolean; onOpenSubagent: (id: string) => void; onDiagramDrawn: () => void; }) { switch (entry.type) { case "user": return ; case "agent": return ( ); case "thought": return ; case "tool": return ; case "plan": return (
Plan
{entry.items.map((item, i) => (
{item.content}
))}
); case "subagent": return ( onOpenSubagent(entry.id)} onDiagramDrawn={onDiagramDrawn} /> ); case "message": return entry.incoming ? (
Task from the parent agent
) : (
Report to the parent agent
); case "permission": // Waiting for an answer, it is asked above the composer; the conversation keeps the record. return entry.chosen || entry.questions?.length ? : null; case "error": return (
); } }); function AgentErrorText({ message }: { message: string }) { return {useAgentErrorText(message)}; } function UserMessage({ task, entry, turn, turnCount, }: { task: AgentTask; entry: UserEntry; turn: number | null; turnCount: number; }) { const [editing, setEditing] = useState(false); const failed = (title: string) => (e: unknown) => notifications().notify({ level: "error", title, body: String(e) }); const fail = failed("Couldn't send the message"); const archived = task.status === "archived"; const idle = !archived && !isBusy(task.status) && turn !== null; const { fork = false, rollback = false } = task.capabilities ?? {}; // Editing and running again from a message need an agent that can drop turns. const inPlace = !archived && rollback && turn !== null; // A copy up to an earlier turn drops the later ones from the copied session. const canFork = idle && fork && (rollback || turn === turnCount - 1); if (editing && turn !== null) { return ( setEditing(false)} onSend={async (text, images) => { if (await rerunFrom(task.id, turn, text, images)) setEditing(false); }} /> ); } const images = entry.images ?? []; // Images are listed after the files in `attachments` and shown as thumbnails instead. // Files mentioned in the text are chips there already. const mentioned = new Set( messageTokens(entry.text).flatMap((t) => { const m = t.kind === "file" ? parseMention(t.value) : null; return m ? [basename(m.rel.replace(/\/$/, ""))] : []; }), ); const files = entry.attachments.slice(0, entry.attachments.length - images.length).filter((a) => !mentioned.has(a)); return (
{/* Actions and the time sit beside the author on hover: the reply under it has the turn's duration. */}
void copyText(entry.text)} /> {inPlace && entry.text && ( setEditing(true)} /> )} {inPlace && ( )} {!archived && entry.text && entry.attachments.length === 0 && ( void ( inPlace ? rerunFrom(task.id, turn, entry.text, images) : resendMessage(task.id, entry.text) ).catch(fail) } /> )} {canFork && ( void forkTask(task.id, turn + 1).catch(failed("Couldn't fork the task"))} /> )} You
{files.length > 0 && (
{files.map((a, i) => ( {a} ))}
)}
); } /** An earlier message edited where it is: sending runs the conversation again from it. */ function MessageEditor({ initial, initialImages, later, onCancel, onSend, }: { initial: string; initialImages: AgentImage[]; /** Turns follow it (they are dropped on send). */ later: boolean; onCancel: () => void; onSend: (text: string, images: AgentImage[]) => Promise; }) { const tx = useTx(); const [text, setText] = useState(initial); const [images, setImages] = useState(initialImages); const [sending, setSending] = useState(false); const [error, setError] = useState(null); const pending = useRef(false); const send = async () => { if ((!text.trim() && images.length === 0) || pending.current) return; pending.current = true; setSending(true); setError(null); try { await onSend(text.trim(), images); } catch (e) { setError(e instanceof Error ? e.message : String(e)); notifications().notify({ level: "error", title: "Couldn't send the message", body: String(e), }); } finally { pending.current = false; setSending(false); } }; return (