The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(webapp): preview file: paths and text files from the session's sandbox
unsupportedpastelsd545462af62c
diff --git a/apps/desktop/src/app/chat/right-rail/preview-file.tsx b/apps/desktop/src/app/chat/right-rail/preview-file.tsxindex fa822fe19fe..a8299ef0e18 100644--- a/apps/desktop/src/app/chat/right-rail/preview-file.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-file.tsx@@ -282,9 +282,9 @@ function dataUrlToBlob(dataUrl: string) {return new Blob([bytes], { type: 'application/pdf' })}-async function readTextPreview(filePath: string) {+async function readTextPreview(filePath: string, sessionId?: string) {try {- return await readDesktopFileText(filePath)+ return await readDesktopFileText(filePath, { sessionId })} catch (error) {const message = error instanceof Error ? error.message : String(error)@@ -744,6 +744,7 @@ export function LocalFilePreview({onClose,onSelectRendered,reloadKey,+ sessionId,target}: {/** Closes the preview's tab; offered when the file can't be shown. */@@ -752,6 +753,8 @@ export function LocalFilePreview({* `rendered` mode to the switcher and routes its selection to the pane. */onSelectRendered?: () => voidreloadKey: number+ /** The session whose tab this is: a gateway read and Save resolve `/workspace` in its sandbox. */+ sessionId?: stringtarget: PreviewTarget}) {const { t } = useI18n()@@ -828,7 +831,7 @@ export function LocalFilePreview({if (isImage || isPdf) {// Prefer bytes the caller already handed us (a pasted/dropped// screenshot) over re-reading a path that may be transient/unreadable.- const dataUrl = target.dataUrl || (await readDesktopFileDataUrl(filePath))+ const dataUrl = target.dataUrl || (await readDesktopFileDataUrl(filePath, { sessionId }))if (active) {setState({ dataUrl, loading: false })@@ -837,7 +840,7 @@ export function LocalFilePreview({return}- const result = await readTextPreview(filePath)+ const result = await readTextPreview(filePath, sessionId)if (active) {const shouldBlock = !forcePreview && (result.binary || (result.byteSize ?? 0) > TEXT_PREVIEW_MAX_BYTES)@@ -902,6 +905,7 @@ export function LocalFilePreview({isText,reloadKey,selfReload,+ sessionId,target.dataUrl,target.language,target.url@@ -1050,7 +1054,7 @@ export function LocalFilePreview({// choice. `force` is the user picking "overwrite" from that banner.if (!force) {try {- const current = await readTextPreview(filePath)+ const current = await readTextPreview(filePath, sessionId)if (!current.binary && (current.text ?? '') !== baselineRef.current) {setConflict(true)diff --git a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx b/apps/desktop/src/app/chat/right-rail/preview-pane.tsxindex ba6041c814c..87df2bed0b4 100644--- a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-pane.tsx@@ -154,6 +154,8 @@ interface PreviewPaneProps {onClose?: () => voidonRestartServer?: (url: string, context?: string) => Promise<string>reloadRequest?: number+ /** The session that owns the tab; a file it names resolves in that session's workspace. */+ sessionId?: string/** The preview tab this pane renders. Keys the per-tab console store the* browser bar's console toggle and the console panel both read. */tabId?: string@@ -273,6 +275,7 @@ export function PreviewPane({onClose,onRestartServer,reloadRequest = 0,+ sessionId,tabId,target}: PreviewPaneProps) {@@ -1546,6 +1549,7 @@ export function PreviewPane({onClose={onClose}onSelectRendered={canRenderHtmlFile ? () => selectRenderMode('preview') : undefined}reloadKey={localReloadKey}+ sessionId={sessionId}target={target}/>))}diff --git a/apps/desktop/src/app/chat/right-rail/preview.tsx b/apps/desktop/src/app/chat/right-rail/preview.tsxindex 545de50cddc..350e396a603 100644--- a/apps/desktop/src/app/chat/right-rail/preview.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview.tsx@@ -39,7 +39,8 @@ export function PreviewTilePane({ onClose, tabId }: PreviewTilePaneProps) {}}, [previewTabs, tabId])- const target = previewTabs.find(tab => tab.id === tabId)?.target+ const tab = previewTabs.find(candidate => candidate.id === tabId)+ const target = tab?.target// The tab closed while this pane was still mounted (the mirror disposes it a// tick later).@@ -53,6 +54,7 @@ export function PreviewTilePane({ onClose, tabId }: PreviewTilePaneProps) {onClose={onClose}onRestartServer={target.kind === 'url' ? (restartPreviewServer ?? undefined) : undefined}reloadRequest={previewReloadRequest}+ sessionId={tab?.sessionId}tabId={tabId}target={target}/>diff --git a/apps/desktop/src/components/chat/preview-attachment.tsx b/apps/desktop/src/components/chat/preview-attachment.tsxindex 42a6cb01057..f8b86125192 100644--- a/apps/desktop/src/components/chat/preview-attachment.tsx+++ b/apps/desktop/src/components/chat/preview-attachment.tsx@@ -161,7 +161,7 @@ export function PreviewAttachment({ target }: { target: string }) {setOpening(true)try {- const preview = await normalizeOrLocalPreviewTarget(requestTarget, requestCwd || undefined)+ const preview = await normalizeOrLocalPreviewTarget(requestTarget, requestCwd || undefined, { sessionId })if (!mountedRef.current ||diff --git a/apps/desktop/src/lib/browser-session-workspace-files.test.tsx b/apps/desktop/src/lib/browser-session-workspace-files.test.tsxindex 2ba2b2cf726..028b2ac7a28 100644--- a/apps/desktop/src/lib/browser-session-workspace-files.test.tsx+++ b/apps/desktop/src/lib/browser-session-workspace-files.test.tsx@@ -1,17 +1,23 @@import { LOCAL_CONNECTION_ID } from '@hermes/shared'-import { cleanup, render, waitFor } from '@testing-library/react'+import { act, cleanup, render, waitFor } from '@testing-library/react'import { atom } from 'nanostores'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { setApiRequestConnection, setApiRequestProfile } from '@/api/client'+import { PreviewTilePane } from '@/app/chat/right-rail/preview'import { SessionViewProvider } from '@/app/chat/session-view'import { MarkdownImage } from '@/components/assistant-ui/markdown-text'+import { $previewTabs } from '@/store/preview'import { $connection } from '@/store/session'import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'import { installBrowserDesktopBridge } from './browser-desktop-bridge'+import { readDesktopFileText } from './desktop-fs'import { resolveMediaPlaybackSrc } from './media'+// The pane's consent dialog needs a QueryClientProvider; these tests read files, not consent.+vi.mock('@/app/chat/right-rail/real-profile-consent-dialog', () => ({ RealProfileConsentDialog: () => null }))+// WA-5: a Docker agent's /workspace is its own session's sandbox, so a Webapp file request names// the session it belongs to. The gateway half is tests/hermes_cli/test_web_server_fs_session_workspace.py.const OWNER = { connectionId: LOCAL_CONNECTION_ID, profile: 'default' }@@ -44,6 +50,7 @@ beforeEach(() => {afterEach(() => {cleanup()+ $previewTabs.set([])clearWebappSession()Reflect.deleteProperty(win, 'hermesDesktop')document.documentElement.removeAttribute('data-hermes-desktop-host')@@ -88,3 +95,56 @@ describe('media in a session sandbox', () => {expect(requests[0].body).toMatchObject({ path: CLIP, route: 'stream', session_id: 'stored-1' })})})++const NOTE = '/workspace/note.txt'++const readsOf = (route: string) => requests.filter(request => request.url.pathname === route)++describe('text previews in a session sandbox', () => {+ it('reads a preview for the session it belongs to', async () => {+ await readDesktopFileText(NOTE, { sessionId: 'sess-1' })+ await readDesktopFileText(NOTE)++ const [scoped, bare] = readsOf('/api/fs/read-text')++ expect(scoped.url.searchParams.get('path')).toBe(NOTE)+ expect(scoped.url.searchParams.getAll('session_id')).toEqual(['sess-1'])+ expect(bare.url.searchParams.get('path')).toBe(NOTE)+ expect(bare.url.searchParams.has('session_id')).toBe(false)+ })++ it('previews a tab from the session that owns it', async () => {+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) =>+ window.setTimeout(() => callback(Date.now()), 0)+ )+ vi.stubGlobal('cancelAnimationFrame', (id: number) => window.clearTimeout(id))+ $previewTabs.set([+ {+ id: 'file:note',+ sessionId: 'stored-1',+ target: { kind: 'file', label: 'note.txt', path: NOTE, previewKind: 'text', source: NOTE, url: `file://${NOTE}` }+ }+ ])++ await act(async () => {+ render(<PreviewTilePane tabId="file:note" />)+ })++ await waitFor(() => expect(readsOf('/api/fs/read-text')).not.toHaveLength(0))+ expect(readsOf('/api/fs/read-text')[0].url.searchParams.get('session_id')).toBe('stored-1')+ })+})++describe('native Desktop reads', () => {+ it('keeps a local read to its path', async () => {+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ const readFileText = vi.fn(async () => ({ path: NOTE, text: 'local' }))+ Object.defineProperty(win, 'hermesDesktop', { configurable: true, value: { readFileText } })+ $connection.set({ mode: 'local' } as never)++ await readDesktopFileText(NOTE, { sessionId: 'sess-1' })++ expect(readFileText).toHaveBeenCalledWith(NOTE)+ expect(requests).toEqual([])+ })+})diff --git a/apps/desktop/src/lib/desktop-fs.ts b/apps/desktop/src/lib/desktop-fs.tsindex fc53855f974..82950f1965b 100644--- a/apps/desktop/src/lib/desktop-fs.ts+++ b/apps/desktop/src/lib/desktop-fs.ts@@ -54,8 +54,16 @@ export function desktopFsProfile(): string | undefined {return $connection.get()?.profile || undefined}-function fsPath(endpoint: string, filePath: string) {- return `/api/fs/${endpoint}?path=${encodeURIComponent(filePath)}`+/** The chat a gateway file belongs to. A Docker agent's `/workspace` is that session's own+ * sandbox, so a gateway read names it; a local (native) read has no use for it. */+export interface DesktopFsSessionScope {+ sessionId?: null | string+}++function fsPath(endpoint: string, filePath: string, scope?: DesktopFsSessionScope) {+ const session = scope?.sessionId ? `&session_id=${encodeURIComponent(scope.sessionId)}` : ''++ return `/api/fs/${endpoint}?path=${encodeURIComponent(filePath)}${session}`}function bridge() {@@ -110,7 +118,10 @@ export async function readDesktopDir(path: string): Promise<HermesReadDirResult>return remoteFsApi<HermesReadDirResult>(fsPath('list', path))}-export async function readDesktopFileText(path: string): Promise<HermesReadFileTextResult> {+export async function readDesktopFileText(+ path: string,+ scope?: DesktopFsSessionScope+): Promise<HermesReadFileTextResult> {if (!isDesktopFsRemoteMode()) {const result = await bridge().readFileText(path)@@ -121,7 +132,7 @@ export async function readDesktopFileText(path: string): Promise<HermesReadFileTreturn result}- return remoteFsApi<HermesReadFileTextResult>(fsPath('read-text', path))+ return remoteFsApi<HermesReadFileTextResult>(fsPath('read-text', path, scope))}// Save UTF-8 text back to a file. Local writes go through the hardened Electron@@ -152,7 +163,7 @@ export async function createRemoteDir(path: string): Promise<string> {return result.path || path}-export async function readDesktopFileDataUrl(path: string): Promise<string> {+export async function readDesktopFileDataUrl(path: string, scope?: DesktopFsSessionScope): Promise<string> {if (!isDesktopFsRemoteMode()) {const result = await bridge().readFileDataUrl(path)@@ -163,7 +174,7 @@ export async function readDesktopFileDataUrl(path: string): Promise<string> {return result}- const result = await remoteFsApi<string | { dataUrl?: string }>(fsPath('read-data-url', path))+ const result = await remoteFsApi<string | { dataUrl?: string }>(fsPath('read-data-url', path, scope))return typeof result === 'string' ? result : result.dataUrl || ''}diff --git a/apps/desktop/src/lib/local-preview.test.ts b/apps/desktop/src/lib/local-preview.test.tsindex d57719fe76d..8103930c3e8 100644--- a/apps/desktop/src/lib/local-preview.test.ts+++ b/apps/desktop/src/lib/local-preview.test.ts@@ -62,7 +62,8 @@ describe('remote HTML previews', () => {...remoteTarget,dataUrl})- expect(readDesktopFileDataUrl).toHaveBeenCalledWith('/srv/report.html')+ // No session scope: the read names none.+ expect(readDesktopFileDataUrl).toHaveBeenCalledWith('/srv/report.html', undefined)})it('falls back to source mode when the transport is not canonical HTML', async () => {diff --git a/apps/desktop/src/lib/local-preview.ts b/apps/desktop/src/lib/local-preview.tsindex 076426b9c6d..23108708540 100644--- a/apps/desktop/src/lib/local-preview.ts+++ b/apps/desktop/src/lib/local-preview.ts@@ -1,7 +1,12 @@import { fileUrlToNativePath } from '@hermes/shared'import DOMPurify from 'dompurify'-import { isDesktopFsRemoteMode, readDesktopFileDataUrl, readDesktopFileText } from '@/lib/desktop-fs'+import {+ type DesktopFsSessionScope,+ isDesktopFsRemoteMode,+ readDesktopFileDataUrl,+ readDesktopFileText+} from '@/lib/desktop-fs'import { isWindowsAbsolutePath } from '@/lib/path-compare'import type { PreviewTarget } from '@/store/preview'@@ -267,7 +272,7 @@ export function localPreviewTarget(rawTarget: string, cwd?: string | null): Prev}}-async function enrichPreviewTarget(target: PreviewTarget | null): Promise<PreviewTarget | null> {+async function enrichPreviewTarget(target: PreviewTarget | null, scope?: DesktopFsSessionScope): Promise<PreviewTarget | null> {if (!isDesktopFsRemoteMode() ||!target ||@@ -280,7 +285,7 @@ async function enrichPreviewTarget(target: PreviewTarget | null): Promise<Previeif (target.previewKind === 'html') {try {- const dataUrl = validatedRemoteHtmlDataUrl(await readDesktopFileDataUrl(target.path || target.source))+ const dataUrl = validatedRemoteHtmlDataUrl(await readDesktopFileDataUrl(target.path || target.source, scope))return dataUrl ? { ...target, dataUrl } : { ...target, renderMode: 'source', transient: true }} catch {@@ -289,7 +294,7 @@ async function enrichPreviewTarget(target: PreviewTarget | null): Promise<Previe}try {- const result = await readDesktopFileText(target.path || target.source)+ const result = await readDesktopFileText(target.path || target.source, scope)return {...target,@@ -306,7 +311,8 @@ async function enrichPreviewTarget(target: PreviewTarget | null): Promise<Previeexport async function normalizeOrLocalPreviewTarget(rawTarget: string,- cwd?: string | null+ cwd?: string | null,+ scope?: DesktopFsSessionScope): Promise<PreviewTarget | null> {try {const normalized = await window.hermesDesktop?.normalizePreviewTarget?.(rawTarget, cwd || undefined)@@ -319,10 +325,10 @@ export async function normalizeOrLocalPreviewTarget(// machine, so remote mode keeps the fabricated fallback the gateway// read resolves later.if (normalized.previewKind === 'directory' || normalized.previewKind === 'missing') {- return isDesktopFsRemoteMode() ? enrichPreviewTarget(localPreviewTarget(rawTarget, cwd)) : null+ return isDesktopFsRemoteMode() ? enrichPreviewTarget(localPreviewTarget(rawTarget, cwd), scope) : null}- return enrichPreviewTarget(normalized)+ return enrichPreviewTarget(normalized, scope)}// The main process resolved the target against the real filesystem and@@ -339,5 +345,5 @@ export async function normalizeOrLocalPreviewTarget(// through to renderer-side local classification so text/images still open.}- return enrichPreviewTarget(localPreviewTarget(rawTarget, cwd))+ return enrichPreviewTarget(localPreviewTarget(rawTarget, cwd), scope)}diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.pyindex c669a861075..44369e385a8 100644--- a/hermes_cli/web_routers/files.py+++ b/hermes_cli/web_routers/files.py@@ -993,7 +993,9 @@ async def fs_list(path: str, request: Request, profile: Optional[str] = None):@router.get("/api/fs/read-text")-async def fs_read_text(path: str, request: Request = None, profile: Optional[str] = None):+async def fs_read_text(+ path: str, request: Request = None, profile: Optional[str] = None, session_id: Optional[str] = None,+):# A staged paste or pick previews from this host, as read-data-url reads it back to send.backend = await asyncio.to_thread(_remote_fs_backend, path, profile)if backend is not None:@@ -1017,7 +1019,8 @@ async def fs_read_text(path: str, request: Request = None, profile: Optional[str"truncated": size > _FS_TEXT_PREVIEW_MAX_BYTES,}profile_home = _fs_profile_home(profile)- target = _agent_fs_path(path, profile_home=profile_home)+ # A session's /workspace is its own sandbox, resolved as download resolves it.+ target = await _fs_download_path(path, profile, session_id)# The same staged-file exception read-data-url makes under a locked files root.if not await asyncio.to_thread(_is_host_file, str(target), profile):_hosted_fs_read_guard(target, request)diff --git a/hermes_cli/web_server_files.py b/hermes_cli/web_server_files.pyindex 5b17e5afea0..d4c2b3a4e98 100644--- a/hermes_cli/web_server_files.py+++ b/hermes_cli/web_server_files.py@@ -244,7 +244,9 @@ def _agent_fs_path(host = _fs_path(raw_path, cwd=cwd)if os.access(host, os.R_OK):return host- translated = _agent_container_path(raw, profile_home=profile_home, workspace_key=workspace_key)+ translated = _agent_container_path(+ _file_url_container_text(raw), profile_home=profile_home, workspace_key=workspace_key,+ )return translated if translated is not None else hosttranslated = _agent_container_path(raw, profile_home=profile_home, workspace_key=workspace_key)if translated is not None:@@ -254,6 +256,18 @@ def _agent_fs_path(return _fs_path(raw_path, cwd=cwd)+def _file_url_container_text(raw: str) -> str:+ """The path a POSIX gateway's ``file:`` URL names (``file:///workspace/x`` -> ``/workspace/x``),+ so a container path spelled as a URL translates like the bare path. Any other text, and every+ URL on a Windows gateway, is returned unchanged; ``_fs_path`` already refused a bad URL."""+ if os.name == "nt" or not raw.lower().startswith("file:"):+ return raw+ try:+ return _file_url_path(raw)+ except ValueError:+ return raw++def _is_unmapped_container_path(raw: str, *, profile_home: Path | None = None) -> bool:"""A docker-backend container path (``/workspace``, ``/root`` or a configuredvolume target) rather than a host path or a typo elsewhere on the host. Readsdiff --git a/tests/hermes_cli/test_web_server_fs_session_workspace.py b/tests/hermes_cli/test_web_server_fs_session_workspace.pyindex 44a2de00a36..2b4912511c0 100644--- a/tests/hermes_cli/test_web_server_fs_session_workspace.py+++ b/tests/hermes_cli/test_web_server_fs_session_workspace.py@@ -127,3 +127,57 @@ def test_stream_refuses_a_clip_outside_the_sessions_workspace(client, sandboxes,assert response.status_code in (400, 403, 404), response.status_codeassert b"outside-clip" not in response.content+++# Part 2: file: paths and text previews++[email protected]("path", ["/workspace/note.txt", "file:///workspace/note.txt"])+def test_read_text_previews_the_sessions_own_workspace_file(client, sandboxes, path):+ def read(**params):+ return client.get("/api/fs/read-text", params={"path": path, **params})++ own = read(session_id="sess-ws")+ other = read(session_id="sess-other")+ bare = read()++ assert own.status_code == 200, own.text+ assert own.json()["text"] == "session note"+ assert own.json()["path"] == str(sandboxes["own"] / "note.txt")+ assert other.json()["text"] == "foreign note"+ # No session keeps the shared profile sandbox, the same answer for both spellings.+ assert (bare.status_code, bare.json()["text"]) == (200, "shared note")+++def test_a_file_url_clip_streams_from_the_sessions_sandbox(client, sandboxes, monkeypatch):+ query = {"path": "file:///workspace/clip.mp4", "session_id": "sess-ws"}++ direct = client.get("/api/files/stream", params=query)+ monkeypatch.setattr(web_server.app.state, "ui_surface", "webapp", raising=False)+ minted = client.post("/api/files/ticket", json={"route": "stream", **query})+ assert minted.status_code == 200, minted.text+ del client.headers[web_server._SESSION_HEADER_NAME]+ ticketed = client.get("/api/files/stream", params={**query, "ticket": minted.json()["ticket"]})++ assert (direct.status_code, direct.content) == (200, b"session-clip")+ assert (ticketed.status_code, ticketed.content) == (200, b"session-clip")++[email protected]("session_id", ["sess-work", "missing-session", " "])+def test_read_text_refuses_a_session_this_profile_does_not_own(client, sandboxes, session_id):+ for path in ("/workspace/note.txt", "file:///workspace/note.txt"):+ response = client.get("/api/fs/read-text", params={"path": path, "session_id": session_id})+ assert response.status_code == 404, (path, response.text)++[email protected]("path", [+ "/workspace/escape.txt",+ "file:///workspace/escape.txt",+ "/workspace/../outside/secret.txt",+ "file:///workspace/sub/../escape.txt",+])+def test_read_text_refuses_a_file_outside_the_sessions_workspace(client, sandboxes, path):+ response = client.get("/api/fs/read-text", params={"path": path, "session_id": "sess-ws"})++ assert response.status_code in (400, 403, 404), response.text+ assert "outside note" not in response.text