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