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

TimelineAssistantRows.tsx

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