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