@devries-cameron20 / t3code-1 / commits / 3e36c5e181
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

refactor(web): timeline user message rows and context chips live in their own files (#22676)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 21, 2026 at 01:12 UTC 3e36c5e1817734cec615e9ee88801a81208861d0
4 files changed +1243 -1224
apps/web/src/components/chat/MessagesTimeline.tsx
+7 -1224
@@ -1,17 +1,12 @@
1 -import { useRenderedAppearance } from "../../hooks/useTheme";
1 import { ThreadFindTimelineContext } from "./ThreadFindProvider";
2 import { shallow } from "zustand/vanilla/shallow";
3 import { shouldPreserveAssistantLineBreaks } from "@t3tools/shared/markdownPipeline";
5 -import { MarkdownFindContext, findRevealRef } from "./markdownFindContext";
4 +import { MarkdownFindContext } from "./markdownFindContext";
5 import { useChatCanvas } from "./ChatCanvasContext";
6 import { WorkLogBlock } from "./WorkLog";
8 -import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
7 import type { WorktreeSetupSnapshot } from "@t3tools/contracts";
10 -import { ReadOnlySourcePreview } from "../files/AttachmentFilePreview";
11 -import { useRightPanelStore } from "~/rightPanelStore";
8 import { deriveTimelineMinimapItems } from "./timelineMinimapItems";
9 import {
14 - COMPOSER_CONTEXT_KINDS,
10 type AssistantCitation,
11 type EnvironmentId,
12 type MessageId,
@@ -24,12 +19,8 @@ import {
19 import { parseScopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment";
20 import { useAtomValue } from "@effect/atom-react";
21 import { environmentThreadDetails } from "../../state/threads";
27 -import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
28 -import { Link } from "@tanstack/react-router";
22 import { canForkProjectedAssistantItem } from "@t3tools/client-runtime/state/thread-workflows";
30 -import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
23 import { resolveWorkGroupScrollAnchor } from "@t3tools/client-runtime/work-log/scroll-anchor";
32 -import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
24 import {
25 subagentGroupSummary,
26 summarizeSubagentStatuses,
@@ -58,74 +49,28 @@ import {
49 type LegendListRef,
50 type MaintainScrollAtEndOptions,
51 } from "@legendapp/list/react";
61 -import { FileDiff } from "@pierre/diffs/react";
62 -import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
63 -import {
64 - type TimelineEntry,
65 - providerErrorPresentation,
66 - createMessageAttachmentPreviewProjector,
67 - selectMessageImageResources,
68 -} from "../../session-logic";
52 +import { type TimelineEntry, providerErrorPresentation } from "../../session-logic";
53 import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates";
70 -import {
71 - type ChatMessage,
72 - type ChatFileAttachment,
73 - type ChatImageAttachment,
74 - isFileAttachment,
75 - isImageAttachment,
76 - isVideoAttachment,
77 - type TurnDiffSummary,
78 -} from "../../types";
79 -import {
80 - getRenderablePatch,
81 - resolveDiffThemeName,
82 - resolveFileDiffPath,
83 -} from "../../lib/diffRendering";
84 -import { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting";
54 +import { type ChatMessage, type ChatFileAttachment, type TurnDiffSummary } from "../../types";
55 import ChatMarkdown from "../ChatMarkdown";
86 -import { ThreadContextChip } from "../ThreadContextChip";
56 import {
57 ArrowRightIcon,
58 BotIcon,
59 CheckIcon,
60 ChevronDownIcon,
61 CircleAlertIcon,
93 - DownloadIcon,
94 - EyeIcon,
62 GitForkIcon,
63 type LucideIcon,
97 - MessageCircleIcon,
98 - MousePointerClickIcon,
99 - PaintbrushIcon,
64 MinusIcon,
101 - Redo2Icon,
65 Minimize2Icon,
103 - Undo2Icon,
66 WrenchIcon,
67 XIcon,
68 ZapIcon,
69 } from "lucide-react";
108 -import { ChevronDown, ChevronRight, Link as LinkIconNode } from "lucide";
109 -import type {
110 - ComposerContextId,
111 - ComposerContextRecord,
112 - KnownComposerContextRecord,
113 -} from "@t3tools/contracts";
114 -import { Button, InlineButton } from "../ui/button";
70 +import { ChevronDown, ChevronRight } from "lucide";
71 +import { Button } from "../ui/button";
72 import { MorphIcon } from "~/components/MorphIcon";
116 -import { useAssetUrlRefresh, useAssetUrls, useAssetUrlState } from "../../assets/assetUrls";
117 -import { AttachmentImage } from "../media/AttachmentImage";
118 -import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
119 -import {
120 - buildAttachmentVideoAsset,
121 - buildAttachmentVideoPreview,
122 - buildExpandedImagePreview,
123 - ExpandedImagePreview,
124 -} from "./ExpandedImagePreview";
125 -import {
126 - SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
127 - SnapShotAttachmentDetails,
128 -} from "./SnapShotAttachmentDetails";
73 +import { ExpandedImagePreview } from "./ExpandedImagePreview";
74 import { ProposedPlanCard } from "./ProposedPlanCard";
75 import { HtmlRenderFrame } from "./HtmlRenderFrame";
76 import { McpAppFrame } from "./McpAppFrame";
@@ -140,9 +85,6 @@ import {
85 timelineContentOverflowsViewport,
86 } from "./timelineScrollAnchoring";
87 import { MessageCopyButton } from "./MessageCopyButton";
143 -import { promptLinkFor } from "../promptLinks/copyPromptLink";
144 -import { PierreEntryIcon } from "./PierreEntryIcon";
145 -import { WorkspaceEntryIcon, WorkspaceEntryTooltip } from "./WorkspaceEntryIcon";
88 import { AssistantSelectionToolbar } from "./AssistantSelectionToolbar";
89 import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
90 import { AssistantCitationSource, type AssistantCitationRequest } from "./AssistantCitationSource";
@@ -158,7 +100,6 @@ import {
100 isTimelineMinimapRowVisible,
101 resolveTimelineMinimapVisibleRange,
102 resolveTimelineMinimapHitStripWidth,
161 - shouldCollapseUserMessage,
103 timelineTurnFoldRunIdsByEntryId,
104 worktreeSetupAgentStarted,
105 type StableMessagesTimelineRowsState,
@@ -169,42 +110,10 @@ import { type ThreadFindMatch } from "./threadFind";
110 import { useThreadFindNavigation } from "./useThreadFindNavigation";
111 import { readThreadFindPosition } from "./threadFindPosition";
112 import type { ThreadFindPositionReader } from "./threadFind";
172 -import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
113 import { Tooltip, TooltipPopup, TooltipTrigger, TooltipScrollDismissArea } from "../ui/tooltip";
114 import { WorktreeSetupCard } from "./WorktreeSetupCard";
175 -import {
176 - ContextChipPopover as UserMessageContextPopover,
177 - ContextChipShell,
178 - FileChip,
179 - ImageChipButton,
180 - PULL_REQUEST_CHIP_KINDS,
181 - PullRequestChip,
182 - UnresolvedChip,
183 -} from "../contextChipParts";
184 -import {
185 - asKnownContextRecord,
186 - isPullRequestSummaryContext,
187 - pullRequestContextDisplayState,
188 - pullRequestContextKindLabel,
189 - resolveUserMessageContext,
190 - reviewCommentContextLabel,
191 - selectedMessageContextFragment,
192 -} from "~/lib/composerContextRecords";
193 -import {
194 - collectComposerContextReferences,
195 - formatComposerContextReference,
196 -} from "@t3tools/shared/composerContextReferences";
197 -import {
198 - COMPOSER_CONTEXT_CLIPBOARD_MIME,
199 - encodeComposerContextClipboardHtml,
200 - encodeComposerContextFragment,
201 -} from "@t3tools/shared/composerContextClipboard";
202 -import { chatMarkdownClipboardPayload } from "../../markdown-clipboard";
203 -import { ContextChip, ContextChipLabel, type ContextChipKind } from "../ContextChip";
204 -import { createContextPresentationRegistry } from "../contextPresentationRegistry";
115 import { useOpenPrLink } from "~/lib/openPullRequestLink";
116 import { useClientSettings } from "~/hooks/useSettings";
207 -import type { ChatMarkdownContextReference } from "../ChatMarkdown";
117 import { useMediaQuery } from "~/hooks/useMediaQuery";
118 import { cn } from "~/lib/utils";
119 import { useUiStateStore } from "~/uiStateStore";
@@ -222,17 +131,9 @@ import {
131 } from "./V2LifecycleRow";
132 import { SecretRequestCard } from "./SecretRequestCard";
133 import { TimelineSystemDivider } from "./TimelineSystemDivider";
225 -import { WorkflowOpeningBlock } from "./WorkflowOpeningBlock";
134
227 -import { SkillChipIcon } from "./SkillInlineText";
135 import * as DateTime from "effect/DateTime";
229 -import { formatWorkspaceRelativePath } from "../../filePathDisplay";
136 import { forwardWheelToTimeline } from "./timelineMinimapWheel";
231 -import {
232 - buildReviewCommentRenderablePatch,
233 - formatReviewCommentFence,
234 - type ReviewCommentContext,
235 -} from "../../reviewCommentContext";
137 import { TimelineMinimap } from "./TimelineMinimap";
138 import {
139 type TimelineRowSharedState,
@@ -255,6 +156,7 @@ import {
156 LiveWorkEntryTimelineRow,
157 WorkGroupToggleTimelineRow,
158 } from "./TimelineWorkGroupRows";
159 +import { UserMessageRow } from "./TimelineUserMessageRow";
160
161 function timelineListStateFor(identity: string): {
162 readonly identity: string;
@@ -1650,487 +1552,6 @@ function ContextCompactionTimelineRow({
1552 );
1553 }
1554
1653 -function UserVideoAttachment({ file }: { readonly file: ChatFileAttachment }) {
1654 - const ctx = use(TimelineRowCtx);
1655 - // Row updates rebuild attachment objects, so the asset follows only the
1656 - // fields it reads.
1657 - const { downloadable, id, mimeType, name } = file;
1658 - const environmentId = ctx.activeThreadEnvironmentId;
1659 - const asset =
1660 - downloadable === false
1661 - ? null
1662 - : buildAttachmentVideoAsset(environmentId, { id, mimeType, name });
1663 - const resource = asset?.resource ?? null;
1664 - const assetUrl = useAssetUrlState(ctx.activeThreadEnvironmentId, resource);
1665 - const refreshAssetUrl = useAssetUrlRefresh(ctx.activeThreadEnvironmentId, resource);
1666 - const src = assetUrl._tag === "Success" ? assetUrl.url : (file.previewUrl ?? null);
1667 -
1668 - if (asset === null && src === null) {
1669 - return (
1670 - <div className="flex aspect-[4/3] w-full items-center justify-center rounded-lg border border-border/80 bg-black px-2 py-3 text-center text-2xs text-white/70">
1671 - {file.name}
1672 - </div>
1673 - );
1674 - }
1675 -
1676 - return (
1677 - <MediaVideoPlayer
1678 - src={src}
1679 - sourceFailed={
1680 - file.previewUrl === undefined && resource !== null && assetUrl._tag === "Failure"
1681 - }
1682 - label={file.name}
1683 - preload="visible"
1684 - onOpen={() => {
1685 - const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
1686 - if (preview) ctx.onImageExpand(preview);
1687 - }}
1688 - className="block aspect-[4/3] w-full"
1689 - videoClassName="aspect-auto size-full rounded-lg border border-border/80"
1690 - stateClassName="aspect-auto min-h-full rounded-lg border border-border/80 bg-black text-white"
1691 - onRetry={asset ? refreshAssetUrl : undefined}
1692 - actionsSource={asset ? { kind: "video", name: file.name, src, asset } : undefined}
1693 - />
1694 - );
1695 -}
1696 -
1697 -function UserMessageRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
1698 - const ctx = use(TimelineRowCtx);
1699 - return ctx.workflowOpening?.messageId === row.message.id ? (
1700 - <WorkflowOpeningBlock
1701 - opening={ctx.workflowOpening}
1702 - environmentId={ctx.activeThreadEnvironmentId}
1703 - onOpenThread={(threadId) => ctx.onOpenThread(ThreadId.make(threadId))}
1704 - />
1705 - ) : (
1706 - <UserTimelineRow row={row} />
1707 - );
1708 -}
1709 -
1710 -function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
1711 - const ctx = use(TimelineRowCtx);
1712 - const { onImageExpand, onFileOpen } = ctx;
1713 - const senderThreadId = row.message.senderThreadId;
1714 - const resources = selectMessageImageResources(row.message.attachments);
1715 - const previewUrls = useAssetUrls(ctx.activeThreadEnvironmentId, resources);
1716 - const [projectPreviews] = useState(createMessageAttachmentPreviewProjector);
1717 - const previewUrlsById = new Map(
1718 - resources.flatMap((resource, index) => {
1719 - const url = previewUrls[index];
1720 - return url ? [[resource.attachmentId, url] as const] : [];
1721 - }),
1722 - );
1723 - const messageWithPreviews = projectPreviews(row.message, (attachment) =>
1724 - previewUrlsById.get(attachment.id),
1725 - );
1726 - const userImages = (messageWithPreviews.attachments ?? []).filter(isImageAttachment);
1727 - const userFiles = (row.message.attachments ?? []).filter(isFileAttachment);
1728 - const userVideos = userFiles.filter(isVideoAttachment);
1729 - const otherUserFiles = userFiles.filter((file) => !isVideoAttachment(file));
1730 - const unknownAttachments = (row.message.attachments ?? []).filter(
1731 - (attachment) => !isImageAttachment(attachment) && !isFileAttachment(attachment),
1732 - );
1733 - const userMessage = resolveUserMessagePresentation(row.message);
1734 - const resolvedContext = resolveUserMessageContext(row.message);
1735 - const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
1736 - const revertTurnCount = row.revertTurnCount;
1737 - const chippedAttachmentIds = new Set(
1738 - collectComposerContextReferences(resolvedContext.text).flatMap((occurrence) => {
1739 - const record = asKnownContextRecord(resolvedContext.recordsById.get(occurrence.contextId));
1740 - return record?.kind === "file" || record?.kind === "image" ? [record.attachmentId] : [];
1741 - }),
1742 - );
1743 - const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
1744 - const unchippedFiles = otherUserFiles.filter((file) => !chippedAttachmentIds.has(file.id));
1745 - const annotationRecordIds = resolvedContext.records
1746 - .filter((record) => record.kind === "preview-annotation")
1747 - .map((record) => record.contextId);
1748 - const plainText = replaceComposerContextReferences(
1749 - resolvedContext.text,
1750 - (reference) => reference.label,
1751 - );
1752 - const promptLink = promptLinkFor(plainText);
1753 - const contextClipboardFragment =
1754 - resolvedContext.records.length === 0
1755 - ? null
1756 - : encodeComposerContextFragment({
1757 - version: 1,
1758 - source: {
1759 - environmentId: ctx.activeThreadEnvironmentId,
1760 - ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),
1761 - messageId: row.message.id,
1762 - },
1763 - records: resolvedContext.records,
1764 - });
1765 - const onBodyCopyCapture = (event: React.ClipboardEvent<HTMLDivElement>) => {
1766 - if (resolvedContext.records.length === 0 || !event.clipboardData) return;
1767 - const selection = window.getSelection();
1768 - if (!selection || selection.isCollapsed) return;
1769 - const copiedMarkdown: string[] = [];
1770 - for (let index = 0; index < selection.rangeCount; index += 1) {
1771 - const container = document.createElement("div");
1772 - container.appendChild(selection.getRangeAt(index).cloneContents());
1773 - // Diagram source is copied text, not authority to export context records.
1774 - for (const element of container.querySelectorAll(
1775 - "[data-markdown-copy]:not([data-markdown-mermaid])",
1776 - )) {
1777 - copiedMarkdown.push(element.getAttribute("data-markdown-copy") ?? "");
1778 - }
1779 - }
1780 - const fragment = selectedMessageContextFragment({
1781 - markdown: copiedMarkdown.join("\n"),
1782 - records: resolvedContext.records,
1783 - environmentId: ctx.activeThreadEnvironmentId,
1784 - ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),
1785 - messageId: row.message.id,
1786 - });
1787 - if (!fragment) return;
1788 - // Claim the copy: without preventDefault the browser default overwrites the
1789 - // custom MIME type. The default content must then be written back explicitly.
1790 - const payload = chatMarkdownClipboardPayload(selection);
1791 - event.preventDefault();
1792 - event.clipboardData.setData("text/plain", payload?.text ?? selection.toString());
1793 - if (payload) {
1794 - event.clipboardData.setData(
1795 - "text/html",
1796 - encodeComposerContextClipboardHtml(payload.text, fragment, payload.html),
1797 - );
1798 - }
1799 - event.clipboardData.setData(COMPOSER_CONTEXT_CLIPBOARD_MIME, fragment);
1800 - };
1801 - const renderContextReference = (reference: ChatMarkdownContextReference) => {
1802 - const record = asKnownContextRecord(resolvedContext.recordsById.get(reference.contextId));
1803 - const annotationImage =
1804 - record?.kind === "preview-annotation"
1805 - ? resolvePreviewAnnotationImage({
1806 - record,
1807 - recordsById: resolvedContext.recordsById,
1808 - userImages,
1809 - previewImages,
1810 - annotationRecordIds,
1811 - })
1812 - : null;
1813 - const attachment =
1814 - record?.kind === "image"
1815 - ? (userImages.find((image) => image.id === record.attachmentId) ?? null)
1816 - : record?.kind === "file"
1817 - ? (userFiles.find((file) => file.id === record.attachmentId) ?? null)
1818 - : null;
1819 - return (
1820 - <span data-thread-find-ignore>
1821 - <UserMessageContextReferenceChip
1822 - reference={reference}
1823 - record={record}
1824 - annotationImage={annotationImage}
1825 - attachment={attachment}
1826 - onExpandImage={(image) => {
1827 - const preview = buildExpandedImagePreview(userImages, image.id);
1828 - if (preview) onImageExpand(preview);
1829 - }}
1830 - onOpenFile={onFileOpen}
1831 - onExpandVideo={(file) => {
1832 - const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
1833 - if (preview) onImageExpand(preview);
1834 - }}
1835 - />
1836 - </span>
1837 - );
1838 - };
1839 -
1840 - return (
1841 - <div className="group flex flex-col items-end gap-1">
1842 - {userMessage.attribution === "automation" ? (
1843 - <p
1844 - className="me-1 text-2xs text-muted-foreground/70"
1845 - data-user-message-attribution="automation"
1846 - >
1847 - {userMessage.scheduledTaskId ? (
1848 - <Link
1849 - to="/settings/scheduled-tasks"
1850 - search={{
1851 - environmentId: ctx.activeThreadEnvironmentId,
1852 - taskId: userMessage.scheduledTaskId,
1853 - }}
1854 - className="rounded-sm hover:text-muted-foreground hover:underline focus-visible:outline-2 focus-visible:outline-ring"
1855 - >
1856 - Sent by automation
1857 - </Link>
1858 - ) : (
1859 - "Sent by automation"
1860 - )}
1861 - </p>
1862 - ) : userMessage.attribution === "t3code" ? (
1863 - <p
1864 - className="me-1 text-2xs text-muted-foreground/70"
1865 - data-user-message-attribution="t3code"
1866 - >
1867 - Sent by T3 Code
1868 - </p>
1869 - ) : userMessage.attribution === "agent" ? (
1870 - <p className="me-1 text-2xs text-muted-foreground/70" data-user-message-attribution="agent">
1871 - {senderThreadId ? (
1872 - <InlineButton
1873 - onClick={() => ctx.onOpenThread(senderThreadId)}
1874 - tone="muted"
1875 - aria-label="Open sending thread"
1876 - >
1877 - Sent by another agent
1878 - </InlineButton>
1879 - ) : (
1880 - "Sent by another agent"
1881 - )}
1882 - </p>
1883 - ) : null}
1884 - {row.message.inputIntent === "steer" ||
1885 - row.message.inputIntent === "promoted_queued_to_steer" ? (
1886 - <UserMessageIntentMarker intent={row.message.inputIntent} />
1887 - ) : null}
1888 - <div className="relative max-w-[80%] rounded-2xl bg-message p-3 text-message-foreground">
1889 - <MessageAuthorHeading>You</MessageAuthorHeading>
1890 - {(regularImages.length > 0 || userVideos.length > 0) && (
1891 - <div className="mb-2 grid max-w-[210px] grid-cols-2 gap-2">
1892 - {regularImages.map((image) => (
1893 - <div
1894 - key={image.id}
1895 - className={cn(
1896 - "bg-background/70",
1897 - image.source?.kind === "snap-shot" && image.previewUrl
1898 - ? cn(SNAP_SHOT_ATTACHMENT_FRAME_CLASS, "col-span-2")
1899 - : "aspect-[4/3] overflow-hidden rounded-lg border border-border/80",
1900 - )}
1901 - >
1902 - {image.previewUrl ? (
1903 - <button
1904 - type="button"
1905 - className="block h-full w-full cursor-zoom-in"
1906 - aria-label={`Preview ${image.name}`}
1907 - onClick={() => {
1908 - const preview = buildExpandedImagePreview(regularImages, image.id);
1909 - if (!preview) return;
1910 - ctx.onImageExpand(preview);
1911 - }}
1912 - >
1913 - <AttachmentImage
1914 - name={image.name}
1915 - mimeType={image.mimeType}
1916 - src={image.previewUrl}
1917 - alt={image.name}
1918 - decoding="async"
1919 - className="block size-full object-cover"
1920 - />
1921 - </button>
1922 - ) : (
1923 - <div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-2xs text-muted-foreground/70">
1924 - {image.name}
1925 - </div>
1926 - )}
1927 - {image.previewUrl && image.source?.kind === "snap-shot" ? (
1928 - <SnapShotAttachmentDetails source={image.source} />
1929 - ) : null}
1930 - </div>
1931 - ))}
1932 - {userVideos.map((file) => (
1933 - <UserVideoAttachment key={file.id} file={file} />
1934 - ))}
1935 - </div>
1936 - )}
1937 - {unchippedFiles.length > 0 || unknownAttachments.length > 0 ? (
1938 - <div className="mb-2 flex flex-col gap-1">
1939 - {unchippedFiles.map((file) => {
1940 - const fileIdentity = (
1941 - <>
1942 - <PierreEntryIcon pathValue={file.name} kind="file" theme={ctx.resolvedTheme} />
1943 - <span className="min-w-0 flex-1 truncate">{file.name}</span>
1944 - </>
1945 - );
1946 - if (file.downloadable !== false) {
1947 - return (
1948 - <div key={file.id} className="flex min-w-0 items-center gap-1">
1949 - <button
1950 - type="button"
1951 - aria-label={`Preview ${file.name}`}
1952 - onClick={() => ctx.onFileOpen(file)}
1953 - className="focus-visible:ring-ring/70 flex min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-md py-1 text-left text-sm hover:underline focus-visible:ring-2 focus-visible:ring-inset focus-visible:outline-none"
1954 - >
1955 - {fileIdentity}
1956 - <EyeIcon className="size-4 shrink-0" />
1957 - </button>
1958 - <Tooltip>
1959 - <TooltipTrigger
1960 - render={
1961 - <Button
1962 - size="icon-xs"
1963 - variant="ghost-muted"
1964 - aria-label={`Download ${file.name}`}
1965 - onClick={() => ctx.onFileDownload(file)}
1966 - />
1967 - }
1968 - >
1969 - <DownloadIcon />
1970 - </TooltipTrigger>
1971 - <TooltipPopup side="top">Download {file.name}</TooltipPopup>
1972 - </Tooltip>
1973 - </div>
1974 - );
1975 - }
1976 -
1977 - return (
1978 - <div key={file.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
1979 - {fileIdentity}
1980 - </div>
1981 - );
1982 - })}
1983 - {unknownAttachments.map((attachment) => (
1984 - <div key={attachment.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
1985 - <PierreEntryIcon
1986 - pathValue={attachment.name}
1987 - kind="file"
1988 - theme={ctx.resolvedTheme}
1989 - />
1990 - <span className="min-w-0 flex-1 truncate">{attachment.name}</span>
1991 - </div>
1992 - ))}
1993 - </div>
1994 - ) : null}
1995 - <div onCopyCapture={onBodyCopyCapture}>
1996 - <CollapsibleUserMessageBody
1997 - text={resolvedContext.text}
1998 - renderContextReference={renderContextReference}
1999 - skills={ctx.skills}
2000 - markdownCwd={ctx.markdownCwd}
2001 - />
2002 - </div>
2003 - </div>
2004 - {row.projectedItem &&
2005 - row.projectedItem.item.status !== "completed" &&
2006 - row.projectedItem.item.status !== "pending" &&
2007 - row.projectedItem.item.status !== "waiting" ? (
2008 - <div className="me-1 flex items-center gap-1.5">
2009 - <span className="rounded-full border border-destructive/25 bg-destructive/8 px-1.5 py-0.5 text-3xs font-medium text-destructive">
2010 - {row.projectedItem.item.status}
2011 - </span>
2012 - </div>
2013 - ) : null}
2014 - <div className="flex w-full max-w-[80%] items-center justify-end pe-1 text-xs tabular-nums opacity-0 transition-opacity duration-200 pointer-coarse:opacity-100 focus-within:opacity-100 group-hover:opacity-100">
2015 - <div className="flex shrink-0 items-center gap-2">
2016 - <Tooltip>
2017 - <TooltipTrigger render={<p className="text-muted-foreground text-xs tabular-nums" />}>
2018 - {formatDayAwareTimestamp(row.message.createdAt, ctx.timestampFormat)}
2019 - </TooltipTrigger>
2020 - <TooltipPopup>
2021 - {formatChatTimestampTooltip(row.message.createdAt, ctx.timestampFormat)}
2022 - </TooltipPopup>
2023 - </Tooltip>
2024 - <div className="flex items-center gap-0.5">
2025 - {typeof revertTurnCount === "number" && (
2026 - <RevertUserMessageButton turnCount={revertTurnCount} messageId={row.message.id} />
2027 - )}
2028 - {resolvedContext.text && (
2029 - <MessageCopyButton
2030 - text={contextClipboardFragment ? resolvedContext.text : plainText}
2031 - {...(contextClipboardFragment
2032 - ? {
2033 - extraFlavors: { [COMPOSER_CONTEXT_CLIPBOARD_MIME]: contextClipboardFragment },
2034 - }
2035 - : {})}
2036 - variant="ghost"
2037 - />
2038 - )}
2039 - {promptLink !== null && (
2040 - <MessageCopyButton
2041 - text={promptLink}
2042 - label="Copy prompt link"
2043 - icon={LinkIconNode}
2044 - variant="ghost"
2045 - />
2046 - )}
2047 - </div>
2048 - </div>
2049 - </div>
2050 - </div>
2051 - );
2052 -}
2053 -
2054 -function UserMessageIntentMarker({
2055 - intent,
2056 -}: {
2057 - readonly intent: "steer" | "promoted_queued_to_steer";
2058 -}) {
2059 - return (
2060 - <Tooltip>
2061 - <TooltipTrigger
2062 - render={
2063 - <div
2064 - className="me-1 flex items-center justify-end gap-1 text-xs leading-none text-muted-foreground"
2065 - data-user-message-intent={intent}
2066 - />
2067 - }
2068 - >
2069 - <Redo2Icon aria-hidden="true" className="size-3" />
2070 - Steer
2071 - </TooltipTrigger>
2072 - <TooltipPopup side="top">
2073 - {intent === "promoted_queued_to_steer"
2074 - ? "Originally queued, then promoted to steer the active turn"
2075 - : "Steered the active turn"}
2076 - </TooltipPopup>
2077 - </Tooltip>
2078 - );
2079 -}
2080 -
2081 -function resolvePreviewAnnotationImage(input: {
2082 - record: Extract<KnownComposerContextRecord, { kind: "preview-annotation" }>;
2083 - recordsById: ReadonlyMap<string, ComposerContextRecord>;
2084 - userImages: ReadonlyArray<ChatImageAttachment>;
2085 - previewImages: ReadonlyArray<ChatImageAttachment>;
2086 - annotationRecordIds: ReadonlyArray<string>;
2087 -}): ChatImageAttachment | null {
2088 - const screenshotRecord = input.record.screenshotContextId
2089 - ? asKnownContextRecord(input.recordsById.get(input.record.screenshotContextId))
2090 - : undefined;
2091 - return (
2092 - (screenshotRecord?.kind === "image"
2093 - ? input.userImages.find((image) => image.id === screenshotRecord.attachmentId)
2094 - : undefined) ??
2095 - input.previewImages.find(
2096 - (image) => image.name === `preview-annotation-${input.record.annotationId}.png`,
2097 - ) ??
2098 - input.previewImages[input.annotationRecordIds.indexOf(input.record.contextId)] ??
2099 - null
2100 - );
2101 -}
2102 -
2103 -function RevertUserMessageButton({
2104 - turnCount,
2105 - messageId,
2106 -}: {
2107 - turnCount: number;
2108 - messageId: MessageId;
2109 -}) {
2110 - const ctx = use(TimelineRowCtx);
2111 - const activity = use(TimelineRowActivityCtx);
2112 -
2113 - return (
2114 - <Tooltip>
2115 - <TooltipTrigger
2116 - render={
2117 - <Button
2118 - type="button"
2119 - size="xs"
2120 - variant="ghost"
2121 - disabled={activity.isRevertingCheckpoint || activity.isWorking}
2122 - onClick={() => ctx.onRevertToTurnCount(turnCount, messageId)}
2123 - aria-label="Edit from here"
2124 - />
2125 - }
2126 - >
2127 - <Undo2Icon className="size-3" />
2128 - </TooltipTrigger>
2129 - <TooltipPopup side="top">Edit from here</TooltipPopup>
2130 - </Tooltip>
2131 - );
2132 -}
2133 -
1555 function TurnFoldTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "turn-fold" }> }) {
1556 const ctx = use(TimelineRowCtx);
1557
@@ -2928,644 +2349,6 @@ function AssistantChangedFilesSectionInner({
2349 );
2350 }
2351
2931 -function UserMessageMentionChip(props: {
2932 - record: Extract<KnownComposerContextRecord, { kind: "mention" }>;
2933 - copyMarkdown: string;
2934 -}) {
2935 - const ctx = use(TimelineRowCtx);
2936 - return (
2937 - <Tooltip>
2938 - <TooltipTrigger
2939 - render={
2940 - <ContextChip
2941 - kind="mention"
2942 - render={<button type="button" />}
2943 - aria-label={`Preview ${props.record.path}`}
2944 - data-markdown-copy={props.copyMarkdown}
2945 - onClick={() => {
2946 - if (ctx.threadRef)
2947 - useRightPanelStore.getState().openFile(ctx.threadRef, props.record.path);
2948 - }}
2949 - >
2950 - <WorkspaceEntryIcon
2951 - path={props.record.path}
2952 - environmentId={ctx.activeThreadEnvironmentId}
2953 - cwd={ctx.workspaceRoot}
2954 - theme={ctx.resolvedTheme}
2955 - />
2956 - <ContextChipLabel>{props.record.label}</ContextChipLabel>
2957 - </ContextChip>
2958 - }
2959 - />
2960 - <TooltipPopup>
2961 - <WorkspaceEntryTooltip
2962 - path={props.record.path}
2963 - environmentId={ctx.activeThreadEnvironmentId}
2964 - cwd={ctx.workspaceRoot}
2965 - />
2966 - </TooltipPopup>
2967 - </Tooltip>
2968 - );
2969 -}
2970 -
2971 -function UserMessageContextChip(props: {
2972 - icon: ReactNode;
2973 - label: string;
2974 - kindLabel?: string;
2975 - copyMarkdown: string;
2976 - tooltip?: string;
2977 - kind: ContextChipKind;
2978 -}) {
2979 - return (
2980 - <ContextChipShell
2981 - kind={props.kind}
2982 - icon={props.icon}
2983 - label={props.label}
2984 - aria-label={props.kindLabel ? `${props.kindLabel}, ${props.label}` : undefined}
2985 - data-markdown-copy={props.copyMarkdown}
2986 - tooltip={props.tooltip}
2987 - />
2988 - );
2989 -}
2990 -
2991 -function UserMessagePullRequestContextChip(props: {
2992 - record: Extract<KnownComposerContextRecord, { kind: "review-comment" }>;
2993 - copyMarkdown: string;
2994 - kind: ContextChipKind;
2995 -}) {
2996 - const { activeThreadEnvironmentId, openPullRequest } = use(TimelineRowCtx);
2997 - const metadata = props.record.pullRequest;
2998 - if (metadata === undefined) return null;
2999 - return (
3000 - <PullRequestChip
3001 - metadata={metadata}
3002 - environmentId={activeThreadEnvironmentId}
3003 - label={reviewCommentContextLabel(props.record)}
3004 - kindLabel={pullRequestContextKindLabel(props.record)}
3005 - kind={props.kind}
3006 - copyMarkdown={props.copyMarkdown}
3007 - onOpen={openPullRequest}
3008 - />
3009 - );
3010 -}
3011 -
3012 -function UserMessagePreviewAnnotationDetails(props: {
3013 - record: Extract<KnownComposerContextRecord, { kind: "preview-annotation" }>;
3014 - image: ChatImageAttachment | null;
3015 -}) {
3016 - const ctx = use(TimelineRowCtx);
3017 - const visibleElements = props.record.elements ?? [];
3018 - return (
3019 - <div className="max-w-full overflow-hidden rounded-lg border border-border/70 bg-background/70">
3020 - {props.image?.previewUrl ? (
3021 - <button
3022 - type="button"
3023 - className="block max-h-64 w-full cursor-zoom-in overflow-hidden border-b border-border/70 bg-muted"
3024 - aria-label={`Preview ${props.image.name}`}
3025 - onClick={() => {
3026 - if (!props.image) return;
3027 - const preview = buildExpandedImagePreview([props.image], props.image.id);
3028 - if (preview) ctx.onImageExpand(preview);
3029 - }}
3030 - >
3031 - <img
3032 - src={props.image.previewUrl}
3033 - alt="Annotated preview crop"
3034 - className="max-h-64 w-full object-contain"
3035 - />
3036 - </button>
3037 - ) : (
3038 - <div className="border-b border-border/70 bg-muted/40 px-3 py-2 text-secondary-label text-xs">
3039 - Screenshot unavailable
3040 - </div>
3041 - )}
3042 - <div className="min-w-0 px-3 py-2.5">
3043 - <div className="text-message-foreground text-xs font-medium">
3044 - {props.record.pageTitle?.trim() || props.record.pageUrl || "Preview annotation"}
3045 - </div>
3046 - {props.record.comment ? (
3047 - <div className="mt-1 whitespace-pre-wrap wrap-break-word text-sm">
3048 - {props.record.comment}
3049 - </div>
3050 - ) : null}
3051 - <div className="mt-1 flex items-center gap-2 text-secondary-label text-3xs">
3052 - {props.record.targetSummary ? (
3053 - <span className="truncate">{props.record.targetSummary}</span>
3054 - ) : null}
3055 - {(props.record.styleChanges?.length ?? 0) > 0 ? (
3056 - <span className="inline-flex shrink-0 items-center gap-1">
3057 - <PaintbrushIcon className="size-3" />
3058 - {props.record.styleChanges?.length ?? 0}
3059 - </span>
3060 - ) : null}
3061 - </div>
3062 - {visibleElements.length > 0 ? (
3063 - <div className="mt-2 space-y-2 border-t border-border/60 pt-2">
3064 - {visibleElements.map((element) => {
3065 - const source = element.source;
3066 - const sourceLabel = source?.fileName
3067 - ? `${source.fileName}${source.lineNumber === null ? "" : `:${source.lineNumber}`}`
3068 - : null;
3069 - return (
3070 - <div
3071 - key={`${element.selector}\u0000${element.tagName}\u0000${sourceLabel ?? ""}\u0000${element.htmlPreview}`}
3072 - className="min-w-0"
3073 - >
3074 - <div className="flex min-w-0 items-center gap-2 text-xs">
3075 - <code className="truncate text-message-foreground">
3076 - {element.selector || `<${element.tagName}>`}
3077 - </code>
3078 - {sourceLabel ? (
3079 - <span className="ml-auto shrink-0 text-secondary-label">{sourceLabel}</span>
3080 - ) : null}
3081 - </div>
3082 - {element.htmlPreview?.trim() ? (
3083 - <pre className="mt-1 max-h-24 overflow-auto whitespace-pre-wrap rounded bg-muted/60 px-2 py-1.5 text-3xs leading-relaxed">
3084 - {element.htmlPreview.trim()}
3085 - </pre>
3086 - ) : null}
3087 - </div>
3088 - );
3089 - })}
3090 - {(props.record.elements?.length ?? 0) > visibleElements.length ? (
3091 - <div className="text-secondary-label text-3xs">
3092 - {(props.record.elements?.length ?? 0) - visibleElements.length} more selected
3093 - elements
3094 - </div>
3095 - ) : null}
3096 - </div>
3097 - ) : null}
3098 - </div>
3099 - </div>
3100 - );
3101 -}
3102 -
3103 -function UserMessageElementDetails({
3104 - record,
3105 -}: {
3106 - record: Extract<KnownComposerContextRecord, { kind: "element" }>;
3107 -}) {
3108 - const sourceLabel = record.source?.fileName
3109 - ? `${record.source.fileName}${record.source.lineNumber === null ? "" : `:${record.source.lineNumber}`}`
3110 - : null;
3111 - return (
3112 - <div className="max-w-full overflow-hidden rounded-lg border border-border/70 bg-background/70">
3113 - <div className="border-b border-border/70 px-3 py-2.5">
3114 - <div className="truncate text-message-foreground text-xs font-medium">
3115 - {record.pageTitle?.trim() || record.pageUrl}
3116 - </div>
3117 - <div className="mt-0.5 truncate text-secondary-label text-3xs">{record.pageUrl}</div>
3118 - </div>
3119 - <div className="space-y-2 px-3 py-2.5">
3120 - <div className="flex min-w-0 items-center gap-2 text-xs">
3121 - <code className="truncate text-message-foreground">
3122 - {record.selector || `<${record.tagName}>`}
3123 - </code>
3124 - {sourceLabel ? (
3125 - <span className="ml-auto shrink-0 text-secondary-label">{sourceLabel}</span>
3126 - ) : null}
3127 - </div>
3128 - {record.htmlPreview?.trim() ? (
3129 - <div className="flex h-40 flex-col overflow-hidden rounded border border-border">
3130 - <ReadOnlySourcePreview name="element.html" text={record.htmlPreview} />
3131 - </div>
3132 - ) : null}
3133 - {record.styles?.trim() ? (
3134 - <div className="flex h-32 flex-col overflow-hidden rounded border border-border">
3135 - <ReadOnlySourcePreview name="styles.css" text={record.styles} />
3136 - </div>
3137 - ) : null}
3138 - </div>
3139 - </div>
3140 - );
3141 -}
3142 -
3143 -interface UserMessageContextRenderContext {
3144 - reference: ChatMarkdownContextReference;
3145 - annotationImage: ChatImageAttachment | null;
3146 - attachment: ChatImageAttachment | ChatFileAttachment | null;
3147 - resolvedTheme: "light" | "dark";
3148 - copyMarkdown: string;
3149 - onExpandImage: (image: ChatImageAttachment) => void;
3150 - onExpandVideo: (file: ChatFileAttachment) => void;
3151 - onOpenFile: (file: ChatFileAttachment) => void;
3152 -}
3153 -
3154 -function UnavailableUserMessageContextChip(props: UserMessageContextRenderContext) {
3155 - return (
3156 - <UnresolvedChip
3157 - label={props.reference.label}
3158 - copyMarkdown={props.copyMarkdown}
3159 - tooltip="This context is no longer available."
3160 - />
3161 - );
3162 -}
3163 -
3164 -const userMessageContextPresentationRegistry = createContextPresentationRegistry<
3165 - KnownComposerContextRecord,
3166 - UserMessageContextRenderContext,
3167 - ReactNode
3168 ->({
3169 - requiredKinds: COMPOSER_CONTEXT_KINDS,
3170 - handlers: [
3171 - {
3172 - kind: "mention",
3173 - canRender: (record) => record.kind === "mention",
3174 - render: (record, context) =>
3175 - record.kind === "mention" ? (
3176 - <UserMessageMentionChip record={record} copyMarkdown={context.copyMarkdown} />
3177 - ) : (
3178 - <UnavailableUserMessageContextChip {...context} />
3179 - ),
3180 - },
3181 - {
3182 - kind: "skill",
3183 - canRender: (record) => record.kind === "skill",
3184 - render: (record, context) =>
3185 - record.kind === "skill" ? (
3186 - <UserMessageContextChip
3187 - icon={<SkillChipIcon />}
3188 - label={record.label || record.name}
3189 - kindLabel="Skill"
3190 - tooltip={`$${record.name}`}
3191 - copyMarkdown={context.copyMarkdown}
3192 - kind="skill"
3193 - />
3194 - ) : (
3195 - <UnavailableUserMessageContextChip {...context} />
3196 - ),
3197 - },
3198 - {
3199 - kind: "thread",
3200 - canRender: (record) => record.kind === "thread",
3201 - render: (record, context) =>
3202 - record.kind === "thread" ? (
3203 - <ThreadContextChip record={record} copyMarkdown={context.copyMarkdown} />
3204 - ) : (
3205 - <UnavailableUserMessageContextChip {...context} />
3206 - ),
3207 - },
3208 - {
3209 - kind: "image",
3210 - canRender: (record, context) =>
3211 - record.kind === "image" &&
3212 - context.attachment !== null &&
3213 - isImageAttachment(context.attachment),
3214 - render: (record, context) => {
3215 - if (
3216 - record.kind !== "image" ||
3217 - context.attachment === null ||
3218 - !isImageAttachment(context.attachment)
3219 - ) {
3220 - return <UnavailableUserMessageContextChip {...context} />;
3221 - }
3222 - const attachment = context.attachment;
3223 - return (
3224 - <ImageChipButton
3225 - name={record.name}
3226 - previewUrl={attachment.previewUrl}
3227 - size={formatAttachmentSize(record.sizeBytes)}
3228 - data-markdown-copy={context.copyMarkdown}
3229 - onClick={() => context.onExpandImage(attachment)}
3230 - />
3231 - );
3232 - },
3233 - },
3234 - {
3235 - kind: "file",
3236 - canRender: (record, context) =>
3237 - record.kind === "file" && context.attachment !== null && context.attachment.type === "file",
3238 - render: (record, context) => {
3239 - if (
3240 - record.kind !== "file" ||
3241 - context.attachment === null ||
3242 - context.attachment.type !== "file"
3243 - ) {
3244 - return <UnavailableUserMessageContextChip {...context} />;
3245 - }
3246 - const attachment = context.attachment;
3247 - const isVideo = isVideoAttachment(attachment);
3248 - const disabled =
3249 - attachment.downloadable === false && (!isVideo || attachment.previewUrl === undefined);
3250 - const size = formatAttachmentSize(record.sizeBytes);
3251 - return (
3252 - <FileChip
3253 - name={record.name}
3254 - size={size}
3255 - isVideo={isVideo}
3256 - theme={context.resolvedTheme}
3257 - disabled={disabled}
3258 - accessibleLabel={`${isVideo ? "Video" : "File"} attachment, ${record.name}, ${size}`}
3259 - copyMarkdown={context.copyMarkdown}
3260 - onOpen={() =>
3261 - isVideo ? context.onExpandVideo(attachment) : context.onOpenFile(attachment)
3262 - }
3263 - tooltip={`${record.name}\n${size}`}
3264 - />
3265 - );
3266 - },
3267 - },
3268 - {
3269 - kind: "terminal",
3270 - canRender: (record) => record.kind === "terminal",
3271 - render: (record, context, definition) =>
3272 - record.kind === "terminal" ? (
3273 - <span data-markdown-copy={context.copyMarkdown}>
3274 - <TerminalContextInlineChip
3275 - label={record.label}
3276 - terminalLabel={record.terminalLabel}
3277 - lineStart={record.lineStart}
3278 - lineEnd={record.lineEnd}
3279 - text={record.text}
3280 - detailsMode={definition.capabilities.details}
3281 - />
3282 - </span>
3283 - ) : (
3284 - <UnavailableUserMessageContextChip {...context} />
3285 - ),
3286 - },
3287 - {
3288 - kind: "element",
3289 - canRender: (record) => record.kind === "element",
3290 - render: (record, context) =>
3291 - record.kind === "element" ? (
3292 - <UserMessageContextPopover
3293 - copyMarkdown={context.copyMarkdown}
3294 - accessibleLabel={`Browser element, ${record.label}`}
3295 - kind="element"
3296 - icon={<MousePointerClickIcon />}
3297 - label={record.label}
3298 - >
3299 - <UserMessageElementDetails record={record} />
3300 - </UserMessageContextPopover>
3301 - ) : (
3302 - <UnavailableUserMessageContextChip {...context} />
3303 - ),
3304 - },
3305 - {
3306 - kind: "review-comment",
3307 - canRender: (record) => record.kind === "review-comment",
3308 - render: (record, context) => {
3309 - if (record.kind !== "review-comment") {
3310 - return <UnavailableUserMessageContextChip {...context} />;
3311 - }
3312 - const isPullRequest = isPullRequestSummaryContext(record);
3313 - const label = reviewCommentContextLabel(record);
3314 - const kindLabel = isPullRequest ? pullRequestContextKindLabel(record) : "Review comment";
3315 - const pullRequestState = pullRequestContextDisplayState(record) ?? "unknown";
3316 - if (isPullRequest && record.pullRequest !== undefined) {
3317 - return (
3318 - <UserMessagePullRequestContextChip
3319 - record={record}
3320 - copyMarkdown={context.copyMarkdown}
3321 - kind={PULL_REQUEST_CHIP_KINDS[pullRequestState]}
3322 - />
3323 - );
3324 - }
3325 - return (
3326 - <UserMessageContextPopover
3327 - copyMarkdown={context.copyMarkdown}
3328 - accessibleLabel={`${kindLabel}, ${label}${record.pullRequest ? `, ${record.pullRequest.title}` : ""}`}
3329 - kind={isPullRequest ? PULL_REQUEST_CHIP_KINDS[pullRequestState] : "review-comment"}
3330 - icon={isPullRequest ? <PullRequestGlyph.pullRequest /> : <MessageCircleIcon />}
3331 - label={label}
3332 - >
3333 - <UserMessageReviewCommentCard
3334 - comment={{
3335 - id: record.contextId,
3336 - sectionId: record.sectionId,
3337 - sectionTitle: record.sectionTitle,
3338 - filePath: record.filePath,
3339 - startIndex: record.startIndex,
3340 - endIndex: record.endIndex,
3341 - rangeLabel: record.rangeLabel,
3342 - text: record.text,
3343 - diff: record.diff,
3344 - ...(record.fenceLanguage !== undefined
3345 - ? { fenceLanguage: record.fenceLanguage }
3346 - : {}),
3347 - ...(record.pullRequest !== undefined ? { pullRequest: record.pullRequest } : {}),
3348 - }}
3349 - />
3350 - </UserMessageContextPopover>
3351 - );
3352 - },
3353 - },
3354 - {
3355 - kind: "preview-annotation",
3356 - canRender: (record) => record.kind === "preview-annotation",
3357 - render: (record, context) =>
3358 - record.kind === "preview-annotation" ? (
3359 - <UserMessageContextPopover
3360 - copyMarkdown={context.copyMarkdown}
3361 - accessibleLabel={`Preview annotation, ${record.label}`}
3362 - kind="preview-annotation"
3363 - icon={<MousePointerClickIcon />}
3364 - label={record.label}
3365 - >
3366 - <UserMessagePreviewAnnotationDetails record={record} image={context.annotationImage} />
3367 - </UserMessageContextPopover>
3368 - ) : (
3369 - <UnavailableUserMessageContextChip {...context} />
3370 - ),
3371 - },
3372 - ],
3373 - fallback: (_kind, _record, context) => <UnavailableUserMessageContextChip {...context} />,
3374 -});
3375 -
3376 -function UserMessageContextReferenceChip(props: {
3377 - reference: ChatMarkdownContextReference;
3378 - record: KnownComposerContextRecord | undefined;
3379 - annotationImage: ChatImageAttachment | null;
3380 - attachment: ChatImageAttachment | ChatFileAttachment | null;
3381 - onExpandImage: (image: ChatImageAttachment) => void;
3382 - onExpandVideo: (file: ChatFileAttachment) => void;
3383 - onOpenFile: (file: ChatFileAttachment) => void;
3384 -}) {
3385 - const { resolvedTheme } = use(TimelineRowCtx);
3386 - const copyMarkdown = formatComposerContextReference({
3387 - kind: props.reference.kind,
3388 - contextId: props.reference.contextId as ComposerContextId,
3389 - label: props.reference.label,
3390 - });
3391 - return userMessageContextPresentationRegistry.render(props.reference.kind, props.record, {
3392 - reference: props.reference,
3393 - annotationImage: props.annotationImage,
3394 - attachment: props.attachment,
3395 - resolvedTheme,
3396 - copyMarkdown,
3397 - onExpandImage: props.onExpandImage,
3398 - onExpandVideo: props.onExpandVideo,
3399 - onOpenFile: props.onOpenFile,
3400 - });
3401 -}
3402 -
3403 -const COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM = 1.75;
3404 -const COLLAPSED_USER_MESSAGE_FADE_MASK = `linear-gradient(to bottom, black calc(100% - ${COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM}rem), transparent)`;
3405 -
3406 -const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(props: {
3407 - text: string;
3408 - renderContextReference: (reference: ChatMarkdownContextReference) => ReactNode;
3409 - skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
3410 - markdownCwd: string | undefined;
3411 - footer?: ReactNode;
3412 -}) {
3413 - const [expanded, setExpanded] = useState(false);
3414 - const revealForFind = () => setExpanded(true);
3415 - const revealRef = findRevealRef(revealForFind);
3416 - const hasVisibleBody = props.text.trim().length > 0;
3417 - const canCollapse = hasVisibleBody && shouldCollapseUserMessage(props.text);
3418 - const isCollapsed = canCollapse && !expanded;
3419 - const showCollapseControl = canCollapse;
3420 -
3421 - return (
3422 - <div>
3423 - {hasVisibleBody ? (
3424 - <div
3425 - ref={revealRef}
3426 - className={cn("relative", isCollapsed && "max-h-44 overflow-hidden")}
3427 - data-user-message-body="true"
3428 - data-thread-find-text="true"
3429 - data-thread-find-fold={isCollapsed ? "" : undefined}
3430 - data-user-message-collapsed={isCollapsed ? "true" : "false"}
3431 - data-user-message-collapsible={canCollapse ? "true" : "false"}
3432 - data-user-message-fade={isCollapsed ? "true" : "false"}
3433 - style={
3434 - isCollapsed
3435 - ? {
3436 - WebkitMaskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
3437 - maskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
3438 - }
3439 - : undefined
3440 - }
3441 - >
3442 - <UserMessageBody
3443 - text={props.text}
3444 - renderContextReference={props.renderContextReference}
3445 - skills={props.skills}
3446 - markdownCwd={props.markdownCwd}
3447 - />
3448 - </div>
3449 - ) : null}
3450 - {showCollapseControl || props.footer ? (
3451 - <div
3452 - className={cn(
3453 - "mt-1.5 flex items-center gap-2",
3454 - showCollapseControl && props.footer ? "justify-between" : "justify-end",
3455 - )}
3456 - data-user-message-footer="true"
3457 - >
3458 - {showCollapseControl ? (
3459 - <Button
3460 - type="button"
3461 - size="xs"
3462 - variant="ghost-muted"
3463 - aria-expanded={expanded}
3464 - data-scroll-anchor-ignore
3465 - onClick={() => setExpanded((value) => !value)}
3466 - className="-ml-1"
3467 - >
3468 - {expanded ? "Show less" : "Show full message"}
3469 - </Button>
3470 - ) : null}
3471 - {props.footer ? (
3472 - <div className="ml-auto flex items-center gap-2">{props.footer}</div>
3473 - ) : null}
3474 - </div>
3475 - ) : null}
3476 - </div>
3477 - );
3478 -});
3479 -
3480 -const UserMessageBody = memo(function UserMessageBody(props: {
3481 - text: string;
3482 - renderContextReference?: (reference: ChatMarkdownContextReference) => ReactNode;
3483 - skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
3484 - markdownCwd: string | undefined;
3485 -}) {
3486 - const ctx = use(TimelineRowCtx);
3487 - if (props.text.length === 0) {
3488 - return null;
3489 - }
3490 - return (
3491 - <ChatMarkdown
3492 - text={props.text}
3493 - cwd={props.markdownCwd}
3494 - threadRef={ctx.threadRef ?? undefined}
3495 - skills={props.skills}
3496 - className="text-foreground"
3497 - lineBreaks
3498 - parseRawHtml={false}
3499 - renderContextReference={props.renderContextReference}
3500 - headingLevelOffset={MESSAGE_HEADING_LEVEL}
3501 - />
3502 - );
3503 -});
3504 -
3505 -function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentContext }) {
3506 - const renderedAppearance = useRenderedAppearance();
3507 - const ctx = use(TimelineRowCtx);
3508 - const fenceLanguage = comment.fenceLanguage ?? "diff";
3509 - const renderablePatch = getRenderablePatch(
3510 - buildReviewCommentRenderablePatch(comment),
3511 - `review-comment:${comment.id}`,
3512 - );
3513 -
3514 - return (
3515 - <div className="space-y-2 rounded-lg border border-border/70 bg-background/70 p-3">
3516 - <div className="space-y-1">
3517 - <div className="text-xs font-medium text-foreground">
3518 - {formatWorkspaceRelativePath(comment.filePath, ctx.workspaceRoot)}
3519 - </div>
3520 - <div className="text-2xs text-muted-foreground">
3521 - {comment.sectionTitle} · {comment.rangeLabel}
3522 - </div>
3523 - </div>
3524 - {comment.text.length > 0 && (
3525 - <div className="wrap-break-word text-sm">
3526 - <ChatMarkdown
3527 - text={comment.text}
3528 - cwd={ctx.markdownCwd}
3529 - skills={ctx.skills}
3530 - parseRawHtml={false}
3531 - lineBreaks
3532 - />
3533 - </div>
3534 - )}
3535 - {fenceLanguage !== "diff" && comment.diff.trim().length > 0 && (
3536 - <ChatMarkdown
3537 - text={formatReviewCommentFence(fenceLanguage, comment.diff)}
3538 - cwd={ctx.markdownCwd}
3539 - threadRef={ctx.threadRef ?? undefined}
3540 - skills={ctx.skills}
3541 - className="text-foreground"
3542 - />
3543 - )}
3544 - {renderablePatch?.kind === "files" && (
3545 - <DiffWorkerPoolProvider>
3546 - {renderablePatch.files.map((fileDiff) => (
3547 - <FileDiff
3548 - key={resolveFileDiffPath(fileDiff)}
3549 - fileDiff={fileDiff}
3550 - options={{
3551 - collapsed: false,
3552 - diffStyle: "unified",
3553 - theme: resolveDiffThemeName(renderedAppearance),
3554 - preferredHighlighter: PREFERRED_HIGHLIGHTER,
3555 - }}
3556 - />
3557 - ))}
3558 - </DiffWorkerPoolProvider>
3559 - )}
3560 - {renderablePatch?.kind === "raw" && (
3561 - <pre className="overflow-x-auto rounded-md bg-muted/40 p-2 text-xs">
3562 - {renderablePatch.text}
3563 - </pre>
3564 - )}
3565 - </div>
3566 - );
3567 -}
3568 -
2352 function handoffRunsSignature(runs: ReadonlyArray<HandoffTimelineRun>): string {
2353 return runs
2354 .map(
apps/web/src/components/chat/TimelineUserMessageRow.logic.ts new
+25
@@ -0,0 +1,25 @@
1 +import { type ChatImageAttachment } from "../../types";
2 +import type { ComposerContextRecord, KnownComposerContextRecord } from "@t3tools/contracts";
3 +import { asKnownContextRecord } from "~/lib/composerContextRecords";
4 +
5 +export function resolvePreviewAnnotationImage(input: {
6 + record: Extract<KnownComposerContextRecord, { kind: "preview-annotation" }>;
7 + recordsById: ReadonlyMap<string, ComposerContextRecord>;
8 + userImages: ReadonlyArray<ChatImageAttachment>;
9 + previewImages: ReadonlyArray<ChatImageAttachment>;
10 + annotationRecordIds: ReadonlyArray<string>;
11 +}): ChatImageAttachment | null {
12 + const screenshotRecord = input.record.screenshotContextId
13 + ? asKnownContextRecord(input.recordsById.get(input.record.screenshotContextId))
14 + : undefined;
15 + return (
16 + (screenshotRecord?.kind === "image"
17 + ? input.userImages.find((image) => image.id === screenshotRecord.attachmentId)
18 + : undefined) ??
19 + input.previewImages.find(
20 + (image) => image.name === `preview-annotation-${input.record.annotationId}.png`,
21 + ) ??
22 + input.previewImages[input.annotationRecordIds.indexOf(input.record.contextId)] ??
23 + null
24 + );
25 +}
apps/web/src/components/chat/TimelineUserMessageRow.tsx new
+619
@@ -0,0 +1,619 @@
1 +import { findRevealRef } from "./markdownFindContext";
2 +import { type MessageId, type ServerProviderSkill, ThreadId } from "@t3tools/contracts";
3 +import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message";
4 +import { Link } from "@tanstack/react-router";
5 +import { replaceComposerContextReferences } from "@t3tools/shared/composerContextReferences";
6 +import { memo, use, useState, type ReactNode } from "react";
7 +import {
8 + createMessageAttachmentPreviewProjector,
9 + selectMessageImageResources,
10 +} from "../../session-logic";
11 +import {
12 + type ChatFileAttachment,
13 + isFileAttachment,
14 + isImageAttachment,
15 + isVideoAttachment,
16 +} from "../../types";
17 +import ChatMarkdown from "../ChatMarkdown";
18 +import { DownloadIcon, EyeIcon, Redo2Icon, Undo2Icon } from "lucide-react";
19 +import { Link as LinkIconNode } from "lucide";
20 +import { Button, InlineButton } from "../ui/button";
21 +import { useAssetUrlRefresh, useAssetUrls, useAssetUrlState } from "../../assets/assetUrls";
22 +import { AttachmentImage } from "../media/AttachmentImage";
23 +import { MediaVideoPlayer } from "../media/MediaVideoPlayer";
24 +import {
25 + buildAttachmentVideoAsset,
26 + buildAttachmentVideoPreview,
27 + buildExpandedImagePreview,
28 +} from "./ExpandedImagePreview";
29 +import {
30 + SNAP_SHOT_ATTACHMENT_FRAME_CLASS,
31 + SnapShotAttachmentDetails,
32 +} from "./SnapShotAttachmentDetails";
33 +import { MessageCopyButton } from "./MessageCopyButton";
34 +import { promptLinkFor } from "../promptLinks/copyPromptLink";
35 +import { PierreEntryIcon } from "./PierreEntryIcon";
36 +import { shouldCollapseUserMessage } from "./MessagesTimeline.logic";
37 +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
38 +import {
39 + asKnownContextRecord,
40 + resolveUserMessageContext,
41 + selectedMessageContextFragment,
42 +} from "~/lib/composerContextRecords";
43 +import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";
44 +import {
45 + COMPOSER_CONTEXT_CLIPBOARD_MIME,
46 + encodeComposerContextClipboardHtml,
47 + encodeComposerContextFragment,
48 +} from "@t3tools/shared/composerContextClipboard";
49 +import { chatMarkdownClipboardPayload } from "../../markdown-clipboard";
50 +import type { ChatMarkdownContextReference } from "../ChatMarkdown";
51 +import { cn } from "~/lib/utils";
52 +import { formatChatTimestampTooltip, formatDayAwareTimestamp } from "../../timestampFormat";
53 +import { WorkflowOpeningBlock } from "./WorkflowOpeningBlock";
54 +import { TimelineRowCtx, TimelineRowActivityCtx, type TimelineRow } from "./timelineRowContext";
55 +import { MESSAGE_HEADING_LEVEL, MessageAuthorHeading } from "./TimelineRowParts";
56 +import { UserMessageContextReferenceChip } from "./UserMessageContextChips";
57 +import { resolvePreviewAnnotationImage } from "./TimelineUserMessageRow.logic";
58 +
59 +function UserVideoAttachment({ file }: { readonly file: ChatFileAttachment }) {
60 + const ctx = use(TimelineRowCtx);
61 + // Row updates rebuild attachment objects, so the asset follows only the
62 + // fields it reads.
63 + const { downloadable, id, mimeType, name } = file;
64 + const environmentId = ctx.activeThreadEnvironmentId;
65 + const asset =
66 + downloadable === false
67 + ? null
68 + : buildAttachmentVideoAsset(environmentId, { id, mimeType, name });
69 + const resource = asset?.resource ?? null;
70 + const assetUrl = useAssetUrlState(ctx.activeThreadEnvironmentId, resource);
71 + const refreshAssetUrl = useAssetUrlRefresh(ctx.activeThreadEnvironmentId, resource);
72 + const src = assetUrl._tag === "Success" ? assetUrl.url : (file.previewUrl ?? null);
73 +
74 + if (asset === null && src === null) {
75 + return (
76 + <div className="flex aspect-[4/3] w-full items-center justify-center rounded-lg border border-border/80 bg-black px-2 py-3 text-center text-2xs text-white/70">
77 + {file.name}
78 + </div>
79 + );
80 + }
81 +
82 + return (
83 + <MediaVideoPlayer
84 + src={src}
85 + sourceFailed={
86 + file.previewUrl === undefined && resource !== null && assetUrl._tag === "Failure"
87 + }
88 + label={file.name}
89 + preload="visible"
90 + onOpen={() => {
91 + const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
92 + if (preview) ctx.onImageExpand(preview);
93 + }}
94 + className="block aspect-[4/3] w-full"
95 + videoClassName="aspect-auto size-full rounded-lg border border-border/80"
96 + stateClassName="aspect-auto min-h-full rounded-lg border border-border/80 bg-black text-white"
97 + onRetry={asset ? refreshAssetUrl : undefined}
98 + actionsSource={asset ? { kind: "video", name: file.name, src, asset } : undefined}
99 + />
100 + );
101 +}
102 +
103 +export function UserMessageRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
104 + const ctx = use(TimelineRowCtx);
105 + return ctx.workflowOpening?.messageId === row.message.id ? (
106 + <WorkflowOpeningBlock
107 + opening={ctx.workflowOpening}
108 + environmentId={ctx.activeThreadEnvironmentId}
109 + onOpenThread={(threadId) => ctx.onOpenThread(ThreadId.make(threadId))}
110 + />
111 + ) : (
112 + <UserTimelineRow row={row} />
113 + );
114 +}
115 +
116 +function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message" }> }) {
117 + const ctx = use(TimelineRowCtx);
118 + const { onImageExpand, onFileOpen } = ctx;
119 + const senderThreadId = row.message.senderThreadId;
120 + const resources = selectMessageImageResources(row.message.attachments);
121 + const previewUrls = useAssetUrls(ctx.activeThreadEnvironmentId, resources);
122 + const [projectPreviews] = useState(createMessageAttachmentPreviewProjector);
123 + const previewUrlsById = new Map(
124 + resources.flatMap((resource, index) => {
125 + const url = previewUrls[index];
126 + return url ? [[resource.attachmentId, url] as const] : [];
127 + }),
128 + );
129 + const messageWithPreviews = projectPreviews(row.message, (attachment) =>
130 + previewUrlsById.get(attachment.id),
131 + );
132 + const userImages = (messageWithPreviews.attachments ?? []).filter(isImageAttachment);
133 + const userFiles = (row.message.attachments ?? []).filter(isFileAttachment);
134 + const userVideos = userFiles.filter(isVideoAttachment);
135 + const otherUserFiles = userFiles.filter((file) => !isVideoAttachment(file));
136 + const unknownAttachments = (row.message.attachments ?? []).filter(
137 + (attachment) => !isImageAttachment(attachment) && !isFileAttachment(attachment),
138 + );
139 + const userMessage = resolveUserMessagePresentation(row.message);
140 + const resolvedContext = resolveUserMessageContext(row.message);
141 + const previewImages = userImages.filter((image) => image.name.startsWith("preview-annotation-"));
142 + const revertTurnCount = row.revertTurnCount;
143 + const chippedAttachmentIds = new Set(
144 + collectComposerContextReferences(resolvedContext.text).flatMap((occurrence) => {
145 + const record = asKnownContextRecord(resolvedContext.recordsById.get(occurrence.contextId));
146 + return record?.kind === "file" || record?.kind === "image" ? [record.attachmentId] : [];
147 + }),
148 + );
149 + const regularImages = userImages.filter((image) => !image.name.startsWith("preview-annotation-"));
150 + const unchippedFiles = otherUserFiles.filter((file) => !chippedAttachmentIds.has(file.id));
151 + const annotationRecordIds = resolvedContext.records
152 + .filter((record) => record.kind === "preview-annotation")
153 + .map((record) => record.contextId);
154 + const plainText = replaceComposerContextReferences(
155 + resolvedContext.text,
156 + (reference) => reference.label,
157 + );
158 + const promptLink = promptLinkFor(plainText);
159 + const contextClipboardFragment =
160 + resolvedContext.records.length === 0
161 + ? null
162 + : encodeComposerContextFragment({
163 + version: 1,
164 + source: {
165 + environmentId: ctx.activeThreadEnvironmentId,
166 + ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),
167 + messageId: row.message.id,
168 + },
169 + records: resolvedContext.records,
170 + });
171 + const onBodyCopyCapture = (event: React.ClipboardEvent<HTMLDivElement>) => {
172 + if (resolvedContext.records.length === 0 || !event.clipboardData) return;
173 + const selection = window.getSelection();
174 + if (!selection || selection.isCollapsed) return;
175 + const copiedMarkdown: string[] = [];
176 + for (let index = 0; index < selection.rangeCount; index += 1) {
177 + const container = document.createElement("div");
178 + container.appendChild(selection.getRangeAt(index).cloneContents());
179 + // Diagram source is copied text, not authority to export context records.
180 + for (const element of container.querySelectorAll(
181 + "[data-markdown-copy]:not([data-markdown-mermaid])",
182 + )) {
183 + copiedMarkdown.push(element.getAttribute("data-markdown-copy") ?? "");
184 + }
185 + }
186 + const fragment = selectedMessageContextFragment({
187 + markdown: copiedMarkdown.join("\n"),
188 + records: resolvedContext.records,
189 + environmentId: ctx.activeThreadEnvironmentId,
190 + ...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),
191 + messageId: row.message.id,
192 + });
193 + if (!fragment) return;
194 + // Claim the copy: without preventDefault the browser default overwrites the
195 + // custom MIME type. The default content must then be written back explicitly.
196 + const payload = chatMarkdownClipboardPayload(selection);
197 + event.preventDefault();
198 + event.clipboardData.setData("text/plain", payload?.text ?? selection.toString());
199 + if (payload) {
200 + event.clipboardData.setData(
201 + "text/html",
202 + encodeComposerContextClipboardHtml(payload.text, fragment, payload.html),
203 + );
204 + }
205 + event.clipboardData.setData(COMPOSER_CONTEXT_CLIPBOARD_MIME, fragment);
206 + };
207 + const renderContextReference = (reference: ChatMarkdownContextReference) => {
208 + const record = asKnownContextRecord(resolvedContext.recordsById.get(reference.contextId));
209 + const annotationImage =
210 + record?.kind === "preview-annotation"
211 + ? resolvePreviewAnnotationImage({
212 + record,
213 + recordsById: resolvedContext.recordsById,
214 + userImages,
215 + previewImages,
216 + annotationRecordIds,
217 + })
218 + : null;
219 + const attachment =
220 + record?.kind === "image"
221 + ? (userImages.find((image) => image.id === record.attachmentId) ?? null)
222 + : record?.kind === "file"
223 + ? (userFiles.find((file) => file.id === record.attachmentId) ?? null)
224 + : null;
225 + return (
226 + <span data-thread-find-ignore>
227 + <UserMessageContextReferenceChip
228 + reference={reference}
229 + record={record}
230 + annotationImage={annotationImage}
231 + attachment={attachment}
232 + onExpandImage={(image) => {
233 + const preview = buildExpandedImagePreview(userImages, image.id);
234 + if (preview) onImageExpand(preview);
235 + }}
236 + onOpenFile={onFileOpen}
237 + onExpandVideo={(file) => {
238 + const preview = buildAttachmentVideoPreview(ctx.activeThreadEnvironmentId, file);
239 + if (preview) onImageExpand(preview);
240 + }}
241 + />
242 + </span>
243 + );
244 + };
245 +
246 + return (
247 + <div className="group flex flex-col items-end gap-1">
248 + {userMessage.attribution === "automation" ? (
249 + <p
250 + className="me-1 text-2xs text-muted-foreground/70"
251 + data-user-message-attribution="automation"
252 + >
253 + {userMessage.scheduledTaskId ? (
254 + <Link
255 + to="/settings/scheduled-tasks"
256 + search={{
257 + environmentId: ctx.activeThreadEnvironmentId,
258 + taskId: userMessage.scheduledTaskId,
259 + }}
260 + className="rounded-sm hover:text-muted-foreground hover:underline focus-visible:outline-2 focus-visible:outline-ring"
261 + >
262 + Sent by automation
263 + </Link>
264 + ) : (
265 + "Sent by automation"
266 + )}
267 + </p>
268 + ) : userMessage.attribution === "t3code" ? (
269 + <p
270 + className="me-1 text-2xs text-muted-foreground/70"
271 + data-user-message-attribution="t3code"
272 + >
273 + Sent by T3 Code
274 + </p>
275 + ) : userMessage.attribution === "agent" ? (
276 + <p className="me-1 text-2xs text-muted-foreground/70" data-user-message-attribution="agent">
277 + {senderThreadId ? (
278 + <InlineButton
279 + onClick={() => ctx.onOpenThread(senderThreadId)}
280 + tone="muted"
281 + aria-label="Open sending thread"
282 + >
283 + Sent by another agent
284 + </InlineButton>
285 + ) : (
286 + "Sent by another agent"
287 + )}
288 + </p>
289 + ) : null}
290 + {row.message.inputIntent === "steer" ||
291 + row.message.inputIntent === "promoted_queued_to_steer" ? (
292 + <UserMessageIntentMarker intent={row.message.inputIntent} />
293 + ) : null}
294 + <div className="relative max-w-[80%] rounded-2xl bg-message p-3 text-message-foreground">
295 + <MessageAuthorHeading>You</MessageAuthorHeading>
296 + {(regularImages.length > 0 || userVideos.length > 0) && (
297 + <div className="mb-2 grid max-w-[210px] grid-cols-2 gap-2">
298 + {regularImages.map((image) => (
299 + <div
300 + key={image.id}
301 + className={cn(
302 + "bg-background/70",
303 + image.source?.kind === "snap-shot" && image.previewUrl
304 + ? cn(SNAP_SHOT_ATTACHMENT_FRAME_CLASS, "col-span-2")
305 + : "aspect-[4/3] overflow-hidden rounded-lg border border-border/80",
306 + )}
307 + >
308 + {image.previewUrl ? (
309 + <button
310 + type="button"
311 + className="block h-full w-full cursor-zoom-in"
312 + aria-label={`Preview ${image.name}`}
313 + onClick={() => {
314 + const preview = buildExpandedImagePreview(regularImages, image.id);
315 + if (!preview) return;
316 + ctx.onImageExpand(preview);
317 + }}
318 + >
319 + <AttachmentImage
320 + name={image.name}
321 + mimeType={image.mimeType}
322 + src={image.previewUrl}
323 + alt={image.name}
324 + decoding="async"
325 + className="block size-full object-cover"
326 + />
327 + </button>
328 + ) : (
329 + <div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-2xs text-muted-foreground/70">
330 + {image.name}
331 + </div>
332 + )}
333 + {image.previewUrl && image.source?.kind === "snap-shot" ? (
334 + <SnapShotAttachmentDetails source={image.source} />
335 + ) : null}
336 + </div>
337 + ))}
338 + {userVideos.map((file) => (
339 + <UserVideoAttachment key={file.id} file={file} />
340 + ))}
341 + </div>
342 + )}
343 + {unchippedFiles.length > 0 || unknownAttachments.length > 0 ? (
344 + <div className="mb-2 flex flex-col gap-1">
345 + {unchippedFiles.map((file) => {
346 + const fileIdentity = (
347 + <>
348 + <PierreEntryIcon pathValue={file.name} kind="file" theme={ctx.resolvedTheme} />
349 + <span className="min-w-0 flex-1 truncate">{file.name}</span>
350 + </>
351 + );
352 + if (file.downloadable !== false) {
353 + return (
354 + <div key={file.id} className="flex min-w-0 items-center gap-1">
355 + <button
356 + type="button"
357 + aria-label={`Preview ${file.name}`}
358 + onClick={() => ctx.onFileOpen(file)}
359 + className="focus-visible:ring-ring/70 flex min-w-0 flex-1 cursor-pointer items-center gap-2 rounded-md py-1 text-left text-sm hover:underline focus-visible:ring-2 focus-visible:ring-inset focus-visible:outline-none"
360 + >
361 + {fileIdentity}
362 + <EyeIcon className="size-4 shrink-0" />
363 + </button>
364 + <Tooltip>
365 + <TooltipTrigger
366 + render={
367 + <Button
368 + size="icon-xs"
369 + variant="ghost-muted"
370 + aria-label={`Download ${file.name}`}
371 + onClick={() => ctx.onFileDownload(file)}
372 + />
373 + }
374 + >
375 + <DownloadIcon />
376 + </TooltipTrigger>
377 + <TooltipPopup side="top">Download {file.name}</TooltipPopup>
378 + </Tooltip>
379 + </div>
380 + );
381 + }
382 +
383 + return (
384 + <div key={file.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
385 + {fileIdentity}
386 + </div>
387 + );
388 + })}
389 + {unknownAttachments.map((attachment) => (
390 + <div key={attachment.id} className="flex min-w-0 items-center gap-2 py-1 text-sm">
391 + <PierreEntryIcon
392 + pathValue={attachment.name}
393 + kind="file"
394 + theme={ctx.resolvedTheme}
395 + />
396 + <span className="min-w-0 flex-1 truncate">{attachment.name}</span>
397 + </div>
398 + ))}
399 + </div>
400 + ) : null}
401 + <div onCopyCapture={onBodyCopyCapture}>
402 + <CollapsibleUserMessageBody
403 + text={resolvedContext.text}
404 + renderContextReference={renderContextReference}
405 + skills={ctx.skills}
406 + markdownCwd={ctx.markdownCwd}
407 + />
408 + </div>
409 + </div>
410 + {row.projectedItem &&
411 + row.projectedItem.item.status !== "completed" &&
412 + row.projectedItem.item.status !== "pending" &&
413 + row.projectedItem.item.status !== "waiting" ? (
414 + <div className="me-1 flex items-center gap-1.5">
415 + <span className="rounded-full border border-destructive/25 bg-destructive/8 px-1.5 py-0.5 text-3xs font-medium text-destructive">
416 + {row.projectedItem.item.status}
417 + </span>
418 + </div>
419 + ) : null}
420 + <div className="flex w-full max-w-[80%] items-center justify-end pe-1 text-xs tabular-nums opacity-0 transition-opacity duration-200 pointer-coarse:opacity-100 focus-within:opacity-100 group-hover:opacity-100">
421 + <div className="flex shrink-0 items-center gap-2">
422 + <Tooltip>
423 + <TooltipTrigger render={<p className="text-muted-foreground text-xs tabular-nums" />}>
424 + {formatDayAwareTimestamp(row.message.createdAt, ctx.timestampFormat)}
425 + </TooltipTrigger>
426 + <TooltipPopup>
427 + {formatChatTimestampTooltip(row.message.createdAt, ctx.timestampFormat)}
428 + </TooltipPopup>
429 + </Tooltip>
430 + <div className="flex items-center gap-0.5">
431 + {typeof revertTurnCount === "number" && (
432 + <RevertUserMessageButton turnCount={revertTurnCount} messageId={row.message.id} />
433 + )}
434 + {resolvedContext.text && (
435 + <MessageCopyButton
436 + text={contextClipboardFragment ? resolvedContext.text : plainText}
437 + {...(contextClipboardFragment
438 + ? {
439 + extraFlavors: { [COMPOSER_CONTEXT_CLIPBOARD_MIME]: contextClipboardFragment },
440 + }
441 + : {})}
442 + variant="ghost"
443 + />
444 + )}
445 + {promptLink !== null && (
446 + <MessageCopyButton
447 + text={promptLink}
448 + label="Copy prompt link"
449 + icon={LinkIconNode}
450 + variant="ghost"
451 + />
452 + )}
453 + </div>
454 + </div>
455 + </div>
456 + </div>
457 + );
458 +}
459 +
460 +function UserMessageIntentMarker({
461 + intent,
462 +}: {
463 + readonly intent: "steer" | "promoted_queued_to_steer";
464 +}) {
465 + return (
466 + <Tooltip>
467 + <TooltipTrigger
468 + render={
469 + <div
470 + className="me-1 flex items-center justify-end gap-1 text-xs leading-none text-muted-foreground"
471 + data-user-message-intent={intent}
472 + />
473 + }
474 + >
475 + <Redo2Icon aria-hidden="true" className="size-3" />
476 + Steer
477 + </TooltipTrigger>
478 + <TooltipPopup side="top">
479 + {intent === "promoted_queued_to_steer"
480 + ? "Originally queued, then promoted to steer the active turn"
481 + : "Steered the active turn"}
482 + </TooltipPopup>
483 + </Tooltip>
484 + );
485 +}
486 +
487 +function RevertUserMessageButton({
488 + turnCount,
489 + messageId,
490 +}: {
491 + turnCount: number;
492 + messageId: MessageId;
493 +}) {
494 + const ctx = use(TimelineRowCtx);
495 + const activity = use(TimelineRowActivityCtx);
496 +
497 + return (
498 + <Tooltip>
499 + <TooltipTrigger
500 + render={
501 + <Button
502 + type="button"
503 + size="xs"
504 + variant="ghost"
505 + disabled={activity.isRevertingCheckpoint || activity.isWorking}
506 + onClick={() => ctx.onRevertToTurnCount(turnCount, messageId)}
507 + aria-label="Edit from here"
508 + />
509 + }
510 + >
511 + <Undo2Icon className="size-3" />
512 + </TooltipTrigger>
513 + <TooltipPopup side="top">Edit from here</TooltipPopup>
514 + </Tooltip>
515 + );
516 +}
517 +
518 +const COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM = 1.75;
519 +
520 +const COLLAPSED_USER_MESSAGE_FADE_MASK = `linear-gradient(to bottom, black calc(100% - ${COLLAPSED_USER_MESSAGE_FADE_HEIGHT_REM}rem), transparent)`;
521 +
522 +const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(props: {
523 + text: string;
524 + renderContextReference: (reference: ChatMarkdownContextReference) => ReactNode;
525 + skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
526 + markdownCwd: string | undefined;
527 + footer?: ReactNode;
528 +}) {
529 + const [expanded, setExpanded] = useState(false);
530 + const revealForFind = () => setExpanded(true);
531 + const revealRef = findRevealRef(revealForFind);
532 + const hasVisibleBody = props.text.trim().length > 0;
533 + const canCollapse = hasVisibleBody && shouldCollapseUserMessage(props.text);
534 + const isCollapsed = canCollapse && !expanded;
535 + const showCollapseControl = canCollapse;
536 +
537 + return (
538 + <div>
539 + {hasVisibleBody ? (
540 + <div
541 + ref={revealRef}
542 + className={cn("relative", isCollapsed && "max-h-44 overflow-hidden")}
543 + data-user-message-body="true"
544 + data-thread-find-text="true"
545 + data-thread-find-fold={isCollapsed ? "" : undefined}
546 + data-user-message-collapsed={isCollapsed ? "true" : "false"}
547 + data-user-message-collapsible={canCollapse ? "true" : "false"}
548 + data-user-message-fade={isCollapsed ? "true" : "false"}
549 + style={
550 + isCollapsed
551 + ? {
552 + WebkitMaskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
553 + maskImage: COLLAPSED_USER_MESSAGE_FADE_MASK,
554 + }
555 + : undefined
556 + }
557 + >
558 + <UserMessageBody
559 + text={props.text}
560 + renderContextReference={props.renderContextReference}
561 + skills={props.skills}
562 + markdownCwd={props.markdownCwd}
563 + />
564 + </div>
565 + ) : null}
566 + {showCollapseControl || props.footer ? (
567 + <div
568 + className={cn(
569 + "mt-1.5 flex items-center gap-2",
570 + showCollapseControl && props.footer ? "justify-between" : "justify-end",
571 + )}
572 + data-user-message-footer="true"
573 + >
574 + {showCollapseControl ? (
575 + <Button
576 + type="button"
577 + size="xs"
578 + variant="ghost-muted"
579 + aria-expanded={expanded}
580 + data-scroll-anchor-ignore
581 + onClick={() => setExpanded((value) => !value)}
582 + className="-ml-1"
583 + >
584 + {expanded ? "Show less" : "Show full message"}
585 + </Button>
586 + ) : null}
587 + {props.footer ? (
588 + <div className="ml-auto flex items-center gap-2">{props.footer}</div>
589 + ) : null}
590 + </div>
591 + ) : null}
592 + </div>
593 + );
594 +});
595 +
596 +const UserMessageBody = memo(function UserMessageBody(props: {
597 + text: string;
598 + renderContextReference?: (reference: ChatMarkdownContextReference) => ReactNode;
599 + skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
600 + markdownCwd: string | undefined;
601 +}) {
602 + const ctx = use(TimelineRowCtx);
603 + if (props.text.length === 0) {
604 + return null;
605 + }
606 + return (
607 + <ChatMarkdown
608 + text={props.text}
609 + cwd={props.markdownCwd}
610 + threadRef={ctx.threadRef ?? undefined}
611 + skills={props.skills}
612 + className="text-foreground"
613 + lineBreaks
614 + parseRawHtml={false}
615 + renderContextReference={props.renderContextReference}
616 + headingLevelOffset={MESSAGE_HEADING_LEVEL}
617 + />
618 + );
619 +});
apps/web/src/components/chat/UserMessageContextChips.tsx new
+592
@@ -0,0 +1,592 @@
1 +import { useRenderedAppearance } from "../../hooks/useTheme";
2 +import { PullRequestGlyph } from "../pullRequest/pullRequestIcons";
3 +import { ReadOnlySourcePreview } from "../files/AttachmentFilePreview";
4 +import { useRightPanelStore } from "~/rightPanelStore";
5 +import { COMPOSER_CONTEXT_KINDS } from "@t3tools/contracts";
6 +import { formatAttachmentSize } from "@t3tools/client-runtime/state/attachments";
7 +import { use, type ReactNode } from "react";
8 +import { FileDiff } from "@pierre/diffs/react";
9 +import { DiffWorkerPoolProvider } from "../DiffWorkerPoolProvider";
10 +import {
11 + type ChatFileAttachment,
12 + type ChatImageAttachment,
13 + isImageAttachment,
14 + isVideoAttachment,
15 +} from "../../types";
16 +import {
17 + getRenderablePatch,
18 + resolveDiffThemeName,
19 + resolveFileDiffPath,
20 +} from "../../lib/diffRendering";
21 +import { PREFERRED_HIGHLIGHTER } from "../../lib/syntaxHighlighting";
22 +import ChatMarkdown from "../ChatMarkdown";
23 +import { ThreadContextChip } from "../ThreadContextChip";
24 +import { MessageCircleIcon, MousePointerClickIcon, PaintbrushIcon } from "lucide-react";
25 +import type { ComposerContextId, KnownComposerContextRecord } from "@t3tools/contracts";
26 +import { buildExpandedImagePreview } from "./ExpandedImagePreview";
27 +import { WorkspaceEntryIcon, WorkspaceEntryTooltip } from "./WorkspaceEntryIcon";
28 +import { TerminalContextInlineChip } from "./TerminalContextInlineChip";
29 +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
30 +import {
31 + ContextChipPopover as UserMessageContextPopover,
32 + ContextChipShell,
33 + FileChip,
34 + ImageChipButton,
35 + PULL_REQUEST_CHIP_KINDS,
36 + PullRequestChip,
37 + UnresolvedChip,
38 +} from "../contextChipParts";
39 +import {
40 + isPullRequestSummaryContext,
41 + pullRequestContextDisplayState,
42 + pullRequestContextKindLabel,
43 + reviewCommentContextLabel,
44 +} from "~/lib/composerContextRecords";
45 +import { formatComposerContextReference } from "@t3tools/shared/composerContextReferences";
46 +import { ContextChip, ContextChipLabel, type ContextChipKind } from "../ContextChip";
47 +import { createContextPresentationRegistry } from "../contextPresentationRegistry";
48 +import type { ChatMarkdownContextReference } from "../ChatMarkdown";
49 +import { SkillChipIcon } from "./SkillInlineText";
50 +import { formatWorkspaceRelativePath } from "../../filePathDisplay";
51 +import {
52 + buildReviewCommentRenderablePatch,
53 + formatReviewCommentFence,
54 + type ReviewCommentContext,
55 +} from "../../reviewCommentContext";
56 +import { TimelineRowCtx } from "./timelineRowContext";
57 +
58 +function UserMessageMentionChip(props: {
59 + record: Extract<KnownComposerContextRecord, { kind: "mention" }>;
60 + copyMarkdown: string;
61 +}) {
62 + const ctx = use(TimelineRowCtx);
63 + return (
64 + <Tooltip>
65 + <TooltipTrigger
66 + render={
67 + <ContextChip
68 + kind="mention"
69 + render={<button type="button" />}
70 + aria-label={`Preview ${props.record.path}`}
71 + data-markdown-copy={props.copyMarkdown}
72 + onClick={() => {
73 + if (ctx.threadRef)
74 + useRightPanelStore.getState().openFile(ctx.threadRef, props.record.path);
75 + }}
76 + >
77 + <WorkspaceEntryIcon
78 + path={props.record.path}
79 + environmentId={ctx.activeThreadEnvironmentId}
80 + cwd={ctx.workspaceRoot}
81 + theme={ctx.resolvedTheme}
82 + />
83 + <ContextChipLabel>{props.record.label}</ContextChipLabel>
84 + </ContextChip>
85 + }
86 + />
87 + <TooltipPopup>
88 + <WorkspaceEntryTooltip
89 + path={props.record.path}
90 + environmentId={ctx.activeThreadEnvironmentId}
91 + cwd={ctx.workspaceRoot}
92 + />
93 + </TooltipPopup>
94 + </Tooltip>
95 + );
96 +}
97 +
98 +function UserMessageContextChip(props: {
99 + icon: ReactNode;
100 + label: string;
101 + kindLabel?: string;
102 + copyMarkdown: string;
103 + tooltip?: string;
104 + kind: ContextChipKind;
105 +}) {
106 + return (
107 + <ContextChipShell
108 + kind={props.kind}
109 + icon={props.icon}
110 + label={props.label}
111 + aria-label={props.kindLabel ? `${props.kindLabel}, ${props.label}` : undefined}
112 + data-markdown-copy={props.copyMarkdown}
113 + tooltip={props.tooltip}
114 + />
115 + );
116 +}
117 +
118 +function UserMessagePullRequestContextChip(props: {
119 + record: Extract<KnownComposerContextRecord, { kind: "review-comment" }>;
120 + copyMarkdown: string;
121 + kind: ContextChipKind;
122 +}) {
123 + const { activeThreadEnvironmentId, openPullRequest } = use(TimelineRowCtx);
124 + const metadata = props.record.pullRequest;
125 + if (metadata === undefined) return null;
126 + return (
127 + <PullRequestChip
128 + metadata={metadata}
129 + environmentId={activeThreadEnvironmentId}
130 + label={reviewCommentContextLabel(props.record)}
131 + kindLabel={pullRequestContextKindLabel(props.record)}
132 + kind={props.kind}
133 + copyMarkdown={props.copyMarkdown}
134 + onOpen={openPullRequest}
135 + />
136 + );
137 +}
138 +
139 +function UserMessagePreviewAnnotationDetails(props: {
140 + record: Extract<KnownComposerContextRecord, { kind: "preview-annotation" }>;
141 + image: ChatImageAttachment | null;
142 +}) {
143 + const ctx = use(TimelineRowCtx);
144 + const visibleElements = props.record.elements ?? [];
145 + return (
146 + <div className="max-w-full overflow-hidden rounded-lg border border-border/70 bg-background/70">
147 + {props.image?.previewUrl ? (
148 + <button
149 + type="button"
150 + className="block max-h-64 w-full cursor-zoom-in overflow-hidden border-b border-border/70 bg-muted"
151 + aria-label={`Preview ${props.image.name}`}
152 + onClick={() => {
153 + if (!props.image) return;
154 + const preview = buildExpandedImagePreview([props.image], props.image.id);
155 + if (preview) ctx.onImageExpand(preview);
156 + }}
157 + >
158 + <img
159 + src={props.image.previewUrl}
160 + alt="Annotated preview crop"
161 + className="max-h-64 w-full object-contain"
162 + />
163 + </button>
164 + ) : (
165 + <div className="border-b border-border/70 bg-muted/40 px-3 py-2 text-secondary-label text-xs">
166 + Screenshot unavailable
167 + </div>
168 + )}
169 + <div className="min-w-0 px-3 py-2.5">
170 + <div className="text-message-foreground text-xs font-medium">
171 + {props.record.pageTitle?.trim() || props.record.pageUrl || "Preview annotation"}
172 + </div>
173 + {props.record.comment ? (
174 + <div className="mt-1 whitespace-pre-wrap wrap-break-word text-sm">
175 + {props.record.comment}
176 + </div>
177 + ) : null}
178 + <div className="mt-1 flex items-center gap-2 text-secondary-label text-3xs">
179 + {props.record.targetSummary ? (
180 + <span className="truncate">{props.record.targetSummary}</span>
181 + ) : null}
182 + {(props.record.styleChanges?.length ?? 0) > 0 ? (
183 + <span className="inline-flex shrink-0 items-center gap-1">
184 + <PaintbrushIcon className="size-3" />
185 + {props.record.styleChanges?.length ?? 0}
186 + </span>
187 + ) : null}
188 + </div>
189 + {visibleElements.length > 0 ? (
190 + <div className="mt-2 space-y-2 border-t border-border/60 pt-2">
191 + {visibleElements.map((element) => {
192 + const source = element.source;
193 + const sourceLabel = source?.fileName
194 + ? `${source.fileName}${source.lineNumber === null ? "" : `:${source.lineNumber}`}`
195 + : null;
196 + return (
197 + <div
198 + key={`${element.selector}\u0000${element.tagName}\u0000${sourceLabel ?? ""}\u0000${element.htmlPreview}`}
199 + className="min-w-0"
200 + >
201 + <div className="flex min-w-0 items-center gap-2 text-xs">
202 + <code className="truncate text-message-foreground">
203 + {element.selector || `<${element.tagName}>`}
204 + </code>
205 + {sourceLabel ? (
206 + <span className="ml-auto shrink-0 text-secondary-label">{sourceLabel}</span>
207 + ) : null}
208 + </div>
209 + {element.htmlPreview?.trim() ? (
210 + <pre className="mt-1 max-h-24 overflow-auto whitespace-pre-wrap rounded bg-muted/60 px-2 py-1.5 text-3xs leading-relaxed">
211 + {element.htmlPreview.trim()}
212 + </pre>
213 + ) : null}
214 + </div>
215 + );
216 + })}
217 + {(props.record.elements?.length ?? 0) > visibleElements.length ? (
218 + <div className="text-secondary-label text-3xs">
219 + {(props.record.elements?.length ?? 0) - visibleElements.length} more selected
220 + elements
221 + </div>
222 + ) : null}
223 + </div>
224 + ) : null}
225 + </div>
226 + </div>
227 + );
228 +}
229 +
230 +function UserMessageElementDetails({
231 + record,
232 +}: {
233 + record: Extract<KnownComposerContextRecord, { kind: "element" }>;
234 +}) {
235 + const sourceLabel = record.source?.fileName
236 + ? `${record.source.fileName}${record.source.lineNumber === null ? "" : `:${record.source.lineNumber}`}`
237 + : null;
238 + return (
239 + <div className="max-w-full overflow-hidden rounded-lg border border-border/70 bg-background/70">
240 + <div className="border-b border-border/70 px-3 py-2.5">
241 + <div className="truncate text-message-foreground text-xs font-medium">
242 + {record.pageTitle?.trim() || record.pageUrl}
243 + </div>
244 + <div className="mt-0.5 truncate text-secondary-label text-3xs">{record.pageUrl}</div>
245 + </div>
246 + <div className="space-y-2 px-3 py-2.5">
247 + <div className="flex min-w-0 items-center gap-2 text-xs">
248 + <code className="truncate text-message-foreground">
249 + {record.selector || `<${record.tagName}>`}
250 + </code>
251 + {sourceLabel ? (
252 + <span className="ml-auto shrink-0 text-secondary-label">{sourceLabel}</span>
253 + ) : null}
254 + </div>
255 + {record.htmlPreview?.trim() ? (
256 + <div className="flex h-40 flex-col overflow-hidden rounded border border-border">
257 + <ReadOnlySourcePreview name="element.html" text={record.htmlPreview} />
258 + </div>
259 + ) : null}
260 + {record.styles?.trim() ? (
261 + <div className="flex h-32 flex-col overflow-hidden rounded border border-border">
262 + <ReadOnlySourcePreview name="styles.css" text={record.styles} />
263 + </div>
264 + ) : null}
265 + </div>
266 + </div>
267 + );
268 +}
269 +
270 +interface UserMessageContextRenderContext {
271 + reference: ChatMarkdownContextReference;
272 + annotationImage: ChatImageAttachment | null;
273 + attachment: ChatImageAttachment | ChatFileAttachment | null;
274 + resolvedTheme: "light" | "dark";
275 + copyMarkdown: string;
276 + onExpandImage: (image: ChatImageAttachment) => void;
277 + onExpandVideo: (file: ChatFileAttachment) => void;
278 + onOpenFile: (file: ChatFileAttachment) => void;
279 +}
280 +
281 +function UnavailableUserMessageContextChip(props: UserMessageContextRenderContext) {
282 + return (
283 + <UnresolvedChip
284 + label={props.reference.label}
285 + copyMarkdown={props.copyMarkdown}
286 + tooltip="This context is no longer available."
287 + />
288 + );
289 +}
290 +
291 +const userMessageContextPresentationRegistry = createContextPresentationRegistry<
292 + KnownComposerContextRecord,
293 + UserMessageContextRenderContext,
294 + ReactNode
295 +>({
296 + requiredKinds: COMPOSER_CONTEXT_KINDS,
297 + handlers: [
298 + {
299 + kind: "mention",
300 + canRender: (record) => record.kind === "mention",
301 + render: (record, context) =>
302 + record.kind === "mention" ? (
303 + <UserMessageMentionChip record={record} copyMarkdown={context.copyMarkdown} />
304 + ) : (
305 + <UnavailableUserMessageContextChip {...context} />
306 + ),
307 + },
308 + {
309 + kind: "skill",
310 + canRender: (record) => record.kind === "skill",
311 + render: (record, context) =>
312 + record.kind === "skill" ? (
313 + <UserMessageContextChip
314 + icon={<SkillChipIcon />}
315 + label={record.label || record.name}
316 + kindLabel="Skill"
317 + tooltip={`$${record.name}`}
318 + copyMarkdown={context.copyMarkdown}
319 + kind="skill"
320 + />
321 + ) : (
322 + <UnavailableUserMessageContextChip {...context} />
323 + ),
324 + },
325 + {
326 + kind: "thread",
327 + canRender: (record) => record.kind === "thread",
328 + render: (record, context) =>
329 + record.kind === "thread" ? (
330 + <ThreadContextChip record={record} copyMarkdown={context.copyMarkdown} />
331 + ) : (
332 + <UnavailableUserMessageContextChip {...context} />
333 + ),
334 + },
335 + {
336 + kind: "image",
337 + canRender: (record, context) =>
338 + record.kind === "image" &&
339 + context.attachment !== null &&
340 + isImageAttachment(context.attachment),
341 + render: (record, context) => {
342 + if (
343 + record.kind !== "image" ||
344 + context.attachment === null ||
345 + !isImageAttachment(context.attachment)
346 + ) {
347 + return <UnavailableUserMessageContextChip {...context} />;
348 + }
349 + const attachment = context.attachment;
350 + return (
351 + <ImageChipButton
352 + name={record.name}
353 + previewUrl={attachment.previewUrl}
354 + size={formatAttachmentSize(record.sizeBytes)}
355 + data-markdown-copy={context.copyMarkdown}
356 + onClick={() => context.onExpandImage(attachment)}
357 + />
358 + );
359 + },
360 + },
361 + {
362 + kind: "file",
363 + canRender: (record, context) =>
364 + record.kind === "file" && context.attachment !== null && context.attachment.type === "file",
365 + render: (record, context) => {
366 + if (
367 + record.kind !== "file" ||
368 + context.attachment === null ||
369 + context.attachment.type !== "file"
370 + ) {
371 + return <UnavailableUserMessageContextChip {...context} />;
372 + }
373 + const attachment = context.attachment;
374 + const isVideo = isVideoAttachment(attachment);
375 + const disabled =
376 + attachment.downloadable === false && (!isVideo || attachment.previewUrl === undefined);
377 + const size = formatAttachmentSize(record.sizeBytes);
378 + return (
379 + <FileChip
380 + name={record.name}
381 + size={size}
382 + isVideo={isVideo}
383 + theme={context.resolvedTheme}
384 + disabled={disabled}
385 + accessibleLabel={`${isVideo ? "Video" : "File"} attachment, ${record.name}, ${size}`}
386 + copyMarkdown={context.copyMarkdown}
387 + onOpen={() =>
388 + isVideo ? context.onExpandVideo(attachment) : context.onOpenFile(attachment)
389 + }
390 + tooltip={`${record.name}\n${size}`}
391 + />
392 + );
393 + },
394 + },
395 + {
396 + kind: "terminal",
397 + canRender: (record) => record.kind === "terminal",
398 + render: (record, context, definition) =>
399 + record.kind === "terminal" ? (
400 + <span data-markdown-copy={context.copyMarkdown}>
401 + <TerminalContextInlineChip
402 + label={record.label}
403 + terminalLabel={record.terminalLabel}
404 + lineStart={record.lineStart}
405 + lineEnd={record.lineEnd}
406 + text={record.text}
407 + detailsMode={definition.capabilities.details}
408 + />
409 + </span>
410 + ) : (
411 + <UnavailableUserMessageContextChip {...context} />
412 + ),
413 + },
414 + {
415 + kind: "element",
416 + canRender: (record) => record.kind === "element",
417 + render: (record, context) =>
418 + record.kind === "element" ? (
419 + <UserMessageContextPopover
420 + copyMarkdown={context.copyMarkdown}
421 + accessibleLabel={`Browser element, ${record.label}`}
422 + kind="element"
423 + icon={<MousePointerClickIcon />}
424 + label={record.label}
425 + >
426 + <UserMessageElementDetails record={record} />
427 + </UserMessageContextPopover>
428 + ) : (
429 + <UnavailableUserMessageContextChip {...context} />
430 + ),
431 + },
432 + {
433 + kind: "review-comment",
434 + canRender: (record) => record.kind === "review-comment",
435 + render: (record, context) => {
436 + if (record.kind !== "review-comment") {
437 + return <UnavailableUserMessageContextChip {...context} />;
438 + }
439 + const isPullRequest = isPullRequestSummaryContext(record);
440 + const label = reviewCommentContextLabel(record);
441 + const kindLabel = isPullRequest ? pullRequestContextKindLabel(record) : "Review comment";
442 + const pullRequestState = pullRequestContextDisplayState(record) ?? "unknown";
443 + if (isPullRequest && record.pullRequest !== undefined) {
444 + return (
445 + <UserMessagePullRequestContextChip
446 + record={record}
447 + copyMarkdown={context.copyMarkdown}
448 + kind={PULL_REQUEST_CHIP_KINDS[pullRequestState]}
449 + />
450 + );
451 + }
452 + return (
453 + <UserMessageContextPopover
454 + copyMarkdown={context.copyMarkdown}
455 + accessibleLabel={`${kindLabel}, ${label}${record.pullRequest ? `, ${record.pullRequest.title}` : ""}`}
456 + kind={isPullRequest ? PULL_REQUEST_CHIP_KINDS[pullRequestState] : "review-comment"}
457 + icon={isPullRequest ? <PullRequestGlyph.pullRequest /> : <MessageCircleIcon />}
458 + label={label}
459 + >
460 + <UserMessageReviewCommentCard
461 + comment={{
462 + id: record.contextId,
463 + sectionId: record.sectionId,
464 + sectionTitle: record.sectionTitle,
465 + filePath: record.filePath,
466 + startIndex: record.startIndex,
467 + endIndex: record.endIndex,
468 + rangeLabel: record.rangeLabel,
469 + text: record.text,
470 + diff: record.diff,
471 + ...(record.fenceLanguage !== undefined
472 + ? { fenceLanguage: record.fenceLanguage }
473 + : {}),
474 + ...(record.pullRequest !== undefined ? { pullRequest: record.pullRequest } : {}),
475 + }}
476 + />
477 + </UserMessageContextPopover>
478 + );
479 + },
480 + },
481 + {
482 + kind: "preview-annotation",
483 + canRender: (record) => record.kind === "preview-annotation",
484 + render: (record, context) =>
485 + record.kind === "preview-annotation" ? (
486 + <UserMessageContextPopover
487 + copyMarkdown={context.copyMarkdown}
488 + accessibleLabel={`Preview annotation, ${record.label}`}
489 + kind="preview-annotation"
490 + icon={<MousePointerClickIcon />}
491 + label={record.label}
492 + >
493 + <UserMessagePreviewAnnotationDetails record={record} image={context.annotationImage} />
494 + </UserMessageContextPopover>
495 + ) : (
496 + <UnavailableUserMessageContextChip {...context} />
497 + ),
498 + },
499 + ],
500 + fallback: (_kind, _record, context) => <UnavailableUserMessageContextChip {...context} />,
501 +});
502 +
503 +export function UserMessageContextReferenceChip(props: {
504 + reference: ChatMarkdownContextReference;
505 + record: KnownComposerContextRecord | undefined;
506 + annotationImage: ChatImageAttachment | null;
507 + attachment: ChatImageAttachment | ChatFileAttachment | null;
508 + onExpandImage: (image: ChatImageAttachment) => void;
509 + onExpandVideo: (file: ChatFileAttachment) => void;
510 + onOpenFile: (file: ChatFileAttachment) => void;
511 +}) {
512 + const { resolvedTheme } = use(TimelineRowCtx);
513 + const copyMarkdown = formatComposerContextReference({
514 + kind: props.reference.kind,
515 + contextId: props.reference.contextId as ComposerContextId,
516 + label: props.reference.label,
517 + });
518 + return userMessageContextPresentationRegistry.render(props.reference.kind, props.record, {
519 + reference: props.reference,
520 + annotationImage: props.annotationImage,
521 + attachment: props.attachment,
522 + resolvedTheme,
523 + copyMarkdown,
524 + onExpandImage: props.onExpandImage,
525 + onExpandVideo: props.onExpandVideo,
526 + onOpenFile: props.onOpenFile,
527 + });
528 +}
529 +
530 +function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentContext }) {
531 + const renderedAppearance = useRenderedAppearance();
532 + const ctx = use(TimelineRowCtx);
533 + const fenceLanguage = comment.fenceLanguage ?? "diff";
534 + const renderablePatch = getRenderablePatch(
535 + buildReviewCommentRenderablePatch(comment),
536 + `review-comment:${comment.id}`,
537 + );
538 +
539 + return (
540 + <div className="space-y-2 rounded-lg border border-border/70 bg-background/70 p-3">
541 + <div className="space-y-1">
542 + <div className="text-xs font-medium text-foreground">
543 + {formatWorkspaceRelativePath(comment.filePath, ctx.workspaceRoot)}
544 + </div>
545 + <div className="text-2xs text-muted-foreground">
546 + {comment.sectionTitle} · {comment.rangeLabel}
547 + </div>
548 + </div>
549 + {comment.text.length > 0 && (
550 + <div className="wrap-break-word text-sm">
551 + <ChatMarkdown
552 + text={comment.text}
553 + cwd={ctx.markdownCwd}
554 + skills={ctx.skills}
555 + parseRawHtml={false}
556 + lineBreaks
557 + />
558 + </div>
559 + )}
560 + {fenceLanguage !== "diff" && comment.diff.trim().length > 0 && (
561 + <ChatMarkdown
562 + text={formatReviewCommentFence(fenceLanguage, comment.diff)}
563 + cwd={ctx.markdownCwd}
564 + threadRef={ctx.threadRef ?? undefined}
565 + skills={ctx.skills}
566 + className="text-foreground"
567 + />
568 + )}
569 + {renderablePatch?.kind === "files" && (
570 + <DiffWorkerPoolProvider>
571 + {renderablePatch.files.map((fileDiff) => (
572 + <FileDiff
573 + key={resolveFileDiffPath(fileDiff)}
574 + fileDiff={fileDiff}
575 + options={{
576 + collapsed: false,
577 + diffStyle: "unified",
578 + theme: resolveDiffThemeName(renderedAppearance),
579 + preferredHighlighter: PREFERRED_HIGHLIGHTER,
580 + }}
581 + />
582 + ))}
583 + </DiffWorkerPoolProvider>
584 + )}
585 + {renderablePatch?.kind === "raw" && (
586 + <pre className="overflow-x-auto rounded-md bg-muted/40 p-2 text-xs">
587 + {renderablePatch.text}
588 + </pre>
589 + )}
590 + </div>
591 + );
592 +}