Open History to see the last commit
1import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/assistantInsights";
2import { MessageId, type TurnItemId } from "@t3tools/contracts";
3import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
4import { agentWorkingDirectories } from "@t3tools/client-runtime/workspace-basename-lookup";
5import { T, useGT, useMessages } from "gt-react";
6import { use, useState } from "react";
7import { type ChatMessage } from "../../types";
8import ChatMarkdown from "../ChatMarkdown";
9import { GitForkIcon, ReplyIcon } from "lucide-react";
10import { captureAssistantMessageOpening } from "~/lib/assistantTextSelection";
11import { responseContextRecord } from "~/lib/composerContextRecords";
12import { Button } from "../ui/button";
13import { ProposedPlanCard } from "./ProposedPlanCard";
14import { HtmlRenderFrame } from "./HtmlRenderFrame";
15import { McpAppFrame } from "./McpAppFrame";
16import { readResponseSubagents, useAssistantMessageText } from "../../state/entities";
17import { MessageCopyButton } from "./MessageCopyButton";
18import { AssistantCitationSource } from "./AssistantCitationSource";
19import { resolveAssistantMessageCopyState } from "./MessagesTimeline.logic";
20import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
21import { cn } from "~/lib/utils";
22import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
23import { readThreadTurnItems } from "../../state/entities";
24import { useV2ItemSupport } from "../../state/v2ItemSupport";
25import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext";
26import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts";
27
28export function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
29 const ctx = use(TimelineRowCtx);
30 const gt = useGT();
31 // The timeline holds a streaming message's row while only its text grows.
32 const liveText = useAssistantMessageText(
33 row.message.streaming ? ctx.threadRef : null,
34 row.projectedItem?.item.id,
35 );
36 const text = liveText ?? row.message.text;
37 const messageText =
38 text || (row.message.streaming || row.suppressEmptyResponse ? "" : gt("(empty response)"));
39
40 return (
41 <>
42 <div className="relative min-w-0 px-1 py-0.5">
43 <MessageAuthorHeading>T3 Code</MessageAuthorHeading>
44 <div data-thread-find-text="true">
45 <AssistantCitationSource
46 messageId={row.message.id}
47 {...(ctx.threadRef ? { threadRef: ctx.threadRef } : {})}
48 itemKey={row.id}
49 request={ctx.citationRequest}
50 listRef={ctx.listRef}
51 >
52 <ChatMarkdown
53 text={messageText}
54 renderInsights
55 cwd={ctx.markdownCwd}
56 agentDirectories={() =>
57 ctx.threadRef && row.projectedItem
58 ? agentWorkingDirectories(readThreadTurnItems(ctx.threadRef), row.projectedItem)
59 : []
60 }
61 threadRef={ctx.threadRef ?? undefined}
62 isStreaming={Boolean(row.message.streaming)}
63 lineBreaks={shouldPreserveAssistantLineBreaks(messageText)}
64 skills={ctx.skills}
65 headingLevelOffset={MESSAGE_HEADING_LEVEL}
66 onUseArtifactTemplate={ctx.onUseArtifactTemplate}
67 onRunShellCommand={ctx.onRunShellCommand}
68 onImageExpand={ctx.onImageExpand}
69 />
70 </AssistantCitationSource>
71 </div>
72 {!row.showAssistantMeta && row.projectedItem?.item.status === "interrupted" ? (
73 <div className="mt-1.5 flex">
74 <AssistantStatusBadge status="interrupted" />
75 </div>
76 ) : null}
77 {row.showAssistantMeta ? (
78 <AssistantMessageMeta
79 className="mt-1.5"
80 projectedItem={row.projectedItem}
81 message={row.message}
82 showCopyButton={row.showAssistantCopyButton}
83 copyStreaming={row.assistantCopyStreaming}
84 />
85 ) : null}
86 </div>
87 </>
88 );
89}
90
91/** Text an agent sent with `send_to_user`, shown as its own words. */
92export function SentMessageTimelineRow({
93 row,
94}: {
95 row: Extract<TimelineRow, { kind: "sent-message" }>;
96}) {
97 const ctx = use(TimelineRowCtx);
98
99 return (
100 <div className="min-w-0 px-1 py-0.5">
101 <MessageAuthorHeading>T3 Code</MessageAuthorHeading>
102 {/* Sent messages have no message id; citations name their turn item instead. */}
103 <AssistantCitationSource
104 messageId={MessageId.make(row.id)}
105 {...(ctx.threadRef ? { threadRef: ctx.threadRef } : {})}
106 itemKey={row.id}
107 request={ctx.citationRequest}
108 listRef={ctx.listRef}
109 >
110 <ChatMarkdown
111 text={row.text}
112 cwd={ctx.markdownCwd}
113 threadRef={ctx.threadRef ?? undefined}
114 lineBreaks={shouldPreserveAssistantLineBreaks(row.text)}
115 skills={ctx.skills}
116 headingLevelOffset={MESSAGE_HEADING_LEVEL}
117 onUseArtifactTemplate={ctx.onUseArtifactTemplate}
118 onRunShellCommand={ctx.onRunShellCommand}
119 onImageExpand={ctx.onImageExpand}
120 />
121 </AssistantCitationSource>
122 </div>
123 );
124}
125
126function AssistantForkButton({
127 projectedItem,
128}: {
129 readonly projectedItem: NonNullable<Extract<TimelineRow, { kind: "message" }>["projectedItem"]>;
130}) {
131 const ctx = use(TimelineRowCtx);
132 const gt = useGT();
133 const [busy, setBusy] = useState(false);
134 const support = useV2ItemSupport({
135 environmentId: ctx.activeThreadEnvironmentId,
136 sourceThreadId: projectedItem.sourceThreadId,
137 sourceItemId: projectedItem.sourceItemId,
138 });
139 const canFork = canForkProjectedAssistantItem({
140 projectedItem,
141 capabilities: support.providerSession?.capabilities,
142 });
143
144 const onForkFromRun = ctx.onForkFromRun;
145 if (!canFork || onForkFromRun === undefined || projectedItem.item.runId === null) return null;
146 const runId = projectedItem.item.runId;
147
148 return (
149 <Tooltip>
150 <TooltipTrigger
151 render={
152 <Button
153 type="button"
154 size="xs"
155 variant="ghost"
156 disabled={busy}
157 onClick={() => {
158 setBusy(true);
159 void onForkFromRun({ sourceThreadId: projectedItem.sourceThreadId, runId }).finally(
160 () => setBusy(false),
161 );
162 }}
163 aria-label={gt("Fork from this response")}
164 />
165 }
166 >
167 <GitForkIcon className={cn("size-3", busy && "animate-pulse")} />
168 </TooltipTrigger>
169 <TooltipPopup side="top">
170 <T>Fork from this response</T>
171 </TooltipPopup>
172 </Tooltip>
173 );
174}
175
176export function AssistantMetaTimelineRow({
177 row,
178}: {
179 row: Extract<TimelineRow, { kind: "assistant-meta" }>;
180}) {
181 return (
182 <div className="px-1">
183 <AssistantMessageMeta
184 className="mt-0.5"
185 projectedItem={row.projectedItem}
186 message={row.message}
187 showCopyButton={row.showAssistantCopyButton}
188 copyStreaming={row.assistantCopyStreaming}
189 alwaysVisible
190 />
191 </div>
192 );
193}
194
195function AssistantMessageMeta({
196 className,
197 projectedItem,
198 message,
199 showCopyButton,
200 copyStreaming,
201 alwaysVisible = false,
202}: {
203 className?: string;
204 projectedItem?: Extract<TimelineRow, { kind: "message" }>["projectedItem"];
205 message: ChatMessage;
206 showCopyButton: boolean;
207 copyStreaming: boolean;
208 alwaysVisible?: boolean;
209}) {
210 const ctx = use(TimelineRowCtx);
211 const m = useMessages();
212
213 return (
214 <div
215 className={cn(
216 "flex items-center gap-2 text-xs tabular-nums transition-opacity duration-200",
217 alwaysVisible
218 ? "opacity-100"
219 : "opacity-0 pointer-coarse:opacity-100 focus-within:opacity-100 group-hover/assistant:opacity-100",
220 className,
221 )}
222 >
223 {projectedItem && projectedItem.item.status !== "completed" ? (
224 <AssistantStatusBadge status={projectedItem.item.status} />
225 ) : null}
226 <AssistantCopyButton
227 message={message}
228 showCopyButton={showCopyButton}
229 streaming={copyStreaming}
230 />
231 {projectedItem?.item.type === "assistant_message" ? (
232 <AssistantForkButton projectedItem={projectedItem} />
233 ) : null}
234 {!message.streaming && projectedItem ? (
235 <AssistantReplyButton message={message} itemId={projectedItem.sourceItemId} />
236 ) : null}
237 {!message.streaming && (
238 <Tooltip>
239 <TooltipTrigger render={<p className="text-muted-foreground text-xs tabular-nums" />}>
240 {formatDayAwareTimestamp(
241 message.updatedAt,
242 ctx.timestampFormat,
243 undefined,
244 undefined,
245 m,
246 )}
247 </TooltipTrigger>
248 <TooltipPopup>
249 {formatChatTimestampTooltip(message.updatedAt, ctx.timestampFormat, m)}
250 </TooltipPopup>
251 </Tooltip>
252 )}
253 </div>
254 );
255}
256
257function AssistantReplyButton({ message, itemId }: { message: ChatMessage; itemId: TurnItemId }) {
258 const ctx = use(TimelineRowCtx);
259 const gt = useGT();
260 const { threadRef, onReplyToResponse } = ctx;
261 if (!threadRef || !onReplyToResponse || !message.text.trim()) return null;
262
263 const reply = () => {
264 // The meta row can sit below trailing tool rows, so the message may be virtualized away.
265 const source = [
266 ...document.querySelectorAll<HTMLElement>("[data-assistant-citation-source]"),
267 ].find(
268 (element) =>
269 element.dataset.assistantCitationSource === message.id &&
270 element.dataset.assistantCitationThread === threadRef.threadId &&
271 element.dataset.assistantCitationEnvironment === threadRef.environmentId,
272 );
273 const opening = captureAssistantMessageOpening(source ?? null, message.text);
274 if (!opening) return;
275 onReplyToResponse(
276 responseContextRecord({
277 citation: { version: 1, ...threadRef, messageId: message.id, ...opening },
278 itemId,
279 subagents: readResponseSubagents(threadRef, itemId),
280 }),
281 );
282 };
283
284 return (
285 <Tooltip>
286 <TooltipTrigger
287 render={
288 <Button
289 type="button"
290 size="xs"
291 variant="ghost-muted"
292 onClick={reply}
293 aria-label={gt("Reply to this response")}
294 />
295 }
296 >
297 <ReplyIcon className="size-3" />
298 </TooltipTrigger>
299 <TooltipPopup side="top">
300 <T>Reply to this response</T>
301 </TooltipPopup>
302 </Tooltip>
303 );
304}
305
306function AssistantStatusBadge({ status }: { status: string }) {
307 return (
308 <span className="rounded-full border border-border/70 px-1.5 py-0.5 font-mono text-3xs text-muted-foreground">
309 {status}
310 </span>
311 );
312}
313
314function AssistantCopyButton({
315 message,
316 showCopyButton,
317 streaming,
318}: {
319 message: ChatMessage;
320 showCopyButton: boolean;
321 streaming: boolean;
322}) {
323 const assistantCopyState = resolveAssistantMessageCopyState({
324 text: message.text ?? null,
325 showCopyButton,
326 streaming,
327 });
328
329 if (!assistantCopyState.visible) {
330 return null;
331 }
332
333 return <MessageCopyButton text={assistantCopyState.text ?? ""} variant="ghost" />;
334}
335
336export function ProposedPlanTimelineRow({
337 row,
338}: {
339 row: Extract<TimelineRow, { kind: "proposed-plan" }>;
340}) {
341 const ctx = use(TimelineRowCtx);
342
343 return (
344 <div className="min-w-0 px-1 py-0.5">
345 <ProposedPlanCard
346 planMarkdown={row.proposedPlan.planMarkdown}
347 environmentId={ctx.activeThreadEnvironmentId}
348 threadRef={ctx.threadRef ?? undefined}
349 cwd={ctx.markdownCwd}
350 workspaceRoot={ctx.workspaceRoot}
351 findActive={ctx.findActive}
352 />
353 </div>
354 );
355}
356
357export function HtmlRenderTimelineRow({
358 row,
359}: {
360 row: Extract<TimelineRow, { kind: "html-render" }>;
361}) {
362 const ctx = use(TimelineRowCtx);
363 const { onAppFullscreenChange } = ctx;
364 const onFullscreenChange = (fullscreen: boolean) => onAppFullscreenChange(row.id, fullscreen);
365
366 if (ctx.renderHtmlRender) {
367 return <div className="min-w-0 px-1">{ctx.renderHtmlRender(row)}</div>;
368 }
369 return (
370 <div className="html-preview-lane min-w-0 px-1">
371 <HtmlRenderFrame
372 key={row.htmlRender.attachmentId}
373 environmentId={ctx.activeThreadEnvironmentId}
374 htmlRender={row.htmlRender}
375 threadRef={ctx.threadRef ?? undefined}
376 onFullscreenChange={onFullscreenChange}
377 />
378 </div>
379 );
380}
381
382export function McpAppTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mcp-app" }> }) {
383 const ctx = use(TimelineRowCtx);
384 const { awaitingUser } = use(TimelineRowActivityCtx);
385
386 return (
387 <div className="min-w-0 px-1">
388 <McpAppFrame
389 key={row.mcpApp.attachmentId}
390 environmentId={ctx.activeThreadEnvironmentId}
391 threadId={row.sourceThreadId}
392 conversationThreadId={ctx.threadRef?.threadId ?? row.sourceThreadId}
393 itemId={row.itemId}
394 revision={row.revision}
395 app={row.mcpApp}
396 onSendMessage={ctx.onSendAppMessage}
397 awaitingUser={awaitingUser}
398 onFullscreenChange={(fullscreen) => ctx.onAppFullscreenChange(row.id, fullscreen)}
399 />
400 </div>
401 );
402}