diff --git a/CHANGELOG.md b/CHANGELOG.md index 304da937a..36e3092c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ All notable changes to **omp-web** (`@kahme247/ompweb`) are documented in this f ### Added +- **Follow assistant progress and final replies.** Each turn identifies the model and highlights its latest output. After a successful final reply, earlier progress can be expanded; interrupted, failed and truncated turns stay open. - **Archive and restore sessions on linked hosts.** Archiving now works for sessions on any linked machine, not only this one. The Archived Sessions browser lists every host's archive, shows which host each session is on, and restores it on that host. A host that is offline or runs an older ompweb host is named in the browser instead of hiding its archive silently. Restore rejects a session ID already active on any registered host, so every registered host must be online to restore, even an archive on this machine; the browser names the offline host that blocks it. A per-session claim stops web-server processes that share one agent directory from restoring the same session together; it does not coordinate separate web servers that share a daemon. A restore on another host keeps running when the web server stops waiting for it (after 30 s, or when the link drops), so the session stays claimed until that host's daemon process confirms it stopped: restoring the same ID again, on any host, is refused until then instead of creating a second active copy. Only the daemon process that took the restore can confirm that, so if the daemon was replaced, restarted or shut down meanwhile, or its host was unregistered, the session stays blocked: there is no timeout and no automatic clearing, and recovery is manual (see AGENTS.md). A restored session's attachments and other files are put back before the session becomes visible, so a file attached from another tab at that moment can no longer fail the restore or block retrying it. Restore streams archives with fixed 256 MiB compressed and expanded limits and rejects unsupported session IDs before consuming the archive. - **Several web apps can share one host daemon and the same live sessions.** Link additional servers with `ompweb host login --add --url ` (token from stdin). Prompts, tool progress, results and dialogs stay synchronized, and restarting one web app leaves the other connected to the same omp process. Link protocol v7 moves session startup, idle cleanup and interrupted-run recovery into the host; older links remain supported without sharing their processes. Schedule the first daemon upgrade while its host is quiescent. - **Sidebar marks sessions with an unsent draft.** A session whose composer still holds text or attachments shows a small pencil beside its title, so a half-written message is easy to find again. The mark follows this browser tab's drafts. diff --git a/app/globals.css b/app/globals.css index 9ec5a0e13..a87f1cfbc 100644 --- a/app/globals.css +++ b/app/globals.css @@ -3332,6 +3332,160 @@ html[data-touch-targets="accessible"] .chat-scroll-bottom { animation: chat-message-in var(--dur-med) var(--ease-out-warm) both; } +/* Keep each assistant output legible while activity stays secondary. */ +.assistant-turn-header { + display: flex; + align-items: center; + gap: 7px; + margin: 18px 0 18px; + color: var(--text-muted); + font-size: 11px; + overflow-wrap: anywhere; +} +.assistant-turn-icon { + display: inline-flex; + align-items: center; + justify-content: center; + width: 24px; + height: 24px; + flex-shrink: 0; + border-radius: 7px; + background: color-mix(in srgb, var(--accent) 9%, var(--bg)); + color: var(--accent); +} +.assistant-turn-name { font-size: 12px; font-weight: 600; color: var(--text); } +.assistant-output-step { + position: relative; + min-width: 0; + margin: 0 0 26px 11px; + padding: 0 0 0 20px; + border-left: 1px solid var(--border); +} +.assistant-output-step::before { + content: ""; + position: absolute; + left: -6px; + top: 7px; + width: 5px; + height: 5px; + box-sizing: content-box; + border: 3px solid var(--bg); + border-radius: 50%; + background: var(--text-dim); +} +.assistant-output-latest { + margin-left: 10px; + padding: 12px 14px 12px 19px; + border-left: 2px solid var(--accent); + border-radius: 0 var(--radius-control) var(--radius-control) 0; + background: color-mix(in srgb, var(--accent) 5%, var(--bg)); +} +.assistant-output-latest::before { display: none; } +.assistant-output-label { + margin-bottom: 7px; + color: var(--accent); + font-size: 11px; + font-weight: 500; +} +.assistant-output-message { position: relative; min-width: 0; } +.assistant-output-message [data-message-text] > .markdown-body { + color: var(--text); + font-size: calc(var(--chat-font-size) + 1px); + line-height: max(1.75, var(--chat-line-height)); +} +.assistant-output-footer { + min-height: 28px; + margin-top: 8px !important; + justify-content: flex-end !important; +} +.assistant-output-actions { + flex-wrap: nowrap !important; + opacity: 0; + pointer-events: none; + transition: opacity var(--dur-fast) var(--ease-out-warm); +} +.assistant-output-step:hover .assistant-output-actions, +.assistant-output-step:focus-within .assistant-output-actions, +.assistant-output-latest .assistant-output-actions, +.assistant-output-final .assistant-output-actions { + opacity: 1; + pointer-events: auto; +} +.assistant-output-actions > div { flex-wrap: nowrap !important; gap: 2px !important; } +.assistant-output-actions button { + justify-content: center !important; + gap: 0 !important; + width: 28px; + height: 28px !important; + min-height: 28px !important; + padding: 0 !important; + font-size: 0 !important; +} +.assistant-output-actions .message-copy-action > span { + position: absolute; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip-path: inset(50%); + white-space: nowrap; +} +.assistant-output-time { margin-right: auto; color: var(--text-dim); font-size: 11px; } +.transcript-process-group { margin: 6px 0; } +.transcript-process-content { + margin-top: 7px; + padding: 10px 12px; + border: 1px solid var(--border); + border-radius: var(--radius-control); + background: var(--tool-bg); +} +.transcript-process-caption { margin-bottom: 7px; font-size: 11px; color: var(--text-muted); } +.turn-progress-history { margin: 0 0 23px 11px; padding-bottom: 12px; border-bottom: 1px solid var(--border); } +.turn-progress-toggle { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 6px; + width: 100%; + min-height: 28px; + border: 0; + padding: 3px 0; + background: transparent; + color: var(--text-muted); + text-align: left; + font: inherit; + font-size: 12px; + cursor: pointer; +} +.turn-progress-toggle:hover { color: var(--text); } +.turn-progress-toggle svg { flex-shrink: 0; transition: transform var(--dur-fast) var(--ease-out-warm); } +.turn-progress-toggle[aria-expanded="true"] svg { transform: rotate(90deg); } +.turn-progress-count { font-size: 11px; } +.turn-progress-action { margin-left: auto; font-size: 11px; } +.turn-progress-history > div:not([hidden]) { padding-top: 22px; } +.turn-progress-history .assistant-output-step { margin-left: 0; } +.turn-progress-history .assistant-output-step:last-child { margin-bottom: 6px; } +@media (max-width: 640px) { + .assistant-output-step { margin-left: 6px; padding-left: 15px; } + .assistant-output-latest { margin-left: 5px; padding-right: 10px; } + .assistant-output-message [data-message-text] > .markdown-body { font-size: max(15px, var(--chat-font-size)); } +} +@media (hover: none), (pointer: coarse) { + .assistant-output-actions { + opacity: 1; + pointer-events: auto; + } + .assistant-output-actions button { width: 44px; height: 44px !important; min-height: 44px !important; } + .turn-progress-toggle { min-height: 44px; } +} +html[data-touch-targets="accessible"] .assistant-output-actions { + opacity: 1; + pointer-events: auto; +} +html[data-touch-targets="accessible"] .assistant-output-actions button { width: 44px; height: 44px !important; min-height: 44px !important; } +html[data-touch-targets="accessible"] .turn-progress-toggle { min-height: 44px; } + .message-copy-actions { display: flex; flex-wrap: wrap; diff --git a/components/ChatWindow-live-tail.transition.test.mjs b/components/ChatWindow-live-tail.transition.test.mjs new file mode 100644 index 000000000..95521900a --- /dev/null +++ b/components/ChatWindow-live-tail.transition.test.mjs @@ -0,0 +1,28 @@ +import assert from "node:assert/strict"; +import "../tests/setup-dom.mjs"; +import test, { afterEach } from "node:test"; +import React from "react"; + +const { render, fireEvent, cleanup } = await import("@testing-library/react/pure.js"); +const { ChatLiveTail } = await import("./ChatWindow-live-tail.tsx"); +afterEach(cleanup); + +test("first streamed text preserves a manually opened thinking block", () => { + const thinking = { type: "thinking", thinking: "Checking the details" }; + const message = { role: "assistant", provider: "p", model: "m", timestamp: 1, content: [thinking] }; + const props = { + streamingMessage: message, isStreaming: true, previousOutputModel: null, + pendingToolHeaders: [], deferredBash: [], pendingBash: null, toolResults: new Map(), + modelNames: {}, cwd: undefined, sessionId: undefined, + toolCallsDefaultCollapsed: true, expandThinkingByDefault: false, hideThinking: false, + }; + const view = render(React.createElement(ChatLiveTail, props)); + fireEvent.click(view.getByRole("button", { name: /Thinking/ })); + assert.ok(view.getByText("Checking the details")); + view.rerender(React.createElement(ChatLiveTail, { + ...props, + streamingMessage: { ...message, content: [thinking, { type: "text", text: "First answer" }] }, + })); + assert.ok(view.getByText("Checking the details")); + assert.ok(view.getByText("First answer")); +}); diff --git a/components/ChatWindow-live-tail.tsx b/components/ChatWindow-live-tail.tsx index 3b8cabd1c..295b626bc 100644 --- a/components/ChatWindow-live-tail.tsx +++ b/components/ChatWindow-live-tail.tsx @@ -1,13 +1,17 @@ "use client"; -import type { AgentMessage, BashExecutionMessage, ToolResultMessage } from "@/lib/types"; +import type { AgentMessage, AssistantMessage, BashExecutionMessage, ToolResultMessage } from "@/lib/types"; import { useI18n } from "@/lib/i18n"; import { MessageView } from "./MessageView"; +import { assistantModelName, AssistantOutputStep, AssistantTurnHeader, hasAssistantOutput } from "./TranscriptOutput"; /** 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; + isStreaming: boolean; + /** Provider and model of the preceding visible assistant output, if any. */ + previousOutputModel: string | null; liveTokensPerSecond?: number | null; /** Running tools no message renders yet, shown as status rows while tool calls are collapsed. */ pendingToolHeaders: { id: string; name: string }[]; @@ -27,27 +31,38 @@ export interface ChatLiveTailProps { /** 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, + streamingMessage, isStreaming, previousOutputModel, liveTokensPerSecond, pendingToolHeaders, deferredBash, pendingBash, toolResults, modelNames, cwd, onOpenFile, sessionId, toolCallsDefaultCollapsed, expandThinkingByDefault, hideThinking, }: ChatLiveTailProps) { const { t } = useI18n(); + const hasOutput = streamingMessage?.role === "assistant" && hasAssistantOutput(streamingMessage); return ( <> {/* Also while held: a finished reply stays until its saved row replaces it in the same render (useAgentSession-stream). */} {streamingMessage && ( - + <> + {hasOutput && streamingMessage.role === "assistant" && previousOutputModel !== `${streamingMessage.provider}:${streamingMessage.model}` && ( + + )} + + + + )} {toolCallsDefaultCollapsed && pendingToolHeaders.map((tool) => ( diff --git a/components/ChatWindow-transcript-group-row.tsx b/components/ChatWindow-transcript-group-row.tsx index d99bcc464..a5ca2d73d 100644 --- a/components/ChatWindow-transcript-group-row.tsx +++ b/components/ChatWindow-transcript-group-row.tsx @@ -4,10 +4,11 @@ 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"; +import { completedTurnReplyIndex, type ActivityPiece, type TranscriptRow, type TranscriptSegment } from "@/lib/chat-transcript-plan"; +import { assistantModelName, hasAssistantOutput, AssistantTurnHeader, TurnProgressHistory } from "./TranscriptOutput"; /** 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; +export type RenderMessage = (idx: number, options?: { attachRef?: boolean; keyPrefix?: string; messageOverride?: AgentMessage; showTimestamp?: boolean; sourceBlockIndices?: number[]; final?: boolean; latest?: boolean; followingActivity?: ReactNode }) => ReactNode; /** A planned user turn: the user message plus its text and activity segments. */ export type TranscriptGroupRow = Extract; @@ -20,6 +21,14 @@ export interface TranscriptGroupRowContext { flat: boolean; messageRefs: React.RefObject<(HTMLDivElement | null)[]>; visibleRefIndexByMessage: Map; + entryIds: string[]; + modelNames: Record; + turnActive: boolean; + latestOutputIndex: number; + streamingHasOutput: boolean; + searchQuery: string; + expandThinkingByDefault: boolean; + showToolCallsUnfolded: boolean; } function withAssistantBlocks( @@ -92,53 +101,96 @@ export function renderActivityPieces(messages: AgentMessage[], pieces: ActivityP } /** 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[] { +export function renderTranscriptGroupRow(row: TranscriptGroupRow, { messages, renderMessage, flat, messageRefs, visibleRefIndexByMessage, entryIds, modelNames, turnActive, latestOutputIndex, streamingHasOutput, searchQuery, expandThinkingByDefault, showToolCallsUnfolded }: TranscriptGroupRowContext): ReactNode[] { const { userIndex: userIdx, endIndex: endIdx, segments } = row; const rendered: ReactNode[] = []; + const replyIndex = turnActive ? null : completedTurnReplyIndex(messages, userIdx, endIdx); + const finalSegment = replyIndex === null ? -1 : segments.findLastIndex(segment => segment.kind === "text" && segment.index === replyIndex && segment.last); + const firstText = segments.find(segment => segment.kind === "text"); + const headerMessage = replyIndex !== null ? messages[replyIndex] : firstText ? messages[firstText.index] : null; + const turnHeader = headerMessage?.role === "assistant" ? : null; + rendered.push(renderMessage(userIdx)); + if (turnHeader) rendered.push(turnHeader); 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++) { + let previousModel = headerMessage?.role === "assistant" ? `${headerMessage.provider}:${headerMessage.model}` : ""; + for (let renderIdx = userIdx + 1; renderIdx < endIdx; renderIdx++) { + const message = messages[renderIdx]; + if (message.role === "assistant" && hasAssistantOutput(message)) { + const model = `${message.provider}:${message.model}`; + if (model !== previousModel) rendered.push(); + previousModel = model; + } 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 lastTextSegment = segments.findLastIndex(segment => segment.kind === "text"); + const renderActivity = (segment: Extract, segmentIdx: number, attached: Set): ReactNode => { const refIdx = segment.pieces - .filter((piece) => !attached.has(piece.index)) - .map((piece) => visibleRefIndexByMessage.get(piece.index)) + .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; }} - > + return ( +
{ messageRefs.current[refIdx] = el; }}> {() => renderActivityPieces(messages, segment.pieces, renderMessage)} -
, +
); - }); + }; + const renderSegments = (from: number, to: number): ReactNode[] => { + const output: ReactNode[] = []; + // Reopening history must attach the same message refs again. + const attached = new Set(); + let previousModel = headerMessage?.role === "assistant" ? `${headerMessage.provider}:${headerMessage.model}` : ""; + for (let segmentIdx = from; segmentIdx < to; segmentIdx += 1) { + const segment = segments[segmentIdx]; + if (segment.kind === "text") { + const msg = messages[segment.index] as AssistantMessage; + const model = `${msg.provider}:${msg.model}`; + if (model !== previousModel) output.push(); + previousModel = model; + const override = withAssistantBlocks(msg, segment.blocks, { omitUsage: !segment.last }); + if (!segment.last) override.errorMessage = undefined; + const attachRef = !attached.has(segment.index); + attached.add(segment.index); + const next = segments[segmentIdx + 1]; + const followingActivity = segmentIdx + 1 < to && next?.kind === "activity" ? renderActivity(next, segmentIdx + 1, attached) : undefined; + output.push(renderMessage(segment.index, { + attachRef, + keyPrefix: `text-${segmentIdx}`, + messageOverride: override, + sourceBlockIndices: segment.blocks.map(block => msg.content.indexOf(block)), + latest: segment.index === latestOutputIndex && !streamingHasOutput && segmentIdx === lastTextSegment, + final: segmentIdx === finalSegment, + followingActivity, + ...(segment.last ? {} : { showTimestamp: false }), + })); + if (followingActivity) segmentIdx += 1; + } else { + output.push(renderActivity(segment, segmentIdx, attached)); + } + } + return output; + }; + const progress = finalSegment > 0 ? segments.slice(0, finalSegment) : []; + const outputCount = progress.filter(segment => segment.kind === "text").length; + if (outputCount > 0 && replyIndex !== null && !searchQuery.trim() && !expandThinkingByDefault && !showToolCallsUnfolded) { + const toolCallCount = progress.reduce((count, segment) => count + (segment.kind === "activity" ? segment.toolCallCount : 0), 0); + const progressIndices = new Set(progress.flatMap(segment => segment.kind === "text" ? [segment.index] : segment.pieces.map(piece => piece.index))); + progressIndices.delete(replyIndex); + rendered.push( + { for (const index of progressIndices) { const refIdx = visibleRefIndexByMessage.get(index); if (refIdx !== undefined) messageRefs.current[refIdx] = el; } }}> + {() => renderSegments(0, finalSegment)} + , + ); + rendered.push(...renderSegments(finalSegment, segments.length)); + } else { + rendered.push(...renderSegments(0, segments.length)); + } return rendered; } diff --git a/components/ChatWindow.activity.test.mjs b/components/ChatWindow.activity.test.mjs index fba533f93..95d412f7b 100644 --- a/components/ChatWindow.activity.test.mjs +++ b/components/ChatWindow.activity.test.mjs @@ -1,8 +1,13 @@ import assert from "node:assert/strict"; import "../tests/setup-dom.mjs"; -import test from "node:test"; +import test, { afterEach } from "node:test"; +import React from "react"; +const { render, fireEvent, cleanup } = await import("@testing-library/react/pure.js"); const { renderActivityPieces } = await import("./ChatWindow-transcript-group-row.tsx"); +const { CommittedTranscript } = await import("./ChatWindow.tsx"); +const { collectToolResults, isGroupAnchor } = await import("../lib/chat-transcript-plan.ts"); +afterEach(cleanup); const call = (id, name = "bash") => ({ type: "toolCall", toolCallId: id, toolName: name, input: { command: id } }); const assistant = (content) => ({ role: "assistant", provider: "p", model: "m", content }); @@ -35,3 +40,118 @@ test("folded activity keeps tool calls from separate messages as separate entrie assert.deepEqual(calls[1].options.sourceBlockIndices, [0, 1, 2]); assert.equal(new Set(calls.map(({ idx, options }) => `${options.keyPrefix}-${idx}`)).size, calls.length); }); + +const text = value => ({ type: "text", text: value }); +const taskMessages = final => [ + { role: "user", content: "Check the build" }, + assistant([text("Checking the dependencies."), call("check", "read")]), + { role: "toolResult", toolCallId: "check", content: [text("Dependencies loaded")] }, + assistant([text("Running the checks.")]), + { ...assistant([text("The checks passed.")]), stopReason: "stop", ...final }, +]; + +function transcriptProps(messages, overrides = {}) { + const visibleRefIndexByMessage = new Map(); + let lastAnchorIdx = -1; + messages.forEach((message, index) => { + if (isGroupAnchor(message)) lastAnchorIdx = index; + if (message.role === "user" || message.role === "assistant") visibleRefIndexByMessage.set(index, visibleRefIndexByMessage.size); + }); + return { + messages, entryIds: messages.map((_, index) => `entry-${index}`), + conversationMeta: { toolResultsMap: collectToolResults(messages), lastAnchorIdx, visibleRefIndexByMessage }, + messageRefs: { current: [] }, isStreaming: false, streamingHasOutput: false, sessionBusy: false, isCompacting: false, externalRunActive: false, + isNew: false, forkingEntryId: null, editingEntryId: null, handleFork: () => {}, handleEdit: async () => true, + modelNames: { "p:m": "Test model" }, messageCwd: undefined, sessionId: "test-session", toolCallsDefaultCollapsed: true, + hideToolActivity: true, neverFoldActivity: false, showToolCallsUnfolded: false, expandThinkingByDefault: false, hideThinkingBlock: false, searchQuery: "", visibleCount: 50, nearBottom: true, + sentinelRef: { current: null }, handleLoadMoreClick: () => {}, ...overrides, + }; +} + +test("running outputs stay visible, then normal completion folds progress and preserves the actual final reply", () => { + const props = transcriptProps(taskMessages(), { sessionBusy: true }); + const view = render(React.createElement(CommittedTranscript, props)); + assert.ok(view.getByText("Checking the dependencies.")); + assert.ok(view.getByText("Running the checks.")); + assert.equal(view.getAllByText("Test model").length, 1); + assert.equal(view.container.querySelectorAll(".assistant-output-latest").length, 1); + assert.equal(view.queryByText("Final reply"), null, "a stop frame alone does not end a still-running task"); + + view.rerender(React.createElement(CommittedTranscript, { ...props, sessionBusy: false })); + const fold = view.getByRole("button", { name: /Task progress.*2 outputs.*1 tool call/ }); + assert.equal(fold.getAttribute("aria-expanded"), "false"); + assert.equal(view.queryByText("Checking the dependencies."), null); + assert.ok(view.getByText("The checks passed.")); + assert.ok(view.getByText("Final reply")); + assert.equal(view.getAllByText("Test model").length, 1); + const progressRef = props.conversationMeta.visibleRefIndexByMessage.get(1); + assert.equal(props.messageRefs.current[progressRef], fold.parentElement); + + for (let cycle = 0; cycle < 2; cycle += 1) { + fireEvent.click(fold); + assert.equal(fold.getAttribute("aria-expanded"), "true"); + assert.ok(view.getByText("Checking the dependencies.")); + assert.ok(view.getByText("Running the checks.")); + assert.ok(props.messageRefs.current[progressRef].textContent.includes("Checking the dependencies.")); + const tools = view.getByRole("button", { name: /Process details.*tool call/ }); + fireEvent.click(tools); + fireEvent.click(view.container.querySelector(".activity-row-trigger")); + assert.ok(view.getByText("Dependencies loaded")); + fireEvent.click(fold); + assert.equal(view.queryByText("Checking the dependencies."), null); + assert.equal(props.messageRefs.current[progressRef], fold.parentElement); + } +}); + +test("errors, interruptions, truncated and unknown endings keep progress open", () => { + for (const stopReason of ["error", "aborted", "length", undefined]) { + const final = { stopReason, ...(stopReason === "error" ? { errorMessage: "Provider failed" } : {}) }; + const view = render(React.createElement(CommittedTranscript, transcriptProps(taskMessages(final)))); + assert.ok(view.getByText("Checking the dependencies.")); + assert.equal(view.queryByText("Task progress"), null); + assert.equal(view.queryByText("Final reply"), null); + if (stopReason === "error") assert.ok(view.getByRole("alert")); + if (stopReason === "aborted") assert.ok(view.getByRole("status")); + view.unmount(); + } +}); + +test("a continuing task unfolds and folds again on its next final reply", () => { + const messages = taskMessages(); + const view = render(React.createElement(CommittedTranscript, transcriptProps(messages))); + fireEvent.click(view.getByRole("button", { name: /Task progress/ })); + assert.ok(view.getByText("Checking the dependencies.")); + const continued = [...messages, assistant([text("Checking one more case.")])]; + view.rerender(React.createElement(CommittedTranscript, transcriptProps(continued, { sessionBusy: true }))); + assert.ok(view.getByText("Checking the dependencies.")); + assert.ok(view.getByText("Checking one more case.")); + const completed = [...continued, { ...assistant([text("All cases checked.")]), stopReason: "stop" }]; + view.rerender(React.createElement(CommittedTranscript, transcriptProps(completed))); + assert.equal(view.queryByText("Checking the dependencies."), null); + assert.equal(view.getByRole("button", { name: /Task progress/ }).getAttribute("aria-expanded"), "false"); + assert.ok(view.getByText("All cases checked.")); +}); + +test("streaming text removes the highlight from the previous committed output", () => { + const props = transcriptProps(taskMessages({ stopReason: "toolUse" }), { sessionBusy: true, isStreaming: true, streamingHasOutput: true }); + const view = render(React.createElement(CommittedTranscript, props)); + assert.equal(view.container.querySelectorAll(".assistant-output-latest").length, 0); + assert.ok(view.getByText("Running the checks.")); +}); + +test("an empty aborted response remains visible and never folds the preceding progress", () => { + const messages = taskMessages({ content: [], stopReason: "aborted" }); + const view = render(React.createElement(CommittedTranscript, transcriptProps(messages))); + assert.ok(view.getByText("Checking the dependencies.")); + assert.ok(view.getByRole("status")); + assert.equal(view.queryByText("Task progress"), null); +}); + +test("search and unfolded activity preferences keep earlier outputs accessible", () => { + for (const overrides of [{ searchQuery: "dependencies" }, { expandThinkingByDefault: true }, { showToolCallsUnfolded: true }, { neverFoldActivity: true }]) { + const view = render(React.createElement(CommittedTranscript, transcriptProps(taskMessages(), overrides))); + assert.ok(view.getByText("Checking the dependencies.")); + assert.equal(view.queryByText("Task progress"), null); + view.unmount(); + } +}); diff --git a/components/ChatWindow.tsx b/components/ChatWindow.tsx index 7f03f2777..05696ec8e 100644 --- a/components/ChatWindow.tsx +++ b/components/ChatWindow.tsx @@ -11,6 +11,7 @@ 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 { AssistantOutputStep, AssistantTurnHeader, assistantModelName, hasAssistantOutput } from "./TranscriptOutput"; import { ChatInput, type ChatInputHandle } from "./ChatInput"; import { ExtensionDialog } from "./ExtensionDialog"; import { SubagentTranscriptDialog } from "./SubagentTranscriptDialog"; @@ -173,6 +174,7 @@ function assistantSpeech( return null; } + // Retain the last successful value across welcome-screen remounts, not reloads. let lastKnownOmpVersion: string | undefined; @@ -208,12 +210,14 @@ export function OmpRuntimeVersion() { ); } + interface CommittedTranscriptProps { messages: AgentMessage[]; entryIds: string[]; conversationMeta: { toolResultsMap: Map; lastAnchorIdx: number; visibleRefIndexByMessage: Map }; messageRefs: React.RefObject<(HTMLDivElement | null)[]>; isStreaming: boolean; + streamingHasOutput: boolean; sessionBusy: boolean; isCompacting: boolean; /** A run started outside this UI looks active from the transcript tail (see @@ -237,6 +241,7 @@ interface CommittedTranscriptProps { showToolCallsUnfolded: boolean; expandThinkingByDefault: boolean; hideThinkingBlock: boolean; + searchQuery: string; visibleCount: number; /** True while the viewport is near the bottom of the conversation. When * false (user is reading history), the render window anchors its top so @@ -253,15 +258,22 @@ interface CommittedTranscriptProps { * change `streamingMessage`, rendered separately) do not re-run the O(history) * grouping/splitting work at display-frame cadence. */ -const CommittedTranscript = memo(function CommittedTranscript({ - messages, entryIds, conversationMeta, messageRefs, isStreaming, sessionBusy, isCompacting, externalRunActive, isNew, forkingEntryId, editingEntryId, +export const CommittedTranscript = memo(function CommittedTranscript({ + messages, entryIds, conversationMeta, messageRefs, isStreaming, streamingHasOutput, sessionBusy, isCompacting, externalRunActive, isNew, forkingEntryId, editingEntryId, handleFork, handleEdit, modelNames, messageCwd, onOpenFile, sessionId, - toolCallsDefaultCollapsed, hideToolActivity, neverFoldActivity, showToolCallsUnfolded, expandThinkingByDefault, hideThinkingBlock, visibleCount, nearBottom, sentinelRef, handleLoadMoreClick, + toolCallsDefaultCollapsed, hideToolActivity, neverFoldActivity, showToolCallsUnfolded, expandThinkingByDefault, hideThinkingBlock, searchQuery = "", visibleCount, nearBottom, sentinelRef, handleLoadMoreClick, }: CommittedTranscriptProps) { const { t } = useI18n(); const { toolResultsMap, lastAnchorIdx, visibleRefIndexByMessage } = conversationMeta; // omp's `branch` command accepts a user entry only; see lib/chat-fork.ts. const forkTargets = useMemo(() => resolveForkTargets(messages, entryIds), [messages, entryIds]); + const latestOutputIndex = useMemo(() => { + for (let index = messages.length - 1; index >= 0; index -= 1) { + if (hasAssistantOutput(messages[index])) return index; + if (isGroupAnchor(messages[index])) break; + } + return -1; + }, [messages]); const attachVisibleRef = (idx: number, refIndex: number) => (el: HTMLDivElement | null) => { messageRefs.current[refIndex] = el; @@ -293,7 +305,8 @@ const CommittedTranscript = memo(function CommittedTranscript({ const canOfferFork = !sessionBusy && !isNew && !!forkTarget && forkableRow; const canOfferEdit = !sessionBusy && !isCompacting && !isNew && msg.role === "user" && !msg.branchSummary && !!entryIds[idx]; const historyMutationPending = forkingEntryId !== null || editingEntryId !== null; - const view = ( + const focusedOutput = hasAssistantOutput(msg); + const messageView = ( ); + const view = focusedOutput ? ( + + {messageView} + {options.followingActivity} + + ) : {messageView}{options.followingActivity}; if (!isVisible || options.attachRef === false || currentRefIdx === undefined) return view; return (
@@ -371,10 +392,17 @@ const CommittedTranscript = memo(function CommittedTranscript({ for (let rowIdx = startIndex; rowIdx < rows.length; rowIdx++) { const row = rows[rowIdx]; if (row.kind === "message") { + const message = messages[row.index]; + if (message.role === "assistant" && hasAssistantOutput(message)) rendered.push(); rendered.push(renderMessage(row.index)); continue; } - rendered.push(...renderTranscriptGroupRow(row, { messages, renderMessage, flat: rendersFlat(row), messageRefs, visibleRefIndexByMessage })); + rendered.push(...renderTranscriptGroupRow(row, { + messages, renderMessage, flat: rendersFlat(row), messageRefs, visibleRefIndexByMessage, + entryIds, modelNames, + turnActive: row.endIndex === messages.length && row.userIndex === lastAnchorIdx && (sessionBusy || externalRunActive || isStreaming), + latestOutputIndex, streamingHasOutput, searchQuery, expandThinkingByDefault, showToolCallsUnfolded, + })); } return ( <> @@ -820,13 +848,18 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, hostStatu let hasCompaction = false; const visibleRefIndexByMessage = new Map(); let refIdx = 0; + let lastOutputModel: string | null = null; messages.forEach((message, index) => { if (message.role === "custom" && message.customType === "compaction") hasCompaction = true; - if (isGroupAnchor(message)) lastAnchorIdx = index; + if (isGroupAnchor(message)) { + lastAnchorIdx = index; + lastOutputModel = null; + } + if (message.role === "assistant" && hasAssistantOutput(message)) lastOutputModel = `${message.provider}:${message.model}`; if (message.role === "user" || message.role === "assistant") visibleRefIndexByMessage.set(index, refIdx++); }); - return { toolResultsMap, lastAnchorIdx, hasCompaction, visibleRefIndexByMessage }; + return { toolResultsMap, lastAnchorIdx, hasCompaction, visibleRefIndexByMessage, lastOutputModel }; }, [messages]); // Runtime tool results span committed messages plus the tool calls omp is // still executing. A committed result always wins; the live snapshot only @@ -1289,6 +1322,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, hostStatu conversationMeta={conversationMetaWithLive} messageRefs={messageRefs} isStreaming={streamState.isStreaming} + streamingHasOutput={hasAssistantOutput(streamState.streamingMessage)} sessionBusy={sessionBusy} isCompacting={isCompacting} externalRunActive={externalRunActive} @@ -1307,6 +1341,7 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, hostStatu showToolCallsUnfolded={showToolCallsUnfolded} expandThinkingByDefault={expandThinkingByDefault} hideThinkingBlock={hideThinkingBlock} + searchQuery={searchQuery} visibleCount={visibleCount} nearBottom={nearBottom} sentinelRef={sentinelRef} @@ -1314,6 +1349,8 @@ export function ChatWindow({ session, newSessionCwd, newSessionHostId, hostStatu /> ; } if (message.role === "assistant") { - return ; + return ; } if (message.role === "toolResult") { // Rendered inline under its toolCall — skip standalone rendering if paired @@ -263,6 +266,8 @@ export const MessageView = memo(function MessageView({ message, isStreaming, too && prev.toolCallsDefaultCollapsed === next.toolCallsDefaultCollapsed && prev.expandThinkingByDefault === next.expandThinkingByDefault && prev.hideThinking === next.hideThinking + && prev.hideModelLabel === next.hideModelLabel + && prev.compactActions === next.compactActions && prev.sourceBlockIndices?.join() === next.sourceBlockIndices?.join() && (!prev.isStreaming || prev.liveTokensPerSecond === next.liveTokensPerSecond); }); @@ -632,6 +637,8 @@ function AssistantMessageView({ hideThinking, sourceBlockIndices, liveTokensPerSecond, + hideModelLabel, + compactActions, }: { message: AssistantMessage; isStreaming?: boolean; @@ -654,6 +661,8 @@ function AssistantMessageView({ hideThinking: boolean; sourceBlockIndices?: number[]; liveTokensPerSecond?: number | null; + hideModelLabel: boolean; + compactActions: boolean; }) { const { t, locale } = useI18n(); const { isSupported: ttsSupported, isSpeaking: ttsSpeaking, speakingId: ttsSpeakingId, toggle: ttsToggle } = useSpeechContext(); @@ -673,9 +682,8 @@ function AssistantMessageView({ .map((block, index) => ({ block, originalIndex: sourceBlockIndices?.[index] ?? index })) .filter(({ block }) => !(hideThinking && block.type === "thinking") && !isEmptyThinkingBlock(block, { isStreaming })); const blocks = blockItems.map(({ block }) => block); - // Activity rows stay compact; a row that also carries reply text keeps its model label. const hideHeader = blocks.some((block) => block.type === "thinking" || block.type === "toolCall") && !blocks.some(isReplyBlock); - const errorMessage = message.errorMessage?.trim() || null; + const errorMessage = message.errorMessage?.trim() || (message.stopReason === "aborted" ? t("messageView.interruptedByUser") : message.stopReason === "error" ? t("agentSession.responseFailed") : null); const isInterrupted = isInterruptedMessage(errorMessage, message.stopReason); const blockItemsRef = useRef(blockItems); blockItemsRef.current = blockItems; @@ -759,9 +767,9 @@ function AssistantMessageView({ return (
{/* Model label */}
- {message.provider && ( + {message.provider && !hideModelLabel && ( {modelNames?.[`${message.provider}:${message.model}`] ?? modelNames?.[message.model] ?? message.model} )} {isStreaming && (() => { @@ -879,8 +887,10 @@ function AssistantMessageView({
{!isStreaming && (texts.some((text) => text.trim()) || time || canFork || (ttsSupported && speakableText.trim().length > 0)) && ( -
-
+ <> +
+ {compactActions && time && {time}} +
{ttsSupported && speakableText.trim().length > 0 && ( @@ -898,8 +908,9 @@ function AssistantMessageView({ )} {canFork && }
- {time && {time}} + {!compactActions && time && {time}}
+ )}
); diff --git a/components/TranscriptOutput.tsx b/components/TranscriptOutput.tsx new file mode 100644 index 000000000..c0e3b88cb --- /dev/null +++ b/components/TranscriptOutput.tsx @@ -0,0 +1,60 @@ +"use client"; + +import { useId, useState, type ReactNode, type Ref } from "react"; +import { ChevronRight, Sparkles } from "lucide-react"; +import { useI18n } from "@/lib/i18n"; +import type { AgentMessage, AssistantMessage } from "@/lib/types"; + +export function hasAssistantOutput(message: Partial | null): boolean { + return message?.role === "assistant" && ((Array.isArray(message.content) && message.content.some(block => + block.type === "image" || (block.type === "text" && block.text.trim().length > 0), + )) || !!message.errorMessage?.trim() || message.stopReason === "error" || message.stopReason === "aborted"); +} + +export function assistantModelName(message: AssistantMessage, names: Record): string { + return names[`${message.provider}:${message.model}`] ?? names[message.model] ?? message.model ?? ""; +} + +export function AssistantTurnHeader({ model }: { model: string }) { + return ( +
+ + AI + {model && {model}} +
+ ); +} + +export function AssistantOutputStep({ latest, final, active = true, children }: { latest?: boolean; final?: boolean; active?: boolean; children: ReactNode }) { + const { t } = useI18n(); + return ( +
+ {(latest || final) &&
{t(final ? "chatWindow.finalReply" : "chatWindow.latestOutput")}
} + {children} +
+ ); +} + +/** Only mounted for a completed turn. A new final entry remounts this fold, + * so continuing a task and finishing again folds the new progress as well. */ +export function TurnProgressHistory({ outputCount, toolCallCount, collapsedRef, children }: { + outputCount: number; + toolCallCount: number; + collapsedRef?: Ref; + children: () => ReactNode; +}) { + const { t, tn } = useI18n(); + const [expanded, setExpanded] = useState(false); + const contentId = useId(); + return ( +
+ + +
+ ); +} diff --git a/lib/chat-transcript-plan.test.mjs b/lib/chat-transcript-plan.test.mjs index bec8c3c07..d05f0ee3a 100644 --- a/lib/chat-transcript-plan.test.mjs +++ b/lib/chat-transcript-plan.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import test from "node:test"; -const { planTranscriptRows, looksLikeRunningTurn, collectToolResults, sanitizePassiveToolContext } = await import("./chat-transcript-plan.ts"); +const { planTranscriptRows, completedTurnReplyIndex, looksLikeRunningTurn, collectToolResults, sanitizePassiveToolContext } = await import("./chat-transcript-plan.ts"); function user(id, content = `u-${id}`) { return { role: "user", content }; @@ -28,12 +28,12 @@ function shape(row) { }); } -test("plans a plain Q/A pair as standalone rows", () => { +test("a plain Q/A pair keeps its turn boundary without an activity fold", () => { const rows = planTranscriptRows([user("u1"), assistant("a1")]); - assert.deepEqual(rows, [ - { kind: "message", index: 0 }, - { kind: "message", index: 1 }, - ]); + assert.equal(rows.length, 1); + assert.deepEqual(shape(rows[0]), [["text", "a-a1"]]); + assert.equal(rows[0].userIndex, 0); + assert.equal(rows[0].endIndex, 2); }); test("an answer that ended the turn stays visible when a reminder resumes the agent", () => { @@ -99,10 +99,7 @@ test("hideThinking drops thinking, so a turn with only thinking and text has not const messages = [user("u1"), assistant("a1", [{ type: "thinking", thinking: "hmm" }, { type: "text", text: "Answer" }])]; const shown = planTranscriptRows(messages); assert.deepEqual(shape(shown[0]), [["activity", [1]], ["text", "Answer"]]); - assert.deepEqual(planTranscriptRows(messages, { hideThinking: true }), [ - { kind: "message", index: 0 }, - { kind: "message", index: 1 }, - ]); + assert.deepEqual(shape(planTranscriptRows(messages, { hideThinking: true })[0]), [["text", "Answer"]]); }); test("showThinking keeps thinking out of the fold, so an expanded block is not hidden on commit", () => { @@ -120,11 +117,9 @@ test("showThinking keeps thinking out of the fold, so an expanded block is not h ["activity", [["toolCall"]]], ["text", 3, ["thinking", "text"]], ]); - // A turn of only thinking and text has nothing left to fold. - assert.deepEqual(planTranscriptRows([user("u1"), assistant("a1", [{ type: "thinking", thinking: "hmm" }, { type: "text", text: "Answer" }])], { showThinking: true }), [ - { kind: "message", index: 0 }, - { kind: "message", index: 1 }, - ]); + // The turn stays grouped for its model header even without folded activity. + const [plain] = planTranscriptRows([user("u1"), assistant("a1", [{ type: "thinking", thinking: "hmm" }, { type: "text", text: "Answer" }])], { showThinking: true }); + assert.deepEqual(plain.segments.map(segment => [segment.kind, segment.index, segment.blocks.map(block => block.type)]), [["text", 1, ["thinking", "text"]]]); }); test("showToolCalls keeps tool call rows out of the fold; with showThinking nothing is left to fold", () => { @@ -141,11 +136,10 @@ test("showToolCalls keeps tool call rows out of the fold; with showThinking noth ["text", ["toolCall"]], ["text", ["text"]], ]); - // Nothing left to fold: standalone rows, without a row for the tool result (it renders under its call). - assert.deepEqual(planTranscriptRows(messages, { showToolCalls: true, showThinking: true }), [ - { kind: "message", index: 0 }, - { kind: "message", index: 1 }, - { kind: "message", index: 3 }, + // Both blocks remain visible in the grouped turn; tool results stay under their call. + assert.deepEqual(kinds(planTranscriptRows(messages, { showToolCalls: true, showThinking: true })[0]), [ + ["text", ["thinking", "toolCall"]], + ["text", ["text"]], ]); }); @@ -169,11 +163,23 @@ test("neverFold plans every turn as standalone rows, so the render window counts test("mount notices, which never render, do not open an empty fold", () => { const mount = { role: "custom", customType: "xdev-mount-notice", display: true, content: "mounted" }; - assert.deepEqual(planTranscriptRows([user("u1"), mount, assistant("a1")]), [ - { kind: "message", index: 0 }, - { kind: "message", index: 1 }, - { kind: "message", index: 2 }, - ]); + assert.deepEqual(shape(planTranscriptRows([user("u1"), mount, assistant("a1")])[0]), [["text", "a-a1"]]); +}); + +test("only a normal terminal reply can summarize a turn", () => { + const preamble = assistant("working", [{ type: "text", text: "Checking" }, toolCall("tc1")]); + const base = [user("u1"), preamble, toolResult("tc1")]; + const reply = { ...assistant("done"), stopReason: "stop" }; + assert.equal(completedTurnReplyIndex([...base, reply], 0, 4), 3); + for (const stopReason of [undefined, "length", "toolUse", "aborted", "error"]) { + assert.equal(completedTurnReplyIndex([...base, { ...reply, stopReason }], 0, 4), null, `${stopReason} is not a final reply`); + } + assert.equal(completedTurnReplyIndex([...base, { ...reply, errorMessage: "Provider failed" }], 0, 4), null); + assert.equal(completedTurnReplyIndex([...base, { ...reply, content: [{ type: "text", text: " " }] }], 0, 4), null); + assert.equal(completedTurnReplyIndex([...base, { ...preamble, stopReason: "stop" }], 0, 4), null); + assert.equal(completedTurnReplyIndex(base, 0, base.length), null); + assert.equal(completedTurnReplyIndex([...base, reply, passive("context")], 0, 5), 3); + assert.equal(completedTurnReplyIndex([...base, reply, { role: "developer", content: "Continue working" }], 0, 5), null); }); test("#136 a tail awaiting a tool result counts as a live foreign run", () => { diff --git a/lib/chat-transcript-plan.ts b/lib/chat-transcript-plan.ts index 0b8bdf8db..27b2c221f 100644 --- a/lib/chat-transcript-plan.ts +++ b/lib/chat-transcript-plan.ts @@ -10,12 +10,13 @@ import type { AgentMessage, AssistantContentBlock, AssistantMessage, CustomMessa * * Rows are appended in transcript order; a row is either: * - { kind: "message", index } — one message rendered standalone (messages - * before the first anchor, or a turn with nothing to fold) + * before the first anchor) * - { kind: "group", userIndex, endIndex, segments } — one anchored turn. Like - * the omp TUI, agent text is never hidden: the turn renders as its anchor + * the omp TUI, agent text is retained: the turn renders as its anchor * followed by `segments` in order, where each run of activity (thinking, * tool calls, notices) between two pieces of text folds into one collapsed - * row. A turn stays one row so the render-window math is unchanged. + * row. Completed turns can fold progress before their final reply. A turn + * stays one row so the render-window math is unchanged. */ /** A folded activity entry: the listed blocks of an assistant message, or a whole non-assistant message. */ @@ -53,6 +54,21 @@ export function isGroupAnchor(message: AgentMessage): boolean { return message.role === "custom" && (message as CustomMessage).customType === "compaction"; } +/** A normal stop with a real reply is required before folding progress. In + * particular, a tool preamble, truncated response or failed/aborted message + * is not a final reply. Unknown legacy stop reasons stay expanded. */ +export function completedTurnReplyIndex(messages: AgentMessage[], start: number, end: number): number | null { + for (let index = end - 1; index > start; index -= 1) { + const message = messages[index]; + if (isPassiveToolContext(message) || (message.role === "custom" && message.customType === "xdev-mount-notice")) continue; + if (message.role !== "assistant" || message.stopReason !== "stop" || message.errorMessage?.trim()) return null; + const blocks = getDisplayableAssistantBlocks(message); + if (blocks.some(block => block.type === "toolCall")) return null; + return blocks.some(block => block.type === "image" || (block.type === "text" && block.text.trim())) ? index : null; + } + return null; +} + /** Split one anchored turn into text and folded-activity segments. */ export function planTurnSegments( messages: AgentMessage[], @@ -115,7 +131,7 @@ export function planTurnSegments( flushOther(); // A provider error must stay visible: when the message ended in activity, // it gets its own (empty) text segment to carry the error. - if (assistant.errorMessage?.trim() && segments.at(-1) !== lastText) { + if ((assistant.errorMessage?.trim() || assistant.stopReason === "error" || assistant.stopReason === "aborted") && segments.at(-1) !== lastText) { lastText = { kind: "text", index: idx, blocks: [], last: false }; segments.push(lastText); activity = null; @@ -255,16 +271,14 @@ export function planTranscriptRows(messages: AgentMessage[], options: PlanOption const userIdx = idx; let endIdx = userIdx + 1; while (endIdx < messages.length && !isGroupAnchor(messages[endIdx])) endIdx += 1; - // "Never fold" plans standalone rows, so the render window counts every message. - const segments = options.neverFold ? [] : planTurnSegments(messages, userIdx, endIdx, options); - if (segments.some((segment) => segment.kind === "activity")) { - rows.push({ kind: "group", userIndex: userIdx, endIndex: endIdx, segments }); - } else { - // Nothing to fold: render the anchor and the rest as standalone messages. - // Tool results render under their tool call, as in the fold, so they get no row. + if (options.neverFold) { + // Keep standalone rows pageable when activity is never folded. for (let renderIdx = userIdx; renderIdx < endIdx; renderIdx++) { if (messages[renderIdx].role !== "toolResult") rows.push({ kind: "message", index: renderIdx }); } + } else { + const segments = planTurnSegments(messages, userIdx, endIdx, options); + rows.push({ kind: "group", userIndex: userIdx, endIndex: endIdx, segments }); } idx = endIdx; } diff --git a/lib/i18n/locales/en.json b/lib/i18n/locales/en.json index 2e38ee1bc..ed0d55aac 100644 --- a/lib/i18n/locales/en.json +++ b/lib/i18n/locales/en.json @@ -581,6 +581,13 @@ "chatWindow.messageCount.one": "{count} message", "chatWindow.messageCount.other": "{count} messages", "chatWindow.processDetails": "Process details", + "chatWindow.latestOutput": "Latest output", + "chatWindow.finalReply": "Final reply", + "chatWindow.turnProgress": "Task progress", + "chatWindow.outputCount.one": "{count} output", + "chatWindow.outputCount.other": "{count} outputs", + "chatWindow.expandProgress": "Expand", + "chatWindow.collapseProgress": "Collapse", "chatWindow.runningCommand": "Running command...", "chatWindow.runningNamed": "Running {names}...", "chatWindow.runningNamedMore": "Running {names} (+{more})...", diff --git a/lib/i18n/locales/ja.json b/lib/i18n/locales/ja.json index b29de7e0e..6d3e690e3 100644 --- a/lib/i18n/locales/ja.json +++ b/lib/i18n/locales/ja.json @@ -564,6 +564,13 @@ "chatWindow.messageCount.one": "{count} 件のメッセージ", "chatWindow.messageCount.other": "{count} 件のメッセージ", "chatWindow.processDetails": "プロセス詳細", + "chatWindow.latestOutput": "最新の出力", + "chatWindow.finalReply": "最終回答", + "chatWindow.turnProgress": "今回の進捗", + "chatWindow.outputCount.one": "{count} 件の出力", + "chatWindow.outputCount.other": "{count} 件の出力", + "chatWindow.expandProgress": "詳細を表示", + "chatWindow.collapseProgress": "折りたたむ", "chatWindow.runningCommand": "コマンドを実行中...", "chatWindow.runningNamed": "{names} を実行中...", "chatWindow.runningNamedMore": "{names}(+{more})を実行中...", diff --git a/lib/i18n/locales/zh-CN.json b/lib/i18n/locales/zh-CN.json index 46664f881..4cad402c5 100644 --- a/lib/i18n/locales/zh-CN.json +++ b/lib/i18n/locales/zh-CN.json @@ -564,6 +564,13 @@ "chatWindow.messageCount.one": "{count} 条消息", "chatWindow.messageCount.other": "{count} 条消息", "chatWindow.processDetails": "过程详情", + "chatWindow.latestOutput": "最新输出", + "chatWindow.finalReply": "最终答复", + "chatWindow.turnProgress": "本轮进展", + "chatWindow.outputCount.one": "{count} 条输出", + "chatWindow.outputCount.other": "{count} 条输出", + "chatWindow.expandProgress": "展开查看", + "chatWindow.collapseProgress": "收起", "chatWindow.runningCommand": "正在运行命令...", "chatWindow.runningNamed": "正在运行 {names}...", "chatWindow.runningNamedMore": "正在运行 {names}(+{more})...",