From febd39a426612b7a1a6f251b9b81fe83dd25e248 Mon Sep 17 00:00:00 2001 From: Harshil Vasoya Date: Tue, 24 Nov 2026 09:30:21 +0530 Subject: [PATCH 01/20] feat: introduce Artifacts page with server integration --- .changeset/artifacts-page-flagged.md | 7 + packages/assistant-ui-runtime/src/index.ts | 3 + .../assistant-ui-runtime/src/server/index.ts | 3 + .../assistant-ui-runtime/src/server/types.ts | 42 +++ packages/frontend/src/App.tsx | 4 + .../src/artifacts/dummyArtifactServer.ts | 83 +++++ .../frontend/src/artifacts/dummyArtifacts.ts | 66 ++++ .../artifacts/dummyArtifactServer.test.ts | 59 ++++ packages/trueforge-ui/src/analytics/events.ts | 8 + .../src/atoms/ArtifactsButton.tsx | 74 +++++ .../src/atoms/FilePreviewPanel.tsx | 26 +- .../trueforge-ui/src/atoms/RowActionItem.tsx | 37 +++ .../src/atoms/ShareSessionDialog.tsx | 25 +- .../atoms/artifacts/ArtifactEditDialog.tsx | 140 +++++++++ .../atoms/artifacts/ArtifactScopeFilter.tsx | 53 ++++ .../atoms/artifacts/ArtifactsEmptyState.tsx | 30 ++ .../src/atoms/artifacts/ArtifactsPage.tsx | 283 ++++++++++++++++++ .../src/atoms/artifacts/ArtifactsTable.tsx | 133 ++++++++ .../src/atoms/artifacts/artifactDisplay.ts | 28 ++ .../atoms/environments/EnvironmentsPage.tsx | 42 +-- .../src/containers/ThreadListContainer.tsx | 7 +- .../src/containers/useResolvedServer.ts | 4 +- packages/trueforge-ui/src/index.ts | 7 + .../trueforge-ui/src/layouts/DrawerLayout.tsx | 31 +- .../src/layouts/SidebarLayout.tsx | 35 ++- .../src/layouts/StackChatPanel.tsx | 24 +- .../trueforge-agent-server-adapter/index.ts | 7 +- .../src/routing/ShellRouteSync.tsx | 23 +- .../trueforge-ui/src/routing/derivePlace.ts | 6 +- packages/trueforge-ui/src/routing/paths.ts | 16 + packages/trueforge-ui/src/routing/types.ts | 10 + .../trueforge-ui/src/server/ServerContext.tsx | 13 + .../src/server/ShellModeContext.tsx | 73 ++++- .../src/server/TrueForgeServerConfig.ts | 4 +- .../src/server/createTrueForgeServer.ts | 17 +- packages/trueforge-ui/src/server/queryKeys.ts | 5 + .../trueforge-ui/src/server/serverChrome.ts | 10 + packages/trueforge-ui/src/server/types.ts | 3 + packages/trueforge-ui/src/styles.css | 32 ++ .../trueforge-ui/src/theme/defaultSlots.ts | 8 + .../trueforge-ui/src/utils/artifactRef.ts | 15 + .../atoms/artifacts/ArtifactsPage.test.tsx | 137 +++++++++ .../ThreadListContainer.pagination.test.tsx | 1 + .../trueforge-ui/test/publicUiExports.test.ts | 2 + .../test/routing/ShellRouteSync.test.tsx | 69 +++++ .../test/routing/derivePlace.test.ts | 15 + .../trueforge-ui/test/routing/paths.test.ts | 8 + .../trueforge-ui/test/server/mockServer.ts | 12 + .../test/server/serverChrome.test.ts | 11 + .../test/utils/artifactRef.test.ts | 18 ++ 50 files changed, 1706 insertions(+), 63 deletions(-) create mode 100644 .changeset/artifacts-page-flagged.md create mode 100644 packages/frontend/src/artifacts/dummyArtifactServer.ts create mode 100644 packages/frontend/src/artifacts/dummyArtifacts.ts create mode 100644 packages/frontend/tests/artifacts/dummyArtifactServer.test.ts create mode 100644 packages/trueforge-ui/src/atoms/ArtifactsButton.tsx create mode 100644 packages/trueforge-ui/src/atoms/RowActionItem.tsx create mode 100644 packages/trueforge-ui/src/atoms/artifacts/ArtifactEditDialog.tsx create mode 100644 packages/trueforge-ui/src/atoms/artifacts/ArtifactScopeFilter.tsx create mode 100644 packages/trueforge-ui/src/atoms/artifacts/ArtifactsEmptyState.tsx create mode 100644 packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx create mode 100644 packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx create mode 100644 packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts create mode 100644 packages/trueforge-ui/src/utils/artifactRef.ts create mode 100644 packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx create mode 100644 packages/trueforge-ui/test/utils/artifactRef.test.ts diff --git a/.changeset/artifacts-page-flagged.md b/.changeset/artifacts-page-flagged.md new file mode 100644 index 0000000000..05de32c677 --- /dev/null +++ b/.changeset/artifacts-page-flagged.md @@ -0,0 +1,7 @@ +--- +'@truefoundry/trueforge-assistant-ui-runtime': patch +'@truefoundry/trueforge-ui': patch +'@truefoundry/trueforge': patch +--- + +Add an optional `artifacts` server port and an Artifacts page (list plus file preview) after Environments. The standalone app shows it with dummy data only when `VITE_ENABLE_ARTIFACTS=true`. diff --git a/packages/assistant-ui-runtime/src/index.ts b/packages/assistant-ui-runtime/src/index.ts index a1810a36fa..7152940756 100644 --- a/packages/assistant-ui-runtime/src/index.ts +++ b/packages/assistant-ui-runtime/src/index.ts @@ -116,6 +116,8 @@ export type { AgentUIServer, AgentUIServerPort, ApprovalDecision, + Artifact, + ArtifactServer, AuthenticateConnectorRequest, CatalogServer, CodeSnippet, @@ -153,6 +155,7 @@ export type { DefinedSkill, GithubSkill, ImportGithubSkillRequest, + ListArtifactsParams, ListPermissionsRequest, ListPermissionsResponse, ListResult, diff --git a/packages/assistant-ui-runtime/src/server/index.ts b/packages/assistant-ui-runtime/src/server/index.ts index aabe9e389b..87c1ccd2e3 100644 --- a/packages/assistant-ui-runtime/src/server/index.ts +++ b/packages/assistant-ui-runtime/src/server/index.ts @@ -27,6 +27,8 @@ export type { AgentUIServer, AgentUIServerPort, ApprovalDecision, + Artifact, + ArtifactServer, AuthenticateConnectorRequest, CatalogServer, CodeSnippet, @@ -65,6 +67,7 @@ export type { DirectoryUser, GithubSkill, ImportGithubSkillRequest, + ListArtifactsParams, ListPermissionsRequest, ListPermissionsResponse, ListResult, diff --git a/packages/assistant-ui-runtime/src/server/types.ts b/packages/assistant-ui-runtime/src/server/types.ts index 2530726096..8c802d867f 100644 --- a/packages/assistant-ui-runtime/src/server/types.ts +++ b/packages/assistant-ui-runtime/src/server/types.ts @@ -1373,6 +1373,43 @@ export interface SandboxEnvironmentServer; } +// --------------------------------------------------------------------------- +// Artifacts — versioned, shareable outputs that outlive the session sandbox +// --------------------------------------------------------------------------- + +export interface Artifact { + /** Stable identifier used in URLs. Must not contain `-`. */ + id: string; + slug: string; + title: string; + latestVersion: number; + /** Latest version's default file to render, relative to the version. Null before the first version. */ + entryPoint: string | null; + createdBySubject: Subject; + createdBySessionId: string; + createdAt: string; + updatedAt: string; +} + +export interface ListArtifactsParams extends Pick { + /** Only artifacts created in this session. */ + createdBySessionId?: string; + /** Case-insensitive substring match on title. */ + title?: string; + /** Resolved by the server against the caller. Defaults to `all`. */ + scope?: 'all' | 'created_by_me' | 'shared_with_me'; +} + +export interface ArtifactServer { + /** Caller's artifacts, most recently updated first. */ + listArtifacts(req?: ListArtifactsParams): Promise>; + getArtifact(req: { id: string }): Promise; + updateArtifact(req: { id: string; title: string }): Promise; + deleteArtifact(req: { id: string }): Promise; + /** Defaults to the latest version and its `entryPoint`. */ + readArtifactFile(req: { slug: string; version?: number; path?: string }): Promise; +} + // --------------------------------------------------------------------------- // Permissions — optional resource mutation grants // --------------------------------------------------------------------------- @@ -1521,6 +1558,9 @@ export interface AgentMetricsServer< * `sandboxEnvironments` is optional — if the host passes it, Environments UI * can call `useSandboxEnvironmentServer()`; if omitted, that surface stays hidden. * + * `artifacts` is optional — if the host passes it, the Artifacts page can call + * `useArtifactServer()`; if omitted, that surface stays hidden. + * * `metrics` is optional — if the host passes it, agent-detail UI can render * aggregate meter cards and time-series charts. * @@ -1537,6 +1577,7 @@ export type AgentUIServerPort< TPermissions extends PermissionsServer = PermissionsServer, TSessionAccess extends SessionAccessServer = SessionAccessServer, TConfiguration extends ConfigurationServer = ConfigurationServer, + TArtifacts extends ArtifactServer = ArtifactServer, > = TChat & TBuilder & { catalog?: TCatalog; @@ -1545,6 +1586,7 @@ export type AgentUIServerPort< sessions?: TSessions; schedules?: TSchedules; sandboxEnvironments?: TSandboxEnvironments; + artifacts?: TArtifacts; metrics?: TMetrics; permissions?: TPermissions; /** Optional session sharing port; omit to hide the invite and collaborator UI. */ diff --git a/packages/frontend/src/App.tsx b/packages/frontend/src/App.tsx index 6102c2c370..f90bc49a46 100644 --- a/packages/frontend/src/App.tsx +++ b/packages/frontend/src/App.tsx @@ -18,6 +18,7 @@ import { import posthog from 'posthog-js'; import { useEffect, useMemo, useState } from 'react'; import { ThinkingOrb } from 'thinking-orbs'; +import { createDummyArtifactServer } from './artifacts/dummyArtifactServer'; import { AuthErrorScreen } from './AuthErrorScreen'; import { createAuthAwareFetch } from './authFetch'; import { probeSession, type SessionState } from './authSession'; @@ -63,6 +64,8 @@ const authAwareFetch = SENTRY_DSN ? withSentryRootSpan(createAuthAwareFetch()) : // UI + API share the public prefix from `window.__TRUEFORGE_BASE_PATH__`. const bootClient = createTrueForgeClient({ baseUrl: API_BASE_URL, fetch: authAwareFetch }); const routerBasename = uiRouterBasename(); +// Stable identity: the resolved server rebuilds when `artifacts` changes. +const dummyArtifactServer = createDummyArtifactServer(); /** Host brand: primary CTA fill is a gradient (see `index.css`); keep solid token for accents. */ const appTheme: ThemeConfig = { @@ -258,6 +261,7 @@ export function App() { type: 'trueforge', baseUrl: API_BASE_URL, fetch: authAwareFetch, + artifacts: dummyArtifactServer, }} layout="sidebar" withRouter diff --git a/packages/frontend/src/artifacts/dummyArtifactServer.ts b/packages/frontend/src/artifacts/dummyArtifactServer.ts new file mode 100644 index 0000000000..f93be5551e --- /dev/null +++ b/packages/frontend/src/artifacts/dummyArtifactServer.ts @@ -0,0 +1,83 @@ +import type { Artifact, ArtifactServer, ListArtifactsParams } from '@truefoundry/trueforge-ui'; + +import { buildDummyArtifacts, DUMMY_CURRENT_SUBJECT_ID } from './dummyArtifacts'; + +const DEFAULT_LIMIT = 10; + +function matchesScope(artifact: Artifact, scope: ListArtifactsParams['scope']): boolean { + if (scope === undefined || scope === 'all') { + return true; + } + const mine = artifact.createdBySubject.subjectId === DUMMY_CURRENT_SUBJECT_ID; + return scope === 'created_by_me' ? mine : !mine; +} + +function sampleContent({ title, entryPoint }: Pick): Blob { + if (entryPoint?.endsWith('.md')) { + return new Blob([`# ${title}\n\nSample report content.\n\n- Item one\n- Item two\n`], { type: 'text/markdown' }); + } + return new Blob([`

${title}

Sample artifact.

`], { + type: 'text/html', + }); +} + +// TODO: remove once the artifacts API ships and the host passes a real ArtifactServer. +export function createDummyArtifactServer(): ArtifactServer { + const artifacts = buildDummyArtifacts().sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); + return { + listArtifacts: ({ + limit = DEFAULT_LIMIT, + pageToken, + title, + createdBySessionId, + scope, + }: ListArtifactsParams = {}) => { + const needle = title?.trim().toLowerCase() ?? ''; + const matches = artifacts.filter( + artifact => + (needle === '' || artifact.title.toLowerCase().includes(needle)) && + (createdBySessionId === undefined || artifact.createdBySessionId === createdBySessionId) && + matchesScope(artifact, scope), + ); + const offset = pageToken === undefined ? 0 : Number(pageToken); + const data = matches.slice(offset, offset + limit); + const previousOffset = Math.max(offset - limit, 0); + return Promise.resolve({ + data, + ...(offset + limit < matches.length ? { nextPageToken: String(offset + limit) } : {}), + ...(offset > 0 ? { previousPageToken: String(previousOffset) } : {}), + }); + }, + getArtifact: ({ id }) => { + const artifact = artifacts.find(candidate => candidate.id === id); + return artifact === undefined + ? Promise.reject(new Error(`Artifact "${id}" not found`)) + : Promise.resolve(artifact); + }, + updateArtifact: ({ id, title }) => { + const index = artifacts.findIndex(candidate => candidate.id === id); + const current = index < 0 ? undefined : artifacts[index]; + if (current === undefined) { + return Promise.reject(new Error(`Artifact "${id}" not found`)); + } + const next = { ...current, title: title.trim(), updatedAt: new Date().toISOString() }; + artifacts[index] = next; + artifacts.sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)); + return Promise.resolve(next); + }, + deleteArtifact: ({ id }) => { + const index = artifacts.findIndex(candidate => candidate.id === id); + if (index < 0) { + return Promise.reject(new Error(`Artifact "${id}" not found`)); + } + artifacts.splice(index, 1); + return Promise.resolve(); + }, + readArtifactFile: ({ slug }) => { + const artifact = artifacts.find(candidate => candidate.slug === slug); + return artifact === undefined + ? Promise.reject(new Error(`Artifact "${slug}" not found`)) + : Promise.resolve(sampleContent(artifact)); + }, + }; +} diff --git a/packages/frontend/src/artifacts/dummyArtifacts.ts b/packages/frontend/src/artifacts/dummyArtifacts.ts new file mode 100644 index 0000000000..2aa2da8ab1 --- /dev/null +++ b/packages/frontend/src/artifacts/dummyArtifacts.ts @@ -0,0 +1,66 @@ +import type { Artifact } from '@truefoundry/trueforge-ui'; + +const HOUR_MS = 60 * 60 * 1000; + +export const DUMMY_CURRENT_SUBJECT_ID = 'dummy-user'; +const SUBJECT = { subjectId: DUMMY_CURRENT_SUBJECT_ID, subjectType: 'user', subjectDisplayName: 'Demo User' } as const; +const OTHER_SUBJECT = { subjectId: 'dummy-priya', subjectType: 'user', subjectDisplayName: 'Priya Shah' } as const; + +const ROWS: readonly { + slug: string; + title: string; + latestVersion: number; + entryPoint: string | null; + ageHours: number; +}[] = [ + { slug: 'space-channel-plan', title: 'Space channel plan', latestVersion: 3, entryPoint: 'index.html', ageHours: 2 }, + { slug: 'agents-inventory', title: 'Agents inventory', latestVersion: 1, entryPoint: 'report.md', ageHours: 5 }, + { slug: 'schedules-report', title: 'Schedules report', latestVersion: 2, entryPoint: 'report.md', ageHours: 9 }, + { slug: 'q4-gtm-brief', title: 'Q4 GTM brief', latestVersion: 4, entryPoint: 'index.html', ageHours: 27 }, + { slug: 'pricing-calculator', title: 'Pricing calculator', latestVersion: 2, entryPoint: 'index.html', ageHours: 30 }, + { + slug: 'usage-dashboard', + title: 'Usage dashboard', + latestVersion: 1, + entryPoint: 'dashboard/index.html', + ageHours: 52, + }, + { + slug: 'onboarding-checklist', + title: 'Onboarding checklist', + latestVersion: 1, + entryPoint: 'report.md', + ageHours: 75, + }, + { + slug: 'incident-postmortem', + title: 'Incident postmortem', + latestVersion: 3, + entryPoint: 'report.md', + ageHours: 98, + }, + { slug: 'eval-results', title: 'Eval results', latestVersion: 2, entryPoint: 'index.html', ageHours: 120 }, + { slug: 'roadmap-timeline', title: 'Roadmap timeline', latestVersion: 4, entryPoint: 'index.html', ageHours: 160 }, + { + slug: 'cost-breakdown', + title: 'Cost breakdown', + latestVersion: 1, + entryPoint: 'dashboard/index.html', + ageHours: 210, + }, + { slug: 'empty-draft', title: 'Empty draft', latestVersion: 1, entryPoint: null, ageHours: 300 }, +]; + +export function buildDummyArtifacts({ nowMs = Date.now() }: { nowMs?: number } = {}): Artifact[] { + return ROWS.map(({ ageHours, ...row }, index) => { + const updatedAt = new Date(nowMs - ageHours * HOUR_MS).toISOString(); + return { + id: `art${String(index + 1).padStart(3, '0')}`, + ...row, + createdBySubject: index % 3 === 2 ? OTHER_SUBJECT : SUBJECT, + createdBySessionId: `dummy-session-${row.slug}`, + createdAt: new Date(nowMs - (ageHours + 24) * HOUR_MS).toISOString(), + updatedAt, + }; + }); +} diff --git a/packages/frontend/tests/artifacts/dummyArtifactServer.test.ts b/packages/frontend/tests/artifacts/dummyArtifactServer.test.ts new file mode 100644 index 0000000000..590dbfb0ef --- /dev/null +++ b/packages/frontend/tests/artifacts/dummyArtifactServer.test.ts @@ -0,0 +1,59 @@ +import assert from 'node:assert/strict'; +import { test } from 'node:test'; + +import { createDummyArtifactServer } from '../../src/artifacts/dummyArtifactServer'; + +test('lists newest first and pages with tokens', async () => { + const server = createDummyArtifactServer(); + const first = await server.listArtifacts({ limit: 5 }); + assert.equal(first.data.length, 5); + assert.ok(first.nextPageToken !== undefined); + assert.equal(first.previousPageToken, undefined); + const updated = first.data.map(artifact => artifact.updatedAt); + assert.deepEqual([...updated].sort().reverse(), updated); + + const second = await server.listArtifacts({ limit: 5, pageToken: first.nextPageToken }); + assert.ok(second.previousPageToken !== undefined); + assert.notEqual(second.data[0]?.slug, first.data[0]?.slug); +}); + +test('filters by title and reads file content', async () => { + const server = createDummyArtifactServer(); + const { data } = await server.listArtifacts({ title: 'PRICING' }); + assert.deepEqual( + data.map(artifact => artifact.slug), + ['pricing-calculator'], + ); + const blob = await server.readArtifactFile({ slug: 'pricing-calculator' }); + assert.match(await blob.text(), /Pricing calculator/); + await assert.rejects(server.readArtifactFile({ slug: 'missing' })); +}); + +test('gets an artifact by id', async () => { + const server = createDummyArtifactServer(); + const [first] = (await server.listArtifacts()).data; + assert.ok(first !== undefined); + assert.equal((await server.getArtifact({ id: first.id })).slug, first.slug); + assert.ok(!first.id.includes('-')); + await assert.rejects(server.getArtifact({ id: 'missing' })); +}); + +test('renames and deletes by id', async () => { + const server = createDummyArtifactServer(); + const [first] = (await server.listArtifacts()).data; + assert.ok(first !== undefined); + const renamed = await server.updateArtifact({ id: first.id, title: 'Renamed brief' }); + assert.equal(renamed.title, 'Renamed brief'); + assert.equal((await server.listArtifacts({ title: 'Renamed' })).data[0]?.id, first.id); + await server.deleteArtifact({ id: first.id }); + assert.equal((await server.listArtifacts({ title: 'Renamed' })).data.length, 0); +}); + +test('filters by scope against the current user', async () => { + const server = createDummyArtifactServer(); + const mine = await server.listArtifacts({ scope: 'created_by_me', limit: 100 }); + const shared = await server.listArtifacts({ scope: 'shared_with_me', limit: 100 }); + const all = await server.listArtifacts({ limit: 100 }); + assert.ok(mine.data.length > 0 && shared.data.length > 0); + assert.equal(mine.data.length + shared.data.length, all.data.length); +}); diff --git a/packages/trueforge-ui/src/analytics/events.ts b/packages/trueforge-ui/src/analytics/events.ts index b135a3ac7d..1085fcb569 100644 --- a/packages/trueforge-ui/src/analytics/events.ts +++ b/packages/trueforge-ui/src/analytics/events.ts @@ -84,6 +84,14 @@ export const AnalyticsEvents = { EDITED: 'trueforge.environment.edited', DELETED: 'trueforge.environment.deleted', }, + Artifact: { + PAGE_OPENED: 'trueforge.artifact.page_opened', + PREVIEW_OPENED: 'trueforge.artifact.preview_opened', + DOWNLOADED: 'trueforge.artifact.downloaded', + SHARE_OPENED: 'trueforge.artifact.share_opened', + EDITED: 'trueforge.artifact.edited', + DELETED: 'trueforge.artifact.deleted', + }, Sdk: { HTTP_TIMEOUT: 'trueforge.sdk.http_timeout', }, diff --git a/packages/trueforge-ui/src/atoms/ArtifactsButton.tsx b/packages/trueforge-ui/src/atoms/ArtifactsButton.tsx new file mode 100644 index 0000000000..34112a0071 --- /dev/null +++ b/packages/trueforge-ui/src/atoms/ArtifactsButton.tsx @@ -0,0 +1,74 @@ +'use client'; + +import { useTrackAnalytics } from '../analytics/AnalyticsProvider.js'; +import { AnalyticsEvents } from '../analytics/events.js'; +import { Icon } from '../icons/Icon.js'; +import { useOptionalArtifactServer } from '../server/ServerContext.js'; +import { useOptionalShellMode } from '../server/ShellModeContext.js'; +import { isArtifactsChromeEnabled } from '../server/serverChrome.js'; +import { + auiButtonClass, + shellRailSelectedClassName, + sidebarButtonRadiusClassName, + sidebarRailButtonClassName, +} from './lib/buttonClasses.js'; +import { cn } from './lib/cn.js'; +import { RailTooltip } from './primitives/Tooltip.js'; + +export type ArtifactsButtonProps = { + className?: string; + compact?: boolean; +}; + +export function ArtifactsButton({ className, compact = false }: ArtifactsButtonProps) { + const shell = useOptionalShellMode(); + const artifactServer = useOptionalArtifactServer(); + const track = useTrackAnalytics(); + + const enabled = isArtifactsChromeEnabled({ artifacts: artifactServer }) && shell != null; + const open = shell?.artifactsOpen === true; + + if (!enabled) return null; + + const button = ( + + ); + + return ( +
+ {compact ? {button} : button} +
+ ); +} + +declare module '../theme/SlotsProvider.js' { + interface AtomSlots { + ArtifactsButton: typeof ArtifactsButton; + } +} diff --git a/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx b/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx index 180f5871fc..90199f5980 100644 --- a/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx +++ b/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx @@ -1,6 +1,6 @@ 'use client'; -import { useEffect, useRef, type PointerEvent as ReactPointerEvent } from 'react'; +import { useEffect, useLayoutEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from 'react'; import { clampPreviewWidth } from '../filePreview/previewPaneWidth.js'; import { FILE_PREVIEW_HIGHLIGHT_CHAR_LIMIT, type ReadFilePreviewResult } from '../filePreview/readFilePreview.js'; @@ -121,11 +121,29 @@ export function FilePreviewPanel({ }: FilePreviewPanelProps) { const panelRef = useRef(null); 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); + // Side-pane rectangle captured just before expanding, so the reveal starts from it. + const expandFromRef = useRef(null); useEffect(() => { panelRef.current?.focus(); }, [name, placement]); + useLayoutEffect(() => { + const from = expandFromRef.current; + expandFromRef.current = null; + const el = panelRef.current; + if (from == null || el == null || placement !== 'full' || typeof el.animate !== 'function') return; + if (typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches) { + return; + } + const to = el.getBoundingClientRect(); + // Content is already laid out at full size; clip-path reveals it from the old rectangle outward. + const start = `inset(${from.top - to.top}px ${to.right - from.right}px ${to.bottom - from.bottom}px ${from.left - to.left}px)`; + el.animate({ clipPath: [start, 'inset(0px)'] }, { duration: 280, easing: 'cubic-bezier(0.2, 0, 0, 1)' }); + }, [placement]); + const onResizePointerDown = (event: ReactPointerEvent) => { if (onWidthChange == null) return; event.preventDefault(); @@ -158,6 +176,7 @@ export function FilePreviewPanel({ tabIndex={-1} data-slot="aui_file-preview" data-placement={placement} + data-mount-placement={mountPlacement} aria-label={`Preview of ${name}`} onKeyDown={event => { if (event.key !== 'Escape') return; @@ -236,7 +255,10 @@ export function FilePreviewPanel({ {placement !== 'full' && onEnterFullPage != null ? ( + } + > + {SCOPE_OPTIONS.map(option => ( + onChange(option.value)} + > + {option.label} + {option.value === scope ? : null} + + ))} + + ); +} diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsEmptyState.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsEmptyState.tsx new file mode 100644 index 0000000000..a8af80846f --- /dev/null +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsEmptyState.tsx @@ -0,0 +1,30 @@ +'use client'; + +import { EmptyScreen, EmptyScreenQueryHighlight } from '../EmptyScreen.js'; +import type { ArtifactScope } from './ArtifactScopeFilter.js'; + +export function ArtifactsEmptyState({ title, scope }: { title: string; scope: ArtifactScope }) { + if (title !== '') { + return ( + + No artifacts match {title}. + + } + className="min-h-full" + /> + ); + } + if (scope === 'all') { + return ( + + ); + } + return ; +} diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx new file mode 100644 index 0000000000..89e27b2224 --- /dev/null +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx @@ -0,0 +1,283 @@ +'use client'; + +import { keepPreviousData, useQuery } from '@tanstack/react-query'; +import { useCallback, useEffect, useMemo, useRef, useState, type ComponentType } from 'react'; + +import { useTrackAnalytics } from '../../analytics/AnalyticsProvider.js'; +import { AnalyticsEvents } from '../../analytics/events.js'; +import { FilePreviewHost } from '../../containers/FilePreviewHost.js'; +import { useToasterOptional } from '../../containers/ToasterContainer.js'; +import { FilePreviewBoundary, useFilePreview } from '../../filePreview/FilePreviewContext.js'; +import { useServerQueryClient } from '../../server/queryClient.js'; +import { queryKeys } from '../../server/queryKeys.js'; +import { useArtifactServer } from '../../server/ServerContext.js'; +import { useOptionalShellMode } from '../../server/ShellModeContext.js'; +import type { Artifact, ListArtifactsParams } from '../../server/types.js'; +import { artifactIdFromRef, artifactRef } from '../../utils/artifactRef.js'; +import { getErrorMessage } from '../../utils/getErrorMessage.js'; +import { filenameFromPath, triggerBrowserDownload } from '../../utils/triggerBrowserDownload.js'; +import { EmptyScreen } from '../EmptyScreen.js'; +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 { ArtifactDeleteDialog, ArtifactEditDialog, artifactMutations } from './ArtifactEditDialog.js'; +import { ArtifactScopeFilter, type ArtifactScope } from './ArtifactScopeFilter.js'; +import { ArtifactsEmptyState } from './ArtifactsEmptyState.js'; +import { ArtifactsTable } from './ArtifactsTable.js'; + +const PAGE_SIZE_OPTIONS = [10, 25] as const; +const SEARCH_DEBOUNCE_MS = 300; +const EMPTY_ARTIFACTS: Artifact[] = []; + +function nonEmptyToken(token: string | undefined): string | undefined { + return token === undefined || token === '' ? undefined : token; +} + +export type ArtifactsPageProps = Record; + +export function ArtifactsPage(_props: ArtifactsPageProps) { + return ( + + + + ); +} + +function ArtifactsPageBody() { + const artifactServer = useArtifactServer(); + const queryClient = useServerQueryClient(); + const toaster = useToasterOptional(); + const track = useTrackAnalytics(); + const preview = useFilePreview(); + const { close: closePreview, open: openFilePreview } = preview; + const shell = useOptionalShellMode(); + const setArtifactRef = shell?.setArtifactRef; + const urlArtifactRef = shell?.artifactRef ?? null; + // Ref of the artifact whose preview this page opened; keeps URL and preview in step. + const openedRefRef = useRef(null); + + const [searchInput, setSearchInput] = useState(''); + const [title, setTitle] = useState(''); + const [scope, setScope] = useState('all'); + const [editing, setEditing] = useState(null); + const [pendingDelete, setPendingDelete] = useState(null); + const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE); + const pageScope = JSON.stringify([pageSize, title, scope]); + const [pageCursor, setPageCursor] = useState<{ scope: string; token: string | undefined }>({ + scope: pageScope, + token: undefined, + }); + const pageToken = pageCursor.scope === pageScope ? pageCursor.token : undefined; + + // The preview target outlives this page in a shared provider, so clear it on both ends. + useEffect(() => { + closePreview(); + return closePreview; + }, [closePreview]); + + useEffect(() => { + const timer = window.setTimeout(() => setTitle(searchInput.trim()), SEARCH_DEBOUNCE_MS); + return () => window.clearTimeout(timer); + }, [searchInput]); + + const listParams = useMemo( + (): ListArtifactsParams => ({ + limit: pageSize, + ...(pageToken === undefined ? {} : { pageToken }), + ...(title === '' ? {} : { title }), + scope, + }), + [pageSize, pageToken, scope, title], + ); + const listQuery = useQuery( + { + queryKey: queryKeys.artifacts.list(listParams), + queryFn: () => artifactServer.listArtifacts(listParams), + placeholderData: keepPreviousData, + }, + queryClient, + ); + + const artifacts = listQuery.data?.data ?? EMPTY_ARTIFACTS; + const listSettled = !listQuery.isPlaceholderData; + const nextPageToken = listSettled ? nonEmptyToken(listQuery.data?.nextPageToken) : undefined; + const previousPageToken = listSettled ? nonEmptyToken(listQuery.data?.previousPageToken) : undefined; + const showSkeleton = (listQuery.isPending || listQuery.isPlaceholderData) && artifacts.length === 0; + const error = + listQuery.error != null && artifacts.length === 0 + ? getErrorMessage(listQuery.error, 'Check your connection and try again.') + : null; + + const openPreview = useCallback( + (artifact: Artifact) => { + const { entryPoint, slug } = artifact; + if (entryPoint == null) return; + track(AnalyticsEvents.Artifact.PREVIEW_OPENED, { artifact_slug: slug }); + const ref = artifactRef(artifact); + openedRefRef.current = ref; + setArtifactRef?.(ref); + openFilePreview({ + name: artifact.title, + path: entryPoint, + turnId: artifactPreviewKey(artifact), + load: () => artifactServer.readArtifactFile({ slug }), + }); + }, + [artifactServer, openFilePreview, setArtifactRef, track], + ); + + // URL -> preview: deep link, or back to the list. + useEffect(() => { + if (urlArtifactRef == null) { + if (openedRefRef.current != null) { + openedRefRef.current = null; + closePreview(); + } + return; + } + if (urlArtifactRef === openedRefRef.current) return; + let cancelled = false; + void artifactServer + .getArtifact({ id: artifactIdFromRef(urlArtifactRef) }) + .then(artifact => { + if (!cancelled) openPreview(artifact); + }) + .catch((caught: unknown) => { + if (cancelled) return; + toaster?.showError(caught); + setArtifactRef?.(null); + }); + return () => { + cancelled = true; + }; + }, [urlArtifactRef, artifactServer, openPreview, closePreview, setArtifactRef, toaster]); + + // Preview -> URL: closing the panel returns to the list URL. + const previewOpen = preview.target != null; + useEffect(() => { + if (!previewOpen && openedRefRef.current != null) { + openedRefRef.current = null; + setArtifactRef?.(null); + } + }, [previewOpen, setArtifactRef]); + + const { saveTitle, deleteArtifact } = artifactMutations({ + artifactServer, + queryClient, + toaster, + track, + previewTurnId: preview.target?.turnId, + closePreview, + setArtifactRef, + openedRef: openedRefRef, + }); + + const downloadArtifact = async (artifact: Artifact) => { + if (artifact.entryPoint == null) return; + try { + const blob = await artifactServer.readArtifactFile({ slug: artifact.slug }); + triggerBrowserDownload(blob, filenameFromPath(artifact.entryPoint)); + track(AnalyticsEvents.Artifact.DOWNLOADED, { artifact_slug: artifact.slug }); + } catch (caught) { + toaster?.showError(caught); + } + }; + + const hasPageNav = nextPageToken != null || previousPageToken != null || artifacts.length > 0; + + return ( +
+ +
+ +
+ +
+ } + /> +
+
+ {error != null ? ( +
+ +
+ ) : showSkeleton ? ( +
+ {Array.from({ length: 5 }, (_, i) => ( + + ))} +
+ ) : artifacts.length === 0 ? ( + + ) : ( +
+ void downloadArtifact(artifact)} + onEdit={setEditing} + onDelete={setPendingDelete} + onShare={artifact => track(AnalyticsEvents.Artifact.SHARE_OPENED, { artifact_slug: artifact.slug })} + /> + {hasPageNav ? ( + setPageCursor({ scope: pageScope, token: previousPageToken })} + onNext={() => { + if (nextPageToken != null) setPageCursor({ scope: pageScope, token: nextPageToken }); + }} + pageSizeOptions={PAGE_SIZE_OPTIONS} + onPageSizeChange={setPageSize} + /> + ) : null} +
+ )} +
+ +
+ {editing != null ? ( + setEditing(null)} + onSave={next => { + if (editing == null) return; + void saveTitle({ artifact: editing, title: next }).then(saved => { + if (saved) setEditing(null); + }); + }} + /> + ) : null} + {pendingDelete != null ? ( + setPendingDelete(null)} + onConfirm={() => { + if (pendingDelete == null) return; + const target = pendingDelete; + setPendingDelete(null); + void deleteArtifact(target); + }} + /> + ) : null} + + ); +} + +declare module '../../theme/SlotsProvider.js' { + interface AtomSlots { + ArtifactsPage: ComponentType; + } +} diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx new file mode 100644 index 0000000000..5c07251486 --- /dev/null +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx @@ -0,0 +1,133 @@ +'use client'; + +import { useState } from 'react'; + +import { Icon } from '../../icons/Icon.js'; +import type { Artifact } from '../../server/types.js'; +import { useSlot } from '../../theme/SlotsProvider.js'; +import { auiButtonClass } from '../lib/buttonClasses.js'; +import { cn } from '../lib/cn.js'; +import { formatRelativeTime } from '../lib/dateFormat.js'; +import { Badge } from '../primitives/Badge.js'; +import { DropdownMenu, DropdownMenuSeparator } from '../primitives/DropdownMenu.js'; +import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../primitives/Table.js'; +import { RowActionItem } from '../RowActionItem.js'; +import { artifactPreviewKey, artifactTypeLabel, NO_ENTRY_POINT_REASON } from './artifactDisplay.js'; + +export type ArtifactsTableProps = { + artifacts: Artifact[]; + selectedKey: string | undefined; + onOpen: (artifact: Artifact) => void; + onDownload: (artifact: Artifact) => void; + onEdit: (artifact: Artifact) => void; + onDelete: (artifact: Artifact) => void; + onShare: (artifact: Artifact) => void; +}; + +export function ArtifactsTable({ + artifacts, + selectedKey, + onOpen, + onDownload, + onEdit, + onDelete, + onShare, +}: ArtifactsTableProps) { + const ShareSessionDialog = useSlot('ShareSessionDialog'); + const [sharing, setSharing] = useState(null); + + return ( + + + + Name + Type + Version + Updated + + + + + {artifacts.map(artifact => { + const noEntryReason = artifact.entryPoint == null ? NO_ENTRY_POINT_REASON : undefined; + return ( + onOpen(artifact)} + > + +
+ {artifact.title} + {artifact.slug} +
+
+ + + {artifactTypeLabel(artifact.entryPoint)} + + + v{artifact.latestVersion} + {formatRelativeTime(artifact.updatedAt)} + {/* Swallow here so menu clicks do not also open the preview. */} + event.stopPropagation()}> + + + + } + > + onEdit(artifact)} /> + onOpen(artifact)} /> + onDownload(artifact)} + /> + { + onShare(artifact); + setSharing(artifact); + }} + /> + + onDelete(artifact)} + /> + + {sharing?.id === artifact.id ? ( + { + if (!next) setSharing(null); + }} + trigger={} + /> + ) : null} + +
+ ); + })} +
+
+ ); +} diff --git a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts new file mode 100644 index 0000000000..1f8f1ac9eb --- /dev/null +++ b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts @@ -0,0 +1,28 @@ +import { fileExtension } from '../../filePreview/readFilePreview.js'; +import type { Artifact } from '../../server/types.js'; + +const TYPE_LABELS: Record = { + html: 'HTML', + htm: 'HTML', + md: 'Markdown', + markdown: 'Markdown', + pdf: 'PDF', + png: 'Image', + jpg: 'Image', + jpeg: 'Image', + svg: 'Image', + json: 'JSON', +}; + +export function artifactTypeLabel(entryPoint: string | null): string { + if (entryPoint == null) return 'Unknown'; + const ext = fileExtension(entryPoint); + return TYPE_LABELS[ext] ?? (ext === '' ? 'File' : ext.toUpperCase()); +} + +export const NO_ENTRY_POINT_REASON = 'This artifact has no entry file to open.'; + +/** Preview cache identity; a new version must not reuse the previous bytes. */ +export function artifactPreviewKey({ slug, latestVersion }: Pick): string { + return `${slug}@v${String(latestVersion)}`; +} diff --git a/packages/trueforge-ui/src/atoms/environments/EnvironmentsPage.tsx b/packages/trueforge-ui/src/atoms/environments/EnvironmentsPage.tsx index dfb3ccd467..24434afc9b 100644 --- a/packages/trueforge-ui/src/atoms/environments/EnvironmentsPage.tsx +++ b/packages/trueforge-ui/src/atoms/environments/EnvironmentsPage.tsx @@ -28,7 +28,7 @@ import { PageHeader } from '../PageHeader.js'; import { Badge } from '../primitives/Badge.js'; import { Button } from '../primitives/Button.js'; import ConfirmDeleteDialog from '../primitives/ConfirmDeleteDialog.js'; -import { DropdownMenu, DropdownMenuItem } from '../primitives/DropdownMenu.js'; +import { DropdownMenu } from '../primitives/DropdownMenu.js'; import SearchInput from '../primitives/SearchInput.js'; import { Skeleton } from '../primitives/Skeleton.js'; import { @@ -42,6 +42,7 @@ import { TableTokenPagination, } from '../primitives/Table.js'; import { Tooltip } from '../primitives/Tooltip.js'; +import { RowActionItem } from '../RowActionItem.js'; import { formatNetworkingSummary, formatResourcesSummary, isReservedEnvironmentName } from './environmentDisplay.js'; import { EnvironmentFormDrawer } from './EnvironmentFormDrawer.js'; import { EnvironmentStatusBadge } from './EnvironmentStatusBadge.js'; @@ -114,37 +115,6 @@ function environmentRowActionReasons({ }; } -/** A row action that stays visible when unavailable, greyed out and explaining itself on hover. */ -function EnvironmentActionItem({ - label, - icon, - reason, - className, - onClick, -}: { - label: string; - icon: string; - /** Why the action is unavailable; when set the item is disabled and shows this on hover. */ - reason: string | undefined; - className?: string; - onClick: () => void; -}) { - const item = ( - - - {label} - - ); - // The tooltip hangs off a wrapping span: a disabled item takes no mouse events of its own. - return reason === undefined ? ( - item - ) : ( - - {item} - - ); -} - export type EnvironmentsPageProps = Record; export function EnvironmentsPage(_props: EnvironmentsPageProps) { @@ -488,13 +458,13 @@ export function EnvironmentsPage(_props: EnvironmentsPageProps) { } > - setDrawer({ kind: 'edit', environment: env })} /> - - - undefined); }; @@ -731,6 +735,7 @@ export function ThreadListContainer({ + )} diff --git a/packages/trueforge-ui/src/containers/useResolvedServer.ts b/packages/trueforge-ui/src/containers/useResolvedServer.ts index 0c1462bd10..88f4dad05c 100644 --- a/packages/trueforge-ui/src/containers/useResolvedServer.ts +++ b/packages/trueforge-ui/src/containers/useResolvedServer.ts @@ -103,6 +103,7 @@ export function useResolvedServer( const trueforgeFetch = builtIn?.fetch; const catalog = builtIn?.catalog; const permissions = builtIn?.permissions; + const artifacts = builtIn?.artifacts; const [state, setState] = useState(() => { if (directServer) { @@ -128,6 +129,7 @@ export function useResolvedServer( ...(trueforgeFetch !== undefined ? { fetch: trueforgeFetch } : {}), ...(catalog != null ? { catalog } : {}), ...(permissions != null ? { permissions } : {}), + ...(artifacts != null ? { artifacts } : {}), }); }; @@ -154,7 +156,7 @@ export function useResolvedServer( return () => { cancelled = true; }; - }, [directServer, trueforgeBaseUrl, trueforgeToken, trueforgeFetch, catalog, permissions, onError]); + }, [directServer, trueforgeBaseUrl, trueforgeToken, trueforgeFetch, catalog, permissions, artifacts, onError]); return state; } diff --git a/packages/trueforge-ui/src/index.ts b/packages/trueforge-ui/src/index.ts index 6fc7a719f2..9d1bfd80d9 100644 --- a/packages/trueforge-ui/src/index.ts +++ b/packages/trueforge-ui/src/index.ts @@ -30,6 +30,10 @@ export type { ThemePreset, } from './theme/types.js'; +export { ArtifactsPage } from './atoms/artifacts/ArtifactsPage.js'; +export type { ArtifactsPageProps } from './atoms/artifacts/ArtifactsPage.js'; +export { ArtifactsButton } from './atoms/ArtifactsButton.js'; +export type { ArtifactsButtonProps } from './atoms/ArtifactsButton.js'; export { EnvironmentsPage } from './atoms/environments/EnvironmentsPage.js'; export type { EnvironmentsPageProps } from './atoms/environments/EnvironmentsPage.js'; export { EnvironmentsButton } from './atoms/EnvironmentsButton.js'; @@ -366,6 +370,8 @@ export type { AgentSpec, AgentUIServer, ApprovalDecision, + Artifact, + ArtifactServer, AuthenticateConnectorRequest, CatalogServer, CodeSnippet, @@ -396,6 +402,7 @@ export type { DefinedSkill, GithubSkill, ImportGithubSkillRequest, + ListArtifactsParams, ListPermissionsRequest, ListPermissionsResponse, ListResult, diff --git a/packages/trueforge-ui/src/layouts/DrawerLayout.tsx b/packages/trueforge-ui/src/layouts/DrawerLayout.tsx index 683de7c853..d3b253bc58 100644 --- a/packages/trueforge-ui/src/layouts/DrawerLayout.tsx +++ b/packages/trueforge-ui/src/layouts/DrawerLayout.tsx @@ -35,6 +35,7 @@ export function DrawerLayout({ className }: { className?: string }) { const AgentDetailsPage = useSlot('AgentDetailsPage'); const AgentsLibrary = useSlot('AgentsLibrary'); const SessionsPage = useSlot('SessionsPage'); + const ArtifactsPage = useSlot('ArtifactsPage'); const ShareChatButton = useSlot('ShareChatButton'); const SaveAgentButton = useSlot('SaveAgentButton'); const SelectAgentEmptyState = useSlot('SelectAgentEmptyState'); @@ -46,11 +47,17 @@ export function DrawerLayout({ className }: { className?: string }) { const sessionsOpen = shell?.sessionsOpen === true; const schedulesOpen = shell?.schedulesOpen === true; const environmentsOpen = shell?.environmentsOpen === true; - const overlayOpen = settingsOpen || libraryOpen || sessionsOpen || schedulesOpen || environmentsOpen; + const artifactsOpen = shell?.artifactsOpen === true; + const overlayOpen = settingsOpen || libraryOpen || sessionsOpen || schedulesOpen || environmentsOpen || artifactsOpen; const chatChromeActionsVisible = useChatChromeActionsVisible(); const isCreateAgent = shell != null && shellIsCreateAgent(shell.mode); const showDesktopOnlyNotice = - isMobile && (sessionsOpen || schedulesOpen || environmentsOpen || (isCreateAgent && !settingsOpen && !libraryOpen)); + isMobile && + (sessionsOpen || + schedulesOpen || + environmentsOpen || + artifactsOpen || + (isCreateAgent && !settingsOpen && !libraryOpen)); const showAgentConfig = isCreateAgent && !overlayOpen && !isMobile; const showNewActions = shell?.isNewChatEnabled !== false; @@ -64,6 +71,7 @@ export function DrawerLayout({ className }: { className?: string }) { shell?.setSettingsOpen(false); shell?.setSchedulesOpen(false); shell?.setEnvironmentsOpen(false); + shell?.setArtifactsOpen(false); void Promise.resolve(aui.threads().switchToNewThread()).catch(() => undefined); }; @@ -80,12 +88,13 @@ export function DrawerLayout({ className }: { className?: string }) { shell?.setSchedulesOpen(false); shell?.setSessionsOpen(false); shell?.setEnvironmentsOpen(false); + shell?.setArtifactsOpen(false); // Only exit create-agent when leaving the mobile Build Agent notice — not when // dismissing Agents/Schedules over an in-progress desktop builder. if (showDesktopOnlyNotice && isCreateAgent) shell?.openDraft(); }; - const showBackToChat = showDesktopOnlyNotice || libraryOpen || schedulesOpen || environmentsOpen; + const showBackToChat = showDesktopOnlyNotice || libraryOpen || schedulesOpen || environmentsOpen || artifactsOpen; return (
@@ -215,6 +224,22 @@ export function DrawerLayout({ className }: { className?: string }) { > + ) : artifactsOpen ? ( + + + Loading +
+ } + > + + ) : isIdle ? ( ) : ( diff --git a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx b/packages/trueforge-ui/src/layouts/SidebarLayout.tsx index 640fc2e28b..4eaef64439 100644 --- a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx +++ b/packages/trueforge-ui/src/layouts/SidebarLayout.tsx @@ -114,13 +114,15 @@ function SidebarNav(): ReactNode { const SessionsBrowserButton = useSlot('SessionsBrowserButton'); const SchedulesButton = useSlot('SchedulesButton'); const EnvironmentsButton = useSlot('EnvironmentsButton'); + const ArtifactsButton = useSlot('ArtifactsButton'); const showNewActions = shell?.isNewChatEnabled !== false; const overlayOpen = shell?.settingsOpen === true || shell?.libraryOpen === true || shell?.sessionsOpen === true || shell?.schedulesOpen === true || - shell?.environmentsOpen === true; + shell?.environmentsOpen === true || + shell?.artifactsOpen === true; const mode = shell?.mode; const newChatSelected = !overlayOpen && @@ -139,6 +141,7 @@ function SidebarNav(): ReactNode { shell?.setSettingsOpen(false); shell?.setSchedulesOpen(false); shell?.setEnvironmentsOpen(false); + shell?.setArtifactsOpen(false); void Promise.resolve(aui.threads().switchToNewThread()).catch(() => undefined); }; @@ -188,6 +191,7 @@ function SidebarNav(): ReactNode { + ); } @@ -288,6 +292,7 @@ export function SidebarLayout({ className }: { className?: string }) { const AgentDetailsPage = useSlot('AgentDetailsPage'); const AgentsLibrary = useSlot('AgentsLibrary'); const SessionsPage = useSlot('SessionsPage'); + const ArtifactsPage = useSlot('ArtifactsPage'); const ShareChatButton = useSlot('ShareChatButton'); const ResetAgentBuilderButton = useSlot('ResetAgentBuilderButton'); const ClearChatButton = useSlot('ClearChatButton'); @@ -306,11 +311,17 @@ export function SidebarLayout({ className }: { className?: string }) { const sessionsOpen = shell?.sessionsOpen === true; const schedulesOpen = shell?.schedulesOpen === true; const environmentsOpen = shell?.environmentsOpen === true; - const overlayOpen = settingsOpen || libraryOpen || sessionsOpen || schedulesOpen || environmentsOpen; + const artifactsOpen = shell?.artifactsOpen === true; + const overlayOpen = settingsOpen || libraryOpen || sessionsOpen || schedulesOpen || environmentsOpen || artifactsOpen; const isCreateAgent = shell != null && shellIsCreateAgent(shell.mode); - // Build Agent, Sessions, Schedules, and Environments are desktop-only; keep the URL and show a notice. + // Build Agent, Sessions, Schedules, Environments, and Artifacts are desktop-only; keep the URL and show a notice. const showDesktopOnlyNotice = - isMobile && (sessionsOpen || schedulesOpen || environmentsOpen || (isCreateAgent && !settingsOpen && !libraryOpen)); + isMobile && + (sessionsOpen || + schedulesOpen || + environmentsOpen || + artifactsOpen || + (isCreateAgent && !settingsOpen && !libraryOpen)); const showAgentConfig = isCreateAgent && !overlayOpen && !isMobile; const showRecentHistory = isRecentHistoryVisible({ overlayOpen, mode: shell?.mode }); const hasChatHeaderContent = useChatHeaderContentVisible(); @@ -475,6 +486,22 @@ export function SidebarLayout({ className }: { className?: string }) { > + ) : artifactsOpen ? ( + + + Loading + + } + > + + ) : isIdle ? ( ) : ( diff --git a/packages/trueforge-ui/src/layouts/StackChatPanel.tsx b/packages/trueforge-ui/src/layouts/StackChatPanel.tsx index 8dcc852a62..26cc43ff20 100644 --- a/packages/trueforge-ui/src/layouts/StackChatPanel.tsx +++ b/packages/trueforge-ui/src/layouts/StackChatPanel.tsx @@ -42,6 +42,7 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelPro const AgentDetailsPage = useSlot('AgentDetailsPage'); const AgentsLibrary = useSlot('AgentsLibrary'); const SessionsPage = useSlot('SessionsPage'); + const ArtifactsPage = useSlot('ArtifactsPage'); const ShareChatButton = useSlot('ShareChatButton'); const SaveAgentButton = useSlot('SaveAgentButton'); const SelectAgentEmptyState = useSlot('SelectAgentEmptyState'); @@ -52,6 +53,7 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelPro const sessionsOpen = shell?.sessionsOpen === true; const schedulesOpen = shell?.schedulesOpen === true; const environmentsOpen = shell?.environmentsOpen === true; + const artifactsOpen = shell?.artifactsOpen === true; const chatChromeActionsVisible = useChatChromeActionsVisible(); const showNewActions = shell?.isNewChatEnabled !== false; @@ -70,6 +72,7 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelPro shell?.setSettingsOpen(false); shell?.setSchedulesOpen(false); shell?.setEnvironmentsOpen(false); + shell?.setArtifactsOpen(false); void Promise.resolve(aui.threads().switchToNewThread()).catch(() => undefined); }; @@ -149,6 +152,24 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelPro + ) : artifactsOpen ? ( +
+ + + Loading +
+ } + > + + + ) : ( <>
- {libraryOpen || schedulesOpen || environmentsOpen ? ( + {libraryOpen || schedulesOpen || environmentsOpen || artifactsOpen ? (
) : artifacts.length === 0 ? ( - + ) : (
void downloadArtifact(artifact)} onEdit={setEditing} onDelete={setPendingDelete} - onShare={artifact => track(AnalyticsEvents.Artifact.SHARE_OPENED, { artifact_slug: artifact.slug })} + onShare={artifact => track(AnalyticsEvents.Artifact.SHARE_OPENED, { artifact_id: artifact.id })} /> {hasPageNav ? ( setEditing(null)} onSave={next => { if (editing == null) return; - void saveTitle({ artifact: editing, title: next }).then(saved => { + void saveName({ artifact: editing, name: next }).then(saved => { if (saved) setEditing(null); }); }} diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx index 5c07251486..ab90f7367d 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx @@ -52,7 +52,7 @@ export function ArtifactsTable({ const noEntryReason = artifact.entryPoint == null ? NO_ENTRY_POINT_REASON : undefined; return ( onOpen(artifact)} > -
- {artifact.title} - {artifact.slug} -
+ {artifact.name}
@@ -81,7 +78,7 @@ export function ArtifactsTable({ diff --git a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts index 1f8f1ac9eb..cd7d9b507f 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts +++ b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts @@ -23,6 +23,6 @@ export function artifactTypeLabel(entryPoint: string | null): string { export const NO_ENTRY_POINT_REASON = 'This artifact has no entry file to open.'; /** Preview cache identity; a new version must not reuse the previous bytes. */ -export function artifactPreviewKey({ slug, latestVersion }: Pick): string { - return `${slug}@v${String(latestVersion)}`; +export function artifactPreviewKey({ id, latestVersion }: Pick): string { + return `${id}@v${String(latestVersion)}`; } diff --git a/packages/trueforge-ui/src/containers/useResolvedServer.ts b/packages/trueforge-ui/src/containers/useResolvedServer.ts index 88f4dad05c..0ab330b879 100644 --- a/packages/trueforge-ui/src/containers/useResolvedServer.ts +++ b/packages/trueforge-ui/src/containers/useResolvedServer.ts @@ -104,6 +104,7 @@ export function useResolvedServer( const catalog = builtIn?.catalog; const permissions = builtIn?.permissions; const artifacts = builtIn?.artifacts; + const artifactsEnabled = builtIn?.artifactsEnabled === true; const [state, setState] = useState(() => { if (directServer) { @@ -130,6 +131,7 @@ export function useResolvedServer( ...(catalog != null ? { catalog } : {}), ...(permissions != null ? { permissions } : {}), ...(artifacts != null ? { artifacts } : {}), + ...(artifactsEnabled ? { artifactsEnabled: true } : {}), }); }; @@ -156,7 +158,17 @@ export function useResolvedServer( return () => { cancelled = true; }; - }, [directServer, trueforgeBaseUrl, trueforgeToken, trueforgeFetch, catalog, permissions, artifacts, onError]); + }, [ + directServer, + trueforgeBaseUrl, + trueforgeToken, + trueforgeFetch, + catalog, + permissions, + artifacts, + artifactsEnabled, + onError, + ]); return state; } diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts new file mode 100644 index 0000000000..7b3cdfdf9f --- /dev/null +++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts @@ -0,0 +1,44 @@ +/** + * Harness ArtifactServer adapter. Only `list` exists on the API; the other methods reject + * until their routes land. + */ +import type { TrueForge, TrueForgeApi } from '@truefoundry/trueforge-sdk'; +import type { Artifact, ArtifactServer, ListArtifactsParams } from '../../server/types.js'; +import { toListResult } from './chatServer.js'; + +function unavailable(action: string): Promise { + return Promise.reject(new Error(`${action} is not available yet`)); +} + +function toUiArtifact(artifact: TrueForgeApi.Artifact): Artifact { + return { + id: artifact.id, + name: artifact.name, + latestVersion: artifact.latestVersion, + entryPoint: artifact.entryPoint, + createdBySubject: artifact.createdBySubject, + createdBySessionId: artifact.createdBySessionId, + createdByAgentId: artifact.createdByAgentId, + createdAt: artifact.createdAt.toISOString(), + updatedAt: artifact.updatedAt.toISOString(), + }; +} + +export function createArtifactServer(client: TrueForge): ArtifactServer { + return { + async listArtifacts(request: ListArtifactsParams = {}) { + // `scope` stays on the page until the backend confirms it. The list route has no such param. + const page = await client.artifacts.list({ + ...(request.limit === undefined ? {} : { limit: request.limit }), + ...(request.pageToken === undefined ? {} : { pageToken: request.pageToken }), + ...(request.createdBySessionId === undefined ? {} : { createdBySessionId: request.createdBySessionId }), + ...(request.name === undefined || request.name.length === 0 ? {} : { name: request.name }), + }); + return toListResult(page, toUiArtifact); + }, + getArtifact: () => unavailable('Get artifact'), + updateArtifact: () => unavailable('Rename artifact'), + deleteArtifact: () => unavailable('Delete artifact'), + readArtifactFile: () => unavailable('Read artifact file'), + }; +} diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/index.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/index.ts index 7444f8dbc7..58ece53c31 100644 --- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/index.ts +++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/index.ts @@ -5,6 +5,7 @@ import { createTrueForgeServer } from '../../server/createTrueForgeServer.js'; import type { ArtifactServer, CatalogServer, PermissionsServer } from '../../server/types.js'; import { createHarnessAgentMetricsServer } from './agentMetricsServer.js'; import { createHarnessAgentSessionsServer } from './agentSessionsServer.js'; +import { createArtifactServer } from './artifactServer.js'; import { createHarnessBuilderServer } from './builderServer.js'; import { createConnectorCatalog } from './catalogs/connectorCatalog.js'; import { createMemoryProviderCatalog } from './catalogs/memoryProviderCatalog.js'; @@ -26,6 +27,7 @@ export { createHarnessAgentSessionsServer, type CreateHarnessAgentSessionsServerOptions, } from './agentSessionsServer.js'; +export { createArtifactServer } from './artifactServer.js'; export { createHarnessBuilderServer, modelProviderLogosByName, @@ -98,15 +100,17 @@ export type CreateTrueForgeAgentUIServerOptions = CreateTrueForgeClientOptions & catalog?: CatalogServer; /** Optional host-provided resource permissions port. */ permissions?: PermissionsServer; - /** Optional host-provided artifacts port. */ + /** Override the list-backed artifacts port. */ artifacts?: ArtifactServer; + /** Attach the list-backed port when `artifacts` is omitted. */ + artifactsEnabled?: boolean; }; /** * Compose chat + builder + agent sessions + default settings catalogs into an `AgentUIServer`. */ export function createTrueForgeAgentUIServer(options: CreateTrueForgeAgentUIServerOptions = {}) { - const { catalog: catalogOverride, permissions, artifacts, ...clientOptions } = options; + const { catalog: catalogOverride, permissions, artifacts, artifactsEnabled, ...clientOptions } = options; const client = createTrueForgeClient(clientOptions); const catalog = catalogOverride ?? @@ -119,6 +123,8 @@ export function createTrueForgeAgentUIServer(options: CreateTrueForgeAgentUIServ memoryCatalog: createMemoryProviderCatalog(client), } satisfies CatalogServer); + const resolvedArtifacts = artifacts ?? (artifactsEnabled === true ? createArtifactServer(client) : undefined); + return createTrueForgeServer({ chatServer: createHarnessChatServer({ client }), ...createHarnessBuilderServer({ client }), @@ -128,7 +134,7 @@ export function createTrueForgeAgentUIServer(options: CreateTrueForgeAgentUIServ metrics: createHarnessAgentMetricsServer({ ...clientOptions, client }), schedules: createScheduleServer({ client }), sandboxEnvironments: createSandboxEnvironmentServer({ client }), - ...(artifacts == null ? {} : { artifacts }), + ...(resolvedArtifacts != null ? { artifacts: resolvedArtifacts } : {}), permissions: permissions ?? createHarnessPermissionsServer({ client }), sessionAccess: createHarnessSessionAccessServer({ client }), getMe: async () => { diff --git a/packages/trueforge-ui/src/routing/types.ts b/packages/trueforge-ui/src/routing/types.ts index 4db772e1ed..172eae9199 100644 --- a/packages/trueforge-ui/src/routing/types.ts +++ b/packages/trueforge-ui/src/routing/types.ts @@ -42,7 +42,7 @@ export type RoutesConfig = { environments?: string | false; /** Artifacts page. `false` keeps artifacts overlay-only (no URL). Default `'/artifacts'`. */ artifacts?: string | false; - /** Artifact preview (`name-id`). `false` disables. Default `'/artifacts/:artifactRef'`. */ + /** Artifact preview (`name--id`). `false` disables. Default `'/artifacts/:artifactRef'`. */ artifact?: string | false; /** Agent builder. `false` disables its dedicated URL. Default `'/build-agent'`. */ buildAgent?: string | false; diff --git a/packages/trueforge-ui/src/server/TrueForgeServerConfig.ts b/packages/trueforge-ui/src/server/TrueForgeServerConfig.ts index ba153650ba..835bca7d7d 100644 --- a/packages/trueforge-ui/src/server/TrueForgeServerConfig.ts +++ b/packages/trueforge-ui/src/server/TrueForgeServerConfig.ts @@ -14,8 +14,10 @@ export type TrueForgeBuiltInServerConfig = { fetch?: typeof fetch; catalog?: CatalogServer; permissions?: PermissionsServer; - /** Artifacts page port; omit to hide the Artifacts surface. */ + /** Custom artifacts port. When set, it replaces the built-in list client. */ artifacts?: ArtifactServer; + /** Attach the built-in list client. Ignored when `artifacts` is set. */ + artifactsEnabled?: boolean; }; /** diff --git a/packages/trueforge-ui/src/utils/artifactRef.ts b/packages/trueforge-ui/src/utils/artifactRef.ts index ede3e8d16b..ffacfdcd21 100644 --- a/packages/trueforge-ui/src/utils/artifactRef.ts +++ b/packages/trueforge-ui/src/utils/artifactRef.ts @@ -1,15 +1,20 @@ import type { Artifact } from '../server/types.js'; -/** URL segment `title-with-hyphens-{id}`; the id is everything after the last `-`. */ -export function artifactRef({ title, id }: Pick): string { - const name = title +// Ids are lowercase ULIDs with no `-`, and the slug collapses runs of `-`, so `--` only appears as the separator. +const REF_SEPARATOR = '--'; + +/** URL segment `name-with-hyphens--{id}`. */ +export function artifactRef({ name, id }: Pick): string { + const slug = name .toLowerCase() .normalize('NFKD') .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, ''); - return name === '' ? id : `${name}-${id}`; + return slug === '' ? id : `${slug}${REF_SEPARATOR}${id}`; } +/** Reads only the id after the last `--`. The name part is display-only and is never parsed. */ export function artifactIdFromRef(ref: string): string { - return ref.slice(ref.lastIndexOf('-') + 1); + const at = ref.lastIndexOf(REF_SEPARATOR); + return at < 0 ? ref : ref.slice(at + REF_SEPARATOR.length); } diff --git a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx index 824b2a0488..82e5475a9c 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx +++ b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx @@ -13,20 +13,21 @@ import { createMockAgentUIServer, createMockArtifactServer, createMockCatalog } const subject = { subjectId: 'user-1', subjectType: 'user', subjectDisplayName: 'alice' }; -function artifact(overrides: Partial & Pick): Artifact { +function artifact(overrides: Partial & Pick): Artifact { return { latestVersion: 2, entryPoint: 'report.md', createdBySubject: subject, createdBySessionId: 'session-1', + createdByAgentId: null, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', ...overrides, }; } -const q4Brief = artifact({ id: 'a1', slug: 'q4-brief', title: 'Q4 brief' }); -const sample = [q4Brief, artifact({ id: 'a2', slug: 'empty-draft', title: 'Empty draft', entryPoint: null })]; +const q4Brief = artifact({ id: 'a1', name: 'Q4 brief' }); +const sample = [q4Brief, artifact({ id: 'a2', name: 'Empty draft', entryPoint: null })]; // FilePreviewProvider reads thread state, so the page needs a runtime like the real layouts give it. function WithRuntime({ children }: { children: ReactNode }) { @@ -57,7 +58,6 @@ describe('ArtifactsPage', () => { it('lists artifacts with type and version', async () => { renderWith(createMockArtifactServer({ listArtifacts: vi.fn(async () => ({ data: sample })) })); expect(await screen.findByText('Q4 brief')).toBeInTheDocument(); - expect(screen.getByText('q4-brief')).toBeInTheDocument(); expect(screen.getAllByText('v2')).toHaveLength(2); expect(screen.getByText('Markdown')).toBeInTheDocument(); expect(screen.getByText('Unknown')).toBeInTheDocument(); @@ -79,19 +79,19 @@ describe('ArtifactsPage', () => { expect(screen.queryByText('Failed to fetch')).not.toBeInTheDocument(); }); - it('sends the debounced search text as title', async () => { + it('sends the debounced search text as name', async () => { const listArtifacts = vi.fn(async () => ({ data: sample })); renderWith(createMockArtifactServer({ listArtifacts })); await screen.findByText('Q4 brief'); - fireEvent.change(screen.getByPlaceholderText('Search artifacts by title'), { target: { value: ' brief ' } }); - await waitFor(() => expect(listArtifacts).toHaveBeenLastCalledWith(expect.objectContaining({ title: 'brief' }))); + fireEvent.change(screen.getByPlaceholderText('Search artifacts by name'), { target: { value: ' brief ' } }); + await waitFor(() => expect(listArtifacts).toHaveBeenLastCalledWith(expect.objectContaining({ name: 'brief' }))); }); it('opens the preview from a row click by reading the artifact file', async () => { const readArtifactFile = vi.fn(async () => new Blob(['# Hello'], { type: 'text/markdown' })); renderWith(createMockArtifactServer({ listArtifacts: async () => ({ data: sample }), readArtifactFile })); fireEvent.click(await screen.findByText('Q4 brief')); - await waitFor(() => expect(readArtifactFile).toHaveBeenCalledWith({ slug: 'q4-brief' })); + await waitFor(() => expect(readArtifactFile).toHaveBeenCalledWith({ id: 'a1' })); }); it('puts the artifact in the URL on open, and deep-links by id', async () => { @@ -113,7 +113,7 @@ describe('ArtifactsPage', () => { , ); fireEvent.click(await screen.findByText('Q4 brief')); - await waitFor(() => expect(screen.getByTestId('ref')).toHaveTextContent('q4-brief-a1')); + await waitFor(() => expect(screen.getByTestId('ref')).toHaveTextContent('q4-brief--a1')); expect(getArtifact).not.toHaveBeenCalled(); }); diff --git a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/permissionsServer.test.ts b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/permissionsServer.test.ts index 8747f20cb2..22b29e9647 100644 --- a/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/permissionsServer.test.ts +++ b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/permissionsServer.test.ts @@ -31,6 +31,13 @@ describe('createTrueForgeAgentUIServer permissions', () => { expect(server.permissions?.listPermissions).toEqual(expect.any(Function)); }); + it('omits artifacts unless artifactsEnabled is set', () => { + expect(createTrueForgeAgentUIServer({ fetch: vi.fn() }).artifacts).toBeUndefined(); + expect(createTrueForgeAgentUIServer({ fetch: vi.fn(), artifactsEnabled: true }).artifacts?.listArtifacts).toEqual( + expect.any(Function), + ); + }); + it('preserves an explicit permissions port', () => { const permissions: PermissionsServer = { listPermissions: vi.fn(async (): Promise => ({ diff --git a/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx b/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx index 727de0d05a..94a5ca9729 100644 --- a/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx +++ b/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx @@ -800,14 +800,14 @@ describe('ShellRouteSync', () => { it('opens an artifact preview from a deep link and returns to the list', async () => { renderSync({ - initialEntries: ['/artifacts/q4-brief-a1'], + initialEntries: ['/artifacts/q4-brief--a1'], agentConfig: { mode: 'AgentLibraryWithComposer' }, includeArtifacts: true, }); await waitFor(() => { expect(shell.artifactsOpen).toBe(true); - expect(shell.artifactRef).toBe('q4-brief-a1'); - expect(pathname).toBe('/artifacts/q4-brief-a1'); + expect(shell.artifactRef).toBe('q4-brief--a1'); + expect(pathname).toBe('/artifacts/q4-brief--a1'); }); act(() => shell.setArtifactRef(null)); expect(pathname).toBe('/artifacts'); diff --git a/packages/trueforge-ui/test/routing/derivePlace.test.ts b/packages/trueforge-ui/test/routing/derivePlace.test.ts index d4912e3462..215c98a5f4 100644 --- a/packages/trueforge-ui/test/routing/derivePlace.test.ts +++ b/packages/trueforge-ui/test/routing/derivePlace.test.ts @@ -71,11 +71,11 @@ describe('derivePlace', () => { }); it('artifact preview is a distinct place only while artifacts is open', () => { - expect(derivePlace(snap({ artifactsOpen: true, artifactRef: 'q4-brief-a1' }))).toEqual({ + expect(derivePlace(snap({ artifactsOpen: true, artifactRef: 'q4-brief--a1' }))).toEqual({ type: 'artifact', - artifactRef: 'q4-brief-a1', + artifactRef: 'q4-brief--a1', }); - expect(derivePlace(snap({ artifactsOpen: false, artifactRef: 'q4-brief-a1' }))).toEqual({ type: 'root' }); + expect(derivePlace(snap({ artifactsOpen: false, artifactRef: 'q4-brief--a1' }))).toEqual({ type: 'root' }); }); it('schedules wins over environments when both are open', () => { diff --git a/packages/trueforge-ui/test/routing/paths.test.ts b/packages/trueforge-ui/test/routing/paths.test.ts index 26034622e7..8666749ca4 100644 --- a/packages/trueforge-ui/test/routing/paths.test.ts +++ b/packages/trueforge-ui/test/routing/paths.test.ts @@ -62,7 +62,7 @@ describe('buildPath', () => { expect(buildPath({ type: 'schedules' }, routes)).toBe('/schedules'); expect(buildPath({ type: 'environments' }, routes)).toBe('/environments'); expect(buildPath({ type: 'artifacts' }, routes)).toBe('/artifacts'); - expect(buildPath({ type: 'artifact', artifactRef: 'q4-brief-a1' }, routes)).toBe('/artifacts/q4-brief-a1'); + expect(buildPath({ type: 'artifact', artifactRef: 'q4-brief--a1' }, routes)).toBe('/artifacts/q4-brief--a1'); expect(buildPath({ type: 'buildAgent' }, routes)).toBe('/build-agent'); expect(buildPath({ type: 'agent', agentName: 'code-helper' }, routes)).toBe('/agents/code-helper'); expect(buildPath({ type: 'session', sessionId: 'abc123' }, routes)).toBe('/sessions/abc123'); @@ -193,7 +193,7 @@ describe('matchPath', () => { expect(matchPath('/schedules', routes)).toEqual({ type: 'schedules' }); expect(matchPath('/environments', routes)).toEqual({ type: 'environments' }); expect(matchPath('/artifacts', routes)).toEqual({ type: 'artifacts' }); - expect(matchPath('/artifacts/q4-brief-a1', routes)).toEqual({ type: 'artifact', artifactRef: 'q4-brief-a1' }); + expect(matchPath('/artifacts/q4-brief--a1', routes)).toEqual({ type: 'artifact', artifactRef: 'q4-brief--a1' }); expect(matchPath('/build-agent', routes)).toEqual({ type: 'buildAgent' }); expect(matchPath('/agents/a%2Fb', routes)).toEqual({ type: 'agent', agentName: 'a/b' }); expect(matchPath('/sessions', routes)).toEqual({ type: 'sessionsBrowser' }); @@ -227,7 +227,7 @@ describe('matchPath', () => { { type: 'schedules' as const }, { type: 'environments' as const }, { type: 'artifacts' as const }, - { type: 'artifact' as const, artifactRef: 'q4-brief-a1' }, + { type: 'artifact' as const, artifactRef: 'q4-brief--a1' }, { type: 'buildAgent' as const }, { type: 'agent' as const, agentName: 'weird name/1' }, { type: 'session' as const, sessionId: 'sess 9' }, diff --git a/packages/trueforge-ui/test/utils/artifactRef.test.ts b/packages/trueforge-ui/test/utils/artifactRef.test.ts index 614d3bd013..b3986d7a31 100644 --- a/packages/trueforge-ui/test/utils/artifactRef.test.ts +++ b/packages/trueforge-ui/test/utils/artifactRef.test.ts @@ -3,16 +3,22 @@ import { describe, expect, it } from 'vitest'; import { artifactIdFromRef, artifactRef } from '@/utils/artifactRef.js'; describe('artifactRef', () => { - it('joins a hyphenated title and the id', () => { - expect(artifactRef({ title: 'Q4 GTM brief!', id: 'a1' })).toBe('q4-gtm-brief-a1'); + it('joins a hyphenated name and the id', () => { + expect(artifactRef({ name: 'Q4 GTM brief!', id: 'a1' })).toBe('q4-gtm-brief--a1'); }); - it('falls back to the id when the title has no usable characters', () => { - expect(artifactRef({ title: '???', id: 'a1' })).toBe('a1'); + it('falls back to the id when the name has no usable characters', () => { + expect(artifactRef({ name: '???', id: 'a1' })).toBe('a1'); }); - it('reads the id back from the last segment', () => { - expect(artifactIdFromRef('q4-gtm-brief-a1')).toBe('a1'); + it('reads only the id after the separator, ignoring the name', () => { + expect(artifactIdFromRef('q4-gtm-brief--a1')).toBe('a1'); expect(artifactIdFromRef('a1')).toBe('a1'); }); + + it('round-trips a name whose slug contains single hyphens', () => { + const ref = artifactRef({ name: 'Roadmap - v2', id: '01hzx' }); + expect(ref).toBe('roadmap-v2--01hzx'); + expect(artifactIdFromRef(ref)).toBe('01hzx'); + }); }); From e830c498843f42c339aa745a1bdeec17e7248dcc Mon Sep 17 00:00:00 2001 From: Harshil Vasoya Date: Tue, 24 Nov 2026 11:17:43 +0530 Subject: [PATCH 03/20] feat: truncate artifact names in URLs to a maximum length of 32 characters --- packages/trueforge-ui/src/utils/artifactRef.ts | 8 ++++++-- packages/trueforge-ui/test/utils/artifactRef.test.ts | 8 ++++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/packages/trueforge-ui/src/utils/artifactRef.ts b/packages/trueforge-ui/src/utils/artifactRef.ts index ffacfdcd21..a84d72dc5f 100644 --- a/packages/trueforge-ui/src/utils/artifactRef.ts +++ b/packages/trueforge-ui/src/utils/artifactRef.ts @@ -2,14 +2,18 @@ import type { Artifact } from '../server/types.js'; // Ids are lowercase ULIDs with no `-`, and the slug collapses runs of `-`, so `--` only appears as the separator. const REF_SEPARATOR = '--'; +// Keeps long titles from producing long URLs; the id is what identifies the artifact. +const MAX_SLUG_LENGTH = 32; -/** URL segment `name-with-hyphens--{id}`. */ +/** URL segment `name-with-hyphens--{id}`, with the name truncated to `MAX_SLUG_LENGTH`. */ export function artifactRef({ name, id }: Pick): string { const slug = name .toLowerCase() .normalize('NFKD') .replace(/[^a-z0-9]+/g, '-') - .replace(/^-+|-+$/g, ''); + .replace(/^-+|-+$/g, '') + .slice(0, MAX_SLUG_LENGTH) + .replace(/-+$/g, ''); return slug === '' ? id : `${slug}${REF_SEPARATOR}${id}`; } diff --git a/packages/trueforge-ui/test/utils/artifactRef.test.ts b/packages/trueforge-ui/test/utils/artifactRef.test.ts index b3986d7a31..1ff2dfb994 100644 --- a/packages/trueforge-ui/test/utils/artifactRef.test.ts +++ b/packages/trueforge-ui/test/utils/artifactRef.test.ts @@ -16,6 +16,14 @@ describe('artifactRef', () => { expect(artifactIdFromRef('a1')).toBe('a1'); }); + it('truncates long names without leaving a trailing hyphen', () => { + const ref = artifactRef({ name: `${'word '.repeat(30)}`, id: '01hzx' }); + const slug = ref.slice(0, ref.lastIndexOf('--')); + expect(slug.length).toBeLessThanOrEqual(32); + expect(slug.endsWith('-')).toBe(false); + expect(artifactIdFromRef(ref)).toBe('01hzx'); + }); + it('round-trips a name whose slug contains single hyphens', () => { const ref = artifactRef({ name: 'Roadmap - v2', id: '01hzx' }); expect(ref).toBe('roadmap-v2--01hzx'); From 9a6971d1bbef67c5399e00fa924b5f1c7a52a3ad Mon Sep 17 00:00:00 2001 From: Harshil Vasoya Date: Tue, 24 Nov 2026 14:13:49 +0530 Subject: [PATCH 04/20] refactor: update ArtifactsButton icon and modify ArtifactsTable to display creator name instead of type and version --- .../src/atoms/ArtifactsButton.tsx | 2 +- .../src/atoms/artifacts/ArtifactsTable.tsx | 12 ++++------- .../src/atoms/artifacts/artifactDisplay.ts | 20 ------------------- .../trueforge-ui/src/icons/IconRegistry.tsx | 2 ++ .../atoms/artifacts/ArtifactsPage.test.tsx | 13 +++++++----- 5 files changed, 15 insertions(+), 34 deletions(-) diff --git a/packages/trueforge-ui/src/atoms/ArtifactsButton.tsx b/packages/trueforge-ui/src/atoms/ArtifactsButton.tsx index 34112a0071..9824b91f40 100644 --- a/packages/trueforge-ui/src/atoms/ArtifactsButton.tsx +++ b/packages/trueforge-ui/src/atoms/ArtifactsButton.tsx @@ -50,7 +50,7 @@ export function ArtifactsButton({ className, compact = false }: ArtifactsButtonP shell.setArtifactsOpen(!open); }} > - + {compact ? null : ( <> Artifacts diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx index ab90f7367d..621e031fbd 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx @@ -5,14 +5,14 @@ import { useState } from 'react'; import { Icon } from '../../icons/Icon.js'; import type { Artifact } from '../../server/types.js'; import { useSlot } from '../../theme/SlotsProvider.js'; +import { CreatedByCell } from '../CreatedByCell.js'; import { auiButtonClass } from '../lib/buttonClasses.js'; import { cn } from '../lib/cn.js'; import { formatRelativeTime } from '../lib/dateFormat.js'; -import { Badge } from '../primitives/Badge.js'; import { DropdownMenu, DropdownMenuSeparator } from '../primitives/DropdownMenu.js'; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '../primitives/Table.js'; import { RowActionItem } from '../RowActionItem.js'; -import { artifactPreviewKey, artifactTypeLabel, NO_ENTRY_POINT_REASON } from './artifactDisplay.js'; +import { artifactPreviewKey, NO_ENTRY_POINT_REASON } from './artifactDisplay.js'; export type ArtifactsTableProps = { artifacts: Artifact[]; @@ -41,8 +41,7 @@ export function ArtifactsTable({ Name - Type - Version + Created by Updated @@ -63,11 +62,8 @@ export function ArtifactsTable({ {artifact.name} - - {artifactTypeLabel(artifact.entryPoint)} - + - v{artifact.latestVersion} {formatRelativeTime(artifact.updatedAt)} {/* Swallow here so menu clicks do not also open the preview. */} event.stopPropagation()}> diff --git a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts index cd7d9b507f..cac6dc955f 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts +++ b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts @@ -1,25 +1,5 @@ -import { fileExtension } from '../../filePreview/readFilePreview.js'; import type { Artifact } from '../../server/types.js'; -const TYPE_LABELS: Record = { - html: 'HTML', - htm: 'HTML', - md: 'Markdown', - markdown: 'Markdown', - pdf: 'PDF', - png: 'Image', - jpg: 'Image', - jpeg: 'Image', - svg: 'Image', - json: 'JSON', -}; - -export function artifactTypeLabel(entryPoint: string | null): string { - if (entryPoint == null) return 'Unknown'; - const ext = fileExtension(entryPoint); - return TYPE_LABELS[ext] ?? (ext === '' ? 'File' : ext.toUpperCase()); -} - export const NO_ENTRY_POINT_REASON = 'This artifact has no entry file to open.'; /** Preview cache identity; a new version must not reuse the previous bytes. */ diff --git a/packages/trueforge-ui/src/icons/IconRegistry.tsx b/packages/trueforge-ui/src/icons/IconRegistry.tsx index e88bd1b938..0793d144aa 100644 --- a/packages/trueforge-ui/src/icons/IconRegistry.tsx +++ b/packages/trueforge-ui/src/icons/IconRegistry.tsx @@ -34,6 +34,7 @@ import { FileCode2, FileSpreadsheet, FileText, + GalleryHorizontalEnd, GripVertical, History, Info, @@ -185,6 +186,7 @@ const defaults: Record = { 'chevrons-up-down': ChevronsUpDown, loader: Loader2, file: File, + 'gallery-horizontal-end': GalleryHorizontalEnd, 'file-code': FileCode2, 'file-spreadsheet': FileSpreadsheet, 'file-text': FileText, diff --git a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx index 82e5475a9c..80323ed51b 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx +++ b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx @@ -55,12 +55,14 @@ function renderWith(artifactServer: ArtifactServer | undefined, ui = { - it('lists artifacts with type and version', async () => { + it('lists artifacts with the creator name and without type or version', async () => { renderWith(createMockArtifactServer({ listArtifacts: vi.fn(async () => ({ data: sample })) })); expect(await screen.findByText('Q4 brief')).toBeInTheDocument(); - expect(screen.getAllByText('v2')).toHaveLength(2); - expect(screen.getByText('Markdown')).toBeInTheDocument(); - expect(screen.getByText('Unknown')).toBeInTheDocument(); + expect(screen.getByRole('columnheader', { name: 'Created by' })).toBeInTheDocument(); + expect(screen.getAllByText('alice')).toHaveLength(2); + expect(screen.queryByRole('columnheader', { name: 'Type' })).not.toBeInTheDocument(); + expect(screen.queryByRole('columnheader', { name: 'Version' })).not.toBeInTheDocument(); + expect(screen.queryByText('v2')).not.toBeInTheDocument(); }); it('shows the empty state and a friendly load error', async () => { @@ -132,6 +134,7 @@ describe('ArtifactsButton', () => { withoutPort.unmount(); renderWith(createMockArtifactServer(), ); - expect(screen.getByRole('button', { name: 'Artifacts' })).toBeInTheDocument(); + const button = screen.getByRole('button', { name: 'Artifacts' }); + expect(button.querySelector('svg')).toHaveClass('lucide-gallery-horizontal-end'); }); }); From b8289e18e795f4f31dc410780b859a750bfbb511 Mon Sep 17 00:00:00 2001 From: Harshil Vasoya Date: Tue, 24 Nov 2026 14:16:19 +0530 Subject: [PATCH 05/20] refactor: update ArtifactsButton icon and modify ArtifactsTable to display creator name instead of type and version --- .../test/atoms/artifacts/ArtifactsPage.test.tsx | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx index 80323ed51b..3f9514aac4 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx +++ b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx @@ -1,7 +1,7 @@ // @vitest-environment jsdom import { AssistantRuntimeProvider, useExternalStoreRuntime, type ThreadMessageLike } from '@assistant-ui/react'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; -import type { ReactNode } from 'react'; +import { useEffect, useRef, type ReactNode } from 'react'; import { describe, expect, it, vi } from 'vitest'; import { ArtifactsButton } from '@/atoms/ArtifactsButton.js'; @@ -105,7 +105,19 @@ describe('ArtifactsPage', () => { readArtifactFile, }); function RefProbe() { - return {useOptionalShellMode()?.artifactRef ?? 'none'}; + const shell = useOptionalShellMode(); + // The shell only publishes artifactRef while the artifacts page is open. + const opened = useRef(false); + useEffect(() => { + if (shell == null || opened.current) return; + opened.current = true; + shell.setArtifactsOpen(true); + }, [shell]); + return ( + + {shell?.artifactRef ?? 'none'} + + ); } renderWith( artifacts, @@ -114,6 +126,7 @@ describe('ArtifactsPage', () => { , ); + await waitFor(() => expect(screen.getByTestId('ref')).toHaveAttribute('data-open', 'true')); fireEvent.click(await screen.findByText('Q4 brief')); await waitFor(() => expect(screen.getByTestId('ref')).toHaveTextContent('q4-brief--a1')); expect(getArtifact).not.toHaveBeenCalled(); From 95297ceec6e6a659f6740fd421b02ae6df2c1b81 Mon Sep 17 00:00:00 2001 From: harshil-2096 Date: Fri, 27 Nov 2026 05:06:29 +0000 Subject: [PATCH 06/20] feat: wire artifact rename and align artifacts UI with BE response Co-authored-by: Cursor --- .changeset/artifacts-page-flagged.md | 2 +- .../assistant-ui-runtime/src/server/types.ts | 11 +-- packages/trueforge-ui/src/analytics/events.ts | 1 - .../src/atoms/artifacts/ArtifactsPage.tsx | 12 ++- .../src/atoms/artifacts/ArtifactsTable.tsx | 46 ++---------- .../src/atoms/artifacts/artifactDisplay.ts | 8 +- .../artifactServer.ts | 12 ++- .../atoms/artifacts/ArtifactsPage.test.tsx | 45 ++++++++--- .../artifactServer.test.ts | 74 +++++++++++++++++++ 9 files changed, 130 insertions(+), 81 deletions(-) create mode 100644 packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/artifactServer.test.ts diff --git a/.changeset/artifacts-page-flagged.md b/.changeset/artifacts-page-flagged.md index 1243ae862e..8dc30ca42b 100644 --- a/.changeset/artifacts-page-flagged.md +++ b/.changeset/artifacts-page-flagged.md @@ -4,4 +4,4 @@ '@truefoundry/trueforge': patch --- -Add an Artifacts page after Environments. The standalone app shows it when `VITE_ENABLE_ARTIFACTS=true`. The list reads `GET /api/v1/artifacts`. Preview, rename, delete, and file read stay unwired until those routes exist. +Add an Artifacts page after Environments. The standalone app shows it when `VITE_ENABLE_ARTIFACTS=true`. The list reads `GET /api/v1/artifacts` with name search, and rename calls the update route. Preview, delete, share, and file read stay unwired until those routes exist. diff --git a/packages/assistant-ui-runtime/src/server/types.ts b/packages/assistant-ui-runtime/src/server/types.ts index f1fbefd0e6..be08b9baf1 100644 --- a/packages/assistant-ui-runtime/src/server/types.ts +++ b/packages/assistant-ui-runtime/src/server/types.ts @@ -1391,21 +1391,12 @@ export interface Artifact { /** Stable identifier used in URLs. Must not contain `-`. */ id: string; name: string; - /** Latest version. 0 before the first version. */ - latestVersion: number; - /** Latest version's default file to render, relative to the version. Null before the first version. */ - entryPoint: string | null; createdBySubject: Subject; - createdBySessionId: string; - /** Registry agent of the creating session. Null when the session used an inline agent spec. */ - createdByAgentId: string | null; createdAt: string; updatedAt: string; } export interface ListArtifactsParams extends Pick { - /** Only artifacts created in this session. */ - createdBySessionId?: string; /** Case-insensitive substring match on name. */ name?: string; /** @@ -1421,7 +1412,7 @@ export interface ArtifactServer { getArtifact(req: { id: string }): Promise; updateArtifact(req: { id: string; name: string }): Promise; deleteArtifact(req: { id: string }): Promise; - /** Defaults to the latest version and its `entryPoint`. */ + /** Defaults to the latest version's entry file. */ readArtifactFile(req: { id: string; version?: number; path?: string }): Promise; } diff --git a/packages/trueforge-ui/src/analytics/events.ts b/packages/trueforge-ui/src/analytics/events.ts index f606b172f3..b563a99758 100644 --- a/packages/trueforge-ui/src/analytics/events.ts +++ b/packages/trueforge-ui/src/analytics/events.ts @@ -96,7 +96,6 @@ export const AnalyticsEvents = { PAGE_OPENED: 'trueforge.artifact.page_opened', PREVIEW_OPENED: 'trueforge.artifact.preview_opened', DOWNLOADED: 'trueforge.artifact.downloaded', - SHARE_OPENED: 'trueforge.artifact.share_opened', EDITED: 'trueforge.artifact.edited', DELETED: 'trueforge.artifact.deleted', }, diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx index fe1c74596b..187b883c1b 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx @@ -15,7 +15,7 @@ import { useOptionalShellMode } from '../../server/ShellModeContext.js'; import type { Artifact, ListArtifactsParams } from '../../server/types.js'; import { artifactIdFromRef, artifactRef } from '../../utils/artifactRef.js'; import { getErrorMessage } from '../../utils/getErrorMessage.js'; -import { filenameFromPath, triggerBrowserDownload } from '../../utils/triggerBrowserDownload.js'; +import { triggerBrowserDownload } from '../../utils/triggerBrowserDownload.js'; import { EmptyScreen } from '../EmptyScreen.js'; import { PageHeader } from '../PageHeader.js'; import SearchInput from '../primitives/SearchInput.js'; @@ -112,15 +112,15 @@ function ArtifactsPageBody() { const openPreview = useCallback( (artifact: Artifact) => { - const { entryPoint, id } = artifact; - if (entryPoint == null) return; + const { id } = artifact; track(AnalyticsEvents.Artifact.PREVIEW_OPENED, { artifact_id: id }); const ref = artifactRef(artifact); openedRefRef.current = ref; setArtifactRef?.(ref); openFilePreview({ name: artifact.name, - path: entryPoint, + // 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 }), }); @@ -175,10 +175,9 @@ function ArtifactsPageBody() { }); const downloadArtifact = async (artifact: Artifact) => { - if (artifact.entryPoint == null) return; try { const blob = await artifactServer.readArtifactFile({ id: artifact.id }); - triggerBrowserDownload(blob, filenameFromPath(artifact.entryPoint)); + triggerBrowserDownload(blob, artifact.name); track(AnalyticsEvents.Artifact.DOWNLOADED, { artifact_id: artifact.id }); } catch (caught) { toaster?.showError(caught); @@ -227,7 +226,6 @@ function ArtifactsPageBody() { onDownload={artifact => void downloadArtifact(artifact)} onEdit={setEditing} onDelete={setPendingDelete} - onShare={artifact => track(AnalyticsEvents.Artifact.SHARE_OPENED, { artifact_id: artifact.id })} /> {hasPageNav ? ( void; onEdit: (artifact: Artifact) => void; onDelete: (artifact: Artifact) => void; - onShare: (artifact: Artifact) => void; }; -export function ArtifactsTable({ - artifacts, - selectedKey, - onOpen, - onDownload, - onEdit, - onDelete, - onShare, -}: ArtifactsTableProps) { - const ShareSessionDialog = useSlot('ShareSessionDialog'); - const [sharing, setSharing] = useState(null); - +export function ArtifactsTable({ artifacts, selectedKey, onOpen, onDownload, onEdit, onDelete }: ArtifactsTableProps) { return ( @@ -48,7 +33,6 @@ export function ArtifactsTable({ {artifacts.map(artifact => { - const noEntryReason = artifact.entryPoint == null ? NO_ENTRY_POINT_REASON : undefined; return ( {formatRelativeTime(artifact.updatedAt)} {/* Swallow here so menu clicks do not also open the preview. */} - event.stopPropagation()}> + event.stopPropagation()}> onEdit(artifact)} /> - onOpen(artifact)} /> + onOpen(artifact)} /> onDownload(artifact)} - /> - { - onShare(artifact); - setSharing(artifact); - }} + onClick={() => onDownload(artifact)} /> + {}} /> onDelete(artifact)} /> - {sharing?.id === artifact.id ? ( - { - if (!next) setSharing(null); - }} - trigger={} - /> - ) : null} ); diff --git a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts index cac6dc955f..6fe48e9b39 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts +++ b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts @@ -1,8 +1,8 @@ import type { Artifact } from '../../server/types.js'; -export const NO_ENTRY_POINT_REASON = 'This artifact has no entry file to open.'; +export const SHARE_UNAVAILABLE_REASON = 'Sharing artifacts is not available yet.'; -/** Preview cache identity; a new version must not reuse the previous bytes. */ -export function artifactPreviewKey({ id, latestVersion }: Pick): string { - return `${id}@v${String(latestVersion)}`; +/** 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}`; } diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts index 7b3cdfdf9f..0e415d9da7 100644 --- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts +++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts @@ -1,5 +1,5 @@ /** - * Harness ArtifactServer adapter. Only `list` exists on the API; the other methods reject + * Harness ArtifactServer adapter. `list` and rename exist on the API; the other methods reject * until their routes land. */ import type { TrueForge, TrueForgeApi } from '@truefoundry/trueforge-sdk'; @@ -14,11 +14,7 @@ function toUiArtifact(artifact: TrueForgeApi.Artifact): Artifact { return { id: artifact.id, name: artifact.name, - latestVersion: artifact.latestVersion, - entryPoint: artifact.entryPoint, createdBySubject: artifact.createdBySubject, - createdBySessionId: artifact.createdBySessionId, - createdByAgentId: artifact.createdByAgentId, createdAt: artifact.createdAt.toISOString(), updatedAt: artifact.updatedAt.toISOString(), }; @@ -31,13 +27,15 @@ export function createArtifactServer(client: TrueForge): ArtifactServer { const page = await client.artifacts.list({ ...(request.limit === undefined ? {} : { limit: request.limit }), ...(request.pageToken === undefined ? {} : { pageToken: request.pageToken }), - ...(request.createdBySessionId === undefined ? {} : { createdBySessionId: request.createdBySessionId }), ...(request.name === undefined || request.name.length === 0 ? {} : { name: request.name }), }); return toListResult(page, toUiArtifact); }, getArtifact: () => unavailable('Get artifact'), - updateArtifact: () => unavailable('Rename artifact'), + async updateArtifact({ id, name }) { + const response = await client.artifacts.update(id, { name }); + return toUiArtifact(response.data); + }, deleteArtifact: () => unavailable('Delete artifact'), readArtifactFile: () => unavailable('Read artifact file'), }; diff --git a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx index 3f9514aac4..331d46592d 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx +++ b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx @@ -2,7 +2,7 @@ import { AssistantRuntimeProvider, useExternalStoreRuntime, type ThreadMessageLike } from '@assistant-ui/react'; import { fireEvent, render, screen, waitFor } from '@testing-library/react'; import { useEffect, useRef, type ReactNode } from 'react'; -import { describe, expect, it, vi } from 'vitest'; +import { beforeAll, describe, expect, it, vi } from 'vitest'; import { ArtifactsButton } from '@/atoms/ArtifactsButton.js'; import { ArtifactsPage } from '@/atoms/artifacts/ArtifactsPage.js'; @@ -15,11 +15,7 @@ const subject = { subjectId: 'user-1', subjectType: 'user', subjectDisplayName: function artifact(overrides: Partial & Pick): Artifact { return { - latestVersion: 2, - entryPoint: 'report.md', createdBySubject: subject, - createdBySessionId: 'session-1', - createdByAgentId: null, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', ...overrides, @@ -27,7 +23,7 @@ function artifact(overrides: Partial & Pick): } const q4Brief = artifact({ id: 'a1', name: 'Q4 brief' }); -const sample = [q4Brief, artifact({ id: 'a2', name: 'Empty draft', entryPoint: null })]; +const sample = [q4Brief, artifact({ id: 'a2', name: 'Eval results' })]; // FilePreviewProvider reads thread state, so the page needs a runtime like the real layouts give it. function WithRuntime({ children }: { children: ReactNode }) { @@ -54,6 +50,17 @@ function renderWith(artifactServer: ArtifactServer | undefined, ui = { + // jsdom has no modal support, which the edit dialog relies on. + HTMLDialogElement.prototype.showModal = function showModal() { + this.setAttribute('open', ''); + }; + HTMLDialogElement.prototype.close = function close() { + this.removeAttribute('open'); + this.dispatchEvent(new Event('close')); + }; +}); + describe('ArtifactsPage', () => { it('lists artifacts with the creator name and without type or version', async () => { renderWith(createMockArtifactServer({ listArtifacts: vi.fn(async () => ({ data: sample })) })); @@ -132,11 +139,27 @@ describe('ArtifactsPage', () => { expect(getArtifact).not.toHaveBeenCalled(); }); - it('does not open a preview for an artifact without an entry file', async () => { - const readArtifactFile = vi.fn(async () => new Blob(['x'])); - renderWith(createMockArtifactServer({ listArtifacts: async () => ({ data: sample }), readArtifactFile })); - fireEvent.click(await screen.findByText('Empty draft')); - expect(readArtifactFile).not.toHaveBeenCalled(); + it('renames an artifact from the row menu and refetches the list', async () => { + const listArtifacts = vi.fn(async () => ({ data: sample })); + const updateArtifact = vi.fn(async ({ id, name }: { id: string; name: string }) => artifact({ id, name })); + renderWith(createMockArtifactServer({ listArtifacts, updateArtifact })); + await screen.findByText('Q4 brief'); + const callsBefore = listArtifacts.mock.calls.length; + + fireEvent.click(screen.getByRole('button', { name: 'Actions for Q4 brief' })); + fireEvent.click(await screen.findByText('Edit')); + fireEvent.change(await screen.findByLabelText('Artifact name'), { target: { value: ' Q4 summary ' } }); + fireEvent.click(screen.getByRole('button', { name: 'Save' })); + + await waitFor(() => expect(updateArtifact).toHaveBeenCalledWith({ id: 'a1', name: 'Q4 summary' })); + await waitFor(() => expect(listArtifacts.mock.calls.length).toBeGreaterThan(callsBefore)); + }); + + it('keeps Share disabled because artifacts carry no session to share', async () => { + renderWith(createMockArtifactServer({ listArtifacts: async () => ({ data: sample }) })); + await screen.findByText('Q4 brief'); + fireEvent.click(screen.getByRole('button', { name: 'Actions for Q4 brief' })); + expect(await screen.findByRole('menuitem', { name: 'Share' })).toBeDisabled(); }); }); 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 new file mode 100644 index 0000000000..428f6377ea --- /dev/null +++ b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/artifactServer.test.ts @@ -0,0 +1,74 @@ +import { describe, expect, it, vi } from 'vitest'; + +import { createArtifactServer } from '@/plugins/trueforge-agent-server-adapter/artifactServer.js'; +import type { TrueForge } from '@truefoundry/trueforge-sdk'; + +const createdBySubject = { + subjectId: 'user-1', + subjectType: 'user' as const, + subjectDisplayName: 'alice@example.com', +}; + +const sdkArtifact = { + id: 'a1', + name: 'Q4 brief', + createdBySubject, + createdAt: new Date('2024-01-01T00:00:00.000Z'), + updatedAt: new Date('2024-01-02T00:00:00.000Z'), +}; + +function mockClient({ + list = vi.fn(), + update = vi.fn(), +}: { + list?: ReturnType; + update?: ReturnType; +}) { + return { artifacts: { list, update } } as unknown as TrueForge; +} + +describe('createArtifactServer', () => { + it('lists artifacts with paging tokens and forwards the name search', async () => { + const list = vi.fn(async () => ({ + data: [sdkArtifact], + response: { pagination: { limit: 10, nextPageToken: 'next-1' } }, + })); + const server = createArtifactServer(mockClient({ list })); + + const page = await server.listArtifacts({ limit: 10, pageToken: 'p1', name: 'brief', scope: 'created_by_me' }); + + expect(list).toHaveBeenCalledWith({ limit: 10, pageToken: 'p1', name: 'brief' }); + expect(page.nextPageToken).toBe('next-1'); + expect(page.data).toEqual([ + { + id: 'a1', + name: 'Q4 brief', + createdBySubject, + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-02T00:00:00.000Z', + }, + ]); + }); + + 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('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' }); + + expect(update).toHaveBeenCalledWith('a1', { name: 'Renamed' }); + expect(renamed.name).toBe('Renamed'); + 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'); + }); +}); From 705a665c5f6c0fd751e55c5e6b1b33ee939cc63b Mon Sep 17 00:00:00 2001 From: harshil-2096 Date: Fri, 27 Nov 2026 05:23:08 +0000 Subject: [PATCH 07/20] feat: hide artifacts scope filter until the list API supports it The "All / Created by me / Shared with me" dropdown was never sent to the backend (the adapter drops `scope`), so it did nothing. Remove the filter and its state, the scope-aware empty-state branch, and the unused `scope` field on ListArtifactsParams. Also restyle the Artifacts sidebar item to match the other nav items (no chevron, shared hover and selected classes). Co-authored-by: Cursor --- .../assistant-ui-runtime/src/server/types.ts | 5 -- .../src/atoms/ArtifactsButton.tsx | 19 +++---- .../atoms/artifacts/ArtifactScopeFilter.tsx | 53 ------------------- .../atoms/artifacts/ArtifactsEmptyState.tsx | 20 +++---- .../src/atoms/artifacts/ArtifactsPage.tsx | 16 ++---- .../artifactServer.ts | 1 - .../atoms/artifacts/ArtifactsPage.test.tsx | 6 +++ .../artifactServer.test.ts | 2 +- 8 files changed, 30 insertions(+), 92 deletions(-) delete mode 100644 packages/trueforge-ui/src/atoms/artifacts/ArtifactScopeFilter.tsx diff --git a/packages/assistant-ui-runtime/src/server/types.ts b/packages/assistant-ui-runtime/src/server/types.ts index be08b9baf1..540c35e0a5 100644 --- a/packages/assistant-ui-runtime/src/server/types.ts +++ b/packages/assistant-ui-runtime/src/server/types.ts @@ -1399,11 +1399,6 @@ export interface Artifact { export interface ListArtifactsParams extends Pick { /** Case-insensitive substring match on name. */ name?: string; - /** - * Not on the list API yet. The page still sends it; the adapter does not forward it - * until the backend confirms `created_by_me` / `shared_with_me`. - */ - scope?: 'all' | 'created_by_me' | 'shared_with_me'; } export interface ArtifactServer { diff --git a/packages/trueforge-ui/src/atoms/ArtifactsButton.tsx b/packages/trueforge-ui/src/atoms/ArtifactsButton.tsx index 9824b91f40..7f501811b9 100644 --- a/packages/trueforge-ui/src/atoms/ArtifactsButton.tsx +++ b/packages/trueforge-ui/src/atoms/ArtifactsButton.tsx @@ -8,6 +8,8 @@ import { useOptionalShellMode } from '../server/ShellModeContext.js'; import { isArtifactsChromeEnabled } from '../server/serverChrome.js'; import { auiButtonClass, + shellHoverClassName, + shellNavSelectedClassName, shellRailSelectedClassName, sidebarButtonRadiusClassName, sidebarRailButtonClassName, @@ -38,11 +40,15 @@ export function ArtifactsButton({ className, compact = false }: ArtifactsButtonP className={auiButtonClass({ variant: 'ghost', className: cn( - 'font-normal shadow-none hover:bg-secondary-button-hover hover:text-ghost-button-text', + 'font-normal shadow-none', compact ? cn(sidebarRailButtonClassName, 'text-inherit') - : cn(sidebarButtonRadiusClassName, 'h-8 w-full !justify-start px-2.5 text-sm text-sidebar-text'), - open && shellRailSelectedClassName, + : cn( + sidebarButtonRadiusClassName, + 'h-8 w-full !justify-start px-2.5 text-sm text-sidebar-text', + shellHoverClassName, + ), + open && (compact ? shellRailSelectedClassName : shellNavSelectedClassName), ), })} onClick={() => { @@ -51,12 +57,7 @@ export function ArtifactsButton({ className, compact = false }: ArtifactsButtonP }} > - {compact ? null : ( - <> - Artifacts - - - )} + {compact ? null : Artifacts} ); diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactScopeFilter.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactScopeFilter.tsx deleted file mode 100644 index 5a54a7fbea..0000000000 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactScopeFilter.tsx +++ /dev/null @@ -1,53 +0,0 @@ -'use client'; - -import { Icon } from '../../icons/Icon.js'; -import type { ListArtifactsParams } from '../../server/types.js'; -import { auiSelectTriggerClass } from '../lib/selectClasses.js'; -import { DropdownMenu, DropdownMenuItem } from '../primitives/DropdownMenu.js'; - -export type ArtifactScope = NonNullable; - -const SCOPE_OPTIONS: readonly { value: ArtifactScope; label: string }[] = [ - { value: 'all', label: 'All artifacts' }, - { value: 'created_by_me', label: 'Created by me' }, - { value: 'shared_with_me', label: 'Shared with me' }, -]; - -export function ArtifactScopeFilter({ - scope, - onChange, -}: { - scope: ArtifactScope; - onChange: (next: ArtifactScope) => void; -}) { - const label = SCOPE_OPTIONS.find(option => option.value === scope)?.label ?? 'All artifacts'; - - return ( - - {label} - - - } - > - {SCOPE_OPTIONS.map(option => ( - onChange(option.value)} - > - {option.label} - {option.value === scope ? : null} - - ))} - - ); -} diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsEmptyState.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsEmptyState.tsx index a8af80846f..208f74592a 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsEmptyState.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsEmptyState.tsx @@ -1,9 +1,8 @@ 'use client'; import { EmptyScreen, EmptyScreenQueryHighlight } from '../EmptyScreen.js'; -import type { ArtifactScope } from './ArtifactScopeFilter.js'; -export function ArtifactsEmptyState({ title, scope }: { title: string; scope: ArtifactScope }) { +export function ArtifactsEmptyState({ title }: { title: string }) { if (title !== '') { return ( ); } - if (scope === 'all') { - return ( - - ); - } - return ; + return ( + + ); } diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx index 187b883c1b..fbd312d089 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx @@ -23,7 +23,6 @@ import { Skeleton } from '../primitives/Skeleton.js'; import { DEFAULT_TABLE_PAGE_SIZE, TableTokenPagination } from '../primitives/Table.js'; import { artifactPreviewKey } from './artifactDisplay.js'; import { ArtifactDeleteDialog, ArtifactEditDialog, artifactMutations } from './ArtifactEditDialog.js'; -import { ArtifactScopeFilter, type ArtifactScope } from './ArtifactScopeFilter.js'; import { ArtifactsEmptyState } from './ArtifactsEmptyState.js'; import { ArtifactsTable } from './ArtifactsTable.js'; @@ -60,11 +59,10 @@ function ArtifactsPageBody() { const [searchInput, setSearchInput] = useState(''); const [name, setName] = useState(''); - const [scope, setScope] = useState('all'); const [editing, setEditing] = useState(null); const [pendingDelete, setPendingDelete] = useState(null); const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE); - const pageScope = JSON.stringify([pageSize, name, scope]); + const pageScope = JSON.stringify([pageSize, name]); const [pageCursor, setPageCursor] = useState<{ scope: string; token: string | undefined }>({ scope: pageScope, token: undefined, @@ -87,9 +85,8 @@ function ArtifactsPageBody() { limit: pageSize, ...(pageToken === undefined ? {} : { pageToken }), ...(name === '' ? {} : { name }), - scope, }), - [name, pageSize, pageToken, scope], + [name, pageSize, pageToken], ); const listQuery = useQuery( { @@ -191,11 +188,8 @@ function ArtifactsPageBody() { -
- -
- +
+
} /> @@ -216,7 +210,7 @@ function ArtifactsPageBody() { ))} ) : artifacts.length === 0 ? ( - + ) : (
{ expect(screen.queryByText('Failed to fetch')).not.toBeInTheDocument(); }); + it('offers no owner filter, since the list API has no scope param yet', async () => { + renderWith(createMockArtifactServer({ listArtifacts: async () => ({ data: sample }) })); + await screen.findByText('Q4 brief'); + expect(screen.queryByRole('button', { name: 'Filter artifacts' })).not.toBeInTheDocument(); + }); + it('sends the debounced search text as name', async () => { const listArtifacts = vi.fn(async () => ({ data: sample })); renderWith(createMockArtifactServer({ listArtifacts })); 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 428f6377ea..f12062a1cb 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 @@ -35,7 +35,7 @@ describe('createArtifactServer', () => { })); const server = createArtifactServer(mockClient({ list })); - const page = await server.listArtifacts({ limit: 10, pageToken: 'p1', name: 'brief', scope: 'created_by_me' }); + const page = await server.listArtifacts({ limit: 10, pageToken: 'p1', name: 'brief' }); expect(list).toHaveBeenCalledWith({ limit: 10, pageToken: 'p1', name: 'brief' }); expect(page.nextPageToken).toBe('next-1'); From d8d01bb53bd2ae37e775c82cc17fcd101cd56e77 Mon Sep 17 00:00:00 2001 From: harshil-2096 Date: Fri, 27 Nov 2026 08:46:50 +0000 Subject: [PATCH 08/20] feat: add session artifacts listing ui --- .changeset/session-artifacts-card.md | 7 + .../assistant-ui-runtime/src/server/types.ts | 2 + packages/trueforge-ui/src/analytics/events.ts | 2 + .../trueforge-ui/src/atoms/ThreadShell.tsx | 26 ++-- .../src/atoms/artifacts/ArtifactsPage.tsx | 10 +- .../atoms/artifacts/SessionArtifactsCard.tsx | 89 +++++++++++ .../src/atoms/artifacts/artifactDisplay.ts | 40 ++++- .../src/atoms/primitives/FileTree.tsx | 106 +++++++++++++ .../containers/SessionArtifactsContainer.tsx | 85 +++++++++++ .../src/containers/ThreadContainer.tsx | 25 +++- .../trueforge-ui/src/icons/IconRegistry.tsx | 8 + .../artifactServer.ts | 6 +- packages/trueforge-ui/src/server/queryKeys.ts | 2 + .../trueforge-ui/src/theme/defaultSlots.ts | 2 + .../test/atoms/ThreadShell.test.tsx | 18 ++- .../artifacts/SessionArtifactsCard.test.tsx | 83 +++++++++++ .../test/atoms/primitives/FileTree.test.tsx | 68 +++++++++ .../SessionArtifactsContainer.test.tsx | 140 ++++++++++++++++++ .../artifactServer.test.ts | 22 ++- .../trueforge-ui/test/server/mockServer.ts | 1 + 20 files changed, 709 insertions(+), 33 deletions(-) create mode 100644 .changeset/session-artifacts-card.md create mode 100644 packages/trueforge-ui/src/atoms/artifacts/SessionArtifactsCard.tsx create mode 100644 packages/trueforge-ui/src/atoms/primitives/FileTree.tsx create mode 100644 packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx create mode 100644 packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx create mode 100644 packages/trueforge-ui/test/atoms/primitives/FileTree.test.tsx create mode 100644 packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx diff --git a/.changeset/session-artifacts-card.md b/.changeset/session-artifacts-card.md new file mode 100644 index 0000000000..7e2fce64dc --- /dev/null +++ b/.changeset/session-artifacts-card.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`. diff --git a/packages/assistant-ui-runtime/src/server/types.ts b/packages/assistant-ui-runtime/src/server/types.ts index 540c35e0a5..ee85ede1ad 100644 --- a/packages/assistant-ui-runtime/src/server/types.ts +++ b/packages/assistant-ui-runtime/src/server/types.ts @@ -1404,6 +1404,8 @@ export interface ListArtifactsParams extends Pick { /** Caller's artifacts, most recently updated first. */ listArtifacts(req?: ListArtifactsParams): 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; updateArtifact(req: { id: string; name: string }): Promise; deleteArtifact(req: { id: string }): Promise; diff --git a/packages/trueforge-ui/src/analytics/events.ts b/packages/trueforge-ui/src/analytics/events.ts index b563a99758..0d34862ed1 100644 --- a/packages/trueforge-ui/src/analytics/events.ts +++ b/packages/trueforge-ui/src/analytics/events.ts @@ -98,6 +98,8 @@ export const AnalyticsEvents = { DOWNLOADED: 'trueforge.artifact.downloaded', EDITED: 'trueforge.artifact.edited', DELETED: 'trueforge.artifact.deleted', + SESSION_CARD_PREVIEW_OPENED: 'trueforge.artifact.session_card_preview_opened', + SESSION_CARD_SHOW_MORE: 'trueforge.artifact.session_card_show_more', }, FilePreview: { RELOADED: 'trueforge.file_preview.reloaded', diff --git a/packages/trueforge-ui/src/atoms/ThreadShell.tsx b/packages/trueforge-ui/src/atoms/ThreadShell.tsx index b3019980a6..129c1c4803 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/ArtifactsPage.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx index fbd312d089..d93e892f6a 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 { ArtifactDeleteDialog, ArtifactEditDialog, artifactMutations } from './ArtifactEditDialog.js'; import { ArtifactsEmptyState } from './ArtifactsEmptyState.js'; import { ArtifactsTable } from './ArtifactsTable.js'; @@ -114,13 +114,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], ); 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..27ff3ff06f --- /dev/null +++ b/packages/trueforge-ui/src/atoms/artifacts/SessionArtifactsCard.tsx @@ -0,0 +1,89 @@ +'use client'; + +import { useState } from 'react'; + +import { Icon } from '../../icons/Icon.js'; +import type { Artifact } from '../../server/types.js'; +import { cn } from '../lib/cn.js'; +import { FileTree } from '../primitives/FileTree.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; + className?: string; +}; + +const getArtifactPath = (artifact: Artifact) => artifact.name; +const getArtifactKey = (artifact: Artifact) => artifact.id; + +export function SessionArtifactsCard({ + artifacts, + selectedKey, + onOpen, + onShowMore, + className, +}: SessionArtifactsCardProps) { + const [expanded, setExpanded] = useState(false); + const hiddenCount = Math.max(artifacts.length - SESSION_ARTIFACTS_VISIBLE_COUNT, 0); + const visible = expanded ? artifacts : artifacts.slice(0, SESSION_ARTIFACTS_VISIBLE_COUNT); + + return ( +
+

Artifacts

+ { + const type = artifactType(item); + return ( + + ); + }} + /> + {hiddenCount > 0 ? ( + + ) : null} +
+ ); +} + +declare module '../../theme/SlotsProvider.js' { + interface AtomSlots { + SessionArtifactsCard: typeof SessionArtifactsCard; + } +} diff --git a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts index 6fe48e9b39..4595027d08 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts +++ b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts @@ -1,4 +1,6 @@ -import type { Artifact } from '../../server/types.js'; +import type { SandboxFilePreviewTarget } from '../../filePreview/FilePreviewContext.js'; +import { fileExtension, inlinePreviewKind } from '../../filePreview/readFilePreview.js'; +import type { Artifact, ArtifactServer } from '../../server/types.js'; export const SHARE_UNAVAILABLE_REASON = 'Sharing artifacts is not available yet.'; @@ -6,3 +8,39 @@ export const SHARE_UNAVAILABLE_REASON = 'Sharing artifacts is not available yet. 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, +}: { + artifact: Artifact; + artifactServer: ArtifactServer; +}): SandboxFilePreviewTarget { + return { + 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: artifact.id }), + }; +} + +const VIDEO_EXT = new Set(['mp4', 'mov', 'webm', 'mkv', 'avi', 'm4v']); +const AUDIO_EXT = new Set(['mp3', 'wav', 'ogg', 'm4a', 'flac', 'aac']); + +export type ArtifactType = { label: string; icon: string }; + +const FILE_TYPE: ArtifactType = { label: 'File', icon: 'file' }; + +/** Short type label and icon for an artifact row, derived from the file name extension. */ +export function artifactType({ name }: Pick): ArtifactType { + const kind = inlinePreviewKind({ name, path: name }); + if (kind === 'image') return { label: 'Image', icon: 'file-image' }; + if (kind === 'html') return { label: 'Html', icon: 'file-code' }; + if (kind === 'pdf') return { label: 'Pdf', icon: 'file-text' }; + const extension = fileExtension(name); + if (VIDEO_EXT.has(extension)) return { label: 'Video', icon: 'file-video' }; + if (AUDIO_EXT.has(extension)) return { label: 'Audio', icon: 'file-audio' }; + return FILE_TYPE; +} diff --git a/packages/trueforge-ui/src/atoms/primitives/FileTree.tsx b/packages/trueforge-ui/src/atoms/primitives/FileTree.tsx new file mode 100644 index 0000000000..1a410da924 --- /dev/null +++ b/packages/trueforge-ui/src/atoms/primitives/FileTree.tsx @@ -0,0 +1,106 @@ +'use client'; + +import { useMemo, useState, type ReactNode } from 'react'; + +import { Icon } from '../../icons/Icon.js'; +import { cn } from '../lib/cn.js'; + +type FileTreeNode = + | { kind: 'folder'; name: string; path: string; children: FileTreeNode[] } + | { kind: 'file'; name: string; key: string; item: T }; + +export type FileTreeProps = { + items: readonly T[]; + /** Slash-separated path; every segment but the last becomes a folder row. */ + getPath: (item: T) => string; + getKey: (item: T) => string; + renderItem: (args: { item: T; name: string }) => ReactNode; + /** Folders start open unless this is false. */ + defaultExpanded?: boolean; + className?: string; +}; + +const INDENT_REM = 0.75; + +function buildTree({ + items, + getPath, + getKey, +}: Pick, 'items' | 'getPath' | 'getKey'>): FileTreeNode[] { + const root: FileTreeNode[] = []; + for (const item of items) { + // A path like `a//b/` yields empty segments; dropping them keeps the file name non-empty. + const segments = getPath(item) + .split('/') + .filter(segment => segment !== ''); + const fileName = segments.pop() ?? getPath(item); + let level = root; + let folderPath = ''; + for (const segment of segments) { + folderPath = folderPath === '' ? segment : `${folderPath}/${segment}`; + let folder = level.find(node => node.kind === 'folder' && node.name === segment); + if (folder?.kind !== 'folder') { + folder = { kind: 'folder', name: segment, path: folderPath, children: [] }; + level.push(folder); + } + level = folder.children; + } + level.push({ kind: 'file', name: fileName, key: getKey(item), item }); + } + return root; +} + +export function FileTree({ + items, + getPath, + getKey, + renderItem, + defaultExpanded = true, + className, +}: FileTreeProps) { + const tree = useMemo(() => buildTree({ items, getPath, getKey }), [items, getPath, getKey]); + // Only folders the user toggled are stored; the rest follow `defaultExpanded`. + const [toggled, setToggled] = useState>(new Set()); + + const isOpen = (path: string) => (toggled.has(path) ? !defaultExpanded : defaultExpanded); + const toggle = (path: string) => + setToggled(current => { + const next = new Set(current); + if (next.has(path)) next.delete(path); + else next.add(path); + return next; + }); + + const renderNodes = ({ nodes, depth }: { nodes: FileTreeNode[]; depth: number }): ReactNode => ( +
    + {nodes.map(node => { + if (node.kind === 'file') { + return ( +
  • + {renderItem({ item: node.item, name: node.name })} +
  • + ); + } + const open = isOpen(node.path); + return ( +
  • + + {open ? renderNodes({ nodes: node.children, depth: depth + 1 }) : null} +
  • + ); + })} +
+ ); + + return renderNodes({ nodes: tree, depth: 0 }); +} diff --git a/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx new file mode 100644 index 0000000000..c30117c958 --- /dev/null +++ b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx @@ -0,0 +1,85 @@ +'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 { artifactPreviewTarget } from '../atoms/artifacts/artifactDisplay.js'; +import { useFilePreview } from '../filePreview/FilePreviewContext.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'; + +/** 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; + +function useSessionArtifactsQuery() { + const artifactServer = useOptionalArtifactServer(); + const sessionId = useAuiState(state => state.threadListItem.remoteId); + const isRunning = useAuiState(state => state.thread.isRunning); + const queryClient = useServerQueryClient(); + const query = useQuery( + { + queryKey: queryKeys.artifacts.session(sessionId ?? ''), + queryFn: + artifactServer == null || sessionId == null || sessionId === '' + ? skipToken + : () => artifactServer.listSessionArtifacts({ sessionId }), + refetchInterval: isRunning ? SESSION_ARTIFACTS_RUN_POLL_MS : false, + }, + queryClient, + ); + return { artifactServer, sessionId: sessionId ?? null, artifacts: query.data }; +} + +/** True when the active session has artifacts, so the composer leaves room for the card column. */ +export function useSessionArtifactsVisible(): boolean { + return (useSessionArtifactsQuery().artifacts?.length ?? 0) > 0; +} + +/** Card listing the artifacts the active session produced; renders nothing when there are none. */ +export function SessionArtifactsContainer() { + const SessionArtifactsCard = useSlot('SessionArtifactsCard'); + const queryClient = useServerQueryClient(); + const track = useTrackAnalytics(); + const preview = useFilePreview(); + const { open: openFilePreview } = preview; + const isRunning = useAuiState(state => state.thread.isRunning); + const { artifactServer, sessionId, artifacts } = 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 (artifactServer == null || artifacts == null || artifacts.length === 0) return null; + + const openArtifact = (artifact: Artifact) => { + track(AnalyticsEvents.Artifact.SESSION_CARD_PREVIEW_OPENED, { artifact_id: artifact.id }); + openFilePreview(artifactPreviewTarget({ artifact, artifactServer })); + }; + + // 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. + return ( +
+ track(AnalyticsEvents.Artifact.SESSION_CARD_SHOW_MORE)} + /> +
+ ); +} diff --git a/packages/trueforge-ui/src/containers/ThreadContainer.tsx b/packages/trueforge-ui/src/containers/ThreadContainer.tsx index 754e1a1fc6..28a5597fab 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,11 @@ 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, + SessionArtifactsContainer, + useSessionArtifactsVisible, +} from './SessionArtifactsContainer.js'; import { UserEditComposerContainer } from './UserEditComposerContainer.js'; import { UserMessageContainer } from './UserMessageContainer.js'; @@ -54,6 +60,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'); @@ -80,7 +87,7 @@ export function ThreadContainer({ composer }: ThreadContainerProps) {
- + }> {isEmpty && } {isEmpty && !showMessageSkeleton && composer} {showMessageSkeleton ? ( @@ -106,12 +113,16 @@ export function ThreadContainer({ composer }: ThreadContainerProps) { {!showMessageSkeleton && !isEmpty && ( - - - - - {composer} - +
+ + + + + {composer} + +
)}
diff --git a/packages/trueforge-ui/src/icons/IconRegistry.tsx b/packages/trueforge-ui/src/icons/IconRegistry.tsx index f41f60dc5f..690a88b55a 100644 --- a/packages/trueforge-ui/src/icons/IconRegistry.tsx +++ b/packages/trueforge-ui/src/icons/IconRegistry.tsx @@ -41,9 +41,13 @@ import { EllipsisVertical, ExternalLink, File, + FileAudio, FileCode2, + FileImage, FileSpreadsheet, FileText, + FileVideo, + Folder, GalleryHorizontalEnd, GripVertical, History, @@ -202,6 +206,10 @@ const defaults: Record = { file: File, 'gallery-horizontal-end': GalleryHorizontalEnd, 'file-code': FileCode2, + 'file-image': FileImage, + 'file-video': FileVideo, + 'file-audio': FileAudio, + folder: Folder, 'file-spreadsheet': FileSpreadsheet, 'file-text': FileText, clone: Copy, diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts index 5908af6d6d..6adcb5834f 100644 --- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts +++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts @@ -1,5 +1,5 @@ /** - * Harness ArtifactServer adapter. `list` and rename exist on the API; the other methods reject + * Harness ArtifactServer adapter. List, session list and rename exist on the API; the other methods reject * until their routes land. */ import type { TrueForge, TrueForgeApi } from '@truefoundry/trueforge-sdk'; @@ -30,6 +30,10 @@ export function createArtifactServer(client: TrueForge): ArtifactServer { }); return toListResult(page, toUiArtifact); }, + async listSessionArtifacts({ sessionId }) { + const response = await client.sessions.listArtifacts(sessionId); + return response.data.map(toUiArtifact); + }, getArtifact: () => unavailable('Get artifact'), async updateArtifact({ id, name }) { const response = await client.artifacts.update(id, { name }); diff --git a/packages/trueforge-ui/src/server/queryKeys.ts b/packages/trueforge-ui/src/server/queryKeys.ts index ad22cf3ad4..87426a97b5 100644 --- a/packages/trueforge-ui/src/server/queryKeys.ts +++ b/packages/trueforge-ui/src/server/queryKeys.ts @@ -108,6 +108,8 @@ export const queryKeys = { artifacts: { all: () => key('artifacts'), list: (params: ListArtifactsParams) => key('artifacts', 'list', params), + /** Nested under `all()` so artifact rename/delete invalidation reaches the session card. */ + session: (sessionId: string) => key('artifacts', 'session', sessionId), }, metrics: { all: () => key('metrics'), diff --git a/packages/trueforge-ui/src/theme/defaultSlots.ts b/packages/trueforge-ui/src/theme/defaultSlots.ts index a4eb32fade..f69dcb6525 100644 --- a/packages/trueforge-ui/src/theme/defaultSlots.ts +++ b/packages/trueforge-ui/src/theme/defaultSlots.ts @@ -38,6 +38,7 @@ import { AgentLibraryRow, AgentsLibrary } from '../atoms/AgentsLibrary.js'; import { AgentsLibraryButton } from '../atoms/AgentsLibraryButton.js'; import { ApprovalNavBanner } from '../atoms/ApprovalNavBanner.js'; import type { ArtifactsPageProps } from '../atoms/artifacts/ArtifactsPage.js'; +import { SessionArtifactsCard } from '../atoms/artifacts/SessionArtifactsCard.js'; import { ArtifactsButton } from '../atoms/ArtifactsButton.js'; import { AssistantMessageBubble } from '../atoms/AssistantMessageBubble.js'; import { AttachmentCard } from '../atoms/AttachmentCard.js'; @@ -283,6 +284,7 @@ export const defaultSlots = { EnvironmentsButton, ArtifactsPage, ArtifactsButton, + SessionArtifactsCard, SaveAgentButton, SaveAgentForm, SelectAgentEmptyState, diff --git a/packages/trueforge-ui/test/atoms/ThreadShell.test.tsx b/packages/trueforge-ui/test/atoms/ThreadShell.test.tsx index 7f1875ea1e..f36f20875f 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', () => { @@ -55,7 +61,9 @@ describe('ThreadViewportShell', () => { 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/SessionArtifactsCard.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx new file mode 100644 index 0000000000..0c2a899d7f --- /dev/null +++ b/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx @@ -0,0 +1,83 @@ +// @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', + }; +} + +const names = ['a.png', 'b.html', 'c.mp4', 'd.mp3', '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 with 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(); + expect(screen.getAllByText('Image')).toHaveLength(1); + expect(screen.getByText('Html')).toBeInTheDocument(); + expect(screen.getByText('Video')).toBeInTheDocument(); + expect(screen.getByText('Audio')).toBeInTheDocument(); + expect(screen.getByText('Pdf')).toBeInTheDocument(); + expect(screen.getByText('File')).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('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'); + }); + + it('nests artifacts that share a folder under an expandable row', () => { + render( + , + ); + + const folder = screen.getByRole('button', { name: /assets/ }); + expect(screen.getByText('logo.png')).toBeInTheDocument(); + fireEvent.click(folder); + expect(screen.queryByText('logo.png')).not.toBeInTheDocument(); + expect(screen.getByText('demo.mp4')).toBeInTheDocument(); + }); +}); diff --git a/packages/trueforge-ui/test/atoms/primitives/FileTree.test.tsx b/packages/trueforge-ui/test/atoms/primitives/FileTree.test.tsx new file mode 100644 index 0000000000..506fd27b3c --- /dev/null +++ b/packages/trueforge-ui/test/atoms/primitives/FileTree.test.tsx @@ -0,0 +1,68 @@ +// @vitest-environment jsdom +import { fireEvent, render, screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; + +import { FileTree } from '@/atoms/primitives/FileTree.js'; + +type Entry = { id: string; path: string }; + +const entries: Entry[] = [ + { id: '1', path: 'readme.md' }, + { id: '2', path: 'references/imports.md' }, + { id: '3', path: 'references/notes.md' }, + { id: '4', path: 'references/deep/leaf.md' }, +]; + +const getPath = (entry: Entry) => entry.path; +const getKey = (entry: Entry) => entry.id; + +function renderTree(props: { defaultExpanded?: boolean } = {}) { + return render( + {name}} + {...props} + />, + ); +} + +describe('FileTree', () => { + it('renders root files plainly and groups shared folders under one chevron row', () => { + renderTree(); + + expect(screen.getByText('readme.md')).toBeInTheDocument(); + expect(screen.getAllByRole('button', { name: /references/ })).toHaveLength(1); + expect(screen.getByText('imports.md')).toBeInTheDocument(); + expect(screen.getByText('notes.md')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /deep/ })).toBeInTheDocument(); + expect(screen.getByText('leaf.md')).toBeInTheDocument(); + }); + + it('collapses and expands a folder from its row', () => { + renderTree(); + const folder = screen.getByRole('button', { name: /references/ }); + expect(folder).toHaveAttribute('aria-expanded', 'true'); + + fireEvent.click(folder); + expect(folder).toHaveAttribute('aria-expanded', 'false'); + expect(screen.queryByText('imports.md')).not.toBeInTheDocument(); + expect(screen.queryByText('leaf.md')).not.toBeInTheDocument(); + expect(screen.getByText('readme.md')).toBeInTheDocument(); + + fireEvent.click(folder); + expect(folder).toHaveAttribute('aria-expanded', 'true'); + expect(screen.getByText('imports.md')).toBeInTheDocument(); + }); + + it('starts collapsed when defaultExpanded is false', () => { + renderTree({ defaultExpanded: false }); + const folder = screen.getByRole('button', { name: /references/ }); + expect(folder).toHaveAttribute('aria-expanded', 'false'); + expect(screen.queryByText('imports.md')).not.toBeInTheDocument(); + + fireEvent.click(folder); + expect(screen.getByText('imports.md')).toBeInTheDocument(); + }); +}); 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..83865928c4 --- /dev/null +++ b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx @@ -0,0 +1,140 @@ +// @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 { SESSION_ARTIFACTS_RUN_POLL_MS, SessionArtifactsContainer } from '@/containers/SessionArtifactsContainer.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', + }; +} + +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, +}: { + artifacts: ReturnType | undefined; + track?: (eventName: string, data?: Record) => void; +}) { + const server = createMockAgentUIServer({ + catalog: createMockCatalog(), + ...(artifacts === undefined ? {} : { artifacts }), + }); + return render( + + + + + + + + + + , + ); +} + +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('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('renders nothing when the session has no artifacts', async () => { + const listSessionArtifacts = vi.fn(async () => []); + renderContainer({ artifacts: createMockArtifactServer({ listSessionArtifacts }) }); + + await waitFor(() => expect(listSessionArtifacts).toHaveBeenCalled()); + expect(screen.queryByLabelText('Session 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/plugins/trueforge-agent-server-adapter/artifactServer.test.ts b/packages/trueforge-ui/test/plugins/trueforge-agent-server-adapter/artifactServer.test.ts index f12062a1cb..dde02a53bc 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 @@ -20,11 +20,13 @@ const sdkArtifact = { function mockClient({ list = vi.fn(), update = vi.fn(), + listSessionArtifacts = vi.fn(), }: { list?: ReturnType; update?: ReturnType; + listSessionArtifacts?: ReturnType; }) { - return { artifacts: { list, update } } as unknown as TrueForge; + return { artifacts: { list, update }, sessions: { listArtifacts: listSessionArtifacts } } as unknown as TrueForge; } describe('createArtifactServer', () => { @@ -56,6 +58,24 @@ describe('createArtifactServer', () => { 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', + }, + ]); + }); + 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' }); diff --git a/packages/trueforge-ui/test/server/mockServer.ts b/packages/trueforge-ui/test/server/mockServer.ts index 55934f1b8a..95f321ce88 100644 --- a/packages/trueforge-ui/test/server/mockServer.ts +++ b/packages/trueforge-ui/test/server/mockServer.ts @@ -85,6 +85,7 @@ export function createMockSandboxEnvironmentServer( export function createMockArtifactServer(overrides: Partial = {}): ArtifactServer { return { listArtifacts: async () => ({ data: [] }), + listSessionArtifacts: async () => [], getArtifact: unavailable, updateArtifact: unavailable, deleteArtifact: unavailable, From 0a92839e988f0d61341db8bcdcbf6028b27ac65c Mon Sep 17 00:00:00 2001 From: harshil-2096 Date: Fri, 27 Nov 2026 09:02:54 +0000 Subject: [PATCH 09/20] feat: hide Share and Delete options in artifact menu until API support is available --- .changeset/artifacts-hide-share-delete.md | 6 + packages/trueforge-ui/src/analytics/events.ts | 1 - .../atoms/artifacts/ArtifactEditDialog.tsx | 108 +++++------------- .../src/atoms/artifacts/ArtifactsPage.tsx | 35 +----- .../src/atoms/artifacts/ArtifactsTable.tsx | 16 +-- .../src/atoms/artifacts/artifactDisplay.ts | 2 - packages/trueforge-ui/src/routing/paths.ts | 7 +- packages/trueforge-ui/src/routing/types.ts | 4 +- .../atoms/artifacts/ArtifactsPage.test.tsx | 6 +- .../trueforge-ui/test/routing/paths.test.ts | 11 +- 10 files changed, 60 insertions(+), 136 deletions(-) create mode 100644 .changeset/artifacts-hide-share-delete.md diff --git a/.changeset/artifacts-hide-share-delete.md b/.changeset/artifacts-hide-share-delete.md new file mode 100644 index 0000000000..10dffa2985 --- /dev/null +++ b/.changeset/artifacts-hide-share-delete.md @@ -0,0 +1,6 @@ +--- +'@truefoundry/trueforge-ui': patch +'@truefoundry/trueforge': patch +--- + +Hide Share and Delete from the artifact row menu until the API supports them, and rename artifacts through a React Query mutation. The artifact preview URL now derives from `routes.paths.artifacts`, so the separate `paths.artifact` option is removed. diff --git a/packages/trueforge-ui/src/analytics/events.ts b/packages/trueforge-ui/src/analytics/events.ts index b563a99758..56c12b33f0 100644 --- a/packages/trueforge-ui/src/analytics/events.ts +++ b/packages/trueforge-ui/src/analytics/events.ts @@ -97,7 +97,6 @@ export const AnalyticsEvents = { PREVIEW_OPENED: 'trueforge.artifact.preview_opened', DOWNLOADED: 'trueforge.artifact.downloaded', EDITED: 'trueforge.artifact.edited', - DELETED: 'trueforge.artifact.deleted', }, FilePreview: { RELOADED: 'trueforge.file_preview.reloaded', diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactEditDialog.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactEditDialog.tsx index 38d6706b46..e8eb8f3f1c 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactEditDialog.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactEditDialog.tsx @@ -1,25 +1,27 @@ 'use client'; -import type { QueryClient } from '@tanstack/react-query'; -import { useState, type MutableRefObject } from 'react'; +import { useMutation } from '@tanstack/react-query'; +import { useState } from 'react'; +import { useTrackAnalytics } from '../../analytics/AnalyticsProvider.js'; import { AnalyticsEvents } from '../../analytics/events.js'; -import type { TrackAnalytics } from '../../analytics/types.js'; -import type { useToasterOptional } from '../../containers/ToasterContainer.js'; +import { useToasterOptional } from '../../containers/ToasterContainer.js'; +import { useServerQueryClient } from '../../server/queryClient.js'; import { queryKeys } from '../../server/queryKeys.js'; -import type { Artifact, ArtifactServer } from '../../server/types.js'; +import { useArtifactServer } from '../../server/ServerContext.js'; +import type { Artifact } from '../../server/types.js'; import { auiInputClass } from '../lib/inputClasses.js'; import { Button } from '../primitives/Button.js'; -import ConfirmDeleteDialog from '../primitives/ConfirmDeleteDialog.js'; import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '../primitives/Dialog.js'; -import { artifactPreviewKey } from './artifactDisplay.js'; export function ArtifactEditDialog({ artifact, + saving, onCancel, onSave, }: { artifact: Artifact; + saving: boolean; onCancel: () => void; onSave: (name: string) => void; }) { @@ -54,7 +56,7 @@ export function ArtifactEditDialog({ onSave(trimmed)} > Save @@ -64,77 +66,23 @@ export function ArtifactEditDialog({ ); } -export function ArtifactDeleteDialog({ - artifact, - onCancel, - onConfirm, -}: { - artifact: Artifact; - onCancel: () => void; - onConfirm: () => void; -}) { - return ( - - Delete {artifact.name}? This cannot be undone. - - } - confirmLabel="Delete" - onCancel={onCancel} - onConfirm={onConfirm} - /> - ); -} +export function useRenameArtifact() { + const artifactServer = useArtifactServer(); + const queryClient = useServerQueryClient(); + const toaster = useToasterOptional(); + const track = useTrackAnalytics(); -export function artifactMutations({ - artifactServer, - queryClient, - toaster, - track, - previewTurnId, - closePreview, - setArtifactRef, - openedRef, -}: { - artifactServer: ArtifactServer; - queryClient: QueryClient; - toaster: ReturnType; - track: TrackAnalytics; - previewTurnId: string | undefined; - closePreview: () => void; - setArtifactRef: ((ref: string | null) => void) | undefined; - openedRef: MutableRefObject; -}) { - const saveName = async ({ artifact, name }: { artifact: Artifact; name: string }) => { - try { - await artifactServer.updateArtifact({ id: artifact.id, name }); - track(AnalyticsEvents.Artifact.EDITED, { artifact_id: artifact.id }); - toaster?.showSuccess({ title: 'Artifact updated' }); - void queryClient.invalidateQueries({ queryKey: queryKeys.artifacts.all() }); - return true; - } catch (caught) { - toaster?.showError(caught); - return false; - } - }; - - const deleteArtifact = async (artifact: Artifact) => { - try { - await artifactServer.deleteArtifact({ id: artifact.id }); - if (artifactPreviewKey(artifact) === previewTurnId) { - openedRef.current = null; - closePreview(); - setArtifactRef?.(null); - } - track(AnalyticsEvents.Artifact.DELETED, { artifact_id: artifact.id }); - toaster?.showSuccess({ title: 'Artifact deleted' }); - void queryClient.invalidateQueries({ queryKey: queryKeys.artifacts.all() }); - } catch (caught) { - toaster?.showError(caught); - } - }; - - return { saveName, deleteArtifact }; + return useMutation( + { + mutationFn: ({ artifact, name }: { artifact: Artifact; name: string }) => + artifactServer.updateArtifact({ id: artifact.id, name }), + onSuccess: (_updated, { artifact }) => { + track(AnalyticsEvents.Artifact.EDITED, { artifact_id: artifact.id }); + toaster?.showSuccess({ title: 'Artifact updated' }); + void queryClient.invalidateQueries({ queryKey: queryKeys.artifacts.all() }); + }, + onError: caught => toaster?.showError(caught), + }, + queryClient, + ); } diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx index fbd312d089..dab0c38535 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsPage.tsx @@ -22,7 +22,7 @@ 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 { ArtifactDeleteDialog, ArtifactEditDialog, artifactMutations } from './ArtifactEditDialog.js'; +import { ArtifactEditDialog, useRenameArtifact } from './ArtifactEditDialog.js'; import { ArtifactsEmptyState } from './ArtifactsEmptyState.js'; import { ArtifactsTable } from './ArtifactsTable.js'; @@ -60,7 +60,6 @@ function ArtifactsPageBody() { const [searchInput, setSearchInput] = useState(''); const [name, setName] = useState(''); const [editing, setEditing] = useState(null); - const [pendingDelete, setPendingDelete] = useState(null); const [pageSize, setPageSize] = useState(DEFAULT_TABLE_PAGE_SIZE); const pageScope = JSON.stringify([pageSize, name]); const [pageCursor, setPageCursor] = useState<{ scope: string; token: string | undefined }>({ @@ -160,16 +159,7 @@ function ArtifactsPageBody() { } }, [previewOpen, setArtifactRef]); - const { saveName, deleteArtifact } = artifactMutations({ - artifactServer, - queryClient, - toaster, - track, - previewTurnId: preview.target?.turnId, - closePreview, - setArtifactRef, - openedRef: openedRefRef, - }); + const renameArtifact = useRenameArtifact(); const downloadArtifact = async (artifact: Artifact) => { try { @@ -219,7 +209,6 @@ function ArtifactsPageBody() { onOpen={openPreview} onDownload={artifact => void downloadArtifact(artifact)} onEdit={setEditing} - onDelete={setPendingDelete} /> {hasPageNav ? ( setEditing(null)} - onSave={next => { - if (editing == null) return; - void saveName({ artifact: editing, name: next }).then(saved => { - if (saved) setEditing(null); - }); - }} - /> - ) : null} - {pendingDelete != null ? ( - setPendingDelete(null)} - onConfirm={() => { - if (pendingDelete == null) return; - const target = pendingDelete; - setPendingDelete(null); - void deleteArtifact(target); - }} + onSave={name => renameArtifact.mutate({ artifact: editing, name }, { onSuccess: () => setEditing(null) })} /> ) : null}
diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx index f6926b053b..f92758115b 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx @@ -6,10 +6,10 @@ import { CreatedByCell } from '../CreatedByCell.js'; import { auiButtonClass } from '../lib/buttonClasses.js'; import { cn } from '../lib/cn.js'; import { formatRelativeTime } from '../lib/dateFormat.js'; -import { DropdownMenu, DropdownMenuSeparator } from '../primitives/DropdownMenu.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, SHARE_UNAVAILABLE_REASON } from './artifactDisplay.js'; +import { artifactPreviewKey } from './artifactDisplay.js'; export type ArtifactsTableProps = { artifacts: Artifact[]; @@ -17,10 +17,9 @@ export type ArtifactsTableProps = { onOpen: (artifact: Artifact) => void; onDownload: (artifact: Artifact) => void; onEdit: (artifact: Artifact) => void; - onDelete: (artifact: Artifact) => void; }; -export function ArtifactsTable({ artifacts, selectedKey, onOpen, onDownload, onEdit, onDelete }: ArtifactsTableProps) { +export function ArtifactsTable({ artifacts, selectedKey, onOpen, onDownload, onEdit }: ArtifactsTableProps) { return (
@@ -72,15 +71,6 @@ export function ArtifactsTable({ artifacts, selectedKey, onOpen, onDownload, onE reason={undefined} onClick={() => onDownload(artifact)} /> - {}} /> - - onDelete(artifact)} - /> diff --git a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts index 6fe48e9b39..a5339ed464 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts +++ b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts @@ -1,7 +1,5 @@ import type { Artifact } from '../../server/types.js'; -export const SHARE_UNAVAILABLE_REASON = 'Sharing artifacts is not available yet.'; - /** 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}`; diff --git a/packages/trueforge-ui/src/routing/paths.ts b/packages/trueforge-ui/src/routing/paths.ts index 34be5f838d..3d4df8dffa 100644 --- a/packages/trueforge-ui/src/routing/paths.ts +++ b/packages/trueforge-ui/src/routing/paths.ts @@ -20,7 +20,6 @@ const DEFAULTS = { schedules: '/schedules', environments: '/environments', artifacts: '/artifacts', - artifact: '/artifacts/:artifactRef', buildAgent: '/build-agent', agent: '/agents/:agentName', session: '/sessions/:sessionId', @@ -42,6 +41,8 @@ function resolveOptional(value: string | false | undefined, fallback: string): s export function resolveRoutesConfig(routes?: RoutesConfig): ResolvedRoutes { const paths = routes?.paths; + // The preview is a child of the list, so disabling the list also disables the preview. + const artifacts = resolveOptional(paths?.artifacts, DEFAULTS.artifacts); return { basename: routes?.basename ?? '', root: normalizePath(paths?.root ?? DEFAULTS.root), @@ -50,8 +51,8 @@ export function resolveRoutesConfig(routes?: RoutesConfig): ResolvedRoutes { libraryAgent: resolveOptional(paths?.libraryAgent, DEFAULTS.libraryAgent), schedules: resolveOptional(paths?.schedules, DEFAULTS.schedules), environments: resolveOptional(paths?.environments, DEFAULTS.environments), - artifacts: resolveOptional(paths?.artifacts, DEFAULTS.artifacts), - artifact: resolveOptional(paths?.artifact, DEFAULTS.artifact), + artifacts, + artifact: artifacts == null ? null : `${artifacts}/:artifactRef`, buildAgent: resolveOptional(paths?.buildAgent, DEFAULTS.buildAgent), agent: resolveOptional(paths?.agent, DEFAULTS.agent), session: resolveOptional(paths?.session, DEFAULTS.session), diff --git a/packages/trueforge-ui/src/routing/types.ts b/packages/trueforge-ui/src/routing/types.ts index 7b2a3f4d38..28bfc9adf2 100644 --- a/packages/trueforge-ui/src/routing/types.ts +++ b/packages/trueforge-ui/src/routing/types.ts @@ -40,10 +40,8 @@ export type RoutesConfig = { schedules?: string | false; /** Environments page. `false` keeps environments overlay-only (no URL). Default `'/environments'`. */ environments?: string | false; - /** Artifacts page. `false` keeps artifacts overlay-only (no URL). Default `'/artifacts'`. */ + /** Artifacts page. Preview lives at `/:artifactRef`. `false` keeps artifacts overlay-only (no URL). Default `'/artifacts'`. */ artifacts?: string | false; - /** Artifact preview (`name--id`). `false` disables. Default `'/artifacts/:artifactRef'`. */ - artifact?: string | false; /** Agent builder. `false` disables its dedicated URL. Default `'/build-agent'`. */ buildAgent?: string | false; /** Immutable "Try" agent. `false` disables. Default `'/agents/:agentName'`. */ diff --git a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx index 7093d35794..6b1077f865 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx +++ b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx @@ -161,11 +161,13 @@ describe('ArtifactsPage', () => { await waitFor(() => expect(listArtifacts.mock.calls.length).toBeGreaterThan(callsBefore)); }); - it('keeps Share disabled because artifacts carry no session to share', async () => { + it('hides Share and Delete until the API supports them', async () => { renderWith(createMockArtifactServer({ listArtifacts: async () => ({ data: sample }) })); await screen.findByText('Q4 brief'); fireEvent.click(screen.getByRole('button', { name: 'Actions for Q4 brief' })); - expect(await screen.findByRole('menuitem', { name: 'Share' })).toBeDisabled(); + await screen.findByRole('menuitem', { name: 'Edit' }); + expect(screen.queryByRole('menuitem', { name: 'Share' })).not.toBeInTheDocument(); + expect(screen.queryByRole('menuitem', { name: 'Delete' })).not.toBeInTheDocument(); }); }); diff --git a/packages/trueforge-ui/test/routing/paths.test.ts b/packages/trueforge-ui/test/routing/paths.test.ts index 8666749ca4..b4913ef685 100644 --- a/packages/trueforge-ui/test/routing/paths.test.ts +++ b/packages/trueforge-ui/test/routing/paths.test.ts @@ -76,12 +76,21 @@ describe('buildPath', () => { it('returns null for disabled places', () => { const disabled = resolveRoutesConfig({ - paths: { settings: false, library: false, libraryAgent: false, agent: false }, + paths: { settings: false, library: false, libraryAgent: false, agent: false, artifacts: false }, }); expect(buildPath({ type: 'settings' }, disabled)).toBeNull(); expect(buildPath({ type: 'library' }, disabled)).toBeNull(); expect(buildPath({ type: 'libraryAgent', agentId: 'x' }, disabled)).toBeNull(); expect(buildPath({ type: 'agent', agentName: 'x' }, disabled)).toBeNull(); + expect(buildPath({ type: 'artifacts' }, disabled)).toBeNull(); + expect(buildPath({ type: 'artifact', artifactRef: 'x--a1' }, disabled)).toBeNull(); + }); + + it('nests the artifact preview under a custom artifacts path', () => { + const custom = resolveRoutesConfig({ paths: { artifacts: '/files' } }); + expect(custom.artifact).toBe('/files/:artifactRef'); + expect(buildPath({ type: 'artifact', artifactRef: 'q4--a1' }, custom)).toBe('/files/q4--a1'); + expect(matchPath('/files/q4--a1', custom)).toEqual({ type: 'artifact', artifactRef: 'q4--a1' }); }); it('builds an absolute resume href with basename and cleared share search', () => { From a5323024277c7a80c01d74173d2494f438bbfbb3 Mon Sep 17 00:00:00 2001 From: harshil-2096 Date: Fri, 27 Nov 2026 11:34:51 +0000 Subject: [PATCH 10/20] implement session artifacts toggle and update artifact icons --- .changeset/artifact-image-icon-tree.md | 6 +++ .changeset/session-artifacts-toggle.md | 6 +++ packages/trueforge-ui/src/analytics/events.ts | 1 + .../src/atoms/FilePreviewPanel.tsx | 3 +- .../SessionArtifactsToggleButton.tsx | 42 +++++++++++++++++++ .../src/atoms/artifacts/artifactDisplay.ts | 2 +- .../containers/SessionArtifactsContainer.tsx | 17 ++++++-- .../SessionArtifactsPanelContext.tsx | 22 ++++++++++ .../src/containers/TrueForgeUIShell.tsx | 7 +++- .../trueforge-ui/src/icons/IconRegistry.tsx | 2 + .../trueforge-ui/src/layouts/DrawerLayout.tsx | 2 + .../src/layouts/SidebarLayout.tsx | 2 + .../src/layouts/StackChatPanel.tsx | 2 + .../trueforge-ui/src/theme/defaultSlots.ts | 2 + .../SessionArtifactsContainer.test.tsx | 42 ++++++++++++++++++- 15 files changed, 149 insertions(+), 9 deletions(-) create mode 100644 .changeset/artifact-image-icon-tree.md create mode 100644 .changeset/session-artifacts-toggle.md create mode 100644 packages/trueforge-ui/src/atoms/artifacts/SessionArtifactsToggleButton.tsx create mode 100644 packages/trueforge-ui/src/containers/SessionArtifactsPanelContext.tsx diff --git a/.changeset/artifact-image-icon-tree.md b/.changeset/artifact-image-icon-tree.md new file mode 100644 index 0000000000..fa5b21dafa --- /dev/null +++ b/.changeset/artifact-image-icon-tree.md @@ -0,0 +1,6 @@ +--- +'@truefoundry/trueforge-ui': patch +'@truefoundry/trueforge': patch +--- + +Use the Lucide `image` icon for image artifacts in the session tree and file preview header. diff --git a/.changeset/session-artifacts-toggle.md b/.changeset/session-artifacts-toggle.md new file mode 100644 index 0000000000..88c5c78d89 --- /dev/null +++ b/.changeset/session-artifacts-toggle.md @@ -0,0 +1,6 @@ +--- +'@truefoundry/trueforge-ui': patch +'@truefoundry/trueforge': patch +--- + +Add an Artifacts button before Share in the chat header, shown once the session has artifacts, to hide or show the session artifacts card. diff --git a/packages/trueforge-ui/src/analytics/events.ts b/packages/trueforge-ui/src/analytics/events.ts index 1fc9efb5c4..965bcd69e9 100644 --- a/packages/trueforge-ui/src/analytics/events.ts +++ b/packages/trueforge-ui/src/analytics/events.ts @@ -99,6 +99,7 @@ export const AnalyticsEvents = { EDITED: 'trueforge.artifact.edited', 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', diff --git a/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx b/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx index 6df792a037..c002732633 100644 --- a/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx +++ b/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx @@ -6,6 +6,7 @@ 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'; @@ -235,7 +236,7 @@ export function FilePreviewPanel({ ) : null}
- + {name} {onReload != null ? ( + ); +} + +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 5fd76b0f57..ca12f13443 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts +++ b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts @@ -34,7 +34,7 @@ const FILE_TYPE: ArtifactType = { label: 'File', icon: 'file' }; /** Short type label and icon for an artifact row, derived from the file name extension. */ export function artifactType({ name }: Pick): ArtifactType { const kind = inlinePreviewKind({ name, path: name }); - if (kind === 'image') return { label: 'Image', icon: 'file-image' }; + 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' }; const extension = fileExtension(name); diff --git a/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx index c30117c958..5a141db57e 100644 --- a/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx +++ b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx @@ -13,6 +13,7 @@ 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 { 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]'; @@ -39,17 +40,25 @@ function useSessionArtifactsQuery() { return { artifactServer, sessionId: sessionId ?? null, artifacts: query.data }; } -/** True when the active session has artifacts, so the composer leaves room for the card column. */ -export function useSessionArtifactsVisible(): boolean { +/** True when the active session has artifacts, whether or not the card is currently shown. */ +export function useSessionArtifactsAvailable(): boolean { return (useSessionArtifactsQuery().artifacts?.length ?? 0) > 0; } -/** Card listing the artifacts the active session produced; renders nothing when there are none. */ +/** True when the card column is on screen, so the composer leaves room for it. */ +export function useSessionArtifactsVisible(): boolean { + const available = useSessionArtifactsAvailable(); + const panel = useOptionalSessionArtifactsPanel(); + return available && (panel?.open ?? true); +} + +/** Card listing the artifacts the active session produced; renders nothing when there are none or it is hidden. */ 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 { artifactServer, sessionId, artifacts } = useSessionArtifactsQuery(); @@ -63,7 +72,7 @@ export function SessionArtifactsContainer() { wasRunning.current = isRunning; }, [isRunning, queryClient, sessionId]); - if (artifactServer == null || artifacts == null || artifacts.length === 0) return null; + if (artifactServer == null || artifacts == null || artifacts.length === 0 || panel?.open === false) return null; const openArtifact = (artifact: Artifact) => { track(AnalyticsEvents.Artifact.SESSION_CARD_PREVIEW_OPENED, { artifact_id: artifact.id }); diff --git a/packages/trueforge-ui/src/containers/SessionArtifactsPanelContext.tsx b/packages/trueforge-ui/src/containers/SessionArtifactsPanelContext.tsx new file mode 100644 index 0000000000..f8abeeb03a --- /dev/null +++ b/packages/trueforge-ui/src/containers/SessionArtifactsPanelContext.tsx @@ -0,0 +1,22 @@ +'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. */ +export function SessionArtifactsPanelProvider({ children }: { children: ReactNode }) { + const [open, setOpen] = useState(true); + 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/TrueForgeUIShell.tsx b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx index 86b4ef09b3..2aebd94d89 100644 --- a/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx +++ b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx @@ -31,6 +31,7 @@ import type { AgentUIServer, CreateSessionRequest } from '../server/types.js'; import { SlotsProvider, useThemeMode, type SlotOverrides } from '../theme/SlotsProvider.js'; import type { LayoutProp, ThemeConfig } from '../theme/types.js'; import { getErrorMessage } from '../utils/getErrorMessage.js'; +import { SessionArtifactsPanelProvider } from './SessionArtifactsPanelContext.js'; import { ToasterProvider } from './ToasterContainer.js'; import { TrueForgeChatProvider, type TrueForgeChatProviderProps } from './TrueForgeChatProvider.js'; import { useResolvedServer } from './useResolvedServer.js'; @@ -331,7 +332,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/icons/IconRegistry.tsx b/packages/trueforge-ui/src/icons/IconRegistry.tsx index 690a88b55a..e777194143 100644 --- a/packages/trueforge-ui/src/icons/IconRegistry.tsx +++ b/packages/trueforge-ui/src/icons/IconRegistry.tsx @@ -51,6 +51,7 @@ import { GalleryHorizontalEnd, GripVertical, History, + Image, Info, Layers, Layers2, @@ -207,6 +208,7 @@ const defaults: Record = { 'gallery-horizontal-end': GalleryHorizontalEnd, 'file-code': FileCode2, 'file-image': FileImage, + image: Image, 'file-video': FileVideo, 'file-audio': FileAudio, folder: Folder, diff --git a/packages/trueforge-ui/src/layouts/DrawerLayout.tsx b/packages/trueforge-ui/src/layouts/DrawerLayout.tsx index 0f0d4cb32d..f3cbee37b8 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 SelectAgentEmptyState = useSlot('SelectAgentEmptyState'); const UserAvatar = useSlot('UserAvatar'); @@ -119,6 +120,7 @@ export function DrawerLayout({ className }: { className?: string }) { {!overlayOpen && !showDesktopOnlyNotice ? ( <> + diff --git a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx b/packages/trueforge-ui/src/layouts/SidebarLayout.tsx index b299891cf5..9cf422f627 100644 --- a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx +++ b/packages/trueforge-ui/src/layouts/SidebarLayout.tsx @@ -485,6 +485,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'); @@ -603,6 +604,7 @@ function SidebarLayoutBody({ className }: { className?: string }) { !overlayOpen && !showDesktopOnlyNotice ? ( <> + diff --git a/packages/trueforge-ui/src/layouts/StackChatPanel.tsx b/packages/trueforge-ui/src/layouts/StackChatPanel.tsx index d8b08b3862..d14ee48dc2 100644 --- a/packages/trueforge-ui/src/layouts/StackChatPanel.tsx +++ b/packages/trueforge-ui/src/layouts/StackChatPanel.tsx @@ -40,6 +40,7 @@ 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 SelectAgentEmptyState = useSlot('SelectAgentEmptyState'); const UserAvatar = useSlot('UserAvatar'); @@ -179,6 +180,7 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelPro end={ <> + diff --git a/packages/trueforge-ui/src/theme/defaultSlots.ts b/packages/trueforge-ui/src/theme/defaultSlots.ts index f69dcb6525..d25153a470 100644 --- a/packages/trueforge-ui/src/theme/defaultSlots.ts +++ b/packages/trueforge-ui/src/theme/defaultSlots.ts @@ -39,6 +39,7 @@ import { AgentsLibraryButton } from '../atoms/AgentsLibraryButton.js'; import { ApprovalNavBanner } from '../atoms/ApprovalNavBanner.js'; import type { ArtifactsPageProps } from '../atoms/artifacts/ArtifactsPage.js'; import { SessionArtifactsCard } from '../atoms/artifacts/SessionArtifactsCard.js'; +import { SessionArtifactsToggleButton } from '../atoms/artifacts/SessionArtifactsToggleButton.js'; import { ArtifactsButton } from '../atoms/ArtifactsButton.js'; import { AssistantMessageBubble } from '../atoms/AssistantMessageBubble.js'; import { AttachmentCard } from '../atoms/AttachmentCard.js'; @@ -285,6 +286,7 @@ export const defaultSlots = { ArtifactsPage, ArtifactsButton, SessionArtifactsCard, + SessionArtifactsToggleButton, SaveAgentButton, SaveAgentForm, SelectAgentEmptyState, diff --git a/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx index 83865928c4..d3dcec2798 100644 --- a/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx +++ b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx @@ -4,7 +4,9 @@ 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 { 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'; @@ -50,9 +52,11 @@ function PreviewProbe() { function renderContainer({ artifacts, track, + withToggle = false, }: { artifacts: ReturnType | undefined; track?: (eventName: string, data?: Record) => void; + withToggle?: boolean; }) { const server = createMockAgentUIServer({ catalog: createMockCatalog(), @@ -63,8 +67,11 @@ function renderContainer({ - - + + {withToggle ? : null} + + + @@ -118,6 +125,37 @@ describe('SessionArtifactsContainer', () => { 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'); + + fireEvent.click(toggle); + expect(screen.queryByLabelText('Session artifacts')).not.toBeInTheDocument(); + 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(screen.getByLabelText('Session artifacts')).toBeInTheDocument(); + expect(track).toHaveBeenCalledWith(AnalyticsEvents.Artifact.SESSION_CARD_TOGGLED, { open: true }); + }); + + it('shows no toggle when the session has no artifacts', async () => { + const listSessionArtifacts = vi.fn(async () => []); + renderContainer({ artifacts: createMockArtifactServer({ listSessionArtifacts }), withToggle: true }); + + await waitFor(() => expect(listSessionArtifacts).toHaveBeenCalled()); + expect(screen.queryByRole('button', { name: 'Artifacts' })).not.toBeInTheDocument(); + }); + it('renders nothing when the session has no artifacts', async () => { const listSessionArtifacts = vi.fn(async () => []); renderContainer({ artifacts: createMockArtifactServer({ listSessionArtifacts }) }); From e1850881bdb3072612f1d3d8b773b1c31f80d87b Mon Sep 17 00:00:00 2001 From: harshil-2096 Date: Fri, 27 Nov 2026 11:46:35 +0000 Subject: [PATCH 11/20] enhance session artifacts container with transition effects and improve visibility logic --- .../containers/SessionArtifactsContainer.tsx | 34 ++++++++++++++----- .../src/containers/ThreadContainer.tsx | 7 +++- .../SessionArtifactsContainer.test.tsx | 9 +++-- 3 files changed, 38 insertions(+), 12 deletions(-) diff --git a/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx index 5a141db57e..be7abfe5e3 100644 --- a/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx +++ b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx @@ -7,6 +7,7 @@ import { useTrackAnalytics } from '../analytics/AnalyticsProvider.js'; import { AnalyticsEvents } from '../analytics/events.js'; import { useAuiState } from '../assistant-ui.js'; import { artifactPreviewTarget } from '../atoms/artifacts/artifactDisplay.js'; +import { cn } from '../atoms/lib/cn.js'; import { useFilePreview } from '../filePreview/FilePreviewContext.js'; import { useServerQueryClient } from '../server/queryClient.js'; import { queryKeys } from '../server/queryKeys.js'; @@ -21,6 +22,9 @@ 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 useSessionArtifactsQuery() { const artifactServer = useOptionalArtifactServer(); const sessionId = useAuiState(state => state.threadListItem.remoteId); @@ -52,7 +56,7 @@ export function useSessionArtifactsVisible(): boolean { return available && (panel?.open ?? true); } -/** Card listing the artifacts the active session produced; renders nothing when there are none or it is hidden. */ +/** Card listing the artifacts the active session produced; renders nothing when there are none. */ export function SessionArtifactsContainer() { const SessionArtifactsCard = useSlot('SessionArtifactsCard'); const queryClient = useServerQueryClient(); @@ -72,8 +76,9 @@ export function SessionArtifactsContainer() { wasRunning.current = isRunning; }, [isRunning, queryClient, sessionId]); - if (artifactServer == null || artifacts == null || artifacts.length === 0 || panel?.open === false) return null; + if (artifactServer == null || artifacts == null || artifacts.length === 0) return null; + const open = panel?.open !== false; const openArtifact = (artifact: Artifact) => { track(AnalyticsEvents.Artifact.SESSION_CARD_PREVIEW_OPENED, { artifact_id: artifact.id }); openFilePreview(artifactPreviewTarget({ artifact, artifactServer })); @@ -81,14 +86,25 @@ export function SessionArtifactsContainer() { // 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 ( -
- track(AnalyticsEvents.Artifact.SESSION_CARD_SHOW_MORE)} - /> + ); } diff --git a/packages/trueforge-ui/src/containers/ThreadContainer.tsx b/packages/trueforge-ui/src/containers/ThreadContainer.tsx index 28a5597fab..2a05b3ce13 100644 --- a/packages/trueforge-ui/src/containers/ThreadContainer.tsx +++ b/packages/trueforge-ui/src/containers/ThreadContainer.tsx @@ -18,6 +18,7 @@ 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'; @@ -114,7 +115,11 @@ export function ThreadContainer({ composer }: ThreadContainerProps) { {!showMessageSkeleton && !isEmpty && (
diff --git a/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx index d3dcec2798..3000442788 100644 --- a/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx +++ b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx @@ -138,13 +138,18 @@ describe('SessionArtifactsContainer', () => { 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); - expect(screen.queryByLabelText('Session artifacts')).not.toBeInTheDocument(); + // The column collapses in place rather than unmounting, so it can animate. + expect(column()).toHaveAttribute('data-state', 'closed'); + expect(column()).toHaveClass('invisible'); 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(screen.getByLabelText('Session artifacts')).toBeInTheDocument(); + expect(column()).toHaveAttribute('data-state', 'open'); expect(track).toHaveBeenCalledWith(AnalyticsEvents.Artifact.SESSION_CARD_TOGGLED, { open: true }); }); From fd8307aeaa713d3ee88d11d81b83d1ece1c09343 Mon Sep 17 00:00:00 2001 From: harshil-2096 Date: Tue, 1 Dec 2026 08:38:55 +0000 Subject: [PATCH 12/20] refactor: enhance session artifacts functionality with improved empty state handling and toggle behavior --- .../trueforge-ui/src/atoms/ThreadShell.tsx | 2 +- .../atoms/artifacts/SessionArtifactsCard.tsx | 1 + .../SessionArtifactsToggleButton.tsx | 25 +++++++---- .../containers/SessionArtifactsContainer.tsx | 45 +++++++++++-------- .../SessionArtifactsPanelContext.tsx | 12 +++-- .../test/atoms/ThreadShell.test.tsx | 12 +++++ .../artifacts/SessionArtifactsCard.test.tsx | 5 +++ .../SessionArtifactsContainer.test.tsx | 38 ++++++++++++---- 8 files changed, 100 insertions(+), 40 deletions(-) diff --git a/packages/trueforge-ui/src/atoms/ThreadShell.tsx b/packages/trueforge-ui/src/atoms/ThreadShell.tsx index 129c1c4803..ed9eb85e5a 100644 --- a/packages/trueforge-ui/src/atoms/ThreadShell.tsx +++ b/packages/trueforge-ui/src/atoms/ThreadShell.tsx @@ -49,7 +49,7 @@ export const ThreadViewportShell = forwardRef -
+

Artifacts

+ {artifacts.length === 0 ?

No artifacts yet

: null} state.threadListItem.remoteId); - if (!available || panel == null) return null; + if (panel == null) 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 ( { - track(AnalyticsEvents.Artifact.SESSION_CARD_TOGGLED, { open: !open }); - setOpen(!open); - }} + onClick={toggleArtifacts} > Artifacts diff --git a/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx index be7abfe5e3..6a9a870539 100644 --- a/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx +++ b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx @@ -25,38 +25,43 @@ 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; +} + +/** Lists only while the card is open: a closed card neither fetches nor polls, and reopening refetches. */ function useSessionArtifactsQuery() { const artifactServer = useOptionalArtifactServer(); - const sessionId = useAuiState(state => state.threadListItem.remoteId); + const sessionId = useStoredSessionId(); const isRunning = useAuiState(state => state.thread.isRunning); + const panel = useOptionalSessionArtifactsPanel(); + const open = panel?.open ?? true; const queryClient = useServerQueryClient(); const query = useQuery( { queryKey: queryKeys.artifacts.session(sessionId ?? ''), queryFn: - artifactServer == null || sessionId == null || sessionId === '' + artifactServer == null || sessionId == null ? skipToken : () => artifactServer.listSessionArtifacts({ sessionId }), - refetchInterval: isRunning ? SESSION_ARTIFACTS_RUN_POLL_MS : false, + enabled: open, + refetchInterval: open && isRunning ? SESSION_ARTIFACTS_RUN_POLL_MS : false, }, queryClient, ); - return { artifactServer, sessionId: sessionId ?? null, artifacts: query.data }; -} - -/** True when the active session has artifacts, whether or not the card is currently shown. */ -export function useSessionArtifactsAvailable(): boolean { - return (useSessionArtifactsQuery().artifacts?.length ?? 0) > 0; + return { artifactServer, sessionId, artifacts: query.data }; } /** True when the card column is on screen, so the composer leaves room for it. */ export function useSessionArtifactsVisible(): boolean { - const available = useSessionArtifactsAvailable(); + const artifactServer = useOptionalArtifactServer(); + const sessionId = useStoredSessionId(); const panel = useOptionalSessionArtifactsPanel(); - return available && (panel?.open ?? true); + return artifactServer != null && sessionId != null && (panel?.open ?? true); } -/** Card listing the artifacts the active session produced; renders nothing when there are none. */ +/** 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(); @@ -76,7 +81,7 @@ export function SessionArtifactsContainer() { wasRunning.current = isRunning; }, [isRunning, queryClient, sessionId]); - if (artifactServer == null || artifacts == null || artifacts.length === 0) return null; + if (artifactServer == null || sessionId == null) return null; const open = panel?.open !== false; const openArtifact = (artifact: Artifact) => { @@ -98,12 +103,14 @@ export function SessionArtifactsContainer() { )} >
- track(AnalyticsEvents.Artifact.SESSION_CARD_SHOW_MORE)} - /> + {artifacts == null ? null : ( + track(AnalyticsEvents.Artifact.SESSION_CARD_SHOW_MORE)} + /> + )}
); diff --git a/packages/trueforge-ui/src/containers/SessionArtifactsPanelContext.tsx b/packages/trueforge-ui/src/containers/SessionArtifactsPanelContext.tsx index f8abeeb03a..d9cdd643dc 100644 --- a/packages/trueforge-ui/src/containers/SessionArtifactsPanelContext.tsx +++ b/packages/trueforge-ui/src/containers/SessionArtifactsPanelContext.tsx @@ -9,9 +9,15 @@ type SessionArtifactsPanelValue = { const SessionArtifactsPanelContext = createContext(null); -/** Shared by the header toggle and the thread so both agree on whether the artifacts card is shown. */ -export function SessionArtifactsPanelProvider({ children }: { children: ReactNode }) { - const [open, setOpen] = useState(true); +/** 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}; } diff --git a/packages/trueforge-ui/test/atoms/ThreadShell.test.tsx b/packages/trueforge-ui/test/atoms/ThreadShell.test.tsx index f36f20875f..97f5661674 100644 --- a/packages/trueforge-ui/test/atoms/ThreadShell.test.tsx +++ b/packages/trueforge-ui/test/atoms/ThreadShell.test.tsx @@ -58,6 +58,18 @@ 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(); diff --git a/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx index 0c2a899d7f..2047fe586d 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx +++ b/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx @@ -49,6 +49,11 @@ describe('SessionArtifactsCard', () => { expect(onShowMore).toHaveBeenCalledTimes(1); }); + 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(); diff --git a/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx index 3000442788..7be463bc0a 100644 --- a/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx +++ b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx @@ -53,10 +53,12 @@ function renderContainer({ artifacts, track, withToggle = false, + defaultOpen = true, }: { artifacts: ReturnType | undefined; track?: (eventName: string, data?: Record) => void; withToggle?: boolean; + defaultOpen?: boolean; }) { const server = createMockAgentUIServer({ catalog: createMockCatalog(), @@ -67,7 +69,7 @@ function renderContainer({ - + {withToggle ? : null} @@ -153,20 +155,38 @@ describe('SessionArtifactsContainer', () => { expect(track).toHaveBeenCalledWith(AnalyticsEvents.Artifact.SESSION_CARD_TOGGLED, { open: true }); }); - it('shows no toggle when the session has no artifacts', async () => { + 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 }); - await waitFor(() => expect(listSessionArtifacts).toHaveBeenCalled()); - expect(screen.queryByRole('button', { name: 'Artifacts' })).not.toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Artifacts' })).toBeInTheDocument(); + expect(await screen.findByText('No artifacts yet')).toBeInTheDocument(); }); - it('renders nothing when the session has no artifacts', async () => { - const listSessionArtifacts = vi.fn(async () => []); - renderContainer({ artifacts: createMockArtifactServer({ listSessionArtifacts }) }); + 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 waitFor(() => expect(listSessionArtifacts).toHaveBeenCalled()); - expect(screen.queryByLabelText('Session artifacts')).not.toBeInTheDocument(); + 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('renders nothing without an artifact server or a stored session', async () => { From 0c1f9622b7c4ae2d4e8eaedb094246927dfe8510 Mon Sep 17 00:00:00 2001 From: harshil-2096 Date: Tue, 1 Dec 2026 09:24:05 +0000 Subject: [PATCH 13/20] chore:remove multiple changelog files --- .changeset/artifact-image-icon-tree.md | 6 ------ .changeset/session-artifacts-card.md | 7 ------- .changeset/session-artifacts-listing-ui.md | 7 +++++++ .changeset/session-artifacts-toggle.md | 6 ------ 4 files changed, 7 insertions(+), 19 deletions(-) delete mode 100644 .changeset/artifact-image-icon-tree.md delete mode 100644 .changeset/session-artifacts-card.md create mode 100644 .changeset/session-artifacts-listing-ui.md delete mode 100644 .changeset/session-artifacts-toggle.md diff --git a/.changeset/artifact-image-icon-tree.md b/.changeset/artifact-image-icon-tree.md deleted file mode 100644 index fa5b21dafa..0000000000 --- a/.changeset/artifact-image-icon-tree.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -'@truefoundry/trueforge-ui': patch -'@truefoundry/trueforge': patch ---- - -Use the Lucide `image` icon for image artifacts in the session tree and file preview header. diff --git a/.changeset/session-artifacts-card.md b/.changeset/session-artifacts-card.md deleted file mode 100644 index 7e2fce64dc..0000000000 --- a/.changeset/session-artifacts-card.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -'@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`. 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/.changeset/session-artifacts-toggle.md b/.changeset/session-artifacts-toggle.md deleted file mode 100644 index 88c5c78d89..0000000000 --- a/.changeset/session-artifacts-toggle.md +++ /dev/null @@ -1,6 +0,0 @@ ---- -'@truefoundry/trueforge-ui': patch -'@truefoundry/trueforge': patch ---- - -Add an Artifacts button before Share in the chat header, shown once the session has artifacts, to hide or show the session artifacts card. From 51aaf71698bc4c74309df88d22eeb4f9660b6a0d Mon Sep 17 00:00:00 2001 From: harshil-2096 Date: Tue, 1 Dec 2026 09:59:47 +0000 Subject: [PATCH 14/20] refactor: standardize event handler definitions across components for improved readability and maintainability --- packages/trueforge-ui/AGENTS.md | 1 + .../src/atoms/FilePreviewPanel.tsx | 58 ++++++++++++------- .../src/atoms/artifacts/ArtifactsPage.tsx | 15 +++-- .../atoms/artifacts/SessionArtifactsCard.tsx | 53 +++++++++-------- .../src/layouts/SidebarLayout.tsx | 16 ++--- .../src/layouts/StackChatPanel.tsx | 11 ++-- 6 files changed, 89 insertions(+), 65 deletions(-) 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/atoms/FilePreviewPanel.tsx b/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx index c002732633..a37675e2d4 100644 --- a/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx +++ b/packages/trueforge-ui/src/atoms/FilePreviewPanel.tsx @@ -1,6 +1,13 @@ 'use client'; -import { useEffect, useLayoutEffect, useRef, useState, type PointerEvent as ReactPointerEvent } from 'react'; +import { + useEffect, + useLayoutEffect, + useRef, + useState, + type KeyboardEvent as ReactKeyboardEvent, + type PointerEvent as ReactPointerEvent, +} from 'react'; import { clampPreviewWidth } from '../filePreview/previewPaneWidth.js'; import { FILE_PREVIEW_HIGHLIGHT_CHAR_LIMIT, type ReadFilePreviewResult } from '../filePreview/readFilePreview.js'; @@ -172,6 +179,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/artifacts/ArtifactsTable.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx index f92758115b..6aaf7e5cd0 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx @@ -9,7 +9,7 @@ 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[]; @@ -42,7 +42,10 @@ export function ArtifactsTable({ artifacts, selectedKey, onOpen, onDownload, onE onClick={() => onOpen(artifact)} > - {artifact.name} + + + {artifact.name} + @@ -65,12 +68,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.isDir ? null : ( + onDownload(artifact)} + /> + )} diff --git a/packages/trueforge-ui/src/atoms/artifacts/SessionArtifactsCard.tsx b/packages/trueforge-ui/src/atoms/artifacts/SessionArtifactsCard.tsx index 21c0c9d205..da9c64faf2 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/SessionArtifactsCard.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/SessionArtifactsCard.tsx @@ -1,10 +1,11 @@ 'use client'; -import { useState } from 'react'; +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. */ @@ -15,17 +16,39 @@ export type SessionArtifactsCardProps = { 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. */ + 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); @@ -34,22 +57,39 @@ export function SessionArtifactsCard({ setExpanded(current => !current); }; + const toggleFolder = (artifact: Artifact) => { + onToggleFolder?.(artifact); + setOpenFolders(current => { + const next = new Set(current); + if (!next.delete(artifact.id)) next.add(artifact.id); + return next; + }); + }; + const renderArtifactRow = (artifact: Artifact) => { const type = artifactType(artifact); + const asTree = artifact.isDir && renderFolderFiles != null; + const folderOpen = asTree && openFolders.has(artifact.id); return ( - + <> + + {folderOpen ?
{renderFolderFiles(artifact)}
: null} + ); }; @@ -62,7 +102,10 @@ export function SessionArtifactsCard({ )} >

Artifacts

- {artifacts.length === 0 ?

No artifacts yet

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

No artifacts yet

+ ) : null}
    {visible.map(artifact => (
  • {renderArtifactRow(artifact)}
  • diff --git a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts index ca12f13443..9ff1494ff8 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts +++ b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts @@ -1,4 +1,5 @@ import type { SandboxFilePreviewTarget } from '../../filePreview/FilePreviewContext.js'; +import { folderFileTarget } from '../../filePreview/folderFileTarget.js'; import { fileExtension, inlinePreviewKind } from '../../filePreview/readFilePreview.js'; import type { Artifact, ArtifactServer } from '../../server/types.js'; @@ -11,17 +12,33 @@ export function artifactPreviewKey({ id, updatedAt }: Pick artifactServer.readArtifactFile({ id: artifact.id }), + // A folder opens on its file list, since one entry file would hide the rest of its contents. + ...(artifact.isDir + ? { + folder: { + cacheKey: artifactPreviewKey(artifact), + 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; } const VIDEO_EXT = new Set(['mp4', 'mov', 'webm', 'mkv', 'avi', 'm4v']); @@ -31,8 +48,11 @@ export type ArtifactType = { label: string; icon: string }; const FILE_TYPE: ArtifactType = { label: 'File', icon: 'file' }; -/** Short type label and icon for an artifact row, derived from the file name extension. */ -export function artifactType({ name }: Pick): ArtifactType { +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 }: Pick): 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' }; diff --git a/packages/trueforge-ui/src/containers/FilePreviewFolderBrowserContainer.tsx b/packages/trueforge-ui/src/containers/FilePreviewFolderBrowserContainer.tsx new file mode 100644 index 0000000000..ddde27b9a4 --- /dev/null +++ b/packages/trueforge-ui/src/containers/FilePreviewFolderBrowserContainer.tsx @@ -0,0 +1,20 @@ +'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 }); + return ; +} diff --git a/packages/trueforge-ui/src/containers/FilePreviewHost.tsx b/packages/trueforge-ui/src/containers/FilePreviewHost.tsx index a43ecabf9a..64a6d6f61c 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 picked from its folder (none until one 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,13 @@ 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, so opening another preview starts on that folder's file list. + const selectedPath = selection != null && selection.targetKey === targetKey ? selection.path : 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 +80,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 +102,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 index e9c188aee1..401ad69d93 100644 --- a/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx +++ b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx @@ -15,6 +15,7 @@ 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. */ @@ -60,7 +61,7 @@ function useSessionArtifactsQuery() { }, queryClient, ); - return { artifactServer, sessionId, artifacts: query.data }; + return { artifactServer, sessionId, artifacts: query.data, loading: query.isPending }; } /** True when the card column is on screen, so the composer leaves room for it. */ @@ -80,7 +81,7 @@ export function SessionArtifactsContainer() { const { open: openFilePreview } = preview; const isRunning = useAuiState(state => state.thread.isRunning); const supported = useSessionArtifactsSupported(); - const { artifactServer, sessionId, artifacts } = useSessionArtifactsQuery(); + 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); @@ -94,9 +95,23 @@ export function SessionArtifactsContainer() { if (!supported || artifactServer == null || sessionId == null) return null; const open = panel?.open !== false; - const openArtifact = (artifact: Artifact) => { + const openArtifact = (artifact: Artifact, filePath?: string) => { track(AnalyticsEvents.Artifact.SESSION_CARD_PREVIEW_OPENED, { artifact_id: artifact.id }); - openFilePreview(artifactPreviewTarget({ artifact, artifactServer })); + openFilePreview( + artifactPreviewTarget({ artifact, artifactServer, ...(filePath === undefined ? {} : { filePath }) }), + ); + }; + + const renderFolderFiles = (artifact: Artifact) => { + const { folder } = artifactPreviewTarget({ artifact, artifactServer }); + if (folder == null) return null; + return ( + openArtifact(artifact, path)} + /> + ); }; // Rendered inside the thread scroll root, beside the messages: the messages shift left and the @@ -113,14 +128,17 @@ export function SessionArtifactsContainer() { )} >
    - {artifacts == null ? null : ( - track(AnalyticsEvents.Artifact.SESSION_CARD_SHOW_MORE)} - /> - )} + openArtifact(artifact)} + onShowMore={() => track(AnalyticsEvents.Artifact.SESSION_CARD_SHOW_MORE)} + renderFolderFiles={renderFolderFiles} + onToggleFolder={artifact => + track(AnalyticsEvents.Artifact.SESSION_CARD_FOLDER_TOGGLED, { artifact_id: artifact.id }) + } + />
); diff --git a/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsx b/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsx index 61d456e4f0..3f79c0f41a 100644 --- a/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsx +++ b/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsx @@ -3,13 +3,24 @@ 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; +}; + 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..ac7befeccd --- /dev/null +++ b/packages/trueforge-ui/src/filePreview/folderFileTarget.ts @@ -0,0 +1,20 @@ +import { filenameFromPath } from '../utils/triggerBrowserDownload.js'; +import type { FilePreviewFolder, SandboxFilePreviewTarget } from './FilePreviewContext.js'; + +/** 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: `${target.turnId}:${path}`, + load: () => folder.loadFile(path), + }; +} 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..1e370451a2 --- /dev/null +++ b/packages/trueforge-ui/src/filePreview/useFolderTree.ts @@ -0,0 +1,80 @@ +'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'; + +export type FolderLevel = { status: 'loading' } | { status: 'error' } | { 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; +}; + +/** + * 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. + * State belongs to one folder, so the caller remounts it (by `key`) when a different folder opens. + */ +export function useFolderTree({ + cacheKey, + list, +}: { + cacheKey: string; + list: (path: string) => Promise; +}): FolderTree { + const queryClient = useServerQueryClient(); + const [levels, setLevels] = useState>>({}); + const [expanded, setExpanded] = useState>(new Set()); + const listRef = useRef(list); + listRef.current = list; + + 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(() => { + // A failed revalidation keeps the files already on screen. + setLevels(current => + current[path]?.status === 'ready' ? current : { ...current, [path]: { status: 'error' } }, + ); + }); + }, + [cacheKey, queryClient], + ); + + useEffect(() => { + 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/icons/IconRegistry.tsx b/packages/trueforge-ui/src/icons/IconRegistry.tsx index 471926e9c4..ada91be790 100644 --- a/packages/trueforge-ui/src/icons/IconRegistry.tsx +++ b/packages/trueforge-ui/src/icons/IconRegistry.tsx @@ -46,6 +46,7 @@ import { FileSpreadsheet, FileText, FileVideo, + Folder, GalleryHorizontalEnd, GripVertical, History, @@ -208,6 +209,7 @@ const defaults: Record = { image: Image, 'file-video': FileVideo, 'file-audio': FileAudio, + 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 6e5bd17007..ea77249e26 100644 --- a/packages/trueforge-ui/src/index.ts +++ b/packages/trueforge-ui/src/index.ts @@ -106,6 +106,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'; @@ -154,6 +156,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'; @@ -384,6 +387,8 @@ export type { AgentUIServer, ApprovalDecision, Artifact, + ArtifactDetail, + ArtifactFile, ArtifactServer, AuthenticateConnectorRequest, AutoModel, diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts index 6adcb5834f..adfb917a71 100644 --- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts +++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts @@ -1,9 +1,15 @@ /** - * Harness ArtifactServer adapter. List, session list and rename exist on the API; the other methods reject - * until their routes land. + * Harness ArtifactServer adapter. Get, list, list files, session list and rename exist on the API; the other methods + * reject until their routes land. */ import type { TrueForge, TrueForgeApi } from '@truefoundry/trueforge-sdk'; -import type { Artifact, ArtifactServer, ListArtifactsParams } from '../../server/types.js'; +import type { + Artifact, + ArtifactDetail, + ArtifactFile, + ArtifactServer, + ListArtifactsParams, +} from '../../server/types.js'; import { toListResult } from './chatServer.js'; function unavailable(action: string): Promise { @@ -17,10 +23,43 @@ function toUiArtifact(artifact: TrueForgeApi.Artifact): Artifact { createdBySubject: artifact.createdBySubject, createdAt: artifact.createdAt.toISOString(), updatedAt: artifact.updatedAt.toISOString(), + isDir: artifact.isDir, }; } +function toUiArtifactDetail(artifact: TrueForgeApi.ArtifactDetail): ArtifactDetail { + return { ...toUiArtifact(artifact), entryPoint: artifact.entryPoint }; +} + +function toUiArtifactFile(file: TrueForgeApi.ArtifactFile): ArtifactFile { + return { path: file.path, isDir: file.isDir, size: file.fileSize }; +} + +/** Folder part of a file path, with its trailing slash; empty for a top-level file. */ +function parentFolder(filePath: string): string { + return filePath.slice(0, filePath.lastIndexOf('/') + 1); +} + export function createArtifactServer(client: TrueForge): ArtifactServer { + const listFiles = (id: string, path: string | undefined) => + client.artifacts.listFiles(id, path === undefined || path === '' ? {} : { path }); + + // A single-file artifact has exactly one file, at the top level, so one listing reads it without the details call. + const singleFileEntry = async (id: string): Promise => { + const files = (await listFiles(id, '')).data.filter(entry => !entry.isDir); + const [only] = files; + if (only === undefined) throw new Error('Artifact has no files yet'); + if (files.length > 1) throw new Error('Artifact has more than one file; read one by path'); + return only; + }; + + const listedFile = async (id: string, filePath: string): Promise => { + const listing = await listFiles(id, parentFolder(filePath)); + const file = listing.data.find(entry => entry.path === filePath && !entry.isDir); + if (file === undefined) throw new Error(`Artifact file not found: ${filePath}`); + return file; + }; + return { async listArtifacts(request: ListArtifactsParams = {}) { const page = await client.artifacts.list({ @@ -34,12 +73,27 @@ export function createArtifactServer(client: TrueForge): ArtifactServer { const response = await client.sessions.listArtifacts(sessionId); return response.data.map(toUiArtifact); }, - getArtifact: () => unavailable('Get artifact'), + async getArtifact({ id }) { + const response = await client.artifacts.get(id); + return toUiArtifactDetail(response.data); + }, + async listArtifactFiles({ id, path }) { + const response = await listFiles(id, path); + return response.data.map(toUiArtifactFile); + }, async updateArtifact({ id, name }) { const response = await client.artifacts.update(id, { name }); return toUiArtifact(response.data); }, deleteArtifact: () => unavailable('Delete artifact'), - readArtifactFile: () => unavailable('Read artifact file'), + async readArtifactFile({ id, path, version }) { + if (version !== undefined) return unavailable('Reading an artifact version'); + // The API only hands out a download url per listed file, so the file is found in a folder listing. + const entry = path === undefined ? await singleFileEntry(id) : await listedFile(id, path); + if (entry.s3Url == null) throw new Error(`Artifact file not found: ${entry.path}`); + const download = await fetch(entry.s3Url); + if (!download.ok) throw new Error(`Couldn't download artifact file (${String(download.status)})`); + return download.blob(); + }, }; } diff --git a/packages/trueforge-ui/src/server/queryKeys.ts b/packages/trueforge-ui/src/server/queryKeys.ts index 87426a97b5..0e0847f05f 100644 --- a/packages/trueforge-ui/src/server/queryKeys.ts +++ b/packages/trueforge-ui/src/server/queryKeys.ts @@ -110,6 +110,9 @@ export const queryKeys = { list: (params: ListArtifactsParams) => key('artifacts', 'list', params), /** Nested under `all()` so artifact rename/delete invalidation reaches the session card. */ session: (sessionId: string) => key('artifacts', 'session', sessionId), + /** `artifactKey` carries the artifact version, so a new version lists afresh. */ + files: ({ artifactKey, path }: { artifactKey: string; path: string }) => + key('artifacts', 'files', artifactKey, path), }, metrics: { all: () => key('metrics'), diff --git a/packages/trueforge-ui/src/server/types.ts b/packages/trueforge-ui/src/server/types.ts index 3580d09dc5..71b258ce17 100644 --- a/packages/trueforge-ui/src/server/types.ts +++ b/packages/trueforge-ui/src/server/types.ts @@ -33,6 +33,8 @@ export type { AgentUIServer, ApprovalDecision, Artifact, + ArtifactDetail, + ArtifactFile, ArtifactServer, AuthenticateConnectorRequest, AutoModel, diff --git a/packages/trueforge-ui/src/theme/defaultSlots.ts b/packages/trueforge-ui/src/theme/defaultSlots.ts index 7f4c7ca9f4..d418f54b5f 100644 --- a/packages/trueforge-ui/src/theme/defaultSlots.ts +++ b/packages/trueforge-ui/src/theme/defaultSlots.ts @@ -81,6 +81,7 @@ import { InstructionsFullScreenEditor } from '../atoms/draft/InstructionsFullScr import { InstructionsMarkdownEditor } from '../atoms/draft/InstructionsMarkdownEditor.js'; import type { EnvironmentsPageProps } from '../atoms/environments/EnvironmentsPage.js'; import { EnvironmentsButton } from '../atoms/EnvironmentsButton.js'; +import { FilePreviewFolderBrowser } from '../atoms/FilePreviewFolderBrowser.js'; import { FilePreviewPanel } from '../atoms/FilePreviewPanel.js'; import { HistoryLoader } from '../atoms/HistoryLoader.js'; import { Markdown } from '../atoms/Markdown.js'; @@ -238,6 +239,7 @@ export const defaultSlots = { SandboxArtifactDownload, ChatFileDownload, FilePreviewPanel, + FilePreviewFolderBrowser, MonacoEditorCore, CodeEditor, WelcomeScreen, diff --git a/packages/trueforge-ui/src/utils/formatFileSize.ts b/packages/trueforge-ui/src/utils/formatFileSize.ts new file mode 100644 index 0000000000..ac0df323d6 --- /dev/null +++ b/packages/trueforge-ui/src/utils/formatFileSize.ts @@ -0,0 +1,6 @@ +export 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`; +} diff --git a/packages/trueforge-ui/test/atoms/FilePreviewFolderBrowser.test.tsx b/packages/trueforge-ui/test/atoms/FilePreviewFolderBrowser.test.tsx new file mode 100644 index 0000000000..0a3bc04e12 --- /dev/null +++ b/packages/trueforge-ui/test/atoms/FilePreviewFolderBrowser.test.tsx @@ -0,0 +1,117 @@ +// @vitest-environment jsdom +import { fireEvent, render, screen, within } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; + +import { FilePreviewFolderBrowser } from '@/atoms/FilePreviewFolderBrowser.js'; +import type { FolderTree } from '@/filePreview/useFolderTree.js'; +import type { ArtifactFile } from '@/server/types.js'; + +const dataDir: ArtifactFile = { path: 'data/', isDir: true, size: null }; +const indexFile: ArtifactFile = { path: 'index.html', isDir: false, size: 1536 }; +const csvFile: ArtifactFile = { path: 'data/a.csv', isDir: false, size: 3 }; + +function tree(overrides: Partial = {}): FolderTree { + return { + levels: { '': { status: 'ready', entries: [dataDir, indexFile] } }, + expanded: new Set(), + toggle: vi.fn(), + ...overrides, + }; +} + +describe('FilePreviewFolderBrowser', () => { + it('lists the top level with folder names stripped of the trailing slash', () => { + render(); + + expect(screen.getByRole('button', { name: /^data$/ })).toHaveAttribute('aria-expanded', 'false'); + expect(screen.getByRole('button', { name: /index\.html/ })).toBeInTheDocument(); + expect(screen.getByText('1.50 KB')).toBeInTheDocument(); + }); + + it('selects a file and marks the selected one', () => { + const onSelect = vi.fn(); + const { rerender } = render(); + + fireEvent.click(screen.getByRole('button', { name: /index\.html/ })); + expect(onSelect).toHaveBeenCalledWith('index.html'); + expect(screen.getByRole('button', { name: /index\.html/ })).not.toHaveAttribute('aria-current'); + + rerender(); + expect(screen.getByRole('button', { name: /index\.html/ })).toHaveAttribute('aria-current', 'true'); + }); + + it('toggles a folder instead of selecting it and shows its children when expanded', () => { + const toggle = vi.fn(); + const onSelect = vi.fn(); + const { rerender } = render( + , + ); + + fireEvent.click(screen.getByRole('button', { name: /^data$/ })); + expect(toggle).toHaveBeenCalledWith('data/'); + expect(onSelect).not.toHaveBeenCalled(); + expect(screen.queryByRole('button', { name: /a\.csv/ })).not.toBeInTheDocument(); + + rerender( + , + ); + expect(screen.getByRole('button', { name: /^data$/ })).toHaveAttribute('aria-expanded', 'true'); + fireEvent.click(screen.getByRole('button', { name: /a\.csv/ })); + expect(onSelect).toHaveBeenCalledWith('data/a.csv'); + }); + + it('shows loading, empty and error states per level', () => { + const { rerender } = render( + , + ); + const loading = screen.getByRole('status', { name: 'Loading files' }); + expect(loading.querySelector('.animate-pulse')).not.toBeNull(); + + rerender( + , + ); + expect(screen.getByText('This folder is empty.')).toBeInTheDocument(); + + rerender( + , + ); + expect(screen.getByText("Couldn't load these files.")).toBeInTheDocument(); + + rerender( + , + ); + const folderRow = screen.getByRole('button', { name: /^data$/ }).closest('li'); + if (folderRow == null) throw new Error('Expected the folder row to render in a list item'); + expect(within(folderRow).getByText("Couldn't load these files.")).toBeInTheDocument(); + }); +}); diff --git a/packages/trueforge-ui/test/atoms/FilePreviewPanel.test.tsx b/packages/trueforge-ui/test/atoms/FilePreviewPanel.test.tsx index d5c2b5f5a9..10d104b1a3 100644 --- a/packages/trueforge-ui/test/atoms/FilePreviewPanel.test.tsx +++ b/packages/trueforge-ui/test/atoms/FilePreviewPanel.test.tsx @@ -155,6 +155,76 @@ describe('FilePreviewPanel', () => { fireEvent.click(screen.getByRole('button', { name: 'Exit full page' })); expect(onExitFullPage).toHaveBeenCalledTimes(2); }); + + it('shows the folder files beside a hint, with no download or reload until a file is open', () => { + render( + file tree
, 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/artifacts/ArtifactsPage.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx index 6b1077f865..56a85ce283 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,7 +8,7 @@ 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' }; @@ -18,6 +18,7 @@ function artifact(overrides: Partial & Pick): createdBySubject: subject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', + isDir: false, ...overrides, }; } @@ -111,7 +112,7 @@ describe('ArtifactsPage', () => { it('puts the artifact in the URL on open, and deep-links by id', async () => { const readArtifactFile = vi.fn(async () => new Blob(['# Hello'], { type: 'text/markdown' })); - const getArtifact = vi.fn(async () => q4Brief); + const getArtifact = vi.fn(async () => ({ ...q4Brief, entryPoint: 'index.md' })); const artifacts = createMockArtifactServer({ listArtifacts: async () => ({ data: sample }), getArtifact, @@ -171,6 +172,87 @@ describe('ArtifactsPage', () => { }); }); +describe('ArtifactsPage folder artifacts', () => { + const site = artifact({ id: 'f1', name: 'Dummy site', isDir: true }); + const listing: Record = { + '': [ + { path: 'assets/', isDir: true, size: null }, + { path: 'index.html', isDir: false, size: 10 }, + ], + 'assets/': [{ path: 'assets/app.js', isDir: false, size: 5 }], + }; + + 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 folder files 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 Dummy site' }); + expect(await within(panel).findByRole('button', { name: /index\.html/ })).toBeInTheDocument(); + expect(listArtifactFiles).toHaveBeenCalledWith({ id: 'f1', path: '' }); + expect(readArtifactFile).not.toHaveBeenCalled(); + expect(within(panel).queryByRole('button', { name: /^Download/ })).not.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(readArtifactFile).toHaveBeenCalledTimes(2); + expect(await screen.findByRole('complementary', { name: 'Preview of index.html' })).toBeInTheDocument(); + }); + + it('marks each row with a folder or file icon from isDir', 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 index 8d693aa0c7..f18daf3012 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx +++ b/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx @@ -15,6 +15,7 @@ function artifact(id: string, name: string): Artifact { createdBySubject: subject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', + isDir: false, }; } @@ -22,7 +23,7 @@ const names = ['a.png', 'b.html', 'c.mp4', 'd.mp3', 'e.pdf', 'f.txt', 'g.png', ' const artifacts = names.map((name, index) => artifact(`id-${String(index)}`, name)); describe('SessionArtifactsCard', () => { - it('shows six rows with type labels and a "Show N more" toggle', () => { + it('shows six rows without type labels and a "Show N more" toggle', () => { const onShowMore = vi.fn(); render( , @@ -32,12 +33,9 @@ describe('SessionArtifactsCard', () => { expect(screen.getByText('a.png')).toBeInTheDocument(); expect(screen.getByText('f.txt')).toBeInTheDocument(); expect(screen.queryByText('g.png')).not.toBeInTheDocument(); - expect(screen.getAllByText('Image')).toHaveLength(1); - expect(screen.getByText('Html')).toBeInTheDocument(); - expect(screen.getByText('Video')).toBeInTheDocument(); - expect(screen.getByText('Audio')).toBeInTheDocument(); - expect(screen.getByText('Pdf')).toBeInTheDocument(); - expect(screen.getByText('File')).toBeInTheDocument(); + for (const label of ['Image', 'Html', 'Video', 'Audio', 'Pdf', 'File']) { + expect(screen.queryByText(label)).not.toBeInTheDocument(); + } fireEvent.click(screen.getByRole('button', { name: 'Show 2 more' })); expect(onShowMore).toHaveBeenCalledTimes(1); @@ -49,6 +47,65 @@ describe('SessionArtifactsCard', () => { 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'), isDir: true }; + 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'), isDir: true }; + 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); + expect(onOpen).not.toHaveBeenCalled(); + + fireEvent.click(row); + 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'), isDir: true }; + 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(); 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..d01be684da --- /dev/null +++ b/packages/trueforge-ui/test/atoms/artifacts/artifactDisplay.test.ts @@ -0,0 +1,89 @@ +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(overrides: Partial = {}): 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', + isDir: false, + ...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' }); + }); +}); + +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 }), + }); + + 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 }]); + const readArtifactFile = vi.fn(async () => new Blob(['x'])); + const target = artifactPreviewTarget({ + artifact: artifact({ isDir: true }), + artifactServer: createMockArtifactServer({ listArtifactFiles, readArtifactFile }), + }); + + expect(target.folder).toBeDefined(); + await expect(target.folder?.list('')).resolves.toEqual([{ path: 'index.html', isDir: false, size: 10 }]); + expect(listArtifactFiles).toHaveBeenCalledWith({ id: 'a1', path: '' }); + + await target.folder?.loadFile('data/a.csv'); + expect(readArtifactFile).toHaveBeenCalledWith({ id: 'a1', path: 'data/a.csv' }); + }); +}); + +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/containers/SessionArtifactsContainer.test.tsx b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx index dcdab74338..5c285e7270 100644 --- a/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx +++ b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx @@ -34,6 +34,7 @@ function artifact(id: string, name: string): Artifact { createdBySubject: subject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', + isDir: false, }; } @@ -116,6 +117,56 @@ describe('SessionArtifactsContainer', () => { 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 and opens a picked file on its own', async () => { + const folder: Artifact = { ...artifact('f1', 'Dummy site'), isDir: true }; + const listSessionArtifacts = vi.fn(async () => [folder]); + const listArtifactFiles = vi.fn(async ({ path = '' }: { id: string; path?: string }) => + path === '' + ? [ + { path: 'assets/', isDir: true, size: null }, + { path: 'index.html', isDir: false, size: 10 }, + ] + : [{ path: 'assets/app.js', isDir: false, size: 5 }], + ); + 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('none'); + 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('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' })); 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..53402d0c8e --- /dev/null +++ b/packages/trueforge-ui/test/filePreview/useFolderTree.test.tsx @@ -0,0 +1,84 @@ +// @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 }; +const indexFile: ArtifactFile = { path: 'index.html', isDir: false, size: 10 }; +const csvFile: ArtifactFile = { path: 'data/a.csv', isDir: false, size: 3 }; + +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' })); + + 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('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 dde02a53bc..488f5b174a 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,20 +15,36 @@ const sdkArtifact = { createdBySubject, createdAt: new Date('2024-01-01T00:00:00.000Z'), updatedAt: new Date('2024-01-02T00:00:00.000Z'), + isDir: false, }; 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 }, sessions: { listArtifacts: listSessionArtifacts } } as unknown as TrueForge; + return { + artifacts: { list, get, listFiles, update }, + sessions: { listArtifacts: listSessionArtifacts }, + } as unknown as TrueForge; } +const htmlFile = { path: 'index.html', isDir: false, s3Url: 'https://s3.test/index.html', fileSize: 10 }; +const dataDir = { path: 'data/', isDir: true, s3Url: null, fileSize: null }; +const csvFile = { path: 'data/a.csv', isDir: false, s3Url: 'https://s3.test/a.csv', fileSize: 3 }; + +afterEach(() => { + vi.unstubAllGlobals(); +}); + describe('createArtifactServer', () => { it('lists artifacts with paging tokens and forwards the name search', async () => { const list = vi.fn(async () => ({ @@ -48,10 +64,37 @@ describe('createArtifactServer', () => { createdBySubject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', + isDir: false, }, ]); }); + it('maps the folder flag from the list response', async () => { + const list = vi.fn(async () => ({ + data: [{ ...sdkArtifact, isDir: true }], + response: { pagination: { limit: 25 } }, + })); + const page = await createArtifactServer(mockClient({ list })).listArtifacts(); + + expect(page.data[0]?.isDir).toBe(true); + }); + + it('gets one artifact with its entry point and folder flag', async () => { + const get = vi.fn(async () => ({ data: { ...sdkArtifact, isDir: true, entryPoint: 'index.html' } })); + const detail = await createArtifactServer(mockClient({ get })).getArtifact({ id: 'a1' }); + + expect(get).toHaveBeenCalledWith('a1'); + expect(detail).toEqual({ + id: 'a1', + name: 'Q4 brief', + createdBySubject, + createdAt: '2024-01-01T00:00:00.000Z', + updatedAt: '2024-01-02T00:00:00.000Z', + isDir: true, + 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: '' }); @@ -72,6 +115,7 @@ describe('createArtifactServer', () => { createdBySubject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', + isDir: false, }, ]); }); @@ -85,10 +129,107 @@ describe('createArtifactServer', () => { expect(renamed.updatedAt).toBe('2024-01-02T00:00:00.000Z'); }); + it('lists one folder level 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 }, + { path: 'index.html', isDir: false, size: 10 }, + ]); + 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 fetchFile = vi.fn(async () => new Response('

