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

TimelineAssistantRows.tsx

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