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

TimelineWorkEntryRow.tsx

625 lines22.1 KB

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;
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;
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 );
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 );
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 const resetTime = resetAt ? formatUpcomingTimestamp(resetAt, timestampFormat) : null;
213 const label = warning
214 ? `Usage limit reached.${resetTime ? ` Retry after ${resetTime}.` : ""}`
215 : workEntry.label;
216 const retryRunId =
217 failureItem.runId !== null &&
218 retryableWorkspacePreparationRunIds.has(failureItem.runId) &&
219 failureItem.failure.code === ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE
220 ? failureItem.runId
221 : null;
222 return (
223 <WorkLogRow
224 data-v2-item-type="error"
225 data-v2-item-visibility={workEntry.projectedItem?.visibility}
226 wrapLabel
227 icon={
228 <CircleAlertIcon
229 className={cn("size-4", warning ? "text-warning" : "text-destructive")}
230 />
231 }
232 label={
233 <span
234 className={cn("text-sm font-medium", warning ? "text-warning" : "text-destructive")}
235 >
236 {label}
237 </span>
238 }
239 trailing={
240 <TimelineRowTimestamp
241 createdAt={workEntry.createdAt}
242 timestampFormat={timestampFormat}
243 alwaysVisible
244 />
245 }
246 >
247 {!warning ? (
248 <p className="ms-7 whitespace-pre-wrap break-words py-1 text-sm leading-relaxed text-foreground/80">
249 {failureItem.failure.message}
250 </p>
251 ) : null}
252 {retryRunId !== null && onRetryWorkspacePreparation ? (
253 <div className="ms-7 pb-1">
254 <Button
255 type="button"
256 size="xs"
257 variant="outline"
258 onClick={() => onRetryWorkspacePreparation(retryRunId)}
259 >
260 <RotateCcwIcon aria-hidden />
261 Retry
262 </Button>
263 </div>
264 ) : null}
265 </WorkLogRow>
266 );
267 }
268 const iconConfig = workToneIcon(workEntry.tone);
269 const showWarningIndicator = workEntry.sourceActivityKind === "runtime.warning";
270 const showFailedIndicator =
271 !showWarningIndicator && workEntryDisplayIndicatesToolFailure(workEntry);
272 const showDestructiveRowStyle =
273 !showWarningIndicator &&
274 showFailedIndicator &&
275 (workEntrySignalsSevereFailure(workEntry) || !workLogEntryIsToolLike(workEntry));
276 const entryIconName =
277 showWarningIndicator || showDestructiveRowStyle ? "circle-alert" : workEntryIconName(workEntry);
278 const entryToolIcon =
279 showWarningIndicator || showDestructiveRowStyle
280 ? undefined
281 : (workEntry.toolIcon ?? workEntry.toolSource?.icon);
282 const isReasoning = workEntry.itemType === "reasoning";
283 const questionHeading = workEntry.questionAnswer
284 ? getQuestionTextPreview(workEntry.questionAnswer)
285 : "";
286 const previewText =
287 isReasoning && expanded
288 ? workEntry.toolLifecycleStatus === "inProgress"
289 ? "Thinking"
290 : "Thought"
291 : questionHeading || (displayLabel ?? workEntryDisplayLabel(workEntry, workspaceRoot));
292 const answerPreview =
293 workEntry.questionAnswer && hasQuestionAnswer(workEntry.questionAnswer)
294 ? getQuestionAnswerPreview(workEntry.questionAnswer)
295 : null;
296 const viewedImagePath = workEntryViewedImagePath(workEntry);
297 const payload = workEntry.structuredPayload;
298 const skill =
299 payload?.type === "dynamic_tool"
300 ? claudeSkillInvocation(payload.toolName, payload.input)
301 : undefined;
302 const plainOutput =
303 toolGroupAction(workEntry) === "read"
304 ? workEntryReadOutput(workEntry, workspaceRoot)
305 : skill
306 ? (skill.args ?? null)
307 : undefined;
308 const viewedImage =
309 viewedImagePath && threadRef
310 ? resolveViewedImageAsset(viewedImagePath, {
311 threadId: threadRef.threadId,
312 workspaceRoot,
313 })
314 : null;
315 const canExpand =
316 previewText.trim().length > 0 ||
317 (workEntry.itemType === "dynamic_tool" && workEntry.toolData !== undefined) ||
318 Boolean(
319 workEntryRawCommand(workEntry) ||
320 workEntry.command?.trim() ||
321 workEntry.detail?.trim() ||
322 workEntry.changedFiles?.length ||
323 viewedImage,
324 );
325 const expandedBody =
326 expanded && !isReasoning
327 ? plainOutput !== undefined
328 ? plainOutput
329 : buildToolCallExpandedBody(
330 workEntry,
331 workspaceRoot,
332 previewText,
333 viewedImage ? viewedImagePath : null,
334 )
335 : null;
336 const plainOutputFetches =
337 plainOutput !== undefined &&
338 workEntry.projectedItem !== undefined &&
339 turnItemNeedsDetailFetch(workEntry.projectedItem.item);
340 const canExpandProjectedItem =
341 plainOutput !== undefined
342 ? Boolean(plainOutput || viewedImage || workEntry.questionAnswer || plainOutputFetches)
343 : workEntry.projectedItem === undefined
344 ? canExpand
345 : isReasoning
346 ? Boolean(workEntry.detail?.trim())
347 : Boolean(
348 viewedImage ||
349 workEntry.questionAnswer ||
350 turnItemHasDetail(workEntry.projectedItem.item),
351 );
352 const iconWrapperClass = cn(
353 "flex size-4 items-center justify-center",
354 showWarningIndicator
355 ? "text-warning"
356 : showDestructiveRowStyle
357 ? "text-destructive"
358 : showFailedIndicator
359 ? failedToolIconClassName
360 : workEntry.tone === "tool"
361 ? "text-icon-muted"
362 : iconConfig.className,
363 );
364 const headingClass = showWarningIndicator
365 ? "font-medium text-warning"
366 : showDestructiveRowStyle
367 ? "font-medium text-destructive"
368 : workLogEntryIsToolLike(workEntry)
369 ? "text-secondary-label"
370 : "text-foreground/80";
371 const threadLabel = isReasoning ? null : threadReadLabel(previewText, threadTarget);
372 const accessiblePreview = [threadLabel?.text ?? previewText, answerPreview]
373 .filter(Boolean)
374 .join(": ");
375 const accessibleDisplayText = showFailedIndicator
376 ? `${accessiblePreview}, tool call failed`
377 : accessiblePreview;
378 const rowToggleProps = canExpandProjectedItem
379 ? {
380 role: "button" as const,
381 tabIndex: 0 as const,
382 "aria-label": accessibleDisplayText,
383 "aria-expanded": expanded,
384 onClick: toggleExpanded,
385 onKeyDown: (e: KeyboardEvent<HTMLDivElement>) => {
386 if (e.target === e.currentTarget && (e.key === "Enter" || e.key === " ")) {
387 e.preventDefault();
388 toggleExpanded();
389 }
390 },
391 }
392 : {};
393​
394 return (
395 <WorkLogRow
396 data-v2-item-type={workEntry.projectedItem?.item.type}
397 data-v2-item-visibility={workEntry.projectedItem?.visibility}
398 {...rowToggleProps}
399 icon={
400 <span
401 className={iconWrapperClass}
402 role={showFailedIndicator ? "img" : undefined}
403 aria-label={showFailedIndicator ? "Tool call failed" : undefined}
404 >
405 <ToolActivityIconView
406 icon={entryToolIcon}
407 fallbackName={entryIconName}
408 className="block size-4 shrink-0 stroke-2"
409 muted
410 />
411 </span>
412 }
413 label={
414 <div className="min-w-0 flex-1 overflow-hidden">
415 <p className="flex min-w-0 w-full items-baseline gap-1.5 text-sm leading-relaxed">
416 <span
417 className={cn(answerPreview ? "min-w-0" : "min-w-0 flex-1", "truncate", headingClass)}
418 >
419 {isReasoning && !expanded ? (
420 <ChatMarkdown
421 inline
422 text={workEntry.detail ?? previewText}
423 cwd={ctx.markdownCwd}
424 parseRawHtml={false}
425 extraRemarkPlugins={
426 workEntry.toolLifecycleStatus === "inProgress"
427 ? THINKING_PREVIEW_PLUGINS
428 : THOUGHT_PREVIEW_PLUGINS
429 }
430 />
431 ) : threadLabel ? (
432 <ThreadReadLabel
433 label={threadLabel}
434 environmentId={ctx.activeThreadEnvironmentId}
435 linked
436 />
437 ) : (
438 previewText
439 )}
440 </span>
441 {answerPreview ? (
442 <span
443 className={cn(
444 "min-w-0 truncate",
445 !expanded &&
446 workEntry.questionAnswer &&
447 hasQuestionAnswer(workEntry.questionAnswer)
448 ? "text-foreground"
449 : "text-muted-foreground",
450 )}
451 >
452 {answerPreview}
453 </span>
454 ) : null}
455 </p>
456 </div>
457 }
458 trailing={
459 <>
460 {createdThread ? (
461 <button
462 type="button"
463 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"
464 aria-label={`Open ${createdThread.title ?? "created thread"}`}
465 onClick={(event) => {
466 event.stopPropagation();
467 ctx.onOpenThread(createdThread.targetThreadId);
468 }}
469 onKeyDown={stopRowToggle}
470 >
471 Open chat
472 </button>
473 ) : null}
474 {notifiedSubagentThreadId ? (
475 <InlineButton
476 aria-label="Open subagent thread"
477 onClick={(event) => {
478 event.stopPropagation();
479 ctx.onOpenThread(notifiedSubagentThreadId);
480 }}
481 onKeyDown={stopRowToggle}
482 >
483 Open subagent
484 </InlineButton>
485 ) : null}
486 {showFailedIndicator &&
487 !showDestructiveRowStyle &&
488 !toolIconAcceptsTint(entryToolIcon) ? (
489 <XIcon aria-hidden className={cn("size-3 shrink-0", failedToolIconClassName)} />
490 ) : null}
491 <TimelineRowTimestamp createdAt={workEntry.createdAt} timestampFormat={timestampFormat} />
492 <span
493 className={cn(
494 "flex size-4 shrink-0 items-center justify-center",
495 !canExpandProjectedItem && "invisible",
496 )}
497 aria-hidden
498 >
499 <ChevronRightIcon
500 className={cn(
501 "size-3 shrink-0 text-icon-muted opacity-70 transition-transform duration-200",
502 expanded && "rotate-90",
503 )}
504 />
505 </span>
506 </>
507 }
508 >
509 {expanded && viewedImage && threadRef ? (
510 <WorkLogDetails kind="media">
511 <ChatMarkdownAssetImage
512 environmentId={threadRef.environmentId}
513 resource={viewedImage.resource}
514 alt={viewedImage.alt}
515 srcFragment={viewedImage.srcFragment}
516 workspaceRoot={workspaceRoot}
517 maxHeightRem={16}
518 onImageExpand={onImageExpand}
519 />
520 </WorkLogDetails>
521 ) : null}
522 {expanded && workEntry.questionAnswer ? (
523 <QuestionAnswerHistory answer={workEntry.questionAnswer} />
524 ) : null}
525 {expanded && isReasoning ? <ReasoningTraceContent entries={[workEntry]} /> : null}
526 {expanded &&
527 !isReasoning &&
528 !workEntry.questionAnswer &&
529 canExpandProjectedItem &&
530 (expandedBody ||
531 plainOutputFetches ||
532 (workEntry.projectedItem && plainOutput === undefined)) ? (
533 <WorkLogDetails kind="panel">
534 {workEntry.projectedItem && plainOutput === undefined ? (
535 <V2ItemInspector
536 projectedItem={workEntry.projectedItem}
537 environmentId={ctx.activeThreadEnvironmentId}
538 cwd={ctx.markdownCwd}
539 workspaceRoot={workspaceRoot}
540 onOpenToolDiff={ctx.onOpenToolDiff}
541 onImageExpand={ctx.onImageExpand}
542 source={ctx.turnItemSource}
543 />
544 ) : (
545 <>
546 {expandedBody ? (
547 <pre className={toolCallExpandedBodyClassName}>{expandedBody}</pre>
548 ) : null}
549 {plainOutputFetches && workEntry.projectedItem ? (
550 <FetchedToolOutput
551 projectedItem={workEntry.projectedItem}
552 environmentId={ctx.activeThreadEnvironmentId}
553 onImageExpand={onImageExpand}
554 source={ctx.turnItemSource}
555 />
556 ) : null}
557 </>
558 )}
559 </WorkLogDetails>
560 ) : null}
561 </WorkLogRow>
562 );
564​
565function QuestionAnswerHistory({
566 answer,
567}: {
568 answer: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
569}) {
570 const { activeThreadEnvironmentId } = use(TimelineRowCtx);
571 const attachments = Object.values(answer.attachmentsByQuestionId).flat();
572 const resources = attachments.map((attachment) => ({
573 _tag: "attachment" as const,
574 attachmentId: attachment.id,
575 }));
576 const urls = useAssetUrls(activeThreadEnvironmentId, resources);
577 return (
578 <div className="ms-7 mt-2 space-y-2" onClick={stopRowToggle}>
579 {[
580 ...new Set([
581 ...Object.keys(answer.questionTextById ?? {}),
582 ...Object.keys(answer.answers),
583 ...Object.keys(answer.attachmentsByQuestionId),
584 ]),
585 ].map((questionId) => (
586 <div key={questionId} className="space-y-1">
587 {answer.questionTextById?.[questionId] ? (
588 <p className="whitespace-pre-wrap text-sm text-muted-foreground">
589 {answer.questionTextById[questionId]}
590 </p>
591 ) : null}
592 {getQuestionAnswerText(answer.answers[questionId]) ? (
593 <p className="ms-3 whitespace-pre-wrap text-sm text-muted-foreground">
594 {getQuestionAnswerText(answer.answers[questionId])}
595 </p>
596 ) : null}
597 <div className="flex flex-wrap gap-2">
598 {(answer.attachmentsByQuestionId[questionId] ?? []).map((attachment) => {
599 const url = urls[attachments.indexOf(attachment)];
600 return (
601 <a
602 key={attachment.id}
603 href={url ?? undefined}
604 target="_blank"
605 rel="noreferrer"
606 className="text-sm underline"
607 >
608 {attachment.type === "image" && url ? (
609 <img
610 src={url}
611 alt={attachment.name}
612 className="h-20 max-w-32 rounded object-contain"
613 />
614 ) : (
615 attachment.name
616 )}
617 </a>
618 );
619 })}
620 </div>
621 </div>
622 ))}
623 </div>
624 );