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

TimelineAssistantRows.tsx

506 lines16.4 KB

1import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";
2import { MessageId, type RunId, type TurnItemId } from "@t3tools/contracts";
3import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
4import { agentWorkingDirectories } from "@t3tools/client-runtime/workspace-basename-lookup";
5import { memo, use, useState } from "react";
6import { type ChatMessage, type TurnDiffSummary } from "../../types";
7import ChatMarkdown from "../ChatMarkdown";
8import { GitForkIcon, ReplyIcon } from "lucide-react";
9import { captureAssistantMessageOpening } from "~/lib/assistantTextSelection";
10import { responseContextRecord } from "~/lib/composerContextRecords";
11import { Button } from "../ui/button";
12import { ProposedPlanCard } from "./ProposedPlanCard";
13import { HtmlRenderFrame } from "./HtmlRenderFrame";
14import { McpAppFrame } from "./McpAppFrame";
15import { checkpointFileTotals } from "@t3tools/client-runtime/state/thread-checkpoints";
16import { ChangedFilesCard } from "./ChangedFilesTree";
17import { useFileContextMenuHandler } from "../../fileContextMenu";
18import {
19 readResponseSubagents,
20 useAssistantMessageText,
21 useProject,
22 useQuietThreadShell,
23} from "../../state/entities";
24import { MessageCopyButton } from "./MessageCopyButton";
25import { AssistantCitationSource } from "./AssistantCitationSource";
26import { resolveAssistantMessageCopyState } from "./MessagesTimeline.logic";
27import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
28import { cn } from "~/lib/utils";
29import { useUiStateStore } from "~/uiStateStore";
30import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
31import { readThreadTurnItems } from "../../state/entities";
32import { useV2ItemSupport } from "../../state/v2ItemSupport";
33import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext";
34import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts";
35import { useAtomValue } from "@effect/atom-react";
36import { AsyncResult, Atom } from "effect/reactivity";
37import { vcsEnvironment } from "../../state/vcs";
38​
39const NO_VCS_STATUS = Atom.make(AsyncResult.initial());
40​
41export function AssistantTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
42 const ctx = use(TimelineRowCtx);
43 // The timeline holds a streaming message's row while only its text grows.
44 const liveText = useAssistantMessageText(
45 row.message.streaming ? ctx.threadRef : null,
46 row.projectedItem?.item.id,
47 );
48 const text = liveText ?? row.message.text;
49 const messageText =
50 text || (row.message.streaming || row.suppressEmptyResponse ? "" : "(empty response)");
51​
52 return (
53 <>
54 <div className="relative min-w-0 px-1 py-0.5">
55 <MessageAuthorHeading>T3 Code</MessageAuthorHeading>
56 <div data-thread-find-text="true">
57 <AssistantCitationSource
58 messageId={row.message.id}
59 {...(ctx.threadRef ? { threadRef: ctx.threadRef } : {})}
60 itemKey={row.id}
61 request={ctx.citationRequest}
62 listRef={ctx.listRef}
63 >
64 <ChatMarkdown
65 text={messageText}
66 renderInsights
67 cwd={ctx.markdownCwd}
68 agentDirectories={() =>
69 ctx.threadRef && row.projectedItem
70 ? agentWorkingDirectories(readThreadTurnItems(ctx.threadRef), row.projectedItem)
71 : []
72 }
73 threadRef={ctx.threadRef ?? undefined}
74 isStreaming={Boolean(row.message.streaming)}
75 lineBreaks={shouldPreserveAssistantLineBreaks(messageText)}
76 skills={ctx.skills}
77 headingLevelOffset={MESSAGE_HEADING_LEVEL}
78 onUseArtifactTemplate={ctx.onUseArtifactTemplate}
79 onRunShellCommand={ctx.onRunShellCommand}
80 onImageExpand={ctx.onImageExpand}
81 />
82 </AssistantCitationSource>
83 </div>
84 {ctx.onOpenTurnDiff ? (
85 <AssistantChangedFilesSection
86 turnSummary={row.assistantTurnDiffSummary}
87 routeThreadKey={ctx.routeThreadKey}
88 resolvedTheme={ctx.resolvedTheme}
89 onOpenTurnDiff={ctx.onOpenTurnDiff}
90 />
91 ) : null}
92 {!row.showAssistantMeta && row.projectedItem?.item.status === "interrupted" ? (
93 <div className="mt-1.5 flex">
94 <AssistantStatusBadge status="interrupted" />
95 </div>
96 ) : null}
97 {row.showAssistantMeta ? (
98 <AssistantMessageMeta
99 className="mt-1.5"
100 projectedItem={row.projectedItem}
101 message={row.message}
102 showCopyButton={row.showAssistantCopyButton}
103 copyStreaming={row.assistantCopyStreaming}
104 />
105 ) : null}
106 </div>
107 </>
108 );
110​
111/** Text an agent sent with `send_to_user`, shown as its own words. */
112export function SentMessageTimelineRow({
113 row,
114}: {
115 row: Extract<TimelineRow, { kind: "sent-message" }>;
116}) {
117 const ctx = use(TimelineRowCtx);
118​
119 return (
120 <div className="min-w-0 px-1 py-0.5">
121 <MessageAuthorHeading>T3 Code</MessageAuthorHeading>
122 {/* Sent messages have no message id; citations name their turn item instead. */}
123 <AssistantCitationSource
124 messageId={MessageId.make(row.id)}
125 {...(ctx.threadRef ? { threadRef: ctx.threadRef } : {})}
126 itemKey={row.id}
127 request={ctx.citationRequest}
128 listRef={ctx.listRef}
129 >
130 <ChatMarkdown
131 text={row.text}
132 cwd={ctx.markdownCwd}
133 threadRef={ctx.threadRef ?? undefined}
134 lineBreaks={shouldPreserveAssistantLineBreaks(row.text)}
135 skills={ctx.skills}
136 headingLevelOffset={MESSAGE_HEADING_LEVEL}
137 onUseArtifactTemplate={ctx.onUseArtifactTemplate}
138 onRunShellCommand={ctx.onRunShellCommand}
139 onImageExpand={ctx.onImageExpand}
140 />
141 </AssistantCitationSource>
142 </div>
143 );
145​
146function AssistantForkButton({
147 projectedItem,
148}: {
149 readonly projectedItem: NonNullable<Extract<TimelineRow, { kind: "message" }>["projectedItem"]>;
150}) {
151 const ctx = use(TimelineRowCtx);
152 const [busy, setBusy] = useState(false);
153 const support = useV2ItemSupport({
154 environmentId: ctx.activeThreadEnvironmentId,
155 sourceThreadId: projectedItem.sourceThreadId,
156 sourceItemId: projectedItem.sourceItemId,
157 });
158 const canFork = canForkProjectedAssistantItem({
159 projectedItem,
160 capabilities: support.providerSession?.capabilities,
161 });
162​
163 const onForkFromRun = ctx.onForkFromRun;
164 if (!canFork || onForkFromRun === undefined || projectedItem.item.runId === null) return null;
165 const runId = projectedItem.item.runId;
166​
167 return (
168 <Tooltip>
169 <TooltipTrigger
170 render={
171 <Button
172 type="button"
173 size="xs"
174 variant="ghost"
175 disabled={busy}
176 onClick={() => {
177 setBusy(true);
178 void onForkFromRun({ sourceThreadId: projectedItem.sourceThreadId, runId }).finally(
179 () => setBusy(false),
180 );
181 }}
182 aria-label="Fork from this response"
183 />
184 }
185 >
186 <GitForkIcon className={cn("size-3", busy && "animate-pulse")} />
187 </TooltipTrigger>
188 <TooltipPopup side="top">Fork from this response</TooltipPopup>
189 </Tooltip>
190 );
192​
193export function AssistantMetaTimelineRow({
194 row,
195}: {
196 row: Extract<TimelineRow, { kind: "assistant-meta" }>;
197}) {
198 return (
199 <div className="px-1">
200 <AssistantMessageMeta
201 className="mt-0.5"
202 projectedItem={row.projectedItem}
203 message={row.message}
204 showCopyButton={row.showAssistantCopyButton}
205 copyStreaming={row.assistantCopyStreaming}
206 alwaysVisible
207 />
208 </div>
209 );
211​
212function AssistantMessageMeta({
213 className,
214 projectedItem,
215 message,
216 showCopyButton,
217 copyStreaming,
218 alwaysVisible = false,
219}: {
220 className?: string;
221 projectedItem?: Extract<TimelineRow, { kind: "message" }>["projectedItem"];
222 message: ChatMessage;
223 showCopyButton: boolean;
224 copyStreaming: boolean;
225 alwaysVisible?: boolean;
226}) {
227 const ctx = use(TimelineRowCtx);
228​
229 return (
230 <div
231 className={cn(
232 "flex items-center gap-2 text-xs tabular-nums transition-opacity duration-200",
233 alwaysVisible
234 ? "opacity-100"
235 : "opacity-0 pointer-coarse:opacity-100 focus-within:opacity-100 group-hover/assistant:opacity-100",
236 className,
237 )}
238 >
239 {projectedItem && projectedItem.item.status !== "completed" ? (
240 <AssistantStatusBadge status={projectedItem.item.status} />
241 ) : null}
242 <AssistantCopyButton
243 message={message}
244 showCopyButton={showCopyButton}
245 streaming={copyStreaming}
246 />
247 {projectedItem?.item.type === "assistant_message" ? (
248 <AssistantForkButton projectedItem={projectedItem} />
249 ) : null}
250 {!message.streaming && projectedItem ? (
251 <AssistantReplyButton message={message} itemId={projectedItem.sourceItemId} />
252 ) : null}
253 {!message.streaming && (
254 <Tooltip>
255 <TooltipTrigger render={<p className="text-muted-foreground text-xs tabular-nums" />}>
256 {formatDayAwareTimestamp(message.updatedAt, ctx.timestampFormat)}
257 </TooltipTrigger>
258 <TooltipPopup>
259 {formatChatTimestampTooltip(message.updatedAt, ctx.timestampFormat)}
260 </TooltipPopup>
261 </Tooltip>
262 )}
263 </div>
264 );
266​
267function AssistantReplyButton({ message, itemId }: { message: ChatMessage; itemId: TurnItemId }) {
268 const ctx = use(TimelineRowCtx);
269 const { threadRef, onReplyToResponse } = ctx;
270 if (!threadRef || !onReplyToResponse || !message.text.trim()) return null;
271​
272 const reply = () => {
273 // The meta row can sit below trailing tool rows, so the message may be virtualized away.
274 const source = [
275 ...document.querySelectorAll<HTMLElement>("[data-assistant-citation-source]"),
276 ].find(
277 (element) =>
278 element.dataset.assistantCitationSource === message.id &&
279 element.dataset.assistantCitationThread === threadRef.threadId &&
280 element.dataset.assistantCitationEnvironment === threadRef.environmentId,
281 );
282 const opening = captureAssistantMessageOpening(source ?? null, message.text);
283 if (!opening) return;
284 onReplyToResponse(
285 responseContextRecord({
286 citation: { version: 1, ...threadRef, messageId: message.id, ...opening },
287 itemId,
288 subagents: readResponseSubagents(threadRef, itemId),
289 }),
290 );
291 };
292​
293 return (
294 <Tooltip>
295 <TooltipTrigger
296 render={
297 <Button
298 type="button"
299 size="xs"
300 variant="ghost-muted"
301 onClick={reply}
302 aria-label="Reply to this response"
303 />
304 }
305 >
306 <ReplyIcon className="size-3" />
307 </TooltipTrigger>
308 <TooltipPopup side="top">Reply to this response</TooltipPopup>
309 </Tooltip>
310 );
312​
313function AssistantStatusBadge({ status }: { status: string }) {
314 return (
315 <span className="rounded-full border border-border/70 px-1.5 py-0.5 font-mono text-3xs text-muted-foreground">
316 {status}
317 </span>
318 );
320​
321function AssistantCopyButton({
322 message,
323 showCopyButton,
324 streaming,
325}: {
326 message: ChatMessage;
327 showCopyButton: boolean;
328 streaming: boolean;
329}) {
330 const assistantCopyState = resolveAssistantMessageCopyState({
331 text: message.text ?? null,
332 showCopyButton,
333 streaming,
334 });
335​
336 if (!assistantCopyState.visible) {
337 return null;
338 }
339​
340 return <MessageCopyButton text={assistantCopyState.text ?? ""} variant="ghost" />;
342​
343export function ProposedPlanTimelineRow({
344 row,
345}: {
346 row: Extract<TimelineRow, { kind: "proposed-plan" }>;
347}) {
348 const ctx = use(TimelineRowCtx);
349​
350 return (
351 <div className="min-w-0 px-1 py-0.5">
352 <ProposedPlanCard
353 planMarkdown={row.proposedPlan.planMarkdown}
354 environmentId={ctx.activeThreadEnvironmentId}
355 threadRef={ctx.threadRef ?? undefined}
356 cwd={ctx.markdownCwd}
357 workspaceRoot={ctx.workspaceRoot}
358 findActive={ctx.findActive}
359 />
360 </div>
361 );
363​
364export function HtmlRenderTimelineRow({
365 row,
366}: {
367 row: Extract<TimelineRow, { kind: "html-render" }>;
368}) {
369 const ctx = use(TimelineRowCtx);
370 const { onAppFullscreenChange } = ctx;
371 const onFullscreenChange = (fullscreen: boolean) => onAppFullscreenChange(row.id, fullscreen);
372​
373 if (ctx.renderHtmlRender) {
374 return <div className="min-w-0 px-1">{ctx.renderHtmlRender(row)}</div>;
375 }
376 return (
377 <div className="min-w-0 px-1">
378 <HtmlRenderFrame
379 key={row.htmlRender.attachmentId}
380 environmentId={ctx.activeThreadEnvironmentId}
381 htmlRender={row.htmlRender}
382 threadRef={ctx.threadRef ?? undefined}
383 onFullscreenChange={onFullscreenChange}
384 />
385 </div>
386 );
388​
389export function McpAppTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "mcp-app" }> }) {
390 const ctx = use(TimelineRowCtx);
391 const { awaitingUser } = use(TimelineRowActivityCtx);
392​
393 return (
394 <div className="min-w-0 px-1">
395 <McpAppFrame
396 key={row.mcpApp.attachmentId}
397 environmentId={ctx.activeThreadEnvironmentId}
398 threadId={row.sourceThreadId}
399 conversationThreadId={ctx.threadRef?.threadId ?? row.sourceThreadId}
400 itemId={row.itemId}
401 revision={row.revision}
402 app={row.mcpApp}
403 onSendMessage={ctx.onSendAppMessage}
404 awaitingUser={awaitingUser}
405 onFullscreenChange={(fullscreen) => ctx.onAppFullscreenChange(row.id, fullscreen)}
406 />
407 </div>
408 );
410​
411/** Subscribes directly to the UI state store for expand/collapse state,
412 * so toggling re-renders only this component — not the entire list. */
413const AssistantChangedFilesSection = memo(function AssistantChangedFilesSection({
414 turnSummary,
415 routeThreadKey,
416 resolvedTheme,
417 onOpenTurnDiff,
418}: {
419 turnSummary: TurnDiffSummary | undefined;
420 routeThreadKey: string;
421 resolvedTheme: "light" | "dark";
422 displayThreadKey?: string;
423 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
424}) {
425 if (!turnSummary) return null;
426 const checkpointFiles = turnSummary.files;
427 if (checkpointFiles.length === 0) return null;
428​
429 return (
430 <AssistantChangedFilesSectionInner
431 turnSummary={turnSummary}
432 checkpointFiles={checkpointFiles}
433 routeThreadKey={routeThreadKey}
434 resolvedTheme={resolvedTheme}
435 onOpenTurnDiff={onOpenTurnDiff}
436 />
437 );
438});
439​
440function AssistantChangedFilesSectionInner({
441 turnSummary,
442 checkpointFiles,
443 routeThreadKey,
444 resolvedTheme,
445 onOpenTurnDiff,
446}: {
447 turnSummary: TurnDiffSummary;
448 checkpointFiles: TurnDiffSummary["files"];
449 routeThreadKey: string;
450 resolvedTheme: "light" | "dark";
451 displayThreadKey?: string;
452 onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
453}) {
454 const ctx = use(TimelineRowCtx);
455 const persistedExpanded = useUiStateStore(
456 (store) => store.threadChangedFilesExpandedById[routeThreadKey]?.[turnSummary.runId],
457 );
458 const setExpanded = useUiStateStore((store) => store.setThreadChangedFilesExpanded);
459 const allDirectoriesExpanded = persistedExpanded ?? false;
460​
461 const thread = useQuietThreadShell(ctx.threadRef);
462 const activeProject = useProject(
463 thread && thread.projectId
464 ? { environmentId: thread.environmentId, projectId: thread.projectId }
465 : null,
466 );
467 const onFileContextMenu = useFileContextMenuHandler(ctx.activeThreadEnvironmentId);
468 const repositoryRoot = useAtomValue(
469 ctx.workspaceRoot
470 ? vcsEnvironment.status({
471 environmentId: ctx.activeThreadEnvironmentId,
472 input: { cwd: ctx.workspaceRoot },
473 })
474 : NO_VCS_STATUS,
475 (status) => AsyncResult.getOrElse(status, () => null)?.workingTree.rootPath,
476 );
477​
478 return (
479 <ChangedFilesCard
480 runId={turnSummary.runId}
481 files={checkpointFiles}
482 totals={checkpointFileTotals(turnSummary)}
483 allDirectoriesExpanded={allDirectoriesExpanded}
484 resolvedTheme={resolvedTheme}
485 onToggleAllDirectories={() =>
486 setExpanded(routeThreadKey, turnSummary.runId, !allDirectoriesExpanded)
487 }
488 onOpenTurnDiff={onOpenTurnDiff}
489 onFileContextMenu={(filePath, event) =>
490 onFileContextMenu(
491 {
492 environmentId: ctx.activeThreadEnvironmentId,
493 filePath,
494 workspaceRoot: ctx.workspaceRoot,
495 repositoryRoot:
496 repositoryRoot ??
497 (thread?.worktreePath == null
498 ? activeProject?.repositoryIdentity?.rootPath
499 : undefined),
500 },
501 event,
502 )
503 }
504 />
505 );