import type { MouseEvent, ScrollBoxRenderable } from "@opentui/core"; import type { ProviderApprovalDecision, ThreadId, TurnItemId } from "@t3tools/contracts"; import { formatWorkingDurationLabel } from "@t3tools/client-runtime/state/models"; import { liveThoughtLine, workEntryDisplayIndicatesToolFailure, type ToolGroupSummaryKind } from "@t3tools/client-runtime/work-log/presentation"; import { memo, useEffect, useState, type RefObject } from "react"; import { findTextSegments } from "../model/search.ts"; import { findThreadSearchOccurrences } from "@t3tools/shared/threadSearch"; import type { OrchestrationV2SearchThreadResult } from "@t3tools/contracts"; import { FindText } from "./FindText.tsx"; import { Button, Buttons, isLeftClick, isRightClick, useHover } from "./Button.tsx"; import { checkpointFileTotals, type ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; import { formatDuration } from "@t3tools/shared/orchestrationTiming"; import type { Tui3Config } from "../config.ts"; import { CommandOutput } from "./CommandOutput.tsx"; import { BAR } from "./edges.ts"; import type { T3Session, ThreadHistory } from "../client/session.ts"; import { liveWorkEntryLabel, workEntryDisplayLabel, type MessagesTimelineRow, type Timeline, type WorkLogEntry } from "../model/timeline.ts"; import { blockFor } from "../model/transcript.ts"; import { firstLine } from "./text.ts"; import { colors, getMarkdownStyle, toneColor } from "./theme.ts"; /** What a right-click in the conversation was on. */ export type ConversationTarget = | { readonly kind: "message"; readonly messageId: string; readonly role: "user" | "assistant" | "system"; readonly text: string; readonly checkpointTurnCount?: number } /** `omitted`: the server left the output out of the thread; `source` is where to fetch it. */ | { readonly kind: "command"; readonly command: string; readonly output: string; readonly omitted: boolean; readonly source: { readonly threadId: ThreadId; readonly itemId: TurnItemId } | null }; export interface ConversationMouse { readonly respond: (decision: ProviderApprovalDecision) => void; /** A click on a prompt: the turn cursor, as [ and ] move it. */ readonly selectTurn: (messageId: string) => void; /** A click on a folded turn or work group: its own expansion, apart from e. */ readonly toggleFold: (id: string) => void; readonly loadEarlier: () => void; readonly menu: (target: ConversationTarget) => void; /** A click on a changed file: that turn's diff. */ readonly openTurnDiff: (checkpointTurnCount: number) => void; } /** The conversation, row for row as the web app derives it (MessagesTimeline.logic). */ export function ThreadView(props: { readonly timeline: Timeline | null; readonly findQuery?: string | undefined; readonly findMatch?: OrchestrationV2SearchThreadResult["match"] | undefined; readonly selectedMessageId: string | null; readonly session: T3Session; readonly streamCommandOutput: boolean; readonly history: ThreadHistory | null; readonly loading: boolean; readonly error?: string | undefined; readonly workspaceRoot: string | undefined; readonly timestampFormat: Tui3Config["timestampFormat"]; readonly now: number; readonly scrollRef: RefObject; /** For a subagent or fork: the thread it came from, shown as a link in the header. */ readonly parent?: { readonly title: string; readonly threadId: ThreadId } | undefined; /** Opens another thread: a subagent from its work row, or the parent from the header. Keep it stable; rows are memoized on it. */ readonly onOpenThread: (threadId: ThreadId) => void; /** The mouse in the conversation. Keep these stable too. */ readonly mouse: ConversationMouse; }) { const { timeline, history } = props; const pendingIds = new Set(timeline?.pending.approvals.map((approval) => approval.requestId) ?? []); return ( {props.parent ? ( props.onOpenThread(props.parent!.threadId)}> {`↰ ${props.parent.title} (u)`} ) : null} {props.error ? {props.error} : null} {props.loading && !timeline ? Loading… : null} {history?.hasMore || history?.error ? : null} {timeline?.rows.map((row) => ( ))} ); } /** * The turn footer's text: model, how long the run took, and when the reply * landed, day-aware as the web's is. Parts a row doesn't carry are left out; * only a finished turn's last reply (or its detached meta row) gets one. */ function assistantFooter(row: MessagesTimelineRow, timeline: Timeline, timestampFormat: Tui3Config["timestampFormat"], now: number): string { const message = row.kind === "assistant-meta" ? row.message : row.kind === "message" && row.showAssistantMeta ? row.message : null; if (message?.role !== "assistant" || message.streaming) return ""; const meta = message.runId ? timeline.runMeta.get(message.runId) : undefined; const projected = row.kind === "message" || row.kind === "assistant-meta" ? row.projectedItem : undefined; const status = projected && projected.item.status !== "completed" ? projected.item.status : ""; const parts = [ meta?.model && meta.model !== "default" ? meta.model : "", meta?.durationMs !== null && meta?.durationMs !== undefined ? formatDuration(meta.durationMs) : "", dayAwareTime(message.updatedAt, timestampFormat, now), status, ]; return parts.filter(Boolean).join(" · "); } /** The web's day-aware timestamp: a time today, "yesterday at …", then a short date. */ function dayAwareTime(iso: string, format: Tui3Config["timestampFormat"], now: number): string { const date = new Date(iso); if (Number.isNaN(date.getTime())) return ""; const time = date.toLocaleTimeString(undefined, { hour: "numeric", minute: "2-digit", ...(format === "locale" ? {} : { hour12: format === "12-hour" }) }); const today = new Date(now); const dayDiff = Math.round((new Date(today.getFullYear(), today.getMonth(), today.getDate()).getTime() - new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime()) / 86_400_000); if (dayDiff <= 0) return time; if (dayDiff === 1) return `yesterday at ${time}`; const day = date.toLocaleDateString(undefined, { month: "numeric", day: "numeric", ...(date.getFullYear() === today.getFullYear() ? {} : { year: "numeric" as const }) }); return `${day} ${time}`; } function LoadEarlier({ history, onLoad }: { readonly history: ThreadHistory; readonly onLoad: () => void }) { const label = history.loading ? "Loading earlier turns…" : history.error ? `Could not load earlier turns: ${history.error} (o to retry)` : "Load earlier turns (o)"; return ; } function Divider({ label, color, onPress }: { readonly label: string; readonly color: string; readonly onPress?: (() => void) | undefined }) { const [hover, hoverProps] = useHover(); return ( isLeftClick(event) && onPress() } : {})}> {` ${label} `} ); } /** * Memoized: computeStableMessagesTimelineRows keeps unchanged rows identical, * so a streamed update re-renders only its own rows. `now` is nonzero only for * the working row, which ticks. */ const Row = memo(function Row(props: { readonly row: MessagesTimelineRow; readonly selected: boolean; readonly session: T3Session; readonly streamCommandOutput: boolean; readonly scrollRef: RefObject; readonly findQuery: string; readonly activeOccurrence: number | null; readonly pending: boolean; readonly workspaceRoot: string | undefined; /** The turn footer's text for this row, or "" for none. */ readonly footer: string; readonly now: number; readonly workStartedAt: string | null; readonly onOpenThread: (threadId: ThreadId) => void; readonly mouse: ConversationMouse; }) { const { row, workspaceRoot, mouse } = props; switch (row.kind) { case "message": { const { message } = row; if (props.findQuery) { const segments = findTextSegments(message.text, message.role === "user"); if (segments.some((segment) => findThreadSearchOccurrences(segment, props.findQuery).length > 0)) return ; } const summary = row.assistantTurnDiffSummary; const menu = { kind: "message", messageId: message.id, role: message.role, text: message.text, ...(summary && summary.files.length > 0 ? { checkpointTurnCount: summary.checkpointTurnCount } : {}) } as const; if (message.role === "user") return mouse.selectTurn(message.id)} onMenu={() => mouse.menu(menu)} />; if (message.role === "system") return isRightClick(event) && mouse.menu(menu)}>{message.text}; return ( isRightClick(event) && mouse.menu(menu)}> {summary && summary.files.length > 0 ? : null} {props.footer ? {props.footer} : null} ); } case "assistant-meta": return props.footer ? {props.footer} : null; case "turn-fold": case "attempt-fold": // The finished turn's work, folded: the web's turn separator. return ( mouse.toggleFold(row.kind === "turn-fold" ? row.runId : row.attemptId)}> {(hover) => {`${row.label} ${row.expanded ? "⌄" : "›"}`}} ); case "work-toggle": return ( mouse.toggleFold(row.groupId)}> {(hover) => ( {SUMMARY_GLYPH[row.summaryKind] ?? "•"} {` ${row.summary} ${row.expanded ? "⌄" : "›"}`} )} ); case "work": return ( {row.groupedEntries.map((entry) => ( ))} ); case "work-live": return ( {row.thought?.detail ? {`∴ ${liveThoughtLine(row.thought.detail)}`} : null} ); case "working": { const since = props.workStartedAt ? Date.parse(props.workStartedAt) : NaN; const verb = row.compacting ? "Compacting" : "Working"; return ( ◐ {Number.isFinite(since) ? ` ${verb} for ${formatWorkingDurationLabel(props.now - since)}` : ` ${verb}…`} ); } case "thinking": return ∴ Thinking…; case "context-compaction": return ; case "proposed-plan": if (props.findQuery) return ; return ( Plan ); case "event": return ; case "worktree-setup": return ( ◐ {" Setting up worktree…"} ); default: // html-render, mcp-app: nothing a terminal can show. return null; } }); /** The files a turn changed, folded to one line; a file opens that turn's diff. */ function ChangedFiles({ summary, onOpenTurnDiff }: { readonly summary: ThreadCheckpointSummary; readonly onOpenTurnDiff: (checkpointTurnCount: number) => void }) { const [open, setOpen] = useState(false); const [hover, hoverProps] = useHover(); const totals = checkpointFileTotals(summary); const hidden = totals.count - summary.files.length; const openDiff = () => onOpenTurnDiff(summary.checkpointTurnCount); return ( isLeftClick(event) && setOpen(!open)}> ✎ {` ${totals.count} ${totals.count === 1 ? "file" : "files"} `} {` ${open ? "⌄" : "›"}`} {open ? ( {summary.files.map((file) => ( ))} {hidden > 0 ? ( isLeftClick(event) && openDiff()}> {`… ${hidden} more ${hidden === 1 ? "file" : "files"}`} ) : null} ) : null} ); } function ChangedFile({ path, additions, deletions, onPress }: { readonly path: string; readonly additions: number; readonly deletions: number; readonly onPress: () => void }) { const [hover, hoverProps] = useHover(); return ( isLeftClick(event) && onPress()}> {path} ); } /** `+42 −7`, each count in its own colour; a zero count is left out. */ function DiffCounts({ additions, deletions }: { readonly additions: number; readonly deletions: number }) { if (additions === 0 && deletions === 0) return null; return ( {additions > 0 ? {`+${additions}`} : null} {additions > 0 && deletions > 0 ? " " : ""} {deletions > 0 ? {`−${deletions}`} : null} ); } const USER_FOLD_LINES = 8; const USER_FOLD_CHARS = 600; /** Your message: a full-width raised block, folded past 8 lines or 600 characters. */ function UserMessage({ text, messageId, selected, onSelect, onMenu }: { readonly text: string; readonly messageId: string; readonly selected: boolean; readonly onSelect: () => void; readonly onMenu: () => void }) { const [hover, hoverProps] = useHover(); const trimmed = text.trim(); const lines = trimmed.split("\n"); let shown = lines.slice(0, USER_FOLD_LINES).join("\n"); if (shown.length > USER_FOLD_CHARS) shown = `${shown.slice(0, USER_FOLD_CHARS).trimEnd()}…`; const folded = shown.length < trimmed.length; return ( (isRightClick(event) ? onMenu() : isLeftClick(event) ? onSelect() : undefined)}> {shown} {folded ? {`… ${Math.max(1, lines.length - shown.split("\n").length)} more lines`} : null} ); } /** Output the server left out of the thread, fetched when its row opens. */ function OmittedOutput({ session, source }: { readonly session: T3Session; readonly source: { readonly threadId: ThreadId; readonly itemId: TurnItemId } | null }) { const [state, setState] = useState<{ readonly text: string } | { readonly error: string } | null>(null); const threadId = source?.threadId; const itemId = source?.itemId; useEffect(() => { if (!threadId || !itemId) return; let cancelled = false; session.turnItem(threadId, itemId).then( (item) => !cancelled && setState({ text: item?.type === "command_execution" ? (item.output ?? "") : "" }), (error) => !cancelled && setState({ error: error instanceof Error ? error.message : String(error) }), ); return () => { cancelled = true; }; }, [session, threadId, itemId]); if (!source) return The output wasn't sent with the thread.; if (!state) return Loading output…; if ("error" in state) return {`Could not load the output: ${state.error}`}; return {state.text || "No output."}; } function WorkEntry({ entry, expanded: groupExpanded, label, onOpenThread, onMenu, session, streamCommandOutput, scrollRef }: { readonly entry: WorkLogEntry; readonly expanded: boolean; readonly label: string; readonly onOpenThread: (threadId: ThreadId) => void; readonly onMenu: (target: ConversationTarget) => void; readonly session: T3Session; readonly streamCommandOutput: boolean; readonly scrollRef: RefObject }) { const [open, setExpanded] = useState(null); const [hover, hoverProps] = useHover(); const expanded = open ?? groupExpanded; const item = entry.structuredPayload; const command = item?.type === "command_execution" ? item : null; const projected = entry.projectedItem; const failed = workEntryDisplayIndicatesToolFailure(entry); const child = childThreadOf(entry); const glyphColor = failed || entry.tone === "error" ? colors.bad : child ? colors.accent : colors.faint; const clickable = Boolean(command || child); const labelColor = clickable && hover ? colors.text : entry.tone === "thinking" ? colors.faint : colors.muted; const text = ( {failed ? "✕" : glyphFor(entry)} {` ${firstLine(label)}${child ? " ↗" : ""}`} ); const source = projected ? { threadId: projected.sourceThreadId, itemId: projected.sourceItemId } : null; const streaming = expanded && streamCommandOutput && source !== null; if (command) return (isRightClick(event) ? onMenu({ kind: "command", command: command.input, output: command.output ?? "", omitted: command.outputOmitted === true, source }) : isLeftClick(event) ? setExpanded(!expanded) : undefined)}>{expanded ? "⌄ " : "› "}{text} {expanded ? ( {`$ ${command.input}`} {streaming ? : command.outputOmitted ? : {command.output || "No output."}} ) : null} ; return child ? isLeftClick(event) && onOpenThread(child)}>{text} : text; } /** The thread a subagent work row ran in, when it has its own. */ export function childThreadOf(entry: WorkLogEntry): ThreadId | null { const item = entry.structuredPayload; return item?.type === "subagent" ? (item.childThreadId ?? null) : null; } function EventRow({ item, pending, onRespond }: { readonly onRespond: (decision: ProviderApprovalDecision) => void; readonly item: MessagesTimelineRow extends infer R ? (R extends { kind: "event"; projectedItem: { item: infer I } } ? I : never) : never; readonly pending: boolean }) { if (item.type === "approval_request" && pending) { return ( {approvalTitle(item.requestKind)} {item.prompt ? {item.prompt} : null} {item.reason ? {item.reason} : null}