TypeScript
feat(web): pasted text, voice notes, snapshots and sending files get their own shapes (#27377)
mariae57ae5a0bf38
diff --git a/apps/web/src/components/ContextChip.tsx b/apps/web/src/components/ContextChip.tsxindex fcd4c9e4fed..a536f28ccfb 100644--- a/apps/web/src/components/ContextChip.tsx+++ b/apps/web/src/components/ContextChip.tsx@@ -35,6 +35,10 @@ const contextChipVariants = cva("doc-slides": "[--context-chip-accent:var(--context-chip-doc-slides)]","doc-epub": "[--context-chip-accent:var(--context-chip-doc-epub)]",},+ shape: {+ inline: "",+ bubble: "w-64 gap-2 rounded-2xl bg-message px-3 py-2 text-sm text-message-foreground",+ },state: {unresolved: "data-[state=unresolved]:[--context-chip-accent:currentColor]",invalid:@@ -49,11 +53,12 @@ type ContextChipKind = NonNullable<VariantProps<typeof contextChipVariants>["kininterface ContextChipProps extends useRender.ComponentProps<"span"> {kind?: ContextChipKind;state?: "unresolved" | "invalid";+ shape?: "inline" | "bubble";}-function ContextChip({ className, kind, state, render, ...props }: ContextChipProps) {+function ContextChip({ className, kind, state, shape, render, ...props }: ContextChipProps) {const defaultProps = {- className: cn(contextChipVariants({ kind, state }), className),+ className: cn(contextChipVariants({ kind, state, shape }), className),"data-slot": "context-chip","data-state": state,};diff --git a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsxindex 2c7aa332756..24e15957192 100644--- a/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx+++ b/apps/web/src/components/chat/MessagesTimeline.browser.test.tsx@@ -3,6 +3,7 @@ import { onTestFinished } from "vite-plus/test";import { page } from "vite-plus/test/browser";import { stubGlobal } from "../../../test/render";import {+ ComposerContextId,EnvironmentId,MessageId,RunAttemptId,@@ -32,6 +33,11 @@ import { toastManager } from "../ui/toast";import type { CitedHistory } from "./citationProcedure";import type { TimelineNavigation } from "./timelineViewport";import { rememberTimelinePosition } from "./timelineScrollAnchoring";+import {+ COMPOSER_CONTEXT_CLIPBOARD_MIME,+ decodeComposerContextFragment,+} from "@t3tools/shared/composerContextClipboard";+import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";const environmentQuery = vi.hoisted(() => ({error: "Pull request not found",@@ -642,6 +648,75 @@ describe("MessagesTimeline agent messages", () => {});describe("MessagesTimeline attachments", () => {+ it.each(["image", "file"] as const)(+ "copies only matching context records for a wordless %s attachment",+ async (kind) => {+ const attachment = {+ type: kind,+ id: "media",+ name: kind === "image" ? "photo.png" : "clip.mp4",+ mimeType: kind === "image" ? "image/png" : "video/mp4",+ sizeBytes: 100,+ downloadable: false,+ };+ const record = {+ version: 1 as const,+ ...(kind === "image" ? { kind: "image" as const } : { kind: "file" as const }),+ contextId: ComposerContextId.make("media-context"),+ label: attachment.name,+ attachmentId: attachment.id,+ name: attachment.name,+ mimeType: attachment.mimeType,+ sizeBytes: attachment.sizeBytes,+ };+ await using screen = await renderTimeline([message("", { attachments: [attachment] })]);+ expect(screen.buttons("Copy message")).toHaveLength(0);+ await screen.rerender(+ <MessagesTimeline+ {...baseProps()}+ timelineEntries={[+ message("", {+ attachments: [attachment],+ context: { version: 1, records: [{ ...record, attachmentId: "other" }] },+ }),+ ]}+ />,+ );+ expect(screen.buttons("Copy message")).toHaveLength(0);+ await screen.rerender(+ <MessagesTimeline+ {...baseProps()}+ timelineEntries={[+ message("", {+ attachments: [attachment],+ context: {+ version: 1,+ records: [+ record,+ {+ ...record,+ contextId: ComposerContextId.make("other-context"),+ attachmentId: "other",+ },+ ],+ },+ }),+ ]}+ />,+ );+ using write = vi.spyOn(navigator.clipboard, "write").mockResolvedValue();+ await click(screen.button("Copy message"));+ await vi.waitFor(() => expect(write).toHaveBeenCalledOnce());+ const [item] = write.mock.calls[0]![0];+ const text = await (await item!.getType("text/plain")).text();+ const fragment = await (await item!.getType(COMPOSER_CONTEXT_CLIPBOARD_MIME)).text();+ expect(+ collectComposerContextReferences(text).map((reference) => reference.contextId),+ ).toEqual([record.contextId]);+ expect(decodeComposerContextFragment(fragment)?.records).toEqual([record]);+ },+ );+it.each(["loadedmetadata", "loadeddata", "canplay"])("plays audio with unknown duration after %s and updates the total later",async (readyEvent) => {diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.logic.ts b/apps/web/src/components/chat/TimelineUserMessageRow.logic.tsindex 9738e29d7cc..2bb6d0470fa 100644--- a/apps/web/src/components/chat/TimelineUserMessageRow.logic.ts+++ b/apps/web/src/components/chat/TimelineUserMessageRow.logic.ts@@ -1,7 +1,11 @@-import { type ChatImageAttachment } from "../../types";+import { type ChatFileAttachment, type ChatImageAttachment } from "../../types";import type { ComposerContextRecord, KnownComposerContextRecord } from "@t3tools/contracts";import { asKnownContextRecord } from "~/lib/composerContextRecords";+export function userMessageFileLabel(file: Pick<ChatFileAttachment, "name" | "source">) {+ return file.source?._tag === "pasted-text" ? "Pasted text" : file.name;+}+export function resolvePreviewAnnotationImage(input: {record: Extract<KnownComposerContextRecord, { kind: "preview-annotation" }>;recordsById: ReadonlyMap<string, ComposerContextRecord>;diff --git a/apps/web/src/components/chat/TimelineUserMessageRow.tsx b/apps/web/src/components/chat/TimelineUserMessageRow.tsxindex aee30e27d51..48086d40b4b 100644--- a/apps/web/src/components/chat/TimelineUserMessageRow.tsx+++ b/apps/web/src/components/chat/TimelineUserMessageRow.tsx@@ -62,7 +62,10 @@ import {resolveUserMessageContext,selectedMessageContextFragment,} from "~/lib/composerContextRecords";-import { collectComposerContextReferences } from "@t3tools/shared/composerContextReferences";+import {+ collectComposerContextReferences,+ formatComposerContextReference,+} from "@t3tools/shared/composerContextReferences";import {COMPOSER_CONTEXT_CLIPBOARD_MIME,encodeComposerContextClipboardHtml,@@ -80,7 +83,10 @@ import {TimelineRowTimestamp,} from "./TimelineRowParts";import { UserMessageContextReferenceChip } from "./UserMessageContextChips";-import { resolvePreviewAnnotationImage } from "./TimelineUserMessageRow.logic";+import {+ resolvePreviewAnnotationImage,+ userMessageFileLabel,+} from "./TimelineUserMessageRow.logic";// Drawn inside the media so dark screenshots keep an edge on the dark background.const MEDIA_EDGE_CLASS_NAME =@@ -97,6 +103,8 @@ function UserFileCard({readonly copyMarkdown: string | undefined;}) {const ctx = use(TimelineRowCtx);+ const pastedText = file.source?._tag === "pasted-text";+ const label = userMessageFileLabel(file);const extension = /\.([a-z0-9]{1,8})$/i.exec(file.name)?.[1]?.toUpperCase() ?? "File";const identity = (<>@@ -105,10 +113,17 @@ function UserFileCard({</span><span className="min-w-0 flex-1"><span className="block truncate text-sm font-medium group-hover/file:underline">- {file.name}+ {label}</span><span className="block text-xs text-muted-foreground tabular-nums">- {extension} · {formatBytes(file.sizeBytes)}+ {file.downloadable === false ? (+ "Sending…"+ ) : (+ <>+ {!pastedText && `${extension} · `}+ {formatBytes(file.sizeBytes)}+ </>+ )}</span></span></>@@ -119,12 +134,17 @@ function UserFileCard({className="flex w-64 max-w-full items-center gap-1 rounded-2xl bg-message py-2 ps-2 pe-1 text-message-foreground">{file.downloadable === false ? (- <div className="flex min-w-0 flex-1 items-center gap-3">{identity}</div>+ <>+ <div className="flex min-w-0 flex-1 items-center gap-3">{identity}</div>+ <Button size="icon-xs" variant="ghost-muted" disabled aria-label="Sending attachment">+ <DownloadIcon />+ </Button>+ </>) : (<><buttontype="button"- aria-label={`Preview ${file.name}`}+ aria-label={`Preview ${label}`}onClick={() => ctx.onFileOpen(file)}className="group/file focus-visible:ring-ring/70 flex min-w-0 flex-1 cursor-pointer items-center gap-3 rounded-xl text-left focus-visible:ring-2 focus-visible:ring-inset focus-visible:outline-none">@@ -136,14 +156,14 @@ function UserFileCard({<Buttonsize="icon-xs"variant="ghost-muted"- aria-label={`Download ${file.name}`}+ aria-label={`Download ${label}`}onClick={() => ctx.onFileDownload(file)}/>}><DownloadIcon /></TooltipTrigger>- <TooltipPopup side="top">Download {file.name}</TooltipPopup>+ <TooltipPopup side="top">Download {label}</TooltipPopup></Tooltip></>)}@@ -457,11 +477,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"regularImages.length + userVideos.length > 0;const standaloneMedia = mediaOnly || mediaAboveText;// A lone image keeps its own shape; a 4:3 crop hides most of a wide screenshot.- const loneImage =- standaloneMedia &&- userVideos.length === 0 &&- regularImages.length === 1 &&- regularImages[0]!.source?.kind !== "snap-shot";+ const loneImage = standaloneMedia && userVideos.length === 0 && regularImages.length === 1;// Several images share one rounded shape, split by hairlines.const collage =standaloneMedia &&@@ -483,6 +499,21 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"? "": reference.label,).trim() === "";+ const audioOnly =+ !folded &&+ userMessage.attribution !== "guest" &&+ userAudio.length > 0 &&+ regularImages.length + userVideos.length + otherUserFiles.length + unknownAttachments.length ===+ 0 &&+ replaceComposerContextReferences(resolvedContext.text, (reference) =>+ attachmentReferences.some(+ (attached) =>+ attached.contextId === reference.contextId &&+ userAudio.some((file) => file.id === attached.attachmentId),+ )+ ? ""+ : reference.label,+ ).trim() === "";const annotationRecordIds = resolvedContext.records.filter((record) => record.kind === "preview-annotation").map((record) => record.contextId);@@ -496,8 +527,19 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message".split(/\r?\n/).find((line) => line.trim().length > 0)?.trim() ?? "";+ const mediaCopyRecords = mediaOnly+ ? resolvedContext.records.flatMap((record) => {+ const known = asKnownContextRecord(record);+ return (known?.kind === "image" || known?.kind === "file") &&+ (regularImages.some((image) => image.id === known.attachmentId) ||+ userVideos.some((file) => file.id === known.attachmentId))+ ? [known]+ : [];+ })+ : [];+ const copyRecords = mediaOnly ? mediaCopyRecords : resolvedContext.records;const contextClipboardFragment =- resolvedContext.records.length === 0+ copyRecords.length === 0? null: encodeComposerContextFragment({version: 1,@@ -506,8 +548,10 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"...(ctx.threadRef ? { threadId: ctx.threadRef.threadId } : {}),messageId: row.message.id,},- records: resolvedContext.records,+ records: copyRecords,});+ const copyText =+ resolvedContext.text || mediaCopyRecords.map(formatComposerContextReference).join("\n");const onBodyCopyCapture = (event: React.ClipboardEvent<HTMLDivElement>) => {if (resolvedContext.records.length === 0 || !event.clipboardData) return;const selection = window.getSelection();@@ -616,9 +660,13 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message""bg-background/70",image.source?.kind === "snap-shot" && image.previewUrl? cn(- SNAP_SHOT_ATTACHMENT_FRAME_CLASS,"col-span-2",- standaloneMedia && "justify-self-end",+ standaloneMedia+ ? cn(+ MEDIA_EDGE_CLASS_NAME,+ "min-h-16 justify-self-end overflow-hidden rounded-2xl",+ )+ : SNAP_SHOT_ATTACHMENT_FRAME_CLASS,): loneImage? cn(MEDIA_EDGE_CLASS_NAME, "overflow-hidden rounded-2xl")@@ -657,10 +705,11 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"loading="lazy"className={cn("block transform-gpu",- // A fixed height keeps the row from growing when the image loads.- loneImage- ? "h-48 w-auto min-w-24 max-w-full object-cover"- : "size-full object-cover",+ standaloneMedia && image.source?.kind === "snap-shot"+ ? "h-auto max-h-48 w-auto min-w-24 max-w-full object-contain"+ : loneImage+ ? "h-48 w-auto min-w-24 max-w-full object-cover"+ : "size-full object-cover",)}/></button>@@ -724,8 +773,8 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"BUBBLE_CHIP_CLASS_NAME,userMessage.attribution === "guest"? guestBubbleClassName(false)- : !mediaOnly && !fileCardsOnly && "bg-message",- !folded && !mediaOnly && !fileCardsOnly && "p-3",+ : !mediaOnly && !fileCardsOnly && !audioOnly && "bg-message",+ !folded && !mediaOnly && !fileCardsOnly && !audioOnly && "p-3",folded && expanded && "w-full",)}>@@ -760,11 +809,12 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message">{!mediaAboveText && mediaBlock}{userAudio.length > 0 ? (- <div className="mb-2 flex max-w-full flex-col gap-1">+ <div className={cn("flex max-w-full flex-col gap-1", !audioOnly && "mb-2")}>{userAudio.map((file) => (<InlineAudioPreviewkey={file.id}name={file.name}+ variant={audioOnly ? "bubble" : "chip"}environmentId={ctx.activeThreadEnvironmentId}resource={{_tag: "attachment",@@ -795,6 +845,8 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"{!fileCardsOnly && (unchippedFiles.length > 0 || unknownAttachments.length > 0) ? (<div className="mb-2 flex flex-col gap-1">{unchippedFiles.map((file) => {+ const pastedText = file.source?._tag === "pasted-text";+ const label = userMessageFileLabel(file);const fileIdentity = (<><PierreEntryIcon@@ -802,7 +854,14 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"kind="file"theme={ctx.resolvedTheme}/>- <span className="min-w-0 flex-1 truncate">{file.name}</span>+ <span className="min-w-0 flex-1">+ <span className="block truncate">{label}</span>+ {file.downloadable === false || pastedText ? (+ <span className="block text-xs text-muted-foreground tabular-nums">+ {file.downloadable === false ? "Sending…" : formatBytes(file.sizeBytes)}+ </span>+ ) : null}+ </span></>);if (file.downloadable !== false) {@@ -810,7 +869,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"<div key={file.id} className="flex min-w-0 items-center gap-1"><buttontype="button"- aria-label={`Preview ${file.name}`}+ aria-label={`Preview ${label}`}onClick={() => ctx.onFileOpen(file)}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">@@ -823,14 +882,14 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"<Buttonsize="icon-xs"variant="ghost-muted"- aria-label={`Download ${file.name}`}+ aria-label={`Download ${label}`}onClick={() => ctx.onFileDownload(file)}/>}><DownloadIcon /></TooltipTrigger>- <TooltipPopup side="top">Download {file.name}</TooltipPopup>+ <TooltipPopup side="top">Download {label}</TooltipPopup></Tooltip></div>);@@ -854,7 +913,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"))}</div>) : null}- {fileCardsOnly ? null : (+ {fileCardsOnly || audioOnly ? null : (<div onCopyCapture={onBodyCopyCapture}><CollapsibleUserMessageBodytext={resolvedContext.text}@@ -889,9 +948,9 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"{typeof revertTurnCount === "number" && (<RevertUserMessageButton turnCount={revertTurnCount} messageId={row.message.id} />)}- {resolvedContext.text && (+ {copyText && (<MessageCopyButton- text={contextClipboardFragment ? resolvedContext.text : plainText}+ text={contextClipboardFragment ? copyText : plainText}{...(contextClipboardFragment? {extraFlavors: {diff --git a/apps/web/src/components/chat/UserMessageContextChips.tsx b/apps/web/src/components/chat/UserMessageContextChips.tsxindex 10aca8366ba..2638692caab 100644--- a/apps/web/src/components/chat/UserMessageContextChips.tsx+++ b/apps/web/src/components/chat/UserMessageContextChips.tsx@@ -60,6 +60,7 @@ import {type ReviewCommentContext,} from "../../reviewCommentContext";import { TimelineRowCtx } from "./timelineRowContext";+import { userMessageFileLabel } from "./TimelineUserMessageRow.logic";function UserMessageMentionChip(props: {record: Extract<KnownComposerContextRecord, { kind: "mention" }>;@@ -372,12 +373,14 @@ const userMessageContextPresentationRegistry = createContextPresentationRegistry}const attachment = context.attachment;const isVideo = isVideoAttachment(attachment);+ const label = userMessageFileLabel(attachment);const disabled =attachment.downloadable === false && (!isVideo || attachment.previewUrl === undefined);- const size = formatAttachmentSize(record.sizeBytes);+ const size =+ attachment.downloadable === false ? "Sending…" : formatAttachmentSize(record.sizeBytes);return (<FileChip- name={record.name}+ name={label}svgPreview={isSvgAttachment(attachment)? { environmentId: context.environmentId, attachmentId: attachment.id }@@ -387,12 +390,12 @@ const userMessageContextPresentationRegistry = createContextPresentationRegistryisVideo={isVideo}theme={context.resolvedTheme}disabled={disabled}- accessibleLabel={`${isVideo ? "Video" : "File"} attachment, ${record.name}, ${size}`}+ accessibleLabel={`${isVideo ? "Video" : "File"} attachment, ${label}, ${size}`}copyMarkdown={context.copyMarkdown}onOpen={() =>isVideo ? context.onExpandVideo(attachment) : context.onOpenFile(attachment)}- tooltip={`${record.name}\n${size}`}+ tooltip={`${label}\n${size}`}/>);},diff --git a/apps/web/src/components/files/AudioPreview.tsx b/apps/web/src/components/files/AudioPreview.tsxindex 0a8f4bcfe16..abd05015a94 100644--- a/apps/web/src/components/files/AudioPreview.tsx+++ b/apps/web/src/components/files/AudioPreview.tsx@@ -15,6 +15,7 @@ type AudioPreviewProps = {readonly revision?: string | null;readonly onError?: () => void;readonly compact?: boolean;+ readonly variant?: "chip" | "bubble";readonly failed?: boolean;readonly onOpen?: (() => void) | undefined;readonly onRetry?: () => void;@@ -111,6 +112,7 @@ function AudioChip(props: AudioPreviewProps) {<ContextChipkind="file"{...(props.failed ? { state: "invalid" as const } : {})}+ {...(props.variant === "bubble" ? { shape: "bubble" as const } : {})}className="relative isolate overflow-hidden"title={props.failed ? "Audio unavailable. Open the file or retry playback." : props.name}>@@ -140,7 +142,7 @@ function AudioChip(props: AudioPreviewProps) {><Icon aria-hidden className={loading && props.src ? "animate-spin" : undefined} /></ContextChipAction>- <ContextChipLabel className="max-w-72">+ <ContextChipLabel className={props.variant === "bubble" ? "flex-1" : "max-w-72"}>{open ? (<buttontype="button"diff --git a/apps/web/src/components/files/InlineAudioPreview.tsx b/apps/web/src/components/files/InlineAudioPreview.tsxindex 6cc0e18f047..94709bcebb5 100644--- a/apps/web/src/components/files/InlineAudioPreview.tsx+++ b/apps/web/src/components/files/InlineAudioPreview.tsx@@ -12,6 +12,7 @@ export function InlineAudioPreview(props: {readonly src?: string;readonly copyMarkdown?: string;readonly onOpen?: () => void;+ readonly variant?: "chip" | "bubble";}) {const container = useRef<HTMLSpanElement>(null);const [visible, setVisible] = useState(false);@@ -41,6 +42,7 @@ export function InlineAudioPreview(props: {<span ref={container} data-markdown-copy={props.copyMarkdown}><AudioPreviewcompact+ variant={props.variant ?? "chip"}name={props.name}src={src ?? ""}revision={