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

TimelineWorkEntryRow.tsx

679 lines24.2 KB

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