The open-source agent harness - the runtime layer that turns an LLM into a working agent.
chore: Enhance attachment ui (#802)
harshil-2096fa9977166a6f
diff --git a/.changeset/visible-attachment-metadata.md b/.changeset/visible-attachment-metadata.mdnew file mode 100644index 000000000..a0d6689b1--- /dev/null+++ b/.changeset/visible-attachment-metadata.md@@ -0,0 +1,5 @@+---+"@truefoundry/trueforge-ui": patch+---++Show file-type icons, filenames, and sizes for composer and sent message attachments.diff --git a/packages/trueforge-ui/src/atoms/AttachmentCard.tsx b/packages/trueforge-ui/src/atoms/AttachmentCard.tsxindex 5ea2feec9..b99f6589b 100644--- a/packages/trueforge-ui/src/atoms/AttachmentCard.tsx+++ b/packages/trueforge-ui/src/atoms/AttachmentCard.tsx@@ -14,6 +14,7 @@ export type AttachmentCardSize = 'chip' | 'preview';export type AttachmentCardProps = {name: string;contentType?: string;+ sizeBytes?: number;previewSrc?: string;isImage?: boolean;size?: AttachmentCardSize;@@ -23,8 +24,35 @@ export type AttachmentCardProps = {className?: string;};+const FILE_ICON_BY_EXTENSION: Record<string, string> = {+ pdf: 'file-text',+ ppt: 'file-text',+ pptx: 'file-text',+ doc: 'file-text',+ docx: 'file-text',+ txt: 'file-text',+ csv: 'file-spreadsheet',+ xls: 'file-spreadsheet',+ xlsx: 'file-spreadsheet',+ json: 'file-code',+};++export function getAttachmentFileIconName(name: string): string {+ const dotIndex = name.lastIndexOf('.');+ const extension = dotIndex > 0 && dotIndex < name.length - 1 ? name.slice(dotIndex + 1).toLowerCase() : undefined;+ return extension == null ? 'file' : (FILE_ICON_BY_EXTENSION[extension] ?? 'file');+}++function formatFileSize(bytes: number): string {+ if (bytes === 0) return '0 B';+ const megabytes = bytes / (1024 * 1024);+ if (megabytes < 1) return `${(bytes / 1024).toFixed(2)} KB`;+ return `${megabytes.toFixed(2)} MB`;+}+export function AttachmentCard({name,+ sizeBytes,previewSrc,isImage = false,size = 'chip',@@ -50,24 +78,45 @@ export function AttachmentCard({);}+ const imageChip = isImage && previewSrc != null;+ const fileIcon = getAttachmentFileIconName(name);+return (<divdata-slot="aui_attachment-chip"style={previewRem != null ? { maxWidth: `${previewRem}rem` } : undefined}- className={cn('aui-attachment-chip relative size-14 shrink-0', className)}+ className={cn(+ 'aui-attachment-chip group relative shrink-0 overflow-hidden rounded-lg border border-primary-button-bg/20',+ imageChip+ ? 'size-14'+ : cn(+ 'bg-secondary-bg flex h-14 min-w-0 items-center gap-2 px-2 py-1.5',+ previewRem == null && 'max-w-40',+ onRemove != null && 'pe-6',+ ),+ className,+ )}>- <Tooltip content={name} side="top" triggerClassName="size-full">- <div className="bg-secondary-bg relative size-full overflow-hidden rounded-[calc(var(--composer-radius,1.5rem)-var(--composer-padding,8px))] border border-primary-button-bg/20">- <Avatar className="size-full rounded-none">- <AvatarImage src={isImage ? previewSrc : undefined} alt={name} className="object-cover" />- {/* bg-none drops the default gradient (bg-image group), which bg-secondary-bg alone would not override. */}- <AvatarFallback className="rounded-none bg-secondary-bg bg-none text-text-secondary">- <Icon name="file" size="1.5rem" className="text-text-secondary" />- </AvatarFallback>- </Avatar>- </div>- </Tooltip>- <span className="sr-only">{name}</span>+ {imageChip ? (+ <Avatar className="size-full rounded-none">+ <AvatarImage src={previewSrc} alt={name} className="object-cover" />+ <AvatarFallback className="rounded-none bg-secondary-bg bg-none text-text-secondary">+ <Icon name="file" size="1.5rem" className="text-text-secondary" />+ </AvatarFallback>+ </Avatar>+ ) : (+ <>+ <Icon name={fileIcon} size="1.5rem" className="text-text-secondary shrink-0" />+ <div className="flex min-w-0 flex-col gap-0.5">+ <Tooltip content={name} side="top" triggerClassName="min-w-0">+ <span className="text-text-primary min-w-0 truncate text-sm font-medium">{name}</span>+ </Tooltip>+ {sizeBytes != null ? (+ <span className="text-text-secondary truncate text-xs">{formatFileSize(sizeBytes)}</span>+ ) : null}+ </div>+ </>+ )}{onRemove && (<buttontype="button"@@ -77,14 +126,14 @@ export function AttachmentCard({variant: 'ghost',size: 'icon',className:- 'aui-attachment-tile-remove absolute inset-e-1 top-1 z-10 size-5 rounded-full bg-black/50 text-white hover:bg-black/70 hover:text-white',+ 'aui-attachment-tile-remove absolute inset-e-0.5 top-0.5 z-10 size-4 rounded-full bg-black/50 text-white transition-opacity hover:bg-black/70 hover:text-white md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100',})}onClick={e => {e.stopPropagation();onRemove();}}>- <Icon name="xmark" size="0.75rem" />+ <Icon name="xmark" size="0.625rem" /></button>)}</div>diff --git a/packages/trueforge-ui/src/containers/AttachmentsContainer.tsx b/packages/trueforge-ui/src/containers/AttachmentsContainer.tsxindex 96dbcf0a0..eef812c03 100644--- a/packages/trueforge-ui/src/containers/AttachmentsContainer.tsx+++ b/packages/trueforge-ui/src/containers/AttachmentsContainer.tsx@@ -6,6 +6,24 @@ import { USER_MESSAGE_ATTACHMENT_PREVIEW_REM } from '../constants/attachments.jsimport { useSlot } from '../theme/SlotsProvider.js';import { isImageAttachment, useAttachmentPreviewSrc } from './useAttachmentPreviewSrc.js';+function base64DataUriByteSize(data: string): number | undefined {+ const commaIndex = data.indexOf(',');+ if (commaIndex < 0 || !data.slice(0, commaIndex).endsWith(';base64')) return undefined;++ const payload = data.slice(commaIndex + 1).replace(/\s/g, '');+ const padding = payload.endsWith('==') ? 2 : payload.endsWith('=') ? 1 : 0;+ return Math.max(0, Math.floor((payload.length * 3) / 4) - padding);+}++function useAttachmentSizeBytes(): number | undefined {+ const fileSize = useAuiState(s => ('file' in s.attachment ? s.attachment.file?.size : undefined));+ const data = useAuiState(s => {+ const filePart = s.attachment.content?.find(part => part.type === 'file');+ return filePart?.type === 'file' ? filePart.data : undefined;+ });+ return fileSize ?? (data == null ? undefined : base64DataUriByteSize(data));+}+function ComposerAttachmentItem() {const AttachmentPreviewDialog = useSlot('AttachmentPreviewDialog');const AttachmentCard = useSlot('AttachmentCard');@@ -15,12 +33,14 @@ function ComposerAttachmentItem() {const type = useAuiState(s => s.attachment.type);const isImage = isImageAttachment(type, contentType);const previewSrc = useAttachmentPreviewSrc();+ const sizeBytes = useAttachmentSizeBytes();return (<AttachmentPreviewDialog previewSrc={previewSrc}><AttachmentCardname={name}contentType={contentType}+ sizeBytes={sizeBytes}previewSrc={previewSrc}isImage={isImage}size="chip"@@ -30,7 +50,7 @@ function ComposerAttachmentItem() {);}-function MessageAttachmentItem() {+function MessageAttachmentItem({ kind }: { kind: 'image' | 'file' }) {const AttachmentPreviewDialog = useSlot('AttachmentPreviewDialog');const AttachmentCard = useSlot('AttachmentCard');const name = useAuiState(s => s.attachment.name);@@ -38,11 +58,16 @@ function MessageAttachmentItem() {const type = useAuiState(s => s.attachment.type);const isImage = isImageAttachment(type, contentType);const previewSrc = useAttachmentPreviewSrc();+ const sizeBytes = useAttachmentSizeBytes();+ const isPreview = isImage && previewSrc != null;++ if ((kind === 'image') !== isPreview) return null;const card = (<AttachmentCardname={name}contentType={contentType}+ sizeBytes={sizeBytes}previewSrc={previewSrc}isImage={isImage}size={isImage ? 'preview' : 'chip'}@@ -50,7 +75,7 @@ function MessageAttachmentItem() {/>);- if (isImage && previewSrc) {+ if (isPreview && previewSrc) {return <AttachmentPreviewDialog previewSrc={previewSrc}>{card}</AttachmentPreviewDialog>;}@@ -59,16 +84,23 @@ function MessageAttachmentItem() {export function ComposerAttachmentsContainer() {return (- <div className="aui-composer-attachments flex w-full flex-row flex-wrap items-center gap-2 empty:hidden">+ <div className="aui-composer-attachments aui-scrollbar-hidden flex w-full min-w-0 flex-row flex-nowrap items-center gap-2 overflow-x-auto overflow-y-hidden empty:hidden"><ComposerPrimitive.Attachments>{() => <ComposerAttachmentItem />}</ComposerPrimitive.Attachments></div>);}+const messageAttachmentRowClass = 'flex flex-row flex-wrap justify-end gap-2 empty:hidden';+export function MessageAttachmentsContainer() {return (- <div className="aui-user-message-attachments-end col-span-full col-start-1 row-start-1 flex w-full flex-row justify-end gap-2">- <MessagePrimitive.Attachments>{() => <MessageAttachmentItem />}</MessagePrimitive.Attachments>+ <div className="aui-user-message-attachments-end col-span-full col-start-1 row-start-1 flex w-full flex-col items-end gap-2">+ <div className={messageAttachmentRowClass}>+ <MessagePrimitive.Attachments>{() => <MessageAttachmentItem kind="image" />}</MessagePrimitive.Attachments>+ </div>+ <div className={messageAttachmentRowClass}>+ <MessagePrimitive.Attachments>{() => <MessageAttachmentItem kind="file" />}</MessagePrimitive.Attachments>+ </div></div>);}diff --git a/packages/trueforge-ui/src/containers/useAttachmentPreviewSrc.ts b/packages/trueforge-ui/src/containers/useAttachmentPreviewSrc.tsindex fefe4967b..7f0e976d3 100644--- a/packages/trueforge-ui/src/containers/useAttachmentPreviewSrc.ts+++ b/packages/trueforge-ui/src/containers/useAttachmentPreviewSrc.ts@@ -1,7 +1,7 @@'use client';import { useAuiState } from '@assistant-ui/react';-import { useEffect, useState } from 'react';+import { useLayoutEffect, useState } from 'react';export function isImageAttachment(type: string, contentType?: string): boolean {return type === 'image' || (contentType?.startsWith('image/') ?? false);@@ -10,7 +10,8 @@ export function isImageAttachment(type: string, contentType?: string): boolean {function useFileObjectUrl(file: File | undefined): string | undefined {const [src, setSrc] = useState<string | undefined>(undefined);- useEffect(() => {+ // Before paint, so an image chip does not first render as a file chip.+ useLayoutEffect(() => {if (!file) {setSrc(undefined);return;diff --git a/packages/trueforge-ui/src/icons/IconRegistry.tsx b/packages/trueforge-ui/src/icons/IconRegistry.tsxindex 50757cb24..31bbf86cd 100644--- a/packages/trueforge-ui/src/icons/IconRegistry.tsx+++ b/packages/trueforge-ui/src/icons/IconRegistry.tsx@@ -28,6 +28,9 @@ import {EllipsisVertical,ExternalLink,File,+ FileCode2,+ FileSpreadsheet,+ FileText,Github,GripVertical,History,@@ -159,6 +162,9 @@ const defaults: Record<string, IconEntry> = {'chevrons-up-down': ChevronsUpDown,loader: Loader2,file: File,+ 'file-code': FileCode2,+ 'file-spreadsheet': FileSpreadsheet,+ 'file-text': FileText,clone: Copy,copy: Copy,'dollar-sign': DollarSign,diff --git a/packages/trueforge-ui/test/atoms/AttachmentCard.test.tsx b/packages/trueforge-ui/test/atoms/AttachmentCard.test.tsxindex d4fd542af..ed895ff66 100644--- a/packages/trueforge-ui/test/atoms/AttachmentCard.test.tsx+++ b/packages/trueforge-ui/test/atoms/AttachmentCard.test.tsx@@ -1,7 +1,7 @@import { fireEvent, render, screen } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';-import { AttachmentCard } from '@/atoms/AttachmentCard.js';+import { AttachmentCard, getAttachmentFileIconName } from '@/atoms/AttachmentCard.js';describe('AttachmentCard', () => {it('renders an image preview with accessible text and a configured size', () => {@@ -30,27 +30,68 @@ describe('AttachmentCard', () => {previewSrc="/thumbnail.png"isImagepreviewRem={8}+ sizeBytes={72}onRemove={onRemove}/>,);const chip = container.querySelector('[data-slot="aui_attachment-chip"]');+ expect(chip).toHaveClass('size-14', 'rounded-lg');expect(chip).toHaveStyle({ maxWidth: '8rem' });expect(screen.getByRole('img', { name: 'long-image-name.png' })).toHaveAttribute('src', '/thumbnail.png');+ expect(screen.queryByText('long-image-name.png')).not.toBeInTheDocument();+ expect(screen.queryByText('0.07 KB')).not.toBeInTheDocument();const removeButton = screen.getByRole('button', { name: 'Remove file' });expect(removeButton).toHaveAttribute('type', 'button');expect(removeButton).toHaveAttribute('title', 'Remove file');+ expect(removeButton.className).toMatch(/md:opacity-0/);+ expect(removeButton.className).not.toMatch(/(?:^|\s)opacity-0(?:\s|$)/);fireEvent.click(removeButton);expect(onRemove).toHaveBeenCalledOnce();});- it('falls back to a file chip when image preview data is unavailable', () => {- const { container } = render(<AttachmentCard name="report.pdf" contentType="application/pdf" isImage />);+ it('renders visible file metadata when image preview data is unavailable', () => {+ const { container } = render(+ <AttachmentCard name="report.pdf" contentType="application/pdf" isImage sizeBytes={72} />,+ );- expect(container.querySelector('[data-slot="aui_attachment-chip"]')).toBeInTheDocument();+ const chip = container.querySelector('[data-slot="aui_attachment-chip"]');+ expect(chip).toBeInTheDocument();+ expect(chip).toHaveClass('h-14', 'rounded-lg', 'max-w-40');expect(screen.getByText('report.pdf')).toBeInTheDocument();+ expect(screen.getByText('0.07 KB')).toBeInTheDocument();expect(screen.queryByRole('img')).not.toBeInTheDocument();expect(screen.queryByRole('button', { name: 'Remove file' })).not.toBeInTheDocument();});++ it('matches image chip height and radius with a capped file chip width', () => {+ const { container } = render(+ <>+ <AttachmentCard name="photo.png" previewSrc="/photo.png" isImage />+ <AttachmentCard name="very-long-report-filename.pdf" contentType="application/pdf" sizeBytes={2048} />+ </>,+ );++ const chips = container.querySelectorAll('[data-slot="aui_attachment-chip"]');+ expect(chips).toHaveLength(2);+ expect(chips[0]).toHaveClass('size-14', 'rounded-lg');+ expect(chips[1]).toHaveClass('h-14', 'rounded-lg', 'max-w-40');+ expect(screen.getByText('very-long-report-filename.pdf')).toHaveClass('truncate');+ });++ it.each([+ ['report.pdf', 'file-text'],+ ['slides.pptx', 'file-text'],+ ['document.docx', 'file-text'],+ ['notes.txt', 'file-text'],+ ['results.csv', 'file-spreadsheet'],+ ['workbook.xlsx', 'file-spreadsheet'],+ ['config.json', 'file-code'],+ ['bundle.zip', 'file'],+ ['photo.png', 'file'],+ ['attachment', 'file'],+ ])('maps %s to the %s icon', (name, expectedIcon) => {+ expect(getAttachmentFileIconName(name)).toBe(expectedIcon);+ });});diff --git a/packages/trueforge-ui/test/containers/AttachmentsContainer.test.tsx b/packages/trueforge-ui/test/containers/AttachmentsContainer.test.tsxindex d58a46e6f..a6e1a6c8b 100644--- a/packages/trueforge-ui/test/containers/AttachmentsContainer.test.tsx+++ b/packages/trueforge-ui/test/containers/AttachmentsContainer.test.tsx@@ -123,18 +123,18 @@ describe('attachment containers', () => {const file = new File(['image'], 'diagram.png', { type: 'image/png' });fireEvent.change(input, { target: { files: [file] } });- expect(await screen.findByText('diagram.png')).toBeInTheDocument();await waitFor(() => {expect(screen.getByTestId('attachment-preview-slot')).toHaveAttribute('data-preview-src','blob:composer-preview',);});+ expect(screen.getByRole('img', { name: 'diagram.png' })).toBeInTheDocument();fireEvent.click(screen.getByRole('button', { name: 'Remove file' }));await waitFor(() => {- expect(screen.queryByText('diagram.png')).not.toBeInTheDocument();+ expect(screen.queryByRole('img', { name: 'diagram.png' })).not.toBeInTheDocument();});expect(remove).toHaveBeenCalledTimes(1);expect(remove.mock.calls[0]?.[0]).toMatchObject({@@ -144,6 +144,35 @@ describe('attachment containers', () => {});});+ it('shows the staged file name and size', async () => {+ const adapter = createAttachmentAdapter(async () => {});++ render(+ <AttachmentRuntimeHarness adapter={adapter}>+ <ComposerAttachmentPickerContainer />+ <ComposerAttachmentsContainer />+ </AttachmentRuntimeHarness>,+ );++ fireEvent.click(screen.getByRole('button', { name: 'Add Attachment' }));+ const input = document.querySelector<HTMLInputElement>('input[type="file"]');+ if (input === null) {+ throw new Error('Expected attachment file input');+ }++ const file = new File([new Uint8Array(2048)], 'report.pdf', { type: 'application/pdf' });+ fireEvent.change(input, { target: { files: [file] } });++ expect(await screen.findByText('report.pdf')).toBeInTheDocument();+ expect(screen.getByText('2.00 KB')).toBeInTheDocument();+ expect(document.querySelector('.aui-composer-attachments')).toHaveClass(+ 'flex-nowrap',+ 'overflow-x-auto',+ 'overflow-y-hidden',+ 'aui-scrollbar-hidden',+ );+ });+it('opens a full-size preview for a sent image attachment', () => {render(<RuntimeHarnessdiff --git a/packages/trueforge-ui/test/containers/UserMessageContainer.test.tsx b/packages/trueforge-ui/test/containers/UserMessageContainer.test.tsxindex e61641669..60ee5b542 100644--- a/packages/trueforge-ui/test/containers/UserMessageContainer.test.tsx+++ b/packages/trueforge-ui/test/containers/UserMessageContainer.test.tsx@@ -52,6 +52,7 @@ describe('UserMessageContainer', () => {});it('renders a file attachment chip above the text bubble', () => {+ const fileData = `data:application/pdf;base64,${btoa('x'.repeat(1024))}`;renderUserMessage([{role: 'user',@@ -68,7 +69,7 @@ describe('UserMessageContainer', () => {type: 'file',mimeType: 'application/pdf',filename: 'report.pdf',- data: 'data:application/pdf;base64,AAAA',+ data: fileData,},],},@@ -78,6 +79,45 @@ describe('UserMessageContainer', () => {expect(screen.getByText('See attached')).toBeInTheDocument();const chip = screen.getByText('report.pdf').closest("[data-slot='aui_attachment-chip']");expect(chip).toHaveStyle({ maxWidth: '12rem' });+ expect(screen.getByText('1.00 KB')).toBeInTheDocument();+ expect(document.querySelector('.aui-user-message-attachments-end')).toHaveClass('flex-col');+ expect(chip?.parentElement).toHaveClass('flex-wrap');+ });++ it('renders image previews and file chips in separate rows', () => {+ renderUserMessage([+ {+ role: 'user',+ content: 'Mixed',+ attachments: [+ {+ id: 'att-file',+ type: 'file',+ name: 'notes.txt',+ contentType: 'text/plain',+ status: { type: 'complete' },+ content: [+ { type: 'file', mimeType: 'text/plain', filename: 'notes.txt', data: 'data:text/plain;base64,eA==' },+ ],+ },+ {+ id: 'att-image',+ type: 'image',+ name: 'photo.png',+ contentType: 'image/png',+ status: { type: 'complete' },+ content: [{ type: 'image', image: 'data:image/png;base64,iVBORw0KGgo=', filename: 'photo.png' }],+ },+ ],+ },+ ]);++ const container = document.querySelector('.aui-user-message-attachments-end');+ const rows = Array.from(container?.children ?? []);+ const imageRowIndex = rows.findIndex(row => row.contains(screen.getByAltText('photo.png')));+ const fileRowIndex = rows.findIndex(row => row.contains(screen.getByText('notes.txt')));+ expect(imageRowIndex).toBeGreaterThanOrEqual(0);+ expect(fileRowIndex).toBeGreaterThan(imageRowIndex);});it('shows the action bar when the thread is idle', () => {