import type { MouseEvent, ScrollBoxRenderable } from "@opentui/core"; import type { ProviderApprovalDecision, ThreadId } 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, 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 { CommandOutput } from "./CommandOutput.tsx"; 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 kind: "command"; readonly command: string; readonly output: string }; 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; } /** The conversation, row for row as the web app derives it (MessagesTimeline.logic). */ export function ThreadView(props: { readonly project: string; readonly title: string; readonly detail: string; 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 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.project ? `${props.project} / ` : ""} {props.title} {props.detail} {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) => ( ))} ); } 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; 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 menu = { kind: "message", messageId: message.id, role: message.role, text: message.text } 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)}> ); } 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)} border> {(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: // assistant-meta, html-render, mcp-app: nothing a terminal can show. return null; } }); const USER_FOLD_LINES = 8; const USER_FOLD_CHARS = 600; /** The web's user bubble: right-aligned, at most 80% wide, 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} ); } 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 tone = failed || entry.tone === "error" ? colors.bad : child ? colors.accent : entry.tone === "thinking" ? colors.faint : colors.muted; const clickable = Boolean(command || child); const text = {`${failed ? "✕" : glyphFor(entry)} ${firstLine(label)}${child ? " ↗" : ""}`}; if (command) return (isRightClick(event) ? onMenu({ kind: "command", command: command.input, output: command.output ?? "" }) : isLeftClick(event) ? setExpanded(!expanded) : undefined)}>{expanded ? "⌄ " : "› "}{text} {expanded && streamCommandOutput && projected ? : expanded ? {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}