The open-source agent harness - the runtime layer that turns an LLM into a working agent.
Preview sandbox files in the chat (#926)
Abhishek Choudharyc88d850cb926
diff --git a/.changeset/chat-sandbox-file-preview.md b/.changeset/chat-sandbox-file-preview.mdnew file mode 100644index 000000000..636e5a238--- /dev/null+++ b/.changeset/chat-sandbox-file-preview.md@@ -0,0 +1,5 @@+---+'@truefoundry/trueforge-ui': patch+---++Preview sandbox files the assistant generates in the chat, in a side panel, and full page, instead of requiring a download to see them.diff --git a/packages/trueforge-ui/src/atoms/ChatFileDownload.tsx b/packages/trueforge-ui/src/atoms/ChatFileDownload.tsxindex 6596c061c..4e1b536a7 100644--- a/packages/trueforge-ui/src/atoms/ChatFileDownload.tsx+++ b/packages/trueforge-ui/src/atoms/ChatFileDownload.tsx@@ -1,8 +1,17 @@'use client';-import { useState, type MouseEvent } from 'react';+import { useMemo, useState, type MouseEvent } from 'react';+import {+ useFilePreviewLoader,+ useFilePreviewTurnId,+ useOptionalFilePreview,+ type SandboxFilePreviewTarget,+} from '../filePreview/FilePreviewContext.js';+import { inlinePreviewKind } from '../filePreview/readFilePreview.js';+import { useLoadedFilePreview } from '../filePreview/useLoadedFilePreview.js';import { Icon } from '../icons/Icon.js';+import { InlineFilePreviewCard } from './InlineFilePreviewCard.js';import { cn } from './lib/cn.js';import { Spinner } from './primitives/Spinner.js';import { Tooltip } from './primitives/Tooltip.js';@@ -29,90 +38,281 @@ export function ChatFileDownload({readOnlyTooltip,}: ChatFileDownloadProps) {const [downloadingPath, setDownloadingPath] = useState<string | null>(null);+ const preview = useOptionalFilePreview();+ const previewTurnId = useFilePreviewTurnId();+ const loadPreviewFile = useFilePreviewLoader();+ const canPreview = preview != null && previewTurnId != null && loadPreviewFile != null && readOnly !== true;+ const visualFiles = canPreview ? files.filter(file => inlinePreviewKind(file) != null) : [];+ const chipFiles = canPreview ? files.filter(file => inlinePreviewKind(file) == null) : files;- return (- <details- open- className="aui-sandbox-artifacts group my-2 overflow-hidden rounded-lg border border-primary-button-bg/20 bg-card-bg"- data-testid="aui-sandbox-artifacts"- >- <summary className="min-h-9 cursor-pointer list-none bg-primary-button-bg/5 px-3 py-2 text-xs font-medium leading-none text-primary-button-bg [&::-webkit-details-marker]:hidden">- <span className="inline-flex items-center gap-1">- <Icon name="chevron-down" size={13} className="shrink-0 transition-transform group-open:rotate-180" />- <Icon name="file" size={16} className="shrink-0" />- <span className="leading-none">- {files.length} {files.length === 1 ? 'file' : 'files'} generated+ const startDownload = ({ path, name }: { path: string; name: string }) => {+ if (!onDownloadArtifact || downloadingPath === path) return;+ setDownloadingPath(path);+ void onDownloadArtifact(path, name).finally(() => {+ setDownloadingPath(current => (current === path ? null : current));+ });+ };++ const chips =+ chipFiles.length === 0 ? null : (+ <details+ open+ className={cn(+ 'aui-sandbox-artifacts group overflow-hidden rounded-lg border border-primary-button-bg/20 bg-card-bg',+ visualFiles.length === 0 && 'my-2',+ )}+ data-testid="aui-sandbox-artifacts"+ >+ <summary className="min-h-9 cursor-pointer list-none bg-primary-button-bg/5 px-3 py-2 text-xs font-medium leading-none text-primary-button-bg [&::-webkit-details-marker]:hidden">+ <span className="inline-flex items-center gap-1">+ <Icon name="chevron-down" size={13} className="shrink-0 transition-transform group-open:rotate-180" />+ <Icon name="file" size={16} className="shrink-0" />+ <span className="leading-none">+ {chipFiles.length} {chipFiles.length === 1 ? 'file' : 'files'} generated+ </span></span>- </span>- </summary>-- <div className="flex flex-wrap items-center gap-y-1 px-3 py-2">- {files.map(({ name, path }) => {- if (readOnly) {- const itemClassName =- 'mr-3 inline-flex min-h-7 items-center gap-1.5 border-r border-border pr-3 text-xs text-text-secondary last:mr-0 last:border-r-0 last:pr-0';- const label = (- <>- <Icon name="file" size={14} className="shrink-0" />- <span className="leading-none">{name}</span>- </>- );- if (readOnlyTooltip) {- return (- <Tooltip key={path} content={readOnlyTooltip} triggerClassName={itemClassName}>- <span className="inline-flex items-center gap-1.5">{label}</span>- </Tooltip>- );- }- return (- <span key={path} className={itemClassName}>- {label}- </span>- );- }-- const href = fileDownloadBaseUrl ? `${fileDownloadBaseUrl}${path}` : undefined;- const canDownload = Boolean(onDownloadArtifact || href);- const isDownloading = downloadingPath === path;-- const handleClick = (event: MouseEvent) => {- if (!onDownloadArtifact || isDownloading) {- event.preventDefault();- return;- }- event.preventDefault();- setDownloadingPath(path);- void onDownloadArtifact(path, name).finally(() => {- setDownloadingPath(current => (current === path ? null : current));- });- };+ </summary>+ <div className="flex flex-wrap items-center gap-y-1 px-3 py-2">+ {chipFiles.map(file => (+ <ArtifactChip+ key={file.path}+ file={file}+ downloadingPath={downloadingPath}+ onStartDownload={startDownload}+ {...(fileDownloadBaseUrl != null ? { fileDownloadBaseUrl } : {})}+ {...(onDownloadArtifact != null ? { onDownloadArtifact } : {})}+ {...(readOnly != null ? { readOnly } : {})}+ {...(readOnlyTooltip != null ? { readOnlyTooltip } : {})}+ {...(preview != null ? { preview } : {})}+ {...(previewTurnId != null ? { previewTurnId } : {})}+ {...(loadPreviewFile != null ? { loadPreviewFile } : {})}+ canPreview={canPreview}+ />+ ))}+ </div>+ </details>+ );++ if (visualFiles.length === 0 || preview == null || previewTurnId == null) return chips;++ return (+ <div className="my-2 flex flex-col gap-2">+ <div className="flex flex-wrap gap-2">+ {visualFiles.map(file => {+ const href = fileDownloadBaseUrl ? `${fileDownloadBaseUrl}${file.path}` : undefined;return (- <a- key={path}- href={canDownload ? (href ?? '#') : undefined}- onClick={onDownloadArtifact ? handleClick : undefined}+ <VisualSandboxFile+ key={file.path}+ name={file.name}+ path={file.path}+ turnId={previewTurnId}+ enlarged={preview.target?.path === file.path && preview.target.turnId === previewTurnId}+ onEnlarge={() => {+ const loadFile = loadPreviewFile;+ if (loadFile == null) return;+ preview.open({+ name: file.name,+ path: file.path,+ turnId: previewTurnId,+ load: () => loadFile(file.path),+ });+ }}+ downloadBusy={downloadingPath === file.path}+ {...(onDownloadArtifact != null+ ? { onDownload: () => startDownload({ path: file.path, name: file.name }) }+ : {})}+ {...(href != null ? { downloadHref: href } : {})}+ />+ );+ })}+ </div>+ {chips}+ </div>+ );+}++function VisualSandboxFile({+ name,+ path,+ turnId,+ enlarged,+ onEnlarge,+ onDownload,+ downloadHref,+ downloadBusy,+}: {+ name: string;+ path: string;+ turnId: string;+ enlarged: boolean;+ onEnlarge: () => void;+ onDownload?: () => void;+ downloadHref?: string;+ downloadBusy: boolean;+}) {+ const loadFile = useFilePreviewLoader();+ const target = useMemo((): SandboxFilePreviewTarget | null => {+ if (loadFile == null) return null;+ return { name, path, turnId, load: () => loadFile(path) };+ }, [loadFile, name, path, turnId]);+ const loaded = useLoadedFilePreview(target, 0);++ return (+ <InlineFilePreviewCard+ name={name}+ view={loaded.view}+ enlarged={enlarged}+ onEnlarge={onEnlarge}+ downloadBusy={downloadBusy}+ {...(onDownload != null ? { onDownload } : {})}+ {...(downloadHref != null ? { downloadHref } : {})}+ />+ );+}++function ArtifactChip({+ file,+ downloadingPath,+ onStartDownload,+ fileDownloadBaseUrl,+ onDownloadArtifact,+ readOnly,+ readOnlyTooltip,+ preview,+ previewTurnId,+ loadPreviewFile,+ canPreview,+}: {+ file: ChatFileDownloadFile;+ downloadingPath: string | null;+ onStartDownload: (file: { path: string; name: string }) => void;+ fileDownloadBaseUrl?: string;+ onDownloadArtifact?: (path: string, filename: string) => Promise<void>;+ readOnly?: boolean;+ readOnlyTooltip?: string;+ preview?: ReturnType<typeof useOptionalFilePreview>;+ previewTurnId?: string;+ loadPreviewFile?: ((path: string) => Promise<Blob>) | null;+ canPreview: boolean;+}) {+ const { name, path } = file;++ if (readOnly) {+ const itemClassName =+ 'mr-3 inline-flex min-h-7 items-center gap-1.5 border-r border-border pr-3 text-xs text-text-secondary last:mr-0 last:border-r-0 last:pr-0';+ const label = (+ <>+ <Icon name="file" size={14} className="shrink-0" />+ <span className="leading-none">{name}</span>+ </>+ );+ if (readOnlyTooltip) {+ return (+ <Tooltip content={readOnlyTooltip} triggerClassName={itemClassName}>+ <span className="inline-flex items-center gap-1.5">{label}</span>+ </Tooltip>+ );+ }+ return <span className={itemClassName}>{label}</span>;+ }++ const href = fileDownloadBaseUrl ? `${fileDownloadBaseUrl}${path}` : undefined;+ const canDownload = Boolean(onDownloadArtifact || href);+ const isDownloading = downloadingPath === path;++ const handleClick = (event: MouseEvent) => {+ if (!onDownloadArtifact || isDownloading) {+ event.preventDefault();+ return;+ }+ event.preventDefault();+ onStartDownload({ path, name });+ };++ if (canPreview && preview != null && previewTurnId != null && loadPreviewFile != null) {+ const previewing = preview.target?.path === path && preview.target.turnId === previewTurnId;+ const openPreview = () => {+ const loadFile = loadPreviewFile;+ preview.open({+ name,+ path,+ turnId: previewTurnId,+ load: () => loadFile(path),+ });+ };++ return (+ <span+ className={cn(+ 'mr-3 inline-flex min-h-7 items-center gap-1 border-r border-border pr-3 last:mr-0 last:border-r-0 last:pr-0',+ previewing && 'rounded-md bg-primary-button-bg/10',+ )}+ >+ <button+ type="button"+ onClick={openPreview}+ aria-pressed={previewing}+ title={`Preview ${name}`}+ aria-label={`Preview ${name}`}+ className="inline-flex cursor-pointer items-center gap-1.5 text-xs text-text-primary hover:text-primary-button-bg"+ >+ <Icon name="file" size={14} className="shrink-0 text-text-secondary" />+ <span className="leading-none">{name}</span>+ </button>+ {canDownload ? (+ onDownloadArtifact ? (+ <button+ type="button"+ onClick={() => onStartDownload({ path, name })}+ disabled={isDownloading}aria-busy={isDownloading || undefined}+ aria-label={isDownloading ? `Downloading ${name}` : `Download ${name}`}+ title={isDownloading ? `Downloading ${name}` : `Download ${name}`}className={cn(- 'mr-3 inline-flex min-h-7 items-center gap-1.5 border-r border-border pr-3 text-xs text-text-primary last:mr-0 last:border-r-0 last:pr-0',- canDownload && !isDownloading && 'cursor-pointer hover:text-primary-button-bg',- (isDownloading || !canDownload) && 'pointer-events-none opacity-60',+ 'inline-flex items-center text-primary-button-bg',+ isDownloading ? 'cursor-progress' : 'cursor-pointer hover:text-primary-button-bg',)}+ >+ {isDownloading ? <Spinner size={14} /> : <Icon name="download" size={14} />}+ </button>+ ) : (+ <a+ href={href}download={name}- aria-label={isDownloading ? `Downloading ${name}` : `Download ${name}`}+ aria-label={`Download ${name}`}+ title={`Download ${name}`}+ className="inline-flex items-center text-primary-button-bg hover:text-primary-button-bg">- <Icon name="file" size={14} className="shrink-0 text-text-secondary" />- <span className="leading-none">{name}</span>- {isDownloading ? (- <Spinner size={14} className="shrink-0 text-primary-button-bg" />- ) : (- <Icon name="download" size={14} className="shrink-0 text-primary-button-bg" />- )}+ <Icon name="download" size={14} /></a>- );- })}- </div>- </details>+ )+ ) : null}+ </span>+ );+ }++ return (+ <a+ href={canDownload ? (href ?? '#') : undefined}+ onClick={onDownloadArtifact ? handleClick : undefined}+ aria-busy={isDownloading || undefined}+ className={cn(+ 'mr-3 inline-flex min-h-7 items-center gap-1.5 border-r border-border pr-3 text-xs text-text-primary last:mr-0 last:border-r-0 last:pr-0',+ canDownload && !isDownloading && 'cursor-pointer hover:text-primary-button-bg',+ (isDownloading || !canDownload) && 'pointer-events-none opacity-60',+ )}+ download={name}+ aria-label={isDownloading ? `Downloading ${name}` : `Download ${name}`}+ >+ <Icon name="file" size={14} className="shrink-0 text-text-secondary" />+ <span className="leading-none">{name}</span>+ {isDownloading ? (+ <Spinner size={14} className="shrink-0 text-primary-button-bg" />+ ) : (+ <Icon name="download" size={14} className="shrink-0 text-primary-button-bg" />+ )}+ </a>);}diff --git a/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx b/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsxnew file mode 100644index 000000000..180f5871f--- /dev/null+++ b/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx@@ -0,0 +1,288 @@+'use client';++import { useEffect, useRef, type PointerEvent as ReactPointerEvent } from 'react';++import { clampPreviewWidth } from '../filePreview/previewPaneWidth.js';+import { FILE_PREVIEW_HIGHLIGHT_CHAR_LIMIT, type ReadFilePreviewResult } from '../filePreview/readFilePreview.js';+import { Icon } from '../icons/Icon.js';+import { useSlot } from '../theme/SlotsProvider.js';+import { auiButtonClass } from './lib/buttonClasses.js';+import { cn } from './lib/cn.js';+import { Spinner } from './primitives/Spinner.js';++export type FilePreviewView =+ | { status: 'loading' }+ | { status: 'error'; message: string }+ | Exclude<ReadFilePreviewResult, { status: 'media' }>+ | { status: 'media'; media: 'image' | 'pdf'; objectUrl: string };++export type FilePreviewPanelProps = {+ name: string;+ placement: 'side' | 'overlay' | 'full';+ view: FilePreviewView;+ onClose: () => void;+ onDownload: () => void;+ onEnterFullPage?: () => void;+ onExitFullPage?: () => void;+ onRetry?: () => void;+ downloadBusy?: boolean;+ /** Side-pane width in CSS pixels. Overlay and full-page placement ignore this. */+ widthPx?: number;+ onWidthChange?: (widthPx: number) => void;+};++function PreviewBody({ name, view }: { name: string; view: FilePreviewView }) {+ const SyntaxHighlighter = useSlot('SyntaxHighlighter');+ const Markdown = useSlot('Markdown');++ if (view.status === 'loading') {+ return (+ <div className="flex h-full items-center justify-center text-text-secondary">+ <Spinner size={20} />+ </div>+ );+ }++ if (view.status === 'error' || view.status === 'unavailable') {+ return (+ <div className="flex h-full items-center justify-center px-6 text-center text-sm text-text-secondary">+ {view.message}+ </div>+ );+ }++ if (view.status === 'media') {+ if (view.media === 'image') {+ return (+ <div className="flex h-full items-center justify-center p-4">+ <img src={view.objectUrl} alt={name} className="max-h-full max-w-full object-contain" />+ </div>+ );+ }+ return <iframe title={name} src={view.objectUrl} className="absolute inset-0 h-full w-full border-0" />;+ }++ if (view.status === 'html') {+ return (+ <iframe+ title={name}+ // Scripts and forms run only after the page is opened. Popups stay off, and same-origin is omitted so the page cannot read the chat.+ sandbox="allow-scripts allow-forms"+ referrerPolicy="no-referrer"+ srcDoc={view.text}+ className="absolute inset-0 h-full w-full border-0 bg-white"+ />+ );+ }++ if (view.status === 'markdown') {+ return (+ <div className="px-4 py-3">+ <Markdown content={view.text} />+ </div>+ );+ }++ if (view.language != null && view.text.length <= FILE_PREVIEW_HIGHLIGHT_CHAR_LIMIT) {+ return (+ <SyntaxHighlighter+ code={view.text}+ language={view.language}+ showLineNumbers+ className="my-0 h-full rounded-none"+ />+ );+ }++ return (+ <pre className="m-0 min-h-full whitespace-pre-wrap break-words p-4 font-mono text-sm text-text-primary">+ {view.text}+ </pre>+ );+}++function resizePreview(aside: HTMLElement, requested: number, onWidthChange: (widthPx: number) => void) {+ const rowWidth = aside.parentElement?.getBoundingClientRect().width ?? 0;+ onWidthChange(clampPreviewWidth({ requested, rowWidth }));+}++export function FilePreviewPanel({+ name,+ placement,+ view,+ onClose,+ onDownload,+ onEnterFullPage,+ onExitFullPage,+ onRetry,+ downloadBusy = false,+ widthPx,+ onWidthChange,+}: FilePreviewPanelProps) {+ const panelRef = useRef<HTMLElement>(null);+ const showResizeHandle = placement === 'side' && onWidthChange != null;++ useEffect(() => {+ panelRef.current?.focus();+ }, [name, placement]);++ const onResizePointerDown = (event: ReactPointerEvent<HTMLDivElement>) => {+ if (onWidthChange == null) return;+ event.preventDefault();+ const handle = event.currentTarget;+ const aside = panelRef.current;+ if (aside == null) return;+ if (typeof handle.setPointerCapture === 'function') handle.setPointerCapture(event.pointerId);+ const originX = event.clientX;+ const originWidth = aside.getBoundingClientRect().width;++ const move = (ev: PointerEvent) => {+ resizePreview(aside, originWidth + (originX - ev.clientX), onWidthChange);+ };+ const end = (ev: PointerEvent) => {+ if (typeof handle.hasPointerCapture === 'function' && handle.hasPointerCapture(ev.pointerId)) {+ handle.releasePointerCapture(ev.pointerId);+ }+ handle.removeEventListener('pointermove', move);+ handle.removeEventListener('pointerup', end);+ handle.removeEventListener('pointercancel', end);+ };+ handle.addEventListener('pointermove', move);+ handle.addEventListener('pointerup', end);+ handle.addEventListener('pointercancel', end);+ };++ const panel = (+ <aside+ ref={panelRef}+ tabIndex={-1}+ data-slot="aui_file-preview"+ data-placement={placement}+ aria-label={`Preview of ${name}`}+ onKeyDown={event => {+ if (event.key !== 'Escape') return;+ // Keep Escape from also dismissing the widget or mobile nav behind the preview.+ event.stopPropagation();+ if (placement === 'full' && onExitFullPage != null) onExitFullPage();+ else onClose();+ }}+ style={placement === 'side' && widthPx != null ? { width: `${widthPx}px` } : undefined}+ className={cn(+ 'aui-file-preview relative flex min-h-0 min-w-0 flex-col bg-primary-bg outline-none',+ placement === 'overlay' && 'absolute inset-0 z-30',+ // Fills the chat pane only. The app sidebar and top bar stay visible.+ placement === 'full' && 'absolute inset-0 z-30',+ placement === 'side' && 'h-full shrink-0 border-l border-border',+ placement === 'side' && widthPx == null && 'w-1/2 max-w-[42rem]',+ )}+ >+ {showResizeHandle ? (+ <div+ role="separator"+ aria-orientation="vertical"+ aria-label="Resize preview"+ {...(widthPx != null ? { 'aria-valuenow': Math.round(widthPx) } : {})}+ tabIndex={0}+ title="Drag to resize"+ onPointerDown={onResizePointerDown}+ onKeyDown={event => {+ if (onWidthChange == null || panelRef.current == null) return;+ const step = event.shiftKey ? 48 : 16;+ if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;+ event.preventDefault();+ event.stopPropagation();+ const origin = panelRef.current.getBoundingClientRect().width;+ const delta = event.key === 'ArrowLeft' ? step : -step;+ resizePreview(panelRef.current, origin + delta, onWidthChange);+ }}+ className="group/resizer absolute inset-y-0 -left-2 z-20 flex w-4 cursor-col-resize touch-none items-center justify-center focus-visible:outline-none"+ >+ <div+ aria-hidden+ className="absolute inset-y-0 left-1/2 w-px -translate-x-1/2 bg-border group-hover/resizer:bg-primary-button-bg"+ />+ <div+ aria-hidden+ className={cn(+ 'relative flex h-10 w-3.5 items-center justify-center rounded-full border border-border shadow-sm',+ 'bg-primary-bg text-text-secondary',+ 'group-hover/resizer:border-primary-button-bg group-hover/resizer:bg-primary-button-bg group-hover/resizer:text-primary-button-text',+ 'group-focus-visible/resizer:border-primary-button-bg group-focus-visible/resizer:bg-primary-button-bg group-focus-visible/resizer:text-primary-button-text',+ )}+ >+ <Icon name="grip-vertical" size={12} />+ </div>+ </div>+ ) : null}+ <header className="flex h-11 shrink-0 items-center gap-2 border-b border-border px-3">+ <Icon name="file" size={16} className="shrink-0 text-text-secondary" />+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-text-primary">{name}</span>+ {view.status === 'error' && onRetry != null ? (+ <button type="button" onClick={onRetry} className={auiButtonClass({ variant: 'ghost', size: 'small' })}>+ Retry+ </button>+ ) : null}+ {placement === 'full' && onExitFullPage != null ? (+ <button+ type="button"+ onClick={onExitFullPage}+ aria-label="Exit full page"+ title="Exit full page"+ className={auiButtonClass({ variant: 'ghost', size: 'icon', className: 'h-7 w-7' })}+ >+ <Icon name="compress" size={14} />+ </button>+ ) : null}+ {placement !== 'full' && onEnterFullPage != null ? (+ <button+ type="button"+ onClick={onEnterFullPage}+ aria-label="Full page"+ title="Full page"+ className={auiButtonClass({ variant: 'ghost', size: 'icon', className: 'h-7 w-7' })}+ >+ <Icon name="expand" size={14} />+ </button>+ ) : null}+ <button+ type="button"+ onClick={onDownload}+ disabled={downloadBusy}+ aria-busy={downloadBusy || undefined}+ aria-label={downloadBusy ? `Downloading ${name}` : `Download ${name}`}+ title="Download"+ className={auiButtonClass({ variant: 'ghost', size: 'icon', className: 'h-7 w-7' })}+ >+ {downloadBusy ? <Spinner size={14} /> : <Icon name="download" size={14} />}+ </button>+ <button+ type="button"+ onClick={onClose}+ aria-label="Close preview"+ title="Close preview"+ className={auiButtonClass({ variant: 'ghost', size: 'icon', className: 'h-7 w-7' })}+ >+ <Icon name="xmark" size={14} />+ </button>+ </header>+ <div+ className={cn(+ 'relative h-full min-h-0 flex-1',+ view.status === 'html' || (view.status === 'media' && view.media === 'pdf')+ ? 'overflow-hidden'+ : 'overflow-auto',+ )}+ >+ <PreviewBody name={name} view={view} />+ </div>+ </aside>+ );++ return panel;+}++declare module '../theme/SlotsProvider.js' {+ interface AtomSlots {+ FilePreviewPanel: typeof FilePreviewPanel;+ }+}diff --git a/packages/trueforge-ui/src/atoms/InlineFilePreviewCard.tsx b/packages/trueforge-ui/src/atoms/InlineFilePreviewCard.tsxnew file mode 100644index 000000000..84e768995--- /dev/null+++ b/packages/trueforge-ui/src/atoms/InlineFilePreviewCard.tsx@@ -0,0 +1,167 @@+'use client';++import { Icon } from '../icons/Icon.js';+import type { FilePreviewView } from './FilePreviewPanel.js';+import { auiButtonClass } from './lib/buttonClasses.js';+import { cn } from './lib/cn.js';+import { Spinner } from './primitives/Spinner.js';++export type InlineFilePreviewCardProps = {+ name: string;+ view: FilePreviewView;+ enlarged: boolean;+ onEnlarge: () => void;+ onDownload?: () => void;+ downloadHref?: string;+ downloadBusy?: boolean;+};++function Thumbnail({ name, view }: { name: string; view: FilePreviewView }) {+ if (view.status === 'loading') {+ return (+ <div className="flex aspect-video items-center justify-center bg-primary-bg text-text-secondary">+ <Spinner size={16} />+ </div>+ );+ }++ if (view.status === 'error' || view.status === 'unavailable') {+ return (+ <div className="flex aspect-video items-center justify-center bg-primary-bg px-4 text-center text-xs text-text-secondary">+ {view.message}+ </div>+ );+ }++ if (view.status === 'html') {+ return (+ <div className="@container relative aspect-video overflow-hidden bg-white">+ <iframe+ title={`Thumbnail of ${name}`}+ // Scripts paint the page. Forms and popups stay off so a card cannot leave the thread on its own.+ sandbox="allow-scripts"+ referrerPolicy="no-referrer"+ srcDoc={view.text}+ tabIndex={-1}+ // Desktop-sized frame, scaled into the card so the page lays out as it will when enlarged.+ style={{ width: '80rem', height: '45rem', transform: 'scale(calc(100cqw / 80rem))' }}+ className="pointer-events-none absolute top-0 left-0 origin-top-left border-0"+ />+ </div>+ );+ }++ if (view.status === 'media' && view.media === 'image') {+ return (+ <div className="aspect-video overflow-hidden bg-primary-bg">+ <img src={view.objectUrl} alt="" className="h-full w-full object-cover object-top" />+ </div>+ );+ }++ if (view.status === 'media' && view.media === 'pdf') {+ return (+ <iframe+ title={`Thumbnail of ${name}`}+ src={view.objectUrl}+ tabIndex={-1}+ className="pointer-events-none aspect-video w-full border-0 bg-white"+ />+ );+ }++ return (+ <div className="flex aspect-video items-center justify-center bg-primary-bg px-4 text-center text-xs text-text-secondary">+ Open the preview to read this file.+ </div>+ );+}++function DownloadControl({+ name,+ onDownload,+ downloadHref,+ downloadBusy,+}: {+ name: string;+ onDownload?: () => void;+ downloadHref?: string;+ downloadBusy: boolean;+}) {+ const className = auiButtonClass({ variant: 'ghost', size: 'icon', className: 'h-7 w-7' });+ const label = downloadBusy ? `Downloading ${name}` : `Download ${name}`;+ const icon = downloadBusy ? <Spinner size={14} /> : <Icon name="download" size={14} />;++ if (onDownload != null) {+ return (+ <button+ type="button"+ onClick={onDownload}+ disabled={downloadBusy}+ aria-busy={downloadBusy || undefined}+ aria-label={label}+ title="Download"+ className={className}+ >+ {icon}+ </button>+ );+ }++ if (downloadHref == null) return null;+ return (+ <a href={downloadHref} download={name} aria-label={label} title="Download" className={className}>+ {icon}+ </a>+ );+}++/** Thumbnail of a generated page or image, with enlarge and download controls. */+export function InlineFilePreviewCard({+ name,+ view,+ enlarged,+ onEnlarge,+ onDownload,+ downloadHref,+ downloadBusy = false,+}: InlineFilePreviewCardProps) {+ return (+ <article+ data-slot="aui_inline-file-preview"+ className={cn(+ 'w-full max-w-80 overflow-hidden rounded-lg border bg-card-bg shadow-sm',+ enlarged ? 'border-primary-button-bg' : 'border-border',+ )}+ >+ <button+ type="button"+ onClick={onEnlarge}+ aria-pressed={enlarged}+ aria-label={`Enlarge preview of ${name}`}+ className="block w-full cursor-pointer text-left"+ >+ <Thumbnail name={name} view={view} />+ </button>+ <footer className="flex items-center gap-1 border-t border-border px-2.5 py-1.5">+ <span className="min-w-0 flex-1 truncate text-sm text-text-primary">{name}</span>+ <button+ type="button"+ onClick={onEnlarge}+ aria-pressed={enlarged}+ aria-label={`Enlarge ${name}`}+ title="Enlarge preview"+ className={auiButtonClass({ variant: 'ghost', size: 'icon', className: 'h-7 w-7' })}+ >+ <Icon name="expand" size={14} />+ </button>+ <DownloadControl+ name={name}+ downloadBusy={downloadBusy}+ {...(onDownload != null ? { onDownload } : {})}+ {...(downloadHref != null ? { downloadHref } : {})}+ />+ </footer>+ </article>+ );+}diff --git a/packages/trueforge-ui/src/containers/AssistantTextContainer.tsx b/packages/trueforge-ui/src/containers/AssistantTextContainer.tsxindex 01e588f84..7bd3236eb 100644--- a/packages/trueforge-ui/src/containers/AssistantTextContainer.tsx+++ b/packages/trueforge-ui/src/containers/AssistantTextContainer.tsx@@ -7,27 +7,15 @@ import {type ReasoningMessagePart,type TextMessagePart,} from '@assistant-ui/react';-import { useTrueForgeDownloadSandboxFile } from '@truefoundry/trueforge-assistant-ui-runtime';+import { useTrueForgeDownloadSandboxFile, useTrueForgeTurnId } from '@truefoundry/trueforge-assistant-ui-runtime';import { useCallback, useMemo, useRef } from 'react';+import { FilePreviewLoaderScope, FilePreviewTurnScope } from '../filePreview/FilePreviewContext.js';import { MARKDOWN_SMOOTH_BACKLOG_CHARS, useThrottledMarkdownText } from '../hooks/useThrottledMarkdownText.js';import { useSlot } from '../theme/SlotsProvider.js';+import { filenameFromPath, triggerBrowserDownload } from '../utils/triggerBrowserDownload.js';import { useToasterOptional } from './ToasterContainer.js';-function filenameFromPath(path: string): string {- return path.split('/').pop() || 'download';-}--function triggerBrowserDownload(blob: Blob, filename: string) {- if (typeof document === 'undefined') return;- const url = URL.createObjectURL(blob);- const anchor = document.createElement('a');- anchor.href = url;- anchor.download = filename;- anchor.click();- URL.revokeObjectURL(url);-}-export function AssistantTextContainer() {const Markdown = useSlot('Markdown');const toaster = useToasterOptional();@@ -36,6 +24,8 @@ export function AssistantTextContainer() {// OpenUI does not remount.const downloadRef = useRef({ downloadSandboxFile, toaster });downloadRef.current = { downloadSandboxFile, toaster };+ const turnId = useTrueForgeTurnId();+ const loadSandboxFile = useCallback((path: string) => downloadRef.current.downloadSandboxFile(path), []);const partState = useAuiState(s => s.part as MessagePartState & (TextMessagePart | ReasoningMessagePart));// Preserve the typewriter effect while it keeps pace. If its visible prefix falls too far@@ -87,8 +77,16 @@ export function AssistantTextContainer() {}, []);// Skip markdown re-parse when a raw SSE tick did not advance the committed display text.- return useMemo(+ const markdown = useMemo(() => <Markdown content={text} isStreaming={isStreaming} onDownloadArtifact={handleDownloadArtifact} />,[Markdown, text, isStreaming, handleDownloadArtifact],);++ if (turnId == null) return markdown;++ return (+ <FilePreviewTurnScope turnId={turnId}>+ <FilePreviewLoaderScope load={loadSandboxFile}>{markdown}</FilePreviewLoaderScope>+ </FilePreviewTurnScope>+ );}diff --git a/packages/trueforge-ui/src/containers/FilePreviewHost.tsx b/packages/trueforge-ui/src/containers/FilePreviewHost.tsxnew file mode 100644index 000000000..eb304a896--- /dev/null+++ b/packages/trueforge-ui/src/containers/FilePreviewHost.tsx@@ -0,0 +1,98 @@+'use client';++import { useLayoutEffect, useState } from 'react';++import { useCompactLayout } from '../atoms/lib/CompactLayoutContext.js';+import { useIsMobile } from '../atoms/lib/useIsMobile.js';+import { useFilePreview } from '../filePreview/FilePreviewContext.js';+import { clampPreviewWidth, defaultPreviewWidth } from '../filePreview/previewPaneWidth.js';+import { useLoadedFilePreview } from '../filePreview/useLoadedFilePreview.js';+import { useSlot } from '../theme/SlotsProvider.js';+import { filenameFromPath, triggerBrowserDownload } from '../utils/triggerBrowserDownload.js';+import { useToasterOptional } from './ToasterContainer.js';++const PREVIEW_WIDTH_KEY = 'trueforge.file-preview-width';++function readStoredPreviewWidth(): number | null {+ try {+ const raw = sessionStorage.getItem(PREVIEW_WIDTH_KEY);+ if (raw == null) return null;+ const value = Number(raw);+ return Number.isFinite(value) ? value : null;+ } catch {+ return null;+ }+}++function storePreviewWidth(widthPx: number) {+ try {+ sessionStorage.setItem(PREVIEW_WIDTH_KEY, String(Math.round(widthPx)));+ } catch {+ // Private browsing can reject storage. The width still applies for this view.+ }+}++/** Side pane, or a preview that fills the chat column without covering the app sidebar. */+export function FilePreviewHost() {+ const preview = useFilePreview();+ const FilePreviewPanel = useSlot('FilePreviewPanel');+ const compact = useCompactLayout();+ const isMobile = useIsMobile();+ const toaster = useToasterOptional();+ const [reloadToken, setReloadToken] = useState(0);+ const [downloadBusy, setDownloadBusy] = useState(false);+ const [widthPx, setWidthPx] = useState<number | null>(readStoredPreviewWidth);+ const loaded = useLoadedFilePreview(preview.target, reloadToken);+ const target = preview.target;+ const placement = preview.presentation === 'full' ? 'full' : compact || isMobile ? 'overlay' : 'side';++ useLayoutEffect(() => {+ if (target == null || placement !== 'side') return;+ const rowWidth = document.querySelector('[data-slot="aui_file-preview-row"]')?.getBoundingClientRect().width ?? 0;+ if (rowWidth <= 0) return;+ const next = widthPx == null ? defaultPreviewWidth(rowWidth) : clampPreviewWidth({ requested: widthPx, rowWidth });+ if (widthPx == null || Math.abs(next - widthPx) > 1) setWidthPx(next);+ }, [placement, target, widthPx]);++ if (target == null) return null;+ const canRetry = loaded.view.status === 'error';++ const handleDownload = () => {+ if (downloadBusy) return;+ setDownloadBusy(true);+ void (async () => {+ try {+ const blob = loaded.blob ?? (await target.load());+ triggerBrowserDownload(blob, filenameFromPath(target.path));+ } catch (error) {+ if (toaster != null) toaster.showError(error);+ else console.error('Failed to download sandbox file', error);+ } finally {+ setDownloadBusy(false);+ }+ })();+ };++ return (+ <FilePreviewPanel+ name={target.name}+ placement={placement}+ view={loaded.view}+ onClose={preview.close}+ onDownload={handleDownload}+ onEnterFullPage={() => preview.setPresentation('full')}+ onExitFullPage={() => preview.setPresentation('panel')}+ downloadBusy={downloadBusy}+ {...(placement === 'side' && widthPx != null ? { widthPx } : {})}+ {...(placement === 'side'+ ? {+ onWidthChange: (next: number) => {+ setWidthPx(next);+ storePreviewWidth(next);+ },+ }+ : {})}+ {...(canRetry ? { onRetry: () => setReloadToken(token => token + 1) } : {})}+ />+ );+}diff --git a/packages/trueforge-ui/src/containers/ThreadContainer.tsx b/packages/trueforge-ui/src/containers/ThreadContainer.tsxindex 32f5a372f..854fd0ba9 100644--- a/packages/trueforge-ui/src/containers/ThreadContainer.tsx+++ b/packages/trueforge-ui/src/containers/ThreadContainer.tsx@@ -3,6 +3,7 @@import { ThreadPrimitive, useAuiState } from '@assistant-ui/react';import { useEffect, type ReactNode } from 'react';import { preloadMarkdownOpenUI } from '../atoms/Markdown.js';+import { FilePreviewBoundary } from '../filePreview/FilePreviewContext.js';import { ComposerBusyProvider } from '../hooks/useComposerBusyState.js';import { useSyncSessionTitle } from '../hooks/useSyncSessionTitle.js';import { useOptionalShellMode } from '../server/ShellModeContext.js';@@ -10,6 +11,7 @@ import { useSlot } from '../theme/SlotsProvider.js';import { isNewChatView } from '../utils/isNewChatView.js';import { ApprovalFocusProvider } from './approvalFocus.js';import { AssistantMessageContainer } from './AssistantMessageContainer.js';+import { FilePreviewHost } from './FilePreviewHost.js';import { HistoryLoaderContainer } from './HistoryLoaderContainer.js';import { ResumeUnavailableContainer } from './ResumeUnavailableContainer.js';import { UserEditComposerContainer } from './UserEditComposerContainer.js';@@ -65,47 +67,54 @@ export function ThreadContainer({ composer }: ThreadContainerProps) {: undefined;return (- <ComposerBusyProvider>- <ApprovalFocusProvider>- <ThreadPrimitive.Root asChild>- <ThreadRootShell>- <ThreadPrimitive.Viewport asChild autoScroll>- <ThreadViewportShell isEmpty={isEmpty}>- {isEmpty && <WelcomeScreen heading={welcomeHeading} />}- {isEmpty && !isLoading && composer}- {isLoading ? (- <MessageListSkeleton />- ) : (- !isEmpty && (- <>- <HistoryLoaderContainer />- <MessageGroup>- <ThreadPrimitive.Messages>- {({ message }) => (- <AnimatedMessageShell>- <ThreadMessage isEditing={message.role === 'user' && message.composer.isEditing} />- </AnimatedMessageShell>- )}- </ThreadPrimitive.Messages>- <ResumeUnavailableContainer />- </MessageGroup>- </>- )- )}- </ThreadViewportShell>- </ThreadPrimitive.Viewport>+ <FilePreviewBoundary>+ <ComposerBusyProvider>+ <ApprovalFocusProvider>+ <ThreadPrimitive.Root asChild>+ <ThreadRootShell>+ <div data-slot="aui_file-preview-row" className="relative flex min-h-0 w-full min-w-0 flex-1">+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">+ <ThreadPrimitive.Viewport asChild autoScroll>+ <ThreadViewportShell isEmpty={isEmpty}>+ {isEmpty && <WelcomeScreen heading={welcomeHeading} />}+ {isEmpty && !isLoading && composer}+ {isLoading ? (+ <MessageListSkeleton />+ ) : (+ !isEmpty && (+ <>+ <HistoryLoaderContainer />+ <MessageGroup>+ <ThreadPrimitive.Messages>+ {({ message }) => (+ <AnimatedMessageShell>+ <ThreadMessage isEditing={message.role === 'user' && message.composer.isEditing} />+ </AnimatedMessageShell>+ )}+ </ThreadPrimitive.Messages>+ <ResumeUnavailableContainer />+ </MessageGroup>+ </>+ )+ )}+ </ThreadViewportShell>+ </ThreadPrimitive.Viewport>- {!isLoading && !isEmpty && (- <ThreadComposerAreaShell isEmpty={isEmpty}>- <ThreadPrimitive.ScrollToBottom asChild>- <ScrollToBottomButton />- </ThreadPrimitive.ScrollToBottom>- {composer}- </ThreadComposerAreaShell>- )}- </ThreadRootShell>- </ThreadPrimitive.Root>- </ApprovalFocusProvider>- </ComposerBusyProvider>+ {!isLoading && !isEmpty && (+ <ThreadComposerAreaShell isEmpty={isEmpty}>+ <ThreadPrimitive.ScrollToBottom asChild>+ <ScrollToBottomButton />+ </ThreadPrimitive.ScrollToBottom>+ {composer}+ </ThreadComposerAreaShell>+ )}+ </div>+ <FilePreviewHost />+ </div>+ </ThreadRootShell>+ </ThreadPrimitive.Root>+ </ApprovalFocusProvider>+ </ComposerBusyProvider>+ </FilePreviewBoundary>);}diff --git a/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsx b/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsxnew file mode 100644index 000000000..61d456e4f--- /dev/null+++ b/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsx@@ -0,0 +1,109 @@+'use client';++import { useAuiState } from '@assistant-ui/react';+import { createContext, useCallback, useContext, useMemo, useRef, useState, type ReactNode } from 'react';++import { isNewChatView } from '../utils/isNewChatView.js';++export type SandboxFilePreviewTarget = {+ name: string;+ path: string;+ turnId: string;+ load: () => Promise<Blob>;+};++export type FilePreviewPresentation = 'panel' | 'full';++type FilePreviewContextValue = {+ target: SandboxFilePreviewTarget | null;+ presentation: FilePreviewPresentation;+ open: (target: SandboxFilePreviewTarget) => void;+ close: () => void;+ setPresentation: (presentation: FilePreviewPresentation) => void;+};++const FilePreviewContext = createContext<FilePreviewContextValue | null>(null);+const FilePreviewTurnContext = createContext<string | undefined>(undefined);+const FilePreviewLoaderContext = createContext<((path: string) => Promise<Blob>) | null>(null);++export function FilePreviewProvider({ children }: { children: ReactNode }) {+ const [target, setTarget] = useState<SandboxFilePreviewTarget | null>(null);+ const [presentation, setPresentation] = useState<FilePreviewPresentation>('panel');+ const threadId = useAuiState(state => state.threadListItem.id);+ const isNewChat = useAuiState(isNewChatView);+ const targetKey = target == null ? null : `${target.turnId}:${target.path}`;+ const previousTargetKey = useRef(targetKey);+ if (previousTargetKey.current !== targetKey) {+ previousTargetKey.current = targetKey;+ if (presentation !== 'panel') setPresentation('panel');+ }++ // Local id changes for unsaved threads too. remoteId stays null until the session is stored.+ const previousThreadId = useRef(threadId);+ if (previousThreadId.current !== threadId) {+ previousThreadId.current = threadId;+ setTarget(null);+ }++ const previousIsNewChat = useRef(isNewChat);+ if (previousIsNewChat.current !== isNewChat) {+ previousIsNewChat.current = isNewChat;+ if (isNewChat) setTarget(null);+ }++ const open = useCallback((next: SandboxFilePreviewTarget) => {+ setTarget(next);+ }, []);+ const close = useCallback(() => {+ setTarget(null);+ }, []);+ const value = useMemo(+ () => ({ target, presentation, open, close, setPresentation }),+ [target, presentation, open, close, setPresentation],+ );++ return <FilePreviewContext.Provider value={value}>{children}</FilePreviewContext.Provider>;+}++export function useFilePreview(): FilePreviewContextValue {+ const value = useContext(FilePreviewContext);+ if (value == null) {+ throw new Error('File preview is only available inside FilePreviewProvider.');+ }+ return value;+}++export function useOptionalFilePreview(): FilePreviewContextValue | null {+ return useContext(FilePreviewContext);+}++/** Uses the layout provider when the sidebar already owns preview state. */+export function FilePreviewBoundary({ children }: { children: ReactNode }) {+ const existing = useOptionalFilePreview();+ if (existing != null) return children;+ return <FilePreviewProvider>{children}</FilePreviewProvider>;+}++/** Binds artifact chips in one assistant message to the turn that wrote them. */+export function FilePreviewTurnScope({ turnId, children }: { turnId: string | undefined; children: ReactNode }) {+ return <FilePreviewTurnContext.Provider value={turnId}>{children}</FilePreviewTurnContext.Provider>;+}++export function useFilePreviewTurnId(): string | undefined {+ return useContext(FilePreviewTurnContext);+}++/** Turn-scoped sandbox read for artifact chips. Not a markdown prop, so opening a preview does not remount the message. */+export function FilePreviewLoaderScope({+ load,+ children,+}: {+ load: (path: string) => Promise<Blob>;+ children: ReactNode;+}) {+ return <FilePreviewLoaderContext.Provider value={load}>{children}</FilePreviewLoaderContext.Provider>;+}++export function useFilePreviewLoader(): ((path: string) => Promise<Blob>) | null {+ return useContext(FilePreviewLoaderContext);+}diff --git a/packages/trueforge-ui/src/filePreview/previewPaneWidth.ts b/packages/trueforge-ui/src/filePreview/previewPaneWidth.tsnew file mode 100644index 000000000..10f74ea5c--- /dev/null+++ b/packages/trueforge-ui/src/filePreview/previewPaneWidth.ts@@ -0,0 +1,15 @@+/** CSS pixels. Drag math uses the row's measured width. */+const MIN_PREVIEW_PX = 18 * 16;+const MAX_PREVIEW_RATIO = 0.75;+const DEFAULT_PREVIEW_RATIO = 0.42;++export function clampPreviewWidth({ requested, rowWidth }: { requested: number; rowWidth: number }): number {+ if (rowWidth <= 0) return requested;+ const min = Math.min(MIN_PREVIEW_PX, rowWidth * 0.3);+ const max = Math.max(min, rowWidth * MAX_PREVIEW_RATIO);+ return Math.min(max, Math.max(min, requested));+}++export function defaultPreviewWidth(rowWidth: number): number {+ return clampPreviewWidth({ requested: rowWidth * DEFAULT_PREVIEW_RATIO, rowWidth });+}diff --git a/packages/trueforge-ui/src/filePreview/readFilePreview.ts b/packages/trueforge-ui/src/filePreview/readFilePreview.tsnew file mode 100644index 000000000..fb8f497b1--- /dev/null+++ b/packages/trueforge-ui/src/filePreview/readFilePreview.ts@@ -0,0 +1,169 @@+/** Cap preview reads so a huge sandbox file cannot freeze the chat. */+export const FILE_PREVIEW_BYTE_LIMIT = 2 * 1024 * 1024;++/** Prism is skipped above this so a long source file still paints as plain text. */+export const FILE_PREVIEW_HIGHLIGHT_CHAR_LIMIT = 100_000;++const IMAGE_MIME_BY_EXT: Record<string, string> = {+ png: 'image/png',+ jpg: 'image/jpeg',+ jpeg: 'image/jpeg',+ gif: 'image/gif',+ webp: 'image/webp',+ svg: 'image/svg+xml',+ bmp: 'image/bmp',+ avif: 'image/avif',+ ico: 'image/x-icon',+};++const LANGUAGE_BY_EXT: Record<string, string> = {+ js: 'javascript',+ jsx: 'jsx',+ mjs: 'javascript',+ cjs: 'javascript',+ ts: 'typescript',+ tsx: 'tsx',+ py: 'python',+ rb: 'ruby',+ go: 'go',+ rs: 'rust',+ java: 'java',+ kt: 'kotlin',+ swift: 'swift',+ c: 'c',+ h: 'c',+ cpp: 'cpp',+ cc: 'cpp',+ hpp: 'cpp',+ cs: 'csharp',+ php: 'php',+ json: 'json',+ css: 'css',+ scss: 'scss',+ xml: 'markup',+ yml: 'yaml',+ yaml: 'yaml',+ sh: 'bash',+ bash: 'bash',+ zsh: 'bash',+ sql: 'sql',+ graphql: 'graphql',+ toml: 'toml',+};++const HTML_EXT = new Set(['html', 'htm']);+const MARKDOWN_EXT = new Set(['md', 'markdown']);++export type ReadFilePreviewResult =+ | { status: 'text'; text: string; language?: string }+ | { status: 'markdown'; text: string }+ | { status: 'html'; text: string }+ | { status: 'media'; media: 'image' | 'pdf'; mimeType: string }+ | { status: 'unavailable'; message: string };++const EMPTY_FILE_MESSAGE = 'This file is empty.';+const TOO_LARGE_MESSAGE = 'This file is too large to preview. Download it to open it locally.';+const BINARY_MESSAGE = "This file can't be previewed here. Download it to open it locally.";++export function fileExtension(name: string): string {+ const base = name.split('/').pop() ?? name;+ const dot = base.lastIndexOf('.');+ if (dot <= 0 || dot === base.length - 1) return '';+ return base.slice(dot + 1).toLowerCase();+}++function looksBinary(text: string): boolean {+ const sample = text.length > 8000 ? text.slice(0, 8000) : text;+ return sample.includes('\0');+}++function readBlobText(blob: Blob): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => {+ resolve(typeof reader.result === 'string' ? reader.result : '');+ };+ reader.onerror = () => {+ reject(reader.error ?? new Error('Failed to read file'));+ };+ reader.readAsText(blob);+ });+}++export function languageForFileName(name: string): string | undefined {+ return LANGUAGE_BY_EXT[fileExtension(name)];+}++/**+ * Artifact chips use a human label (`Sample HTML`) and a real sandbox path+ * (`/tmp/sample.html`). The path owns the type; the label is only a fallback.+ */+export function previewExtension({ name, path }: { name: string; path: string }): string {+ return fileExtension(path) || fileExtension(name);+}++/** Files that can paint a thumbnail in the message. Source and markdown stay as chips. */+export function inlinePreviewKind(source: { name: string; path: string }): 'html' | 'image' | 'pdf' | null {+ const extension = previewExtension(source);+ if (HTML_EXT.has(extension)) return 'html';+ if (extension === 'pdf') return 'pdf';+ if (IMAGE_MIME_BY_EXT[extension] != null) return 'image';+ return null;+}++function looksLikeHtmlDocument(text: string): boolean {+ const start = text.trimStart().slice(0, 300).toLowerCase();+ return start.startsWith('<!doctype html') || start.startsWith('<html');+}++function looksLikeMarkdown(text: string): boolean {+ return /^#{1,6}\s/m.test(text.trimStart().slice(0, 500));+}++export function blobWithMimeType(blob: Blob, mimeType: string): Blob {+ if (blob.type === mimeType) return blob;+ return new Blob([blob], { type: mimeType });+}++/**+ * Classifies a sandbox file for in-chat preview. Images and PDFs stay binary;+ * everything else is treated as text unless the bytes look binary.+ */+export async function readFilePreview(+ blob: Blob,+ source: { name: string; path: string },+): Promise<ReadFilePreviewResult> {+ if (blob.size === 0) {+ return { status: 'unavailable', message: EMPTY_FILE_MESSAGE };+ }+ if (blob.size > FILE_PREVIEW_BYTE_LIMIT) {+ return { status: 'unavailable', message: TOO_LARGE_MESSAGE };+ }++ const extension = previewExtension(source);+ const imageMime = IMAGE_MIME_BY_EXT[extension];+ if (imageMime != null) {+ return { status: 'media', media: 'image', mimeType: imageMime };+ }+ if (extension === 'pdf') {+ return { status: 'media', media: 'pdf', mimeType: 'application/pdf' };+ }++ const text = await readBlobText(blob);+ if (looksBinary(text)) {+ return { status: 'unavailable', message: BINARY_MESSAGE };+ }+ if (text.trim().length === 0) {+ return { status: 'unavailable', message: EMPTY_FILE_MESSAGE };+ }+ if (HTML_EXT.has(extension) || (extension.length === 0 && looksLikeHtmlDocument(text))) {+ return { status: 'html', text };+ }+ if (MARKDOWN_EXT.has(extension) || (extension.length === 0 && looksLikeMarkdown(text))) {+ return { status: 'markdown', text };+ }++ const language = LANGUAGE_BY_EXT[extension];+ if (language == null) return { status: 'text', text };+ return { status: 'text', text, language };+}diff --git a/packages/trueforge-ui/src/filePreview/useLoadedFilePreview.ts b/packages/trueforge-ui/src/filePreview/useLoadedFilePreview.tsnew file mode 100644index 000000000..3f54a2a44--- /dev/null+++ b/packages/trueforge-ui/src/filePreview/useLoadedFilePreview.ts@@ -0,0 +1,81 @@+'use client';++import { useEffect, useState } from 'react';++import type { FilePreviewView } from '../atoms/FilePreviewPanel.js';+import type { SandboxFilePreviewTarget } from './FilePreviewContext.js';+import { blobWithMimeType, readFilePreview } from './readFilePreview.js';++export type LoadedFilePreview = {+ view: FilePreviewView;+ /** Bytes already fetched for this target, reused by the panel download control. */+ blob: Blob | null;+};++const LOAD_ERROR_MESSAGE = "Couldn't load a preview of this file.";+const EMPTY_LOADED: LoadedFilePreview = { view: { status: 'loading' }, blob: null };++function loadedKey(target: SandboxFilePreviewTarget | null, reloadToken: number): string | null {+ if (target == null) return null;+ return `${target.turnId}\0${target.path}\0${reloadToken}`;+}++/**+ * Loads the open sandbox file once per target. The object URL created for images+ * and PDFs is revoked when that request is dropped.+ *+ * The host stays mounted across close and open, so a result for a different file+ * is dropped during render. Otherwise the new title can paint the previous bytes,+ * and download can save them under the new path.+ */+export function useLoadedFilePreview(target: SandboxFilePreviewTarget | null, reloadToken: number): LoadedFilePreview {+ const key = loadedKey(target, reloadToken);+ const [loaded, setLoaded] = useState<LoadedFilePreview & { key: string | null }>({+ key: null,+ ...EMPTY_LOADED,+ });+ if (loaded.key !== key) {+ setLoaded({ key, ...EMPTY_LOADED });+ }++ useEffect(() => {+ if (target == null || key == null) return;+ let cancelled = false;+ let objectUrl: string | undefined;+ setLoaded({ key, ...EMPTY_LOADED });++ void (async () => {+ try {+ const blob = await target.load();+ if (cancelled) return;+ const result = await readFilePreview(blob, { name: target.name, path: target.path });+ if (cancelled) return;+ if (result.status === 'media') {+ objectUrl = URL.createObjectURL(blobWithMimeType(blob, result.mimeType));+ if (cancelled) {+ URL.revokeObjectURL(objectUrl);+ return;+ }+ setLoaded({+ key,+ blob,+ view: { status: 'media', media: result.media, objectUrl },+ });+ return;+ }+ setLoaded({ key, blob, view: result });+ } catch {+ if (!cancelled) {+ setLoaded({ key, blob: null, view: { status: 'error', message: LOAD_ERROR_MESSAGE } });+ }+ }+ })();++ return () => {+ cancelled = true;+ if (objectUrl != null) URL.revokeObjectURL(objectUrl);+ };+ }, [target, reloadToken, key]);++ return loaded.key === key ? loaded : EMPTY_LOADED;+}diff --git a/packages/trueforge-ui/src/index.ts b/packages/trueforge-ui/src/index.tsindex b83f7f12f..8c5a9f22f 100644--- a/packages/trueforge-ui/src/index.ts+++ b/packages/trueforge-ui/src/index.ts@@ -94,6 +94,8 @@ export { ChatFileDownload } from './atoms/ChatFileDownload.js';export type { ChatFileDownloadFile, ChatFileDownloadProps } from './atoms/ChatFileDownload.js';export { CodeEditor } from './atoms/CodeEditor.js';export type { CodeEditorProps } from './atoms/CodeEditor.js';+export { FilePreviewPanel } from './atoms/FilePreviewPanel.js';+export type { FilePreviewPanelProps, FilePreviewView } from './atoms/FilePreviewPanel.js';export { HistoryLoader } from './atoms/HistoryLoader.js';export type { HistoryLoaderProps } from './atoms/HistoryLoader.js';export { Markdown, preloadMarkdownOpenUI } from './atoms/Markdown.js';diff --git a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx b/packages/trueforge-ui/src/layouts/SidebarLayout.tsxindex a53f1be93..e04a34872 100644--- a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx+++ b/packages/trueforge-ui/src/layouts/SidebarLayout.tsx@@ -22,6 +22,7 @@ import { ShellActions } from '../atoms/ShellActions.js';import { AgentConfigDrawerContainer } from '../containers/AgentConfigDrawerContainer.js';import { Thread } from '../containers/Thread.js';import { ThreadListContainer } from '../containers/ThreadListContainer.js';+import { FilePreviewProvider, useFilePreview } from '../filePreview/FilePreviewContext.js';import { useChatHeaderContentVisible } from '../hooks/useChatChromeActionsVisible.js';import { Icon } from '../icons/Icon.js';import { shellIsCreateAgent, useOptionalShellMode, type ShellMode } from '../server/ShellModeContext.js';@@ -46,6 +47,19 @@ function isRecentHistoryVisible({ overlayOpen, mode }: { overlayOpen: boolean; mreturn !overlayOpen && mode?.status === 'active' && !mode.isCreateAgent;}+function RecentChatsAside() {+ const preview = useFilePreview();+ if (preview.presentation === 'full') return null;+ return (+ <aside+ aria-label="Recent chats"+ className="hidden min-h-0 w-64 shrink-0 border-r border-border bg-sidebar-bg md:flex"+ >+ <ThreadListContainer variant="recent-history" />+ </aside>+ );+}+function SidebarNav(): ReactNode {const aui = useAui();const shell = useOptionalShellMode();@@ -273,62 +287,57 @@ export function SidebarLayout({ className }: { className?: string }) {}/>- <div className="flex min-h-0 min-w-0 flex-1">- {showRecentHistory ? (- <aside- aria-label="Recent chats"- className="hidden min-h-0 w-64 shrink-0 border-r border-border bg-sidebar-bg md:flex"- >- <ThreadListContainer variant="recent-history" />- </aside>- ) : null}+ <FilePreviewProvider>+ <div className="flex min-h-0 min-w-0 flex-1">+ {showRecentHistory ? <RecentChatsAside /> : null}- <div ref={mainRef} className="min-h-0 min-w-0 flex-1">- {settingsOpen ? (- <Suspense- fallback={- <div- className="flex h-full items-center justify-center"- role="status"- aria-live="polite"- aria-busy="true"- >- <Spinner size={28} className="text-text-primary" />- <span className="sr-only">Loading</span>- </div>- }- >- <TruefoundrySettingsBuilder />- </Suspense>- ) : sessionsOpen ? (- <SessionsPage />- ) : libraryOpen && shell?.libraryAgentId != null ? (- <AgentDetailsPage key={shell.libraryAgentId} agentId={shell.libraryAgentId} />- ) : libraryOpen ? (- <AgentsLibrary onSelectAgent={() => setMobileNavOpen(false)} />- ) : schedulesOpen ? (- <Suspense- fallback={- <div- className="flex h-full items-center justify-center"- role="status"- aria-live="polite"- aria-busy="true"- >- <Spinner size={28} className="text-text-primary" />- <span className="sr-only">Loading</span>- </div>- }- >- <SchedulesPage />- </Suspense>- ) : isIdle ? (- <SelectAgentEmptyState />- ) : (- <Thread />- )}+ <div ref={mainRef} className="min-h-0 min-w-0 flex-1">+ {settingsOpen ? (+ <Suspense+ fallback={+ <div+ className="flex h-full items-center justify-center"+ role="status"+ aria-live="polite"+ aria-busy="true"+ >+ <Spinner size={28} className="text-text-primary" />+ <span className="sr-only">Loading</span>+ </div>+ }+ >+ <TruefoundrySettingsBuilder />+ </Suspense>+ ) : sessionsOpen ? (+ <SessionsPage />+ ) : libraryOpen && shell?.libraryAgentId != null ? (+ <AgentDetailsPage key={shell.libraryAgentId} agentId={shell.libraryAgentId} />+ ) : libraryOpen ? (+ <AgentsLibrary onSelectAgent={() => setMobileNavOpen(false)} />+ ) : schedulesOpen ? (+ <Suspense+ fallback={+ <div+ className="flex h-full items-center justify-center"+ role="status"+ aria-live="polite"+ aria-busy="true"+ >+ <Spinner size={28} className="text-text-primary" />+ <span className="sr-only">Loading</span>+ </div>+ }+ >+ <SchedulesPage />+ </Suspense>+ ) : isIdle ? (+ <SelectAgentEmptyState />+ ) : (+ <Thread />+ )}+ </div></div>- </div>+ </FilePreviewProvider></div>{/* Mobile: same narrow rail as desktop */}diff --git a/packages/trueforge-ui/src/theme/defaultSlots.ts b/packages/trueforge-ui/src/theme/defaultSlots.tsindex 2f85523ca..603a13101 100644--- a/packages/trueforge-ui/src/theme/defaultSlots.ts+++ b/packages/trueforge-ui/src/theme/defaultSlots.ts@@ -62,6 +62,7 @@ import { DraftComposerActionsMenu } from '../atoms/draft/DraftComposerActionsMenimport { DraftComposerLeftSection, DraftComposerRightSection } from '../atoms/draft/DraftComposerSections.js';import { CatalogRow, ConnectorConnectButton, DraftCompositeSelector } from '../atoms/draft/DraftCompositeSelector.js';import { DraftModelSelector } from '../atoms/draft/DraftModelSelector.js';+import { FilePreviewPanel } from '../atoms/FilePreviewPanel.js';import { HistoryLoader } from '../atoms/HistoryLoader.js';import { Markdown } from '../atoms/Markdown.js';import { MessageActionBar } from '../atoms/MessageActionBar.js';@@ -190,6 +191,7 @@ export const defaultSlots = {OpenUiFenceBlock,SandboxArtifactDownload,ChatFileDownload,+ FilePreviewPanel,MonacoEditorCore,CodeEditor,WelcomeScreen,diff --git a/packages/trueforge-ui/src/utils/triggerBrowserDownload.ts b/packages/trueforge-ui/src/utils/triggerBrowserDownload.tsnew file mode 100644index 000000000..0b24d7347--- /dev/null+++ b/packages/trueforge-ui/src/utils/triggerBrowserDownload.ts@@ -0,0 +1,15 @@+/** Last path segment, so a human chip label cannot drop the file extension. */+export function filenameFromPath(path: string): string {+ const base = path.split('/').pop() ?? '';+ return base.length > 0 ? base : 'download';+}++export function triggerBrowserDownload(blob: Blob, filename: string): void {+ if (typeof document === 'undefined') return;+ const url = URL.createObjectURL(blob);+ const anchor = document.createElement('a');+ anchor.href = url;+ anchor.download = filename;+ anchor.click();+ URL.revokeObjectURL(url);+}diff --git a/packages/trueforge-ui/test/atoms/FilePreviewPanel.test.tsx b/packages/trueforge-ui/test/atoms/FilePreviewPanel.test.tsxnew file mode 100644index 000000000..200ba0ed0--- /dev/null+++ b/packages/trueforge-ui/test/atoms/FilePreviewPanel.test.tsx@@ -0,0 +1,161 @@+// @vitest-environment jsdom+import { fireEvent, render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { FilePreviewPanel } from '@/atoms/FilePreviewPanel.js';++describe('FilePreviewPanel', () => {+ it('renders html in a sandboxed frame and closes from the header', () => {+ const onClose = vi.fn();+ render(+ <FilePreviewPanel+ name="dashboard.html"+ placement="side"+ view={{ status: 'html', text: '<h1>Dashboard</h1>' }}+ onClose={onClose}+ onDownload={vi.fn()}+ />,+ );++ const frame = screen.getByTitle('dashboard.html');+ expect(frame.tagName).toBe('IFRAME');+ expect(frame).toHaveAttribute('sandbox', 'allow-scripts allow-forms');+ expect(frame.getAttribute('sandbox')).not.toContain('allow-popups');+ expect(frame.getAttribute('sandbox')).not.toContain('allow-same-origin');+ expect(frame).toHaveAttribute('srcdoc', '<h1>Dashboard</h1>');++ fireEvent.click(screen.getByRole('button', { name: 'Close preview' }));+ expect(onClose).toHaveBeenCalledOnce();+ });++ it('shows an image from the object url and downloads from the header', () => {+ const onDownload = vi.fn();+ render(+ <FilePreviewPanel+ name="chart.png"+ placement="overlay"+ view={{ status: 'media', media: 'image', objectUrl: 'blob:chart' }}+ onClose={vi.fn()}+ onDownload={onDownload}+ />,+ );++ expect(screen.getByRole('img', { name: 'chart.png' })).toHaveAttribute('src', 'blob:chart');+ expect(screen.getByRole('complementary', { name: 'Preview of chart.png' })).toHaveAttribute(+ 'data-placement',+ 'overlay',+ );+ expect(screen.queryByRole('separator', { name: 'Resize preview' })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Download chart.png' }));+ expect(onDownload).toHaveBeenCalledOnce();+ });++ it('offers retry when the file failed to load and closes on Escape', () => {+ const onClose = vi.fn();+ const onRetry = vi.fn();+ render(+ <FilePreviewPanel+ name="report.txt"+ placement="side"+ view={{ status: 'error', message: "Couldn't load a preview of this file." }}+ onClose={onClose}+ onDownload={vi.fn()}+ onRetry={onRetry}+ />,+ );++ expect(screen.getByText("Couldn't load a preview of this file.")).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Retry' }));+ expect(onRetry).toHaveBeenCalledOnce();+ fireEvent.keyDown(screen.getByRole('complementary', { name: 'Preview of report.txt' }), { key: 'Escape' });+ expect(onClose).toHaveBeenCalledOnce();+ });++ it('widens the side pane from the resize handle', () => {+ const onWidthChange = vi.fn();+ render(+ <div>+ <FilePreviewPanel+ name="report.txt"+ placement="side"+ widthPx={420}+ view={{ status: 'text', text: 'hello' }}+ onClose={vi.fn()}+ onDownload={vi.fn()}+ onWidthChange={onWidthChange}+ />+ </div>,+ );++ const aside = screen.getByRole('complementary', { name: 'Preview of report.txt' });+ const row = aside.parentElement;+ if (row == null) throw new Error('Expected the preview row');+ vi.spyOn(aside, 'getBoundingClientRect').mockReturnValue(rect(420));+ vi.spyOn(row, 'getBoundingClientRect').mockReturnValue(rect(1000));++ fireEvent.keyDown(screen.getByRole('separator', { name: 'Resize preview' }), { key: 'ArrowLeft' });+ expect(onWidthChange).toHaveBeenCalledWith(436);+ });++ it('fills the chat pane from the full-page control and returns on Escape', () => {+ const onEnterFullPage = vi.fn();+ const onExitFullPage = vi.fn();+ const onClose = vi.fn();+ const { rerender } = render(+ <FilePreviewPanel+ name="dashboard.html"+ placement="side"+ view={{ status: 'html', text: '<h1>Dashboard</h1>' }}+ onClose={onClose}+ onDownload={vi.fn()}+ onEnterFullPage={onEnterFullPage}+ onExitFullPage={onExitFullPage}+ />,+ );++ fireEvent.click(screen.getByRole('button', { name: 'Full page' }));+ expect(onEnterFullPage).toHaveBeenCalledOnce();++ rerender(+ <FilePreviewPanel+ name="dashboard.html"+ placement="full"+ view={{ status: 'html', text: '<h1>Dashboard</h1>' }}+ onClose={onClose}+ onDownload={vi.fn()}+ onEnterFullPage={onEnterFullPage}+ onExitFullPage={onExitFullPage}+ />,+ );++ const panel = screen.getByRole('complementary', { name: 'Preview of dashboard.html' });+ expect(panel).toHaveAttribute('data-placement', 'full');+ expect(panel.parentElement).not.toBe(document.body);+ expect(panel).toHaveClass('absolute', 'inset-0');+ expect(panel).not.toHaveClass('fixed');+ expect(screen.queryByRole('separator', { name: 'Resize preview' })).not.toBeInTheDocument();++ fireEvent.keyDown(panel, { key: 'Escape' });+ expect(onExitFullPage).toHaveBeenCalledOnce();+ expect(onClose).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: 'Exit full page' }));+ expect(onExitFullPage).toHaveBeenCalledTimes(2);+ });+});++function rect(width: number): DOMRect {+ return {+ x: 0,+ y: 0,+ top: 0,+ left: 0,+ right: width,+ bottom: 0,+ width,+ height: 0,+ toJSON() {+ return {};+ },+ };+}diff --git a/packages/trueforge-ui/test/atoms/InlineFilePreviewCard.test.tsx b/packages/trueforge-ui/test/atoms/InlineFilePreviewCard.test.tsxnew file mode 100644index 000000000..7a131f3eb--- /dev/null+++ b/packages/trueforge-ui/test/atoms/InlineFilePreviewCard.test.tsx@@ -0,0 +1,31 @@+// @vitest-environment jsdom+import { fireEvent, render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { InlineFilePreviewCard } from '@/atoms/InlineFilePreviewCard.js';++describe('InlineFilePreviewCard', () => {+ it('shows a scaled html thumbnail and enlarges from the card or the button', () => {+ const onEnlarge = vi.fn();+ render(+ <InlineFilePreviewCard+ name="Metrics redesign"+ enlarged={false}+ view={{ status: 'html', text: '<h1>Metrics</h1>' }}+ onEnlarge={onEnlarge}+ onDownload={vi.fn()}+ />,+ );++ const thumbnail = screen.getByTitle('Thumbnail of Metrics redesign');+ expect(thumbnail).toHaveAttribute('sandbox', 'allow-scripts');+ expect(thumbnail.getAttribute('sandbox')).not.toContain('allow-popups');+ expect(thumbnail.getAttribute('sandbox')).not.toContain('allow-forms');+ expect(thumbnail).toHaveAttribute('srcdoc', '<h1>Metrics</h1>');+ expect(screen.getByText('Metrics redesign')).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Enlarge preview of Metrics redesign' }));+ fireEvent.click(screen.getByRole('button', { name: 'Enlarge Metrics redesign' }));+ expect(onEnlarge).toHaveBeenCalledTimes(2);+ });+});diff --git a/packages/trueforge-ui/test/containers/FilePreviewHost.test.tsx b/packages/trueforge-ui/test/containers/FilePreviewHost.test.tsxnew file mode 100644index 000000000..5b275bcd0--- /dev/null+++ b/packages/trueforge-ui/test/containers/FilePreviewHost.test.tsx@@ -0,0 +1,151 @@+// @vitest-environment jsdom+import { AssistantRuntimeProvider, useExternalStoreRuntime, type ThreadMessageLike } from '@assistant-ui/react';+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { trueForgeExtras } from '@truefoundry/trueforge-assistant-ui-runtime';+import { describe, expect, it, vi } from 'vitest';++import { ThreadContainer } from '@/containers/ThreadContainer.js';++const artifactMessage = {+ role: 'assistant',+ content: ['Files ready:', '', '```sandbox_artifacts', '[report.txt](/tmp/report.txt)', '```'].join('\n'),+ metadata: { custom: { turnId: 'turn-42', sandboxId: 'sbx-1' } },+} satisfies ThreadMessageLike;++function PreviewHarness({+ downloadSandboxFile,+ message = artifactMessage,+}: {+ downloadSandboxFile: (req: { turnId: string; path: string }) => Promise<Blob>;+ message?: ThreadMessageLike;+}) {+ const runtime = useExternalStoreRuntime({+ messages: [message],+ isRunning: false,+ convertMessage: (message: ThreadMessageLike) => message,+ onNew: async () => {},+ extras: trueForgeExtras.provide({+ pendingApprovals: [],+ pendingToolResponses: [],+ pendingMcpAuth: null,+ resumeUnavailable: false,+ sandboxId: 'sbx-1',+ respondToToolApproval: () => {},+ respondToToolResponse: () => {},+ resumeMcpAuth: async () => {},+ downloadSandboxFile,+ cancel: async () => {},+ resetFromTurn: async () => {},+ reload: () => {},+ hasOlderHistory: false,+ isLoadingOlderHistory: false,+ loadOlderHistory: async () => {},+ draft: null,+ }),+ });++ return (+ <AssistantRuntimeProvider runtime={runtime}>+ <ThreadContainer />+ </AssistantRuntimeProvider>+ );+}++describe('sandbox file preview', () => {+ it('opens a generated file beside the chat and still downloads it', async () => {+ const downloadSandboxFile = vi.fn(async () => new Blob(['hello harness']));+ const anchorClick = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => {});+ if (typeof Element.prototype.scrollTo !== 'function') {+ Element.prototype.scrollTo = () => undefined;+ }++ try {+ render(<PreviewHarness downloadSandboxFile={downloadSandboxFile} />);++ fireEvent.click(await screen.findByRole('button', { name: 'Preview report.txt' }));++ const panel = await screen.findByRole('complementary', { name: 'Preview of report.txt' });+ await waitFor(() => {+ expect(panel).toHaveTextContent('hello harness');+ });+ expect(downloadSandboxFile).toHaveBeenCalledTimes(1);+ expect(downloadSandboxFile).toHaveBeenCalledWith({ turnId: 'turn-42', path: '/tmp/report.txt' });+ expect(anchorClick).not.toHaveBeenCalled();+ expect(screen.getByRole('button', { name: 'Preview report.txt' })).toHaveAttribute('aria-pressed', 'true');++ fireEvent.click(within(panel).getByRole('button', { name: 'Download report.txt' }));+ await waitFor(() => {+ expect(anchorClick).toHaveBeenCalledTimes(1);+ });+ expect(downloadSandboxFile).toHaveBeenCalledTimes(1);++ fireEvent.click(+ within(screen.getByTestId('aui-sandbox-artifacts')).getByRole('button', { name: 'Download report.txt' }),+ );+ await waitFor(() => {+ expect(downloadSandboxFile).toHaveBeenCalledTimes(2);+ });+ expect(anchorClick).toHaveBeenCalledTimes(2);++ fireEvent.click(within(panel).getByRole('button', { name: 'Close preview' }));+ expect(screen.queryByRole('complementary', { name: 'Preview of report.txt' })).not.toBeInTheDocument();+ } finally {+ anchorClick.mockRestore();+ }+ });++ it('previews an html file in the chat, then enlarged and full page', async () => {+ const html = '<!doctype html><h1>Metrics</h1>';+ const downloadSandboxFile = vi.fn(async () => new Blob([html]));+ let downloadedName = '';+ const anchorClick = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function mockClick(+ this: HTMLAnchorElement,+ ) {+ downloadedName = this.download;+ });+ if (typeof Element.prototype.scrollTo !== 'function') {+ Element.prototype.scrollTo = () => undefined;+ }++ render(+ <PreviewHarness+ downloadSandboxFile={downloadSandboxFile}+ message={{+ role: 'assistant',+ content: ['Done', '', '```sandbox_artifacts', '[Metrics redesign](/tmp/metrics.html)', '```'].join('\n'),+ metadata: { custom: { turnId: 'turn-42', sandboxId: 'sbx-1' } },+ }}+ />,+ );++ const thumbnail = await screen.findByTitle('Thumbnail of Metrics redesign');+ await waitFor(() => {+ expect(thumbnail).toHaveAttribute('srcdoc', html);+ });+ expect(screen.queryByText('1 file generated')).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Enlarge Metrics redesign' }));+ const panel = await screen.findByRole('complementary', { name: 'Preview of Metrics redesign' });+ await waitFor(() => {+ expect(within(panel).getByTitle('Metrics redesign')).toHaveAttribute('srcdoc', html);+ });+ expect(screen.getByRole('button', { name: 'Enlarge Metrics redesign' })).toHaveAttribute('aria-pressed', 'true');++ fireEvent.click(within(panel).getByRole('button', { name: 'Full page' }));+ const fullPage = screen.getByRole('complementary', { name: 'Preview of Metrics redesign' });+ expect(fullPage).toHaveAttribute('data-placement', 'full');+ expect(fullPage.parentElement).toHaveAttribute('data-slot', 'aui_file-preview-row');+ expect(fullPage).not.toHaveClass('fixed');++ fireEvent.click(screen.getByRole('button', { name: 'Exit full page' }));+ const side = screen.getByRole('complementary', { name: 'Preview of Metrics redesign' });+ expect(side).toHaveAttribute('data-placement', 'side');+ expect(side.parentElement).not.toBe(document.body);++ fireEvent.click(within(side).getByRole('button', { name: 'Download Metrics redesign' }));+ await waitFor(() => {+ expect(downloadedName).toBe('metrics.html');+ });+ anchorClick.mockRestore();+ });+});diff --git a/packages/trueforge-ui/test/filePreview/FilePreviewContext.test.tsx b/packages/trueforge-ui/test/filePreview/FilePreviewContext.test.tsxnew file mode 100644index 000000000..a710bf201--- /dev/null+++ b/packages/trueforge-ui/test/filePreview/FilePreviewContext.test.tsx@@ -0,0 +1,78 @@+// @vitest-environment jsdom+import { AssistantRuntimeProvider, useExternalStoreRuntime, type ThreadMessageLike } from '@assistant-ui/react';+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { useState as useReactState } from 'react';+import { describe, expect, it } from 'vitest';++import { FilePreviewProvider, useFilePreview } from '@/filePreview/FilePreviewContext.js';++const message = {+ role: 'assistant',+ content: 'A local thread with no saved session id.',+} satisfies ThreadMessageLike;++function Probe() {+ const preview = useFilePreview();+ return (+ <>+ <button+ type="button"+ onClick={() => {+ preview.open({+ name: 'Dash',+ path: '/tmp/dash.html',+ turnId: 'turn-1',+ load: async () => new Blob(['hi']),+ });+ }}+ >+ Open preview+ </button>+ <span>{preview.target == null ? 'closed' : preview.target.path}</span>+ </>+ );+}++function Harness({ threadId }: { threadId: string }) {+ const runtime = useExternalStoreRuntime({+ messages: [message],+ isRunning: false,+ convertMessage: (next: ThreadMessageLike) => next,+ onNew: async () => {},+ adapters: { threadList: { threadId } },+ });++ return (+ <AssistantRuntimeProvider runtime={runtime}>+ <FilePreviewProvider>+ <Probe />+ </FilePreviewProvider>+ </AssistantRuntimeProvider>+ );+}++function TestApp() {+ const [threadId, setThreadId] = useReactState('unsaved-a');+ return (+ <>+ <button type="button" onClick={() => setThreadId('unsaved-b')}>+ Switch thread+ </button>+ <Harness threadId={threadId} />+ </>+ );+}++describe('FilePreviewProvider', () => {+ it('closes the preview when the local thread changes, even without a remote id', async () => {+ render(<TestApp />);++ fireEvent.click(screen.getByRole('button', { name: 'Open preview' }));+ expect(screen.getByText('/tmp/dash.html')).toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Switch thread' }));+ await waitFor(() => {+ expect(screen.getByText('closed')).toBeInTheDocument();+ });+ });+});diff --git a/packages/trueforge-ui/test/filePreview/previewPaneWidth.test.ts b/packages/trueforge-ui/test/filePreview/previewPaneWidth.test.tsnew file mode 100644index 000000000..d10cb4a99--- /dev/null+++ b/packages/trueforge-ui/test/filePreview/previewPaneWidth.test.ts@@ -0,0 +1,15 @@+import { describe, expect, it } from 'vitest';++import { clampPreviewWidth, defaultPreviewWidth } from '@/filePreview/previewPaneWidth.js';++describe('clampPreviewWidth', () => {+ it('keeps the pane between a minimum and 75% of the row', () => {+ expect(clampPreviewWidth({ requested: 100, rowWidth: 1000 })).toBe(18 * 16);+ expect(clampPreviewWidth({ requested: 900, rowWidth: 1000 })).toBe(750);+ expect(clampPreviewWidth({ requested: 420, rowWidth: 1000 })).toBe(420);+ });++ it('defaults to 42% of the row', () => {+ expect(defaultPreviewWidth(1000)).toBe(420);+ });+});diff --git a/packages/trueforge-ui/test/filePreview/readFilePreview.test.ts b/packages/trueforge-ui/test/filePreview/readFilePreview.test.tsnew file mode 100644index 000000000..db71b31f8--- /dev/null+++ b/packages/trueforge-ui/test/filePreview/readFilePreview.test.ts@@ -0,0 +1,115 @@+import { describe, expect, it } from 'vitest';++import {+ FILE_PREVIEW_BYTE_LIMIT,+ fileExtension,+ inlinePreviewKind,+ languageForFileName,+ readFilePreview,+} from '@/filePreview/readFilePreview.js';++describe('fileExtension', () => {+ it('reads the last extension and ignores a leading dot', () => {+ expect(fileExtension('report.TXT')).toBe('txt');+ expect(fileExtension('/tmp/chart.min.js')).toBe('js');+ expect(fileExtension('.gitignore')).toBe('');+ expect(fileExtension('README')).toBe('');+ });+});++function source(name: string, path = name) {+ return { name, path };+}++describe('readFilePreview', () => {+ it('classifies source, markup, and media from the file name', async () => {+ await expect(readFilePreview(new Blob(['export const n = 1;\n']), source('demo.js'))).resolves.toEqual({+ status: 'text',+ text: 'export const n = 1;\n',+ language: 'javascript',+ });+ await expect(readFilePreview(new Blob(['<h1>Hi</h1>']), source('page.html'))).resolves.toEqual({+ status: 'html',+ text: '<h1>Hi</h1>',+ });+ await expect(readFilePreview(new Blob(['# Notes\n']), source('notes.md'))).resolves.toEqual({+ status: 'markdown',+ text: '# Notes\n',+ });+ await expect(readFilePreview(new Blob(['plain']), source('notes.txt'))).resolves.toEqual({+ status: 'text',+ text: 'plain',+ });+ await expect(readFilePreview(new Blob([new Uint8Array([1, 2, 3])]), source('shot.png'))).resolves.toEqual({+ status: 'media',+ media: 'image',+ mimeType: 'image/png',+ });+ await expect(readFilePreview(new Blob([new Uint8Array([1, 2, 3])]), source('brief.pdf'))).resolves.toEqual({+ status: 'media',+ media: 'pdf',+ mimeType: 'application/pdf',+ });+ });++ it('uses the sandbox path when the chip label has no extension', async () => {+ const html = '<!DOCTYPE html><html><body><h1>Sample</h1></body></html>';+ await expect(readFilePreview(new Blob([html]), source('Sample HTML', '/tmp/sample.html'))).resolves.toEqual({+ status: 'html',+ text: html,+ });+ const markdown = '# Sample Markdown\n\n**Bold** text\n';+ await expect(readFilePreview(new Blob([markdown]), source('Sample Markdown', '/tmp/notes.md'))).resolves.toEqual({+ status: 'markdown',+ text: markdown,+ });+ });++ it('renders an extensionless html document instead of raw source', async () => {+ const html = '<!DOCTYPE html><html><body>Hi</body></html>';+ await expect(readFilePreview(new Blob([html]), source('Sample HTML', '/tmp/Sample HTML'))).resolves.toEqual({+ status: 'html',+ text: html,+ });+ });++ it('renders an extensionless markdown note that starts with a heading', async () => {+ const markdown = '# Sample Markdown Preview\n\n**Bold** text\n';+ await expect(+ readFilePreview(new Blob([markdown]), source('Sample Markdown', '/tmp/Sample Markdown')),+ ).resolves.toEqual({+ status: 'markdown',+ text: markdown,+ });+ });++ it('refuses empty, oversized, and binary files', async () => {+ await expect(readFilePreview(new Blob([]), source('empty.txt'))).resolves.toEqual({+ status: 'unavailable',+ message: 'This file is empty.',+ });+ await expect(+ readFilePreview(new Blob([new Uint8Array(FILE_PREVIEW_BYTE_LIMIT + 1)]), source('big.txt')),+ ).resolves.toEqual({+ status: 'unavailable',+ message: 'This file is too large to preview. Download it to open it locally.',+ });+ await expect(readFilePreview(new Blob([new Uint8Array([0, 1, 2])]), source('data.txt'))).resolves.toEqual({+ status: 'unavailable',+ message: "This file can't be previewed here. Download it to open it locally.",+ });+ });++ it('maps a known source extension to a highlighter language', () => {+ expect(languageForFileName('main.py')).toBe('python');+ expect(languageForFileName('notes.txt')).toBeUndefined();+ });++ it('picks a chat thumbnail for pages and images, and a chip for source', () => {+ expect(inlinePreviewKind(source('Metrics', '/tmp/metrics.html'))).toBe('html');+ expect(inlinePreviewKind(source('chart.png'))).toBe('image');+ expect(inlinePreviewKind(source('brief.pdf'))).toBe('pdf');+ expect(inlinePreviewKind(source('main.py'))).toBeNull();+ expect(inlinePreviewKind(source('Sample HTML', '/tmp/Sample HTML'))).toBeNull();+ });+});diff --git a/packages/trueforge-ui/test/filePreview/useLoadedFilePreview.test.tsx b/packages/trueforge-ui/test/filePreview/useLoadedFilePreview.test.tsxnew file mode 100644index 000000000..8282bafba--- /dev/null+++ b/packages/trueforge-ui/test/filePreview/useLoadedFilePreview.test.tsx@@ -0,0 +1,59 @@+// @vitest-environment jsdom+import { act, render, screen, waitFor } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import type { SandboxFilePreviewTarget } from '@/filePreview/FilePreviewContext.js';+import { useLoadedFilePreview } from '@/filePreview/useLoadedFilePreview.js';++function deferredFile({ path, text }: { path: string; text: string }) {+ let resolve: (blob: Blob) => void = () => undefined;+ const pending = new Promise<Blob>(done => {+ resolve = done;+ });+ const target: SandboxFilePreviewTarget = {+ name: 'Label',+ path,+ turnId: 'turn-1',+ load: () => pending,+ };+ return { target, finish: () => resolve(new Blob([text])) };+}++function Probe({ target }: { target: SandboxFilePreviewTarget | null }) {+ const loaded = useLoadedFilePreview(target, 0);+ const text = loaded.view.status === 'text' || loaded.view.status === 'html' ? loaded.view.text : '';+ return (+ <div+ data-testid="preview"+ data-status={loaded.view.status}+ data-blob={loaded.blob == null ? 'none' : 'set'}+ data-text={text}+ />+ );+}++describe('useLoadedFilePreview', () => {+ it('drops the previous file before the next one loads', async () => {+ const first = deferredFile({ path: '/tmp/a.txt', text: 'alpha' });+ const second = deferredFile({ path: '/tmp/b.txt', text: 'beta' });+ const { rerender } = render(<Probe target={first.target} />);++ expect(screen.getByTestId('preview')).toHaveAttribute('data-status', 'loading');+ expect(screen.getByTestId('preview')).toHaveAttribute('data-blob', 'none');++ await act(async () => {+ first.finish();+ });+ await waitFor(() => {+ expect(screen.getByTestId('preview')).toHaveAttribute('data-text', 'alpha');+ });++ rerender(<Probe target={second.target} />);+ expect(screen.getByTestId('preview')).toHaveAttribute('data-status', 'loading');+ expect(screen.getByTestId('preview')).toHaveAttribute('data-blob', 'none');+ expect(screen.getByTestId('preview')).toHaveAttribute('data-text', '');++ rerender(<Probe target={null} />);+ expect(screen.getByTestId('preview')).toHaveAttribute('data-blob', 'none');+ });+});diff --git a/packages/trueforge-ui/test/layouts/SidebarLayout.preview.test.tsx b/packages/trueforge-ui/test/layouts/SidebarLayout.preview.test.tsxnew file mode 100644index 000000000..29e5129ce--- /dev/null+++ b/packages/trueforge-ui/test/layouts/SidebarLayout.preview.test.tsx@@ -0,0 +1,90 @@+// @vitest-environment jsdom+import { AssistantRuntimeProvider, useExternalStoreRuntime, type ThreadMessageLike } from '@assistant-ui/react';+import { fireEvent, render, screen, waitFor, within } from '@testing-library/react';+import { trueForgeExtras } from '@truefoundry/trueforge-assistant-ui-runtime';+import type { ReactNode } from 'react';+import { describe, expect, it } from 'vitest';++import { AgentConfigInstructionsProvider } from '@/atoms/draft/AgentConfigInstructionsContext.js';+import { SidebarLayout } from '@/layouts/SidebarLayout.js';+import { ServerProvider } from '@/server/ServerContext.js';+import { ShellModeProvider } from '@/server/ShellModeContext.js';+import { SlotsProvider } from '@/theme/SlotsProvider.js';+import { createMockAgentUIServer } from '../server/mockServer.js';++const htmlMessage = {+ role: 'assistant',+ content: ['Done', '', '```sandbox_artifacts', '[Metrics redesign](/tmp/metrics.html)', '```'].join('\n'),+ metadata: { custom: { turnId: 'turn-42', sandboxId: 'sbx-1' } },+} satisfies ThreadMessageLike;++function SidebarPreviewHarness({ children }: { children: ReactNode }) {+ const runtime = useExternalStoreRuntime({+ messages: [htmlMessage],+ isRunning: false,+ convertMessage: (message: ThreadMessageLike) => message,+ onNew: async () => {},+ extras: trueForgeExtras.provide({+ pendingApprovals: [],+ pendingToolResponses: [],+ pendingMcpAuth: null,+ resumeUnavailable: false,+ sandboxId: 'sbx-1',+ respondToToolApproval: () => {},+ respondToToolResponse: () => {},+ resumeMcpAuth: async () => {},+ downloadSandboxFile: async () => new Blob(['<!doctype html><h1>Metrics</h1>']),+ cancel: async () => {},+ resetFromTurn: async () => {},+ reload: () => {},+ hasOlderHistory: false,+ isLoadingOlderHistory: false,+ loadOlderHistory: async () => {},+ draft: null,+ }),+ });++ return (+ <SlotsProvider>+ <ServerProvider server={createMockAgentUIServer()}>+ <ShellModeProvider>+ <AgentConfigInstructionsProvider>+ <AssistantRuntimeProvider runtime={runtime}>{children}</AssistantRuntimeProvider>+ </AgentConfigInstructionsProvider>+ </ShellModeProvider>+ </ServerProvider>+ </SlotsProvider>+ );+}++describe('SidebarLayout file preview', () => {+ it('collapses recent chats while the preview fills the chat pane', async () => {+ if (typeof Element.prototype.scrollTo !== 'function') {+ Element.prototype.scrollTo = () => undefined;+ }++ render(+ <SidebarPreviewHarness>+ <SidebarLayout />+ </SidebarPreviewHarness>,+ );++ expect(screen.getByRole('complementary', { name: 'Recent chats' })).toBeInTheDocument();++ fireEvent.click(await screen.findByRole('button', { name: 'Enlarge Metrics redesign' }));+ const panel = await screen.findByRole('complementary', { name: 'Preview of Metrics redesign' });+ expect(screen.getByRole('complementary', { name: 'Recent chats' })).toBeInTheDocument();++ fireEvent.click(within(panel).getByRole('button', { name: 'Full page' }));+ await waitFor(() => {+ expect(screen.queryByRole('complementary', { name: 'Recent chats' })).not.toBeInTheDocument();+ });+ expect(screen.getByRole('complementary', { name: 'Preview of Metrics redesign' })).toHaveAttribute(+ 'data-placement',+ 'full',+ );++ fireEvent.click(screen.getByRole('button', { name: 'Exit full page' }));+ expect(screen.getByRole('complementary', { name: 'Recent chats' })).toBeInTheDocument();+ });+});diff --git a/packages/trueforge-ui/test/publicUiExports.test.ts b/packages/trueforge-ui/test/publicUiExports.test.tsindex e0b2752d9..09435c45d 100644--- a/packages/trueforge-ui/test/publicUiExports.test.ts+++ b/packages/trueforge-ui/test/publicUiExports.test.ts@@ -53,6 +53,7 @@ const expectedRuntimeExports: Array<keyof typeof sdk> = ['CanCreateAgentProvider','CenteredModal','ChatFileDownload',+ 'FilePreviewPanel','ClearChatButton','CodeEditor','ComposerAttachmentPickerContainer',