diff --git a/components/ChatWindow-live-tail.tsx b/components/ChatWindow-live-tail.tsx new file mode 100644 index 000000000..3b8cabd1c --- /dev/null +++ b/components/ChatWindow-live-tail.tsx @@ -0,0 +1,93 @@ +"use client"; + +import type { AgentMessage, BashExecutionMessage, ToolResultMessage } from "@/lib/types"; +import { useI18n } from "@/lib/i18n"; +import { MessageView } from "./MessageView"; + +/** What `ChatLiveTail` needs from `ChatWindow`: the not-yet-committed end of the running turn. */ +export interface ChatLiveTailProps { + /** The reply omp is streaming, also while held until its committed row replaces it. */ + streamingMessage: Partial | null; + liveTokensPerSecond?: number | null; + /** Running tools no message renders yet, shown as status rows while tool calls are collapsed. */ + pendingToolHeaders: { id: string; name: string }[]; + /** `!command` results omp holds back until a later prompt records them. */ + deferredBash: BashExecutionMessage[]; + /** A `!command` the user started that has no result yet. */ + pendingBash: { command: string; excludeFromContext: boolean } | null; + toolResults: Map; + modelNames: Record; + cwd: string | undefined; + onOpenFile?: (filePath: string) => void; + sessionId: string | undefined; + toolCallsDefaultCollapsed: boolean; + expandThinkingByDefault: boolean; + hideThinking: boolean; +} + +/** The running turn's live end after the committed transcript: streaming reply, pending tool rows, `!command` output. */ +export function ChatLiveTail({ + streamingMessage, liveTokensPerSecond, pendingToolHeaders, deferredBash, pendingBash, toolResults, modelNames, cwd, onOpenFile, sessionId, + toolCallsDefaultCollapsed, expandThinkingByDefault, hideThinking, +}: ChatLiveTailProps) { + const { t } = useI18n(); + return ( + <> + {/* Also while held: a finished reply stays until its saved row + replaces it in the same render (useAgentSession-stream). */} + {streamingMessage && ( + + )} + + {toolCallsDefaultCollapsed && pendingToolHeaders.map((tool) => ( +
+ + {tool.name} +
+ ))} + + {deferredBash.map((message, index) => ( + + ))} + + {pendingBash && ( + + )} + + ); +} diff --git a/components/ChatWindow-transcript-group-row.tsx b/components/ChatWindow-transcript-group-row.tsx new file mode 100644 index 000000000..d99bcc464 --- /dev/null +++ b/components/ChatWindow-transcript-group-row.tsx @@ -0,0 +1,144 @@ +"use client"; + +import { useState, type ReactNode } from "react"; +import { ChevronDown, Layers } from "lucide-react"; +import type { AgentMessage, AssistantContentBlock, AssistantMessage } from "@/lib/types"; +import { useI18n } from "@/lib/i18n"; +import type { ActivityPiece, TranscriptRow } from "@/lib/chat-transcript-plan"; + +/** Renders one committed message, optionally as a partial/overridden view under its own key prefix. */ +export type RenderMessage = (idx: number, options?: { attachRef?: boolean; keyPrefix?: string; messageOverride?: AgentMessage; showTimestamp?: boolean; sourceBlockIndices?: number[] }) => ReactNode; + +/** A planned user turn: the user message plus its text and activity segments. */ +export type TranscriptGroupRow = Extract; + +/** What `renderTranscriptGroupRow` needs from `CommittedTranscript`. */ +export interface TranscriptGroupRowContext { + messages: AgentMessage[]; + renderMessage: RenderMessage; + /** Render every message of the turn as its own row, nothing folded (the running turn with tool activity shown). */ + flat: boolean; + messageRefs: React.RefObject<(HTMLDivElement | null)[]>; + visibleRefIndexByMessage: Map; +} + +function withAssistantBlocks( + message: AssistantMessage, + content: AssistantContentBlock[], + options: { omitUsage?: boolean } = {}, +): AssistantMessage { + const next = { ...message, content }; + if (options.omitUsage) next.usage = undefined; + return next; +} + +function ProcessDetailsGroup({ messageCount, toolCallCount, children }: { messageCount: number; toolCallCount: number; children: () => ReactNode }) { + const { t, tn } = useI18n(); + const [expanded, setExpanded] = useState(false); + const parts = [t("chatWindow.processDetails"), tn("chatWindow.messageCount", messageCount)]; + if (toolCallCount > 0) parts.push(tn("chatWindow.toolCallCount", toolCallCount)); + + return ( +
+ + {expanded && ( +
+ {children()} +
+ )} +
+ ); +} + +/** Render a folded activity run exactly as it streamed: one entry per piece, never merged across messages. */ +export function renderActivityPieces(messages: AgentMessage[], pieces: ActivityPiece[], renderMessage: RenderMessage): ReactNode[] { + return pieces.map((piece, pieceIdx) => { + if (!piece.blocks) return renderMessage(piece.index, { attachRef: false, keyPrefix: "activity" }); + const msg = messages[piece.index] as AssistantMessage; + return renderMessage(piece.index, { + attachRef: false, + keyPrefix: `activity-${pieceIdx}`, + messageOverride: { ...withAssistantBlocks(msg, piece.blocks, { omitUsage: true }), errorMessage: undefined }, + showTimestamp: false, + sourceBlockIndices: piece.blocks.map((block) => msg.content.indexOf(block)), + }); + }); +} + +/** Render one user turn as keyed transcript entries for `CommittedTranscript`'s row list. */ +export function renderTranscriptGroupRow(row: TranscriptGroupRow, { messages, renderMessage, flat, messageRefs, visibleRefIndexByMessage }: TranscriptGroupRowContext): ReactNode[] { + const { userIndex: userIdx, endIndex: endIdx, segments } = row; + const rendered: ReactNode[] = []; + + if (flat) { + // Live tail: stays flat so streaming updates and tool progress stay in + // view, and folds once the run ends. + for (let renderIdx = userIdx; renderIdx < endIdx; renderIdx++) { + rendered.push(renderMessage(renderIdx)); + } + return rendered; + } + + rendered.push(renderMessage(userIdx)); + // A message split across segments keeps its navigation ref on the first one. + const attached = new Set(); + segments.forEach((segment, segmentIdx) => { + if (segment.kind === "text") { + const msg = messages[segment.index] as AssistantMessage; + const override = withAssistantBlocks(msg, segment.blocks, { omitUsage: !segment.last }); + if (!segment.last) override.errorMessage = undefined; + rendered.push(renderMessage(segment.index, { + attachRef: !attached.has(segment.index), + keyPrefix: `text-${segmentIdx}`, + messageOverride: override, + ...(segment.last ? {} : { showTimestamp: false }), + // Thinking can ride in a text segment; deferred text loads by source index. + sourceBlockIndices: segment.blocks.map((block) => msg.content.indexOf(block)), + })); + attached.add(segment.index); + return; + } + const refIdx = segment.pieces + .filter((piece) => !attached.has(piece.index)) + .map((piece) => visibleRefIndexByMessage.get(piece.index)) + .find((value): value is number => typeof value === "number"); + for (const piece of segment.pieces) attached.add(piece.index); + rendered.push( +
{ messageRefs.current[refIdx] = el; }} + > + + {() => renderActivityPieces(messages, segment.pieces, renderMessage)} + +
, + ); + }); + return rendered; +} diff --git a/components/ChatWindow.activity.test.mjs b/components/ChatWindow.activity.test.mjs index e9af8df45..fba533f93 100644 --- a/components/ChatWindow.activity.test.mjs +++ b/components/ChatWindow.activity.test.mjs @@ -2,7 +2,7 @@ import assert from "node:assert/strict"; import "../tests/setup-dom.mjs"; import test from "node:test"; -const { renderActivityPieces } = await import("./ChatWindow.tsx"); +const { renderActivityPieces } = await import("./ChatWindow-transcript-group-row.tsx"); const call = (id, name = "bash") => ({ type: "toolCall", toolCallId: id, toolName: name, input: { command: id } }); const assistant = (content) => ({ role: "assistant", provider: "p", model: "m", content }); diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index 9838cd986..7f03f2777 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -2,12 +2,14 @@ import { sendAgentCommand } from "@/lib/agent-client"; import { registerAbortHandler } from "@/hooks/useKeyboardShortcuts"; import { Fragment, memo, useCallback, useEffect, useMemo, useRef, useState, type ReactNode, type Ref } from "react"; -import { ArrowDown, ChevronDown, ChevronUp, Layers, Paperclip, Square } from "lucide-react"; -import type { AgentMessage, AssistantContentBlock, AssistantMessage, BashExecutionMessage, ExtensionUiRequest, SessionInfo, SessionTreeNode, ToolResultMessage } from "@/lib/types"; +import { ArrowDown, ChevronDown, ChevronUp, Paperclip, Square } from "lucide-react"; +import type { AgentMessage, AssistantMessage, ExtensionUiRequest, SessionInfo, SessionTreeNode, ToolResultMessage } from "@/lib/types"; import { translate, useI18n } from "@/lib/i18n"; -import { collectToolResults, isGroupAnchor, planTranscriptRows, type ActivityPiece, type TranscriptRow } from "@/lib/chat-transcript-plan"; +import { collectToolResults, isGroupAnchor, planTranscriptRows, type TranscriptRow } from "@/lib/chat-transcript-plan"; import { isReplyBlock } from "@/lib/message-display"; import { resolveForkTargets } from "@/lib/chat-fork"; +import { renderTranscriptGroupRow, type RenderMessage } from "./ChatWindow-transcript-group-row"; +import { ChatLiveTail } from "./ChatWindow-live-tail"; import { HeldMessageView, MessageView } from "./MessageView"; import { ChatInput, type ChatInputHandle } from "./ChatInput"; import { ExtensionDialog } from "./ExtensionDialog"; @@ -171,16 +173,6 @@ function assistantSpeech( return null; } -function withAssistantBlocks( - message: AssistantMessage, - content: AssistantContentBlock[], - options: { omitUsage?: boolean } = {}, -): AssistantMessage { - const next = { ...message, content }; - if (options.omitUsage) next.usage = undefined; - return next; -} - // Retain the last successful value across welcome-screen remounts, not reloads. let lastKnownOmpVersion: string | undefined; @@ -216,67 +208,6 @@ export function OmpRuntimeVersion() { ); } -function ProcessDetailsGroup({ messageCount, toolCallCount, children }: { messageCount: number; toolCallCount: number; children: () => ReactNode }) { - const { t, tn } = useI18n(); - const [expanded, setExpanded] = useState(false); - const parts = [t("chatWindow.processDetails"), tn("chatWindow.messageCount", messageCount)]; - if (toolCallCount > 0) parts.push(tn("chatWindow.toolCallCount", toolCallCount)); - - return ( -
- - {expanded && ( -
- {children()} -
- )} -
- ); -} - -type RenderMessage = (idx: number, options?: { attachRef?: boolean; keyPrefix?: string; messageOverride?: AgentMessage; showTimestamp?: boolean; sourceBlockIndices?: number[] }) => ReactNode; - -/** Render a folded activity run exactly as it streamed: one entry per piece, never merged across messages. */ -export function renderActivityPieces(messages: AgentMessage[], pieces: ActivityPiece[], renderMessage: RenderMessage): ReactNode[] { - return pieces.map((piece, pieceIdx) => { - if (!piece.blocks) return renderMessage(piece.index, { attachRef: false, keyPrefix: "activity" }); - const msg = messages[piece.index] as AssistantMessage; - return renderMessage(piece.index, { - attachRef: false, - keyPrefix: `activity-${pieceIdx}`, - messageOverride: { ...withAssistantBlocks(msg, piece.blocks, { omitUsage: true }), errorMessage: undefined }, - showTimestamp: false, - sourceBlockIndices: piece.blocks.map((block) => msg.content.indexOf(block)), - }); - }); -} - interface CommittedTranscriptProps { messages: AgentMessage[]; entryIds: string[]; @@ -443,52 +374,7 @@ const CommittedTranscript = memo(function CommittedTranscript({ rendered.push(renderMessage(row.index)); continue; } - const { userIndex: userIdx, endIndex: endIdx, segments } = row; - - if (rendersFlat(row)) { - // Live tail: stays flat so streaming updates and tool progress stay in - // view, and folds once the run ends. - for (let renderIdx = userIdx; renderIdx < endIdx; renderIdx++) { - rendered.push(renderMessage(renderIdx)); - } - continue; - } - - rendered.push(renderMessage(userIdx)); - // A message split across segments keeps its navigation ref on the first one. - const attached = new Set(); - segments.forEach((segment, segmentIdx) => { - if (segment.kind === "text") { - const msg = messages[segment.index] as AssistantMessage; - const override = withAssistantBlocks(msg, segment.blocks, { omitUsage: !segment.last }); - if (!segment.last) override.errorMessage = undefined; - rendered.push(renderMessage(segment.index, { - attachRef: !attached.has(segment.index), - keyPrefix: `text-${segmentIdx}`, - messageOverride: override, - ...(segment.last ? {} : { showTimestamp: false }), - // Thinking can ride in a text segment; deferred text loads by source index. - sourceBlockIndices: segment.blocks.map((block) => msg.content.indexOf(block)), - })); - attached.add(segment.index); - return; - } - const refIdx = segment.pieces - .filter((piece) => !attached.has(piece.index)) - .map((piece) => visibleRefIndexByMessage.get(piece.index)) - .find((value): value is number => typeof value === "number"); - for (const piece of segment.pieces) attached.add(piece.index); - rendered.push( -
{ messageRefs.current[refIdx] = el; }} - > - - {() => renderActivityPieces(messages, segment.pieces, renderMessage)} - -
, - ); - }); + rendered.push(...renderTranscriptGroupRow(row, { messages, renderMessage, flat: rendersFlat(row), messageRefs, visibleRefIndexByMessage })); } return ( <> @@ -1426,62 +1312,21 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, hostStatu sentinelRef={sentinelRef} handleLoadMoreClick={handleLoadMoreClick} /> - {/* Also while held: a finished reply stays until its saved row - replaces it in the same render (useAgentSession-stream). */} - {streamState.streamingMessage && ( - - )} - - {toolCallsDefaultCollapsed && pendingToolHeaders.map((tool) => ( -
- - {tool.name} -
- ))} - - - {deferredBash.map((message, index) => ( - - ))} - - {pendingBash && ( - - )} + {/* After the live turn, in submission order: what omp does not have yet. */} {heldMessages.map((held) => ( diff --git a/components/MarkdownBody.tsx b/components/MarkdownBody.tsx index 64086eacc..fdf011cbc 100644 --- a/components/MarkdownBody.tsx +++ b/components/MarkdownBody.tsx @@ -15,7 +15,8 @@ import { TableChart } from "./TableChart"; // The default sanitizer reads `C:` as a scheme; a drive path (`\` arrives as `%5C`) is a local file the `a` renderer opens. const urlTransform: UrlTransform = (url, key, node) => (/^[A-Za-z]:(?:\/|%5C)/i.test(url) ? url : agentAwareUrlTransform(url, key, node)); -interface MarkdownBodyProps { +/** Props accepted by `MarkdownBody`. */ +export interface MarkdownBodyProps { children: string; className?: string; isStreaming?: boolean; @@ -25,7 +26,17 @@ interface MarkdownBodyProps { autoCharts?: boolean; } -export function MarkdownBody({ children, className, isStreaming, cwd, onOpenFile, suppressImages = false, autoCharts = false }: MarkdownBodyProps) { +/** Everything `MarkdownBody` hands to `ReactMarkdown`: source text, plugins, element renderers and URL transform. */ +export interface MarkdownBodyRendering { + markdown: string; + remarkPlugins: MarkdownPlugins["remarkPlugins"]; + rehypePlugins: MarkdownPlugins["rehypePlugins"]; + components: Components; + urlTransform: UrlTransform; +} + +/** Builds omp-web's markdown rendering setup (links, images, tables, code) so any renderer can reuse it. */ +export function useMarkdownBodyRendering({ children, isStreaming, cwd, onOpenFile, suppressImages = false, autoCharts = false }: Omit): MarkdownBodyRendering { const normalizedMarkdown = useMemo(() => normalizeDisplayMath(children), [children]); const fileSource = useContext(WorkspaceFileContext); const { remarkPlugins: baseRemarkPlugins, rehypePlugins } = useMarkdownPlugins(normalizedMarkdown); @@ -163,15 +174,22 @@ export function MarkdownBody({ children, className, isStreaming, cwd, onOpenFile }; }, [isStreaming, cwd, onOpenFile, suppressImages, openAgentLink, autoCharts, fileSource]); + return { markdown: normalizedMarkdown, remarkPlugins, rehypePlugins, components, urlTransform }; +} + +/** Render agent markdown with `useMarkdownBodyRendering`'s setup. */ +export function MarkdownBody({ className, ...props }: MarkdownBodyProps) { + const rendering = useMarkdownBodyRendering(props); + return (
- {normalizedMarkdown} + {rendering.markdown}
); diff --git a/components/MessageView.tsx b/components/MessageView.tsx index a8e2f1a1c..53771b965 100644 --- a/components/MessageView.tsx +++ b/components/MessageView.tsx @@ -458,7 +458,7 @@ function UserMessageView({ message, cwd, onOpenFile, entryId, onFork, forking, f {/* Bottom row: action buttons + timestamp — inside the bubble's column, spanning its width, so the timestamp aligns with its right edge. */} -
@@ -765,6 +765,7 @@ function AssistantMessageView({ > {/* Model label */}
{!isStreaming && (texts.some((text) => text.trim()) || time || canFork || (ttsSupported && speakableText.trim().length > 0)) && ( -
+
{ttsSupported && speakableText.trim().length > 0 && (