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

TimelineAssistantRows.tsx

390 lines12.5 KB

1import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";
2import { MessageId, 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 <AssistantCitationSource
263 messageId={MessageId.make(row.id)}
264 {...(ctx.threadRef ? { threadRef: ctx.threadRef } : {})}
265 itemKey={row.id}
266 request={ctx.citationRequest}
267 listRef={ctx.listRef}
268 htmlRender
269 >
270 <HtmlRenderFrame
271 // A recycled row must not keep another page's frozen frame.
272 key={row.htmlRender.attachmentId}
273 environmentId={ctx.activeThreadEnvironmentId}
274 htmlRender={row.htmlRender}
275 threadRef={ctx.threadRef ?? undefined}
276 onFullscreenChange={onFullscreenChange}
277 />
278 </AssistantCitationSource>
279 </div>
280 );
282​
283export function McpAppTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mcp-app" }> }) {
284 const ctx = use(TimelineRowCtx);
285 const { awaitingUser } = use(TimelineRowActivityCtx);
286​
287 return (
288 <div className="min-w-0 px-1">
289 <McpAppFrame
290 key={row.mcpApp.attachmentId}
291 environmentId={ctx.activeThreadEnvironmentId}
292 threadId={row.sourceThreadId}
293 conversationThreadId={ctx.threadRef?.threadId ?? row.sourceThreadId}
294 itemId={row.itemId}
295 revision={row.revision}
296 app={row.mcpApp}
297 onSendMessage={ctx.onSendAppMessage}
298 awaitingUser={awaitingUser}
299 onFullscreenChange={(fullscreen) => ctx.onAppFullscreenChange(row.id, fullscreen)}
300 />
301 </div>
302 );
304​
305/** Subscribes directly to the UI state store for expand/collapse state,
306 * so toggling re-renders only this component — not the entire list. */
307const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection({
308 turnSummary,
309 routeThreadKey,
310 resolvedTheme,
311 onOpenTurnDiff,
312}: {
313 turnSummary: TurnDiffSummary | undefined;
314 routeThreadKey: string;
315 resolvedTheme: "light" | "dark";
316 displayThreadKey?: string;
317 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
318}) {
319 if (!turnSummary) return null;
320 const checkpointFiles = turnSummary.files;
321 if (checkpointFiles.length === 0) return null;
322​
323 return (
324 <AssistantChangedFilesSectionInner
325 turnSummary={turnSummary}
326 checkpointFiles={checkpointFiles}
327 routeThreadKey={routeThreadKey}
328 resolvedTheme={resolvedTheme}
329 onOpenTurnDiff={onOpenTurnDiff}
330 />
331 );
332});
333​
334function AssistantChangedFilesSectionInner({
335 turnSummary,
336 checkpointFiles,
337 routeThreadKey,
338 resolvedTheme,
339 onOpenTurnDiff,
340}: {
341 turnSummary: TurnDiffSummary;
342 checkpointFiles: TurnDiffSummary["files"];
343 routeThreadKey: string;
344 resolvedTheme: "light" | "dark";
345 displayThreadKey?: string;
346 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
347}) {
348 const ctx = use(TimelineRowCtx);
349 const persistedExpanded = useUiStateStore(
350 (store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.runId],
351 );
352 const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
353 const allDirectoriesExpanded = persistedExpanded ?? false;
354​
355 const thread = useThreadShell(ctx.threadRef);
356 const activeProject = useProject(
357 thread && thread.projectId
358 ? { environmentId: thread.environmentId, projectId: thread.projectId }
359 : null,
360 );
361 const onFileContextMenu = useFileContextMenuHandler(ctx.activeThreadEnvironmentId);
362​
363 return (
364 <ChangedFilesCard
365 runId={turnSummary.runId}
366 files={checkpointFiles}
367 totals={checkpointFileTotals(turnSummary)}
368 allDirectoriesExpanded={allDirectoriesExpanded}
369 resolvedTheme={resolvedTheme}
370 onToggleAllDirectories={() =>
371 setExpanded(routeThreadKey, turnSummary.runId, !allDirectoriesExpanded)
372 }
373 onOpenTurnDiff={onOpenTurnDiff}
374 onFileContextMenu={(filePath, event) =>
375 onFileContextMenu(
376 {
377 environmentId: ctx.activeThreadEnvironmentId,
378 filePath,
379 workspaceRoot: ctx.workspaceRoot,
380 repositoryRoot:
381 thread?.worktreePath == null
382 ? activeProject?.repositoryIdentity?.rootPath
383 : undefined,
384 },
385 event,
386 )
387 }
388 />
389 );