The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 22, 20:45 UTC
refactor(web): timeline work entry rows and tool icons live in their own files (#22674)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 21, 2026 at 01:12 UTC
bea879025debc5b3f0c6c62949e3d2cb02ffc6e5
7 files changed
+1321
-1203
apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
+2
-1
@@ -6,7 +6,8 @@ import { describe, expect, it, vi } from "vite-plus/test";
6
import "~/index.css";
7
8
import { act, render } from "../../../test/render";
9
-import { MessagesTimeline, remarkThoughtPreview } from "./MessagesTimeline";
9
+import { MessagesTimeline } from "./MessagesTimeline";
10
+import { remarkThoughtPreview } from "./TimelineWorkEntryRow.logic";
11
import { parseMarkdownWithMath } from "@t3tools/shared/markdownMath";
12
13
const pullRequestQuery = vi.hoisted(() => ({ error: "Pull request not found" }));
apps/web/src/components/chat/MessagesTimeline.tsx
+40
-1202
@@ -1,31 +1,27 @@
1
import { useRenderedAppearance } from "../../hooks/useTheme";
2
-import type { Root, RootContent } from "mdast";
2
import { ThreadFindTimelineContext } from "./ThreadFindProvider";
3
import { shallow } from "zustand/vanilla/shallow";
4
import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";
5
import { MarkdownFindContext, findRevealRef } from "./markdownFindContext";
6
import { useChatCanvas } from "./ChatCanvasContext";
8
-import { WorkLogBlock, WorkLogButton, WorkLogDetails, WorkLogList, WorkLogRow } from "./WorkLog";
7
+import { WorkLogBlock, WorkLogButton, WorkLogList, WorkLogRow } from "./WorkLog";
8
import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
9
import type { WorktreeSetupSnapshot } from "@t3tools/contracts";
10
import { ReadOnlySourcePreview } from "../files/AttachmentFilePreview";
11
import { useRightPanelStore } from "~/rightPanelStore";
12
import {
13
getQuestionAnswerPreview,
15
- getQuestionAnswerText,
14
getQuestionTextPreview,
15
hasQuestionAnswer,
16
} from "@t3tools/client-runtime/work-log/user-input";
17
import { deriveTimelineMinimapItems } from "./timelineMinimapItems";
18
import {
19
COMPOSER_CONTEXT_KINDS,
22
- ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE,
20
type AssistantCitation,
21
type EnvironmentId,
22
type MessageId,
23
type OrchestrationV2TurnItem,
24
type RunAttemptId,
28
- type ScopedThreadRef,
25
type ServerProviderSkill,
26
type RunId,
27
ThreadId,
@@ -37,19 +33,9 @@ import { environmentThreadDetails } from "../../state/threads";
33
import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
34
import { Link } from "@tanstack/react-router";
35
import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
40
-import { notificationChildThreadId } from "@t3tools/client-runtime/state/thread-execution";
36
import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
42
-import {
43
- liveThoughtLine,
44
- resolveWorkEntryToolPresentation,
45
- resolveViewedImageAsset,
46
- workEntryViewedImagePath,
47
-} from "@t3tools/client-runtime/work-log/presentation";
37
+import { liveThoughtLine } from "@t3tools/client-runtime/work-log/presentation";
38
import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
49
-import {
50
- turnItemHasDetail,
51
- turnItemNeedsDetailFetch,
52
-} from "@t3tools/client-runtime/work-log/item-detail";
39
import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
40
import {
41
subagentGroupSummary,
@@ -63,13 +49,9 @@ const NOOP_USE_ARTIFACT_TEMPLATE = () => {};
49
const NOOP_OPEN_ATTACHMENT = (_attachment: ChatFileAttachment) => {};
50
51
import { resolveChatListAnchoredEndSpace } from "@t3tools/shared/chatList";
66
-import { toolActivityFaviconUrl } from "@t3tools/shared/favicon";
52
import { formatDuration } from "@t3tools/shared/orchestrationTiming";
68
-import { getProjectFaviconCacheKey } from "@t3tools/shared/projectFavicon";
69
-import { claudeSkillInvocation, isJavaScriptReplTool } from "@t3tools/shared/toolActivity";
53
import { observeVisibleAnimation } from "../../lib/visibleAnimation";
54
import {
72
- createContext,
55
memo,
56
use,
57
useContext,
@@ -77,8 +59,6 @@ import {
59
useLayoutEffect,
60
useRef,
61
useState,
80
- type KeyboardEvent,
81
- type MouseEvent,
62
type ReactNode,
63
} from "react";
64
import {
@@ -94,8 +74,6 @@ import {
74
createMessageAttachmentPreviewProjector,
75
selectMessageImageResources,
76
workEntryDisplayIndicatesToolFailure,
97
- workEntrySignalsSevereFailure,
98
- workLogEntryIsToolLike,
77
} from "../../session-logic";
78
import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
79
import {
@@ -113,21 +91,17 @@ import {
91
resolveFileDiffPath,
92
} from "../../lib/diffRendering";
93
import { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting";
116
-import ChatMarkdown, { ChatMarkdownAssetImage } from "../ChatMarkdown";
117
-import { T3Wordmark } from "../T3Wordmark";
94
+import ChatMarkdown from "../ChatMarkdown";
95
import { ThreadContextChip } from "../ThreadContextChip";
96
import {
97
ArrowRightIcon,
98
BotIcon,
122
- BrainIcon,
99
CheckIcon,
100
ChevronDownIcon,
125
- ChevronRightIcon,
101
CircleAlertIcon,
102
DownloadIcon,
103
EyeIcon,
104
GitForkIcon,
130
- GlobeIcon,
105
type LucideIcon,
106
MessageCircleIcon,
107
MousePointerClickIcon,
@@ -135,17 +109,10 @@ import {
109
MinusIcon,
110
Redo2Icon,
111
Minimize2Icon,
138
- SearchIcon,
139
- SmartphoneIcon,
140
- SquarePenIcon,
141
- TerminalIcon,
112
Undo2Icon,
143
- HammerIcon,
113
WrenchIcon,
145
- Code2Icon,
114
XIcon,
115
ZapIcon,
148
- RotateCcwIcon,
116
} from "lucide-react";
117
import { ChevronDown, ChevronRight, Link as LinkIconNode } from "lucide";
118
import type {
@@ -188,11 +155,7 @@ import { PierreEntryIcon } from "./PierreEntryIcon";
155
import { WorkspaceEntryIcon, WorkspaceEntryTooltip } from "./WorkspaceEntryIcon";
156
import { AssistantSelectionToolbar } from "./AssistantSelectionToolbar";
157
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
191
-import {
192
- AssistantCitationSource,
193
- type AssistantCitationRequest,
194
- type AssistantCitationTarget,
195
-} from "./AssistantCitationSource";
158
+import { AssistantCitationSource, type AssistantCitationRequest } from "./AssistantCitationSource";
159
import { useAssistantCitationTarget, type CitationHistoryPage } from "./useAssistantCitationTarget";
160
import {
161
computeStableMessagesTimelineRows,
@@ -210,18 +173,11 @@ import {
173
shouldCollapseUserMessage,
174
shouldFollowWorkGroupAppend,
175
timelineTurnFoldRunIdsByEntryId,
213
- threadReadLabelPrefix,
214
- threadReadTargetId,
215
- threadReadTargetTitle,
216
- toolGroupAction,
217
- workEntryDisplayLabel,
218
- workEntryReadOutput,
176
workEntryIsVisibleInGroup,
177
worktreeSetupAgentStarted,
178
type StableMessagesTimelineRowsState,
179
type MessagesTimelineRow,
180
type TimelineLatestRun,
224
- type WorkGroupScrollAnchor,
181
} from "./MessagesTimeline.logic";
182
import { type ThreadFindMatch } from "./threadFind";
183
import { useThreadFindNavigation } from "./useThreadFindNavigation";
@@ -269,19 +225,14 @@ import { useMediaQuery } from "~/hooks/useMediaQuery";
225
import { cn } from "~/lib/utils";
226
import { useUiStateStore } from "~/uiStateStore";
227
import { type TimestampFormat } from "@t3tools/contracts/settings";
272
-import {
273
- formatChatTimestampTooltip,
274
- formatDayAwareTimestamp,
275
- formatUpcomingTimestamp,
276
-} from "../../timestampFormat";
277
-import { FetchedToolOutput, V2ItemInspector } from "./V2ItemInspector";
228
+import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
229
+import { V2ItemInspector } from "./V2ItemInspector";
230
import { useV2ItemSupport } from "../../state/v2ItemSupport";
231
import { Collapsible, CollapsibleTrigger, CollapsiblePanel } from "../ui/collapsible";
232
import {
233
isV2LifecycleItem,
234
EnvironmentSubagentAvatar,
235
SubagentElapsed,
284
- SubagentNotificationLink,
236
V2LifecycleRow,
237
type HandoffTimelineRun,
238
} from "./V2LifecycleRow";
@@ -299,76 +250,41 @@ import {
250
type ReviewCommentContext,
251
} from "../../reviewCommentContext";
252
import { TimelineMinimap } from "./TimelineMinimap";
253
+import {
254
+ type TimelineRowSharedState,
255
+ type TimelineRowActivityState,
256
+ TimelineRowCtx,
257
+ TimelineRowActivityCtx,
258
+ type WorkGroupViewState,
259
+ WorkGroupViewCtx,
260
+ type TimelineWorkEntry,
261
+ type TimelineRow,
262
+} from "./timelineRowContext";
263
+import {
264
+ MESSAGE_HEADING_LEVEL,
265
+ MessageAuthorHeading,
266
+ TimelineRowTimestamp,
267
+ ActivityShimmerOverlay,
268
+} from "./TimelineRowParts";
269
+import {
270
+ failedToolIconClassName,
271
+ toolIconAcceptsTint,
272
+ type WorkEntryIconName,
273
+ ToolActivityIconView,
274
+} from "./TimelineToolActivityIcon";
275
+import {
276
+ useThreadReadTarget,
277
+ threadReadLabel,
278
+ ThreadReadLabel,
279
+ ReasoningTraceContent,
280
+ SimpleWorkEntryRow,
281
+} from "./TimelineWorkEntryRow";
282
+import {
283
+ remarkThoughtPreview,
284
+ toolGroupSummaryIconName,
285
+ workEntryIconName,
286
+} from "./TimelineWorkEntryRow.logic";
287
303
-interface TimelineRowSharedState {
304
- citationRequest: AssistantCitationTarget | null;
305
- listRef: React.RefObject<LegendListRef | null>;
306
- timestampFormat: TimestampFormat;
307
- routeThreadKey: string;
308
- threadRef: ScopedThreadRef | null;
309
- markdownCwd: string | undefined;
310
- resolvedTheme: "light" | "dark";
311
- workspaceRoot: string | undefined;
312
- skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
313
- runs: ReadonlyArray<HandoffTimelineRun>;
314
- activeThreadEnvironmentId: EnvironmentId;
315
- onRevertToTurnCount: (targetTurnCount: number, messageId: MessageId) => void;
316
- onUseArtifactTemplate: (template: CodexArtifactTemplate) => void;
317
- onSendAppMessage: ((text: string) => Promise<void>) | undefined;
318
- onAppFullscreenChange: (rowId: string, fullscreen: boolean) => void;
319
- onRunShellCommand: ((command: string) => void) | undefined;
320
- findActive: boolean;
321
- onImageExpand: (preview: ExpandedImagePreview) => void;
322
- displayThreadKey?: string;
323
- onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
324
- onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;
325
- workflowOpening: WorkflowOpening | null;
326
- onForkFromRun: (input: {
327
- readonly sourceThreadId: ThreadId;
328
- readonly runId: RunId;
329
- }) => Promise<void>;
330
- onRollbackCheckpoint: (input: {
331
- readonly checkpointId: string;
332
- readonly scopeId: string;
333
- }) => void;
334
- onToggleTurnFold: (runId: RunId) => void;
335
- onToggleAttemptFold: (attemptId: RunAttemptId) => void;
336
- onFileOpen: (attachment: ChatFileAttachment) => void;
337
- onFileDownload: (attachment: ChatFileAttachment) => void;
338
- openPullRequest: (event: MouseEvent<HTMLElement>, url: string) => void;
339
- onToggleWorkGroup: (groupId: string, anchorKey: string) => void;
340
- onToggleWorkEntry: (anchorKey: string, collapsed: boolean) => void;
341
- onCancelWorktreeSetup: (() => void) | null;
342
- retryableWorkspacePreparationRunIds: ReadonlySet<RunId>;
343
- onRetryWorkspacePreparation: ((runId: RunId) => void) | null;
344
- onWorktreeSetupWorkLocally: (() => void) | null;
345
- onOpenWorktreeSetupTerminal: ((terminalId: string) => void) | null;
346
- workGroupViewState: WorkGroupViewState;
347
-}
348
-
349
-interface TimelineRowActivityState {
350
- isWorking: boolean;
351
- isCompacting: boolean;
352
- isRevertingCheckpoint: boolean;
353
- activeTurnInProgress: boolean;
354
- awaitingUser: boolean;
355
- isPreparingWorktree: boolean;
356
- latestRunId: RunId | null;
357
- backgroundWorktreeSetup: WorktreeSetupSnapshot | null;
358
-}
359
-
360
-const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
361
-const TimelineRowActivityCtx = createContext<TimelineRowActivityState>(null!);
362
-
363
-interface WorkGroupViewState {
364
- scrollPositions: Map<string, WorkGroupScrollAnchor>;
365
- expandedEntries: Set<string>;
366
-}
367
-
368
-const WorkGroupViewCtx = createContext<{
369
- state: WorkGroupViewState;
370
- onToggleEntry: (collapsed: boolean) => void;
371
-} | null>(null);
288
function timelineListStateFor(identity: string): {
289
readonly identity: string;
290
readonly rememberedPosition: RememberedTimelinePosition | undefined;
@@ -1620,9 +1536,6 @@ function getItemType(item: MessagesTimelineRow) {
1536
return `message:${item.message.role}:${lengthBucket}`;
1537
}
1538
1623
-type TimelineWorkEntry = Extract<MessagesTimelineRow, { kind: "work" }>["groupedEntries"][number];
1624
-type TimelineRow = MessagesTimelineRow;
1625
-
1539
const TimelineRowContent = memo(function TimelineRowContent({ row }: { row: TimelineRow }) {
1540
const isExpandedToolGroup = row.kind === "work" && row.isExpandedToolGroup;
1541
const isSubagentGroup = row.kind === "event" && row.projectedItem.item.type === "subagent";
@@ -1810,12 +1723,6 @@ function UserVideoAttachment({ file }: { readonly file: ChatFileAttachment }) {
1723
);
1724
}
1725
1813
-const MESSAGE_HEADING_LEVEL = 3;
1814
-
1815
-function MessageAuthorHeading({ children }: { children: string }) {
1816
- return <h3 className="sr-only select-none">{children}</h3>;
1817
-}
1818
-
1726
function UserMessageRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
1727
const ctx = use(TimelineRowCtx);
1728
return ctx.workflowOpening?.messageId === row.message.id ? (
@@ -2253,37 +2160,6 @@ function RevertUserMessageButton({
2160
);
2161
}
2162
2256
-function TimelineRowTimestamp({
2257
- createdAt,
2258
- timestampFormat,
2259
- className,
2260
- alwaysVisible = false,
2261
-}: {
2262
- createdAt: string;
2263
- timestampFormat: TimestampFormat;
2264
- className?: string;
2265
- alwaysVisible?: boolean;
2266
-}) {
2267
- return (
2268
- <Tooltip>
2269
- <TooltipTrigger
2270
- render={
2271
- <span
2272
- className={cn(
2273
- "pointer-events-none absolute me-1 shrink-0 whitespace-nowrap rounded-md text-muted-foreground text-xs tabular-nums opacity-0 group-hover/timeline-row:pointer-events-auto group-hover/timeline-row:static group-hover/timeline-row:opacity-100 group-focus-within/timeline-row:pointer-events-auto group-focus-within/timeline-row:static group-focus-within/timeline-row:opacity-100",
2274
- alwaysVisible && "pointer-events-auto static opacity-100",
2275
- className,
2276
- )}
2277
- />
2278
- }
2279
- >
2280
- {formatDayAwareTimestamp(createdAt, timestampFormat)}
2281
- </TooltipTrigger>
2282
- <TooltipPopup>{formatChatTimestampTooltip(createdAt, timestampFormat)}</TooltipPopup>
2283
- </Tooltip>
2284
- );
2285
-}
2286
-
2163
function TurnFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "turn-fold" }> }) {
2164
const ctx = use(TimelineRowCtx);
2165
@@ -3240,25 +3116,6 @@ function ExpandedWorkGroupEntries({
3116
3117
const workEntryKey = (entry: TimelineWorkEntry) => entry.id;
3118
3243
-function ActivityShimmerOverlay({ children }: { children: ReactNode }) {
3244
- return (
3245
- <span
3246
- aria-hidden
3247
- className="live-activity-focus pointer-events-none absolute inset-y-0 select-none"
3248
- >
3249
- <span className="live-activity-focus-counter block">
3250
- <span className="live-activity-focus-aligned block text-foreground">{children}</span>
3251
- </span>
3252
- </span>
3253
- );
3254
-}
3255
-
3256
-const failedToolIconClassName = "text-tool-error-icon/40";
3257
-
3258
-function toolIconAcceptsTint(toolIcon: ToolActivityIcon | undefined): boolean {
3259
- return toolIcon === undefined;
3260
-}
3261
-
3119
function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "working" }> }) {
3120
const { isCompacting, isPreparingWorktree, backgroundWorktreeSetup } =
3121
use(TimelineRowActivityCtx);
@@ -3458,49 +3315,6 @@ function LiveActivityContent({
3315
);
3316
}
3317
3461
-function useThreadReadTarget(entry: TimelineWorkEntry, environmentId: EnvironmentId) {
3462
- const rawThreadId = threadReadTargetId(entry);
3463
- const threadId = rawThreadId === null ? null : ThreadId.make(rawThreadId);
3464
- const shell = useThreadShell(threadId ? scopeThreadRef(environmentId, threadId) : null);
3465
- const title = threadReadTargetTitle(shell);
3466
- return threadId && title ? { threadId, title } : null;
3467
-}
3468
-
3469
-function threadReadLabel(label: string, target: ReturnType<typeof useThreadReadTarget>) {
3470
- const prefix = target && threadReadLabelPrefix(label);
3471
- return prefix ? { ...target, prefix, text: `${prefix} “${target.title}”` } : null;
3472
-}
3473
-
3474
-function ThreadReadLabel({
3475
- label,
3476
- environmentId,
3477
- linked,
3478
-}: {
3479
- label: NonNullable<ReturnType<typeof threadReadLabel>>;
3480
- environmentId: EnvironmentId;
3481
- linked: boolean;
3482
-}) {
3483
- return (
3484
- <span className="flex min-w-0">
3485
- <span className="shrink-0">{label.prefix} “</span>
3486
- {linked ? (
3487
- <Link
3488
- to="/$environmentId/$threadId"
3489
- params={{ environmentId, threadId: label.threadId }}
3490
- className="min-w-0 truncate rounded-sm text-foreground underline-offset-2 hover:underline focus-visible:outline-2 focus-visible:outline-ring"
3491
- onClick={stopRowToggle}
3492
- onKeyDown={stopRowToggle}
3493
- >
3494
- {label.title}
3495
- </Link>
3496
- ) : (
3497
- <span className="min-w-0 truncate">{label.title}</span>
3498
- )}
3499
- <span className="shrink-0">”</span>
3500
- </span>
3501
- );
3502
-}
3503
-
3318
function LiveWorkEntryTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "work-live" }> }) {
3319
const ctx = use(TimelineRowCtx);
3320
const threadTarget = useThreadReadTarget(row.entry, ctx.activeThreadEnvironmentId);
@@ -3597,49 +3411,6 @@ function LiveWorkEntryTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "
3411
);
3412
}
3413
3600
-function toolGroupSummaryIconName(
3601
- kind: Extract<TimelineRow, { kind: "work-toggle" }>["summaryKind"],
3602
-): WorkEntryIconName {
3603
- switch (kind) {
3604
- case "pull-request":
3605
- case "link-pr":
3606
- case "unlink-pr":
3607
- case "list-prs":
3608
- case "watch-pr":
3609
- case "unwatch-pr":
3610
- return "pull-request";
3611
- case "read":
3612
- return "eye";
3613
- case "edit":
3614
- return "square-pen";
3615
- case "command":
3616
- return "terminal";
3617
- case "thread-create":
3618
- return "t3-code";
3619
- case "browser":
3620
- return "browser";
3621
- case "device":
3622
- return "device";
3623
- case "search":
3624
- return "globe";
3625
- case "code-search":
3626
- return "search";
3627
- case "other":
3628
- return "wrench";
3629
- case "dynamic-tool":
3630
- return "hammer";
3631
- case "reasoning":
3632
- return "brain";
3633
- case "agent-tool":
3634
- return "bot";
3635
- case "tone-tool":
3636
- return "zap";
3637
- case "update":
3638
- case "mixed":
3639
- return "hammer";
3640
- }
3641
-}
3642
-
3414
function WorkGroupToggleTimelineRow({
3415
row,
3416
}: {
@@ -4506,936 +4277,3 @@ function useStableRows(rows: MessagesTimelineRow[], identity: string): MessagesT
4277
setState({ identity, source: rows, stable });
4278
return stable.result;
4279
}
4509
-
4510
-type WorkEntryIconName =
4511
- | "bot"
4512
- | "brain"
4513
- | "browser"
4514
- | "check"
4515
- | "circle-alert"
4516
- | "computer"
4517
- | "code"
4518
- | "device"
4519
- | "eye"
4520
- | "globe"
4521
- | "hammer"
4522
- | "message-circle"
4523
- | "search"
4524
- | "square-pen"
4525
- | "terminal"
4526
- | "pull-request"
4527
- | "t3-code"
4528
- | "wrench"
4529
- | "x"
4530
- | "zap";
4531
-
4532
-function BrowserAppIcon({ className }: { className: string }) {
4533
- return (
4534
- <svg
4535
- viewBox="0 0 24 24"
4536
- fill="none"
4537
- stroke="currentColor"
4538
- strokeWidth="1.9"
4539
- strokeLinecap="round"
4540
- strokeLinejoin="round"
4541
- className={className}
4542
- aria-hidden
4543
- >
4544
- <path d="M8.5 19H7.2C4.4 19 3 17.5 3 14.6V7.4C3 4.5 4.5 3 7.4 3h8.2C18.5 3 20 4.5 20 7.4v2.4" />
4545
- <circle cx="7.4" cy="7.2" r="0.75" fill="currentColor" stroke="none" />
4546
- <path d="M11.2 7.2h4.3" />
4547
- <path d="m12.4 11.4 7.5 2.6-3.4 1.6-1.5 3.6z" fill="currentColor" stroke="none" />
4548
- </svg>
4549
- );
4550
-}
4551
-
4552
-function ToolActivityIconView(props: {
4553
- icon: ToolActivityIcon | undefined;
4554
- fallbackName: WorkEntryIconName;
4555
- className: string;
4556
- muted: boolean;
4557
-}) {
4558
- const { resolvedTheme } = use(TimelineRowCtx);
4559
- const fallbackClassName = cn(props.className, props.muted && "opacity-70 light:brightness-60");
4560
- if (!props.icon) {
4561
- return <WorkEntryIcon name={props.fallbackName} className={fallbackClassName} />;
4562
- }
4563
- if (props.icon._tag === "website") {
4564
- const src = toolActivityFaviconUrl(props.icon, resolvedTheme, 32);
4565
- return src ? (
4566
- <ToolActivityImageIcon
4567
- key={src}
4568
- cacheKey={src}
4569
- src={src}
4570
- fallbackName={props.fallbackName}
4571
- className={props.className}
4572
- muted={props.muted}
4573
- />
4574
- ) : (
4575
- <WorkEntryIcon name={props.fallbackName} className={fallbackClassName} />
4576
- );
4577
- }
4578
- if (props.icon._tag === "themed-logo") {
4579
- const src =
4580
- resolvedTheme === "dark"
4581
- ? (props.icon.logoUrlDark ?? props.icon.logoUrl)
4582
- : props.icon.logoUrl;
4583
- return (
4584
- <ToolActivityImageIcon
4585
- key={src}
4586
- cacheKey={src}
4587
- src={src}
4588
- fallbackName={props.fallbackName}
4589
- className={props.className}
4590
- muted={props.muted}
4591
- />
4592
- );
4593
- }
4594
- return (
4595
- <NativeAppToolActivityIcon
4596
- app={props.icon.app}
4597
- fallbackName={props.fallbackName}
4598
- className={cn(props.className, "size-5")}
4599
- muted={props.muted}
4600
- />
4601
- );
4602
-}
4603
-
4604
-function NativeAppToolActivityIcon(props: {
4605
- app: Extract<ToolActivityIcon, { readonly _tag: "native-app" }>["app"];
4606
- fallbackName: WorkEntryIconName;
4607
- className: string;
4608
- muted: boolean;
4609
-}) {
4610
- const { activeThreadEnvironmentId } = use(TimelineRowCtx);
4611
- const asset = useAssetUrlState(activeThreadEnvironmentId, {
4612
- _tag: "native-app-icon",
4613
- app: props.app,
4614
- });
4615
- if (asset._tag !== "Success") {
4616
- return (
4617
- <WorkEntryIcon
4618
- name={props.fallbackName}
4619
- className={cn(props.className, props.muted && "opacity-70 light:brightness-60")}
4620
- />
4621
- );
4622
- }
4623
- const cacheKey = getProjectFaviconCacheKey(
4624
- activeThreadEnvironmentId,
4625
- JSON.stringify(props.app),
4626
- asset.url,
4627
- );
4628
- return (
4629
- <ToolActivityImageIcon
4630
- key={cacheKey}
4631
- cacheKey={cacheKey}
4632
- src={asset.url}
4633
- fallbackName={props.fallbackName}
4634
- className={props.className}
4635
- muted={props.muted}
4636
- />
4637
- );
4638
-}
4639
-
4640
-const loadedToolActivityIconSrcs = new Map<string, string>();
4641
-
4642
-function ToolActivityImageIcon(props: {
4643
- cacheKey: string;
4644
- src: string;
4645
- fallbackName: WorkEntryIconName;
4646
- className: string;
4647
- muted: boolean;
4648
-}) {
4649
- const [displayedSrc, setDisplayedSrc] = useState<string | null>(
4650
- () => loadedToolActivityIconSrcs.get(props.cacheKey) ?? null,
4651
- );
4652
- const isLoading = displayedSrc !== props.src;
4653
- const handleLoadError = (failedSrc: string) => {
4654
- if (loadedToolActivityIconSrcs.get(props.cacheKey) === failedSrc) {
4655
- loadedToolActivityIconSrcs.delete(props.cacheKey);
4656
- }
4657
- setDisplayedSrc((currentSrc) => (currentSrc === failedSrc ? null : currentSrc));
4658
- };
4659
- return (
4660
- <>
4661
- {displayedSrc === null ? (
4662
- <WorkEntryIcon
4663
- name={props.fallbackName}
4664
- className={cn(props.className, props.muted && "opacity-70 light:brightness-60")}
4665
- />
4666
- ) : null}
4667
- {displayedSrc ? (
4668
- <span
4669
- className={cn(
4670
- props.className,
4671
- "inline-block overflow-hidden rounded-xs bg-background",
4672
- props.muted && "opacity-70",
4673
- )}
4674
- >
4675
- <img
4676
- src={displayedSrc}
4677
- alt=""
4678
- aria-hidden
4679
- decoding="async"
4680
- referrerPolicy="no-referrer"
4681
- className={cn("block size-full object-contain", props.muted && "light:brightness-60")}
4682
- onError={() => handleLoadError(displayedSrc)}
4683
- />
4684
- </span>
4685
- ) : null}
4686
- {isLoading ? (
4687
- <img
4688
- src={props.src}
4689
- alt=""
4690
- aria-hidden
4691
- decoding="async"
4692
- referrerPolicy="no-referrer"
4693
- className="hidden"
4694
- onLoad={() => {
4695
- loadedToolActivityIconSrcs.set(props.cacheKey, props.src);
4696
- setDisplayedSrc(props.src);
4697
- }}
4698
- onError={() => handleLoadError(props.src)}
4699
- />
4700
- ) : null}
4701
- </>
4702
- );
4703
-}
4704
-
4705
-function WorkEntryIcon({ name, className }: { name: WorkEntryIconName; className: string }) {
4706
- switch (name) {
4707
- case "pull-request":
4708
- return <PullRequestGlyph.pullRequest className={className} aria-hidden />;
4709
- case "bot":
4710
- return <BotIcon className={className} aria-hidden />;
4711
- case "brain":
4712
- return <BrainIcon className={className} aria-hidden />;
4713
- case "browser":
4714
- case "computer":
4715
- return <BrowserAppIcon className={className} />;
4716
- case "code":
4717
- return <Code2Icon className={className} aria-hidden />;
4718
- case "device":
4719
- return <SmartphoneIcon className={className} aria-hidden />;
4720
- case "t3-code":
4721
- return <T3Wordmark className={className} aria-hidden />;
4722
- case "check":
4723
- return <CheckIcon className={className} aria-hidden />;
4724
- case "circle-alert":
4725
- return <CircleAlertIcon className={className} aria-hidden />;
4726
- case "eye":
4727
- return <EyeIcon className={className} aria-hidden />;
4728
- case "globe":
4729
- return <GlobeIcon className={className} aria-hidden />;
4730
- case "hammer":
4731
- return <HammerIcon className={className} aria-hidden />;
4732
- case "search":
4733
- return <SearchIcon className={className} aria-hidden />;
4734
- case "message-circle":
4735
- return <MessageCircleIcon className={className} aria-hidden />;
4736
- case "square-pen":
4737
- return <SquarePenIcon className={className} aria-hidden />;
4738
- case "terminal":
4739
- return <TerminalIcon className={className} aria-hidden />;
4740
- case "wrench":
4741
- return <WrenchIcon className={className} aria-hidden />;
4742
- case "x":
4743
- return <XIcon className={className} aria-hidden />;
4744
- case "zap":
4745
- return <ZapIcon className={className} aria-hidden />;
4746
- }
4747
-}
4748
-
4749
-function workToneIcon(tone: TimelineWorkEntry["tone"]): {
4750
- iconName: WorkEntryIconName;
4751
- className: string;
4752
-} {
4753
- if (tone === "error") {
4754
- return {
4755
- iconName: "circle-alert",
4756
- className: "text-foreground/92",
4757
- };
4758
- }
4759
- if (tone === "thinking") {
4760
- return {
4761
- iconName: "brain",
4762
- className: "text-icon-muted",
4763
- };
4764
- }
4765
- if (tone === "info") {
4766
- return {
4767
- iconName: "check",
4768
- className: "text-muted-foreground",
4769
- };
4770
- }
4771
- return {
4772
- iconName: "zap",
4773
- className: "text-foreground/92",
4774
- };
4775
-}
4776
-
4777
-function workEntryRawCommand(
4778
- workEntry: Pick<TimelineWorkEntry, "command" | "rawCommand">,
4779
-): string | null {
4780
- const rawCommand = workEntry.rawCommand?.trim();
4781
- if (!rawCommand || !workEntry.command) {
4782
- return null;
4783
- }
4784
- return rawCommand === workEntry.command.trim() ? null : rawCommand;
4785
-}
4786
-
4787
-function buildToolCallExpandedBody(
4788
- workEntry: TimelineWorkEntry,
4789
- workspaceRoot: string | undefined,
4790
- visibleLabel: string,
4791
- viewedImagePath: string | null,
4792
-): string | null {
4793
- const blocks: string[] = [];
4794
- const seen = new Set<string>([visibleLabel.trim()]);
4795
- const addBlock = (value: string | null | undefined) => {
4796
- const text = value?.trim();
4797
- if (!text || seen.has(text)) return;
4798
- seen.add(text);
4799
- blocks.push(text);
4800
- };
4801
- if (workEntry.itemType === "dynamic_tool" && workEntry.toolData !== undefined) {
4802
- const input =
4803
- workEntry.structuredPayload?.type === "dynamic_tool"
4804
- ? workEntry.structuredPayload.input
4805
- : workEntry.toolData !== null &&
4806
- typeof workEntry.toolData === "object" &&
4807
- "input" in workEntry.toolData
4808
- ? workEntry.toolData.input
4809
- : undefined;
4810
- if (input !== undefined) addBlock(`Tool input\n${JSON.stringify(input, null, 2)}`);
4811
- }
4812
- const command = workEntry.command?.trim();
4813
- const raw = workEntryRawCommand(workEntry);
4814
- if (command === visibleLabel.trim()) {
4815
- seen.add(command);
4816
- } else {
4817
- addBlock(raw ?? command);
4818
- }
4819
- const detail = workEntry.detail?.trim();
4820
- if (detail !== viewedImagePath?.trim()) {
4821
- addBlock(detail);
4822
- }
4823
- const viewedImagePaths = new Set(
4824
- viewedImagePath
4825
- ? [viewedImagePath.trim(), formatWorkspaceRelativePath(viewedImagePath, workspaceRoot)]
4826
- : [],
4827
- );
4828
- const changedFiles = (workEntry.changedFiles ?? []).flatMap((filePath) => {
4829
- const formattedPath = formatWorkspaceRelativePath(filePath, workspaceRoot);
4830
- return viewedImagePaths.has(filePath) ||
4831
- viewedImagePaths.has(formattedPath) ||
4832
- filePath.trim() === detail ||
4833
- formattedPath === detail
4834
- ? []
4835
- : [formattedPath];
4836
- });
4837
- if (changedFiles.length > 0) {
4838
- addBlock([...new Set(changedFiles)].join("\n"));
4839
- }
4840
- return blocks.length > 0 ? blocks.join("\n\n") : null;
4841
-}
4842
-
4843
-const toolCallExpandedBodyClassName =
4844
- "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";
4845
-
4846
-function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {
4847
- if (workEntry.structuredPayload?.type === "notification") {
4848
- if (workEntry.structuredPayload.outcome === "failed") return "circle-alert";
4849
- const source = workEntry.structuredPayload.source;
4850
- switch (source.kind) {
4851
- case "subagent":
4852
- case "delegated_task":
4853
- return "bot";
4854
- case "command":
4855
- return "terminal";
4856
- case "monitor":
4857
- return "eye";
4858
- case "background_task":
4859
- return "zap";
4860
- case "system":
4861
- return "t3-code";
4862
- default:
4863
- source satisfies never;
4864
- return "zap";
4865
- }
4866
- }
4867
- if (workEntry.itemType === "user_input_request" || workEntry.itemType === "approval_request") {
4868
- return "message-circle";
4869
- }
4870
- if (workEntry.toolSurface) return workEntry.toolSurface;
4871
- if (
4872
- workEntry.structuredPayload?.type === "dynamic_tool" &&
4873
- isJavaScriptReplTool(workEntry.structuredPayload.toolName)
4874
- )
4875
- return "code";
4876
- const toolPresentation = resolveWorkEntryToolPresentation(workEntry);
4877
- if (toolPresentation) return toolPresentation.icon;
4878
- const action = toolGroupAction(workEntry);
4879
- if (action !== "other") return toolGroupSummaryIconName(action);
4880
-
4881
- switch (workEntry.itemType) {
4882
- case "dynamic_tool":
4883
- return "wrench";
4884
- case "subagent":
4885
- return "bot";
4886
- }
4887
-
4888
- return workToneIcon(workEntry.tone).iconName;
4889
-}
4890
-
4891
-const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation();
4892
-
4893
-/** Compact reasoning keeps formulas while flattening other Markdown into label text. */
4894
-export function remarkThoughtPreview(fallback: string) {
4895
- return (tree: Root) => {
4896
- const children: RootContent[] = [];
4897
- const append = (value: string) => {
4898
- const last = children.at(-1);
4899
- const text = value.replace(/\s+/g, " ");
4900
- if (last?.type === "text") last.value = (last.value + text).replace(/\s+/g, " ");
4901
- else children.push({ type: "text", value: text });
4902
- };
4903
- const visit = (node: Root | RootContent) => {
4904
- if (node.type === "html" || node.type === "definition") return;
4905
- if (node.type === "math" || node.type === "inlineMath") {
4906
- children.push({
4907
- type: "inlineMath",
4908
- value: node.value,
4909
- position: node.position,
4910
- data: {
4911
- hName: "code",
4912
- hProperties: { className: ["language-math", "math-inline"] },
4913
- hChildren: [{ type: "text", value: node.value }],
4914
- },
4915
- });
4916
- } else if ("alt" in node) append(node.alt ?? "");
4917
- else if ("value" in node) append(node.value);
4918
- else if ("children" in node) {
4919
- node.children.forEach((child, index) => {
4920
- if (
4921
- index &&
4922
- ["root", "blockquote", "list", "listItem", "table", "tableRow"].includes(node.type)
4923
- )
4924
- append(" ");
4925
- visit(child);
4926
- });
4927
- } else if (node.type === "break") append(" ");
4928
- };
4929
- visit(tree);
4930
- const first = children[0];
4931
- const last = children.at(-1);
4932
- if (first?.type === "text") first.value = first.value.trimStart();
4933
- if (last?.type === "text") last.value = last.value.trimEnd();
4934
- tree.children = children.some((child) => child.type !== "text" || child.value)
4935
- ? children
4936
- : [{ type: "text", value: fallback }];
4937
- };
4938
-}
4939
-
4940
-function ReasoningTraceContent({ entries }: { entries: ReadonlyArray<TimelineWorkEntry> }) {
4941
- const ctx = use(TimelineRowCtx);
4942
- const { isWorking, latestRunId } = use(TimelineRowActivityCtx);
4943
- const isStreaming = (entry: TimelineWorkEntry) =>
4944
- isWorking && entry.runId === latestRunId && entry.toolLifecycleStatus === "inProgress";
4945
- return (
4946
- <WorkLogDetails followLive={entries.some(isStreaming)}>
4947
- {entries.map((entry) => (
4948
- <ChatMarkdown
4949
- key={entry.id}
4950
- className="text-foreground"
4951
- text={entry.detail ?? ""}
4952
- cwd={ctx.markdownCwd}
4953
- threadRef={ctx.threadRef ?? undefined}
4954
- skills={ctx.skills}
4955
- isStreaming={isStreaming(entry)}
4956
- headingLevelOffset={MESSAGE_HEADING_LEVEL}
4957
- onUseArtifactTemplate={ctx.onUseArtifactTemplate}
4958
- onImageExpand={ctx.onImageExpand}
4959
- lineBreaks
4960
- />
4961
- ))}
4962
- </WorkLogDetails>
4963
- );
4964
-}
4965
-
4966
-type WorkEntryRowProps = {
4967
- workEntry: TimelineWorkEntry;
4968
- workspaceRoot: string | undefined;
4969
- displayLabel?: string | undefined;
4970
- onToggleEntry?: ((collapsed: boolean) => void) | undefined;
4971
-};
4972
-
4973
-const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: WorkEntryRowProps) {
4974
- const ctx = use(TimelineRowCtx);
4975
- const item = props.workEntry.projectedItem?.item;
4976
- const childThreadId =
4977
- item?.type === "notification" ? notificationChildThreadId(item.source) : undefined;
4978
- if (item?.type !== "notification" || childThreadId === undefined) {
4979
- return <WorkEntryLogRow {...props} />;
4980
- }
4981
- return (
4982
- <SubagentNotificationLink
4983
- parentRef={scopeThreadRef(ctx.activeThreadEnvironmentId, item.threadId)}
4984
- childThreadId={childThreadId}
4985
- outcome={item.outcome}
4986
- createdAt={props.workEntry.createdAt}
4987
- timestampFormat={ctx.timestampFormat}
4988
- onOpenThread={ctx.onOpenThread}
4989
- fallback={<WorkEntryLogRow {...props} />}
4990
- />
4991
- );
4992
-});
4993
-
4994
-function WorkEntryLogRow(props: WorkEntryRowProps) {
4995
- const { workEntry, workspaceRoot, displayLabel } = props;
4996
- const ctx = use(TimelineRowCtx);
4997
- const { threadRef, onImageExpand, timestampFormat } = ctx;
4998
- const { retryableWorkspacePreparationRunIds, onRetryWorkspacePreparation } = ctx;
4999
- const threadTarget = useThreadReadTarget(workEntry, ctx.activeThreadEnvironmentId);
5000
- const createdThread =
5001
- workEntry.projectedItem?.item.type === "thread_created"
5002
- ? workEntry.projectedItem.item
5003
- : undefined;
5004
- const notifiedSubagentThreadId =
5005
- workEntry.projectedItem?.item.type === "notification"
5006
- ? notificationChildThreadId(workEntry.projectedItem.item.source)
5007
- : undefined;
5008
- const groupView = use(WorkGroupViewCtx);
5009
- const [expanded, setExpanded] = useState(
5010
- () => groupView?.state.expandedEntries.has(workEntry.id) ?? false,
5011
- );
5012
- const toggleExpanded = () => {
5013
- const next = !expanded;
5014
- if (groupView) {
5015
- groupView.onToggleEntry(!next);
5016
- if (next) groupView.state.expandedEntries.add(workEntry.id);
5017
- else groupView.state.expandedEntries.delete(workEntry.id);
5018
- } else {
5019
- props.onToggleEntry?.(!next);
5020
- }
5021
- setExpanded(next);
5022
- };
5023
- const failureItem = workEntry.projectedItem?.item;
5024
- if (failureItem?.type === "error" && failureItem.status === "failed") {
5025
- const warning = failureItem.failure.class === "usage_limit";
5026
- const resetAt = failureItem.failure.resetAt;
5027
- const resetTime = resetAt ? formatUpcomingTimestamp(resetAt, timestampFormat) : null;
5028
- const label = warning
5029
- ? `Usage limit reached.${resetTime ? ` Retry after ${resetTime}.` : ""}`
5030
- : workEntry.label;
5031
- const retryRunId =
5032
- failureItem.runId !== null &&
5033
- retryableWorkspacePreparationRunIds.has(failureItem.runId) &&
5034
- failureItem.failure.code === ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE
5035
- ? failureItem.runId
5036
- : null;
5037
- return (
5038
- <WorkLogRow
5039
- data-v2-item-type="error"
5040
- data-v2-item-visibility={workEntry.projectedItem?.visibility}
5041
- wrapLabel
5042
- icon={
5043
- <CircleAlertIcon
5044
- className={cn("size-4", warning ? "text-warning" : "text-destructive")}
5045
- />
5046
- }
5047
- label={
5048
- <span
5049
- className={cn("text-sm font-medium", warning ? "text-warning" : "text-destructive")}
5050
- >
5051
- {label}
5052
- </span>
5053
- }
5054
- trailing={
5055
- <TimelineRowTimestamp
5056
- createdAt={workEntry.createdAt}
5057
- timestampFormat={timestampFormat}
5058
- alwaysVisible
5059
- />
5060
- }
5061
- >
5062
- {!warning ? (
5063
- <p className="ms-7 whitespace-pre-wrap break-words py-1 text-sm leading-relaxed text-foreground/80">
5064
- {failureItem.failure.message}
5065
- </p>
5066
- ) : null}
5067
- {retryRunId !== null && onRetryWorkspacePreparation ? (
5068
- <div className="ms-7 pb-1">
5069
- <Button
5070
- type="button"
5071
- size="xs"
5072
- variant="outline"
5073
- onClick={() => onRetryWorkspacePreparation(retryRunId)}
5074
- >
5075
- <RotateCcwIcon aria-hidden />
5076
- Retry
5077
- </Button>
5078
- </div>
5079
- ) : null}
5080
- </WorkLogRow>
5081
- );
5082
- }
5083
- const iconConfig = workToneIcon(workEntry.tone);
5084
- const showWarningIndicator = workEntry.sourceActivityKind === "runtime.warning";
5085
- const showFailedIndicator =
5086
- !showWarningIndicator && workEntryDisplayIndicatesToolFailure(workEntry);
5087
- const showDestructiveRowStyle =
5088
- !showWarningIndicator &&
5089
- showFailedIndicator &&
5090
- (workEntrySignalsSevereFailure(workEntry) || !workLogEntryIsToolLike(workEntry));
5091
- const entryIconName =
5092
- showWarningIndicator || showDestructiveRowStyle ? "circle-alert" : workEntryIconName(workEntry);
5093
- const entryToolIcon =
5094
- showWarningIndicator || showDestructiveRowStyle
5095
- ? undefined
5096
- : (workEntry.toolIcon ?? workEntry.toolSource?.icon);
5097
- const isReasoning = workEntry.itemType === "reasoning";
5098
- const questionHeading = workEntry.questionAnswer
5099
- ? getQuestionTextPreview(workEntry.questionAnswer)
5100
- : "";
5101
- const previewText =
5102
- isReasoning && expanded
5103
- ? workEntry.toolLifecycleStatus === "inProgress"
5104
- ? "Thinking"
5105
- : "Thought"
5106
- : questionHeading || (displayLabel ?? workEntryDisplayLabel(workEntry, workspaceRoot));
5107
- const answerPreview =
5108
- workEntry.questionAnswer && hasQuestionAnswer(workEntry.questionAnswer)
5109
- ? getQuestionAnswerPreview(workEntry.questionAnswer)
5110
- : null;
5111
- const viewedImagePath = workEntryViewedImagePath(workEntry);
5112
- const payload = workEntry.structuredPayload;
5113
- const skill =
5114
- payload?.type === "dynamic_tool"
5115
- ? claudeSkillInvocation(payload.toolName, payload.input)
5116
- : undefined;
5117
- const plainOutput =
5118
- toolGroupAction(workEntry) === "read"
5119
- ? workEntryReadOutput(workEntry, workspaceRoot)
5120
- : skill
5121
- ? (skill.args ?? null)
5122
- : undefined;
5123
- const viewedImage =
5124
- viewedImagePath && threadRef
5125
- ? resolveViewedImageAsset(viewedImagePath, {
5126
- threadId: threadRef.threadId,
5127
- workspaceRoot,
5128
- })
5129
- : null;
5130
- const canExpand =
5131
- previewText.trim().length > 0 ||
5132
- (workEntry.itemType === "dynamic_tool" && workEntry.toolData !== undefined) ||
5133
- Boolean(
5134
- workEntryRawCommand(workEntry) ||
5135
- workEntry.command?.trim() ||
5136
- workEntry.detail?.trim() ||
5137
- workEntry.changedFiles?.length ||
5138
- viewedImage,
5139
- );
5140
- const expandedBody =
5141
- expanded && !isReasoning
5142
- ? plainOutput !== undefined
5143
- ? plainOutput
5144
- : buildToolCallExpandedBody(
5145
- workEntry,
5146
- workspaceRoot,
5147
- previewText,
5148
- viewedImage ? viewedImagePath : null,
5149
- )
5150
- : null;
5151
- const plainOutputFetches =
5152
- plainOutput !== undefined &&
5153
- workEntry.projectedItem !== undefined &&
5154
- turnItemNeedsDetailFetch(workEntry.projectedItem.item);
5155
- const canExpandProjectedItem =
5156
- plainOutput !== undefined
5157
- ? Boolean(plainOutput || viewedImage || workEntry.questionAnswer || plainOutputFetches)
5158
- : workEntry.projectedItem === undefined
5159
- ? canExpand
5160
- : isReasoning
5161
- ? Boolean(workEntry.detail?.trim())
5162
- : Boolean(
5163
- viewedImage ||
5164
- workEntry.questionAnswer ||
5165
- turnItemHasDetail(workEntry.projectedItem.item),
5166
- );
5167
- const iconWrapperClass = cn(
5168
- "flex size-4 items-center justify-center",
5169
- showWarningIndicator
5170
- ? "text-warning"
5171
- : showDestructiveRowStyle
5172
- ? "text-destructive"
5173
- : showFailedIndicator
5174
- ? failedToolIconClassName
5175
- : workEntry.tone === "tool"
5176
- ? "text-icon-muted"
5177
- : iconConfig.className,
5178
- );
5179
- const headingClass = showWarningIndicator
5180
- ? "font-medium text-warning"
5181
- : showDestructiveRowStyle
5182
- ? "font-medium text-destructive"
5183
- : workLogEntryIsToolLike(workEntry)
5184
- ? "text-secondary-label"
5185
- : "text-foreground/80";
5186
- const threadLabel = isReasoning ? null : threadReadLabel(previewText, threadTarget);
5187
- const accessiblePreview = [threadLabel?.text ?? previewText, answerPreview]
5188
- .filter(Boolean)
5189
- .join(": ");
5190
- const accessibleDisplayText = showFailedIndicator
5191
- ? `${accessiblePreview}, tool call failed`
5192
- : accessiblePreview;
5193
- const rowToggleProps = canExpandProjectedItem
5194
- ? {
5195
- role: "button" as const,
5196
- tabIndex: 0 as const,
5197
- "aria-label": accessibleDisplayText,
5198
- "aria-expanded": expanded,
5199
- onClick: toggleExpanded,
5200
- onKeyDown: (e: KeyboardEvent<HTMLDivElement>) => {
5201
- if (e.target === e.currentTarget && (e.key === "Enter" || e.key === " ")) {
5202
- e.preventDefault();
5203
- toggleExpanded();
5204
- }
5205
- },
5206
- }
5207
- : {};
5208
-
5209
- return (
5210
- <WorkLogRow
5211
- data-v2-item-type={workEntry.projectedItem?.item.type}
5212
- data-v2-item-visibility={workEntry.projectedItem?.visibility}
5213
- {...rowToggleProps}
5214
- icon={
5215
- <span
5216
- className={iconWrapperClass}
5217
- role={showFailedIndicator ? "img" : undefined}
5218
- aria-label={showFailedIndicator ? "Tool call failed" : undefined}
5219
- >
5220
- <ToolActivityIconView
5221
- icon={entryToolIcon}
5222
- fallbackName={entryIconName}
5223
- className="block size-4 shrink-0 stroke-2"
5224
- muted
5225
- />
5226
- </span>
5227
- }
5228
- label={
5229
- <div className="min-w-0 flex-1 overflow-hidden">
5230
- <p className="flex min-w-0 w-full items-baseline gap-1.5 text-sm leading-relaxed">
5231
- <span
5232
- className={cn(answerPreview ? "min-w-0" : "min-w-0 flex-1", "truncate", headingClass)}
5233
- >
5234
- {isReasoning && !expanded ? (
5235
- <ChatMarkdown
5236
- inline
5237
- text={workEntry.detail ?? previewText}
5238
- cwd={ctx.markdownCwd}
5239
- parseRawHtml={false}
5240
- extraRemarkPlugins={[
5241
- [
5242
- remarkThoughtPreview,
5243
- workEntry.toolLifecycleStatus === "inProgress" ? "Thinking" : "Thought",
5244
- ],
5245
- ]}
5246
- />
5247
- ) : threadLabel ? (
5248
- <ThreadReadLabel
5249
- label={threadLabel}
5250
- environmentId={ctx.activeThreadEnvironmentId}
5251
- linked
5252
- />
5253
- ) : (
5254
- previewText
5255
- )}
5256
- </span>
5257
- {answerPreview ? (
5258
- <span
5259
- className={cn(
5260
- "min-w-0 truncate",
5261
- !expanded &&
5262
- workEntry.questionAnswer &&
5263
- hasQuestionAnswer(workEntry.questionAnswer)
5264
- ? "text-foreground"
5265
- : "text-muted-foreground",
5266
- )}
5267
- >
5268
- {answerPreview}
5269
- </span>
5270
- ) : null}
5271
- </p>
5272
- </div>
5273
- }
5274
- trailing={
5275
- <>
5276
- {createdThread ? (
5277
- <button
5278
- type="button"
5279
- 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"
5280
- aria-label={`Open ${createdThread.title ?? "created thread"}`}
5281
- onClick={(event) => {
5282
- event.stopPropagation();
5283
- ctx.onOpenThread(createdThread.targetThreadId);
5284
- }}
5285
- onKeyDown={stopRowToggle}
5286
- >
5287
- Open chat
5288
- </button>
5289
- ) : null}
5290
- {notifiedSubagentThreadId ? (
5291
- <InlineButton
5292
- aria-label="Open subagent thread"
5293
- onClick={(event) => {
5294
- event.stopPropagation();
5295
- ctx.onOpenThread(notifiedSubagentThreadId);
5296
- }}
5297
- onKeyDown={stopRowToggle}
5298
- >
5299
- Open subagent
5300
- </InlineButton>
5301
- ) : null}
5302
- {showFailedIndicator &&
5303
- !showDestructiveRowStyle &&
5304
- !toolIconAcceptsTint(entryToolIcon) ? (
5305
- <XIcon aria-hidden className={cn("size-3 shrink-0", failedToolIconClassName)} />
5306
- ) : null}
5307
- <TimelineRowTimestamp createdAt={workEntry.createdAt} timestampFormat={timestampFormat} />
5308
- <span
5309
- className={cn(
5310
- "flex size-4 shrink-0 items-center justify-center",
5311
- !canExpandProjectedItem && "invisible",
5312
- )}
5313
- aria-hidden
5314
- >
5315
- <ChevronRightIcon
5316
- className={cn(
5317
- "size-3 shrink-0 text-icon-muted opacity-70 transition-transform duration-200",
5318
- expanded && "rotate-90",
5319
- )}
5320
- />
5321
- </span>
5322
- </>
5323
- }
5324
- >
5325
- {expanded && viewedImage && threadRef ? (
5326
- <WorkLogDetails kind="media">
5327
- <ChatMarkdownAssetImage
5328
- environmentId={threadRef.environmentId}
5329
- resource={viewedImage.resource}
5330
- alt={viewedImage.alt}
5331
- srcFragment={viewedImage.srcFragment}
5332
- workspaceRoot={workspaceRoot}
5333
- maxHeightRem={16}
5334
- onImageExpand={onImageExpand}
5335
- />
5336
- </WorkLogDetails>
5337
- ) : null}
5338
- {expanded && workEntry.questionAnswer ? (
5339
- <QuestionAnswerHistory answer={workEntry.questionAnswer} />
5340
- ) : null}
5341
- {expanded && isReasoning ? <ReasoningTraceContent entries={[workEntry]} /> : null}
5342
- {expanded &&
5343
- !isReasoning &&
5344
- !workEntry.questionAnswer &&
5345
- canExpandProjectedItem &&
5346
- (expandedBody ||
5347
- plainOutputFetches ||
5348
- (workEntry.projectedItem && plainOutput === undefined)) ? (
5349
- <WorkLogDetails kind="panel">
5350
- {workEntry.projectedItem && plainOutput === undefined ? (
5351
- <V2ItemInspector
5352
- projectedItem={workEntry.projectedItem}
5353
- environmentId={ctx.activeThreadEnvironmentId}
5354
- cwd={ctx.markdownCwd}
5355
- workspaceRoot={workspaceRoot}
5356
- onOpenThread={ctx.onOpenThread}
5357
- onOpenTurnDiff={ctx.onOpenTurnDiff}
5358
- onRollbackCheckpoint={ctx.onRollbackCheckpoint}
5359
- onImageExpand={ctx.onImageExpand}
5360
- />
5361
- ) : (
5362
- <>
5363
- {expandedBody ? (
5364
- <pre className={toolCallExpandedBodyClassName}>{expandedBody}</pre>
5365
- ) : null}
5366
- {plainOutputFetches && workEntry.projectedItem ? (
5367
- <FetchedToolOutput
5368
- projectedItem={workEntry.projectedItem}
5369
- environmentId={ctx.activeThreadEnvironmentId}
5370
- onImageExpand={onImageExpand}
5371
- />
5372
- ) : null}
5373
- </>
5374
- )}
5375
- </WorkLogDetails>
5376
- ) : null}
5377
- </WorkLogRow>
5378
- );
5379
-}
5380
-
5381
-function QuestionAnswerHistory({
5382
- answer,
5383
-}: {
5384
- answer: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
5385
-}) {
5386
- const { activeThreadEnvironmentId } = use(TimelineRowCtx);
5387
- const attachments = Object.values(answer.attachmentsByQuestionId).flat();
5388
- const resources = attachments.map((attachment) => ({
5389
- _tag: "attachment" as const,
5390
- attachmentId: attachment.id,
5391
- }));
5392
- const urls = useAssetUrls(activeThreadEnvironmentId, resources);
5393
- return (
5394
- <div className="ms-7 mt-2 space-y-2" onClick={stopRowToggle}>
5395
- {[
5396
- ...new Set([
5397
- ...Object.keys(answer.questionTextById ?? {}),
5398
- ...Object.keys(answer.answers),
5399
- ...Object.keys(answer.attachmentsByQuestionId),
5400
- ]),
5401
- ].map((questionId) => (
5402
- <div key={questionId} className="space-y-1">
5403
- {answer.questionTextById?.[questionId] ? (
5404
- <p className="whitespace-pre-wrap text-sm text-muted-foreground">
5405
- {answer.questionTextById[questionId]}
5406
- </p>
5407
- ) : null}
5408
- {getQuestionAnswerText(answer.answers[questionId]) ? (
5409
- <p className="ms-3 whitespace-pre-wrap text-sm text-muted-foreground">
5410
- {getQuestionAnswerText(answer.answers[questionId])}
5411
- </p>
5412
- ) : null}
5413
- <div className="flex flex-wrap gap-2">
5414
- {(answer.attachmentsByQuestionId[questionId] ?? []).map((attachment) => {
5415
- const url = urls[attachments.indexOf(attachment)];
5416
- return (
5417
- <a
5418
- key={attachment.id}
5419
- href={url ?? undefined}
5420
- target="_blank"
5421
- rel="noreferrer"
5422
- className="text-sm underline"
5423
- >
5424
- {attachment.type === "image" && url ? (
5425
- <img
5426
- src={url}
5427
- alt={attachment.name}
5428
- className="h-20 max-w-32 rounded object-contain"
5429
- />
5430
- ) : (
5431
- attachment.name
5432
- )}
5433
- </a>
5434
- );
5435
- })}
5436
- </div>
5437
- </div>
5438
- ))}
5439
- </div>
5440
- );
5441
-}
apps/web/src/components/chat/TimelineRowParts.tsx
new
+55
@@ -0,0 +1,55 @@
1
+import { type ReactNode } from "react";
2
+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
3
+import { cn } from "~/lib/utils";
4
+import { type TimestampFormat } from "@t3tools/contracts/settings";
5
+import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
6
+
7
+export const MESSAGE_HEADING_LEVEL = 3;
8
+
9
+export function MessageAuthorHeading({ children }: { children: string }) {
10
+ return <h3 className="sr-only select-none">{children}</h3>;
11
+}
12
+
13
+export function TimelineRowTimestamp({
14
+ createdAt,
15
+ timestampFormat,
16
+ className,
17
+ alwaysVisible = false,
18
+}: {
19
+ createdAt: string;
20
+ timestampFormat: TimestampFormat;
21
+ className?: string;
22
+ alwaysVisible?: boolean;
23
+}) {
24
+ return (
25
+ <Tooltip>
26
+ <TooltipTrigger
27
+ render={
28
+ <span
29
+ className={cn(
30
+ "pointer-events-none absolute me-1 shrink-0 whitespace-nowrap rounded-md text-muted-foreground text-xs tabular-nums opacity-0 group-hover/timeline-row:pointer-events-auto group-hover/timeline-row:static group-hover/timeline-row:opacity-100 group-focus-within/timeline-row:pointer-events-auto group-focus-within/timeline-row:static group-focus-within/timeline-row:opacity-100",
31
+ alwaysVisible && "pointer-events-auto static opacity-100",
32
+ className,
33
+ )}
34
+ />
35
+ }
36
+ >
37
+ {formatDayAwareTimestamp(createdAt, timestampFormat)}
38
+ </TooltipTrigger>
39
+ <TooltipPopup>{formatChatTimestampTooltip(createdAt, timestampFormat)}</TooltipPopup>
40
+ </Tooltip>
41
+ );
42
+}
43
+
44
+export function ActivityShimmerOverlay({ children }: { children: ReactNode }) {
45
+ return (
46
+ <span
47
+ aria-hidden
48
+ className="live-activity-focus pointer-events-none absolute inset-y-0 select-none"
49
+ >
50
+ <span className="live-activity-focus-counter block">
51
+ <span className="live-activity-focus-aligned block text-foreground">{children}</span>
52
+ </span>
53
+ </span>
54
+ );
55
+}
apps/web/src/components/chat/TimelineToolActivityIcon.tsx
new
+272
@@ -0,0 +1,272 @@
1
+import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
2
+import { type ToolActivityIcon } from "@t3tools/contracts";
3
+import { toolActivityFaviconUrl } from "@t3tools/shared/favicon";
4
+import { getProjectFaviconCacheKey } from "@t3tools/shared/projectFavicon";
5
+import { use, useState } from "react";
6
+import { T3Wordmark } from "../T3Wordmark";
7
+import {
8
+ BotIcon,
9
+ BrainIcon,
10
+ CheckIcon,
11
+ CircleAlertIcon,
12
+ EyeIcon,
13
+ GlobeIcon,
14
+ MessageCircleIcon,
15
+ SearchIcon,
16
+ SmartphoneIcon,
17
+ SquarePenIcon,
18
+ TerminalIcon,
19
+ HammerIcon,
20
+ WrenchIcon,
21
+ Code2Icon,
22
+ XIcon,
23
+ ZapIcon,
24
+} from "lucide-react";
25
+import { useAssetUrlState } from "../../assets/assetUrls";
26
+import { cn } from "~/lib/utils";
27
+import { TimelineRowCtx } from "./timelineRowContext";
28
+
29
+export const failedToolIconClassName = "text-tool-error-icon/40";
30
+
31
+export function toolIconAcceptsTint(toolIcon: ToolActivityIcon | undefined): boolean {
32
+ return toolIcon === undefined;
33
+}
34
+
35
+export type WorkEntryIconName =
36
+ | "bot"
37
+ | "brain"
38
+ | "browser"
39
+ | "check"
40
+ | "circle-alert"
41
+ | "computer"
42
+ | "code"
43
+ | "device"
44
+ | "eye"
45
+ | "globe"
46
+ | "hammer"
47
+ | "message-circle"
48
+ | "search"
49
+ | "square-pen"
50
+ | "terminal"
51
+ | "pull-request"
52
+ | "t3-code"
53
+ | "wrench"
54
+ | "x"
55
+ | "zap";
56
+
57
+function BrowserAppIcon({ className }: { className: string }) {
58
+ return (
59
+ <svg
60
+ viewBox="0 0 24 24"
61
+ fill="none"
62
+ stroke="currentColor"
63
+ strokeWidth="1.9"
64
+ strokeLinecap="round"
65
+ strokeLinejoin="round"
66
+ className={className}
67
+ aria-hidden
68
+ >
69
+ <path d="M8.5 19H7.2C4.4 19 3 17.5 3 14.6V7.4C3 4.5 4.5 3 7.4 3h8.2C18.5 3 20 4.5 20 7.4v2.4" />
70
+ <circle cx="7.4" cy="7.2" r="0.75" fill="currentColor" stroke="none" />
71
+ <path d="M11.2 7.2h4.3" />
72
+ <path d="m12.4 11.4 7.5 2.6-3.4 1.6-1.5 3.6z" fill="currentColor" stroke="none" />
73
+ </svg>
74
+ );
75
+}
76
+
77
+export function ToolActivityIconView(props: {
78
+ icon: ToolActivityIcon | undefined;
79
+ fallbackName: WorkEntryIconName;
80
+ className: string;
81
+ muted: boolean;
82
+}) {
83
+ const { resolvedTheme } = use(TimelineRowCtx);
84
+ const fallbackClassName = cn(props.className, props.muted && "opacity-70 light:brightness-60");
85
+ if (!props.icon) {
86
+ return <WorkEntryIcon name={props.fallbackName} className={fallbackClassName} />;
87
+ }
88
+ if (props.icon._tag === "website") {
89
+ const src = toolActivityFaviconUrl(props.icon, resolvedTheme, 32);
90
+ return src ? (
91
+ <ToolActivityImageIcon
92
+ key={src}
93
+ cacheKey={src}
94
+ src={src}
95
+ fallbackName={props.fallbackName}
96
+ className={props.className}
97
+ muted={props.muted}
98
+ />
99
+ ) : (
100
+ <WorkEntryIcon name={props.fallbackName} className={fallbackClassName} />
101
+ );
102
+ }
103
+ if (props.icon._tag === "themed-logo") {
104
+ const src =
105
+ resolvedTheme === "dark"
106
+ ? (props.icon.logoUrlDark ?? props.icon.logoUrl)
107
+ : props.icon.logoUrl;
108
+ return (
109
+ <ToolActivityImageIcon
110
+ key={src}
111
+ cacheKey={src}
112
+ src={src}
113
+ fallbackName={props.fallbackName}
114
+ className={props.className}
115
+ muted={props.muted}
116
+ />
117
+ );
118
+ }
119
+ return (
120
+ <NativeAppToolActivityIcon
121
+ app={props.icon.app}
122
+ fallbackName={props.fallbackName}
123
+ className={cn(props.className, "size-5")}
124
+ muted={props.muted}
125
+ />
126
+ );
127
+}
128
+
129
+function NativeAppToolActivityIcon(props: {
130
+ app: Extract<ToolActivityIcon, { readonly _tag: "native-app" }>["app"];
131
+ fallbackName: WorkEntryIconName;
132
+ className: string;
133
+ muted: boolean;
134
+}) {
135
+ const { activeThreadEnvironmentId } = use(TimelineRowCtx);
136
+ const asset = useAssetUrlState(activeThreadEnvironmentId, {
137
+ _tag: "native-app-icon",
138
+ app: props.app,
139
+ });
140
+ if (asset._tag !== "Success") {
141
+ return (
142
+ <WorkEntryIcon
143
+ name={props.fallbackName}
144
+ className={cn(props.className, props.muted && "opacity-70 light:brightness-60")}
145
+ />
146
+ );
147
+ }
148
+ const cacheKey = getProjectFaviconCacheKey(
149
+ activeThreadEnvironmentId,
150
+ JSON.stringify(props.app),
151
+ asset.url,
152
+ );
153
+ return (
154
+ <ToolActivityImageIcon
155
+ key={cacheKey}
156
+ cacheKey={cacheKey}
157
+ src={asset.url}
158
+ fallbackName={props.fallbackName}
159
+ className={props.className}
160
+ muted={props.muted}
161
+ />
162
+ );
163
+}
164
+
165
+const loadedToolActivityIconSrcs = new Map<string, string>();
166
+
167
+function ToolActivityImageIcon(props: {
168
+ cacheKey: string;
169
+ src: string;
170
+ fallbackName: WorkEntryIconName;
171
+ className: string;
172
+ muted: boolean;
173
+}) {
174
+ const [displayedSrc, setDisplayedSrc] = useState<string | null>(
175
+ () => loadedToolActivityIconSrcs.get(props.cacheKey) ?? null,
176
+ );
177
+ const isLoading = displayedSrc !== props.src;
178
+ const handleLoadError = (failedSrc: string) => {
179
+ if (loadedToolActivityIconSrcs.get(props.cacheKey) === failedSrc) {
180
+ loadedToolActivityIconSrcs.delete(props.cacheKey);
181
+ }
182
+ setDisplayedSrc((currentSrc) => (currentSrc === failedSrc ? null : currentSrc));
183
+ };
184
+ return (
185
+ <>
186
+ {displayedSrc === null ? (
187
+ <WorkEntryIcon
188
+ name={props.fallbackName}
189
+ className={cn(props.className, props.muted && "opacity-70 light:brightness-60")}
190
+ />
191
+ ) : null}
192
+ {displayedSrc ? (
193
+ <span
194
+ className={cn(
195
+ props.className,
196
+ "inline-block overflow-hidden rounded-xs bg-background",
197
+ props.muted && "opacity-70",
198
+ )}
199
+ >
200
+ <img
201
+ src={displayedSrc}
202
+ alt=""
203
+ aria-hidden
204
+ decoding="async"
205
+ referrerPolicy="no-referrer"
206
+ className={cn("block size-full object-contain", props.muted && "light:brightness-60")}
207
+ onError={() => handleLoadError(displayedSrc)}
208
+ />
209
+ </span>
210
+ ) : null}
211
+ {isLoading ? (
212
+ <img
213
+ src={props.src}
214
+ alt=""
215
+ aria-hidden
216
+ decoding="async"
217
+ referrerPolicy="no-referrer"
218
+ className="hidden"
219
+ onLoad={() => {
220
+ loadedToolActivityIconSrcs.set(props.cacheKey, props.src);
221
+ setDisplayedSrc(props.src);
222
+ }}
223
+ onError={() => handleLoadError(props.src)}
224
+ />
225
+ ) : null}
226
+ </>
227
+ );
228
+}
229
+
230
+function WorkEntryIcon({ name, className }: { name: WorkEntryIconName; className: string }) {
231
+ switch (name) {
232
+ case "pull-request":
233
+ return <PullRequestGlyph.pullRequest className={className} aria-hidden />;
234
+ case "bot":
235
+ return <BotIcon className={className} aria-hidden />;
236
+ case "brain":
237
+ return <BrainIcon className={className} aria-hidden />;
238
+ case "browser":
239
+ case "computer":
240
+ return <BrowserAppIcon className={className} />;
241
+ case "code":
242
+ return <Code2Icon className={className} aria-hidden />;
243
+ case "device":
244
+ return <SmartphoneIcon className={className} aria-hidden />;
245
+ case "t3-code":
246
+ return <T3Wordmark className={className} aria-hidden />;
247
+ case "check":
248
+ return <CheckIcon className={className} aria-hidden />;
249
+ case "circle-alert":
250
+ return <CircleAlertIcon className={className} aria-hidden />;
251
+ case "eye":
252
+ return <EyeIcon className={className} aria-hidden />;
253
+ case "globe":
254
+ return <GlobeIcon className={className} aria-hidden />;
255
+ case "hammer":
256
+ return <HammerIcon className={className} aria-hidden />;
257
+ case "search":
258
+ return <SearchIcon className={className} aria-hidden />;
259
+ case "message-circle":
260
+ return <MessageCircleIcon className={className} aria-hidden />;
261
+ case "square-pen":
262
+ return <SquarePenIcon className={className} aria-hidden />;
263
+ case "terminal":
264
+ return <TerminalIcon className={className} aria-hidden />;
265
+ case "wrench":
266
+ return <WrenchIcon className={className} aria-hidden />;
267
+ case "x":
268
+ return <XIcon className={className} aria-hidden />;
269
+ case "zap":
270
+ return <ZapIcon className={className} aria-hidden />;
271
+ }
272
+}
apps/web/src/components/chat/TimelineWorkEntryRow.logic.ts
new
+236
@@ -0,0 +1,236 @@
1
+import type { Root, RootContent } from "mdast";
2
+import { resolveWorkEntryToolPresentation } from "@t3tools/client-runtime/work-log/presentation";
3
+import { isJavaScriptReplTool } from "@t3tools/shared/toolActivity";
4
+import { toolGroupAction } from "./MessagesTimeline.logic";
5
+import { formatWorkspaceRelativePath } from "../../filePathDisplay";
6
+import { type TimelineWorkEntry, type TimelineRow } from "./timelineRowContext";
7
+import { type WorkEntryIconName } from "./TimelineToolActivityIcon";
8
+
9
+export function toolGroupSummaryIconName(
10
+ kind: Extract<TimelineRow, { kind: "work-toggle" }>["summaryKind"],
11
+): WorkEntryIconName {
12
+ switch (kind) {
13
+ case "pull-request":
14
+ case "link-pr":
15
+ case "unlink-pr":
16
+ case "list-prs":
17
+ case "watch-pr":
18
+ case "unwatch-pr":
19
+ return "pull-request";
20
+ case "read":
21
+ return "eye";
22
+ case "edit":
23
+ return "square-pen";
24
+ case "command":
25
+ return "terminal";
26
+ case "thread-create":
27
+ return "t3-code";
28
+ case "browser":
29
+ return "browser";
30
+ case "device":
31
+ return "device";
32
+ case "search":
33
+ return "globe";
34
+ case "code-search":
35
+ return "search";
36
+ case "other":
37
+ return "wrench";
38
+ case "dynamic-tool":
39
+ return "hammer";
40
+ case "reasoning":
41
+ return "brain";
42
+ case "agent-tool":
43
+ return "bot";
44
+ case "tone-tool":
45
+ return "zap";
46
+ case "update":
47
+ case "mixed":
48
+ return "hammer";
49
+ }
50
+}
51
+
52
+export function workToneIcon(tone: TimelineWorkEntry["tone"]): {
53
+ iconName: WorkEntryIconName;
54
+ className: string;
55
+} {
56
+ if (tone === "error") {
57
+ return {
58
+ iconName: "circle-alert",
59
+ className: "text-foreground/92",
60
+ };
61
+ }
62
+ if (tone === "thinking") {
63
+ return {
64
+ iconName: "brain",
65
+ className: "text-icon-muted",
66
+ };
67
+ }
68
+ if (tone === "info") {
69
+ return {
70
+ iconName: "check",
71
+ className: "text-muted-foreground",
72
+ };
73
+ }
74
+ return {
75
+ iconName: "zap",
76
+ className: "text-foreground/92",
77
+ };
78
+}
79
+
80
+export function workEntryRawCommand(
81
+ workEntry: Pick<TimelineWorkEntry, "command" | "rawCommand">,
82
+): string | null {
83
+ const rawCommand = workEntry.rawCommand?.trim();
84
+ if (!rawCommand || !workEntry.command) {
85
+ return null;
86
+ }
87
+ return rawCommand === workEntry.command.trim() ? null : rawCommand;
88
+}
89
+
90
+export function buildToolCallExpandedBody(
91
+ workEntry: TimelineWorkEntry,
92
+ workspaceRoot: string | undefined,
93
+ visibleLabel: string,
94
+ viewedImagePath: string | null,
95
+): string | null {
96
+ const blocks: string[] = [];
97
+ const seen = new Set<string>([visibleLabel.trim()]);
98
+ const addBlock = (value: string | null | undefined) => {
99
+ const text = value?.trim();
100
+ if (!text || seen.has(text)) return;
101
+ seen.add(text);
102
+ blocks.push(text);
103
+ };
104
+ if (workEntry.itemType === "dynamic_tool" && workEntry.toolData !== undefined) {
105
+ const input =
106
+ workEntry.structuredPayload?.type === "dynamic_tool"
107
+ ? workEntry.structuredPayload.input
108
+ : workEntry.toolData !== null &&
109
+ typeof workEntry.toolData === "object" &&
110
+ "input" in workEntry.toolData
111
+ ? workEntry.toolData.input
112
+ : undefined;
113
+ if (input !== undefined) addBlock(`Tool input\n${JSON.stringify(input, null, 2)}`);
114
+ }
115
+ const command = workEntry.command?.trim();
116
+ const raw = workEntryRawCommand(workEntry);
117
+ if (command === visibleLabel.trim()) {
118
+ seen.add(command);
119
+ } else {
120
+ addBlock(raw ?? command);
121
+ }
122
+ const detail = workEntry.detail?.trim();
123
+ if (detail !== viewedImagePath?.trim()) {
124
+ addBlock(detail);
125
+ }
126
+ const viewedImagePaths = new Set(
127
+ viewedImagePath
128
+ ? [viewedImagePath.trim(), formatWorkspaceRelativePath(viewedImagePath, workspaceRoot)]
129
+ : [],
130
+ );
131
+ const changedFiles = (workEntry.changedFiles ?? []).flatMap((filePath) => {
132
+ const formattedPath = formatWorkspaceRelativePath(filePath, workspaceRoot);
133
+ return viewedImagePaths.has(filePath) ||
134
+ viewedImagePaths.has(formattedPath) ||
135
+ filePath.trim() === detail ||
136
+ formattedPath === detail
137
+ ? []
138
+ : [formattedPath];
139
+ });
140
+ if (changedFiles.length > 0) {
141
+ addBlock([...new Set(changedFiles)].join("\n"));
142
+ }
143
+ return blocks.length > 0 ? blocks.join("\n\n") : null;
144
+}
145
+
146
+export function workEntryIconName(workEntry: TimelineWorkEntry): WorkEntryIconName {
147
+ if (workEntry.structuredPayload?.type === "notification") {
148
+ if (workEntry.structuredPayload.outcome === "failed") return "circle-alert";
149
+ const source = workEntry.structuredPayload.source;
150
+ switch (source.kind) {
151
+ case "subagent":
152
+ case "delegated_task":
153
+ return "bot";
154
+ case "command":
155
+ return "terminal";
156
+ case "monitor":
157
+ return "eye";
158
+ case "background_task":
159
+ return "zap";
160
+ case "system":
161
+ return "t3-code";
162
+ default:
163
+ source satisfies never;
164
+ return "zap";
165
+ }
166
+ }
167
+ if (workEntry.itemType === "user_input_request" || workEntry.itemType === "approval_request") {
168
+ return "message-circle";
169
+ }
170
+ if (workEntry.toolSurface) return workEntry.toolSurface;
171
+ if (
172
+ workEntry.structuredPayload?.type === "dynamic_tool" &&
173
+ isJavaScriptReplTool(workEntry.structuredPayload.toolName)
174
+ )
175
+ return "code";
176
+ const toolPresentation = resolveWorkEntryToolPresentation(workEntry);
177
+ if (toolPresentation) return toolPresentation.icon;
178
+ const action = toolGroupAction(workEntry);
179
+ if (action !== "other") return toolGroupSummaryIconName(action);
180
+
181
+ switch (workEntry.itemType) {
182
+ case "dynamic_tool":
183
+ return "wrench";
184
+ case "subagent":
185
+ return "bot";
186
+ }
187
+
188
+ return workToneIcon(workEntry.tone).iconName;
189
+}
190
+
191
+/** Compact reasoning keeps formulas while flattening other Markdown into label text. */
192
+export function remarkThoughtPreview(fallback: string) {
193
+ return (tree: Root) => {
194
+ const children: RootContent[] = [];
195
+ const append = (value: string) => {
196
+ const last = children.at(-1);
197
+ const text = value.replace(/\s+/g, " ");
198
+ if (last?.type === "text") last.value = (last.value + text).replace(/\s+/g, " ");
199
+ else children.push({ type: "text", value: text });
200
+ };
201
+ const visit = (node: Root | RootContent) => {
202
+ if (node.type === "html" || node.type === "definition") return;
203
+ if (node.type === "math" || node.type === "inlineMath") {
204
+ children.push({
205
+ type: "inlineMath",
206
+ value: node.value,
207
+ position: node.position,
208
+ data: {
209
+ hName: "code",
210
+ hProperties: { className: ["language-math", "math-inline"] },
211
+ hChildren: [{ type: "text", value: node.value }],
212
+ },
213
+ });
214
+ } else if ("alt" in node) append(node.alt ?? "");
215
+ else if ("value" in node) append(node.value);
216
+ else if ("children" in node) {
217
+ node.children.forEach((child, index) => {
218
+ if (
219
+ index &&
220
+ ["root", "blockquote", "list", "listItem", "table", "tableRow"].includes(node.type)
221
+ )
222
+ append(" ");
223
+ visit(child);
224
+ });
225
+ } else if (node.type === "break") append(" ");
226
+ };
227
+ visit(tree);
228
+ const first = children[0];
229
+ const last = children.at(-1);
230
+ if (first?.type === "text") first.value = first.value.trimStart();
231
+ if (last?.type === "text") last.value = last.value.trimEnd();
232
+ tree.children = children.some((child) => child.type !== "text" || child.value)
233
+ ? children
234
+ : [{ type: "text", value: fallback }];
235
+ };
236
+}
apps/web/src/components/chat/TimelineWorkEntryRow.tsx
new
+617
@@ -0,0 +1,617 @@
1
+import { WorkLogDetails, WorkLogRow } from "./WorkLog";
2
+import {
3
+ getQuestionAnswerPreview,
4
+ getQuestionAnswerText,
5
+ getQuestionTextPreview,
6
+ hasQuestionAnswer,
7
+} from "@t3tools/client-runtime/work-log/user-input";
8
+import {
9
+ ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE,
10
+ type EnvironmentId,
11
+ ThreadId,
12
+} from "@t3tools/contracts";
13
+import { scopeThreadRef } from "@t3tools/client-runtime/environment";
14
+import { Link } from "@tanstack/react-router";
15
+import { notificationChildThreadId } from "@t3tools/client-runtime/state/thread-execution";
16
+import {
17
+ resolveViewedImageAsset,
18
+ workEntryViewedImagePath,
19
+} from "@t3tools/client-runtime/work-log/presentation";
20
+import {
21
+ turnItemHasDetail,
22
+ turnItemNeedsDetailFetch,
23
+} from "@t3tools/client-runtime/work-log/item-detail";
24
+import { claudeSkillInvocation } from "@t3tools/shared/toolActivity";
25
+import { memo, use, useState, type KeyboardEvent } from "react";
26
+import {
27
+ workEntryDisplayIndicatesToolFailure,
28
+ workEntrySignalsSevereFailure,
29
+ workLogEntryIsToolLike,
30
+} from "../../session-logic";
31
+import ChatMarkdown, { ChatMarkdownAssetImage } from "../ChatMarkdown";
32
+import { ChevronRightIcon, CircleAlertIcon, XIcon, RotateCcwIcon } from "lucide-react";
33
+import { Button, InlineButton } from "../ui/button";
34
+import { useAssetUrls } from "../../assets/assetUrls";
35
+import { useThreadShell } from "../../state/entities";
36
+import {
37
+ threadReadLabelPrefix,
38
+ threadReadTargetId,
39
+ threadReadTargetTitle,
40
+ toolGroupAction,
41
+ workEntryDisplayLabel,
42
+ workEntryReadOutput,
43
+} from "./MessagesTimeline.logic";
44
+import { cn } from "~/lib/utils";
45
+import { formatUpcomingTimestamp } from "../../timestampFormat";
46
+import { FetchedToolOutput, V2ItemInspector } from "./V2ItemInspector";
47
+import { SubagentNotificationLink } from "./V2LifecycleRow";
48
+import {
49
+ TimelineRowCtx,
50
+ TimelineRowActivityCtx,
51
+ WorkGroupViewCtx,
52
+ type TimelineWorkEntry,
53
+} from "./timelineRowContext";
54
+import { MESSAGE_HEADING_LEVEL, TimelineRowTimestamp } from "./TimelineRowParts";
55
+import {
56
+ failedToolIconClassName,
57
+ toolIconAcceptsTint,
58
+ ToolActivityIconView,
59
+} from "./TimelineToolActivityIcon";
60
+import {
61
+ workToneIcon,
62
+ workEntryRawCommand,
63
+ buildToolCallExpandedBody,
64
+ workEntryIconName,
65
+ remarkThoughtPreview,
66
+} from "./TimelineWorkEntryRow.logic";
67
+
68
+export function useThreadReadTarget(entry: TimelineWorkEntry, environmentId: EnvironmentId) {
69
+ const rawThreadId = threadReadTargetId(entry);
70
+ const threadId = rawThreadId === null ? null : ThreadId.make(rawThreadId);
71
+ const shell = useThreadShell(threadId ? scopeThreadRef(environmentId, threadId) : null);
72
+ const title = threadReadTargetTitle(shell);
73
+ return threadId && title ? { threadId, title } : null;
74
+}
75
+
76
+export function threadReadLabel(label: string, target: ReturnType<typeof useThreadReadTarget>) {
77
+ const prefix = target && threadReadLabelPrefix(label);
78
+ return prefix ? { ...target, prefix, text: `${prefix} “${target.title}”` } : null;
79
+}
80
+
81
+export function ThreadReadLabel({
82
+ label,
83
+ environmentId,
84
+ linked,
85
+}: {
86
+ label: NonNullable<ReturnType<typeof threadReadLabel>>;
87
+ environmentId: EnvironmentId;
88
+ linked: boolean;
89
+}) {
90
+ return (
91
+ <span className="flex min-w-0">
92
+ <span className="shrink-0">{label.prefix} “</span>
93
+ {linked ? (
94
+ <Link
95
+ to="/$environmentId/$threadId"
96
+ params={{ environmentId, threadId: label.threadId }}
97
+ className="min-w-0 truncate rounded-sm text-foreground underline-offset-2 hover:underline focus-visible:outline-2 focus-visible:outline-ring"
98
+ onClick={stopRowToggle}
99
+ onKeyDown={stopRowToggle}
100
+ >
101
+ {label.title}
102
+ </Link>
103
+ ) : (
104
+ <span className="min-w-0 truncate">{label.title}</span>
105
+ )}
106
+ <span className="shrink-0">”</span>
107
+ </span>
108
+ );
109
+}
110
+
111
+const toolCallExpandedBodyClassName =
112
+ "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";
113
+
114
+const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation();
115
+
116
+export function ReasoningTraceContent({ entries }: { entries: ReadonlyArray<TimelineWorkEntry> }) {
117
+ const ctx = use(TimelineRowCtx);
118
+ const { isWorking, latestRunId } = use(TimelineRowActivityCtx);
119
+ const isStreaming = (entry: TimelineWorkEntry) =>
120
+ isWorking && entry.runId === latestRunId && entry.toolLifecycleStatus === "inProgress";
121
+ return (
122
+ <WorkLogDetails followLive={entries.some(isStreaming)}>
123
+ {entries.map((entry) => (
124
+ <ChatMarkdown
125
+ key={entry.id}
126
+ className="text-foreground"
127
+ text={entry.detail ?? ""}
128
+ cwd={ctx.markdownCwd}
129
+ threadRef={ctx.threadRef ?? undefined}
130
+ skills={ctx.skills}
131
+ isStreaming={isStreaming(entry)}
132
+ headingLevelOffset={MESSAGE_HEADING_LEVEL}
133
+ onUseArtifactTemplate={ctx.onUseArtifactTemplate}
134
+ onImageExpand={ctx.onImageExpand}
135
+ lineBreaks
136
+ />
137
+ ))}
138
+ </WorkLogDetails>
139
+ );
140
+}
141
+
142
+type WorkEntryRowProps = {
143
+ workEntry: TimelineWorkEntry;
144
+ workspaceRoot: string | undefined;
145
+ displayLabel?: string | undefined;
146
+ onToggleEntry?: ((collapsed: boolean) => void) | undefined;
147
+};
148
+
149
+export const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: WorkEntryRowProps) {
150
+ const ctx = use(TimelineRowCtx);
151
+ const item = props.workEntry.projectedItem?.item;
152
+ const childThreadId =
153
+ item?.type === "notification" ? notificationChildThreadId(item.source) : undefined;
154
+ if (item?.type !== "notification" || childThreadId === undefined) {
155
+ return <WorkEntryLogRow {...props} />;
156
+ }
157
+ return (
158
+ <SubagentNotificationLink
159
+ parentRef={scopeThreadRef(ctx.activeThreadEnvironmentId, item.threadId)}
160
+ childThreadId={childThreadId}
161
+ outcome={item.outcome}
162
+ createdAt={props.workEntry.createdAt}
163
+ timestampFormat={ctx.timestampFormat}
164
+ onOpenThread={ctx.onOpenThread}
165
+ fallback={<WorkEntryLogRow {...props} />}
166
+ />
167
+ );
168
+});
169
+
170
+function WorkEntryLogRow(props: WorkEntryRowProps) {
171
+ const { workEntry, workspaceRoot, displayLabel } = props;
172
+ const ctx = use(TimelineRowCtx);
173
+ const { threadRef, onImageExpand, timestampFormat } = ctx;
174
+ const { retryableWorkspacePreparationRunIds, onRetryWorkspacePreparation } = ctx;
175
+ const threadTarget = useThreadReadTarget(workEntry, ctx.activeThreadEnvironmentId);
176
+ const createdThread =
177
+ workEntry.projectedItem?.item.type === "thread_created"
178
+ ? workEntry.projectedItem.item
179
+ : undefined;
180
+ const notifiedSubagentThreadId =
181
+ workEntry.projectedItem?.item.type === "notification"
182
+ ? notificationChildThreadId(workEntry.projectedItem.item.source)
183
+ : undefined;
184
+ const groupView = use(WorkGroupViewCtx);
185
+ const [expanded, setExpanded] = useState(
186
+ () => groupView?.state.expandedEntries.has(workEntry.id) ?? false,
187
+ );
188
+ const toggleExpanded = () => {
189
+ const next = !expanded;
190
+ if (groupView) {
191
+ groupView.onToggleEntry(!next);
192
+ if (next) groupView.state.expandedEntries.add(workEntry.id);
193
+ else groupView.state.expandedEntries.delete(workEntry.id);
194
+ } else {
195
+ props.onToggleEntry?.(!next);
196
+ }
197
+ setExpanded(next);
198
+ };
199
+ const failureItem = workEntry.projectedItem?.item;
200
+ if (failureItem?.type === "error" && failureItem.status === "failed") {
201
+ const warning = failureItem.failure.class === "usage_limit";
202
+ const resetAt = failureItem.failure.resetAt;
203
+ const resetTime = resetAt ? formatUpcomingTimestamp(resetAt, timestampFormat) : null;
204
+ const label = warning
205
+ ? `Usage limit reached.${resetTime ? ` Retry after ${resetTime}.` : ""}`
206
+ : workEntry.label;
207
+ const retryRunId =
208
+ failureItem.runId !== null &&
209
+ retryableWorkspacePreparationRunIds.has(failureItem.runId) &&
210
+ failureItem.failure.code === ORCHESTRATION_V2_WORKSPACE_PREPARATION_FAILURE_CODE
211
+ ? failureItem.runId
212
+ : null;
213
+ return (
214
+ <WorkLogRow
215
+ data-v2-item-type="error"
216
+ data-v2-item-visibility={workEntry.projectedItem?.visibility}
217
+ wrapLabel
218
+ icon={
219
+ <CircleAlertIcon
220
+ className={cn("size-4", warning ? "text-warning" : "text-destructive")}
221
+ />
222
+ }
223
+ label={
224
+ <span
225
+ className={cn("text-sm font-medium", warning ? "text-warning" : "text-destructive")}
226
+ >
227
+ {label}
228
+ </span>
229
+ }
230
+ trailing={
231
+ <TimelineRowTimestamp
232
+ createdAt={workEntry.createdAt}
233
+ timestampFormat={timestampFormat}
234
+ alwaysVisible
235
+ />
236
+ }
237
+ >
238
+ {!warning ? (
239
+ <p className="ms-7 whitespace-pre-wrap break-words py-1 text-sm leading-relaxed text-foreground/80">
240
+ {failureItem.failure.message}
241
+ </p>
242
+ ) : null}
243
+ {retryRunId !== null && onRetryWorkspacePreparation ? (
244
+ <div className="ms-7 pb-1">
245
+ <Button
246
+ type="button"
247
+ size="xs"
248
+ variant="outline"
249
+ onClick={() => onRetryWorkspacePreparation(retryRunId)}
250
+ >
251
+ <RotateCcwIcon aria-hidden />
252
+ Retry
253
+ </Button>
254
+ </div>
255
+ ) : null}
256
+ </WorkLogRow>
257
+ );
258
+ }
259
+ const iconConfig = workToneIcon(workEntry.tone);
260
+ const showWarningIndicator = workEntry.sourceActivityKind === "runtime.warning";
261
+ const showFailedIndicator =
262
+ !showWarningIndicator && workEntryDisplayIndicatesToolFailure(workEntry);
263
+ const showDestructiveRowStyle =
264
+ !showWarningIndicator &&
265
+ showFailedIndicator &&
266
+ (workEntrySignalsSevereFailure(workEntry) || !workLogEntryIsToolLike(workEntry));
267
+ const entryIconName =
268
+ showWarningIndicator || showDestructiveRowStyle ? "circle-alert" : workEntryIconName(workEntry);
269
+ const entryToolIcon =
270
+ showWarningIndicator || showDestructiveRowStyle
271
+ ? undefined
272
+ : (workEntry.toolIcon ?? workEntry.toolSource?.icon);
273
+ const isReasoning = workEntry.itemType === "reasoning";
274
+ const questionHeading = workEntry.questionAnswer
275
+ ? getQuestionTextPreview(workEntry.questionAnswer)
276
+ : "";
277
+ const previewText =
278
+ isReasoning && expanded
279
+ ? workEntry.toolLifecycleStatus === "inProgress"
280
+ ? "Thinking"
281
+ : "Thought"
282
+ : questionHeading || (displayLabel ?? workEntryDisplayLabel(workEntry, workspaceRoot));
283
+ const answerPreview =
284
+ workEntry.questionAnswer && hasQuestionAnswer(workEntry.questionAnswer)
285
+ ? getQuestionAnswerPreview(workEntry.questionAnswer)
286
+ : null;
287
+ const viewedImagePath = workEntryViewedImagePath(workEntry);
288
+ const payload = workEntry.structuredPayload;
289
+ const skill =
290
+ payload?.type === "dynamic_tool"
291
+ ? claudeSkillInvocation(payload.toolName, payload.input)
292
+ : undefined;
293
+ const plainOutput =
294
+ toolGroupAction(workEntry) === "read"
295
+ ? workEntryReadOutput(workEntry, workspaceRoot)
296
+ : skill
297
+ ? (skill.args ?? null)
298
+ : undefined;
299
+ const viewedImage =
300
+ viewedImagePath && threadRef
301
+ ? resolveViewedImageAsset(viewedImagePath, {
302
+ threadId: threadRef.threadId,
303
+ workspaceRoot,
304
+ })
305
+ : null;
306
+ const canExpand =
307
+ previewText.trim().length > 0 ||
308
+ (workEntry.itemType === "dynamic_tool" && workEntry.toolData !== undefined) ||
309
+ Boolean(
310
+ workEntryRawCommand(workEntry) ||
311
+ workEntry.command?.trim() ||
312
+ workEntry.detail?.trim() ||
313
+ workEntry.changedFiles?.length ||
314
+ viewedImage,
315
+ );
316
+ const expandedBody =
317
+ expanded && !isReasoning
318
+ ? plainOutput !== undefined
319
+ ? plainOutput
320
+ : buildToolCallExpandedBody(
321
+ workEntry,
322
+ workspaceRoot,
323
+ previewText,
324
+ viewedImage ? viewedImagePath : null,
325
+ )
326
+ : null;
327
+ const plainOutputFetches =
328
+ plainOutput !== undefined &&
329
+ workEntry.projectedItem !== undefined &&
330
+ turnItemNeedsDetailFetch(workEntry.projectedItem.item);
331
+ const canExpandProjectedItem =
332
+ plainOutput !== undefined
333
+ ? Boolean(plainOutput || viewedImage || workEntry.questionAnswer || plainOutputFetches)
334
+ : workEntry.projectedItem === undefined
335
+ ? canExpand
336
+ : isReasoning
337
+ ? Boolean(workEntry.detail?.trim())
338
+ : Boolean(
339
+ viewedImage ||
340
+ workEntry.questionAnswer ||
341
+ turnItemHasDetail(workEntry.projectedItem.item),
342
+ );
343
+ const iconWrapperClass = cn(
344
+ "flex size-4 items-center justify-center",
345
+ showWarningIndicator
346
+ ? "text-warning"
347
+ : showDestructiveRowStyle
348
+ ? "text-destructive"
349
+ : showFailedIndicator
350
+ ? failedToolIconClassName
351
+ : workEntry.tone === "tool"
352
+ ? "text-icon-muted"
353
+ : iconConfig.className,
354
+ );
355
+ const headingClass = showWarningIndicator
356
+ ? "font-medium text-warning"
357
+ : showDestructiveRowStyle
358
+ ? "font-medium text-destructive"
359
+ : workLogEntryIsToolLike(workEntry)
360
+ ? "text-secondary-label"
361
+ : "text-foreground/80";
362
+ const threadLabel = isReasoning ? null : threadReadLabel(previewText, threadTarget);
363
+ const accessiblePreview = [threadLabel?.text ?? previewText, answerPreview]
364
+ .filter(Boolean)
365
+ .join(": ");
366
+ const accessibleDisplayText = showFailedIndicator
367
+ ? `${accessiblePreview}, tool call failed`
368
+ : accessiblePreview;
369
+ const rowToggleProps = canExpandProjectedItem
370
+ ? {
371
+ role: "button" as const,
372
+ tabIndex: 0 as const,
373
+ "aria-label": accessibleDisplayText,
374
+ "aria-expanded": expanded,
375
+ onClick: toggleExpanded,
376
+ onKeyDown: (e: KeyboardEvent<HTMLDivElement>) => {
377
+ if (e.target === e.currentTarget && (e.key === "Enter" || e.key === " ")) {
378
+ e.preventDefault();
379
+ toggleExpanded();
380
+ }
381
+ },
382
+ }
383
+ : {};
384
+
385
+ return (
386
+ <WorkLogRow
387
+ data-v2-item-type={workEntry.projectedItem?.item.type}
388
+ data-v2-item-visibility={workEntry.projectedItem?.visibility}
389
+ {...rowToggleProps}
390
+ icon={
391
+ <span
392
+ className={iconWrapperClass}
393
+ role={showFailedIndicator ? "img" : undefined}
394
+ aria-label={showFailedIndicator ? "Tool call failed" : undefined}
395
+ >
396
+ <ToolActivityIconView
397
+ icon={entryToolIcon}
398
+ fallbackName={entryIconName}
399
+ className="block size-4 shrink-0 stroke-2"
400
+ muted
401
+ />
402
+ </span>
403
+ }
404
+ label={
405
+ <div className="min-w-0 flex-1 overflow-hidden">
406
+ <p className="flex min-w-0 w-full items-baseline gap-1.5 text-sm leading-relaxed">
407
+ <span
408
+ className={cn(answerPreview ? "min-w-0" : "min-w-0 flex-1", "truncate", headingClass)}
409
+ >
410
+ {isReasoning && !expanded ? (
411
+ <ChatMarkdown
412
+ inline
413
+ text={workEntry.detail ?? previewText}
414
+ cwd={ctx.markdownCwd}
415
+ parseRawHtml={false}
416
+ extraRemarkPlugins={[
417
+ [
418
+ remarkThoughtPreview,
419
+ workEntry.toolLifecycleStatus === "inProgress" ? "Thinking" : "Thought",
420
+ ],
421
+ ]}
422
+ />
423
+ ) : threadLabel ? (
424
+ <ThreadReadLabel
425
+ label={threadLabel}
426
+ environmentId={ctx.activeThreadEnvironmentId}
427
+ linked
428
+ />
429
+ ) : (
430
+ previewText
431
+ )}
432
+ </span>
433
+ {answerPreview ? (
434
+ <span
435
+ className={cn(
436
+ "min-w-0 truncate",
437
+ !expanded &&
438
+ workEntry.questionAnswer &&
439
+ hasQuestionAnswer(workEntry.questionAnswer)
440
+ ? "text-foreground"
441
+ : "text-muted-foreground",
442
+ )}
443
+ >
444
+ {answerPreview}
445
+ </span>
446
+ ) : null}
447
+ </p>
448
+ </div>
449
+ }
450
+ trailing={
451
+ <>
452
+ {createdThread ? (
453
+ <button
454
+ type="button"
455
+ 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"
456
+ aria-label={`Open ${createdThread.title ?? "created thread"}`}
457
+ onClick={(event) => {
458
+ event.stopPropagation();
459
+ ctx.onOpenThread(createdThread.targetThreadId);
460
+ }}
461
+ onKeyDown={stopRowToggle}
462
+ >
463
+ Open chat
464
+ </button>
465
+ ) : null}
466
+ {notifiedSubagentThreadId ? (
467
+ <InlineButton
468
+ aria-label="Open subagent thread"
469
+ onClick={(event) => {
470
+ event.stopPropagation();
471
+ ctx.onOpenThread(notifiedSubagentThreadId);
472
+ }}
473
+ onKeyDown={stopRowToggle}
474
+ >
475
+ Open subagent
476
+ </InlineButton>
477
+ ) : null}
478
+ {showFailedIndicator &&
479
+ !showDestructiveRowStyle &&
480
+ !toolIconAcceptsTint(entryToolIcon) ? (
481
+ <XIcon aria-hidden className={cn("size-3 shrink-0", failedToolIconClassName)} />
482
+ ) : null}
483
+ <TimelineRowTimestamp createdAt={workEntry.createdAt} timestampFormat={timestampFormat} />
484
+ <span
485
+ className={cn(
486
+ "flex size-4 shrink-0 items-center justify-center",
487
+ !canExpandProjectedItem && "invisible",
488
+ )}
489
+ aria-hidden
490
+ >
491
+ <ChevronRightIcon
492
+ className={cn(
493
+ "size-3 shrink-0 text-icon-muted opacity-70 transition-transform duration-200",
494
+ expanded && "rotate-90",
495
+ )}
496
+ />
497
+ </span>
498
+ </>
499
+ }
500
+ >
501
+ {expanded && viewedImage && threadRef ? (
502
+ <WorkLogDetails kind="media">
503
+ <ChatMarkdownAssetImage
504
+ environmentId={threadRef.environmentId}
505
+ resource={viewedImage.resource}
506
+ alt={viewedImage.alt}
507
+ srcFragment={viewedImage.srcFragment}
508
+ workspaceRoot={workspaceRoot}
509
+ maxHeightRem={16}
510
+ onImageExpand={onImageExpand}
511
+ />
512
+ </WorkLogDetails>
513
+ ) : null}
514
+ {expanded && workEntry.questionAnswer ? (
515
+ <QuestionAnswerHistory answer={workEntry.questionAnswer} />
516
+ ) : null}
517
+ {expanded && isReasoning ? <ReasoningTraceContent entries={[workEntry]} /> : null}
518
+ {expanded &&
519
+ !isReasoning &&
520
+ !workEntry.questionAnswer &&
521
+ canExpandProjectedItem &&
522
+ (expandedBody ||
523
+ plainOutputFetches ||
524
+ (workEntry.projectedItem && plainOutput === undefined)) ? (
525
+ <WorkLogDetails kind="panel">
526
+ {workEntry.projectedItem && plainOutput === undefined ? (
527
+ <V2ItemInspector
528
+ projectedItem={workEntry.projectedItem}
529
+ environmentId={ctx.activeThreadEnvironmentId}
530
+ cwd={ctx.markdownCwd}
531
+ workspaceRoot={workspaceRoot}
532
+ onOpenThread={ctx.onOpenThread}
533
+ onOpenTurnDiff={ctx.onOpenTurnDiff}
534
+ onRollbackCheckpoint={ctx.onRollbackCheckpoint}
535
+ onImageExpand={ctx.onImageExpand}
536
+ />
537
+ ) : (
538
+ <>
539
+ {expandedBody ? (
540
+ <pre className={toolCallExpandedBodyClassName}>{expandedBody}</pre>
541
+ ) : null}
542
+ {plainOutputFetches && workEntry.projectedItem ? (
543
+ <FetchedToolOutput
544
+ projectedItem={workEntry.projectedItem}
545
+ environmentId={ctx.activeThreadEnvironmentId}
546
+ onImageExpand={onImageExpand}
547
+ />
548
+ ) : null}
549
+ </>
550
+ )}
551
+ </WorkLogDetails>
552
+ ) : null}
553
+ </WorkLogRow>
554
+ );
555
+}
556
+
557
+function QuestionAnswerHistory({
558
+ answer,
559
+}: {
560
+ answer: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
561
+}) {
562
+ const { activeThreadEnvironmentId } = use(TimelineRowCtx);
563
+ const attachments = Object.values(answer.attachmentsByQuestionId).flat();
564
+ const resources = attachments.map((attachment) => ({
565
+ _tag: "attachment" as const,
566
+ attachmentId: attachment.id,
567
+ }));
568
+ const urls = useAssetUrls(activeThreadEnvironmentId, resources);
569
+ return (
570
+ <div className="ms-7 mt-2 space-y-2" onClick={stopRowToggle}>
571
+ {[
572
+ ...new Set([
573
+ ...Object.keys(answer.questionTextById ?? {}),
574
+ ...Object.keys(answer.answers),
575
+ ...Object.keys(answer.attachmentsByQuestionId),
576
+ ]),
577
+ ].map((questionId) => (
578
+ <div key={questionId} className="space-y-1">
579
+ {answer.questionTextById?.[questionId] ? (
580
+ <p className="whitespace-pre-wrap text-sm text-muted-foreground">
581
+ {answer.questionTextById[questionId]}
582
+ </p>
583
+ ) : null}
584
+ {getQuestionAnswerText(answer.answers[questionId]) ? (
585
+ <p className="ms-3 whitespace-pre-wrap text-sm text-muted-foreground">
586
+ {getQuestionAnswerText(answer.answers[questionId])}
587
+ </p>
588
+ ) : null}
589
+ <div className="flex flex-wrap gap-2">
590
+ {(answer.attachmentsByQuestionId[questionId] ?? []).map((attachment) => {
591
+ const url = urls[attachments.indexOf(attachment)];
592
+ return (
593
+ <a
594
+ key={attachment.id}
595
+ href={url ?? undefined}
596
+ target="_blank"
597
+ rel="noreferrer"
598
+ className="text-sm underline"
599
+ >
600
+ {attachment.type === "image" && url ? (
601
+ <img
602
+ src={url}
603
+ alt={attachment.name}
604
+ className="h-20 max-w-32 rounded object-contain"
605
+ />
606
+ ) : (
607
+ attachment.name
608
+ )}
609
+ </a>
610
+ );
611
+ })}
612
+ </div>
613
+ </div>
614
+ ))}
615
+ </div>
616
+ );
617
+}
apps/web/src/components/chat/timelineRowContext.ts
new
+99
@@ -0,0 +1,99 @@
1
+import type { WorktreeSetupSnapshot } from "@t3tools/contracts";
2
+import {
3
+ type EnvironmentId,
4
+ type MessageId,
5
+ type OrchestrationV2TurnItem,
6
+ type RunAttemptId,
7
+ type ScopedThreadRef,
8
+ type ServerProviderSkill,
9
+ type RunId,
10
+ ThreadId,
11
+} from "@t3tools/contracts";
12
+import type { WorkflowOpening } from "@t3tools/client-runtime/state/subagentRuntime";
13
+import { createContext, type MouseEvent } from "react";
14
+import { type LegendListRef } from "@legendapp/list/react";
15
+import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
16
+import { type ChatFileAttachment } from "../../types";
17
+import { ExpandedImagePreview } from "./ExpandedImagePreview";
18
+import { type AssistantCitationTarget } from "./AssistantCitationSource";
19
+import { type MessagesTimelineRow, type WorkGroupScrollAnchor } from "./MessagesTimeline.logic";
20
+import { type TimestampFormat } from "@t3tools/contracts/settings";
21
+import { type HandoffTimelineRun } from "./V2LifecycleRow";
22
+
23
+export interface TimelineRowSharedState {
24
+ citationRequest: AssistantCitationTarget | null;
25
+ listRef: React.RefObject<LegendListRef | null>;
26
+ timestampFormat: TimestampFormat;
27
+ routeThreadKey: string;
28
+ threadRef: ScopedThreadRef | null;
29
+ markdownCwd: string | undefined;
30
+ resolvedTheme: "light" | "dark";
31
+ workspaceRoot: string | undefined;
32
+ skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
33
+ runs: ReadonlyArray<HandoffTimelineRun>;
34
+ activeThreadEnvironmentId: EnvironmentId;
35
+ onRevertToTurnCount: (targetTurnCount: number, messageId: MessageId) => void;
36
+ onUseArtifactTemplate: (template: CodexArtifactTemplate) => void;
37
+ onSendAppMessage: ((text: string) => Promise<void>) | undefined;
38
+ onAppFullscreenChange: (rowId: string, fullscreen: boolean) => void;
39
+ onRunShellCommand: ((command: string) => void) | undefined;
40
+ findActive: boolean;
41
+ onImageExpand: (preview: ExpandedImagePreview) => void;
42
+ displayThreadKey?: string;
43
+ onOpenTurnDiff: (runId: RunId, filePath?: string) => void;
44
+ onOpenThread: (threadId: OrchestrationV2TurnItem["threadId"]) => void;
45
+ workflowOpening: WorkflowOpening | null;
46
+ onForkFromRun: (input: {
47
+ readonly sourceThreadId: ThreadId;
48
+ readonly runId: RunId;
49
+ }) => Promise<void>;
50
+ onRollbackCheckpoint: (input: {
51
+ readonly checkpointId: string;
52
+ readonly scopeId: string;
53
+ }) => void;
54
+ onToggleTurnFold: (runId: RunId) => void;
55
+ onToggleAttemptFold: (attemptId: RunAttemptId) => void;
56
+ onFileOpen: (attachment: ChatFileAttachment) => void;
57
+ onFileDownload: (attachment: ChatFileAttachment) => void;
58
+ openPullRequest: (event: MouseEvent<HTMLElement>, url: string) => void;
59
+ onToggleWorkGroup: (groupId: string, anchorKey: string) => void;
60
+ onToggleWorkEntry: (anchorKey: string, collapsed: boolean) => void;
61
+ onCancelWorktreeSetup: (() => void) | null;
62
+ retryableWorkspacePreparationRunIds: ReadonlySet<RunId>;
63
+ onRetryWorkspacePreparation: ((runId: RunId) => void) | null;
64
+ onWorktreeSetupWorkLocally: (() => void) | null;
65
+ onOpenWorktreeSetupTerminal: ((terminalId: string) => void) | null;
66
+ workGroupViewState: WorkGroupViewState;
67
+}
68
+
69
+export interface TimelineRowActivityState {
70
+ isWorking: boolean;
71
+ isCompacting: boolean;
72
+ isRevertingCheckpoint: boolean;
73
+ activeTurnInProgress: boolean;
74
+ awaitingUser: boolean;
75
+ isPreparingWorktree: boolean;
76
+ latestRunId: RunId | null;
77
+ backgroundWorktreeSetup: WorktreeSetupSnapshot | null;
78
+}
79
+
80
+export const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
81
+
82
+export const TimelineRowActivityCtx = createContext<TimelineRowActivityState>(null!);
83
+
84
+export interface WorkGroupViewState {
85
+ scrollPositions: Map<string, WorkGroupScrollAnchor>;
86
+ expandedEntries: Set<string>;
87
+}
88
+
89
+export const WorkGroupViewCtx = createContext<{
90
+ state: WorkGroupViewState;
91
+ onToggleEntry: (collapsed: boolean) => void;
92
+} | null>(null);
93
+
94
+export type TimelineWorkEntry = Extract<
95
+ MessagesTimelineRow,
96
+ { kind: "work" }
97
+>["groupedEntries"][number];
98
+
99
+export type TimelineRow = MessagesTimelineRow;