diff --git a/.changeset/artifact-entry-point-and-access-errors.md b/.changeset/artifact-entry-point-and-access-errors.md new file mode 100644 index 0000000000..b221d4a8f6 --- /dev/null +++ b/.changeset/artifact-entry-point-and-access-errors.md @@ -0,0 +1,7 @@ +--- +'@truefoundry/trueforge-assistant-ui-runtime': patch +'@truefoundry/trueforge-ui': patch +'@truefoundry/trueforge': patch +--- + +Open folder artifacts on their entry file, with the file list beside it, and expand a folder in the session card to preview its entry file. Show an access message when an artifact or its files are refused (403) and a not-found message on 404, instead of a generic failure. Show artifact size in the Artifacts table, drop its Created by column, and show file modified times in the folder tree. Renaming an artifact keeps its cached file listings. `Artifact.filesMetadata.sizeBytes` and `entryPoint` are no longer nullable, `ArtifactFile` gains `lastModified`, and `ArtifactServer` drops the unsupported `deleteArtifact` and `readArtifactFile` `version`. diff --git a/.changeset/artifact-is-dir-and-get.md b/.changeset/artifact-is-dir-and-get.md new file mode 100644 index 0000000000..b51b8b0926 --- /dev/null +++ b/.changeset/artifact-is-dir-and-get.md @@ -0,0 +1,7 @@ +--- +'@truefoundry/trueforge-assistant-ui-runtime': patch +'@truefoundry/trueforge-ui': patch +'@truefoundry/trueforge': patch +--- + +`Artifact` carries `filesMetadata` (`isDir`, `sizeBytes`, `entryPoint`) from the get, list and session list responses, replacing `isDir` and `ArtifactDetail`. `ArtifactServer.getArtifact` resolves an `Artifact`, and `ArtifactServer` gains `listArtifactFiles`. The harness adapter wires get, list files and `readArtifactFile` (by path, defaulting to the entry file). A single-file artifact previews its entry file by extension. A folder artifact previews with its file list beside the open file (hidden when maximized), shows folder and file icons, and has no Download action. The session artifacts card shows a loading skeleton and lists a folder's files as an expandable tree; picking a file previews just that file. Folder listings are cached per artifact version. diff --git a/.changeset/session-artifacts-listing-ui.md b/.changeset/session-artifacts-listing-ui.md new file mode 100644 index 0000000000..aebd897690 --- /dev/null +++ b/.changeset/session-artifacts-listing-ui.md @@ -0,0 +1,7 @@ +--- +'@truefoundry/trueforge-assistant-ui-runtime': patch +'@truefoundry/trueforge-ui': patch +'@truefoundry/trueforge': patch +--- + +Show a session Artifacts card in the chat with type labels, "Show N more", and expandable folder rows for files that share a directory. `ArtifactServer` gains `listSessionArtifacts`. Add an Artifacts button before Share in the chat header, shown once the session has artifacts, to hide or show the session artifacts card. Use the Lucide `image` icon for image artifacts in the session tree and file preview header. diff --git a/packages/assistant-ui-runtime/src/index.ts b/packages/assistant-ui-runtime/src/index.ts index 75e5b06f38..9880bba0c9 100644 --- a/packages/assistant-ui-runtime/src/index.ts +++ b/packages/assistant-ui-runtime/src/index.ts @@ -119,6 +119,7 @@ export type { AgentUIServerPort, ApprovalDecision, Artifact, + ArtifactFile, ArtifactServer, AuthenticateConnectorRequest, AutoModel, diff --git a/packages/assistant-ui-runtime/src/server/index.ts b/packages/assistant-ui-runtime/src/server/index.ts index 4ab639c0b5..3de8c1dd9e 100644 --- a/packages/assistant-ui-runtime/src/server/index.ts +++ b/packages/assistant-ui-runtime/src/server/index.ts @@ -28,6 +28,7 @@ export type { AgentUIServerPort, ApprovalDecision, Artifact, + ArtifactFile, ArtifactServer, AuthenticateConnectorRequest, AutoModel, diff --git a/packages/assistant-ui-runtime/src/server/types.ts b/packages/assistant-ui-runtime/src/server/types.ts index 4548091433..99eba3a61e 100644 --- a/packages/assistant-ui-runtime/src/server/types.ts +++ b/packages/assistant-ui-runtime/src/server/types.ts @@ -1414,6 +1414,26 @@ export interface Artifact { createdBySubject: Subject; createdAt: string; updatedAt: string; + /** Describes the latest version; list and session list responses carry it too. */ + filesMetadata: { + /** True when the latest version is a folder; a single top-level file is false. */ + isDir: boolean; + /** Total size in bytes of the latest version's files. */ + sizeBytes: number; + /** File to render first, relative to the artifact files. */ + entryPoint: string; + }; +} + +/** One entry of a folder artifact's latest version; listings are one level deep. */ +export interface ArtifactFile { + /** Path relative to the artifact files; folders end with `/`. */ + path: string; + isDir: boolean; + /** Size in bytes; null for folders. */ + size: number | null; + /** ISO-8601 modification time; null for folders. */ + lastModified: string | null; } export interface ListArtifactsParams extends Pick { @@ -1424,11 +1444,14 @@ export interface ListArtifactsParams extends Pick { /** Caller's artifacts, most recently updated first. */ listArtifacts(req?: ListArtifactsParams): Promise>; - getArtifact(req: { id: string }): Promise; + /** Artifacts with a version created in the session, most recently updated first. Not paginated. */ + listSessionArtifacts(req: { sessionId: string }): Promise; + getArtifact(req: { id: string }): Promise; + /** One folder level of the latest version; `path` is a folder relative to the artifact files, default the top level. */ + listArtifactFiles(req: { id: string; path?: string }): Promise; updateArtifact(req: { id: string; name: string }): Promise; - deleteArtifact(req: { id: string }): Promise; - /** Defaults to the latest version's entry file. */ - readArtifactFile(req: { id: string; version?: number; path?: string }): Promise; + /** Reads the latest version. Without `path`, reads the file of a single-file artifact; a folder needs a `path`. */ + readArtifactFile(req: { id: string; path?: string }): Promise; } // --------------------------------------------------------------------------- diff --git a/packages/trueforge-ui/AGENTS.md b/packages/trueforge-ui/AGENTS.md index a122144a18..1830673296 100644 --- a/packages/trueforge-ui/AGENTS.md +++ b/packages/trueforge-ui/AGENTS.md @@ -8,6 +8,7 @@ - Primitives MUST render their own popovers, lists, and empty states and expose slot props (e.g. `renderOption`, `menuFooter`, `noDataPlaceholder`); consumers MUST NOT re-render those parts beside the primitive. - Before adding inline markup, check `src/atoms/primitives/` and the `src/atoms/lib/` class helpers; extend an existing primitive rather than forking it. - UI lengths use `rem` (1rem = 16px); prefer Tailwind scale utilities. +- JSX event handlers and callback props MUST NOT be multi-statement inline arrow functions; define a named handler (e.g. `handleToggleExpanded`) and pass it. Single-call forwards like `onClick={() => onOpen(item)}` are fine. ## Analytics diff --git a/packages/trueforge-ui/src/analytics/events.ts b/packages/trueforge-ui/src/analytics/events.ts index 744117b077..1c21d611fd 100644 --- a/packages/trueforge-ui/src/analytics/events.ts +++ b/packages/trueforge-ui/src/analytics/events.ts @@ -104,9 +104,14 @@ export const AnalyticsEvents = { PREVIEW_OPENED: 'trueforge.artifact.preview_opened', DOWNLOADED: 'trueforge.artifact.downloaded', EDITED: 'trueforge.artifact.edited', + SESSION_CARD_FOLDER_TOGGLED: 'trueforge.artifact.session_card_folder_toggled', + SESSION_CARD_PREVIEW_OPENED: 'trueforge.artifact.session_card_preview_opened', + SESSION_CARD_SHOW_MORE: 'trueforge.artifact.session_card_show_more', + SESSION_CARD_TOGGLED: 'trueforge.artifact.session_card_toggled', }, FilePreview: { RELOADED: 'trueforge.file_preview.reloaded', + FOLDER_FILE_SELECTED: 'trueforge.file_preview.folder_file_selected', }, Sdk: { HTTP_TIMEOUT: 'trueforge.sdk.http_timeout', diff --git a/packages/trueforge-ui/src/atoms/AttachmentCard.tsx b/packages/trueforge-ui/src/atoms/AttachmentCard.tsx index b99f6589b1..80e5609259 100644 --- a/packages/trueforge-ui/src/atoms/AttachmentCard.tsx +++ b/packages/trueforge-ui/src/atoms/AttachmentCard.tsx @@ -2,6 +2,7 @@ import { USER_MESSAGE_ATTACHMENT_PREVIEW_REM } from '../constants/attachments.js'; import { Icon } from '../icons/Icon.js'; +import { formatFileSize } from '../utils/formatFileSize.js'; import { auiButtonClass } from './lib/buttonClasses.js'; import { cn } from './lib/cn.js'; import { Avatar, AvatarFallback, AvatarImage } from './primitives/Avatar.js'; @@ -43,13 +44,6 @@ export function getAttachmentFileIconName(name: string): string { 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, diff --git a/packages/trueforge-ui/src/atoms/FilePreviewFolderBrowser.tsx b/packages/trueforge-ui/src/atoms/FilePreviewFolderBrowser.tsx new file mode 100644 index 0000000000..cbcff37d36 --- /dev/null +++ b/packages/trueforge-ui/src/atoms/FilePreviewFolderBrowser.tsx @@ -0,0 +1,136 @@ +'use client'; + +import type { FolderTree } from '../filePreview/useFolderTree.js'; +import { Icon } from '../icons/Icon.js'; +import type { ArtifactFile } from '../server/types.js'; +import { formatFileSize } from '../utils/formatFileSize.js'; +import { artifactType } from './artifacts/artifactDisplay.js'; +import { cn } from './lib/cn.js'; +import { formatAbsoluteDateTime } from './lib/dateFormat.js'; +import { Skeleton } from './primitives/Skeleton.js'; + +export type FilePreviewFolderBrowserProps = { + tree: FolderTree; + selectedPath: string | null; + onSelect: (path: string) => void; +}; + +const INDENT_REM = 0.75; + +function entryName(path: string): string { + return path.replace(/\/$/, '').split('/').pop() ?? path; +} + +function LevelMessage({ children }: { children: string }) { + return

{children}

; +} + +function FolderLevel({ + path, + depth, + tree, + selectedPath, + onSelect, +}: FilePreviewFolderBrowserProps & { path: string; depth: number }) { + const level = tree.levels[path]; + if (level === undefined || level.status === 'loading') { + return ( +
+ {['w-3/4', 'w-1/2', 'w-2/3'].map(width => ( +
+ + +
+ ))} +
+ ); + } + if (level.status === 'error') return {level.message}; + if (level.entries.length === 0) return This folder is empty.; + + const renderEntry = (entry: ArtifactFile) => { + const name = entryName(entry.path); + const indent = { paddingLeft: `${String(depth * INDENT_REM + 0.5)}rem` }; + if (entry.isDir) { + const open = tree.expanded.has(entry.path); + return ( +
  • + + {/* Kept mounted once opened so collapsing does not drop what was already loaded. */} + {open || tree.levels[entry.path] !== undefined ? ( + + ) : null} +
  • + ); + } + const selected = entry.path === selectedPath; + return ( +
  • + +
  • + ); + }; + + return
      {level.entries.map(renderEntry)}
    ; +} + +/** Lazy file tree of a folder artifact; files are selected, folders only open or close. */ +export function FilePreviewFolderBrowser(props: FilePreviewFolderBrowserProps) { + return ( + + ); +} + +declare module '../theme/SlotsProvider.js' { + interface AtomSlots { + FilePreviewFolderBrowser: typeof FilePreviewFolderBrowser; + } +} diff --git a/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx b/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx index 6df792a037..047d8cce45 100644 --- a/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx +++ b/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx @@ -1,11 +1,20 @@ 'use client'; -import { useEffect, useLayoutEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from 'react'; +import { + useEffect, + useLayoutEffect, + useRef, + useState, + type KeyboardEvent as ReactKeyboardEvent, + type ReactNode, + 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 { artifactType } from './artifacts/artifactDisplay.js'; import { auiButtonClass } from './lib/buttonClasses.js'; import { cn } from './lib/cn.js'; import { Button } from './primitives/Button.js'; @@ -27,6 +36,8 @@ export type FilePreviewPanelProps = { onExitFullPage?: () => void; onReload?: () => void; downloadBusy?: boolean; + /** Folder artifacts show `browser` beside the preview; maximized with a file open, the list is hidden. */ + folder?: { browser: ReactNode; fileOpen: boolean }; /** Side-pane width in CSS pixels. Overlay and full-page placement ignore this. */ widthPx?: number; onWidthChange?: (widthPx: number) => void; @@ -117,10 +128,15 @@ export function FilePreviewPanel({ onExitFullPage, onReload, downloadBusy = false, + folder, widthPx, onWidthChange, }: FilePreviewPanelProps) { const panelRef = useRef(null); + // A folder has nothing to reload or download until one of its files is open. + const previewing = folder == null || folder.fileOpen; + // Maximized, the preview gets the whole width; the list returns when the pane is restored. + const listHidden = folder?.fileOpen === true && placement === 'full'; const showResizeHandle = placement === 'side' && onWidthChange != null; // Fixed for the element's lifetime so a placement change never restarts the mount animation. const [mountPlacement] = useState(placement); @@ -171,6 +187,31 @@ export function FilePreviewPanel({ handle.addEventListener('pointercancel', end); }; + const onPanelKeyDown = (event: ReactKeyboardEvent) => { + 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(); + }; + + const onResizeHandleKeyDown = (event: ReactKeyboardEvent) => { + 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); + }; + + const handleEnterFullPage = () => { + if (onEnterFullPage == null) return; + expandFromRef.current = panelRef.current?.getBoundingClientRect() ?? null; + onEnterFullPage(); + }; + const panel = ( ); diff --git a/packages/trueforge-ui/src/atoms/ThreadShell.tsx b/packages/trueforge-ui/src/atoms/ThreadShell.tsx index b3019980a6..ed9eb85e5a 100644 --- a/packages/trueforge-ui/src/atoms/ThreadShell.tsx +++ b/packages/trueforge-ui/src/atoms/ThreadShell.tsx @@ -1,4 +1,4 @@ -import { forwardRef, type ComponentPropsWithRef, type CSSProperties } from 'react'; +import { forwardRef, type ComponentPropsWithRef, type CSSProperties, type ReactNode } from 'react'; import { cn } from './lib/cn.js'; @@ -33,10 +33,12 @@ export type ThreadViewportShellProps = ComponentPropsWithRef<'div'> & { scrollable?: boolean; /** Override the conversation content width without changing the scroll root width. */ contentMaxWidth?: string; + /** Column beside the messages inside the scroll root, so the scrollbar stays at the far right edge. */ + aside?: ReactNode; }; export const ThreadViewportShell = forwardRef( - ({ className, isEmpty, scrollable = true, contentMaxWidth, children, ...rest }, ref) => ( + ({ className, isEmpty, scrollable = true, contentMaxWidth, aside, children, ...rest }, ref) => (
    -
    - {children} +
    +
    + {children} +
    + {aside}
    ), diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactEditDialog.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactEditDialog.tsx index e8eb8f3f1c..21ab11d50d 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactEditDialog.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactEditDialog.tsx @@ -13,6 +13,8 @@ import type { Artifact } from '../../server/types.js'; import { auiInputClass } from '../lib/inputClasses.js'; import { Button } from '../primitives/Button.js'; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '../primitives/Dialog.js'; +import { artifactPreviewKey } from './artifactDisplay.js'; +import { carryFileListings } from './carryFileListings.js'; export function ArtifactEditDialog({ artifact, @@ -76,10 +78,13 @@ export function useRenameArtifact() { { mutationFn: ({ artifact, name }: { artifact: Artifact; name: string }) => artifactServer.updateArtifact({ id: artifact.id, name }), - onSuccess: (_updated, { artifact }) => { + onSuccess: (updated, { artifact }) => { track(AnalyticsEvents.Artifact.EDITED, { artifact_id: artifact.id }); toaster?.showSuccess({ title: 'Artifact updated' }); - void queryClient.invalidateQueries({ queryKey: queryKeys.artifacts.all() }); + // A rename bumps `updatedAt` but leaves the files alone, so their listings move to the new key instead of refetching. + carryFileListings({ queryClient, from: artifactPreviewKey(artifact), to: artifactPreviewKey(updated) }); + void queryClient.invalidateQueries({ queryKey: queryKeys.artifacts.lists() }); + void queryClient.invalidateQueries({ queryKey: queryKeys.artifacts.sessions() }); }, onError: caught => toaster?.showError(caught), }, diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx index dab0c38535..56a03c187a 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx @@ -21,7 +21,7 @@ import { PageHeader } from '../PageHeader.js'; import SearchInput from '../primitives/SearchInput.js'; import { Skeleton } from '../primitives/Skeleton.js'; import { DEFAULT_TABLE_PAGE_SIZE, TableTokenPagination } from '../primitives/Table.js'; -import { artifactPreviewKey } from './artifactDisplay.js'; +import { artifactPreviewTarget } from './artifactDisplay.js'; import { ArtifactEditDialog, useRenameArtifact } from './ArtifactEditDialog.js'; import { ArtifactsEmptyState } from './ArtifactsEmptyState.js'; import { ArtifactsTable } from './ArtifactsTable.js'; @@ -113,13 +113,7 @@ function ArtifactsPageBody() { const ref = artifactRef(artifact); openedRefRef.current = ref; setArtifactRef?.(ref); - openFilePreview({ - name: artifact.name, - // The list carries no entry file path; the read route picks it and the blob type drives rendering. - path: artifact.name, - turnId: artifactPreviewKey(artifact), - load: () => artifactServer.readArtifactFile({ id }), - }); + openFilePreview(artifactPreviewTarget({ artifact, artifactServer })); }, [artifactServer, openFilePreview, setArtifactRef, track], ); @@ -173,6 +167,15 @@ function ArtifactsPageBody() { const hasPageNav = nextPageToken != null || previousPageToken != null || artifacts.length > 0; + const handleNextPage = () => { + if (nextPageToken != null) setPageCursor({ scope: pageScope, token: nextPageToken }); + }; + + const handleSaveRename = (nextName: string) => { + if (editing == null) return; + renameArtifact.mutate({ artifact: editing, name: nextName }, { onSuccess: () => setEditing(null) }); + }; + return (
    setPageCursor({ scope: pageScope, token: previousPageToken })} - onNext={() => { - if (nextPageToken != null) setPageCursor({ scope: pageScope, token: nextPageToken }); - }} + onNext={handleNextPage} pageSizeOptions={PAGE_SIZE_OPTIONS} onPageSizeChange={setPageSize} /> @@ -234,7 +235,7 @@ function ArtifactsPageBody() { artifact={editing} saving={renameArtifact.isPending} onCancel={() => setEditing(null)} - onSave={name => renameArtifact.mutate({ artifact: editing, name }, { onSuccess: () => setEditing(null) })} + onSave={handleSaveRename} /> ) : null}
    diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx index f92758115b..d50916ec33 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx @@ -2,14 +2,14 @@ import { Icon } from '../../icons/Icon.js'; import type { Artifact } from '../../server/types.js'; -import { CreatedByCell } from '../CreatedByCell.js'; +import { formatFileSize } from '../../utils/formatFileSize.js'; import { auiButtonClass } from '../lib/buttonClasses.js'; import { cn } from '../lib/cn.js'; import { formatRelativeTime } from '../lib/dateFormat.js'; import { DropdownMenu } from '../primitives/DropdownMenu.js'; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../primitives/Table.js'; import { RowActionItem } from '../RowActionItem.js'; -import { artifactPreviewKey } from './artifactDisplay.js'; +import { artifactPreviewKey, artifactType } from './artifactDisplay.js'; export type ArtifactsTableProps = { artifacts: Artifact[]; @@ -25,7 +25,7 @@ export function ArtifactsTable({ artifacts, selectedKey, onOpen, onDownload, onE Name - Created by + Size Updated @@ -42,10 +42,17 @@ export function ArtifactsTable({ artifacts, selectedKey, onOpen, onDownload, onE onClick={() => onOpen(artifact)} > - {artifact.name} + + + {artifact.name} + - - + + {formatFileSize(artifact.filesMetadata.sizeBytes)} {formatRelativeTime(artifact.updatedAt)} {/* Swallow here so menu clicks do not also open the preview. */} @@ -64,13 +71,15 @@ export function ArtifactsTable({ artifacts, selectedKey, onOpen, onDownload, onE } > onEdit(artifact)} /> - onOpen(artifact)} /> - onDownload(artifact)} - /> + {/* The API serves files one by one and has no archive route, so a folder has nothing to download. */} + {artifact.filesMetadata.isDir ? null : ( + onDownload(artifact)} + /> + )} diff --git a/packages/trueforge-ui/src/atoms/artifacts/SessionArtifactsCard.tsx b/packages/trueforge-ui/src/atoms/artifacts/SessionArtifactsCard.tsx new file mode 100644 index 0000000000..2a52f9fc38 --- /dev/null +++ b/packages/trueforge-ui/src/atoms/artifacts/SessionArtifactsCard.tsx @@ -0,0 +1,135 @@ +'use client'; + +import { useState, type ReactNode } from 'react'; + +import { Icon } from '../../icons/Icon.js'; +import type { Artifact } from '../../server/types.js'; +import { cn } from '../lib/cn.js'; +import { Skeleton } from '../primitives/Skeleton.js'; +import { artifactPreviewKey, artifactType } from './artifactDisplay.js'; + +/** Rows shown before "Show N more", so a long session does not cover the chat. */ +export const SESSION_ARTIFACTS_VISIBLE_COUNT = 6; + +export type SessionArtifactsCardProps = { + artifacts: Artifact[]; + selectedKey: string | undefined; + onOpen: (artifact: Artifact) => void; + onShowMore?: () => void; + /** True until the first list arrives, so the card shows placeholders instead of looking empty. */ + loading?: boolean; + /** Lists a folder row's files inside the card; without it a folder row opens like a file. Expanding it also calls `onOpen`. */ + renderFolderFiles?: (artifact: Artifact) => ReactNode; + onToggleFolder?: (artifact: Artifact) => void; + className?: string; +}; + +function ArtifactRowsSkeleton() { + return ( +
    + {['w-3/4', 'w-1/2', 'w-2/3'].map(width => ( +
    + + +
    + ))} +
    + ); +} + +export function SessionArtifactsCard({ + artifacts, + selectedKey, + onOpen, + onShowMore, + loading = false, + renderFolderFiles, + onToggleFolder, + className, +}: SessionArtifactsCardProps) { + const [expanded, setExpanded] = useState(false); + const [openFolders, setOpenFolders] = useState>(new Set()); + const hiddenCount = Math.max(artifacts.length - SESSION_ARTIFACTS_VISIBLE_COUNT, 0); + const visible = expanded ? artifacts : artifacts.slice(0, SESSION_ARTIFACTS_VISIBLE_COUNT); + + const handleToggleExpanded = () => { + if (!expanded) onShowMore?.(); + setExpanded(current => !current); + }; + + const toggleFolder = (artifact: Artifact) => { + onToggleFolder?.(artifact); + // Expanding a folder previews its entry file; collapsing leaves the preview as it is. + if (!openFolders.has(artifact.id)) onOpen(artifact); + setOpenFolders(current => { + const next = new Set(current); + if (!next.delete(artifact.id)) next.add(artifact.id); + return next; + }); + }; + + const renderArtifactRow = (artifact: Artifact) => { + const isDir = artifact.filesMetadata.isDir; + const type = artifactType({ name: artifact.name, isDir }); + const asTree = isDir && renderFolderFiles != null; + const folderOpen = asTree && openFolders.has(artifact.id); + return ( + <> + + {folderOpen ?
    {renderFolderFiles(artifact)}
    : null} + + ); + }; + + return ( +
    +

    Artifacts

    + {loading ? : null} + {!loading && artifacts.length === 0 ? ( +

    No artifacts yet

    + ) : null} +
      + {visible.map(artifact => ( +
    • {renderArtifactRow(artifact)}
    • + ))} +
    + {hiddenCount > 0 ? ( + + ) : null} +
    + ); +} + +declare module '../../theme/SlotsProvider.js' { + interface AtomSlots { + SessionArtifactsCard: typeof SessionArtifactsCard; + } +} diff --git a/packages/trueforge-ui/src/atoms/artifacts/SessionArtifactsToggleButton.tsx b/packages/trueforge-ui/src/atoms/artifacts/SessionArtifactsToggleButton.tsx new file mode 100644 index 0000000000..3675191631 --- /dev/null +++ b/packages/trueforge-ui/src/atoms/artifacts/SessionArtifactsToggleButton.tsx @@ -0,0 +1,53 @@ +'use client'; + +import { useTrackAnalytics } from '../../analytics/AnalyticsProvider.js'; +import { AnalyticsEvents } from '../../analytics/events.js'; +import { useAuiState } from '../../assistant-ui.js'; +import { useSessionArtifactsSupported } from '../../containers/SessionArtifactsContainer.js'; +import { useOptionalSessionArtifactsPanel } from '../../containers/SessionArtifactsPanelContext.js'; +import { Icon } from '../../icons/Icon.js'; +import { useServerQueryClient } from '../../server/queryClient.js'; +import { queryKeys } from '../../server/queryKeys.js'; +import { Button } from '../primitives/Button.js'; + +/** Header control that shows or hides the session artifacts card. Hidden when the card cannot show, so it never flips an empty column. */ +export function SessionArtifactsToggleButton() { + const panel = useOptionalSessionArtifactsPanel(); + const supported = useSessionArtifactsSupported(); + const track = useTrackAnalytics(); + const queryClient = useServerQueryClient(); + const sessionId = useAuiState(state => state.threadListItem.remoteId); + + if (panel == null || !supported) return null; + + const { open, setOpen } = panel; + + const toggleArtifacts = () => { + track(AnalyticsEvents.Artifact.SESSION_CARD_TOGGLED, { open: !open }); + // The listing is not polled while closed, so opening marks it stale and the reopened query refetches. + if (!open && sessionId != null && sessionId !== '') { + void queryClient.invalidateQueries({ queryKey: queryKeys.artifacts.session(sessionId) }); + } + setOpen(!open); + }; + + return ( + + ); +} + +declare module '../../theme/SlotsProvider.js' { + interface AtomSlots { + SessionArtifactsToggleButton: typeof SessionArtifactsToggleButton; + } +} diff --git a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts index a5339ed464..6c0c39bc90 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts +++ b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts @@ -1,6 +1,61 @@ -import type { Artifact } from '../../server/types.js'; +import type { SandboxFilePreviewTarget } from '../../filePreview/FilePreviewContext.js'; +import { folderFileTarget } from '../../filePreview/folderFileTarget.js'; +import { inlinePreviewKind } from '../../filePreview/readFilePreview.js'; +import type { Artifact, ArtifactServer } from '../../server/types.js'; /** Preview cache identity; `updatedAt` advances on every new version, so stale bytes are not reused. */ export function artifactPreviewKey({ id, updatedAt }: Pick): string { return `${id}@${updatedAt}`; } + +/** Shared by the Artifacts page and the session card so both open the same preview. */ +export function artifactPreviewTarget({ + artifact, + artifactServer, + filePath, +}: { + artifact: Artifact; + artifactServer: ArtifactServer; + /** A file inside a folder artifact to preview on its own; ignored for single-file artifacts. */ + filePath?: string; +}): SandboxFilePreviewTarget { + const { isDir, entryPoint } = artifact.filesMetadata; + const target: SandboxFilePreviewTarget = { + name: artifact.name, + // The entry file's extension picks the inline renderer. + path: entryPoint, + turnId: artifactPreviewKey(artifact), + // A folder has no single file to read, so it reads its entry file. + load: () => artifactServer.readArtifactFile({ id: artifact.id, ...(isDir ? { path: entryPoint } : {}) }), + // A folder opens on its entry file with the file list beside it, so the rest of its contents stay reachable. + ...(isDir + ? { + folder: { + cacheKey: artifactPreviewKey(artifact), + entryPoint, + list: (path: string) => artifactServer.listArtifactFiles({ id: artifact.id, path }), + loadFile: (path: string) => artifactServer.readArtifactFile({ id: artifact.id, path }), + }, + } + : {}), + }; + return target.folder != null && filePath !== undefined + ? folderFileTarget({ target, folder: target.folder, path: filePath }) + : target; +} + +export type ArtifactType = { label: string; icon: string }; + +const FILE_TYPE: ArtifactType = { label: 'File', icon: 'file' }; + +const FOLDER_TYPE: ArtifactType = { label: 'Folder', icon: 'folder' }; + +/** Short type label and icon for an artifact row; files use the name extension, folders never do. */ +export function artifactType({ name, isDir }: { name: string; isDir: boolean }): ArtifactType { + if (isDir) return FOLDER_TYPE; + const kind = inlinePreviewKind({ name, path: name }); + if (kind === 'image') return { label: 'Image', icon: 'image' }; + if (kind === 'html') return { label: 'Html', icon: 'file-code' }; + if (kind === 'pdf') return { label: 'Pdf', icon: 'file-text' }; + return FILE_TYPE; +} diff --git a/packages/trueforge-ui/src/atoms/artifacts/carryFileListings.ts b/packages/trueforge-ui/src/atoms/artifacts/carryFileListings.ts new file mode 100644 index 0000000000..4c3c2540ad --- /dev/null +++ b/packages/trueforge-ui/src/atoms/artifacts/carryFileListings.ts @@ -0,0 +1,16 @@ +import type { QueryClient } from '@tanstack/react-query'; + +import { queryKeys } from '../../server/queryKeys.js'; +import type { ArtifactFile } from '../../server/types.js'; + +/** Copies cached folder listings from one artifact version key to another, as when only the name changed. */ +export function carryFileListings({ queryClient, from, to }: { queryClient: QueryClient; from: string; to: string }) { + if (from === to) return; + const prefixLength = queryKeys.artifacts.filesOf(from).length; + for (const [queryKey, listing] of queryClient.getQueriesData({ + queryKey: queryKeys.artifacts.filesOf(from), + })) { + if (listing === undefined) continue; + queryClient.setQueryData([...queryKey.slice(0, prefixLength - 1), to, ...queryKey.slice(prefixLength)], listing); + } +} diff --git a/packages/trueforge-ui/src/containers/FilePreviewFolderBrowserContainer.tsx b/packages/trueforge-ui/src/containers/FilePreviewFolderBrowserContainer.tsx new file mode 100644 index 0000000000..0a126cf3d0 --- /dev/null +++ b/packages/trueforge-ui/src/containers/FilePreviewFolderBrowserContainer.tsx @@ -0,0 +1,24 @@ +'use client'; + +import type { FilePreviewFolder } from '../filePreview/FilePreviewContext.js'; +import { useFolderTree } from '../filePreview/useFolderTree.js'; +import { useSlot } from '../theme/SlotsProvider.js'; + +/** Owns the tree state of one folder, so the caller gives it a `key` that changes with the folder. */ +export function FilePreviewFolderBrowserContainer({ + folder, + selectedPath, + onSelect, +}: { + folder: FilePreviewFolder; + selectedPath: string | null; + onSelect: (path: string) => void; +}) { + const FilePreviewFolderBrowser = useSlot('FilePreviewFolderBrowser'); + const tree = useFolderTree({ + cacheKey: folder.cacheKey, + list: folder.list, + revealPath: folder.entryPoint, + }); + return ; +} diff --git a/packages/trueforge-ui/src/containers/FilePreviewHost.tsx b/packages/trueforge-ui/src/containers/FilePreviewHost.tsx index a43ecabf9a..9d9fb397fd 100644 --- a/packages/trueforge-ui/src/containers/FilePreviewHost.tsx +++ b/packages/trueforge-ui/src/containers/FilePreviewHost.tsx @@ -1,16 +1,18 @@ 'use client'; -import { useLayoutEffect, useState } from 'react'; +import { useLayoutEffect, useMemo, useState } from 'react'; import { useTrackAnalytics } from '../analytics/AnalyticsProvider.js'; import { AnalyticsEvents } from '../analytics/events.js'; import { useCompactLayout } from '../atoms/lib/CompactLayoutContext.js'; import { useIsMobile } from '../atoms/lib/useIsMobile.js'; -import { useFilePreview } from '../filePreview/FilePreviewContext.js'; +import { useFilePreview, type SandboxFilePreviewTarget } from '../filePreview/FilePreviewContext.js'; +import { folderFileTarget } from '../filePreview/folderFileTarget.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 { FilePreviewFolderBrowserContainer } from './FilePreviewFolderBrowserContainer.js'; import { useToasterOptional } from './ToasterContainer.js'; const PREVIEW_WIDTH_KEY = 'trueforge.file-preview-width'; @@ -34,6 +36,16 @@ function storePreviewWidth(widthPx: number) { } } +/** The one file the panel previews: the target itself, or the file open in its folder (its entry file until another is picked). */ +function activeFileTarget( + target: SandboxFilePreviewTarget | null, + selectedPath: string | null, +): SandboxFilePreviewTarget | null { + if (target?.folder == null) return target; + if (selectedPath == null) return null; + return folderFileTarget({ target, folder: target.folder, path: selectedPath }); +} + /** Side pane, or a preview that fills the chat column without covering the app sidebar. */ export function FilePreviewHost() { const preview = useFilePreview(); @@ -45,8 +57,16 @@ export function FilePreviewHost() { const [reloadToken, setReloadToken] = useState(0); const [downloadBusy, setDownloadBusy] = useState(false); const [widthPx, setWidthPx] = useState(readStoredPreviewWidth); - const loaded = useLoadedFilePreview(preview.target, reloadToken); const target = preview.target; + const targetKey = target == null ? null : `${target.turnId}:${target.path}`; + const [selection, setSelection] = useState<{ targetKey: string; path: string } | null>(null); + // A pick belongs to the preview it was made in. It is dropped once that preview closes or another opens, so + // reopening the same folder starts on its entry file, which the freshly mounted tree reveals. + if (selection != null && selection.targetKey !== targetKey) setSelection(null); + const picked = selection != null && selection.targetKey === targetKey ? selection.path : null; + const selectedPath = picked ?? target?.folder?.entryPoint ?? null; + const activeTarget = useMemo(() => activeFileTarget(target, selectedPath), [target, selectedPath]); + const loaded = useLoadedFilePreview(activeTarget, reloadToken); const placement = preview.presentation === 'full' ? 'full' : compact || isMobile ? 'overlay' : 'side'; useLayoutEffect(() => { @@ -63,13 +83,19 @@ export function FilePreviewHost() { setReloadToken(token => token + 1); }; + const handleSelectFile = (path: string) => { + if (targetKey == null) return; + track(AnalyticsEvents.FilePreview.FOLDER_FILE_SELECTED); + setSelection({ targetKey, path }); + }; + const handleDownload = () => { - if (downloadBusy) return; + if (downloadBusy || activeTarget == null) return; setDownloadBusy(true); void (async () => { try { - const blob = loaded.blob ?? (await target.load()); - triggerBrowserDownload(blob, filenameFromPath(target.path)); + const blob = loaded.blob ?? (await activeTarget.load()); + triggerBrowserDownload(blob, filenameFromPath(activeTarget.path)); } catch (error) { if (toaster != null) toaster.showError(error); else console.error('Failed to download sandbox file', error); @@ -79,9 +105,10 @@ export function FilePreviewHost() { })(); }; + const { folder } = target; return ( preview.setPresentation('full')} onExitFullPage={() => preview.setPresentation('panel')} downloadBusy={downloadBusy} + {...(folder == null + ? {} + : { + folder: { + browser: ( + + ), + fileOpen: selectedPath != null, + }, + })} {...(placement === 'side' && widthPx != null ? { widthPx } : {})} {...(placement === 'side' ? { diff --git a/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx new file mode 100644 index 0000000000..5d7c10c981 --- /dev/null +++ b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx @@ -0,0 +1,166 @@ +'use client'; + +import { skipToken, useQuery } from '@tanstack/react-query'; +import { useEffect, useRef } from 'react'; + +import { useTrackAnalytics } from '../analytics/AnalyticsProvider.js'; +import { AnalyticsEvents } from '../analytics/events.js'; +import { useAuiState } from '../assistant-ui.js'; +import { artifactPreviewKey, artifactPreviewTarget } from '../atoms/artifacts/artifactDisplay.js'; +import { cn } from '../atoms/lib/cn.js'; +import { useCompactLayout } from '../atoms/lib/CompactLayoutContext.js'; +import { useFilePreview, type SandboxFilePreviewTarget } from '../filePreview/FilePreviewContext.js'; +import { openFolderFilePath } from '../filePreview/folderFileTarget.js'; +import { useServerQueryClient } from '../server/queryClient.js'; +import { queryKeys } from '../server/queryKeys.js'; +import { useOptionalArtifactServer } from '../server/ServerContext.js'; +import type { Artifact } from '../server/types.js'; +import { useSlot } from '../theme/SlotsProvider.js'; +import { FilePreviewFolderBrowserContainer } from './FilePreviewFolderBrowserContainer.js'; +import { useOptionalSessionArtifactsPanel } from './SessionArtifactsPanelContext.js'; + +/** Width of the card column (card plus its padding). The composer uses the same inset so it sits under the chat. */ +export const SESSION_ARTIFACTS_COLUMN_INSET_CLASS = 'lg:pr-[20rem]'; + +/** The backend writes artifacts mid-run and the stream has no artifact event, so the list is polled while a run is active. */ +export const SESSION_ARTIFACTS_RUN_POLL_MS = 5000; + +/** Shared by the card column and the composer inset so both move in step when the card is toggled. */ +export const SESSION_ARTIFACTS_TRANSITION_CLASS = 'duration-200 ease-out motion-reduce:transition-none'; + +function useStoredSessionId(): string | null { + const sessionId = useAuiState(state => state.threadListItem.remoteId); + return sessionId == null || sessionId === '' ? null : sessionId; +} + +/** Gates the card and its toggle. This happens in compact layouts (dock, widget), which have no room beside the chat, and before the first message creates a session. */ +export function useSessionArtifactsSupported(): boolean { + const artifactServer = useOptionalArtifactServer(); + const sessionId = useStoredSessionId(); + const compact = useCompactLayout(); + return artifactServer != null && sessionId != null && !compact; +} + +/** Lists only while the card is open: a closed card neither fetches nor polls, and reopening refetches. */ +function useSessionArtifactsQuery() { + const artifactServer = useOptionalArtifactServer(); + const sessionId = useStoredSessionId(); + const isRunning = useAuiState(state => state.thread.isRunning); + const panel = useOptionalSessionArtifactsPanel(); + const open = panel?.open ?? true; + const supported = useSessionArtifactsSupported(); + const queryClient = useServerQueryClient(); + const query = useQuery( + { + queryKey: queryKeys.artifacts.session(sessionId ?? ''), + queryFn: + artifactServer == null || sessionId == null + ? skipToken + : () => artifactServer.listSessionArtifacts({ sessionId }), + enabled: open && supported, + refetchInterval: open && isRunning ? SESSION_ARTIFACTS_RUN_POLL_MS : false, + }, + queryClient, + ); + return { artifactServer, sessionId, artifacts: query.data, loading: query.isPending }; +} + +/** The open file's row is selected; a file inside a folder is selected in the tree, so its folder row stays plain. */ +function selectedArtifactKey({ + target, + artifacts, +}: { + target: SandboxFilePreviewTarget | null; + artifacts: Artifact[]; +}): string | undefined { + const insideFolder = artifacts.some( + artifact => openFolderFilePath({ target, folderTurnId: artifactPreviewKey(artifact) }) !== null, + ); + return insideFolder ? undefined : target?.turnId; +} + +/** True when the card column is on screen, so the composer leaves room for it. */ +export function useSessionArtifactsVisible(): boolean { + const supported = useSessionArtifactsSupported(); + const panel = useOptionalSessionArtifactsPanel(); + return supported && (panel?.open ?? true); +} + +/** Card listing the artifacts the active session produced; the column collapses when the header toggle closes it. */ +export function SessionArtifactsContainer() { + const SessionArtifactsCard = useSlot('SessionArtifactsCard'); + const queryClient = useServerQueryClient(); + const track = useTrackAnalytics(); + const preview = useFilePreview(); + const panel = useOptionalSessionArtifactsPanel(); + const { open: openFilePreview } = preview; + const isRunning = useAuiState(state => state.thread.isRunning); + const supported = useSessionArtifactsSupported(); + const { artifactServer, sessionId, artifacts, loading } = useSessionArtifactsQuery(); + + // A turn can create artifacts, so the list is refreshed when the run ends rather than on every stream tick. + const wasRunning = useRef(isRunning); + useEffect(() => { + if (wasRunning.current && !isRunning && sessionId != null) { + void queryClient.invalidateQueries({ queryKey: queryKeys.artifacts.session(sessionId) }); + } + wasRunning.current = isRunning; + }, [isRunning, queryClient, sessionId]); + + if (!supported || artifactServer == null || sessionId == null) return null; + + const open = panel?.open !== false; + // The folder's files are listed in the card itself, so a folder opens straight on its entry file. + const openArtifact = (artifact: Artifact, filePath?: string) => { + const { isDir, entryPoint } = artifact.filesMetadata; + const openPath = filePath ?? (isDir ? entryPoint : undefined); + track(AnalyticsEvents.Artifact.SESSION_CARD_PREVIEW_OPENED, { artifact_id: artifact.id }); + openFilePreview( + artifactPreviewTarget({ artifact, artifactServer, ...(openPath === undefined ? {} : { filePath: openPath }) }), + ); + }; + + const renderFolderFiles = (artifact: Artifact) => { + const { folder } = artifactPreviewTarget({ artifact, artifactServer }); + if (folder == null) return null; + return ( + // The poll brings a new version while the card stays mounted, so the tree restarts with it instead of + // keeping expanded subfolders listed from the version before. + openArtifact(artifact, path)} + /> + ); + }; + + // Rendered inside the thread scroll root, beside the messages: the messages shift left and the + // card stays pinned while the chat scrolls, with the scrollbar after it. + // Hiding collapses the column width instead of unmounting, so the centered messages and the composer + // inset glide together; `invisible` drops the collapsed card from focus once the transition ends. + return ( + + ); +} diff --git a/packages/trueforge-ui/src/containers/SessionArtifactsPanelContext.tsx b/packages/trueforge-ui/src/containers/SessionArtifactsPanelContext.tsx new file mode 100644 index 0000000000..d9cdd643dc --- /dev/null +++ b/packages/trueforge-ui/src/containers/SessionArtifactsPanelContext.tsx @@ -0,0 +1,28 @@ +'use client'; + +import { createContext, useContext, useMemo, useState, type ReactNode } from 'react'; + +type SessionArtifactsPanelValue = { + open: boolean; + setOpen: (open: boolean) => void; +}; + +const SessionArtifactsPanelContext = createContext(null); + +/** Shared by the header toggle and the thread so both agree on whether the artifacts card is shown. Starts closed so no listing is fetched until the user asks for it. */ +export function SessionArtifactsPanelProvider({ + children, + defaultOpen = false, +}: { + children: ReactNode; + defaultOpen?: boolean; +}) { + const [open, setOpen] = useState(defaultOpen); + const value = useMemo(() => ({ open, setOpen }), [open]); + return {children}; +} + +/** Null when the host mounts the thread without the shell; the card then stays always shown, with no toggle. */ +export function useOptionalSessionArtifactsPanel(): SessionArtifactsPanelValue | null { + return useContext(SessionArtifactsPanelContext); +} diff --git a/packages/trueforge-ui/src/containers/ThreadContainer.tsx b/packages/trueforge-ui/src/containers/ThreadContainer.tsx index 9a0a0874fa..45edb6cd2a 100644 --- a/packages/trueforge-ui/src/containers/ThreadContainer.tsx +++ b/packages/trueforge-ui/src/containers/ThreadContainer.tsx @@ -2,6 +2,7 @@ import { ThreadPrimitive, useAuiState } from '@assistant-ui/react'; import { useEffect, type ReactNode } from 'react'; +import { cn } from '../atoms/lib/cn.js'; import { preloadMarkdownOpenUI } from '../atoms/Markdown.js'; import { FilePreviewBoundary } from '../filePreview/FilePreviewContext.js'; import { ComposerBusyProvider } from '../hooks/useComposerBusyState.js'; @@ -15,6 +16,12 @@ import { AssistantMessageContainer } from './AssistantMessageContainer.js'; import { FilePreviewHost } from './FilePreviewHost.js'; import { HistoryLoaderContainer } from './HistoryLoaderContainer.js'; import { ResumeUnavailableContainer } from './ResumeUnavailableContainer.js'; +import { + SESSION_ARTIFACTS_COLUMN_INSET_CLASS, + SESSION_ARTIFACTS_TRANSITION_CLASS, + SessionArtifactsContainer, + useSessionArtifactsVisible, +} from './SessionArtifactsContainer.js'; import { UserEditComposerContainer } from './UserEditComposerContainer.js'; import { UserMessageContainer } from './UserMessageContainer.js'; @@ -54,6 +61,7 @@ export function ThreadContainer({ composer }: ThreadContainerProps) { const ScrollToBottomButton = useSlot('ScrollToBottomButton'); const MessageGroup = useSlot('MessageGroup'); const ThreadComposerAreaShell = useSlot('ThreadComposerAreaShell'); + const artifactsVisible = useSessionArtifactsVisible(); const ThreadRootShell = useSlot('ThreadRootShell'); const ThreadViewportShell = useSlot('ThreadViewportShell'); @@ -81,7 +89,7 @@ export function ThreadContainer({ composer }: ThreadContainerProps) {
    - + }> {isEmpty && } {isEmpty && !showMessageSkeleton && composer} {showMessageSkeleton ? ( @@ -108,12 +116,20 @@ export function ThreadContainer({ composer }: ThreadContainerProps) { {/* Startup has no remote id yet. An open session keeps the composer while history loads. */} {!isEmpty && (remoteId != null || !showMessageSkeleton) && ( - - - - - {composer} - +
    + + + + + {composer} + +
    )}
    diff --git a/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx index f1916f928a..18c0628ad9 100644 --- a/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx +++ b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx @@ -33,6 +33,7 @@ import { SlotsProvider, useThemeMode, type SlotOverrides } from '../theme/SlotsP import type { LayoutProp, ThemeConfig } from '../theme/types.js'; import { getErrorMessage } from '../utils/getErrorMessage.js'; import { OnboardingGate } from './Onboarding/OnboardingGate.js'; +import { SessionArtifactsPanelProvider } from './SessionArtifactsPanelContext.js'; import { ToasterProvider } from './ToasterContainer.js'; import { TrueForgeChatProvider, type TrueForgeChatProviderProps } from './TrueForgeChatProvider.js'; import { useResolvedServer } from './useResolvedServer.js'; @@ -338,7 +339,11 @@ export function TrueForgeUIShell(props: TrueForgeUIShellProps) { } const server = resolved.server; - const layoutTree = ; + const layoutTree = ( + + + + ); // Outer toaster for sessions browser / chrome; nested ToasterProvider inside // TrueForgeChatProvider stays for hosts that mount chat alone. Analytics wraps diff --git a/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsx b/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsx index 61d456e4f0..8b10d6f4c0 100644 --- a/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsx +++ b/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsx @@ -3,13 +3,26 @@ import { useAuiState } from '@assistant-ui/react'; import { createContext, useCallback, useContext, useMemo, useRef, useState, type ReactNode } from 'react'; +import type { ArtifactFile } from '../server/types.js'; import { isNewChatView } from '../utils/isNewChatView.js'; +/** Files of a folder artifact; paths are relative to the folder root and `''` is the top level. */ +export type FilePreviewFolder = { + list: (path: string) => Promise; + loadFile: (path: string) => Promise; + /** Identity of the folder's contents; listings are cached under it, so a new version never reuses old ones. */ + cacheKey: string; + /** File opened when the folder opens, so it never starts on an empty preview; relative to the folder root. */ + entryPoint: string; +}; + export type SandboxFilePreviewTarget = { name: string; path: string; turnId: string; + /** For a folder target this reads the entry file; the panel itself previews files picked through `folder`. */ load: () => Promise; + folder?: FilePreviewFolder; }; export type FilePreviewPresentation = 'panel' | 'full'; diff --git a/packages/trueforge-ui/src/filePreview/folderFileTarget.ts b/packages/trueforge-ui/src/filePreview/folderFileTarget.ts new file mode 100644 index 0000000000..3361a6f492 --- /dev/null +++ b/packages/trueforge-ui/src/filePreview/folderFileTarget.ts @@ -0,0 +1,36 @@ +import { filenameFromPath } from '../utils/triggerBrowserDownload.js'; +import type { FilePreviewFolder, SandboxFilePreviewTarget } from './FilePreviewContext.js'; + +function folderFileTurnId({ folderTurnId, path }: { folderTurnId: string; path: string }): string { + return `${folderTurnId}:${path}`; +} + +/** Preview of one file inside a folder; it shares the folder's cache identity so each file caches on its own. */ +export function folderFileTarget({ + target, + folder, + path, +}: { + target: SandboxFilePreviewTarget; + folder: FilePreviewFolder; + path: string; +}): SandboxFilePreviewTarget { + return { + name: filenameFromPath(path), + path, + turnId: folderFileTurnId({ folderTurnId: target.turnId, path }), + load: () => folder.loadFile(path), + }; +} + +/** When a file is open from a folder's tree, the tree marks it as selected; any other preview marks nothing. */ +export function openFolderFilePath({ + target, + folderTurnId, +}: { + target: SandboxFilePreviewTarget | null; + folderTurnId: string; +}): string | null { + if (target == null) return null; + return target.turnId === folderFileTurnId({ folderTurnId, path: target.path }) ? target.path : null; +} diff --git a/packages/trueforge-ui/src/filePreview/previewPaneWidth.ts b/packages/trueforge-ui/src/filePreview/previewPaneWidth.ts index 10f74ea5c1..32bf09c968 100644 --- a/packages/trueforge-ui/src/filePreview/previewPaneWidth.ts +++ b/packages/trueforge-ui/src/filePreview/previewPaneWidth.ts @@ -1,7 +1,7 @@ /** 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; +const DEFAULT_PREVIEW_RATIO = 0.5; export function clampPreviewWidth({ requested, rowWidth }: { requested: number; rowWidth: number }): number { if (rowWidth <= 0) return requested; diff --git a/packages/trueforge-ui/src/filePreview/useFolderTree.ts b/packages/trueforge-ui/src/filePreview/useFolderTree.ts new file mode 100644 index 0000000000..beac2f9c09 --- /dev/null +++ b/packages/trueforge-ui/src/filePreview/useFolderTree.ts @@ -0,0 +1,103 @@ +'use client'; + +import { useCallback, useEffect, useRef, useState } from 'react'; + +import { useServerQueryClient } from '../server/queryClient.js'; +import { queryKeys } from '../server/queryKeys.js'; +import type { ArtifactFile } from '../server/types.js'; +import { artifactErrorMessage } from '../utils/artifactErrorMessage.js'; + +const LEVEL_ERROR_MESSAGE = "Couldn't load these files."; + +export type FolderLevel = + { status: 'loading' } | { status: 'error'; message: string } | { status: 'ready'; entries: ArtifactFile[] }; + +export type FolderTree = { + /** Loaded state per folder path; `''` is the top level. A folder missing here has not been opened yet. */ + levels: Readonly>; + expanded: ReadonlySet; + toggle: (path: string) => void; +}; + +/** Folders above a file, outermost first, each with its trailing slash: `a/b/c.txt` gives `a/`, `a/b/`. */ +function ancestorFolders(filePath: string): string[] { + const segments = filePath.split('/').slice(0, -1); + return segments.map((_, index) => `${segments.slice(0, index + 1).join('/')}/`); +} + +/** + * Lists a folder one level at a time. The top level loads on mount and each subfolder on its first expand, + * because the API has no recursive listing. A level that failed is retried the next time it is expanded. + * Listings are cached per folder version, so reopening a folder shows its files at once and revalidates when stale. + * `revealPath` opens the folders above a file from the start, so a file selected before the tree mounts is visible. + * State belongs to one folder, so the caller remounts it (by `key`) when a different folder opens. + */ +export function useFolderTree({ + cacheKey, + list, + revealPath, +}: { + cacheKey: string; + list: (path: string) => Promise; + revealPath?: string | undefined; +}): FolderTree { + const queryClient = useServerQueryClient(); + const [levels, setLevels] = useState>>({}); + const [expanded, setExpanded] = useState>( + () => new Set(revealPath === undefined ? [] : ancestorFolders(revealPath)), + ); + const listRef = useRef(list); + listRef.current = list; + const revealRef = useRef(revealPath); + + const load = useCallback( + (path: string) => { + const queryKey = queryKeys.artifacts.files({ artifactKey: cacheKey, path }); + const cached = queryClient.getQueryData(queryKey); + setLevels(current => ({ + ...current, + [path]: cached === undefined ? { status: 'loading' } : { status: 'ready', entries: cached }, + })); + queryClient + .fetchQuery({ queryKey, queryFn: () => listRef.current(path) }) + .then(entries => { + setLevels(current => ({ ...current, [path]: { status: 'ready', entries } })); + }) + .catch((error: unknown) => { + // A failed revalidation keeps the files already on screen. + setLevels(current => + current[path]?.status === 'ready' + ? current + : { + ...current, + [path]: { status: 'error', message: artifactErrorMessage({ error, fallback: LEVEL_ERROR_MESSAGE }) }, + }, + ); + }); + }, + [cacheKey, queryClient], + ); + + useEffect(() => { + load(''); + const reveal = revealRef.current; + if (reveal !== undefined) ancestorFolders(reveal).forEach(load); + }, [load]); + + const toggle = useCallback( + (path: string) => { + const opening = !expanded.has(path); + setExpanded(current => { + const next = new Set(current); + if (opening) next.add(path); + else next.delete(path); + return next; + }); + const level = levels[path]; + if (opening && (level === undefined || level.status === 'error')) load(path); + }, + [expanded, levels, load], + ); + + return { levels, expanded, toggle }; +} diff --git a/packages/trueforge-ui/src/filePreview/useLoadedFilePreview.ts b/packages/trueforge-ui/src/filePreview/useLoadedFilePreview.ts index 3f54a2a44f..e392656662 100644 --- a/packages/trueforge-ui/src/filePreview/useLoadedFilePreview.ts +++ b/packages/trueforge-ui/src/filePreview/useLoadedFilePreview.ts @@ -3,6 +3,7 @@ import { useEffect, useState } from 'react'; import type { FilePreviewView } from '../atoms/FilePreviewPanel.js'; +import { artifactErrorMessage } from '../utils/artifactErrorMessage.js'; import type { SandboxFilePreviewTarget } from './FilePreviewContext.js'; import { blobWithMimeType, readFilePreview } from './readFilePreview.js'; @@ -64,9 +65,10 @@ export function useLoadedFilePreview(target: SandboxFilePreviewTarget | null, re return; } setLoaded({ key, blob, view: result }); - } catch { + } catch (error) { if (!cancelled) { - setLoaded({ key, blob: null, view: { status: 'error', message: LOAD_ERROR_MESSAGE } }); + const message = artifactErrorMessage({ error, fallback: LOAD_ERROR_MESSAGE }); + setLoaded({ key, blob: null, view: { status: 'error', message } }); } } })(); diff --git a/packages/trueforge-ui/src/icons/IconRegistry.tsx b/packages/trueforge-ui/src/icons/IconRegistry.tsx index 88f6de68d1..1b4266c024 100644 --- a/packages/trueforge-ui/src/icons/IconRegistry.tsx +++ b/packages/trueforge-ui/src/icons/IconRegistry.tsx @@ -44,9 +44,11 @@ import { FileCode2, FileSpreadsheet, FileText, + Folder, GalleryHorizontalEnd, GripVertical, History, + Image, Info, Layers, Layers2, @@ -202,6 +204,8 @@ const defaults: Record = { file: File, 'gallery-horizontal-end': GalleryHorizontalEnd, 'file-code': FileCode2, + image: Image, + folder: Folder, 'file-spreadsheet': FileSpreadsheet, 'file-text': FileText, clone: Copy, diff --git a/packages/trueforge-ui/src/index.ts b/packages/trueforge-ui/src/index.ts index 65936581b6..e39a6f0cd2 100644 --- a/packages/trueforge-ui/src/index.ts +++ b/packages/trueforge-ui/src/index.ts @@ -108,6 +108,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 { FilePreviewFolderBrowser } from './atoms/FilePreviewFolderBrowser.js'; +export type { FilePreviewFolderBrowserProps } from './atoms/FilePreviewFolderBrowser.js'; export { FilePreviewPanel } from './atoms/FilePreviewPanel.js'; export type { FilePreviewPanelProps, FilePreviewView } from './atoms/FilePreviewPanel.js'; export { HistoryLoader } from './atoms/HistoryLoader.js'; @@ -158,6 +160,7 @@ export { UserMessageEdit } from './atoms/UserMessageEdit.js'; export type { UserMessageEditProps } from './atoms/UserMessageEdit.js'; export { WelcomeScreen } from './atoms/WelcomeScreen.js'; export type { WelcomeScreenProps } from './atoms/WelcomeScreen.js'; +export type { FolderLevel, FolderTree } from './filePreview/useFolderTree.js'; export { AnalyticsEvents, AnalyticsProvider, useTrackAnalytics, withSessionProps } from './analytics/index.js'; export type { AnalyticsConfig, AnalyticsEventProps, TrackAnalytics } from './analytics/index.js'; @@ -388,6 +391,7 @@ export type { AgentUIServer, ApprovalDecision, Artifact, + ArtifactFile, ArtifactServer, AuthenticateConnectorRequest, AutoModel, diff --git a/packages/trueforge-ui/src/layouts/DrawerLayout.tsx b/packages/trueforge-ui/src/layouts/DrawerLayout.tsx index dddba8887a..f6e1319201 100644 --- a/packages/trueforge-ui/src/layouts/DrawerLayout.tsx +++ b/packages/trueforge-ui/src/layouts/DrawerLayout.tsx @@ -33,6 +33,7 @@ export function DrawerLayout({ className }: { className?: string }) { const SessionsPage = useSlot('SessionsPage'); const ArtifactsPage = useSlot('ArtifactsPage'); const ShareChatButton = useSlot('ShareChatButton'); + const SessionArtifactsToggleButton = useSlot('SessionArtifactsToggleButton'); const SaveAgentButton = useSlot('SaveAgentButton'); const AgentUnsavedChangesStatus = useSlot('AgentUnsavedChangesStatus'); const SelectAgentEmptyState = useSlot('SelectAgentEmptyState'); @@ -121,6 +122,7 @@ export function DrawerLayout({ className }: { className?: string }) { <> + diff --git a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx b/packages/trueforge-ui/src/layouts/SidebarLayout.tsx index eb3e590d4e..a3a566bccd 100644 --- a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx +++ b/packages/trueforge-ui/src/layouts/SidebarLayout.tsx @@ -137,6 +137,14 @@ function CollapsedChatHistoryButton(): ReactNode { }; }, [open]); + const toggleOpen = () => { + shell?.setSettingsOpen(false); + shell?.setLibraryOpen(false); + shell?.setSessionsOpen(false); + shell?.setSchedulesOpen(false); + setOpen(value => !value); + }; + const trigger = ( @@ -486,6 +488,7 @@ function SidebarLayoutBody({ className }: { className?: string }) { const SessionsPage = useSlot('SessionsPage'); const ArtifactsPage = useSlot('ArtifactsPage'); const ShareChatButton = useSlot('ShareChatButton'); + const SessionArtifactsToggleButton = useSlot('SessionArtifactsToggleButton'); const ResetAgentBuilderButton = useSlot('ResetAgentBuilderButton'); const ClearChatButton = useSlot('ClearChatButton'); const SaveAgentButton = useSlot('SaveAgentButton'); @@ -606,6 +609,7 @@ function SidebarLayoutBody({ className }: { className?: string }) { <> + diff --git a/packages/trueforge-ui/src/layouts/StackChatPanel.tsx b/packages/trueforge-ui/src/layouts/StackChatPanel.tsx index ea82cdebac..dfce9ffb13 100644 --- a/packages/trueforge-ui/src/layouts/StackChatPanel.tsx +++ b/packages/trueforge-ui/src/layouts/StackChatPanel.tsx @@ -40,11 +40,17 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelPro const SessionsPage = useSlot('SessionsPage'); const ArtifactsPage = useSlot('ArtifactsPage'); const ShareChatButton = useSlot('ShareChatButton'); + const SessionArtifactsToggleButton = useSlot('SessionArtifactsToggleButton'); const SaveAgentButton = useSlot('SaveAgentButton'); const AgentUnsavedChangesStatus = useSlot('AgentUnsavedChangesStatus'); const SelectAgentEmptyState = useSlot('SelectAgentEmptyState'); const UserAvatar = useSlot('UserAvatar'); const isIdle = shell?.mode.status === 'idle'; + const closeSubViews = () => { + shell?.setLibraryOpen(false); + shell?.setSchedulesOpen(false); + shell?.setArtifactsOpen(false); + }; const settingsOpen = shell?.settingsOpen === true; const libraryOpen = shell?.libraryOpen === true; const sessionsOpen = shell?.sessionsOpen === true; @@ -181,6 +187,7 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelPro <> + @@ -198,11 +205,7 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelPro
    , fileOpen: false }} + />, + ); + + expect(screen.getByText('file tree')).toBeVisible(); + expect(screen.getByText('Select a file to preview')).toBeVisible(); + expect(screen.queryByRole('button', { name: /^Download/ })).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Reload preview' })).not.toBeInTheDocument(); + expect(screen.queryByRole('status')).not.toBeInTheDocument(); + }); + + it('keeps the file list on the left of the open file while minimized', () => { + render( + Home' }} + onClose={vi.fn()} + onDownload={vi.fn()} + onReload={vi.fn()} + folder={{ browser:
    file tree
    , fileOpen: true }} + />, + ); + + const tree = screen.getByText('file tree'); + const frame = screen.getByTitle('Site/index.html'); + expect(tree).toBeVisible(); + expect(frame).toHaveAttribute('srcdoc', '

    Home

    '); + expect(tree.compareDocumentPosition(frame) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy(); + expect(screen.queryByText('Select a file to preview')).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Download Site/index.html' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Reload preview' })).toBeInTheDocument(); + }); + + it('hides the file list when maximized on an open file, but not before one is picked', () => { + const { rerender } = render( + Home' }} + onClose={vi.fn()} + onDownload={vi.fn()} + folder={{ browser:
    file tree
    , fileOpen: true }} + />, + ); + expect(screen.getByText('file tree')).not.toBeVisible(); + expect(screen.getByTitle('Site/index.html')).toBeVisible(); + + rerender( + file tree
    , fileOpen: false }} + />, + ); + expect(screen.getByText('file tree')).toBeVisible(); + }); }); function rect(width: number): DOMRect { diff --git a/packages/trueforge-ui/test/atoms/ThreadShell.test.tsx b/packages/trueforge-ui/test/atoms/ThreadShell.test.tsx index 7f1875ea1e..97f5661674 100644 --- a/packages/trueforge-ui/test/atoms/ThreadShell.test.tsx +++ b/packages/trueforge-ui/test/atoms/ThreadShell.test.tsx @@ -32,8 +32,14 @@ describe('ThreadViewportShell', () => { expect(viewport).toHaveAttribute('data-slot', 'aui_thread-viewport'); // CSS smooth scroll fights assistant-ui autoScroll and causes bounce on large streams. expect(viewport.className).not.toMatch(/\bscroll-smooth\b/); - expect(viewport.firstElementChild).toHaveClass('min-h-full', 'justify-center', 'pb-4'); - expect(viewport.firstElementChild).toHaveStyle({ maxWidth: 'var(--thread-max-width, 44rem)' }); + expect(viewport.querySelector('[data-slot="aui_thread-content"]')).toHaveClass( + 'min-h-full', + 'justify-center', + 'pb-4', + ); + expect(viewport.querySelector('[data-slot="aui_thread-content"]')).toHaveStyle({ + maxWidth: 'var(--thread-max-width, 44rem)', + }); expect(viewport).toHaveTextContent('Welcome'); rerender( @@ -41,8 +47,8 @@ describe('ThreadViewportShell', () => {

    Messages

    , ); - expect(viewport.firstElementChild).toHaveClass('pb-32'); - expect(viewport.firstElementChild).not.toHaveClass('justify-center'); + expect(viewport.querySelector('[data-slot="aui_thread-content"]')).toHaveClass('pb-32'); + expect(viewport.querySelector('[data-slot="aui_thread-content"]')).not.toHaveClass('justify-center'); }); it('can leave scrolling to a parent surface', () => { @@ -52,10 +58,24 @@ describe('ThreadViewportShell', () => { expect(screen.getByTestId('viewport')).not.toHaveClass('overflow-y-auto'); }); + it('keeps the message row from flex-shrinking so sticky asides can pin', () => { + render( + Artifacts}> +

    Messages

    +
    , + ); + + const content = screen.getByTestId('viewport').querySelector('[data-slot="aui_thread-content"]'); + expect(content?.parentElement).toHaveClass('min-h-full', 'shrink-0'); + expect(screen.getByTestId('aside')).toBeInTheDocument(); + }); + it('supports a wider content surface without changing the default', () => { render(); - expect(screen.getByTestId('viewport').firstElementChild).toHaveStyle({ maxWidth: '60rem' }); + expect(screen.getByTestId('viewport').querySelector('[data-slot="aui_thread-content"]')).toHaveStyle({ + maxWidth: '60rem', + }); }); }); diff --git a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx index 6b1077f865..8cd23a2896 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx +++ b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom import { AssistantRuntimeProvider, useExternalStoreRuntime, type ThreadMessageLike } from '@assistant-ui/react'; -import { fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { fireEvent, render, screen, waitFor, within } from '@testing-library/react'; import { useEffect, useRef, type ReactNode } from 'react'; import { beforeAll, describe, expect, it, vi } from 'vitest'; @@ -8,16 +8,20 @@ import { ArtifactsButton } from '@/atoms/ArtifactsButton.js'; import { ArtifactsPage } from '@/atoms/artifacts/ArtifactsPage.js'; import { ServerProvider } from '@/server/ServerContext.js'; import { ShellModeProvider, useOptionalShellMode } from '@/server/ShellModeContext.js'; -import type { Artifact, ArtifactServer } from '@/server/types.js'; +import type { Artifact, ArtifactFile, ArtifactServer } from '@/server/types.js'; import { createMockAgentUIServer, createMockArtifactServer, createMockCatalog } from '../../server/mockServer.js'; const subject = { subjectId: 'user-1', subjectType: 'user', subjectDisplayName: 'alice' }; -function artifact(overrides: Partial & Pick): Artifact { +function artifact({ + isDir = false, + ...overrides +}: Partial & Pick & { isDir?: boolean }): Artifact { return { createdBySubject: subject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', + filesMetadata: { isDir, sizeBytes: 10, entryPoint: isDir ? 'index.html' : 'index.md' }, ...overrides, }; } @@ -62,11 +66,13 @@ beforeAll(() => { }); describe('ArtifactsPage', () => { - it('lists artifacts with the creator name and without type or version', async () => { + it('lists artifacts with their size and without creator, type or version', async () => { renderWith(createMockArtifactServer({ listArtifacts: vi.fn(async () => ({ data: sample })) })); expect(await screen.findByText('Q4 brief')).toBeInTheDocument(); - expect(screen.getByRole('columnheader', { name: 'Created by' })).toBeInTheDocument(); - expect(screen.getAllByText('alice')).toHaveLength(2); + expect(screen.getByRole('columnheader', { name: 'Size' })).toBeInTheDocument(); + expect(screen.getAllByText('0.01 KB')).toHaveLength(2); + expect(screen.queryByRole('columnheader', { name: 'Created by' })).not.toBeInTheDocument(); + expect(screen.queryByText('alice')).not.toBeInTheDocument(); expect(screen.queryByRole('columnheader', { name: 'Type' })).not.toBeInTheDocument(); expect(screen.queryByRole('columnheader', { name: 'Version' })).not.toBeInTheDocument(); expect(screen.queryByText('v2')).not.toBeInTheDocument(); @@ -166,11 +172,128 @@ describe('ArtifactsPage', () => { await screen.findByText('Q4 brief'); fireEvent.click(screen.getByRole('button', { name: 'Actions for Q4 brief' })); await screen.findByRole('menuitem', { name: 'Edit' }); + expect(screen.queryByRole('menuitem', { name: 'Open' })).not.toBeInTheDocument(); expect(screen.queryByRole('menuitem', { name: 'Share' })).not.toBeInTheDocument(); expect(screen.queryByRole('menuitem', { name: 'Delete' })).not.toBeInTheDocument(); }); }); +describe('ArtifactsPage folder artifacts', () => { + const site = artifact({ id: 'f1', name: 'Dummy site', isDir: true }); + const listing: Record = { + '': [ + { path: 'assets/', isDir: true, size: null, lastModified: null }, + { path: 'index.html', isDir: false, size: 10, lastModified: null }, + ], + 'assets/': [{ path: 'assets/app.js', isDir: false, size: 5, lastModified: null }], + }; + + function folderServer() { + const listArtifactFiles = vi.fn(async ({ path = '' }: { id: string; path?: string }) => listing[path] ?? []); + const readArtifactFile = vi.fn( + async ({ path }: { id: string; path?: string }) => + new Blob([`contents of ${path ?? 'entry'}`], { type: 'text/plain' }), + ); + const server = createMockArtifactServer({ + listArtifacts: async () => ({ data: [site, q4Brief] }), + listArtifactFiles, + readArtifactFile, + }); + return { listArtifactFiles, readArtifactFile, server }; + } + + it('opens on the entry file with the folder files beside it, and previews each file as it is selected', async () => { + const { listArtifactFiles, readArtifactFile, server } = folderServer(); + renderWith(server); + + fireEvent.click(await screen.findByText('Dummy site')); + const panel = await screen.findByRole('complementary', { name: 'Preview of index.html' }); + expect(await within(panel).findByRole('button', { name: /^index\.html/ })).toHaveAttribute('aria-current', 'true'); + expect(listArtifactFiles).toHaveBeenCalledWith({ id: 'f1', path: '' }); + await waitFor(() => expect(readArtifactFile).toHaveBeenCalledWith({ id: 'f1', path: 'index.html' })); + expect(within(panel).getByRole('button', { name: 'Download index.html' })).toBeInTheDocument(); + + fireEvent.click(within(panel).getByRole('button', { name: /^assets$/ })); + await waitFor(() => expect(listArtifactFiles).toHaveBeenCalledWith({ id: 'f1', path: 'assets/' })); + fireEvent.click(await within(panel).findByRole('button', { name: /app\.js/ })); + + await waitFor(() => expect(readArtifactFile).toHaveBeenCalledWith({ id: 'f1', path: 'assets/app.js' })); + const filePanel = await screen.findByRole('complementary', { name: 'Preview of app.js' }); + await waitFor(() => expect(filePanel).toHaveTextContent('contents of assets/app.js')); + expect(within(filePanel).getByRole('button', { name: 'Download app.js' })).toBeInTheDocument(); + + // The list stays beside the preview, so another file is one click away. + expect(within(filePanel).getByRole('button', { name: /^app\.js/ })).toHaveAttribute('aria-current', 'true'); + fireEvent.click(within(filePanel).getByRole('button', { name: /^index\.html/ })); + await waitFor(() => expect(readArtifactFile).toHaveBeenCalledWith({ id: 'f1', path: 'index.html' })); + expect(await screen.findByRole('complementary', { name: 'Preview of index.html' })).toBeInTheDocument(); + }); + + it('starts on the entry file again when a folder is reopened after another file was picked', async () => { + const { server } = folderServer(); + renderWith(server); + + fireEvent.click(await screen.findByText('Dummy site')); + const panel = await screen.findByRole('complementary', { name: 'Preview of index.html' }); + fireEvent.click(within(panel).getByRole('button', { name: /^assets$/ })); + fireEvent.click(await within(panel).findByRole('button', { name: /app\.js/ })); + await screen.findByRole('complementary', { name: 'Preview of app.js' }); + + fireEvent.click(screen.getByRole('button', { name: 'Close preview' })); + await waitFor(() => expect(screen.queryByRole('complementary')).not.toBeInTheDocument()); + + fireEvent.click(screen.getByText('Dummy site')); + const reopened = await screen.findByRole('complementary', { name: 'Preview of index.html' }); + expect(await within(reopened).findByRole('button', { name: /^index\.html/ })).toHaveAttribute( + 'aria-current', + 'true', + ); + }); + + it('tells a viewer without access, instead of a generic failure, when the files are refused', async () => { + const forbidden = Object.assign(new Error('Forbidden'), { statusCode: 403 }); + const { server } = folderServer(); + renderWith({ + ...server, + listArtifactFiles: vi.fn(async () => Promise.reject(forbidden)), + readArtifactFile: vi.fn(async () => Promise.reject(forbidden)), + }); + + fireEvent.click(await screen.findByText('Dummy site')); + const panel = await screen.findByRole('complementary', { name: 'Preview of index.html' }); + expect(await within(panel).findAllByText("You don't have access to open this artifact.")).toHaveLength(2); + expect(screen.queryByText("Couldn't load these files.")).not.toBeInTheDocument(); + }); + + it('marks each row with a folder or file icon from its folder flag', async () => { + const { server } = folderServer(); + renderWith(server); + + const folderRow = (await screen.findByText('Dummy site')).closest('tr'); + const fileRow = screen.getByText('Q4 brief').closest('tr'); + if (folderRow == null || fileRow == null) throw new Error('Expected both artifact rows to render'); + expect(folderRow.querySelector('svg.lucide-folder')).not.toBeNull(); + expect(fileRow.querySelector('svg.lucide-folder')).toBeNull(); + expect(fileRow.querySelector('svg.lucide-file')).not.toBeNull(); + }); + + it('offers no Download for a folder, and keeps it for a file', async () => { + const { server } = folderServer(); + const { unmount } = renderWith(server); + await screen.findByText('Dummy site'); + + fireEvent.click(screen.getByRole('button', { name: 'Actions for Dummy site' })); + await screen.findByRole('menuitem', { name: 'Edit' }); + expect(screen.queryByRole('menuitem', { name: 'Download' })).not.toBeInTheDocument(); + unmount(); + + renderWith(server); + await screen.findByText('Q4 brief'); + fireEvent.click(screen.getByRole('button', { name: 'Actions for Q4 brief' })); + expect(await screen.findByRole('menuitem', { name: 'Download' })).toBeInTheDocument(); + }); +}); + describe('ArtifactsButton', () => { it('renders only when the artifacts port exists', () => { const withoutPort = renderWith(undefined, ); diff --git a/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx new file mode 100644 index 0000000000..a8bb587173 --- /dev/null +++ b/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx @@ -0,0 +1,134 @@ +// @vitest-environment jsdom +import { fireEvent, render, screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; + +import { artifactPreviewKey } from '@/atoms/artifacts/artifactDisplay.js'; +import { SessionArtifactsCard } from '@/atoms/artifacts/SessionArtifactsCard.js'; +import type { Artifact } from '@/server/types.js'; + +const subject = { subjectId: 'user-1', subjectType: 'user', subjectDisplayName: 'alice' }; + +function artifact(id: string, name: string): Artifact { + return { + id, + name, + createdBySubject: subject, + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-02T00:00:00.000Z', + filesMetadata: { isDir: false, sizeBytes: 10, entryPoint: name }, + }; +} + +const folderMetadata: Artifact['filesMetadata'] = { isDir: true, sizeBytes: 10, entryPoint: 'index.html' }; + +const names = ['a.png', 'b.html', 'c.csv', 'd.md', 'e.pdf', 'f.txt', 'g.png', 'h.png']; +const artifacts = names.map((name, index) => artifact(`id-${String(index)}`, name)); + +describe('SessionArtifactsCard', () => { + it('shows six rows without type labels and a "Show N more" toggle', () => { + const onShowMore = vi.fn(); + render( + , + ); + + expect(screen.getByRole('heading', { name: 'Artifacts' })).toBeInTheDocument(); + expect(screen.getByText('a.png')).toBeInTheDocument(); + expect(screen.getByText('f.txt')).toBeInTheDocument(); + expect(screen.queryByText('g.png')).not.toBeInTheDocument(); + for (const label of ['Image', 'Html', 'Pdf', 'File']) { + expect(screen.queryByText(label)).not.toBeInTheDocument(); + } + + fireEvent.click(screen.getByRole('button', { name: 'Show 2 more' })); + expect(onShowMore).toHaveBeenCalledTimes(1); + expect(screen.getByText('g.png')).toBeInTheDocument(); + expect(screen.getByText('h.png')).toBeInTheDocument(); + + fireEvent.click(screen.getByRole('button', { name: 'Show less' })); + expect(screen.queryByText('g.png')).not.toBeInTheDocument(); + expect(onShowMore).toHaveBeenCalledTimes(1); + }); + + it('shows a folder icon, not a type label, for a folder artifact', () => { + const folder: Artifact = { ...artifact('folder-1', 'Dummy HTML CSS JS'), filesMetadata: folderMetadata }; + render(); + + const row = screen.getByRole('button', { name: 'Dummy HTML CSS JS' }); + expect(row.querySelector('svg.lucide-folder')).not.toBeNull(); + expect(screen.queryByText('Folder')).not.toBeInTheDocument(); + }); + + it('shows skeleton rows instead of the empty state while the list loads', () => { + render(); + + expect(screen.getByRole('status', { name: 'Loading artifacts' })).toBeInTheDocument(); + expect(screen.getByRole('heading', { name: 'Artifacts' })).toBeInTheDocument(); + expect(screen.queryByText('No artifacts yet')).not.toBeInTheDocument(); + }); + + it('expands a folder row in place to list its files, and collapses it again', () => { + const folder: Artifact = { ...artifact('folder-1', 'Site'), filesMetadata: folderMetadata }; + const renderFolderFiles = vi.fn(() =>
    folder files
    ); + const onToggleFolder = vi.fn(); + const onOpen = vi.fn(); + render( + , + ); + + const row = screen.getByRole('button', { name: /Site/ }); + expect(row).toHaveAttribute('aria-expanded', 'false'); + expect(screen.queryByText('folder files')).not.toBeInTheDocument(); + + fireEvent.click(row); + expect(row).toHaveAttribute('aria-expanded', 'true'); + expect(screen.getByText('folder files')).toBeInTheDocument(); + expect(renderFolderFiles).toHaveBeenCalledWith(folder); + expect(onToggleFolder).toHaveBeenCalledWith(folder); + // Expanding previews the entry file; collapsing does not close or reopen it. + expect(onOpen).toHaveBeenCalledTimes(1); + expect(onOpen).toHaveBeenCalledWith(folder); + + fireEvent.click(row); + expect(onOpen).toHaveBeenCalledTimes(1); + expect(row).toHaveAttribute('aria-expanded', 'false'); + expect(screen.queryByText('folder files')).not.toBeInTheDocument(); + }); + + it('opens a folder row like a file when the host gives no way to list its files', () => { + const folder: Artifact = { ...artifact('folder-1', 'Site'), filesMetadata: folderMetadata }; + const onOpen = vi.fn(); + render(); + + const row = screen.getByRole('button', { name: /Site/ }); + expect(row).not.toHaveAttribute('aria-expanded'); + fireEvent.click(row); + expect(onOpen).toHaveBeenCalledWith(folder); + }); + + it('shows an empty state without rows', () => { + render(); + expect(screen.getByText('No artifacts yet')).toBeInTheDocument(); + }); + + it('hides the toggle when everything fits', () => { + render(); + expect(screen.queryByRole('button', { name: /Show/ })).not.toBeInTheDocument(); + }); + + it('opens an artifact on row click and marks the selected one', () => { + const onOpen = vi.fn(); + const selected = artifacts[1]; + if (selected === undefined) throw new Error('missing fixture'); + render(); + + fireEvent.click(screen.getByRole('button', { name: /a\.png/ })); + expect(onOpen).toHaveBeenCalledWith(artifacts[0]); + expect(screen.getByRole('button', { name: /b\.html/ })).toHaveClass('bg-secondary-button-hover'); + }); +}); diff --git a/packages/trueforge-ui/test/atoms/artifacts/artifactDisplay.test.ts b/packages/trueforge-ui/test/atoms/artifacts/artifactDisplay.test.ts new file mode 100644 index 0000000000..d6a98ecfe3 --- /dev/null +++ b/packages/trueforge-ui/test/atoms/artifacts/artifactDisplay.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { artifactPreviewTarget, artifactType } from '@/atoms/artifacts/artifactDisplay.js'; +import type { Artifact } from '@/server/types.js'; + +import { createMockArtifactServer } from '../../server/mockServer.js'; + +const subject = { subjectId: 'user-1', subjectType: 'user', subjectDisplayName: 'alice' } as const; + +function artifact({ isDir = false, ...overrides }: Partial & { isDir?: boolean } = {}): Artifact { + return { + id: 'a1', + name: 'Dummy HTML CSS JS', + createdBySubject: subject, + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-02T00:00:00.000Z', + filesMetadata: { isDir, sizeBytes: 10, entryPoint: 'index.html' }, + ...overrides, + }; +} + +describe('artifactType', () => { + it('labels a folder artifact as a folder whatever its name looks like', () => { + expect(artifactType({ name: 'report.pdf', isDir: true })).toEqual({ label: 'Folder', icon: 'folder' }); + expect(artifactType({ name: 'Dummy HTML CSS JS', isDir: true })).toEqual({ label: 'Folder', icon: 'folder' }); + }); + + it('keeps deriving file types from the extension', () => { + expect(artifactType({ name: 'chart.png', isDir: false })).toEqual({ label: 'Image', icon: 'image' }); + expect(artifactType({ name: 'notes', isDir: false })).toEqual({ label: 'File', icon: 'file' }); + }); + + it('labels media files as plain files, since they cannot be previewed', () => { + expect(artifactType({ name: 'clip.mp4', isDir: false })).toEqual({ label: 'File', icon: 'file' }); + expect(artifactType({ name: 'voice.mp3', isDir: false })).toEqual({ label: 'File', icon: 'file' }); + }); +}); + +describe('artifactPreviewTarget', () => { + it('previews a single-file artifact through its entry file', async () => { + const readArtifactFile = vi.fn(async () => new Blob(['x'])); + const target = artifactPreviewTarget({ + artifact: artifact({ isDir: false }), + artifactServer: createMockArtifactServer({ readArtifactFile }), + }); + + // The entry file's extension, not the artifact name, decides how the preview renders. + expect(target).toMatchObject({ name: 'Dummy HTML CSS JS', path: 'index.html' }); + expect(target.folder).toBeUndefined(); + await target.load(); + expect(readArtifactFile).toHaveBeenCalledWith({ id: 'a1' }); + }); + + it('gives a folder artifact a folder source that lists and reads by path', async () => { + const listArtifactFiles = vi.fn(async () => [{ path: 'index.html', isDir: false, size: 10, lastModified: null }]); + const readArtifactFile = vi.fn(async () => new Blob(['x'])); + const target = artifactPreviewTarget({ + artifact: artifact({ isDir: true }), + artifactServer: createMockArtifactServer({ listArtifactFiles, readArtifactFile }), + }); + + expect(target.folder).toBeDefined(); + expect(target.folder?.entryPoint).toBe('index.html'); + await expect(target.folder?.list('')).resolves.toEqual([ + { path: 'index.html', isDir: false, size: 10, lastModified: null }, + ]); + expect(listArtifactFiles).toHaveBeenCalledWith({ id: 'a1', path: '' }); + + await target.folder?.loadFile('data/a.csv'); + expect(readArtifactFile).toHaveBeenCalledWith({ id: 'a1', path: 'data/a.csv' }); + }); + + it('reads the entry file by path for a folder artifact, which has no single file', async () => { + const readArtifactFile = vi.fn(async () => new Blob(['x'])); + const target = artifactPreviewTarget({ + artifact: artifact({ isDir: true }), + artifactServer: createMockArtifactServer({ readArtifactFile }), + }); + + await target.load(); + expect(readArtifactFile).toHaveBeenCalledWith({ id: 'a1', path: 'index.html' }); + }); +}); + +describe('artifactPreviewTarget with a file path', () => { + it('previews just that file of a folder artifact, named after the file', async () => { + const readArtifactFile = vi.fn(async () => new Blob(['x'])); + const target = artifactPreviewTarget({ + artifact: artifact({ isDir: true }), + artifactServer: createMockArtifactServer({ readArtifactFile }), + filePath: 'data/a.csv', + }); + + expect(target).toMatchObject({ name: 'a.csv', path: 'data/a.csv' }); + expect(target.folder).toBeUndefined(); + await target.load(); + expect(readArtifactFile).toHaveBeenCalledWith({ id: 'a1', path: 'data/a.csv' }); + }); + + it('ignores the file path for a single-file artifact', () => { + const target = artifactPreviewTarget({ + artifact: artifact({ isDir: false }), + artifactServer: createMockArtifactServer(), + filePath: 'data/a.csv', + }); + + expect(target.name).toBe('Dummy HTML CSS JS'); + expect(target.folder).toBeUndefined(); + }); +}); diff --git a/packages/trueforge-ui/test/atoms/artifacts/carryFileListings.test.ts b/packages/trueforge-ui/test/atoms/artifacts/carryFileListings.test.ts new file mode 100644 index 0000000000..e785a00d51 --- /dev/null +++ b/packages/trueforge-ui/test/atoms/artifacts/carryFileListings.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest'; + +import { carryFileListings } from '@/atoms/artifacts/carryFileListings.js'; +import { createServerQueryClient } from '@/server/queryClient.js'; +import { queryKeys } from '@/server/queryKeys.js'; +import type { ArtifactFile } from '@/server/types.js'; + +const file: ArtifactFile = { path: 'index.html', isDir: false, size: 10, lastModified: null }; +const nested: ArtifactFile = { path: 'assets/app.js', isDir: false, size: 5, lastModified: null }; + +describe('carryFileListings', () => { + it('moves every cached level of one artifact version to the new version key', () => { + const queryClient = createServerQueryClient(); + queryClient.setQueryData(queryKeys.artifacts.files({ artifactKey: 'a1@v1', path: '' }), [file]); + queryClient.setQueryData(queryKeys.artifacts.files({ artifactKey: 'a1@v1', path: 'assets/' }), [nested]); + queryClient.setQueryData(queryKeys.artifacts.files({ artifactKey: 'a2@v1', path: '' }), [file]); + + carryFileListings({ queryClient, from: 'a1@v1', to: 'a1@v2' }); + + expect(queryClient.getQueryData(queryKeys.artifacts.files({ artifactKey: 'a1@v2', path: '' }))).toEqual([file]); + expect(queryClient.getQueryData(queryKeys.artifacts.files({ artifactKey: 'a1@v2', path: 'assets/' }))).toEqual([ + nested, + ]); + expect(queryClient.getQueryData(queryKeys.artifacts.files({ artifactKey: 'a2@v2', path: '' }))).toBeUndefined(); + }); + + it('does nothing when the key did not change', () => { + const queryClient = createServerQueryClient(); + queryClient.setQueryData(queryKeys.artifacts.files({ artifactKey: 'a1@v1', path: '' }), [file]); + + carryFileListings({ queryClient, from: 'a1@v1', to: 'a1@v1' }); + + expect(queryClient.getQueryCache().getAll()).toHaveLength(1); + }); +}); diff --git a/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx new file mode 100644 index 0000000000..2e75de905a --- /dev/null +++ b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx @@ -0,0 +1,329 @@ +// @vitest-environment jsdom +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { AnalyticsProvider } from '@/analytics/AnalyticsProvider.js'; +import { AnalyticsEvents } from '@/analytics/events.js'; +import { SessionArtifactsToggleButton } from '@/atoms/artifacts/SessionArtifactsToggleButton.js'; +import { CompactLayoutProvider } from '@/atoms/lib/CompactLayoutContext.js'; +import { SESSION_ARTIFACTS_RUN_POLL_MS, SessionArtifactsContainer } from '@/containers/SessionArtifactsContainer.js'; +import { SessionArtifactsPanelProvider } from '@/containers/SessionArtifactsPanelContext.js'; +import { FilePreviewProvider, useFilePreview } from '@/filePreview/FilePreviewContext.js'; +import { ServerProvider } from '@/server/ServerContext.js'; +import type { Artifact } from '@/server/types.js'; +import { SlotsProvider } from '@/theme/SlotsProvider.js'; +import { createMockAgentUIServer, createMockArtifactServer, createMockCatalog } from '../server/mockServer.js'; + +const runtimeState = vi.hoisted(() => ({ remoteId: 's1' as string | null, isRunning: false })); + +vi.mock('@assistant-ui/react', () => ({ + useAuiState: (selector: (state: unknown) => unknown) => + selector({ + thread: { isRunning: runtimeState.isRunning, isLoading: false, messages: [] }, + threads: { isLoading: false }, + threadListItem: { id: 't1', remoteId: runtimeState.remoteId }, + }), +})); + +const subject = { subjectId: 'user-1', subjectType: 'user', subjectDisplayName: 'alice' }; + +function artifact(id: string, name: string): Artifact { + return { + id, + name, + createdBySubject: subject, + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-02T00:00:00.000Z', + filesMetadata: { isDir: false, sizeBytes: 10, entryPoint: name }, + }; +} + +const folderMetadata: Artifact['filesMetadata'] = { isDir: true, sizeBytes: 10, entryPoint: 'index.html' }; + +function siteFolder(updatedAt = '2024-01-02T00:00:00.000Z'): Artifact { + return { ...artifact('f1', 'Dummy site'), updatedAt, filesMetadata: folderMetadata }; +} + +async function listSiteFiles({ path = '' }: { id: string; path?: string }) { + return Promise.resolve( + path === '' + ? [ + { path: 'assets/', isDir: true, size: null, lastModified: null }, + { path: 'index.html', isDir: false, size: 10, lastModified: null }, + ] + : [{ path: 'assets/app.js', isDir: false, size: 5, lastModified: null }], + ); +} + +function PreviewProbe() { + const { target } = useFilePreview(); + return ( + <> + {target?.name ?? 'none'} + {/* FilePreviewHost is not mounted here, so reading the file is triggered by hand. */} + + + ); +} + +function renderContainer({ + artifacts, + track, + withToggle = false, + defaultOpen = true, + compact = false, +}: { + artifacts: ReturnType | undefined; + track?: (eventName: string, data?: Record) => void; + withToggle?: boolean; + defaultOpen?: boolean; + compact?: boolean; +}) { + const server = createMockAgentUIServer({ + catalog: createMockCatalog(), + ...(artifacts === undefined ? {} : { artifacts }), + }); + const tree = ( + + + + + + {withToggle ? : null} + + + + + + + + ); + return render(compact ? {tree} : tree); +} + +describe('SessionArtifactsContainer', () => { + beforeEach(() => { + runtimeState.remoteId = 's1'; + runtimeState.isRunning = false; + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('polls the session list while a run is active', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + runtimeState.isRunning = true; + const listSessionArtifacts = vi.fn(async () => [artifact('a1', 'report.html')]); + renderContainer({ artifacts: createMockArtifactServer({ listSessionArtifacts }) }); + + await waitFor(() => expect(listSessionArtifacts).toHaveBeenCalledTimes(1)); + await act(() => vi.advanceTimersByTimeAsync(SESSION_ARTIFACTS_RUN_POLL_MS)); + expect(listSessionArtifacts.mock.calls.length).toBeGreaterThanOrEqual(2); + }); + + it('does not poll once the run is idle', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + const listSessionArtifacts = vi.fn(async () => [artifact('a1', 'report.html')]); + renderContainer({ artifacts: createMockArtifactServer({ listSessionArtifacts }) }); + + await waitFor(() => expect(listSessionArtifacts).toHaveBeenCalledTimes(1)); + await act(() => vi.advanceTimersByTimeAsync(SESSION_ARTIFACTS_RUN_POLL_MS * 2)); + expect(listSessionArtifacts).toHaveBeenCalledTimes(1); + }); + + it('shows skeleton rows until the first list arrives', async () => { + let resolveList: (artifacts: Artifact[]) => void = () => undefined; + const listSessionArtifacts = vi.fn( + () => + new Promise(resolve => { + resolveList = resolve; + }), + ); + renderContainer({ artifacts: createMockArtifactServer({ listSessionArtifacts }) }); + + expect(await screen.findByRole('status', { name: 'Loading artifacts' })).toBeInTheDocument(); + expect(screen.queryByText('No artifacts yet')).not.toBeInTheDocument(); + + resolveList([artifact('a1', 'report.html')]); + expect(await screen.findByText('report.html')).toBeInTheDocument(); + expect(screen.queryByRole('status', { name: 'Loading artifacts' })).not.toBeInTheDocument(); + }); + + it('lists a folder artifact as a tree, previews its entry file and opens a picked file on its own', async () => { + const listSessionArtifacts = vi.fn(async () => [siteFolder()]); + const listArtifactFiles = vi.fn(listSiteFiles); + const track = vi.fn(); + renderContainer({ + artifacts: createMockArtifactServer({ listSessionArtifacts, listArtifactFiles }), + track, + }); + + fireEvent.click(await screen.findByRole('button', { name: /Dummy site/ })); + expect(screen.getByLabelText('Preview target')).toHaveTextContent('index.html'); + expect(await screen.findByRole('button', { name: /index\.html/ })).toBeInTheDocument(); + expect(listArtifactFiles).toHaveBeenCalledWith({ id: 'f1', path: '' }); + expect(track).toHaveBeenCalledWith(AnalyticsEvents.Artifact.SESSION_CARD_FOLDER_TOGGLED, { artifact_id: 'f1' }); + + fireEvent.click(screen.getByRole('button', { name: /^assets$/ })); + fireEvent.click(await screen.findByRole('button', { name: /app\.js/ })); + expect(listArtifactFiles).toHaveBeenCalledWith({ id: 'f1', path: 'assets/' }); + // The card already is the tree, so the preview opens on the picked file alone. + expect(screen.getByLabelText('Preview target')).toHaveTextContent('app.js'); + expect(screen.getByLabelText('Preview target')).not.toHaveTextContent('Dummy site'); + expect(track).toHaveBeenCalledWith(AnalyticsEvents.Artifact.SESSION_CARD_PREVIEW_OPENED, { artifact_id: 'f1' }); + }); + + it('marks the previewed file as selected and leaves the folder row plain, starting with the entry file', async () => { + const listSessionArtifacts = vi.fn(async () => [siteFolder()]); + renderContainer({ + artifacts: createMockArtifactServer({ listSessionArtifacts, listArtifactFiles: listSiteFiles }), + }); + + const folderRow = await screen.findByRole('button', { name: /Dummy site/ }); + fireEvent.click(folderRow); + const file = await screen.findByRole('button', { name: /index\.html/ }); + expect(file).toHaveAttribute('aria-current', 'true'); + expect(folderRow).not.toHaveClass('bg-secondary-button-hover'); + + fireEvent.click(screen.getByRole('button', { name: /^assets$/ })); + fireEvent.click(await screen.findByRole('button', { name: /app\.js/ })); + expect(screen.getByLabelText('Preview target')).toHaveTextContent('app.js'); + expect(screen.getByRole('button', { name: /app\.js/ })).toHaveAttribute('aria-current', 'true'); + expect(screen.getByRole('button', { name: /index\.html/ })).not.toHaveAttribute('aria-current'); + expect(screen.getByRole('button', { name: /Dummy site/ })).not.toHaveClass('bg-secondary-button-hover'); + }); + + it('drops expanded subfolders when a new version of the folder arrives while a run polls', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + runtimeState.isRunning = true; + let updatedAt = '2024-01-02T00:00:00.000Z'; + const listSessionArtifacts = vi.fn(async () => [siteFolder(updatedAt)]); + renderContainer({ + artifacts: createMockArtifactServer({ listSessionArtifacts, listArtifactFiles: listSiteFiles }), + }); + + fireEvent.click(await screen.findByRole('button', { name: /Dummy site/ })); + fireEvent.click(await screen.findByRole('button', { name: /^assets$/ })); + expect(await screen.findByText('app.js')).toBeInTheDocument(); + + // The old version's subfolder listing must not outlive the version it was read from. + updatedAt = '2024-01-03T00:00:00.000Z'; + await act(() => vi.advanceTimersByTimeAsync(SESSION_ARTIFACTS_RUN_POLL_MS)); + expect(await screen.findByRole('button', { name: /index\.html/ })).toBeInTheDocument(); + expect(screen.queryByText('app.js')).not.toBeInTheDocument(); + }); + + it('lists the session artifacts and opens a preview from a row', async () => { + const listSessionArtifacts = vi.fn(async () => [artifact('a1', 'report.html')]); + const readArtifactFile = vi.fn(async () => new Blob(['

    hi

    '], { type: 'text/html' })); + const track = vi.fn(); + renderContainer({ artifacts: createMockArtifactServer({ listSessionArtifacts, readArtifactFile }), track }); + + fireEvent.click(await screen.findByText('report.html')); + + expect(listSessionArtifacts).toHaveBeenCalledWith({ sessionId: 's1' }); + expect(screen.getByLabelText('Preview target')).toHaveTextContent('report.html'); + fireEvent.click(screen.getByRole('button', { name: 'load preview' })); + expect(readArtifactFile).toHaveBeenCalledWith({ id: 'a1' }); + expect(track).toHaveBeenCalledWith(AnalyticsEvents.Artifact.SESSION_CARD_PREVIEW_OPENED, { artifact_id: 'a1' }); + }); + + it('hides the card when the header toggle turns it off and shows it again', async () => { + const listSessionArtifacts = vi.fn(async () => [artifact('a1', 'report.html')]); + const track = vi.fn(); + renderContainer({ + artifacts: createMockArtifactServer({ listSessionArtifacts }), + track, + withToggle: true, + }); + + expect(await screen.findByText('report.html')).toBeInTheDocument(); + const toggle = screen.getByRole('button', { name: 'Artifacts' }); + expect(toggle).toHaveAttribute('aria-pressed', 'true'); + + const column = () => screen.getByLabelText('Session artifacts').closest('[data-state]'); + expect(column()).toHaveAttribute('data-state', 'open'); + + fireEvent.click(toggle); + // The column collapses in place rather than unmounting, so it can animate. + expect(column()).toHaveAttribute('data-state', 'closed'); + expect(column()).toHaveClass('invisible'); + // Collapsed height keeps the scroll from holding space for the hidden card. + expect(column()).toHaveClass('h-0'); + expect(screen.getByRole('button', { name: 'Artifacts' })).toHaveAttribute('aria-pressed', 'false'); + expect(track).toHaveBeenCalledWith(AnalyticsEvents.Artifact.SESSION_CARD_TOGGLED, { open: false }); + + fireEvent.click(screen.getByRole('button', { name: 'Artifacts' })); + expect(column()).toHaveAttribute('data-state', 'open'); + expect(track).toHaveBeenCalledWith(AnalyticsEvents.Artifact.SESSION_CARD_TOGGLED, { open: true }); + }); + + it('keeps the toggle available and shows an empty state when the session has no artifacts', async () => { + const listSessionArtifacts = vi.fn(async () => []); + renderContainer({ artifacts: createMockArtifactServer({ listSessionArtifacts }), withToggle: true }); + + expect(screen.getByRole('button', { name: 'Artifacts' })).toBeInTheDocument(); + expect(await screen.findByText('No artifacts yet')).toBeInTheDocument(); + }); + + it('does not list or poll while closed, and refetches each time it is opened', async () => { + vi.useFakeTimers({ shouldAdvanceTime: true }); + runtimeState.isRunning = true; + const listSessionArtifacts = vi.fn(async () => [artifact('a1', 'report.html')]); + renderContainer({ + artifacts: createMockArtifactServer({ listSessionArtifacts }), + withToggle: true, + defaultOpen: false, + }); + + await act(() => vi.advanceTimersByTimeAsync(SESSION_ARTIFACTS_RUN_POLL_MS * 2)); + expect(listSessionArtifacts).not.toHaveBeenCalled(); + + fireEvent.click(screen.getByRole('button', { name: 'Artifacts' })); + expect(await screen.findByText('report.html')).toBeInTheDocument(); + expect(listSessionArtifacts).toHaveBeenCalledTimes(1); + + fireEvent.click(screen.getByRole('button', { name: 'Artifacts' })); + const callsWhileClosed = listSessionArtifacts.mock.calls.length; + await act(() => vi.advanceTimersByTimeAsync(SESSION_ARTIFACTS_RUN_POLL_MS * 2)); + expect(listSessionArtifacts).toHaveBeenCalledTimes(callsWhileClosed); + + fireEvent.click(screen.getByRole('button', { name: 'Artifacts' })); + await waitFor(() => expect(listSessionArtifacts.mock.calls.length).toBeGreaterThan(callsWhileClosed)); + }); + + it('hides the card and toggle in compact layouts, where there is no room beside the chat', () => { + const listSessionArtifacts = vi.fn(async () => [artifact('a1', 'report.html')]); + renderContainer({ + artifacts: createMockArtifactServer({ listSessionArtifacts }), + withToggle: true, + compact: true, + }); + + expect(screen.queryByRole('button', { name: 'Artifacts' })).not.toBeInTheDocument(); + expect(screen.queryByLabelText('Session artifacts')).not.toBeInTheDocument(); + expect(listSessionArtifacts).not.toHaveBeenCalled(); + }); + + it('hides the toggle until the thread has a stored session', () => { + runtimeState.remoteId = null; + renderContainer({ artifacts: createMockArtifactServer(), withToggle: true }); + + expect(screen.queryByRole('button', { name: 'Artifacts' })).not.toBeInTheDocument(); + }); + + it('renders nothing without an artifact server or a stored session', async () => { + const { unmount } = renderContainer({ artifacts: undefined }); + expect(screen.queryByLabelText('Session artifacts')).not.toBeInTheDocument(); + unmount(); + + runtimeState.remoteId = null; + const listSessionArtifacts = vi.fn(async () => [artifact('a1', 'report.html')]); + renderContainer({ artifacts: createMockArtifactServer({ listSessionArtifacts }) }); + expect(screen.queryByLabelText('Session artifacts')).not.toBeInTheDocument(); + expect(listSessionArtifacts).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/trueforge-ui/test/filePreview/folderFileTarget.test.ts b/packages/trueforge-ui/test/filePreview/folderFileTarget.test.ts new file mode 100644 index 0000000000..e9a9ce1e15 --- /dev/null +++ b/packages/trueforge-ui/test/filePreview/folderFileTarget.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it, vi } from 'vitest'; + +import type { FilePreviewFolder, SandboxFilePreviewTarget } from '@/filePreview/FilePreviewContext.js'; +import { folderFileTarget, openFolderFilePath } from '@/filePreview/folderFileTarget.js'; + +function folderTarget(): { target: SandboxFilePreviewTarget; folder: FilePreviewFolder } { + const folder: FilePreviewFolder = { + list: () => Promise.resolve([]), + loadFile: vi.fn(() => Promise.resolve(new Blob(['x']))), + cacheKey: 'a1@v1', + entryPoint: 'index.html', + }; + const target: SandboxFilePreviewTarget = { + name: 'Site', + path: 'index.html', + turnId: 'a1@v1', + load: () => Promise.resolve(new Blob(['x'])), + folder, + }; + return { target, folder }; +} + +describe('folderFileTarget', () => { + it('previews one file of the folder, named after the file and read by its path', async () => { + const { target, folder } = folderTarget(); + const fileTarget = folderFileTarget({ target, folder, path: 'data/a.csv' }); + + expect(fileTarget).toMatchObject({ name: 'a.csv', path: 'data/a.csv' }); + await fileTarget.load(); + expect(folder.loadFile).toHaveBeenCalledWith('data/a.csv'); + }); +}); + +describe('openFolderFilePath', () => { + it('returns the path of a file opened from the folder under the same turn id', () => { + const { target, folder } = folderTarget(); + const fileTarget = folderFileTarget({ target, folder, path: 'data/a.csv' }); + + expect(openFolderFilePath({ target: fileTarget, folderTurnId: 'a1@v1' })).toBe('data/a.csv'); + }); + + it('returns null for a file of another folder or another version of the folder', () => { + const { target, folder } = folderTarget(); + const fileTarget = folderFileTarget({ target, folder, path: 'data/a.csv' }); + + expect(openFolderFilePath({ target: fileTarget, folderTurnId: 'a2@v1' })).toBeNull(); + expect(openFolderFilePath({ target: fileTarget, folderTurnId: 'a1@v2' })).toBeNull(); + }); + + it('returns null for the folder preview itself and when nothing is open', () => { + const { target } = folderTarget(); + + expect(openFolderFilePath({ target, folderTurnId: 'a1@v1' })).toBeNull(); + expect(openFolderFilePath({ target: null, folderTurnId: 'a1@v1' })).toBeNull(); + }); +}); diff --git a/packages/trueforge-ui/test/filePreview/previewPaneWidth.test.ts b/packages/trueforge-ui/test/filePreview/previewPaneWidth.test.ts index d10cb4a994..f747ffda05 100644 --- a/packages/trueforge-ui/test/filePreview/previewPaneWidth.test.ts +++ b/packages/trueforge-ui/test/filePreview/previewPaneWidth.test.ts @@ -9,7 +9,7 @@ describe('clampPreviewWidth', () => { expect(clampPreviewWidth({ requested: 420, rowWidth: 1000 })).toBe(420); }); - it('defaults to 42% of the row', () => { - expect(defaultPreviewWidth(1000)).toBe(420); + it('defaults to half of the row', () => { + expect(defaultPreviewWidth(1000)).toBe(500); }); }); diff --git a/packages/trueforge-ui/test/filePreview/useFolderTree.test.tsx b/packages/trueforge-ui/test/filePreview/useFolderTree.test.tsx new file mode 100644 index 0000000000..584b4b0cca --- /dev/null +++ b/packages/trueforge-ui/test/filePreview/useFolderTree.test.tsx @@ -0,0 +1,114 @@ +// @vitest-environment jsdom +import { act, renderHook, waitFor } from '@testing-library/react'; +import type { ReactNode } from 'react'; +import { describe, expect, it, vi } from 'vitest'; + +import { useFolderTree } from '@/filePreview/useFolderTree.js'; +import { createServerQueryClient, ServerQueryClientContext } from '@/server/queryClient.js'; +import type { ArtifactFile } from '@/server/types.js'; + +const dataDir: ArtifactFile = { path: 'data/', isDir: true, size: null, lastModified: null }; +const indexFile: ArtifactFile = { path: 'index.html', isDir: false, size: 10, lastModified: null }; +const csvFile: ArtifactFile = { path: 'data/a.csv', isDir: false, size: 3, lastModified: null }; + +function listByPath(path: string): Promise { + return Promise.resolve(path === '' ? [dataDir, indexFile] : [csvFile]); +} + +describe('useFolderTree', () => { + it('loads the top level on mount', async () => { + const list = vi.fn(listByPath); + const { result } = renderHook(() => useFolderTree({ cacheKey: 'a1@v1', list })); + + expect(result.current.levels['']).toEqual({ status: 'loading' }); + await waitFor(() => expect(result.current.levels['']).toEqual({ status: 'ready', entries: [dataDir, indexFile] })); + expect(list).toHaveBeenCalledTimes(1); + expect(list).toHaveBeenCalledWith(''); + }); + + it('loads a subfolder on first expand and keeps it when collapsed', async () => { + const list = vi.fn(listByPath); + const { result } = renderHook(() => useFolderTree({ cacheKey: 'a1@v1', list })); + await waitFor(() => expect(result.current.levels['']?.status).toBe('ready')); + + act(() => result.current.toggle('data/')); + expect(result.current.expanded.has('data/')).toBe(true); + await waitFor(() => expect(result.current.levels['data/']).toEqual({ status: 'ready', entries: [csvFile] })); + + act(() => result.current.toggle('data/')); + expect(result.current.expanded.has('data/')).toBe(false); + act(() => result.current.toggle('data/')); + expect(result.current.expanded.has('data/')).toBe(true); + expect(list).toHaveBeenCalledTimes(2); + }); + + it('reports a failed level and retries it on the next expand', async () => { + const list = vi + .fn<(path: string) => Promise>() + .mockImplementationOnce(listByPath) + .mockRejectedValueOnce(new Error('boom')) + .mockImplementation(listByPath); + const { result } = renderHook(() => useFolderTree({ cacheKey: 'a1@v1', list })); + await waitFor(() => expect(result.current.levels['']?.status).toBe('ready')); + + act(() => result.current.toggle('data/')); + await waitFor(() => + expect(result.current.levels['data/']).toEqual({ status: 'error', message: "Couldn't load these files." }), + ); + + act(() => result.current.toggle('data/')); + act(() => result.current.toggle('data/')); + await waitFor(() => expect(result.current.levels['data/']?.status).toBe('ready')); + expect(list).toHaveBeenCalledTimes(3); + }); + + it('explains a refused listing with the access message', async () => { + const forbidden = Object.assign(new Error('Forbidden'), { statusCode: 403 }); + const list = vi + .fn<(path: string) => Promise>() + .mockImplementationOnce(listByPath) + .mockRejectedValueOnce(forbidden); + const { result } = renderHook(() => useFolderTree({ cacheKey: 'a1@v1', list })); + await waitFor(() => expect(result.current.levels['']?.status).toBe('ready')); + + act(() => result.current.toggle('data/')); + await waitFor(() => + expect(result.current.levels['data/']).toEqual({ + status: 'error', + message: "You don't have access to open this artifact.", + }), + ); + }); + + it('opens the folders above the reveal path and lists them from the start', async () => { + const list = vi.fn(listByPath); + const { result } = renderHook(() => useFolderTree({ cacheKey: 'a1@v1', list, revealPath: 'data/a.csv' })); + + expect(result.current.expanded.has('data/')).toBe(true); + await waitFor(() => expect(result.current.levels['data/']).toEqual({ status: 'ready', entries: [csvFile] })); + expect(list).toHaveBeenCalledWith(''); + expect(list).toHaveBeenCalledWith('data/'); + }); + + it('reuses cached listings when the folder is opened again, but not for another version', async () => { + const queryClient = createServerQueryClient(); + const wrapper = ({ children }: { children: ReactNode }) => ( + {children} + ); + const list = vi.fn(listByPath); + + const first = renderHook(() => useFolderTree({ cacheKey: 'a1@v1', list }), { wrapper }); + await waitFor(() => expect(first.result.current.levels['']?.status).toBe('ready')); + first.unmount(); + + const second = renderHook(() => useFolderTree({ cacheKey: 'a1@v1', list }), { wrapper }); + expect(second.result.current.levels['']).toEqual({ status: 'ready', entries: [dataDir, indexFile] }); + await waitFor(() => expect(second.result.current.levels['']?.status).toBe('ready')); + expect(list).toHaveBeenCalledTimes(1); + + const newVersion = renderHook(() => useFolderTree({ cacheKey: 'a1@v2', list }), { wrapper }); + expect(newVersion.result.current.levels['']).toEqual({ status: 'loading' }); + await waitFor(() => expect(newVersion.result.current.levels['']?.status).toBe('ready')); + expect(list).toHaveBeenCalledTimes(2); + }); +}); diff --git a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/artifactServer.test.ts b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/artifactServer.test.ts index f12062a1cb..eb73de77b8 100644 --- a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/artifactServer.test.ts +++ b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/artifactServer.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it, vi } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { createArtifactServer } from '@/plugins/trueforge-agent-server-adapter/artifactServer.js'; import type { TrueForge } from '@truefoundry/trueforge-sdk'; @@ -15,16 +15,58 @@ const sdkArtifact = { createdBySubject, createdAt: new Date('2024-01-01T00:00:00.000Z'), updatedAt: new Date('2024-01-02T00:00:00.000Z'), + filesMetadata: { isDir: false, sizeBytes: 10, entryPoint: 'index.html' }, }; +const uiFilesMetadata = { isDir: false, sizeBytes: 10, entryPoint: 'index.html' }; + function mockClient({ list = vi.fn(), + get = vi.fn(), + listFiles = vi.fn(), update = vi.fn(), + listSessionArtifacts = vi.fn(), }: { list?: ReturnType; + get?: ReturnType; + listFiles?: ReturnType; update?: ReturnType; + listSessionArtifacts?: ReturnType; }) { - return { artifacts: { list, update } } as unknown as TrueForge; + return { + artifacts: { list, get, listFiles, update }, + sessions: { listArtifacts: listSessionArtifacts }, + } as unknown as TrueForge; +} + +const modified = new Date('2024-01-03T00:00:00.000Z'); +const htmlFile = { + path: 'index.html', + isDir: false, + s3Url: 'https://s3.test/index.html', + sizeBytes: 10, + lastModified: modified, +}; +const dataDir = { path: 'data/', isDir: true, s3Url: null, sizeBytes: null, lastModified: null }; +const csvFile = { + path: 'data/a.csv', + isDir: false, + s3Url: 'https://s3.test/a.csv', + sizeBytes: 3, + lastModified: modified, +}; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +// Under jsdom, `Response.blob()` can return a Blob without `.text()` depending on the Node version, so the stubbed +// download hands back one known Blob and tests compare it by identity. +function stubDownload() { + const bytes = new Blob(['file bytes']); + const download = vi.fn(async () => ({ ok: true, status: 200, blob: async () => bytes })); + vi.stubGlobal('fetch', download); + return { bytes, download }; } describe('createArtifactServer', () => { @@ -46,16 +88,63 @@ describe('createArtifactServer', () => { createdBySubject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', + filesMetadata: uiFilesMetadata, }, ]); }); + it('maps the folder flag from the list response', async () => { + const list = vi.fn(async () => ({ + data: [{ ...sdkArtifact, filesMetadata: { isDir: true, sizeBytes: 10, entryPoint: 'index.html' } }], + response: { pagination: { limit: 25 } }, + })); + const page = await createArtifactServer(mockClient({ list })).listArtifacts(); + + expect(page.data[0]?.filesMetadata.isDir).toBe(true); + }); + + it('gets one artifact with its files metadata', async () => { + const get = vi.fn(async () => ({ + data: { ...sdkArtifact, filesMetadata: { isDir: true, sizeBytes: 10, entryPoint: 'index.html' } }, + })); + const artifact = await createArtifactServer(mockClient({ get })).getArtifact({ id: 'a1' }); + + expect(get).toHaveBeenCalledWith('a1'); + expect(artifact).toEqual({ + id: 'a1', + name: 'Q4 brief', + createdBySubject, + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-02T00:00:00.000Z', + filesMetadata: { isDir: true, sizeBytes: 10, entryPoint: 'index.html' }, + }); + }); + it('omits an empty name from the list request', async () => { const list = vi.fn(async () => ({ data: [], response: { pagination: { limit: 25 } } })); await createArtifactServer(mockClient({ list })).listArtifacts({ name: '' }); expect(list).toHaveBeenCalledWith({}); }); + it('lists a session’s artifacts and maps them to UI artifacts', async () => { + const listSessionArtifacts = vi.fn(async () => ({ data: [sdkArtifact] })); + const artifacts = await createArtifactServer(mockClient({ listSessionArtifacts })).listSessionArtifacts({ + sessionId: 's1', + }); + + expect(listSessionArtifacts).toHaveBeenCalledWith('s1'); + expect(artifacts).toEqual([ + { + id: 'a1', + name: 'Q4 brief', + createdBySubject, + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-02T00:00:00.000Z', + filesMetadata: uiFilesMetadata, + }, + ]); + }); + it('renames through the update route and maps the response', async () => { const update = vi.fn(async () => ({ data: { ...sdkArtifact, name: 'Renamed' } })); const renamed = await createArtifactServer(mockClient({ update })).updateArtifact({ id: 'a1', name: 'Renamed' }); @@ -65,10 +154,93 @@ describe('createArtifactServer', () => { expect(renamed.updatedAt).toBe('2024-01-02T00:00:00.000Z'); }); - it('rejects the routes the API does not have yet', async () => { - const server = createArtifactServer(mockClient({})); - await expect(server.getArtifact({ id: 'a1' })).rejects.toThrow('not available yet'); - await expect(server.deleteArtifact({ id: 'a1' })).rejects.toThrow('not available yet'); - await expect(server.readArtifactFile({ id: 'a1' })).rejects.toThrow('not available yet'); + it('lists one folder level with sizes and modified times, without exposing download urls', async () => { + const listFiles = vi.fn(async () => ({ data: [dataDir, htmlFile] })); + const server = createArtifactServer(mockClient({ listFiles })); + + await expect(server.listArtifactFiles({ id: 'a1' })).resolves.toEqual([ + { path: 'data/', isDir: true, size: null, lastModified: null }, + { path: 'index.html', isDir: false, size: 10, lastModified: '2024-01-03T00:00:00.000Z' }, + ]); + expect(listFiles).toHaveBeenCalledWith('a1', {}); + + await server.listArtifactFiles({ id: 'a1', path: 'data/' }); + expect(listFiles).toHaveBeenLastCalledWith('a1', { path: 'data/' }); + }); + + it('reads a top-level file by listing the folder and fetching its download url', async () => { + const listFiles = vi.fn(async () => ({ data: [dataDir, htmlFile] })); + const { bytes, download } = stubDownload(); + + const blob = await createArtifactServer(mockClient({ listFiles })).readArtifactFile({ + id: 'a1', + path: 'index.html', + }); + + expect(listFiles).toHaveBeenCalledWith('a1', {}); + expect(download).toHaveBeenCalledWith('https://s3.test/index.html'); + expect(blob).toBe(bytes); + }); + + it('reads a nested file by listing its parent folder', async () => { + const listFiles = vi.fn(async () => ({ data: [csvFile] })); + const { bytes, download } = stubDownload(); + + const blob = await createArtifactServer(mockClient({ listFiles })).readArtifactFile({ + id: 'a1', + path: 'data/a.csv', + }); + + expect(listFiles).toHaveBeenCalledWith('a1', { path: 'data/' }); + expect(download).toHaveBeenCalledWith('https://s3.test/a.csv'); + expect(blob).toBe(bytes); + }); + + it('reads the only top-level file of a single-file artifact without fetching its details', async () => { + const get = vi.fn(async () => ({ data: sdkArtifact })); + const listFiles = vi.fn(async () => ({ data: [htmlFile] })); + const { bytes, download } = stubDownload(); + + const blob = await createArtifactServer(mockClient({ get, listFiles })).readArtifactFile({ id: 'a1' }); + + expect(get).not.toHaveBeenCalled(); + expect(listFiles).toHaveBeenCalledOnce(); + expect(listFiles).toHaveBeenCalledWith('a1', {}); + expect(download).toHaveBeenCalledWith('https://s3.test/index.html'); + expect(blob).toBe(bytes); + }); + + it('fails to read a single-file artifact that has no files yet', async () => { + const listFiles = vi.fn(async () => ({ data: [] })); + await expect(createArtifactServer(mockClient({ listFiles })).readArtifactFile({ id: 'a1' })).rejects.toThrow( + 'no files', + ); + }); + + it('fails to read without a path when the top level holds more than one file', async () => { + const listFiles = vi.fn(async () => ({ data: [htmlFile, { ...htmlFile, path: 'style.css' }] })); + await expect(createArtifactServer(mockClient({ listFiles })).readArtifactFile({ id: 'a1' })).rejects.toThrow( + 'more than one file', + ); + }); + + it('fails to read a path that is not a file in the listing', async () => { + const listFiles = vi.fn(async () => ({ data: [dataDir] })); + const server = createArtifactServer(mockClient({ listFiles })); + + await expect(server.readArtifactFile({ id: 'a1', path: 'missing.txt' })).rejects.toThrow('missing.txt'); + await expect(server.readArtifactFile({ id: 'a1', path: 'data/' })).rejects.toThrow('data/'); + }); + + it('fails to read when the download is refused', async () => { + const listFiles = vi.fn(async () => ({ data: [htmlFile] })); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('denied', { status: 403 })), + ); + + await expect( + createArtifactServer(mockClient({ listFiles })).readArtifactFile({ id: 'a1', path: 'index.html' }), + ).rejects.toThrow('403'); }); }); diff --git a/packages/trueforge-ui/test/publicUiExports.test.ts b/packages/trueforge-ui/test/publicUiExports.test.ts index 129516cd5f..7a0568e0fd 100644 --- a/packages/trueforge-ui/test/publicUiExports.test.ts +++ b/packages/trueforge-ui/test/publicUiExports.test.ts @@ -61,6 +61,7 @@ const expectedRuntimeExports: Array = [ 'CanCreateAgentProvider', 'CenteredModal', 'ChatFileDownload', + 'FilePreviewFolderBrowser', 'FilePreviewPanel', 'ClearChatButton', 'ResetAgentBuilderButton', diff --git a/packages/trueforge-ui/test/server/mockServer.ts b/packages/trueforge-ui/test/server/mockServer.ts index 55934f1b8a..a6eef644c5 100644 --- a/packages/trueforge-ui/test/server/mockServer.ts +++ b/packages/trueforge-ui/test/server/mockServer.ts @@ -85,9 +85,10 @@ export function createMockSandboxEnvironmentServer( export function createMockArtifactServer(overrides: Partial = {}): ArtifactServer { return { listArtifacts: async () => ({ data: [] }), + listSessionArtifacts: async () => [], getArtifact: unavailable, + listArtifactFiles: async () => [], updateArtifact: unavailable, - deleteArtifact: unavailable, readArtifactFile: unavailable, ...overrides, }; diff --git a/packages/trueforge-ui/test/utils/artifactErrorMessage.test.ts b/packages/trueforge-ui/test/utils/artifactErrorMessage.test.ts new file mode 100644 index 0000000000..f343aee7bd --- /dev/null +++ b/packages/trueforge-ui/test/utils/artifactErrorMessage.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, it } from 'vitest'; + +import { artifactErrorMessage } from '@/utils/artifactErrorMessage.js'; + +const fallback = "Couldn't load a preview of this file."; + +function failure(statusCode: number) { + return Object.assign(new Error('failed'), { statusCode }); +} + +describe('artifactErrorMessage', () => { + it('says the caller has no access on a 403', () => { + expect(artifactErrorMessage({ error: failure(403), fallback })).toBe( + "You don't have access to open this artifact.", + ); + }); + + it('says the artifact or file is gone on a 404', () => { + expect(artifactErrorMessage({ error: failure(404), fallback })).toBe( + 'This artifact or file was not found. It may have been removed.', + ); + }); + + it('keeps the generic message for other statuses and for errors without one', () => { + expect(artifactErrorMessage({ error: failure(500), fallback })).toBe(fallback); + expect(artifactErrorMessage({ error: new Error('network'), fallback })).toBe(fallback); + expect(artifactErrorMessage({ error: 'nope', fallback })).toBe(fallback); + expect(artifactErrorMessage({ error: null, fallback })).toBe(fallback); + }); +});