Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

TimelineAssistantRows.tsx

380 lines12.2 KB

1import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";
2import { type RunId } from "@t3tools/contracts";
3import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
4import { memo, use, useState } from "react";
5import { type ChatMessage, type TurnDiffSummary } from "../../types";
6import ChatMarkdown from "../ChatMarkdown";
7import { GitForkIcon } from "lucide-react";
8import { Button } from "../ui/button";
9import { ProposedPlanCard } from "./ProposedPlanCard";
10import { HtmlRenderFrame } from "./HtmlRenderFrame";
11import { McpAppFrame } from "./McpAppFrame";
12import { checkpointFileTotals } from "@t3tools/client-runtime/state/thread-checkpoints";
13import { ChangedFilesCard } from "./ChangedFilesTree";
14import { useFileContextMenuHandler } from "../../fileContextMenu";
15import { useAssistantMessageText, useProject, useThreadShell } from "../../state/entities";
16import { MessageCopyButton } from "./MessageCopyButton";
17import { AssistantCitationSource } from "./AssistantCitationSource";
18import { resolveAssistantMessageCopyState } from "./MessagesTimeline.logic";
19import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
20import { cn } from "~/lib/utils";
21import { useUiStateStore } from "~/uiStateStore";
22import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
23import { useV2ItemSupport } from "../../state/v2ItemSupport";
24import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext";
25import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts";
26​
27export function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
28 const ctx = use(TimelineRowCtx);
29 // The timeline holds a streaming message's row while only its text grows.
30 const liveText = useAssistantMessageText(
31 row.message.streaming ? ctx.threadRef : null,
32 row.projectedItem?.item.id,
33 );
34 const text = liveText ?? row.message.text;
35 const messageText = text || (row.message.streaming ? "" : "(empty response)");
36​
37 return (
38 <>
39 <div className="relative min-w-0 px-1 py-0.5">
40 <MessageAuthorHeading>T3 Code</MessageAuthorHeading>
41 <div data-thread-find-text="true">
42 <AssistantCitationSource
43 messageId={row.message.id}
44 {...(ctx.threadRef ? { threadRef: ctx.threadRef } : {})}
45 itemKey={row.id}
46 request={ctx.citationRequest}
47 listRef={ctx.listRef}
48 >
49 <ChatMarkdown
50 text={messageText}
51 cwd={ctx.markdownCwd}
52 threadRef={ctx.threadRef ?? undefined}
53 isStreaming={Boolean(row.message.streaming)}
54 lineBreaks={shouldPreserveAssistantLineBreaks(messageText)}
55 skills={ctx.skills}
56 headingLevelOffset={MESSAGE_HEADING_LEVEL}
57 onUseArtifactTemplate={ctx.onUseArtifactTemplate}
58 onRunShellCommand={ctx.onRunShellCommand}
59 onImageExpand={ctx.onImageExpand}
60 />
61 </AssistantCitationSource>
62 </div>
63 {ctx.onOpenTurnDiff ? (
64 <AssistantChangedFilesSection
65 turnSummary={row.assistantTurnDiffSummary}
66 routeThreadKey={ctx.routeThreadKey}
67 resolvedTheme={ctx.resolvedTheme}
68 onOpenTurnDiff={ctx.onOpenTurnDiff}
69 />
70 ) : null}
71 {row.showAssistantMeta ? (
72 <AssistantMessageMeta
73 className="mt-1.5"
74 projectedItem={row.projectedItem}
75 message={row.message}
76 showCopyButton={row.showAssistantCopyButton}
77 copyStreaming={row.assistantCopyStreaming}
78 />
79 ) : null}
80 </div>
81 </>
82 );
84​
85function AssistantForkButton({
86 projectedItem,
87}: {
88 readonly projectedItem: NonNullable<Extract<TimelineRow, { kind: "message" }>["projectedItem"]>;
89}) {
90 const ctx = use(TimelineRowCtx);
91 const [busy, setBusy] = useState(false);
92 const support = useV2ItemSupport({
93 environmentId: ctx.activeThreadEnvironmentId,
94 sourceThreadId: projectedItem.sourceThreadId,
95 sourceItemId: projectedItem.sourceItemId,
96 });
97 const canFork = canForkProjectedAssistantItem({
98 projectedItem,
99 capabilities: support.providerSession?.capabilities,
100 });
101​
102 const onForkFromRun = ctx.onForkFromRun;
103 if (!canFork || onForkFromRun === undefined || projectedItem.item.runId === null) return null;
104 const runId = projectedItem.item.runId;
105​
106 return (
107 <Tooltip>
108 <TooltipTrigger
109 render={
110 <Button
111 type="button"
112 size="xs"
113 variant="ghost"
114 disabled={busy}
115 onClick={() => {
116 setBusy(true);
117 void onForkFromRun({ sourceThreadId: projectedItem.sourceThreadId, runId }).finally(
118 () => setBusy(false),
119 );
120 }}
121 aria-label="Fork from this response"
122 />
123 }
124 >
125 <GitForkIcon className={cn("size-3", busy && "animate-pulse")} />
126 </TooltipTrigger>
127 <TooltipPopup side="top">Fork from this response</TooltipPopup>
128 </Tooltip>
129 );
131​
132export function AssistantMetaTimelineRow({
133 row,
134}: {
135 row: Extract<TimelineRow, { kind: "assistant-meta" }>;
136}) {
137 return (
138 <div className="px-1">
139 <AssistantMessageMeta
140 className="mt-0.5"
141 projectedItem={row.projectedItem}
142 message={row.message}
143 showCopyButton={row.showAssistantCopyButton}
144 copyStreaming={row.assistantCopyStreaming}
145 alwaysVisible
146 />
147 </div>
148 );
150​
151function AssistantMessageMeta({
152 className,
153 projectedItem,
154 message,
155 showCopyButton,
156 copyStreaming,
157 alwaysVisible = false,
158}: {
159 className?: string;
160 projectedItem?: Extract<TimelineRow, { kind: "message" }>["projectedItem"];
161 message: ChatMessage;
162 showCopyButton: boolean;
163 copyStreaming: boolean;
164 alwaysVisible?: boolean;
165}) {
166 const ctx = use(TimelineRowCtx);
167​
168 return (
169 <div
170 className={cn(
171 "flex items-center gap-2 text-xs tabular-nums transition-opacity duration-200",
172 alwaysVisible
173 ? "opacity-100"
174 : "opacity-0 pointer-coarse:opacity-100 focus-within:opacity-100 group-hover/assistant:opacity-100",
175 className,
176 )}
177 >
178 {projectedItem && projectedItem.item.status !== "completed" ? (
179 <span className="rounded-full border border-border/70 px-1.5 py-0.5 font-mono text-3xs text-muted-foreground">
180 {projectedItem.item.status}
181 </span>
182 ) : null}
183 <AssistantCopyButton
184 message={message}
185 showCopyButton={showCopyButton}
186 streaming={copyStreaming}
187 />
188 {projectedItem?.item.type === "assistant_message" ? (
189 <AssistantForkButton projectedItem={projectedItem} />
190 ) : null}
191 {!message.streaming && (
192 <Tooltip>
193 <TooltipTrigger render={<p className="text-muted-foreground text-xs tabular-nums" />}>
194 {formatDayAwareTimestamp(message.updatedAt, ctx.timestampFormat)}
195 </TooltipTrigger>
196 <TooltipPopup>
197 {formatChatTimestampTooltip(message.updatedAt, ctx.timestampFormat)}
198 </TooltipPopup>
199 </Tooltip>
200 )}
201 </div>
202 );
204​
205function AssistantCopyButton({
206 message,
207 showCopyButton,
208 streaming,
209}: {
210 message: ChatMessage;
211 showCopyButton: boolean;
212 streaming: boolean;
213}) {
214 const assistantCopyState = resolveAssistantMessageCopyState({
215 text: message.text ?? null,
216 showCopyButton,
217 streaming,
218 });
219​
220 if (!assistantCopyState.visible) {
221 return null;
222 }
223​
224 return <MessageCopyButton text={assistantCopyState.text ?? ""} variant="ghost" />;
226​
227export function ProposedPlanTimelineRow({
228 row,
229}: {
230 row: Extract<TimelineRow, { kind: "proposed-plan" }>;
231}) {
232 const ctx = use(TimelineRowCtx);
233​
234 return (
235 <div className="min-w-0 px-1 py-0.5">
236 <ProposedPlanCard
237 planMarkdown={row.proposedPlan.planMarkdown}
238 environmentId={ctx.activeThreadEnvironmentId}
239 threadRef={ctx.threadRef ?? undefined}
240 cwd={ctx.markdownCwd}
241 workspaceRoot={ctx.workspaceRoot}
242 findActive={ctx.findActive}
243 />
244 </div>
245 );
247​
248export function HtmlRenderTimelineRow({
249 row,
250}: {
251 row: Extract<TimelineRow, { kind: "html-render" }>;
252}) {
253 const ctx = use(TimelineRowCtx);
254 const { onAppFullscreenChange } = ctx;
255 const onFullscreenChange = (fullscreen: boolean) => onAppFullscreenChange(row.id, fullscreen);
256​
257 if (ctx.renderHtmlRender) {
258 return <div className="min-w-0 px-1">{ctx.renderHtmlRender(row)}</div>;
259 }
260 return (
261 <div className="min-w-0 px-1">
262 <HtmlRenderFrame
263 key={row.htmlRender.attachmentId}
264 environmentId={ctx.activeThreadEnvironmentId}
265 htmlRender={row.htmlRender}
266 threadRef={ctx.threadRef ?? undefined}
267 onFullscreenChange={onFullscreenChange}
268 />
269 </div>
270 );
272​
273export function McpAppTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mcp-app" }> }) {
274 const ctx = use(TimelineRowCtx);
275 const { awaitingUser } = use(TimelineRowActivityCtx);
276​
277 return (
278 <div className="min-w-0 px-1">
279 <McpAppFrame
280 key={row.mcpApp.attachmentId}
281 environmentId={ctx.activeThreadEnvironmentId}
282 threadId={row.sourceThreadId}
283 conversationThreadId={ctx.threadRef?.threadId ?? row.sourceThreadId}
284 itemId={row.itemId}
285 revision={row.revision}
286 app={row.mcpApp}
287 onSendMessage={ctx.onSendAppMessage}
288 awaitingUser={awaitingUser}
289 onFullscreenChange={(fullscreen) => ctx.onAppFullscreenChange(row.id, fullscreen)}
290 />
291 </div>
292 );
294​
295/** Subscribes directly to the UI state store for expand/collapse state,
296 * so toggling re-renders only this component — not the entire list. */
297const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection({
298 turnSummary,
299 routeThreadKey,
300 resolvedTheme,
301 onOpenTurnDiff,
302}: {
303 turnSummary: TurnDiffSummary | undefined;
304 routeThreadKey: string;
305 resolvedTheme: "light" | "dark";
306 displayThreadKey?: string;
307 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
308}) {
309 if (!turnSummary) return null;
310 const checkpointFiles = turnSummary.files;
311 if (checkpointFiles.length === 0) return null;
312​
313 return (
314 <AssistantChangedFilesSectionInner
315 turnSummary={turnSummary}
316 checkpointFiles={checkpointFiles}
317 routeThreadKey={routeThreadKey}
318 resolvedTheme={resolvedTheme}
319 onOpenTurnDiff={onOpenTurnDiff}
320 />
321 );
322});
323​
324function AssistantChangedFilesSectionInner({
325 turnSummary,
326 checkpointFiles,
327 routeThreadKey,
328 resolvedTheme,
329 onOpenTurnDiff,
330}: {
331 turnSummary: TurnDiffSummary;
332 checkpointFiles: TurnDiffSummary["files"];
333 routeThreadKey: string;
334 resolvedTheme: "light" | "dark";
335 displayThreadKey?: string;
336 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
337}) {
338 const ctx = use(TimelineRowCtx);
339 const persistedExpanded = useUiStateStore(
340 (store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.runId],
341 );
342 const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
343 const allDirectoriesExpanded = persistedExpanded ?? false;
344​
345 const thread = useThreadShell(ctx.threadRef);
346 const activeProject = useProject(
347 thread && thread.projectId
348 ? { environmentId: thread.environmentId, projectId: thread.projectId }
349 : null,
350 );
351 const onFileContextMenu = useFileContextMenuHandler(ctx.activeThreadEnvironmentId);
352​
353 return (
354 <ChangedFilesCard
355 runId={turnSummary.runId}
356 files={checkpointFiles}
357 totals={checkpointFileTotals(turnSummary)}
358 allDirectoriesExpanded={allDirectoriesExpanded}
359 resolvedTheme={resolvedTheme}
360 onToggleAllDirectories={() =>
361 setExpanded(routeThreadKey, turnSummary.runId, !allDirectoriesExpanded)
362 }
363 onOpenTurnDiff={onOpenTurnDiff}
364 onFileContextMenu={(filePath, event) =>
365 onFileContextMenu(
366 {
367 environmentId: ctx.activeThreadEnvironmentId,
368 filePath,
369 workspaceRoot: ctx.workspaceRoot,
370 repositoryRoot:
371 thread?.worktreePath == null
372 ? activeProject?.repositoryIdentity?.rootPath
373 : undefined,
374 },
375 event,
376 )
377 }
378 />
379 );