Open History to see the last commit
1import { TimelinePendingApprovalRow } from "./TimelinePendingApprovalRow";
2import { WorkLogDetails, WorkLogRow } from "./WorkLog";
3import {
4 getQuestionAnswerPreview,
5 getQuestionAnswerText,
6 getQuestionTextPreview,
7 hasQuestionAnswer,
8} from "@t3tools/client-runtime/work-log/user-input";
9import {
10 ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE,
11 type EnvironmentId,
12 ThreadId,
13} from "@t3tools/contracts";
14import { scopeThreadRef } from "@t3tools/client-runtime/environment";
15import { Link } from "@tanstack/react-router";
16import { notificationChildThreadId } from "@t3tools/client-runtime/state/thread-execution";
17import {
18 resolveViewedImageAsset,
19 toolGroupAction,
20 workEntryViewedImagePath,
21} from "@t3tools/client-runtime/work-log/presentation";
22import {
23 turnItemHasDetail,
24 turnItemNeedsDetailFetch,
25} from "@t3tools/client-runtime/work-log/item-detail";
26import { claudeSkillInvocation } from "@t3tools/shared/toolActivity";
27import { memo, use, useState, type KeyboardEvent } from "react";
28import {
29 workEntryDisplayIndicatesToolFailure,
30 workEntrySignalsSevereFailure,
31 workLogEntryIsToolLike,
32} from "../../session-logic";
33import ChatMarkdown from "../ChatMarkdown";
34import { ChatMarkdownAssetImage } from "./ChatMarkdownMedia";
35import { ChevronRightIcon, CircleAlertIcon, XIcon, RotateCcwIcon } from "lucide-react";
36import { Button, InlineButton } from "../ui/button";
37import { useAssetUrls } from "../../assets/assetUrls";
38import { useThreadShell } from "../../state/entities";
39import {
40 threadReadLabelPrefix,
41 threadReadTargetId,
42 threadReadTargetTitle,
43 workEntryDisplayLabel,
44 workEntryReadOutput,
45} from "./MessagesTimeline.logic";
46import { cn } from "~/lib/utils";
47import { formatUpcomingTimestamp } from "../../timestampFormat";
48import { FetchedToolOutput, V2ItemInspector } from "./V2ItemInspector";
49import { SubagentNotificationLink } from "./V2LifecycleRow";
50import {
51 TimelineRowCtx,
52 TimelineRowActivityCtx,
53 WorkGroupViewCtx,
54 type TimelineWorkEntry,
55} from "./timelineRowContext";
56import { MESSAGE_HEADING_LEVEL, TimelineRowTimestamp } from "./TimelineRowParts";
57import {
58 failedToolIconClassName,
59 toolIconAcceptsTint,
60 ToolActivityIconView,
61} from "./TimelineToolActivityIcon";
62import {
63 workToneIcon,
64 workEntryRawCommand,
65 buildToolCallExpandedBody,
66 workEntryIconName,
67 remarkThoughtPreview,
68} from "./TimelineWorkEntryRow.logic";
69
70export function useThreadReadTarget(entry: TimelineWorkEntry, environmentId: EnvironmentId) {
71 const rawThreadId = threadReadTargetId(entry);
72 const threadId = rawThreadId === null ? null : ThreadId.make(rawThreadId);
73 const shell = useThreadShell(threadId ? scopeThreadRef(environmentId, threadId) : null);
74 const title = threadReadTargetTitle(shell);
75 return threadId && title ? { threadId, title } : null;
76}
77
78export function threadReadLabel(label: string, target: ReturnType<typeof useThreadReadTarget>) {
79 const prefix = target && threadReadLabelPrefix(label);
80 return prefix ? { ...target, prefix, text: `${prefix} “${target.title}”` } : null;
81}
82
83export function ThreadReadLabel({
84 label,
85 environmentId,
86 linked,
87}: {
88 label: NonNullable<ReturnType<typeof threadReadLabel>>;
89 environmentId: EnvironmentId;
90 linked: boolean;
91}) {
92 return (
93 <span className="flex min-w-0">
94 <span className="shrink-0">{label.prefix} “</span>
95 {linked ? (
96 <Link
97 to="/$environmentId/$threadId"
98 params={{ environmentId, threadId: label.threadId }}
99 className="min-w-0 truncate rounded-sm text-foreground underline-offset-2 hover:underline focus-visible:outline-2 focus-visible:outline-ring"
100 onClick={stopRowToggle}
101 onKeyDown={stopRowToggle}
102 >
103 {label.title}
104 </Link>
105 ) : (
106 <span className="min-w-0 truncate">{label.title}</span>
107 )}
108 <span className="shrink-0">”</span>
109 </span>
110 );
111}
112
113const toolCallExpandedBodyClassName =
114 "max-h-64 cursor-text overflow-auto whitespace-pre-wrap break-words font-mono text-secondary-label text-(length:--font-size-code,var(--text-2xs)) leading-relaxed select-text";
115
116const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation();
117
118export function ReasoningTraceContent({ entries }: { entries: ReadonlyArray<TimelineWorkEntry> }) {
119 const ctx = use(TimelineRowCtx);
120 const { isWorking, latestRunId } = use(TimelineRowActivityCtx);
121 const isStreaming = (entry: TimelineWorkEntry) =>
122 isWorking && entry.runId === latestRunId && entry.toolLifecycleStatus === "inProgress";
123 return (
124 <WorkLogDetails followLive={entries.some(isStreaming)}>
125 {entries.map((entry) => (
126 <ChatMarkdown
127 key={entry.id}
128 className="text-foreground"
129 text={entry.detail ?? ""}
130 cwd={ctx.markdownCwd}
131 threadRef={ctx.threadRef ?? undefined}
132 skills={ctx.skills}
133 isStreaming={isStreaming(entry)}
134 headingLevelOffset={MESSAGE_HEADING_LEVEL}
135 onUseArtifactTemplate={ctx.onUseArtifactTemplate}
136 onImageExpand={ctx.onImageExpand}
137 lineBreaks
138 />
139 ))}
140 </WorkLogDetails>
141 );
142}
143
144type WorkEntryRowProps = {
145 workEntry: TimelineWorkEntry;
146 workspaceRoot: string | undefined;
147 displayLabel?: string | undefined;
148 onToggleEntry?: ((collapsed: boolean) => void) | undefined;
149};
150
151export const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: WorkEntryRowProps) {
152 const ctx = use(TimelineRowCtx);
153 const item = props.workEntry.projectedItem?.item;
154 const childThreadId =
155 item?.type === "notification" ? notificationChildThreadId(item.source) : undefined;
156 if (item?.type !== "notification" || childThreadId === undefined) {
157 return <WorkEntryLogRow {...props} />;
158 }
159 return (
160 <SubagentNotificationLink
161 parentRef={scopeThreadRef(ctx.activeThreadEnvironmentId, item.threadId)}
162 childThreadId={childThreadId}
163 outcome={item.outcome}
164 createdAt={props.workEntry.createdAt}
165 timestampFormat={ctx.timestampFormat}
166 onOpenThread={ctx.onOpenThread}
167 fallback={<WorkEntryLogRow {...props} />}
168 />
169 );
170});
171
172function WorkEntryLogRow(props: WorkEntryRowProps) {
173 const { workEntry, workspaceRoot, displayLabel } = props;
174 const ctx = use(TimelineRowCtx);
175 const { threadRef, onImageExpand, timestampFormat } = ctx;
176 const { retryableWorkspacePreparationRunIds, onRetryWorkspacePreparation } = ctx;
177 const threadTarget = useThreadReadTarget(workEntry, ctx.activeThreadEnvironmentId);
178 const createdThread =
179 workEntry.projectedItem?.item.type === "thread_created"
180 ? workEntry.projectedItem.item
181 : undefined;
182 const notifiedSubagentThreadId =
183 workEntry.projectedItem?.item.type === "notification"
184 ? notificationChildThreadId(workEntry.projectedItem.item.source)
185 : undefined;
186 const groupView = use(WorkGroupViewCtx);
187 const [expanded, setExpanded] = useState(
188 () => groupView?.state.expandedEntries.has(workEntry.id) ?? false,
189 );
190 const toggleExpanded = () => {
191 const next = !expanded;
192 if (groupView) {
193 groupView.onToggleEntry(!next);
194 if (next) groupView.state.expandedEntries.add(workEntry.id);
195 else groupView.state.expandedEntries.delete(workEntry.id);
196 } else {
197 props.onToggleEntry?.(!next);
198 }
199 setExpanded(next);
200 };
201 const failureItem = workEntry.projectedItem?.item;
202 const pendingApproval =
203 failureItem?.type === "approval_request"
204 ? ctx.pendingApprovals.get(failureItem.requestId)
205 : undefined;
206 if (pendingApproval) return <TimelinePendingApprovalRow approval={pendingApproval} />;
207 if (failureItem?.type === "error" && failureItem.status === "failed") {
208 const warning = failureItem.failure.class === "usage_limit";
209 const resetAt = failureItem.failure.resetAt;
210 const resetTime = resetAt ? formatUpcomingTimestamp(resetAt, timestampFormat) : null;
211 const label = warning
212 ? `Usage limit reached.${resetTime ? ` Retry after ${resetTime}.` : ""}`
213 : workEntry.label;
214 const retryRunId =
215 failureItem.runId !== null &&
216 retryableWorkspacePreparationRunIds.has(failureItem.runId) &&
217 failureItem.failure.code === ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE
218 ? failureItem.runId
219 : null;
220 return (
221 <WorkLogRow
222 data-v2-item-type="error"
223 data-v2-item-visibility={workEntry.projectedItem?.visibility}
224 wrapLabel
225 icon={
226 <CircleAlertIcon
227 className={cn("size-4", warning ? "text-warning" : "text-destructive")}
228 />
229 }
230 label={
231 <span
232 className={cn("text-sm font-medium", warning ? "text-warning" : "text-destructive")}
233 >
234 {label}
235 </span>
236 }
237 trailing={
238 <TimelineRowTimestamp
239 createdAt={workEntry.createdAt}
240 timestampFormat={timestampFormat}
241 alwaysVisible
242 />
243 }
244 >
245 {!warning ? (
246 <p className="ms-7 whitespace-pre-wrap break-words py-1 text-sm leading-relaxed text-foreground/80">
247 {failureItem.failure.message}
248 </p>
249 ) : null}
250 {retryRunId !== null && onRetryWorkspacePreparation ? (
251 <div className="ms-7 pb-1">
252 <Button
253 type="button"
254 size="xs"
255 variant="outline"
256 onClick={() => onRetryWorkspacePreparation(retryRunId)}
257 >
258 <RotateCcwIcon aria-hidden />
259 Retry
260 </Button>
261 </div>
262 ) : null}
263 </WorkLogRow>
264 );
265 }
266 const iconConfig = workToneIcon(workEntry.tone);
267 const showWarningIndicator = workEntry.sourceActivityKind === "runtime.warning";
268 const showFailedIndicator =
269 !showWarningIndicator && workEntryDisplayIndicatesToolFailure(workEntry);
270 const showDestructiveRowStyle =
271 !showWarningIndicator &&
272 showFailedIndicator &&
273 (workEntrySignalsSevereFailure(workEntry) || !workLogEntryIsToolLike(workEntry));
274 const entryIconName =
275 showWarningIndicator || showDestructiveRowStyle ? "circle-alert" : workEntryIconName(workEntry);
276 const entryToolIcon =
277 showWarningIndicator || showDestructiveRowStyle
278 ? undefined
279 : (workEntry.toolIcon ?? workEntry.toolSource?.icon);
280 const isReasoning = workEntry.itemType === "reasoning";
281 const questionHeading = workEntry.questionAnswer
282 ? getQuestionTextPreview(workEntry.questionAnswer)
283 : "";
284 const previewText =
285 isReasoning && expanded
286 ? workEntry.toolLifecycleStatus === "inProgress"
287 ? "Thinking"
288 : "Thought"
289 : questionHeading || (displayLabel ?? workEntryDisplayLabel(workEntry, workspaceRoot));
290 const answerPreview =
291 workEntry.questionAnswer && hasQuestionAnswer(workEntry.questionAnswer)
292 ? getQuestionAnswerPreview(workEntry.questionAnswer)
293 : null;
294 const viewedImagePath = workEntryViewedImagePath(workEntry);
295 const payload = workEntry.structuredPayload;
296 const skill =
297 payload?.type === "dynamic_tool"
298 ? claudeSkillInvocation(payload.toolName, payload.input)
299 : undefined;
300 const plainOutput =
301 toolGroupAction(workEntry) === "read"
302 ? workEntryReadOutput(workEntry, workspaceRoot)
303 : skill
304 ? (skill.args ?? null)
305 : undefined;
306 const viewedImage =
307 viewedImagePath && threadRef
308 ? resolveViewedImageAsset(viewedImagePath, {
309 threadId: threadRef.threadId,
310 workspaceRoot,
311 })
312 : null;
313 const canExpand =
314 previewText.trim().length > 0 ||
315 (workEntry.itemType === "dynamic_tool" && workEntry.toolData !== undefined) ||
316 Boolean(
317 workEntryRawCommand(workEntry) ||
318 workEntry.command?.trim() ||
319 workEntry.detail?.trim() ||
320 workEntry.changedFiles?.length ||
321 viewedImage,
322 );
323 const expandedBody =
324 expanded && !isReasoning
325 ? plainOutput !== undefined
326 ? plainOutput
327 : buildToolCallExpandedBody(
328 workEntry,
329 workspaceRoot,
330 previewText,
331 viewedImage ? viewedImagePath : null,
332 )
333 : null;
334 const plainOutputFetches =
335 plainOutput !== undefined &&
336 workEntry.projectedItem !== undefined &&
337 turnItemNeedsDetailFetch(workEntry.projectedItem.item);
338 const canExpandProjectedItem =
339 plainOutput !== undefined
340 ? Boolean(plainOutput || viewedImage || workEntry.questionAnswer || plainOutputFetches)
341 : workEntry.projectedItem === undefined
342 ? canExpand
343 : isReasoning
344 ? Boolean(workEntry.detail?.trim())
345 : Boolean(
346 viewedImage ||
347 workEntry.questionAnswer ||
348 turnItemHasDetail(workEntry.projectedItem.item),
349 );
350 const iconWrapperClass = cn(
351 "flex size-4 items-center justify-center",
352 showWarningIndicator
353 ? "text-warning"
354 : showDestructiveRowStyle
355 ? "text-destructive"
356 : showFailedIndicator
357 ? failedToolIconClassName
358 : workEntry.tone === "tool"
359 ? "text-icon-muted"
360 : iconConfig.className,
361 );
362 const headingClass = showWarningIndicator
363 ? "font-medium text-warning"
364 : showDestructiveRowStyle
365 ? "font-medium text-destructive"
366 : workLogEntryIsToolLike(workEntry)
367 ? "text-secondary-label"
368 : "text-foreground/80";
369 const threadLabel = isReasoning ? null : threadReadLabel(previewText, threadTarget);
370 const accessiblePreview = [threadLabel?.text ?? previewText, answerPreview]
371 .filter(Boolean)
372 .join(": ");
373 const accessibleDisplayText = showFailedIndicator
374 ? `${accessiblePreview}, tool call failed`
375 : accessiblePreview;
376 const rowToggleProps = canExpandProjectedItem
377 ? {
378 role: "button" as const,
379 tabIndex: 0 as const,
380 "aria-label": accessibleDisplayText,
381 "aria-expanded": expanded,
382 onClick: toggleExpanded,
383 onKeyDown: (e: KeyboardEvent<HTMLDivElement>) => {
384 if (e.target === e.currentTarget && (e.key === "Enter" || e.key === " ")) {
385 e.preventDefault();
386 toggleExpanded();
387 }
388 },
389 }
390 : {};
391
392 return (
393 <WorkLogRow
394 data-v2-item-type={workEntry.projectedItem?.item.type}
395 data-v2-item-visibility={workEntry.projectedItem?.visibility}
396 {...rowToggleProps}
397 icon={
398 <span
399 className={iconWrapperClass}
400 role={showFailedIndicator ? "img" : undefined}
401 aria-label={showFailedIndicator ? "Tool call failed" : undefined}
402 >
403 <ToolActivityIconView
404 icon={entryToolIcon}
405 fallbackName={entryIconName}
406 className="block size-4 shrink-0 stroke-2"
407 muted
408 />
409 </span>
410 }
411 label={
412 <div className="min-w-0 flex-1 overflow-hidden">
413 <p className="flex min-w-0 w-full items-baseline gap-1.5 text-sm leading-relaxed">
414 <span
415 className={cn(answerPreview ? "min-w-0" : "min-w-0 flex-1", "truncate", headingClass)}
416 >
417 {isReasoning && !expanded ? (
418 <ChatMarkdown
419 inline
420 text={workEntry.detail ?? previewText}
421 cwd={ctx.markdownCwd}
422 parseRawHtml={false}
423 extraRemarkPlugins={[
424 [
425 remarkThoughtPreview,
426 workEntry.toolLifecycleStatus === "inProgress" ? "Thinking" : "Thought",
427 ],
428 ]}
429 />
430 ) : threadLabel ? (
431 <ThreadReadLabel
432 label={threadLabel}
433 environmentId={ctx.activeThreadEnvironmentId}
434 linked
435 />
436 ) : (
437 previewText
438 )}
439 </span>
440 {answerPreview ? (
441 <span
442 className={cn(
443 "min-w-0 truncate",
444 !expanded &&
445 workEntry.questionAnswer &&
446 hasQuestionAnswer(workEntry.questionAnswer)
447 ? "text-foreground"
448 : "text-muted-foreground",
449 )}
450 >
451 {answerPreview}
452 </span>
453 ) : null}
454 </p>
455 </div>
456 }
457 trailing={
458 <>
459 {createdThread ? (
460 <button
461 type="button"
462 className="shrink-0 rounded-sm text-sm text-primary hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring"
463 aria-label={`Open ${createdThread.title ?? "created thread"}`}
464 onClick={(event) => {
465 event.stopPropagation();
466 ctx.onOpenThread(createdThread.targetThreadId);
467 }}
468 onKeyDown={stopRowToggle}
469 >
470 Open chat
471 </button>
472 ) : null}
473 {notifiedSubagentThreadId ? (
474 <InlineButton
475 aria-label="Open subagent thread"
476 onClick={(event) => {
477 event.stopPropagation();
478 ctx.onOpenThread(notifiedSubagentThreadId);
479 }}
480 onKeyDown={stopRowToggle}
481 >
482 Open subagent
483 </InlineButton>
484 ) : null}
485 {showFailedIndicator &&
486 !showDestructiveRowStyle &&
487 !toolIconAcceptsTint(entryToolIcon) ? (
488 <XIcon aria-hidden className={cn("size-3 shrink-0", failedToolIconClassName)} />
489 ) : null}
490 <TimelineRowTimestamp createdAt={workEntry.createdAt} timestampFormat={timestampFormat} />
491 <span
492 className={cn(
493 "flex size-4 shrink-0 items-center justify-center",
494 !canExpandProjectedItem && "invisible",
495 )}
496 aria-hidden
497 >
498 <ChevronRightIcon
499 className={cn(
500 "size-3 shrink-0 text-icon-muted opacity-70 transition-transform duration-200",
501 expanded && "rotate-90",
502 )}
503 />
504 </span>
505 </>
506 }
507 >
508 {expanded && viewedImage && threadRef ? (
509 <WorkLogDetails kind="media">
510 <ChatMarkdownAssetImage
511 environmentId={threadRef.environmentId}
512 resource={viewedImage.resource}
513 alt={viewedImage.alt}
514 srcFragment={viewedImage.srcFragment}
515 workspaceRoot={workspaceRoot}
516 maxHeightRem={16}
517 onImageExpand={onImageExpand}
518 />
519 </WorkLogDetails>
520 ) : null}
521 {expanded && workEntry.questionAnswer ? (
522 <QuestionAnswerHistory answer={workEntry.questionAnswer} />
523 ) : null}
524 {expanded && isReasoning ? <ReasoningTraceContent entries={[workEntry]} /> : null}
525 {expanded &&
526 !isReasoning &&
527 !workEntry.questionAnswer &&
528 canExpandProjectedItem &&
529 (expandedBody ||
530 plainOutputFetches ||
531 (workEntry.projectedItem && plainOutput === undefined)) ? (
532 <WorkLogDetails kind="panel">
533 {workEntry.projectedItem && plainOutput === undefined ? (
534 <V2ItemInspector
535 projectedItem={workEntry.projectedItem}
536 environmentId={ctx.activeThreadEnvironmentId}
537 cwd={ctx.markdownCwd}
538 workspaceRoot={workspaceRoot}
539 onOpenToolDiff={ctx.onOpenToolDiff}
540 onImageExpand={ctx.onImageExpand}
541 source={ctx.turnItemSource}
542 />
543 ) : (
544 <>
545 {expandedBody ? (
546 <pre className={toolCallExpandedBodyClassName}>{expandedBody}</pre>
547 ) : null}
548 {plainOutputFetches && workEntry.projectedItem ? (
549 <FetchedToolOutput
550 projectedItem={workEntry.projectedItem}
551 environmentId={ctx.activeThreadEnvironmentId}
552 onImageExpand={onImageExpand}
553 source={ctx.turnItemSource}
554 />
555 ) : null}
556 </>
557 )}
558 </WorkLogDetails>
559 ) : null}
560 </WorkLogRow>
561 );
562}
563
564function QuestionAnswerHistory({
565 answer,
566}: {
567 answer: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
568}) {
569 const { activeThreadEnvironmentId } = use(TimelineRowCtx);
570 const attachments = Object.values(answer.attachmentsByQuestionId).flat();
571 const resources = attachments.map((attachment) => ({
572 _tag: "attachment" as const,
573 attachmentId: attachment.id,
574 }));
575 const urls = useAssetUrls(activeThreadEnvironmentId, resources);
576 return (
577 <div className="ms-7 mt-2 space-y-2" onClick={stopRowToggle}>
578 {[
579 ...new Set([
580 ...Object.keys(answer.questionTextById ?? {}),
581 ...Object.keys(answer.answers),
582 ...Object.keys(answer.attachmentsByQuestionId),
583 ]),
584 ].map((questionId) => (
585 <div key={questionId} className="space-y-1">
586 {answer.questionTextById?.[questionId] ? (
587 <p className="whitespace-pre-wrap text-sm text-muted-foreground">
588 {answer.questionTextById[questionId]}
589 </p>
590 ) : null}
591 {getQuestionAnswerText(answer.answers[questionId]) ? (
592 <p className="ms-3 whitespace-pre-wrap text-sm text-muted-foreground">
593 {getQuestionAnswerText(answer.answers[questionId])}
594 </p>
595 ) : null}
596 <div className="flex flex-wrap gap-2">
597 {(answer.attachmentsByQuestionId[questionId] ?? []).map((attachment) => {
598 const url = urls[attachments.indexOf(attachment)];
599 return (
600 <a
601 key={attachment.id}
602 href={url ?? undefined}
603 target="_blank"
604 rel="noreferrer"
605 className="text-sm underline"
606 >
607 {attachment.type === "image" && url ? (
608 <img
609 src={url}
610 alt={attachment.name}
611 className="h-20 max-w-32 rounded object-contain"
612 />
613 ) : (
614 attachment.name
615 )}
616 </a>
617 );
618 })}
619 </div>
620 </div>
621 ))}
622 </div>
623 );
624}