Skip to content

The agent that grows with you

fix(webapp): save a Docker session's file where its preview read it

unsupportedpastelsf6321d12da95
diff --git a/apps/desktop/src/app/chat/right-rail/preview-file.tsx b/apps/desktop/src/app/chat/right-rail/preview-file.tsx
index a8299ef0e18..f7395c13bce 100644
--- a/apps/desktop/src/app/chat/right-rail/preview-file.tsx
+++ b/apps/desktop/src/app/chat/right-rail/preview-file.tsx
@@ -1070,7 +1070,7 @@ export function LocalFilePreview({
// Also guards Overwrite: bypassing a content conflict never authorizes
// writing the same path on another connection/profile or this device.
requireEditorOwner()
- await writeDesktopFileText(filePath, draftRef.current)
+ await writeDesktopFileText(filePath, draftRef.current, { sessionId })
baselineRef.current = draftRef.current
setDirty(false)
setConflict(false)
diff --git a/apps/desktop/src/lib/browser-session-workspace-files.test.tsx b/apps/desktop/src/lib/browser-session-workspace-files.test.tsx
index 028b2ac7a28..783a1a297f4 100644
--- a/apps/desktop/src/lib/browser-session-workspace-files.test.tsx
+++ b/apps/desktop/src/lib/browser-session-workspace-files.test.tsx
@@ -1,10 +1,12 @@
+import { EditorView } from '@codemirror/view'
import { LOCAL_CONNECTION_ID } from '@hermes/shared'
-import { act, cleanup, render, waitFor } from '@testing-library/react'
+import { act, cleanup, fireEvent, render, screen, 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 { LocalFilePreview } from '@/app/chat/right-rail/preview-file'
import { SessionViewProvider } from '@/app/chat/session-view'
import { MarkdownImage } from '@/components/assistant-ui/markdown-text'
import { $previewTabs } from '@/store/preview'
@@ -12,11 +14,14 @@ import { $connection } from '@/store/session'
import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'
import { installBrowserDesktopBridge } from './browser-desktop-bridge'
-import { readDesktopFileText } from './desktop-fs'
+import { readDesktopFileText, writeDesktopFileText } 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 }))
+vi.mock('@/components/chat/shiki-highlighter', () => ({
+ LazyShiki: ({ code }: { code: string }) => <pre>{code}</pre>
+}))
// 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.
@@ -53,7 +58,7 @@ afterEach(() => {
$previewTabs.set([])
clearWebappSession()
Reflect.deleteProperty(win, 'hermesDesktop')
- document.documentElement.removeAttribute('data-hermes-desktop-host')
+ globalThis.document.documentElement.removeAttribute('data-hermes-desktop-host')
setApiRequestConnection(null)
setApiRequestProfile(null)
$connection.set(null)
@@ -135,9 +140,74 @@ describe('text previews in a session sandbox', () => {
})
})
+describe('Save in a session sandbox', () => {
+ it('saves a file for the session it was read for', async () => {
+ await writeDesktopFileText(NOTE, 'edited', { sessionId: 'sess-1' })
+ await writeDesktopFileText(NOTE, 'edited')
+
+ const [scoped, bare] = readsOf('/api/fs/write-text')
+
+ expect(scoped).toMatchObject({ body: { content: 'edited', path: NOTE, session_id: 'sess-1' }, method: 'POST' })
+ expect(bare.body).toEqual({ content: 'edited', path: NOTE })
+ })
+
+ it('saves an edited preview to the session the tab belongs to', async () => {
+ const rangeDescriptors = Object.getOwnPropertyDescriptors(Range.prototype)
+
+ Object.defineProperties(Range.prototype, {
+ getClientRects: { configurable: true, value: () => [] },
+ getBoundingClientRect: { configurable: true, value: () => new DOMRect() }
+ })
+
+ try {
+ const rendered = render(
+ <LocalFilePreview
+ reloadKey={0}
+ sessionId="stored-1"
+ target={{ kind: 'file', label: 'note.txt', path: NOTE, previewKind: 'text', source: NOTE, url: `file://${NOTE}` }}
+ />
+ )
+
+ fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))
+ const editor = EditorView.findFromDOM(rendered.container.querySelector('.cm-content')!)!
+ act(() => editor.dispatch({ changes: { from: 0, to: editor.state.doc.length, insert: 'edited' } }))
+ fireEvent.click(screen.getByRole('button', { name: /Save/ }))
+
+ await waitFor(() => expect(readsOf('/api/fs/write-text')).toHaveLength(1))
+ expect(readsOf('/api/fs/write-text')[0].body).toEqual({ content: 'edited', path: NOTE, session_id: 'stored-1' })
+ // The first load, the stale-on-disk check before the write and the reload after it all
+ // read the same session's copy.
+ const sessions = readsOf('/api/fs/read-text').map(read => read.url.searchParams.get('session_id'))
+
+ expect(sessions.length).toBeGreaterThanOrEqual(2)
+ expect(new Set(sessions)).toEqual(new Set(['stored-1']))
+ } finally {
+ for (const key of ['getClientRects', 'getBoundingClientRect']) {
+ if (rangeDescriptors[key]) {
+ Object.defineProperty(Range.prototype, key, rangeDescriptors[key])
+ } else {
+ Reflect.deleteProperty(Range.prototype, key)
+ }
+ }
+ }
+ })
+})
+
describe('native Desktop reads', () => {
+ it('keeps a local save to its path', async () => {
+ globalThis.document.documentElement.removeAttribute('data-hermes-desktop-host')
+ const writeTextFile = vi.fn(async () => ({ path: NOTE }))
+ Object.defineProperty(win, 'hermesDesktop', { configurable: true, value: { writeTextFile } })
+ $connection.set({ mode: 'local' } as never)
+
+ await writeDesktopFileText(NOTE, 'edited', { sessionId: 'sess-1' })
+
+ expect(writeTextFile).toHaveBeenCalledWith(NOTE, 'edited')
+ expect(requests).toEqual([])
+ })
+
it('keeps a local read to its path', async () => {
- document.documentElement.removeAttribute('data-hermes-desktop-host')
+ globalThis.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)
diff --git a/apps/desktop/src/lib/desktop-fs.ts b/apps/desktop/src/lib/desktop-fs.ts
index 82950f1965b..3d282ade954 100644
--- a/apps/desktop/src/lib/desktop-fs.ts
+++ b/apps/desktop/src/lib/desktop-fs.ts
@@ -139,7 +139,12 @@ export async function readDesktopFileText(
// IPC; remote writes hit the dashboard's POST /api/fs/write-text (same path
// hardening, parent-must-exist, size cap) so the editor behaves identically in
// both modes. Stale-on-disk detection is the caller's job (re-read before save).
-export async function writeDesktopFileText(path: string, content: string): Promise<{ path: string }> {
+// A gateway save names the session the file was read for, so it lands where that read did.
+export async function writeDesktopFileText(
+ path: string,
+ content: string,
+ scope?: DesktopFsSessionScope
+): Promise<{ path: string }> {
const desktop = bridge()
if (!isDesktopFsRemoteMode()) {
@@ -150,7 +155,11 @@ export async function writeDesktopFileText(path: string, content: string): Promi
return desktop.writeTextFile(path, content)
}
- const result = await remoteFsApi<{ ok?: boolean; path?: string }>('/api/fs/write-text', { content, path })
+ const result = await remoteFsApi<{ ok?: boolean; path?: string }>('/api/fs/write-text', {
+ content,
+ path,
+ ...(scope?.sessionId ? { session_id: scope.sessionId } : {})
+ })
return { path: result.path || path }
}
diff --git a/hermes_cli/web_models.py b/hermes_cli/web_models.py
index 412c4b58d3e..2e938bb6597 100644
--- a/hermes_cli/web_models.py
+++ b/hermes_cli/web_models.py
@@ -184,6 +184,8 @@ class MoaConfigPayload(_MoaReferenceControls):
class FsWriteText(BaseModel):
path: str
content: str
+ #: The session the file was read for: its /workspace is that session's sandbox.
+ session_id: Optional[str] = None
class GitPathBody(BaseModel):
path: str
diff --git a/hermes_cli/web_routers/files.py b/hermes_cli/web_routers/files.py
index 44369e385a8..fd14558b92a 100644
--- a/hermes_cli/web_routers/files.py
+++ b/hermes_cli/web_routers/files.py
@@ -1049,7 +1049,9 @@ async def fs_write_text(payload: FsWriteText, profile: Optional[str] = None):
``_fs_path``, the parent must already exist (never build trees), only
regular files may be replaced, payload size-capped, staged to a sibling
temp file and ``os.replace``-d so a crash can't truncate the original.
- Stale-on-disk detection is the client's job (re-read before save).
+ Stale-on-disk detection is the client's job (re-read before save). The
+ target resolves as ``read-text`` resolves it, ``session_id`` included, so a
+ file saves to the same place it was read from.
"""
text = payload.content or ""
# Save where read-text read: a staged paste or pick on this host, all else on the SSH machine.
@@ -1066,7 +1068,7 @@ async def fs_write_text(payload: FsWriteText, profile: Optional[str] = None):
_raise_fs_backend_error(exc)
return {"ok": True, "path": target, "byteSize": byte_size}
- target = _fs_path(payload.path, decode_fallback=False)
+ target = await _fs_download_path(payload.path, profile, payload.session_id, decode_fallback=False)
if len(text.encode("utf-8")) > _FS_TEXT_WRITE_MAX_BYTES:
raise HTTPException(status_code=413, detail="Content too large")
@@ -1099,8 +1101,11 @@ async def fs_write_text(payload: FsWriteText, profile: Optional[str] = None):
return {"ok": True, "path": str(target), "byteSize": len(text.encode("utf-8"))}
-async def _fs_download_path(path: str, profile: Optional[str], session_id: Optional[str]) -> Path:
+async def _fs_download_path(
+ path: str, profile: Optional[str], session_id: Optional[str], *, decode_fallback: bool = True,
+) -> Path:
# Resolve container paths in the requested profile's sandbox, not the active one's.
+ # A write passes decode_fallback=False: it must never land on a decoded twin of its name.
profile_home = _fs_profile_home(profile)
if session_id is not None:
from hermes_cli.web_routers.sessions import get_session_detail
@@ -1112,9 +1117,9 @@ async def _fs_download_path(path: str, profile: Optional[str], session_id: Optio
cwd = session.get("cwd") or ""
return _agent_fs_path(
path, cwd=cwd, profile_home=profile_home,
- workspace_key=_session_workspace_key(session_id, cwd),
+ workspace_key=_session_workspace_key(session_id, cwd), decode_fallback=decode_fallback,
)
- return _agent_fs_path(path, profile_home=profile_home)
+ return _agent_fs_path(path, profile_home=profile_home, decode_fallback=decode_fallback)
def _fs_profile_home(profile: Optional[str]) -> Optional[Path]:
diff --git a/hermes_cli/web_server_files.py b/hermes_cli/web_server_files.py
index d4c2b3a4e98..9c26ba83303 100644
--- a/hermes_cli/web_server_files.py
+++ b/hermes_cli/web_server_files.py
@@ -229,7 +229,7 @@ SANDBOX_NOT_FOUND = "File not found on the gateway host: the path may live insid
def _agent_fs_path(
raw_path: str, *, cwd: str | None = None, profile_home: Path | None = None,
- workspace_key: str = "",
+ workspace_key: str = "", decode_fallback: bool = True,
) -> Path:
"""``_fs_path`` for agent-facing reads; container paths resolve to their host
mount, so callers' boundary guards see the real host target.
@@ -241,7 +241,7 @@ def _agent_fs_path(
"""
raw = str(raw_path or "").strip()
if os.name != "nt":
- host = _fs_path(raw_path, cwd=cwd)
+ host = _fs_path(raw_path, cwd=cwd, decode_fallback=decode_fallback)
if os.access(host, os.R_OK):
return host
translated = _agent_container_path(
@@ -253,7 +253,7 @@ def _agent_fs_path(
return translated
if _is_unmapped_container_path(raw, profile_home=profile_home):
raise HTTPException(status_code=404, detail=SANDBOX_NOT_FOUND)
- return _fs_path(raw_path, cwd=cwd)
+ return _fs_path(raw_path, cwd=cwd, decode_fallback=decode_fallback)
def _file_url_container_text(raw: str) -> str:
diff --git a/tests/hermes_cli/test_web_server_fs_session_workspace.py b/tests/hermes_cli/test_web_server_fs_session_workspace.py
index 2b4912511c0..2f2661b1266 100644
--- a/tests/hermes_cli/test_web_server_fs_session_workspace.py
+++ b/tests/hermes_cli/test_web_server_fs_session_workspace.py
@@ -181,3 +181,54 @@ def test_read_text_refuses_a_file_outside_the_sessions_workspace(client, sandbox
assert response.status_code in (400, 403, 404), response.text
assert "outside note" not in response.text
+
+
+# Part 3: Save
+
+
+def _notes(sandboxes):
+ return {name: (sandboxes[name] / "note.txt").read_text(encoding="utf-8") for name in ("own", "foreign", "shared")}
+
+
[email protected]("path", ["/workspace/note.txt", "file:///workspace/note.txt"])
+def test_save_writes_the_file_the_preview_read(client, sandboxes, path):
+ read = client.get("/api/fs/read-text", params={"path": path, "session_id": "sess-ws"})
+ saved = client.post("/api/fs/write-text", json={"path": path, "content": "edited", "session_id": "sess-ws"})
+
+ assert saved.status_code == 200, saved.text
+ assert saved.json()["path"] == read.json()["path"] == str(sandboxes["own"] / "note.txt")
+ assert _notes(sandboxes) == {"own": "edited", "foreign": "foreign note", "shared": "shared note"}
+
+
+def test_save_without_a_session_writes_where_a_bare_read_reads(client, sandboxes):
+ read = client.get("/api/fs/read-text", params={"path": "/workspace/note.txt"})
+ saved = client.post("/api/fs/write-text", json={"path": "/workspace/note.txt", "content": "edited"})
+
+ assert saved.status_code == 200, saved.text
+ assert saved.json()["path"] == read.json()["path"] == str(sandboxes["shared"] / "note.txt")
+ assert _notes(sandboxes) == {"own": "session note", "foreign": "foreign note", "shared": "edited"}
+
+
[email protected]("session_id", ["sess-work", "missing-session", " "])
+def test_save_refuses_a_session_this_profile_does_not_own(client, sandboxes, session_id):
+ for path in ("/workspace/note.txt", "file:///workspace/note.txt"):
+ response = client.post(
+ "/api/fs/write-text", json={"path": path, "content": "edited", "session_id": session_id},
+ )
+ assert response.status_code == 404, (path, response.text)
+ assert _notes(sandboxes) == {"own": "session note", "foreign": "foreign note", "shared": "shared note"}
+
+
+ "/workspace/escape.txt",
+ "file:///workspace/escape.txt",
+ "/workspace/../outside/secret.txt",
+])
+def test_save_refuses_a_file_outside_the_sessions_workspace(client, sandboxes, path):
+ response = client.post(
+ "/api/fs/write-text", json={"path": path, "content": "edited", "session_id": "sess-ws"},
+ )
+
+ assert response.status_code in (400, 403, 404), response.text
+ assert (sandboxes["outside"] / "secret.txt").read_text(encoding="utf-8") == "outside note"
+ assert (sandboxes["own"] / "escape.txt").is_symlink()