Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(desktop-app): add GFS file explorer tree to the sidebar

Diego Zacarias0475049d70cc
diff --git a/desktop-app/ui/src/App.tsx b/desktop-app/ui/src/App.tsx
index 6e0509cfb..181cd8e01 100644
--- a/desktop-app/ui/src/App.tsx
+++ b/desktop-app/ui/src/App.tsx
@@ -2436,6 +2436,9 @@ export function App() {
onOpenSandboxUiApp={handleOpenSandboxUiApp}
onSettingsMenuOpenChange={setSidebarSettingsMenuOpen}
onSelect={handleSidebarNavSelect}
+ onOpenFilesSection={vm.openFilesSection}
+ onOpenPreviewSection={vm.openPreviewSection}
+ pushToast={vm.pushToast}
toggleRequestId={sidebarToggleRequestId}
/>
<section className="workspace-layout">
diff --git a/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/__tests__/FileExplorerTree.test.tsx b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/__tests__/FileExplorerTree.test.tsx
new file mode 100644
index 000000000..0cb68ae1d
--- /dev/null
+++ b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/__tests__/FileExplorerTree.test.tsx
@@ -0,0 +1,402 @@
+// @vitest-environment jsdom
+import { useRef, useState } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
+import { activeWorkspaceTab, openFilesTab } from '@lib/workspaceTabs'
+import type { WorkspaceTabsState } from '@lib/workspaceTabs.types'
+import { FileExplorerTree } from '..'
+
+// useGfsBrowserController only reads { isAuthenticated, me, runtimeConfigState }
+// from AuthContext. Mock just those so the tree's controller instance stands up
+// without the full provider tree.
+vi.mock('@contexts/AuthContext', () => ({
+ useAuthContext: () => ({
+ isAuthenticated: true,
+ me: { id: 'user-1', teamId: 'team-1' },
+ runtimeConfigState: { envKey: 'test' },
+ }),
+}))
+
+// T1: the fixtures are typed against the real preload wire contract
+// (window.clerum.gfs.listChildren / listAccessible in desktop-app/src/renderer.d.ts),
+// which is the shape the main-process producer emits. That producer runs in the
+// Electron main process and cannot be called from jsdom, so the fixture mirrors
+// the typed boundary — a drift in the contract breaks this factory at compile.
+type ChildWire = Awaited<ReturnType<typeof window.clerum.gfs.listChildren>>['items'][number]
+
+function node(
+ id: string,
+ name: string,
+ kind: 'file' | 'directory',
+ overrides: Partial<ChildWire> = {}
+): ChildWire {
+ return {
+ resourceId: id,
+ rid: id,
+ gfsUri: `gfs://main/${id}`,
+ drive: 'main',
+ parentResourceId: null,
+ name,
+ kind,
+ path: `/${name}`,
+ version: 1,
+ bytes: 4,
+ ...overrides,
+ }
+}
+
+type Producers = {
+ listAccessible?: (drive?: string, cursor?: string) => Promise<unknown>
+ listChildren?: (resourceId: string, drive?: string, cursor?: string) => Promise<unknown>
+ download?: (uri: string) => Promise<unknown>
+}
+
+function installClerum(producers: Producers) {
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ gfs: {
+ listAccessible:
+ producers.listAccessible ?? vi.fn(async () => ({ items: [], nextCursor: null })),
+ listChildren:
+ producers.listChildren ?? vi.fn(async () => ({ items: [], nextCursor: null })),
+ download: producers.download ?? vi.fn(async () => ({ bytes: new ArrayBuffer(4) })),
+ },
+ },
+ })
+}
+
+function renderTree(props: Partial<Parameters<typeof FileExplorerTree>[0]> = {}) {
+ const onOpenFolder = props.onOpenFolder ?? vi.fn()
+ const onOpenPreview = props.onOpenPreview ?? vi.fn()
+ const pushToast = props.pushToast ?? vi.fn()
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ render(
+ <QueryClientProvider client={queryClient}>
+ <FileExplorerTree
+ onOpenFolder={onOpenFolder}
+ onOpenPreview={onOpenPreview}
+ pushToast={pushToast}
+ />
+ </QueryClientProvider>
+ )
+ return { onOpenFolder, onOpenPreview, pushToast }
+}
+
+beforeEach(() => {
+ // jsdom has no object-URL implementation; the download fallback needs both.
+ Object.defineProperty(URL, 'createObjectURL', {
+ configurable: true,
+ value: vi.fn(() => 'blob:x'),
+ })
+ Object.defineProperty(URL, 'revokeObjectURL', { configurable: true, value: vi.fn() })
+})
+
+afterEach(() => {
+ cleanup()
+ vi.restoreAllMocks()
+})
+
+describe('FileExplorerTree — lazy fetch and expand/collapse', () => {
+ it('does not fetch a folder before it is expanded, then loads and hides its children', async () => {
+ const listChildren = vi.fn(async () => ({
+ items: [node('sub-1', 'Sub', 'directory'), node('r-1', 'r.md', 'file')],
+ nextCursor: null,
+ }))
+ installClerum({
+ listAccessible: vi.fn(async () => ({
+ items: [node('reports', 'Reports', 'directory')],
+ nextCursor: null,
+ })),
+ listChildren,
+ })
+
+ renderTree()
+
+ await screen.findByRole('button', { name: 'Reports' })
+ // Lazy: the root list rendered without any per-node children fetch.
+ expect(listChildren).not.toHaveBeenCalled()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Expand Reports' }))
+
+ expect(await screen.findByRole('button', { name: 'Sub' })).toBeTruthy()
+ expect(screen.getByRole('button', { name: 'r.md' })).toBeTruthy()
+ expect(listChildren).toHaveBeenCalledWith('reports', 'main', undefined)
+
+ // Collapsing hides the children again (a container is collapsible at any level).
+ fireEvent.click(screen.getByRole('button', { name: 'Collapse Reports' }))
+ expect(screen.queryByRole('button', { name: 'Sub' })).toBeNull()
+ })
+})
+
+describe('FileExplorerTree — sort ordering', () => {
+ it('renders folders before files, each group alphabetical', async () => {
+ installClerum({
+ listAccessible: vi.fn(async () => ({
+ items: [
+ node('f-b', 'b.txt', 'file'),
+ node('d-z', 'Zeta', 'directory'),
+ node('d-a', 'Alpha', 'directory'),
+ node('f-a', 'a.txt', 'file'),
+ ],
+ nextCursor: null,
+ })),
+ })
+
+ renderTree()
+
+ const tree = await screen.findByRole('tree', { name: 'Shared files' })
+ const names = within(tree)
+ .getAllByRole('treeitem')
+ .map(item => item.querySelector('.da-file-explorer__name')?.textContent)
+ expect(names).toEqual(['Alpha', 'Zeta', 'a.txt', 'b.txt'])
+ })
+})
+
+describe('FileExplorerTree — single-vs-double click cancels the deferred single', () => {
+ // The real browser fires click → click → dblclick; a single fireEvent.doubleClick
+ // dispatches only dblclick, so it never exercises the setTimeout cancellation.
+ // These drive the full sequence and advance the 250ms window to prove the
+ // deferred single-click action was cancelled by the double-click.
+ it('folder: the double-click opens the tab once and never runs the deferred toggle', async () => {
+ const listChildren = vi.fn(async () => ({
+ items: [node('sub-1', 'Sub', 'directory')],
+ nextCursor: null,
+ }))
+ installClerum({
+ listAccessible: vi.fn(async () => ({
+ items: [node('reports', 'Reports', 'directory')],
+ nextCursor: null,
+ })),
+ listChildren,
+ })
+
+ const { onOpenFolder } = renderTree()
+
+ const folderButton = await screen.findByRole('button', { name: 'Reports' })
+ const treeitem = folderButton.closest('[role="treeitem"]') as HTMLElement
+
+ vi.useFakeTimers()
+ try {
+ fireEvent.click(folderButton)
+ fireEvent.click(folderButton)
+ fireEvent.doubleClick(folderButton)
+ act(() => {
+ vi.advanceTimersByTime(300)
+ })
+ } finally {
+ vi.useRealTimers()
+ }
+
+ expect(onOpenFolder).toHaveBeenCalledTimes(1)
+ expect(onOpenFolder).toHaveBeenCalledWith('gfs://main/reports')
+ // The deferred single-click (toggle) was cancelled: the folder did not
+ // expand and its children were never fetched by the toggle.
+ expect(treeitem.getAttribute('aria-expanded')).toBe('false')
+ expect(listChildren).not.toHaveBeenCalled()
+ })
+
+ it('file: the double-click previews once and the deferred select adds nothing', async () => {
+ installClerum({
+ listAccessible: vi.fn(async () => ({
+ items: [node('img-1', 'photo.png', 'file')],
+ nextCursor: null,
+ })),
+ })
+
+ const { onOpenPreview } = renderTree()
+
+ const fileButton = await screen.findByRole('button', { name: 'photo.png' })
+
+ vi.useFakeTimers()
+ try {
+ fireEvent.click(fileButton)
+ fireEvent.click(fileButton)
+ fireEvent.doubleClick(fileButton)
+ expect(onOpenPreview).toHaveBeenCalledTimes(1)
+ act(() => {
+ vi.advanceTimersByTime(300)
+ })
+ } finally {
+ vi.useRealTimers()
+ }
+
+ // Advancing past the single-click window adds no second activation.
+ expect(onOpenPreview).toHaveBeenCalledTimes(1)
+ })
+})
+
+describe('FileExplorerTree — Enter activates (§3.A.4)', () => {
+ it('folder: Enter opens the files tab and does not expand', async () => {
+ const listChildren = vi.fn(async () => ({ items: [], nextCursor: null }))
+ installClerum({
+ listAccessible: vi.fn(async () => ({
+ items: [node('reports', 'Reports', 'directory')],
+ nextCursor: null,
+ })),
+ listChildren,
+ })
+
+ const { onOpenFolder } = renderTree()
+
+ const folderButton = await screen.findByRole('button', { name: 'Reports' })
+ const treeitem = folderButton.closest('[role="treeitem"]') as HTMLElement
+
+ fireEvent.keyDown(folderButton, { key: 'Enter' })
+
+ expect(onOpenFolder).toHaveBeenCalledTimes(1)
+ expect(onOpenFolder).toHaveBeenCalledWith('gfs://main/reports')
+ expect(treeitem.getAttribute('aria-expanded')).toBe('false')
+ expect(listChildren).not.toHaveBeenCalled()
+ })
+
+ it('file: Enter opens the preview tab', async () => {
+ installClerum({
+ listAccessible: vi.fn(async () => ({
+ items: [node('img-1', 'photo.png', 'file')],
+ nextCursor: null,
+ })),
+ })
+
+ const { onOpenPreview } = renderTree()
+
+ const fileButton = await screen.findByRole('button', { name: 'photo.png' })
+ fireEvent.keyDown(fileButton, { key: 'Enter' })
+
+ expect(onOpenPreview).toHaveBeenCalledTimes(1)
+ expect(onOpenPreview).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: 'image', gfsUri: 'gfs://main/img-1', name: 'photo.png' })
+ )
+ })
+})
+
+describe('FileExplorerTree — single-click never navigates', () => {
+ it('selects a file on single-click without opening a preview tab', async () => {
+ installClerum({
+ listAccessible: vi.fn(async () => ({
+ items: [node('img-1', 'photo.png', 'file')],
+ nextCursor: null,
+ })),
+ })
+
+ const { onOpenPreview } = renderTree()
+
+ const fileButton = await screen.findByRole('button', { name: 'photo.png' })
+ const treeitem = fileButton.closest('[role="treeitem"]') as HTMLElement
+ expect(treeitem.getAttribute('aria-selected')).toBe('false')
+
+ fireEvent.click(fileButton)
+
+ // The deferred single-click resolves to selection only (aria-selected), and
+ // never to a preview tab — even after the single-vs-double window elapses.
+ await waitFor(() => expect(treeitem.getAttribute('aria-selected')).toBe('true'))
+ expect(onOpenPreview).not.toHaveBeenCalled()
+ })
+})
+
+describe('FileExplorerTree — double-click activation', () => {
+ it('opens a preview tab for a previewable file on double-click', async () => {
+ installClerum({
+ listAccessible: vi.fn(async () => ({
+ items: [node('img-1', 'photo.png', 'file')],
+ nextCursor: null,
+ })),
+ })
+ const { onOpenPreview } = renderTree()
+
+ const fileButton = await screen.findByRole('button', { name: 'photo.png' })
+ fireEvent.doubleClick(fileButton)
+
+ expect(onOpenPreview).toHaveBeenCalledTimes(1)
+ expect(onOpenPreview).toHaveBeenCalledWith(
+ expect.objectContaining({ kind: 'image', gfsUri: 'gfs://main/img-1', name: 'photo.png' })
+ )
+ })
+
+ it('downloads a non-previewable file on double-click and toasts success', async () => {
+ const download = vi.fn(async () => ({ bytes: new ArrayBuffer(8) }))
+ installClerum({
+ listAccessible: vi.fn(async () => ({
+ items: [node('zip-1', 'archive.zip', 'file')],
+ nextCursor: null,
+ })),
+ download,
+ })
+
+ const { onOpenPreview, pushToast } = renderTree()
+
+ const fileButton = await screen.findByRole('button', { name: 'archive.zip' })
+ fireEvent.doubleClick(fileButton)
+
+ await waitFor(() => expect(download).toHaveBeenCalledWith('gfs://main/zip-1'))
+ await waitFor(() => expect(pushToast).toHaveBeenCalledWith('Downloaded archive.zip', 'success'))
+ expect(onOpenPreview).not.toHaveBeenCalled()
+ })
+})
+
+describe('FileExplorerTree — folder activation focuses an existing files tab', () => {
+ // Drives the real `openFilesTab` reducer (the tab store producer) so the
+ // observable outcome — tab count and which tab is active — is asserted (T4),
+ // not an intermediate call. Opening a folder that already has a files tab
+ // must focus it; a folder with no tab must create one.
+ function Harness({ initialState }: { initialState: WorkspaceTabsState }) {
+ const [state, setState] = useState(initialState)
+ const counter = useRef(0)
+ return (
+ <>
+ <div data-testid="tab-count">{state.tabs.length}</div>
+ <div data-testid="active-path">{activeWorkspaceTab(state)?.files?.path ?? 'none'}</div>
+ <FileExplorerTree
+ onOpenFolder={uri =>
+ setState(current =>
+ openFilesTab(current, { id: `files-new-${(counter.current += 1)}`, path: uri })
+ )
+ }
+ onOpenPreview={vi.fn()}
+ pushToast={vi.fn()}
+ />
+ </>
+ )
+ }
+
+ it('focuses the existing tab instead of creating another, and creates one when none exists', async () => {
+ installClerum({
+ listAccessible: vi.fn(async () => ({
+ items: [node('reports', 'Reports', 'directory'), node('archive', 'Archive', 'directory')],
+ nextCursor: null,
+ })),
+ })
+
+ const initialState: WorkspaceTabsState = {
+ tabs: [
+ { id: 'chat-1', kind: 'chat', title: 'New chat', chat: { agentRef: null, chatId: null } },
+ { id: 'files-1', kind: 'files', title: 'Reports', files: { path: 'gfs://main/reports' } },
+ ],
+ activeTabId: 'chat-1',
+ }
+ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } })
+ render(
+ <QueryClientProvider client={queryClient}>
+ <Harness initialState={initialState} />
+ </QueryClientProvider>
+ )
+
+ const tree = await screen.findByRole('tree', { name: 'Shared files' })
+
+ // Double-clicking the folder that already has a files tab focuses it: no new
+ // tab, and that tab becomes active.
+ fireEvent.doubleClick(within(tree).getByRole('button', { name: 'Reports' }))
+ await waitFor(() =>
+ expect(screen.getByTestId('active-path').textContent).toBe('gfs://main/reports')
+ )
+ expect(screen.getByTestId('tab-count').textContent).toBe('2')
+
+ // A folder with no existing tab creates one.
+ fireEvent.doubleClick(within(tree).getByRole('button', { name: 'Archive' }))
+ await waitFor(() =>
+ expect(screen.getByTestId('active-path').textContent).toBe('gfs://main/archive')
+ )
+ expect(screen.getByTestId('tab-count').textContent).toBe('3')
+ })
+})
diff --git a/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsx b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsx
new file mode 100644
index 000000000..5e16fb00a
--- /dev/null
+++ b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/index.tsx
@@ -0,0 +1,327 @@
+import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import { useInfiniteQuery } from '@tanstack/react-query'
+import { Button, IconButton, StatusBanner } from '@components/Common'
+import { GfsFileIcon } from '@components/GfsFileIcon'
+import { GFS_DRIVE_MAIN } from '@constants/gfsBrowser'
+import { desktopQueryKeys } from '@hooks/domain/queryKeys'
+import {
+ type GfsBrowserChild,
+ useGfsBrowserController,
+} from '@hooks/domain/useGfsBrowserController'
+import { saveGfsFileToDisk } from '@lib/gfsDownload'
+import { resolveGfsPreview } from '@lib/gfsPreview'
+import { IconChevronRight, IconContexts } from '../icons'
+import type { FileExplorerNodeProps, FileExplorerTreeProps } from './types'
+
+// Single-click must not act before we know a double-click is not coming
+// (spec 18 §3.A.4): a single-click's toggle/select is deferred by this window so
+// a double-click (open tab / preview) can cancel it first.
+const DOUBLE_CLICK_DELAY_MS = 250
+
+function errorMessage(error: unknown): string | null {
+ if (!error) return null
+ return error instanceof Error ? error.message : String(error)
+}
+
+/** Folders first, then files, each alphabetical — the VSCode tree ordering. */
+function sortTreeItems(items: GfsBrowserChild[]): GfsBrowserChild[] {
+ return [...items].sort((left, right) => {
+ if (left.kind !== right.kind) return left.kind === 'directory' ? -1 : 1
+ return left.name.localeCompare(right.name)
+ })
+}
+
+/**
+ * One node of the sidebar file explorer. Extracted from `GfsMoveTreeFolder`
+ * (recursion, expand `Set`, lazy per-node `gfsChildren` fetch, "Load more",
+ * ARIA tree roles) but, unlike the move picker, it lists BOTH folders and files
+ * (spec 18 §3.A.1). A single-click toggles a folder / selects a file; opening a
+ * tab or a preview is reserved for the double-click / Enter gesture (§3.A.4).
+ */
+function FileExplorerNode({
+ node,
+ level,
+ scope,
+ accessActive,
+ expandedIds,
+ selectedId,
+ onToggle,
+ onSelect,
+ onActivateFolder,
+ onActivateFile,
+ onAuthorityFailure,
+}: FileExplorerNodeProps) {
+ const isDirectory = node.kind === 'directory'
+ const isExpanded = isDirectory && expandedIds.has(node.resourceId)
+ const isSelected = selectedId === node.resourceId
+
+ const childQuery = useInfiniteQuery({
+ queryKey: desktopQueryKeys.gfsChildren(scope, node.resourceId, GFS_DRIVE_MAIN),
+ queryFn: ({ pageParam }) =>
+ window.clerum.gfs.listChildren(node.resourceId, GFS_DRIVE_MAIN, pageParam),
+ // Gate on live access as the controller's own children query does: a revoked
+ // session fetches nothing (the subtree also unmounts as accessibleResources
+ // empties, but this keeps the guard robust to future refactors).
+ enabled: isExpanded && accessActive,
+ initialPageParam: undefined as string | undefined,
+ getNextPageParam: lastPage => lastPage.nextCursor ?? undefined,
+ })
+ const childError = errorMessage(childQuery.error)
+ const childItems = useMemo(
+ () => sortTreeItems((childQuery.data?.pages ?? []).flatMap(page => page.items)),
+ [childQuery.data]
+ )
+
+ useEffect(() => {
+ if (childError) onAuthorityFailure(childError)
+ }, [childError, onAuthorityFailure])
+
+ // Deferred single-click: cancelled by a double-click within the window.
+ const clickTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
+ const clearClickTimer = useCallback(() => {
+ if (clickTimerRef.current !== null) {
+ clearTimeout(clickTimerRef.current)
+ clickTimerRef.current = null
+ }
+ }, [])
+ useEffect(() => clearClickTimer, [clearClickTimer])
+
+ const runSingleClick = useCallback(() => {
+ if (isDirectory) onToggle(node.resourceId)
+ else onSelect(node.resourceId)
+ }, [isDirectory, node.resourceId, onSelect, onToggle])
+
+ const runActivate = useCallback(() => {
+ if (isDirectory) onActivateFolder(node)
+ else onActivateFile(node)
+ }, [isDirectory, node, onActivateFile, onActivateFolder])
+
+ const handleRowClick = useCallback(() => {
+ clearClickTimer()
+ clickTimerRef.current = setTimeout(() => {
+ clickTimerRef.current = null
+ runSingleClick()
+ }, DOUBLE_CLICK_DELAY_MS)
+ }, [clearClickTimer, runSingleClick])
+
+ const handleRowDoubleClick = useCallback(() => {
+ clearClickTimer()
+ runActivate()
+ }, [clearClickTimer, runActivate])
+
+ const handleRowKeyDown = useCallback(
+ (event: React.KeyboardEvent<HTMLButtonElement>) => {
+ if (event.key !== 'Enter') return
+ // Stop the native button click Enter would otherwise fire (which would run
+ // the single-click action); Enter activates, matching double-click.
+ event.preventDefault()
+ clearClickTimer()
+ runActivate()
+ },
+ [clearClickTimer, runActivate]
+ )
+
+ const loadingChildren = Boolean(isExpanded && childQuery.isFetching && !childQuery.data)
+ const hasMoreChildren = Boolean(childQuery.hasNextPage)
+
+ return (
+ <div
+ aria-expanded={isDirectory ? isExpanded : undefined}
+ aria-level={level}
+ aria-selected={isSelected}
+ className="da-file-explorer__item"
+ role="treeitem"
+ >
+ <div className="da-file-explorer__row">
+ {isDirectory ? (
+ <IconButton
+ aria-expanded={isExpanded}
+ className={`da-file-explorer__toggle${isExpanded ? ' is-expanded' : ''}`}
+ label={`${isExpanded ? 'Collapse' : 'Expand'} ${node.name}`}
+ onClick={() => onToggle(node.resourceId)}
+ size="sm"
+ variant="ghost"
+ >
+ <IconChevronRight />
+ </IconButton>
+ ) : (
+ <span className="da-file-explorer__toggle-placeholder" aria-hidden="true" />
+ )}
+ <Button
+ align="start"
+ block
+ className={`da-file-explorer__label${isSelected ? ' is-selected' : ''}`}
+ color="neutral"
+ onClick={handleRowClick}
+ onDoubleClick={handleRowDoubleClick}
+ onKeyDown={handleRowKeyDown}
+ variant="text"
+ >
+ <span className="da-file-explorer__icon" aria-hidden="true">
+ {isDirectory ? <IconContexts /> : <GfsFileIcon name={node.name} />}
+ </span>
+ <span className="da-file-explorer__name">{node.name}</span>
+ </Button>
+ </div>
+ {isExpanded ? (
+ <div className="da-file-explorer__group" role="group">
+ {loadingChildren ? (
+ <p className="da-file-explorer__message muted" role="status">
+ Loading…
+ </p>
+ ) : null}
+ {childError ? <StatusBanner tone="error" text={childError} compact /> : null}
+ {childItems.map(child => (
+ <FileExplorerNode
+ accessActive={accessActive}
+ expandedIds={expandedIds}
+ key={child.resourceId}
+ level={level + 1}
+ node={child}
+ onActivateFile={onActivateFile}
+ onActivateFolder={onActivateFolder}
+ onAuthorityFailure={onAuthorityFailure}
+ onSelect={onSelect}
+ onToggle={onToggle}
+ scope={scope}
+ selectedId={selectedId}
+ />
+ ))}
+ {hasMoreChildren ? (
+ <div className="da-file-explorer__more">
+ <Button
+ loading={childQuery.isFetchingNextPage}
+ onClick={() => void childQuery.fetchNextPage()}
+ size="xs"
+ variant="text"
+ >
+ Load more
+ </Button>
+ </div>
+ ) : null}
+ {!loadingChildren && !childError && childItems.length === 0 && !hasMoreChildren ? (
+ <p className="da-file-explorer__message muted">Empty folder.</p>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ )
+}
+
+/**
+ * Sidebar file explorer (spec 18 §3.A). The forest root (level 0) is the
+ * "Shared with me" collection — `accessibleResources`, the same source as the
+ * Files page's root view — not a single filesystem root (§3.A.2); every
+ * container is collapsible at any level. Its own `useGfsBrowserController`
+ * instance shares the Files page's TanStack cache by query key, so folders the
+ * page already warmed render instantly and the discovery authority/fail-closed
+ * boundary is reused.
+ */
+export function FileExplorerTree({
+ onOpenFolder,
+ onOpenPreview,
+ pushToast,
+}: FileExplorerTreeProps) {
+ const ctrl = useGfsBrowserController()
+ const [expandedIds, setExpandedIds] = useState<Set<string>>(() => new Set())
+ const [selectedId, setSelectedId] = useState<string | null>(null)
+
+ const roots = useMemo(() => sortTreeItems(ctrl.accessibleResources), [ctrl.accessibleResources])
+
+ const handleToggle = useCallback((resourceId: string) => {
+ setExpandedIds(previous => {
+ const next = new Set(previous)
+ if (next.has(resourceId)) next.delete(resourceId)
+ else next.add(resourceId)
+ return next
+ })
+ }, [])
+
+ const handleSelect = useCallback((resourceId: string) => {
+ setSelectedId(resourceId)
+ }, [])
+
+ const handleActivateFolder = useCallback(
+ (node: GfsBrowserChild) => {
+ onOpenFolder(node.gfsUri)
+ },
+ [onOpenFolder]
+ )
+
+ const authorityFailure = ctrl.handleAuthorityFailure
+ const handleAuthorityFailure = useCallback(
+ (message: string) => {
+ authorityFailure(message, 'operation')
+ },
+ [authorityFailure]
+ )
+
+ const handleActivateFile = useCallback(
+ (node: GfsBrowserChild) => {
+ setSelectedId(node.resourceId)
+ const preview = resolveGfsPreview(node)
+ if (preview) {
+ onOpenPreview(preview)
+ return
+ }
+ void (async () => {
+ try {
+ await saveGfsFileToDisk(node.gfsUri, node.name)
+ pushToast(`Downloaded ${node.name}`, 'success')
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error)
+ if (authorityFailure(message, 'operation')) return
+ pushToast(message, 'error')
+ }
+ })()
+ },
+ [authorityFailure, onOpenPreview, pushToast]
+ )
+
+ return (
+ <div className="da-file-explorer">
+ {ctrl.accessibleNotice ? (
+ <p className="da-file-explorer__message muted">{ctrl.accessibleNotice}</p>
+ ) : ctrl.accessibleError ? (
+ <StatusBanner tone="error" text={ctrl.accessibleError} compact />
+ ) : ctrl.loadingAccessible && roots.length === 0 ? (
+ <p className="da-file-explorer__message muted" role="status">
+ Loading files…
+ </p>
+ ) : roots.length === 0 && !ctrl.hasMoreAccessible ? (
+ <p className="da-file-explorer__message muted">No shared files yet.</p>
+ ) : (
+ <div className="da-file-explorer__tree" role="tree" aria-label="Shared files">
+ {roots.map(node => (
+ <FileExplorerNode
+ accessActive={ctrl.accessState === 'active'}
+ expandedIds={expandedIds}
+ key={node.resourceId}
+ level={1}
+ node={node}
+ onActivateFile={handleActivateFile}
+ onActivateFolder={handleActivateFolder}
+ onAuthorityFailure={handleAuthorityFailure}
+ onSelect={handleSelect}
+ onToggle={handleToggle}
+ scope={ctrl.sessionScope}
+ selectedId={selectedId}
+ />
+ ))}
+ {ctrl.hasMoreAccessible ? (
+ <div className="da-file-explorer__more">
+ <Button
+ loading={ctrl.isFetchingMoreAccessible}
+ onClick={() => ctrl.loadMoreAccessible()}
+ size="xs"
+ variant="text"
+ >
+ Load more
+ </Button>
+ </div>
+ ) : null}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/types.ts b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/types.ts
new file mode 100644
index 000000000..ca3c28539
--- /dev/null
+++ b/desktop-app/ui/src/components/SidebarNav/FileExplorerTree/types.ts
@@ -0,0 +1,36 @@
+import type { GfsBrowserChild } from '@hooks/domain/useGfsBrowserController'
+import type { GfsPreviewResource } from '@lib/gfsPreview'
+import type { Tone } from '@/uiTypes'
+
+/**
+ * Actions the sidebar file explorer hands back to the app. Folder and file
+ * activation are the DOUBLE-CLICK / Enter gestures (spec 18 §3.A.4); a
+ * single-click only toggles/selects inside the tree and never reaches here.
+ */
+export interface FileExplorerTreeProps {
+ /** Double-click / Enter on a folder → open (or focus) its files tab. */
+ onOpenFolder: (gfsUri: string) => void
+ /** Double-click / Enter on a previewable file → open (or focus) its preview tab. */
+ onOpenPreview: (preview: GfsPreviewResource) => void
+ /** Transient success/error feedback for the download fallback. */
+ pushToast: (message: string, tone: Tone) => void
+}
+
+export interface FileExplorerNodeProps {
+ node: GfsBrowserChild
+ /** 1-based ARIA depth (`aria-level`). */
+ level: number
+ /** Cache-scope key shared with the Files page's TanStack queries. */
+ scope: string
+ /** Session access is live: gates the per-node children fetch the same way the
+ * controller gates its own children query — a revoked session fetches nothing. */
+ accessActive: boolean
+ expandedIds: ReadonlySet<string>
+ selectedId: string | null
+ onToggle: (resourceId: string) => void
+ onSelect: (resourceId: string) => void
+ onActivateFolder: (node: GfsBrowserChild) => void
+ onActivateFile: (node: GfsBrowserChild) => void
+ /** Fail-closed hook: a listing authority error revokes the session. */
+ onAuthorityFailure: (message: string) => void
+}
diff --git a/desktop-app/ui/src/components/SidebarNav/index.tsx b/desktop-app/ui/src/components/SidebarNav/index.tsx
index 51746c61e..473d5cf52 100644
--- a/desktop-app/ui/src/components/SidebarNav/index.tsx
+++ b/desktop-app/ui/src/components/SidebarNav/index.tsx
@@ -11,6 +11,7 @@ import { DESKTOP_ROUTES, SIDEBAR_SESSION_PREVIEW_LIMIT } from '@constants/naviga
import { useClickOutside } from '@hooks/useClickOutside'
import { formatDesktopAppVersionTooltip, useDesktopAppInfo } from '@hooks/useDesktopAppInfo'
import type { NavItem } from '@/uiTypes'
+import { FileExplorerTree } from './FileExplorerTree'
import {
IconAgents,
IconAttachFile,
@@ -43,6 +44,9 @@ export function SidebarNav({
onOpenSandboxUiApp,
onSettingsMenuOpenChange,
onSelect,
+ onOpenFilesSection,
+ onOpenPreviewSection,
+ pushToast,
toggleRequestId = 0,
}: SidebarNavProps) {
const { busy, me, handleLogout: onLogout } = useAuthContext()
@@ -57,6 +61,9 @@ export function SidebarNav({
const [mobileMenuOpen, setMobileMenuOpen] = useState(false)
const [chatSessionsOpen, setChatSessionsOpen] = useState(true)
const [appsOpen, setAppsOpen] = useState(true)
+ // Collapsed by default: opening it triggers the "Shared with me" discovery
+ // fetch, so it stays inert until the user reaches for the file tree.
+ const [filesExplorerOpen, setFilesExplorerOpen] = useState(false)
const [sessionMenuId, setSessionMenuId] = useState<string | null>(null)
const [renamingSessionId, setRenamingSessionId] = useState<string | null>(null)
const [sessionRenameValue, setSessionRenameValue] = useState('')
@@ -546,7 +553,9 @@ export function SidebarNav({
))}
<div
- className={`nav-link${navItem === DESKTOP_ROUTES.files ? ' active' : ''}`}
+ className={`nav-link nav-link--with-toggle${
+ navItem === DESKTOP_ROUTES.files ? ' active' : ''
+ }`}
title={collapsed ? 'Files' : undefined}
data-tooltip="Files"
>
@@ -564,7 +573,30 @@ export function SidebarNav({
>
Files
</NavItemControl>
+ <IconButton
+ className="nav-link-session-toggle"
+ label={filesExplorerOpen ? 'Collapse file explorer' : 'Expand file explorer'}
+ aria-expanded={filesExplorerOpen}
+ data-testid="nav-files-explorer-toggle"
+ onClick={event => {
+ event.stopPropagation()
+ setFilesExplorerOpen(open => !open)
+ }}
+ variant="ghost"
+ >
+ <IconChevronRight className={filesExplorerOpen ? 'expanded' : ''} />
+ </IconButton>
</div>
+
+ {!collapsed && filesExplorerOpen && (
+ <div className="nav-file-explorer">
+ <FileExplorerTree
+ onOpenFolder={onOpenFilesSection}
+ onOpenPreview={onOpenPreviewSection}
+ pushToast={pushToast}
+ />
+ </div>
+ )}
</nav>
<div className="sidebar-footer">
diff --git a/desktop-app/ui/src/components/SidebarNav/types.ts b/desktop-app/ui/src/components/SidebarNav/types.ts
index 36fe2840f..c9fa4f2cf 100644
--- a/desktop-app/ui/src/components/SidebarNav/types.ts
+++ b/desktop-app/ui/src/components/SidebarNav/types.ts
@@ -1,4 +1,5 @@
-import type { ActiveSandboxUiApp, NavItem } from '@/uiTypes'
+import type { GfsPreviewResource } from '@lib/gfsPreview'
+import type { ActiveSandboxUiApp, NavItem, Tone } from '@/uiTypes'
export type SidebarNavProps = {
navItem: NavItem
@@ -10,5 +11,13 @@ export type SidebarNavProps = {
onOpenSandboxUiApp: (app: ActiveSandboxUiApp) => void
onSettingsMenuOpenChange?: (open: boolean) => void
onSelect: (item: NavItem) => void
+ /** Open (or focus) a files tab at a folder's gfsUri — the file explorer's
+ * double-click-on-folder action (spec 18 §3.A.4). */
+ onOpenFilesSection: (gfsUri: string) => void
+ /** Open (or focus) a preview tab — the file explorer's double-click on a
+ * previewable file (spec 18 §3.A.4). */
+ onOpenPreviewSection: (preview: GfsPreviewResource) => void
+ /** Transient feedback for the file explorer's download fallback. */
+ pushToast: (message: string, tone: Tone) => void
toggleRequestId?: number
}
diff --git a/desktop-app/ui/src/components/__tests__/SidebarNav.test.tsx b/desktop-app/ui/src/components/__tests__/SidebarNav.test.tsx
index 39c95c776..45baa91eb 100644
--- a/desktop-app/ui/src/components/__tests__/SidebarNav.test.tsx
+++ b/desktop-app/ui/src/components/__tests__/SidebarNav.test.tsx
@@ -45,6 +45,9 @@ function baseProps(overrides: Partial<SidebarNavProps> = {}): SidebarNavProps {
onNewChat: vi.fn(),
onOpenSandboxUiApp: vi.fn(),
onSelect: vi.fn(),
+ onOpenFilesSection: vi.fn(),
+ onOpenPreviewSection: vi.fn(),
+ pushToast: vi.fn(),
...overrides,
}
}
diff --git a/desktop-app/ui/src/lib/gfsDownload.ts b/desktop-app/ui/src/lib/gfsDownload.ts
new file mode 100644
index 000000000..aa13a36aa
--- /dev/null
+++ b/desktop-app/ui/src/lib/gfsDownload.ts
@@ -0,0 +1,17 @@
+/**
+ * Save a GFS resource to disk: download its bytes and trigger a browser save.
+ * The single place that performs the save-to-disk, shared by the Files page and
+ * the sidebar file explorer (spec 18 §3.A.4) so the "download a non-previewable
+ * file" path is not duplicated — the preview-vs-download DECISION stays in
+ * `gfsPreview`. Throws on a download failure so each caller keeps its own
+ * fail-closed (authority) and toast handling.
+ */
+export async function saveGfsFileToDisk(uri: string, name: string): Promise<void> {
+ const { bytes } = await window.clerum.gfs.download(uri)
+ const url = URL.createObjectURL(new Blob([bytes]))
+ const anchor = document.createElement('a')
+ anchor.href = url
+ anchor.download = name
+ anchor.click()
+ setTimeout(() => URL.revokeObjectURL(url), 10_000)
+}
diff --git a/desktop-app/ui/src/pages/FilesPage.tsx b/desktop-app/ui/src/pages/FilesPage.tsx
index f9baab1b5..d77b32e96 100644
--- a/desktop-app/ui/src/pages/FilesPage.tsx
+++ b/desktop-app/ui/src/pages/FilesPage.tsx
@@ -34,6 +34,7 @@ import {
import { desktopQueryKeys } from '@hooks/domain/queryKeys'
import { type GfsCrumb, useGfsBrowserController } from '@hooks/domain/useGfsBrowserController'
import { isEventFromNestedInteractive } from '@lib/clickableRowProps'
+import { saveGfsFileToDisk } from '@lib/gfsDownload'
import { assertGfsFileUploadSize } from '@lib/gfsFileUpload'
import { describeGfsGrantError } from '@lib/gfsGrantErrors'
import { isGfsPreviewFile, resolveGfsPreview } from '@lib/gfsPreview'
@@ -510,13 +511,7 @@ export function FilesPage({
const handleDownload = async (uri: string, name: string) => {
try {
- const { bytes } = await window.clerum.gfs.download(uri)
- const url = URL.createObjectURL(new Blob([bytes]))
- const anchor = document.createElement('a')
- anchor.href = url
- anchor.download = name
- anchor.click()
- setTimeout(() => URL.revokeObjectURL(url), 10_000)
+ await saveGfsFileToDisk(uri, name)
pushToast?.(`Downloaded ${name}`, 'success')
} catch (downloadError) {
if (failClosedOnAuthorizationError(downloadError)) return
diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.css
index 7e6bff0da..2699fb6c1 100644
--- a/desktop-app/ui/src/styles.css
+++ b/desktop-app/ui/src/styles.css
@@ -1799,6 +1799,137 @@ h3 {
line-height: var(--line-height-tight);
}
+/* Sidebar file explorer (spec 18 §3.A) — the accordion panel under "Files". */
+.nav-file-explorer {
+ min-width: 0;
+ margin: 0 0 var(--space-1) 0;
+ padding-left: var(--sidebar-nav-label-indent);
+}
+
+.da-file-explorer {
+ min-width: 0;
+ max-height: min(320px, 42vh);
+ overflow-y: auto;
+ scrollbar-width: thin;
+}
+
+.da-file-explorer__message {
+ padding: var(--space-1) var(--space-1);
+ color: var(--text-dim);
+ font-size: var(--font-size-xs);
+}
+
+.da-file-explorer__tree,
+.da-file-explorer__group {
+ display: grid;
+ align-content: start;
+ gap: 0;
+ min-width: 0;
+}
+
+.da-file-explorer__group {
+ margin-left: var(--space-2);
+ padding-left: var(--space-1);
+ border-left: 1px solid rgba(var(--edge-rgb), 0.24);
+}
+
+.da-file-explorer__item {
+ min-width: 0;
+}
+
+.da-file-explorer__row {
+ min-width: 0;
+ display: grid;
+ grid-template-columns: 22px minmax(0, 1fr);
+ align-items: center;
+ gap: var(--space-0-5);
+}
+
+.da-file-explorer__toggle.ui-icon-button {
+ width: 22px;
+ min-width: 22px;
+ height: 26px;
+ min-height: 26px;
+ padding: 0;
+ border-color: transparent;
+ background: transparent;
+ color: var(--text-dim);
+}
+
+.da-file-explorer__toggle.ui-icon-button:hover:enabled,
+.da-file-explorer__toggle.ui-icon-button:focus-visible {
+ border-color: rgba(var(--accent-rgb), 0.28);
+ background: rgba(var(--accent-rgb), 0.1);
+ color: var(--accent-strong);
+}
+
+.da-file-explorer__toggle svg {
+ width: 14px;
+ height: 14px;
+ transition: transform var(--motion-fast);
+}
+
+.da-file-explorer__toggle.is-expanded svg {
+ transform: rotate(90deg);
+}
+
+.da-file-explorer__toggle-placeholder {
+ width: 22px;
+ height: 26px;
+}
+
+.da-file-explorer__label.ui-button {
+ min-width: 0;
+ min-height: 26px;
+ display: flex;
+ align-items: center;
+ gap: var(--space-1);
+ padding: var(--space-0-5) var(--space-1);
+ border: 1px solid transparent;
+ border-radius: var(--radius-sm);
+ background: transparent;
+ color: var(--text-muted);
+ text-align: left;
+}
+
+.da-file-explorer__label.ui-button:hover:enabled,
+.da-file-explorer__label.ui-button:focus-visible {
+ border-color: rgba(var(--accent-rgb), 0.38);
+ background: var(--list-item-hover-bg);
+ box-shadow: none;
+ color: var(--text);
+}
+
+.da-file-explorer__label.is-selected {
+ background: rgba(var(--accent-rgb), 0.12);
+ color: var(--text);
+}
+
+.da-file-explorer__icon {
+ display: inline-flex;
+ flex: 0 0 auto;
+ color: var(--text-dim);
+}
+
+.da-file-explorer__icon svg {
+ width: 15px;
+ height: 15px;
+}
+
+.da-file-explorer__name {
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: var(--font-size-sm);
+ font-weight: var(--font-weight-medium);
+ line-height: var(--line-height-tight);
+}
+
+.da-file-explorer__more {
+ padding: var(--space-0-5) var(--space-1);
+}
+
.nav-latest-sessions {
display: grid;
gap: 0;