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