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

TimelineAssistantRows.tsx

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