hi

')); + vi.stubGlobal('fetch', fetchFile); + + const blob = await createArtifactServer(mockClient({ listFiles })).readArtifactFile({ + id: 'a1', + path: 'index.html', + }); + + expect(listFiles).toHaveBeenCalledWith('a1', {}); + expect(fetchFile).toHaveBeenCalledWith('https://s3.test/index.html'); + await expect(blob.text()).resolves.toBe('

hi

'); + }); + + it('reads a nested file by listing its parent folder', async () => { + const listFiles = vi.fn(async () => ({ data: [csvFile] })); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('1,2,3')), + ); + + const blob = await createArtifactServer(mockClient({ listFiles })).readArtifactFile({ + id: 'a1', + path: 'data/a.csv', + }); + + expect(listFiles).toHaveBeenCalledWith('a1', { path: 'data/' }); + await expect(blob.text()).resolves.toBe('1,2,3'); + }); + + it('reads the only top-level file of a single-file artifact without fetching its details', async () => { + const get = vi.fn(async () => ({ data: { ...sdkArtifact, entryPoint: 'index.html' } })); + const listFiles = vi.fn(async () => ({ data: [htmlFile] })); + vi.stubGlobal( + 'fetch', + vi.fn(async () => new Response('page')), + ); + + const blob = await createArtifactServer(mockClient({ get, listFiles })).readArtifactFile({ id: 'a1' }); + + expect(get).not.toHaveBeenCalled(); + expect(listFiles).toHaveBeenCalledOnce(); + expect(listFiles).toHaveBeenCalledWith('a1', {}); + expect(fetch).toHaveBeenCalledWith('https://s3.test/index.html'); + await expect(blob.text()).resolves.toBe('page'); + }); + + 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'); + }); + 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'); + await expect(server.readArtifactFile({ id: 'a1', path: 'index.html', version: 2 })).rejects.toThrow( + 'not available yet', + ); }); }); diff --git a/packages/trueforge-ui/test/publicUiExports.test.ts b/packages/trueforge-ui/test/publicUiExports.test.ts index 0353ce3bf5..6f94245a00 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 95f321ce88..8a2e417769 100644 --- a/packages/trueforge-ui/test/server/mockServer.ts +++ b/packages/trueforge-ui/test/server/mockServer.ts @@ -87,6 +87,7 @@ export function createMockArtifactServer(overrides: Partial = {} listArtifacts: async () => ({ data: [] }), listSessionArtifacts: async () => [], getArtifact: unavailable, + listArtifactFiles: async () => [], updateArtifact: unavailable, deleteArtifact: unavailable, readArtifactFile: unavailable, From f29df1824662bb80ed74a6b534ea362222f0d545 Mon Sep 17 00:00:00 2001 From: harshil-2096 Date: Wed, 2 Dec 2026 12:27:45 +0000 Subject: [PATCH 17/20] chore: Artifact structure to include filesMetadata --- .changeset/artifact-is-dir-and-get.md | 2 +- packages/assistant-ui-runtime/src/index.ts | 1 - .../assistant-ui-runtime/src/server/index.ts | 1 - .../assistant-ui-runtime/src/server/types.ts | 18 +++++++------ .../src/atoms/artifacts/ArtifactsTable.tsx | 8 ++++-- .../atoms/artifacts/SessionArtifactsCard.tsx | 5 ++-- .../src/atoms/artifacts/artifactDisplay.ts | 17 +++++------- .../trueforge-ui/src/icons/IconRegistry.tsx | 4 --- packages/trueforge-ui/src/index.ts | 1 - .../artifactServer.ts | 20 +++++--------- packages/trueforge-ui/src/server/types.ts | 1 - .../atoms/artifacts/ArtifactsPage.test.tsx | 11 +++++--- .../artifacts/SessionArtifactsCard.test.tsx | 14 +++++----- .../atoms/artifacts/artifactDisplay.test.ts | 11 ++++++-- .../SessionArtifactsContainer.test.tsx | 6 +++-- .../artifactServer.test.ts | 27 ++++++++++--------- 16 files changed, 76 insertions(+), 71 deletions(-) diff --git a/.changeset/artifact-is-dir-and-get.md b/.changeset/artifact-is-dir-and-get.md index b1badf9593..b51b8b0926 100644 --- a/.changeset/artifact-is-dir-and-get.md +++ b/.changeset/artifact-is-dir-and-get.md @@ -4,4 +4,4 @@ '@truefoundry/trueforge': patch --- -`Artifact` gains `isDir`, `ArtifactServer.getArtifact` resolves an `ArtifactDetail` with the entry point, and `ArtifactServer` gains `listArtifactFiles`. The harness adapter wires get, list files and `readArtifactFile` (by path, defaulting to the entry file). 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. +`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/packages/assistant-ui-runtime/src/index.ts b/packages/assistant-ui-runtime/src/index.ts index ed4464cf91..9880bba0c9 100644 --- a/packages/assistant-ui-runtime/src/index.ts +++ b/packages/assistant-ui-runtime/src/index.ts @@ -119,7 +119,6 @@ export type { AgentUIServerPort, ApprovalDecision, Artifact, - ArtifactDetail, ArtifactFile, ArtifactServer, AuthenticateConnectorRequest, diff --git a/packages/assistant-ui-runtime/src/server/index.ts b/packages/assistant-ui-runtime/src/server/index.ts index ed7991d582..3de8c1dd9e 100644 --- a/packages/assistant-ui-runtime/src/server/index.ts +++ b/packages/assistant-ui-runtime/src/server/index.ts @@ -28,7 +28,6 @@ export type { AgentUIServerPort, ApprovalDecision, Artifact, - ArtifactDetail, ArtifactFile, ArtifactServer, AuthenticateConnectorRequest, diff --git a/packages/assistant-ui-runtime/src/server/types.ts b/packages/assistant-ui-runtime/src/server/types.ts index 18ff1812b1..d2476d87ca 100644 --- a/packages/assistant-ui-runtime/src/server/types.ts +++ b/packages/assistant-ui-runtime/src/server/types.ts @@ -1414,13 +1414,15 @@ export interface Artifact { createdBySubject: Subject; createdAt: string; updatedAt: string; - /** True when the latest version has more than one file or a nested folder; a single top-level file is false. */ - isDir: boolean; -} - -export interface ArtifactDetail extends Artifact { - /** File to render first, relative to the artifact files. Null until the first version is pushed. */ - entryPoint: string | null; + /** 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; + /** Size in bytes; null for folders. */ + sizeBytes: number | null; + /** File to render first, relative to the artifact files. Null until the first version is pushed. */ + entryPoint: string | null; + }; } /** One entry of a folder artifact's latest version; listings are one level deep. */ @@ -1442,7 +1444,7 @@ export interface ArtifactServer { listArtifacts(req?: ListArtifactsParams): 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; + 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; diff --git a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx index 6aaf7e5cd0..4c144b6508 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx @@ -43,7 +43,11 @@ export function ArtifactsTable({ artifacts, selectedKey, onOpen, onDownload, onE > - + {artifact.name} @@ -69,7 +73,7 @@ export function ArtifactsTable({ artifacts, selectedKey, onOpen, onDownload, onE onEdit(artifact)} /> onOpen(artifact)} /> {/* The API serves files one by one and has no archive route, so a folder has nothing to download. */} - {artifact.isDir ? null : ( + {artifact.filesMetadata.isDir ? null : ( { - const type = artifactType(artifact); - const asTree = artifact.isDir && renderFolderFiles != null; + 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 ( <> diff --git a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts index 9ff1494ff8..d6ed209c74 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts +++ b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts @@ -1,6 +1,6 @@ import type { SandboxFilePreviewTarget } from '../../filePreview/FilePreviewContext.js'; import { folderFileTarget } from '../../filePreview/folderFileTarget.js'; -import { fileExtension, inlinePreviewKind } from '../../filePreview/readFilePreview.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. */ @@ -19,14 +19,15 @@ export function artifactPreviewTarget({ /** 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 list carries no entry file path; the read route picks it and the blob type drives rendering. - path: artifact.name, + // The entry file's extension picks the inline renderer; the name only stands in before the first version. + path: entryPoint ?? artifact.name, turnId: artifactPreviewKey(artifact), load: () => artifactServer.readArtifactFile({ id: artifact.id }), // A folder opens on its file list, since one entry file would hide the rest of its contents. - ...(artifact.isDir + ...(isDir ? { folder: { cacheKey: artifactPreviewKey(artifact), @@ -41,9 +42,6 @@ export function artifactPreviewTarget({ : target; } -const VIDEO_EXT = new Set(['mp4', 'mov', 'webm', 'mkv', 'avi', 'm4v']); -const AUDIO_EXT = new Set(['mp3', 'wav', 'ogg', 'm4a', 'flac', 'aac']); - export type ArtifactType = { label: string; icon: string }; const FILE_TYPE: ArtifactType = { label: 'File', icon: 'file' }; @@ -51,14 +49,11 @@ 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 }: Pick): ArtifactType { +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' }; - const extension = fileExtension(name); - if (VIDEO_EXT.has(extension)) return { label: 'Video', icon: 'file-video' }; - if (AUDIO_EXT.has(extension)) return { label: 'Audio', icon: 'file-audio' }; return FILE_TYPE; } diff --git a/packages/trueforge-ui/src/icons/IconRegistry.tsx b/packages/trueforge-ui/src/icons/IconRegistry.tsx index ada91be790..1b4266c024 100644 --- a/packages/trueforge-ui/src/icons/IconRegistry.tsx +++ b/packages/trueforge-ui/src/icons/IconRegistry.tsx @@ -41,11 +41,9 @@ import { EllipsisVertical, ExternalLink, File, - FileAudio, FileCode2, FileSpreadsheet, FileText, - FileVideo, Folder, GalleryHorizontalEnd, GripVertical, @@ -207,8 +205,6 @@ const defaults: Record = { 'gallery-horizontal-end': GalleryHorizontalEnd, 'file-code': FileCode2, image: Image, - 'file-video': FileVideo, - 'file-audio': FileAudio, folder: Folder, 'file-spreadsheet': FileSpreadsheet, 'file-text': FileText, diff --git a/packages/trueforge-ui/src/index.ts b/packages/trueforge-ui/src/index.ts index ea77249e26..fd15e844cc 100644 --- a/packages/trueforge-ui/src/index.ts +++ b/packages/trueforge-ui/src/index.ts @@ -387,7 +387,6 @@ export type { AgentUIServer, ApprovalDecision, Artifact, - ArtifactDetail, ArtifactFile, ArtifactServer, AuthenticateConnectorRequest, diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts index adfb917a71..7266745870 100644 --- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts +++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts @@ -3,13 +3,7 @@ * reject until their routes land. */ import type { TrueForge, TrueForgeApi } from '@truefoundry/trueforge-sdk'; -import type { - Artifact, - ArtifactDetail, - ArtifactFile, - ArtifactServer, - ListArtifactsParams, -} from '../../server/types.js'; +import type { Artifact, ArtifactFile, ArtifactServer, ListArtifactsParams } from '../../server/types.js'; import { toListResult } from './chatServer.js'; function unavailable(action: string): Promise { @@ -23,14 +17,14 @@ function toUiArtifact(artifact: TrueForgeApi.Artifact): Artifact { createdBySubject: artifact.createdBySubject, createdAt: artifact.createdAt.toISOString(), updatedAt: artifact.updatedAt.toISOString(), - isDir: artifact.isDir, + filesMetadata: { + isDir: artifact.filesMetadata.isDir, + sizeBytes: artifact.filesMetadata.sizeBytes, + entryPoint: artifact.filesMetadata.entryPoint, + }, }; } -function toUiArtifactDetail(artifact: TrueForgeApi.ArtifactDetail): ArtifactDetail { - return { ...toUiArtifact(artifact), entryPoint: artifact.entryPoint }; -} - function toUiArtifactFile(file: TrueForgeApi.ArtifactFile): ArtifactFile { return { path: file.path, isDir: file.isDir, size: file.fileSize }; } @@ -75,7 +69,7 @@ export function createArtifactServer(client: TrueForge): ArtifactServer { }, async getArtifact({ id }) { const response = await client.artifacts.get(id); - return toUiArtifactDetail(response.data); + return toUiArtifact(response.data); }, async listArtifactFiles({ id, path }) { const response = await listFiles(id, path); diff --git a/packages/trueforge-ui/src/server/types.ts b/packages/trueforge-ui/src/server/types.ts index 71b258ce17..3622e6aa42 100644 --- a/packages/trueforge-ui/src/server/types.ts +++ b/packages/trueforge-ui/src/server/types.ts @@ -33,7 +33,6 @@ export type { AgentUIServer, ApprovalDecision, Artifact, - ArtifactDetail, ArtifactFile, ArtifactServer, AuthenticateConnectorRequest, diff --git a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx index 56a85ce283..7aeb24b07e 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx +++ b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx @@ -13,12 +13,15 @@ import { createMockAgentUIServer, createMockArtifactServer, createMockCatalog } 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', - isDir: false, + filesMetadata: { isDir, sizeBytes: isDir ? null : 10, entryPoint: 'index.md' }, ...overrides, }; } @@ -112,7 +115,7 @@ describe('ArtifactsPage', () => { it('puts the artifact in the URL on open, and deep-links by id', async () => { const readArtifactFile = vi.fn(async () => new Blob(['# Hello'], { type: 'text/markdown' })); - const getArtifact = vi.fn(async () => ({ ...q4Brief, entryPoint: 'index.md' })); + const getArtifact = vi.fn(async () => q4Brief); const artifacts = createMockArtifactServer({ listArtifacts: async () => ({ data: sample }), getArtifact, @@ -224,7 +227,7 @@ describe('ArtifactsPage folder artifacts', () => { expect(await screen.findByRole('complementary', { name: 'Preview of index.html' })).toBeInTheDocument(); }); - it('marks each row with a folder or file icon from isDir', async () => { + it('marks each row with a folder or file icon from its folder flag', async () => { const { server } = folderServer(); renderWith(server); diff --git a/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx index f18daf3012..d0b6ee4302 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx +++ b/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx @@ -15,11 +15,13 @@ function artifact(id: string, name: string): Artifact { createdBySubject: subject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', - isDir: false, + filesMetadata: { isDir: false, sizeBytes: 10, entryPoint: null }, }; } -const names = ['a.png', 'b.html', 'c.mp4', 'd.mp3', 'e.pdf', 'f.txt', 'g.png', 'h.png']; +const folderMetadata: Artifact['filesMetadata'] = { isDir: true, sizeBytes: null, 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', () => { @@ -33,7 +35,7 @@ describe('SessionArtifactsCard', () => { 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', 'Video', 'Audio', 'Pdf', 'File']) { + for (const label of ['Image', 'Html', 'Pdf', 'File']) { expect(screen.queryByText(label)).not.toBeInTheDocument(); } @@ -48,7 +50,7 @@ describe('SessionArtifactsCard', () => { }); it('shows a folder icon, not a type label, for a folder artifact', () => { - const folder: Artifact = { ...artifact('folder-1', 'Dummy HTML CSS JS'), isDir: true }; + const folder: Artifact = { ...artifact('folder-1', 'Dummy HTML CSS JS'), filesMetadata: folderMetadata }; render(); const row = screen.getByRole('button', { name: 'Dummy HTML CSS JS' }); @@ -65,7 +67,7 @@ describe('SessionArtifactsCard', () => { }); it('expands a folder row in place to list its files, and collapses it again', () => { - const folder: Artifact = { ...artifact('folder-1', 'Site'), isDir: true }; + const folder: Artifact = { ...artifact('folder-1', 'Site'), filesMetadata: folderMetadata }; const renderFolderFiles = vi.fn(() =>
folder files
); const onToggleFolder = vi.fn(); const onOpen = vi.fn(); @@ -96,7 +98,7 @@ describe('SessionArtifactsCard', () => { }); 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'), isDir: true }; + const folder: Artifact = { ...artifact('folder-1', 'Site'), filesMetadata: folderMetadata }; const onOpen = vi.fn(); render(); diff --git a/packages/trueforge-ui/test/atoms/artifacts/artifactDisplay.test.ts b/packages/trueforge-ui/test/atoms/artifacts/artifactDisplay.test.ts index d01be684da..b5bbed2be1 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/artifactDisplay.test.ts +++ b/packages/trueforge-ui/test/atoms/artifacts/artifactDisplay.test.ts @@ -7,14 +7,14 @@ import { createMockArtifactServer } from '../../server/mockServer.js'; const subject = { subjectId: 'user-1', subjectType: 'user', subjectDisplayName: 'alice' } as const; -function artifact(overrides: Partial = {}): Artifact { +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', - isDir: false, + filesMetadata: { isDir, sizeBytes: isDir ? null : 10, entryPoint: 'index.html' }, ...overrides, }; } @@ -29,6 +29,11 @@ describe('artifactType', () => { 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', () => { @@ -39,6 +44,8 @@ describe('artifactPreviewTarget', () => { 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' }); diff --git a/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx index 5c285e7270..91dd40b8ed 100644 --- a/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx +++ b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx @@ -34,10 +34,12 @@ function artifact(id: string, name: string): Artifact { createdBySubject: subject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', - isDir: false, + filesMetadata: { isDir: false, sizeBytes: 10, entryPoint: null }, }; } +const folderMetadata: Artifact['filesMetadata'] = { isDir: true, sizeBytes: null, entryPoint: 'index.html' }; + function PreviewProbe() { const { target } = useFilePreview(); return ( @@ -136,7 +138,7 @@ describe('SessionArtifactsContainer', () => { }); it('lists a folder artifact as a tree and opens a picked file on its own', async () => { - const folder: Artifact = { ...artifact('f1', 'Dummy site'), isDir: true }; + const folder: Artifact = { ...artifact('f1', 'Dummy site'), filesMetadata: folderMetadata }; const listSessionArtifacts = vi.fn(async () => [folder]); const listArtifactFiles = vi.fn(async ({ path = '' }: { id: string; path?: string }) => path === '' 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 488f5b174a..5241deda58 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 @@ -15,9 +15,11 @@ const sdkArtifact = { createdBySubject, createdAt: new Date('2024-01-01T00:00:00.000Z'), updatedAt: new Date('2024-01-02T00:00:00.000Z'), - isDir: false, + 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(), @@ -64,34 +66,35 @@ describe('createArtifactServer', () => { createdBySubject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', - isDir: false, + filesMetadata: uiFilesMetadata, }, ]); }); it('maps the folder flag from the list response', async () => { const list = vi.fn(async () => ({ - data: [{ ...sdkArtifact, isDir: true }], + data: [{ ...sdkArtifact, filesMetadata: { isDir: true, sizeBytes: null, entryPoint: 'index.html' } }], response: { pagination: { limit: 25 } }, })); const page = await createArtifactServer(mockClient({ list })).listArtifacts(); - expect(page.data[0]?.isDir).toBe(true); + expect(page.data[0]?.filesMetadata.isDir).toBe(true); }); - it('gets one artifact with its entry point and folder flag', async () => { - const get = vi.fn(async () => ({ data: { ...sdkArtifact, isDir: true, entryPoint: 'index.html' } })); - const detail = await createArtifactServer(mockClient({ get })).getArtifact({ id: 'a1' }); + it('gets one artifact with its files metadata', async () => { + const get = vi.fn(async () => ({ + data: { ...sdkArtifact, filesMetadata: { isDir: true, sizeBytes: null, entryPoint: 'index.html' } }, + })); + const artifact = await createArtifactServer(mockClient({ get })).getArtifact({ id: 'a1' }); expect(get).toHaveBeenCalledWith('a1'); - expect(detail).toEqual({ + expect(artifact).toEqual({ id: 'a1', name: 'Q4 brief', createdBySubject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', - isDir: true, - entryPoint: 'index.html', + filesMetadata: { isDir: true, sizeBytes: null, entryPoint: 'index.html' }, }); }); @@ -115,7 +118,7 @@ describe('createArtifactServer', () => { createdBySubject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', - isDir: false, + filesMetadata: uiFilesMetadata, }, ]); }); @@ -175,7 +178,7 @@ describe('createArtifactServer', () => { }); it('reads the only top-level file of a single-file artifact without fetching its details', async () => { - const get = vi.fn(async () => ({ data: { ...sdkArtifact, entryPoint: 'index.html' } })); + const get = vi.fn(async () => ({ data: sdkArtifact })); const listFiles = vi.fn(async () => ({ data: [htmlFile] })); vi.stubGlobal( 'fetch', From 28225331df999312cad77a8081c75cd8c382cc53 Mon Sep 17 00:00:00 2001 From: harshil-2096 Date: Wed, 2 Dec 2026 12:51:39 +0000 Subject: [PATCH 18/20] fix: Enhance session artifacts handling by introducing selected artifact key logic and improving folder file preview --- .../containers/SessionArtifactsContainer.tsx | 26 ++++++-- .../src/filePreview/folderFileTarget.ts | 18 ++++- .../SessionArtifactsContainer.test.tsx | 65 ++++++++++++++++--- .../test/filePreview/folderFileTarget.test.ts | 55 ++++++++++++++++ 4 files changed, 149 insertions(+), 15 deletions(-) create mode 100644 packages/trueforge-ui/test/filePreview/folderFileTarget.test.ts diff --git a/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx index 401ad69d93..5921d53c12 100644 --- a/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx +++ b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx @@ -6,10 +6,11 @@ import { useEffect, useRef } from 'react'; import { useTrackAnalytics } from '../analytics/AnalyticsProvider.js'; import { AnalyticsEvents } from '../analytics/events.js'; import { useAuiState } from '../assistant-ui.js'; -import { artifactPreviewTarget } from '../atoms/artifacts/artifactDisplay.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 } from '../filePreview/FilePreviewContext.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'; @@ -64,6 +65,20 @@ function useSessionArtifactsQuery() { return { artifactServer, sessionId, artifacts: query.data, loading: query.isPending }; } +/** When a file opened from a folder's tree is previewed, its folder row is the selected one, as the target key names the file. */ +function selectedArtifactKey({ + target, + artifacts, +}: { + target: SandboxFilePreviewTarget | null; + artifacts: Artifact[]; +}): string | undefined { + const folder = artifacts.find( + artifact => openFolderFilePath({ target, folderTurnId: artifactPreviewKey(artifact) }) !== null, + ); + return folder === undefined ? target?.turnId : artifactPreviewKey(folder); +} + /** True when the card column is on screen, so the composer leaves room for it. */ export function useSessionArtifactsVisible(): boolean { const supported = useSessionArtifactsSupported(); @@ -106,9 +121,12 @@ export function SessionArtifactsContainer() { 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)} /> ); @@ -131,7 +149,7 @@ export function SessionArtifactsContainer() { openArtifact(artifact)} onShowMore={() => track(AnalyticsEvents.Artifact.SESSION_CARD_SHOW_MORE)} renderFolderFiles={renderFolderFiles} diff --git a/packages/trueforge-ui/src/filePreview/folderFileTarget.ts b/packages/trueforge-ui/src/filePreview/folderFileTarget.ts index ac7befeccd..3361a6f492 100644 --- a/packages/trueforge-ui/src/filePreview/folderFileTarget.ts +++ b/packages/trueforge-ui/src/filePreview/folderFileTarget.ts @@ -1,6 +1,10 @@ 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, @@ -14,7 +18,19 @@ export function folderFileTarget({ return { name: filenameFromPath(path), path, - turnId: `${target.turnId}:${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/test/containers/SessionArtifactsContainer.test.tsx b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx index 91dd40b8ed..217f979283 100644 --- a/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx +++ b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx @@ -40,6 +40,21 @@ function artifact(id: string, name: string): Artifact { const folderMetadata: Artifact['filesMetadata'] = { isDir: true, sizeBytes: null, 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 }, + { path: 'index.html', isDir: false, size: 10 }, + ] + : [{ path: 'assets/app.js', isDir: false, size: 5 }], + ); +} + function PreviewProbe() { const { target } = useFilePreview(); return ( @@ -138,16 +153,8 @@ describe('SessionArtifactsContainer', () => { }); it('lists a folder artifact as a tree and opens a picked file on its own', async () => { - const folder: Artifact = { ...artifact('f1', 'Dummy site'), filesMetadata: folderMetadata }; - const listSessionArtifacts = vi.fn(async () => [folder]); - const listArtifactFiles = vi.fn(async ({ path = '' }: { id: string; path?: string }) => - path === '' - ? [ - { path: 'assets/', isDir: true, size: null }, - { path: 'index.html', isDir: false, size: 10 }, - ] - : [{ path: 'assets/app.js', isDir: false, size: 5 }], - ); + const listSessionArtifacts = vi.fn(async () => [siteFolder()]); + const listArtifactFiles = vi.fn(listSiteFiles); const track = vi.fn(); renderContainer({ artifacts: createMockArtifactServer({ listSessionArtifacts, listArtifactFiles }), @@ -169,6 +176,44 @@ describe('SessionArtifactsContainer', () => { expect(track).toHaveBeenCalledWith(AnalyticsEvents.Artifact.SESSION_CARD_PREVIEW_OPENED, { artifact_id: 'f1' }); }); + it('marks the picked file and its folder row as selected while that file is previewed', 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).not.toHaveAttribute('aria-current'); + expect(folderRow).not.toHaveClass('bg-secondary-button-hover'); + + fireEvent.click(file); + expect(screen.getByLabelText('Preview target')).toHaveTextContent('index.html'); + expect(screen.getByRole('button', { name: /index\.html/ })).toHaveAttribute('aria-current', 'true'); + expect(screen.getByRole('button', { name: /Dummy site/ })).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' })); 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..817ec63ac9 --- /dev/null +++ b/packages/trueforge-ui/test/filePreview/folderFileTarget.test.ts @@ -0,0 +1,55 @@ +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', + }; + 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(); + }); +}); From 5b1694721ec45462a501da81103b1faef55b09c1 Mon Sep 17 00:00:00 2001 From: harshil-2096 Date: Thu, 3 Dec 2026 04:56:59 +0000 Subject: [PATCH 19/20] fix: enhance artifact handling with entry file previews and improved error messaging --- .../artifact-entry-point-and-access-errors.md | 7 +++ .../assistant-ui-runtime/src/server/types.ts | 15 ++++--- .../src/atoms/FilePreviewFolderBrowser.tsx | 6 ++- .../atoms/artifacts/ArtifactEditDialog.tsx | 9 +++- .../src/atoms/artifacts/ArtifactsTable.tsx | 9 ++-- .../atoms/artifacts/SessionArtifactsCard.tsx | 4 +- .../src/atoms/artifacts/artifactDisplay.ts | 10 +++-- .../src/atoms/artifacts/carryFileListings.ts | 16 +++++++ .../FilePreviewFolderBrowserContainer.tsx | 6 ++- .../src/containers/FilePreviewHost.tsx | 7 +-- .../containers/SessionArtifactsContainer.tsx | 11 +++-- .../src/filePreview/FilePreviewContext.tsx | 2 + .../src/filePreview/useFolderTree.ts | 31 +++++++++++-- .../src/filePreview/useLoadedFilePreview.ts | 6 ++- .../artifactServer.ts | 18 ++++---- packages/trueforge-ui/src/server/queryKeys.ts | 8 +++- .../src/utils/artifactErrorMessage.ts | 18 ++++++++ .../atoms/FilePreviewFolderBrowser.test.tsx | 30 ++++++++++--- .../atoms/artifacts/ArtifactsPage.test.tsx | 43 +++++++++++++------ .../artifacts/SessionArtifactsCard.test.tsx | 9 ++-- .../atoms/artifacts/artifactDisplay.test.ts | 20 +++++++-- .../atoms/artifacts/carryFileListings.test.ts | 35 +++++++++++++++ .../SessionArtifactsContainer.test.tsx | 28 ++++++------ .../test/filePreview/folderFileTarget.test.ts | 1 + .../test/filePreview/useFolderTree.test.tsx | 38 ++++++++++++++-- .../artifactServer.test.ts | 39 +++++++++-------- .../trueforge-ui/test/server/mockServer.ts | 1 - .../test/utils/artifactErrorMessage.test.ts | 30 +++++++++++++ 28 files changed, 351 insertions(+), 106 deletions(-) create mode 100644 .changeset/artifact-entry-point-and-access-errors.md create mode 100644 packages/trueforge-ui/src/atoms/artifacts/carryFileListings.ts create mode 100644 packages/trueforge-ui/src/utils/artifactErrorMessage.ts create mode 100644 packages/trueforge-ui/test/atoms/artifacts/carryFileListings.test.ts create mode 100644 packages/trueforge-ui/test/utils/artifactErrorMessage.test.ts 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/packages/assistant-ui-runtime/src/server/types.ts b/packages/assistant-ui-runtime/src/server/types.ts index d2476d87ca..99eba3a61e 100644 --- a/packages/assistant-ui-runtime/src/server/types.ts +++ b/packages/assistant-ui-runtime/src/server/types.ts @@ -1418,10 +1418,10 @@ export interface Artifact { filesMetadata: { /** True when the latest version is a folder; a single top-level file is false. */ isDir: boolean; - /** Size in bytes; null for folders. */ - sizeBytes: number | null; - /** File to render first, relative to the artifact files. Null until the first version is pushed. */ - entryPoint: string | null; + /** Total size in bytes of the latest version's files. */ + sizeBytes: number; + /** File to render first, relative to the artifact files. */ + entryPoint: string; }; } @@ -1432,6 +1432,8 @@ export interface ArtifactFile { 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 { @@ -1448,9 +1450,8 @@ export interface ArtifactServer { /** 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; - /** Without `path`, reads the file of a single-file artifact; a folder needs a `path`. */ - 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/src/atoms/FilePreviewFolderBrowser.tsx b/packages/trueforge-ui/src/atoms/FilePreviewFolderBrowser.tsx index 5a0dea8590..cbcff37d36 100644 --- a/packages/trueforge-ui/src/atoms/FilePreviewFolderBrowser.tsx +++ b/packages/trueforge-ui/src/atoms/FilePreviewFolderBrowser.tsx @@ -6,6 +6,7 @@ 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 = { @@ -49,7 +50,7 @@ function FolderLevel({
); } - if (level.status === 'error') return Couldn't load these files.; + if (level.status === 'error') return {level.message}; if (level.entries.length === 0) return This folder is empty.; const renderEntry = (entry: ArtifactFile) => { @@ -92,6 +93,9 @@ function FolderLevel({ type="button" onClick={() => onSelect(entry.path)} style={indent} + {...(entry.lastModified === null + ? {} + : { title: `Modified ${formatAbsoluteDateTime(new Date(entry.lastModified))}` })} {...(selected ? { 'aria-current': true } : {})} className={cn( 'flex w-full cursor-pointer items-center gap-1.5 rounded-md py-1.5 pr-2 text-left text-sm text-text-primary hover:bg-secondary-button-hover', 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/ArtifactsTable.tsx b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx index 4c144b6508..d50916ec33 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx +++ b/packages/trueforge-ui/src/atoms/artifacts/ArtifactsTable.tsx @@ -2,7 +2,7 @@ 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'; @@ -25,7 +25,7 @@ export function ArtifactsTable({ artifacts, selectedKey, onOpen, onDownload, onE Name - Created by + Size Updated @@ -51,8 +51,8 @@ export function ArtifactsTable({ artifacts, selectedKey, onOpen, onDownload, onE {artifact.name} - - + + {formatFileSize(artifact.filesMetadata.sizeBytes)} {formatRelativeTime(artifact.updatedAt)} {/* Swallow here so menu clicks do not also open the preview. */} @@ -71,7 +71,6 @@ export function ArtifactsTable({ artifacts, selectedKey, onOpen, onDownload, onE } > onEdit(artifact)} /> - onOpen(artifact)} /> {/* The API serves files one by one and has no archive route, so a folder has nothing to download. */} {artifact.filesMetadata.isDir ? null : ( 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. */ + /** 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; @@ -59,6 +59,8 @@ export function SessionArtifactsCard({ 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); diff --git a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts index d6ed209c74..6c0c39bc90 100644 --- a/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts +++ b/packages/trueforge-ui/src/atoms/artifacts/artifactDisplay.ts @@ -22,15 +22,17 @@ export function artifactPreviewTarget({ const { isDir, entryPoint } = artifact.filesMetadata; const target: SandboxFilePreviewTarget = { name: artifact.name, - // The entry file's extension picks the inline renderer; the name only stands in before the first version. - path: entryPoint ?? artifact.name, + // The entry file's extension picks the inline renderer. + path: entryPoint, turnId: artifactPreviewKey(artifact), - load: () => artifactServer.readArtifactFile({ id: artifact.id }), - // A folder opens on its file list, since one entry file would hide the rest of its contents. + // 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 }), }, 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 index ddde27b9a4..0a126cf3d0 100644 --- a/packages/trueforge-ui/src/containers/FilePreviewFolderBrowserContainer.tsx +++ b/packages/trueforge-ui/src/containers/FilePreviewFolderBrowserContainer.tsx @@ -15,6 +15,10 @@ export function FilePreviewFolderBrowserContainer({ onSelect: (path: string) => void; }) { const FilePreviewFolderBrowser = useSlot('FilePreviewFolderBrowser'); - const tree = useFolderTree({ cacheKey: folder.cacheKey, list: folder.list }); + 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 64a6d6f61c..c4c961acad 100644 --- a/packages/trueforge-ui/src/containers/FilePreviewHost.tsx +++ b/packages/trueforge-ui/src/containers/FilePreviewHost.tsx @@ -36,7 +36,7 @@ function storePreviewWidth(widthPx: number) { } } -/** The one file the panel previews: the target itself, or the file picked from its folder (none until one is picked). */ +/** 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, @@ -60,8 +60,9 @@ export function FilePreviewHost() { 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, so opening another preview starts on that folder's file list. - const selectedPath = selection != null && selection.targetKey === targetKey ? selection.path : null; + // A pick belongs to the preview it was made in, so opening another preview starts on that folder's entry file. + 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'; diff --git a/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx index 5921d53c12..5d7c10c981 100644 --- a/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx +++ b/packages/trueforge-ui/src/containers/SessionArtifactsContainer.tsx @@ -65,7 +65,7 @@ function useSessionArtifactsQuery() { return { artifactServer, sessionId, artifacts: query.data, loading: query.isPending }; } -/** When a file opened from a folder's tree is previewed, its folder row is the selected one, as the target key names the file. */ +/** 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, @@ -73,10 +73,10 @@ function selectedArtifactKey({ target: SandboxFilePreviewTarget | null; artifacts: Artifact[]; }): string | undefined { - const folder = artifacts.find( + const insideFolder = artifacts.some( artifact => openFolderFilePath({ target, folderTurnId: artifactPreviewKey(artifact) }) !== null, ); - return folder === undefined ? target?.turnId : artifactPreviewKey(folder); + return insideFolder ? undefined : target?.turnId; } /** True when the card column is on screen, so the composer leaves room for it. */ @@ -110,10 +110,13 @@ export function SessionArtifactsContainer() { 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, ...(filePath === undefined ? {} : { filePath }) }), + artifactPreviewTarget({ artifact, artifactServer, ...(openPath === undefined ? {} : { filePath: openPath }) }), ); }; diff --git a/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsx b/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsx index 3f79c0f41a..8b10d6f4c0 100644 --- a/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsx +++ b/packages/trueforge-ui/src/filePreview/FilePreviewContext.tsx @@ -12,6 +12,8 @@ export type FilePreviewFolder = { 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 = { diff --git a/packages/trueforge-ui/src/filePreview/useFolderTree.ts b/packages/trueforge-ui/src/filePreview/useFolderTree.ts index 1e370451a2..beac2f9c09 100644 --- a/packages/trueforge-ui/src/filePreview/useFolderTree.ts +++ b/packages/trueforge-ui/src/filePreview/useFolderTree.ts @@ -5,8 +5,12 @@ 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'; -export type FolderLevel = { status: 'loading' } | { status: 'error' } | { status: 'ready'; entries: ArtifactFile[] }; +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. */ @@ -15,24 +19,36 @@ export type FolderTree = { 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()); + 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) => { @@ -47,10 +63,15 @@ export function useFolderTree({ .then(entries => { setLevels(current => ({ ...current, [path]: { status: 'ready', entries } })); }) - .catch(() => { + .catch((error: unknown) => { // A failed revalidation keeps the files already on screen. setLevels(current => - current[path]?.status === 'ready' ? current : { ...current, [path]: { status: 'error' } }, + current[path]?.status === 'ready' + ? current + : { + ...current, + [path]: { status: 'error', message: artifactErrorMessage({ error, fallback: LEVEL_ERROR_MESSAGE }) }, + }, ); }); }, @@ -59,6 +80,8 @@ export function useFolderTree({ useEffect(() => { load(''); + const reveal = revealRef.current; + if (reveal !== undefined) ancestorFolders(reveal).forEach(load); }, [load]); const toggle = useCallback( 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/plugins/trueforge-agent-server-adapter/artifactServer.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts index 7266745870..965f7ed2a5 100644 --- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts +++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/artifactServer.ts @@ -1,15 +1,10 @@ /** - * Harness ArtifactServer adapter. Get, list, list files, session list and rename exist on the API; the other methods - * reject until their routes land. + * Harness ArtifactServer adapter over the artifacts API: get, list, list files, session list, rename and file reads. */ import type { TrueForge, TrueForgeApi } from '@truefoundry/trueforge-sdk'; import type { Artifact, ArtifactFile, ArtifactServer, ListArtifactsParams } from '../../server/types.js'; import { toListResult } from './chatServer.js'; -function unavailable(action: string): Promise { - return Promise.reject(new Error(`${action} is not available yet`)); -} - function toUiArtifact(artifact: TrueForgeApi.Artifact): Artifact { return { id: artifact.id, @@ -26,7 +21,12 @@ function toUiArtifact(artifact: TrueForgeApi.Artifact): Artifact { } function toUiArtifactFile(file: TrueForgeApi.ArtifactFile): ArtifactFile { - return { path: file.path, isDir: file.isDir, size: file.fileSize }; + return { + path: file.path, + isDir: file.isDir, + size: file.sizeBytes, + lastModified: file.lastModified === null ? null : file.lastModified.toISOString(), + }; } /** Folder part of a file path, with its trailing slash; empty for a top-level file. */ @@ -79,9 +79,7 @@ export function createArtifactServer(client: TrueForge): ArtifactServer { const response = await client.artifacts.update(id, { name }); return toUiArtifact(response.data); }, - deleteArtifact: () => unavailable('Delete artifact'), - async readArtifactFile({ id, path, version }) { - if (version !== undefined) return unavailable('Reading an artifact version'); + async readArtifactFile({ id, path }) { // The API only hands out a download url per listed file, so the file is found in a folder listing. const entry = path === undefined ? await singleFileEntry(id) : await listedFile(id, path); if (entry.s3Url == null) throw new Error(`Artifact file not found: ${entry.path}`); diff --git a/packages/trueforge-ui/src/server/queryKeys.ts b/packages/trueforge-ui/src/server/queryKeys.ts index 97c45aa805..da83a0c466 100644 --- a/packages/trueforge-ui/src/server/queryKeys.ts +++ b/packages/trueforge-ui/src/server/queryKeys.ts @@ -106,10 +106,14 @@ export const queryKeys = { detail: (name: string) => key('environments', 'detail', name), }, artifacts: { - all: () => key('artifacts'), + /** Prefix of every `list` key, so a mutation can refresh the Artifacts page without touching file listings. */ + lists: () => key('artifacts', 'list'), list: (params: ListArtifactsParams) => key('artifacts', 'list', params), - /** Nested under `all()` so artifact rename/delete invalidation reaches the session card. */ + /** Prefix of every session card `session` key. */ + sessions: () => key('artifacts', 'session'), session: (sessionId: string) => key('artifacts', 'session', sessionId), + /** Prefix of every listing of one artifact version. */ + filesOf: (artifactKey: string) => key('artifacts', 'files', artifactKey), /** `artifactKey` carries the artifact version, so a new version lists afresh. */ files: ({ artifactKey, path }: { artifactKey: string; path: string }) => key('artifacts', 'files', artifactKey, path), diff --git a/packages/trueforge-ui/src/utils/artifactErrorMessage.ts b/packages/trueforge-ui/src/utils/artifactErrorMessage.ts new file mode 100644 index 0000000000..f1c708ab98 --- /dev/null +++ b/packages/trueforge-ui/src/utils/artifactErrorMessage.ts @@ -0,0 +1,18 @@ +const NO_ACCESS_MESSAGE = "You don't have access to open this artifact."; +const NOT_FOUND_MESSAGE = 'This artifact or file was not found. It may have been removed.'; + +function statusCodeOf(error: unknown): number | undefined { + if (error == null || typeof error !== 'object' || !('statusCode' in error)) return undefined; + return typeof error.statusCode === 'number' ? error.statusCode : undefined; +} + +/** + * Artifact reads fail with 403 when a shared-session viewer is not the creator and 404 when a file was + * removed, so those get their own copy; anything else keeps the caller's generic message. + */ +export function artifactErrorMessage({ error, fallback }: { error: unknown; fallback: string }): string { + const status = statusCodeOf(error); + if (status === 403) return NO_ACCESS_MESSAGE; + if (status === 404) return NOT_FOUND_MESSAGE; + return fallback; +} diff --git a/packages/trueforge-ui/test/atoms/FilePreviewFolderBrowser.test.tsx b/packages/trueforge-ui/test/atoms/FilePreviewFolderBrowser.test.tsx index 0a3bc04e12..7edc891839 100644 --- a/packages/trueforge-ui/test/atoms/FilePreviewFolderBrowser.test.tsx +++ b/packages/trueforge-ui/test/atoms/FilePreviewFolderBrowser.test.tsx @@ -6,9 +6,14 @@ import { FilePreviewFolderBrowser } from '@/atoms/FilePreviewFolderBrowser.js'; import type { FolderTree } from '@/filePreview/useFolderTree.js'; import type { ArtifactFile } from '@/server/types.js'; -const dataDir: ArtifactFile = { path: 'data/', isDir: true, size: null }; -const indexFile: ArtifactFile = { path: 'index.html', isDir: false, size: 1536 }; -const csvFile: ArtifactFile = { path: 'data/a.csv', isDir: false, size: 3 }; +const dataDir: ArtifactFile = { path: 'data/', isDir: true, size: null, lastModified: null }; +const indexFile: ArtifactFile = { + path: 'index.html', + isDir: false, + size: 1536, + lastModified: '2024-01-03T10:30:00.000Z', +}; +const csvFile: ArtifactFile = { path: 'data/a.csv', isDir: false, size: 3, lastModified: null }; function tree(overrides: Partial = {}): FolderTree { return { @@ -93,7 +98,7 @@ describe('FilePreviewFolderBrowser', () => { rerender( , @@ -104,7 +109,10 @@ describe('FilePreviewFolderBrowser', () => { { ); const folderRow = screen.getByRole('button', { name: /^data$/ }).closest('li'); if (folderRow == null) throw new Error('Expected the folder row to render in a list item'); - expect(within(folderRow).getByText("Couldn't load these files.")).toBeInTheDocument(); + expect(within(folderRow).getByText("You don't have access to open this artifact.")).toBeInTheDocument(); + }); + + it('gives a file its modified time as a tooltip when it has one', () => { + render(); + + expect(screen.getByRole('button', { name: /index\.html/ })).toHaveAttribute( + 'title', + expect.stringMatching(/^Modified .*2024/), + ); + expect(screen.getByRole('button', { name: /^data$/ })).not.toHaveAttribute('title'); }); }); diff --git a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx index 7aeb24b07e..40a53df8f7 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx +++ b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx @@ -21,7 +21,7 @@ function artifact({ createdBySubject: subject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', - filesMetadata: { isDir, sizeBytes: isDir ? null : 10, entryPoint: 'index.md' }, + filesMetadata: { isDir, sizeBytes: 10, entryPoint: isDir ? 'index.html' : 'index.md' }, ...overrides, }; } @@ -66,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(); @@ -170,6 +172,7 @@ 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(); }); @@ -179,10 +182,10 @@ describe('ArtifactsPage folder artifacts', () => { const site = artifact({ id: 'f1', name: 'Dummy site', isDir: true }); const listing: Record = { '': [ - { path: 'assets/', isDir: true, size: null }, - { path: 'index.html', isDir: false, size: 10 }, + { 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 }], + 'assets/': [{ path: 'assets/app.js', isDir: false, size: 5, lastModified: null }], }; function folderServer() { @@ -199,16 +202,16 @@ describe('ArtifactsPage folder artifacts', () => { return { listArtifactFiles, readArtifactFile, server }; } - it('opens on the folder files and previews each file as it is selected', async () => { + 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 Dummy site' }); - expect(await within(panel).findByRole('button', { name: /index\.html/ })).toBeInTheDocument(); + 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: '' }); - expect(readArtifactFile).not.toHaveBeenCalled(); - expect(within(panel).queryByRole('button', { name: /^Download/ })).not.toBeInTheDocument(); + 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/' })); @@ -223,10 +226,24 @@ describe('ArtifactsPage folder artifacts', () => { 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(readArtifactFile).toHaveBeenCalledTimes(2); expect(await screen.findByRole('complementary', { name: 'Preview of index.html' })).toBeInTheDocument(); }); + 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); diff --git a/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx index d0b6ee4302..a8bb587173 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx +++ b/packages/trueforge-ui/test/atoms/artifacts/SessionArtifactsCard.test.tsx @@ -15,11 +15,11 @@ function artifact(id: string, name: string): Artifact { createdBySubject: subject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', - filesMetadata: { isDir: false, sizeBytes: 10, entryPoint: null }, + filesMetadata: { isDir: false, sizeBytes: 10, entryPoint: name }, }; } -const folderMetadata: Artifact['filesMetadata'] = { isDir: true, sizeBytes: null, entryPoint: 'index.html' }; +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)); @@ -90,9 +90,12 @@ describe('SessionArtifactsCard', () => { expect(screen.getByText('folder files')).toBeInTheDocument(); expect(renderFolderFiles).toHaveBeenCalledWith(folder); expect(onToggleFolder).toHaveBeenCalledWith(folder); - expect(onOpen).not.toHaveBeenCalled(); + // 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(); }); diff --git a/packages/trueforge-ui/test/atoms/artifacts/artifactDisplay.test.ts b/packages/trueforge-ui/test/atoms/artifacts/artifactDisplay.test.ts index b5bbed2be1..d6a98ecfe3 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/artifactDisplay.test.ts +++ b/packages/trueforge-ui/test/atoms/artifacts/artifactDisplay.test.ts @@ -14,7 +14,7 @@ function artifact({ isDir = false, ...overrides }: Partial & { isDir?: createdBySubject: subject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', - filesMetadata: { isDir, sizeBytes: isDir ? null : 10, entryPoint: 'index.html' }, + filesMetadata: { isDir, sizeBytes: 10, entryPoint: 'index.html' }, ...overrides, }; } @@ -52,7 +52,7 @@ describe('artifactPreviewTarget', () => { }); 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 }]); + 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 }), @@ -60,12 +60,26 @@ describe('artifactPreviewTarget', () => { }); expect(target.folder).toBeDefined(); - await expect(target.folder?.list('')).resolves.toEqual([{ path: 'index.html', isDir: false, size: 10 }]); + 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', () => { 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 index 217f979283..2e75de905a 100644 --- a/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx +++ b/packages/trueforge-ui/test/containers/SessionArtifactsContainer.test.tsx @@ -34,11 +34,11 @@ function artifact(id: string, name: string): Artifact { createdBySubject: subject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', - filesMetadata: { isDir: false, sizeBytes: 10, entryPoint: null }, + filesMetadata: { isDir: false, sizeBytes: 10, entryPoint: name }, }; } -const folderMetadata: Artifact['filesMetadata'] = { isDir: true, sizeBytes: null, entryPoint: 'index.html' }; +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 }; @@ -48,10 +48,10 @@ async function listSiteFiles({ path = '' }: { id: string; path?: string }) { return Promise.resolve( path === '' ? [ - { path: 'assets/', isDir: true, size: null }, - { path: 'index.html', isDir: false, size: 10 }, + { 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 }], + : [{ path: 'assets/app.js', isDir: false, size: 5, lastModified: null }], ); } @@ -152,7 +152,7 @@ describe('SessionArtifactsContainer', () => { expect(screen.queryByRole('status', { name: 'Loading artifacts' })).not.toBeInTheDocument(); }); - it('lists a folder artifact as a tree and opens a picked file on its own', async () => { + 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(); @@ -162,7 +162,7 @@ describe('SessionArtifactsContainer', () => { }); fireEvent.click(await screen.findByRole('button', { name: /Dummy site/ })); - expect(screen.getByLabelText('Preview target')).toHaveTextContent('none'); + 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' }); @@ -176,7 +176,7 @@ describe('SessionArtifactsContainer', () => { expect(track).toHaveBeenCalledWith(AnalyticsEvents.Artifact.SESSION_CARD_PREVIEW_OPENED, { artifact_id: 'f1' }); }); - it('marks the picked file and its folder row as selected while that file is previewed', async () => { + 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 }), @@ -185,13 +185,15 @@ describe('SessionArtifactsContainer', () => { const folderRow = await screen.findByRole('button', { name: /Dummy site/ }); fireEvent.click(folderRow); const file = await screen.findByRole('button', { name: /index\.html/ }); - expect(file).not.toHaveAttribute('aria-current'); + expect(file).toHaveAttribute('aria-current', 'true'); expect(folderRow).not.toHaveClass('bg-secondary-button-hover'); - fireEvent.click(file); - expect(screen.getByLabelText('Preview target')).toHaveTextContent('index.html'); - expect(screen.getByRole('button', { name: /index\.html/ })).toHaveAttribute('aria-current', 'true'); - expect(screen.getByRole('button', { name: /Dummy site/ })).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 () => { diff --git a/packages/trueforge-ui/test/filePreview/folderFileTarget.test.ts b/packages/trueforge-ui/test/filePreview/folderFileTarget.test.ts index 817ec63ac9..e9a9ce1e15 100644 --- a/packages/trueforge-ui/test/filePreview/folderFileTarget.test.ts +++ b/packages/trueforge-ui/test/filePreview/folderFileTarget.test.ts @@ -8,6 +8,7 @@ function folderTarget(): { target: SandboxFilePreviewTarget; folder: FilePreview list: () => Promise.resolve([]), loadFile: vi.fn(() => Promise.resolve(new Blob(['x']))), cacheKey: 'a1@v1', + entryPoint: 'index.html', }; const target: SandboxFilePreviewTarget = { name: 'Site', diff --git a/packages/trueforge-ui/test/filePreview/useFolderTree.test.tsx b/packages/trueforge-ui/test/filePreview/useFolderTree.test.tsx index 53402d0c8e..584b4b0cca 100644 --- a/packages/trueforge-ui/test/filePreview/useFolderTree.test.tsx +++ b/packages/trueforge-ui/test/filePreview/useFolderTree.test.tsx @@ -7,9 +7,9 @@ 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 }; -const indexFile: ArtifactFile = { path: 'index.html', isDir: false, size: 10 }; -const csvFile: ArtifactFile = { path: 'data/a.csv', isDir: false, size: 3 }; +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]); @@ -52,7 +52,9 @@ describe('useFolderTree', () => { await waitFor(() => expect(result.current.levels['']?.status).toBe('ready')); act(() => result.current.toggle('data/')); - await waitFor(() => expect(result.current.levels['data/']).toEqual({ status: 'error' })); + 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/')); @@ -60,6 +62,34 @@ describe('useFolderTree', () => { 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 }) => ( 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 5241deda58..e42fb20550 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 @@ -39,9 +39,22 @@ function mockClient({ } as unknown as TrueForge; } -const htmlFile = { path: 'index.html', isDir: false, s3Url: 'https://s3.test/index.html', fileSize: 10 }; -const dataDir = { path: 'data/', isDir: true, s3Url: null, fileSize: null }; -const csvFile = { path: 'data/a.csv', isDir: false, s3Url: 'https://s3.test/a.csv', fileSize: 3 }; +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(); @@ -73,7 +86,7 @@ describe('createArtifactServer', () => { it('maps the folder flag from the list response', async () => { const list = vi.fn(async () => ({ - data: [{ ...sdkArtifact, filesMetadata: { isDir: true, sizeBytes: null, entryPoint: 'index.html' } }], + data: [{ ...sdkArtifact, filesMetadata: { isDir: true, sizeBytes: 10, entryPoint: 'index.html' } }], response: { pagination: { limit: 25 } }, })); const page = await createArtifactServer(mockClient({ list })).listArtifacts(); @@ -83,7 +96,7 @@ describe('createArtifactServer', () => { it('gets one artifact with its files metadata', async () => { const get = vi.fn(async () => ({ - data: { ...sdkArtifact, filesMetadata: { isDir: true, sizeBytes: null, entryPoint: 'index.html' } }, + data: { ...sdkArtifact, filesMetadata: { isDir: true, sizeBytes: 10, entryPoint: 'index.html' } }, })); const artifact = await createArtifactServer(mockClient({ get })).getArtifact({ id: 'a1' }); @@ -94,7 +107,7 @@ describe('createArtifactServer', () => { createdBySubject, createdAt: '2024-01-01T00:00:00.000Z', updatedAt: '2024-01-02T00:00:00.000Z', - filesMetadata: { isDir: true, sizeBytes: null, entryPoint: 'index.html' }, + filesMetadata: { isDir: true, sizeBytes: 10, entryPoint: 'index.html' }, }); }); @@ -132,13 +145,13 @@ describe('createArtifactServer', () => { expect(renamed.updatedAt).toBe('2024-01-02T00:00:00.000Z'); }); - it('lists one folder level without exposing download urls', async () => { + 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 }, - { path: 'index.html', isDir: false, size: 10 }, + { 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', {}); @@ -227,12 +240,4 @@ describe('createArtifactServer', () => { createArtifactServer(mockClient({ listFiles })).readArtifactFile({ id: 'a1', path: 'index.html' }), ).rejects.toThrow('403'); }); - - it('rejects the routes the API does not have yet', async () => { - const server = createArtifactServer(mockClient({})); - await expect(server.deleteArtifact({ id: 'a1' })).rejects.toThrow('not available yet'); - await expect(server.readArtifactFile({ id: 'a1', path: 'index.html', version: 2 })).rejects.toThrow( - 'not available yet', - ); - }); }); diff --git a/packages/trueforge-ui/test/server/mockServer.ts b/packages/trueforge-ui/test/server/mockServer.ts index 8a2e417769..a6eef644c5 100644 --- a/packages/trueforge-ui/test/server/mockServer.ts +++ b/packages/trueforge-ui/test/server/mockServer.ts @@ -89,7 +89,6 @@ export function createMockArtifactServer(overrides: Partial = {} 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); + }); +}); From 303099b19aa62cc03b401d7fbc3318e88febbed0 Mon Sep 17 00:00:00 2001 From: harshil-2096 Date: Thu, 3 Dec 2026 05:12:23 +0000 Subject: [PATCH 20/20] fix: update FilePreviewHost logic to reset selection on folder change and add test for reopening entry files --- .../src/containers/FilePreviewHost.tsx | 4 ++- .../atoms/artifacts/ArtifactsPage.test.tsx | 21 ++++++++++++ .../artifactServer.test.ts | 33 ++++++++++--------- 3 files changed, 42 insertions(+), 16 deletions(-) diff --git a/packages/trueforge-ui/src/containers/FilePreviewHost.tsx b/packages/trueforge-ui/src/containers/FilePreviewHost.tsx index c4c961acad..9d9fb397fd 100644 --- a/packages/trueforge-ui/src/containers/FilePreviewHost.tsx +++ b/packages/trueforge-ui/src/containers/FilePreviewHost.tsx @@ -60,7 +60,9 @@ export function FilePreviewHost() { 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, so opening another preview starts on that folder's entry file. + // 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]); diff --git a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx index 40a53df8f7..8cd23a2896 100644 --- a/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx +++ b/packages/trueforge-ui/test/atoms/artifacts/ArtifactsPage.test.tsx @@ -229,6 +229,27 @@ describe('ArtifactsPage folder artifacts', () => { 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(); 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 e42fb20550..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 @@ -60,6 +60,15 @@ 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', () => { it('lists artifacts with paging tokens and forwards the name search', async () => { const list = vi.fn(async () => ({ @@ -161,8 +170,7 @@ describe('createArtifactServer', () => { 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 fetchFile = vi.fn(async () => new Response('

hi

')); - vi.stubGlobal('fetch', fetchFile); + const { bytes, download } = stubDownload(); const blob = await createArtifactServer(mockClient({ listFiles })).readArtifactFile({ id: 'a1', @@ -170,16 +178,13 @@ describe('createArtifactServer', () => { }); expect(listFiles).toHaveBeenCalledWith('a1', {}); - expect(fetchFile).toHaveBeenCalledWith('https://s3.test/index.html'); - await expect(blob.text()).resolves.toBe('

hi

'); + 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] })); - vi.stubGlobal( - 'fetch', - vi.fn(async () => new Response('1,2,3')), - ); + const { bytes, download } = stubDownload(); const blob = await createArtifactServer(mockClient({ listFiles })).readArtifactFile({ id: 'a1', @@ -187,24 +192,22 @@ describe('createArtifactServer', () => { }); expect(listFiles).toHaveBeenCalledWith('a1', { path: 'data/' }); - await expect(blob.text()).resolves.toBe('1,2,3'); + 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] })); - vi.stubGlobal( - 'fetch', - vi.fn(async () => new Response('page')), - ); + 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(fetch).toHaveBeenCalledWith('https://s3.test/index.html'); - await expect(blob.text()).resolves.toBe('page'); + 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 () => {