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

TimelineAssistantRows.tsx

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