The best way to control Claude Code, Codex and more from any computer or phone

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