Skip to content

The agent that grows with you

test(desktop): remote-backend topology — image bytes not client paths (#120730), rename across backend restart (#121192)

teknium17f401ed5e034
diff --git a/apps/desktop/e2e/core/remote-helpers.ts b/apps/desktop/e2e/core/remote-helpers.ts
new file mode 100644
index 00000000000..a3ab43b1c14
--- /dev/null
+++ b/apps/desktop/e2e/core/remote-helpers.ts
@@ -0,0 +1,259 @@
+/**
+ * Remote-backend topology for the core suite: a real `hermes serve` the TEST
+ * spawns (not the app) under its OWN sandbox HOME / HERMES_HOME / cwd, reached
+ * by the Desktop only by URL + token (HERMES_DESKTOP_REMOTE_URL/_TOKEN). Paths
+ * that exist on the client sandbox do not exist on the backend's filesystem
+ * view of the world (different root), which is the shape of a Desktop talking
+ * to a backend on another machine.
+ */
+
+import { type ChildProcess, spawn } from 'node:child_process'
+import * as crypto from 'node:crypto'
+import * as fs from 'node:fs'
+import * as net from 'node:net'
+import * as path from 'node:path'
+import { DatabaseSync } from 'node:sqlite'
+import * as zlib from 'node:zlib'
+
+import { type CoreSandbox, REPO_ROOT } from './harness'
+
+export interface RemoteBackend {
+ url: string
+ token: string
+ port: number
+ pid: () => number
+ /** SIGKILL the backend and wait for it to exit (a crash / host reboot). */
+ kill: () => Promise<void>
+ /** Start it again on the same port and home (the user's service restarting). */
+ restart: () => Promise<void>
+ logTail: () => string
+}
+
+function python(): string {
+ for (const venv of ['.venv', 'venv']) {
+ const candidate = path.join(REPO_ROOT, venv, 'bin', 'python')
+
+ if (fs.existsSync(candidate)) {
+ return candidate
+ }
+ }
+
+ throw new Error(`no Python venv under ${REPO_ROOT} (run uv sync)`)
+}
+
+function freePort(): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const server = net.createServer()
+ server.on('error', reject)
+ server.listen(0, '127.0.0.1', () => {
+ const { port } = server.address() as net.AddressInfo
+ server.close(() => resolve(port))
+ })
+ })
+}
+
+async function waitReady(url: string, token: string, child: ChildProcess, log: string[]): Promise<void> {
+ const deadline = Date.now() + 120_000
+
+ while (Date.now() < deadline) {
+ if (child.exitCode !== null) {
+ throw new Error(`remote backend exited ${child.exitCode} before ready:\n${log.slice(-40).join('\n')}`)
+ }
+
+ try {
+ const res = await fetch(`${url}/api/status`, { headers: { Authorization: `Bearer ${token}` } })
+
+ if (res.ok) {
+ return
+ }
+ } catch {
+ /* not listening yet */
+ }
+
+ await new Promise(resolve => setTimeout(resolve, 250))
+ }
+
+ throw new Error(`remote backend never answered /api/status:\n${log.slice(-40).join('\n')}`)
+}
+
+/** Spawn `hermes serve` for `sandbox` (its HOME/HERMES_HOME, cwd = its root). */
+export async function startRemoteBackend(sandbox: CoreSandbox): Promise<RemoteBackend> {
+ const port = await freePort()
+ const token = crypto.randomBytes(24).toString('base64url')
+ const url = `http://127.0.0.1:${port}`
+ const log: string[] = []
+ let child: ChildProcess
+
+ const env: Record<string, string> = {}
+
+ for (const [key, value] of Object.entries(process.env)) {
+ if (value && !/^_?HERMES_/.test(key) && !/(_API_KEY|_TOKEN|_SECRET|_BASE_URL)$/.test(key) && key !== 'VIRTUAL_ENV') {
+ env[key] = value
+ }
+ }
+
+ const launch = async () => {
+ child = spawn(python(), ['-m', 'hermes_cli.main', 'serve', '--host', '127.0.0.1', '--port', String(port)], {
+ cwd: sandbox.root,
+ env: {
+ ...env,
+ PATH: `${sandbox.bin}${path.delimiter}${env.PATH ?? ''}`,
+ PYTHONPATH: REPO_ROOT,
+ HOME: sandbox.home,
+ HERMES_HOME: sandbox.hermesHome,
+ HERMES_DASHBOARD_SESSION_TOKEN: token,
+ GIT_NO_LAZY_FETCH: '1'
+ },
+ stdio: ['ignore', 'pipe', 'pipe']
+ })
+
+ const collect = (chunk: Buffer) => {
+ log.push(...chunk.toString('utf8').split('\n').filter(Boolean))
+ log.splice(0, Math.max(0, log.length - 200))
+ }
+
+ child.stdout?.on('data', collect)
+ child.stderr?.on('data', collect)
+ await waitReady(url, token, child, log)
+ }
+
+ await launch()
+
+ const kill = async () => {
+ if (child.exitCode !== null || child.signalCode !== null) {
+ return
+ }
+
+ const exited = new Promise<void>(resolve => child.once('exit', () => resolve()))
+ child.kill('SIGKILL')
+ await exited
+ }
+
+ return {
+ url,
+ token,
+ port,
+ pid: () => child.pid ?? -1,
+ kill,
+ restart: async () => {
+ await kill()
+ await launch()
+ },
+ logTail: () => log.slice(-60).join('\n')
+ }
+}
+
+/** Remote-mode env for the app: no local backend, attach by URL + token. */
+export function remoteEnv(backend: RemoteBackend): Record<string, string> {
+ return { HERMES_DESKTOP_REMOTE_URL: backend.url, HERMES_DESKTOP_REMOTE_TOKEN: backend.token }
+}
+
+function withDb<T>(dbPath: string, read: (db: DatabaseSync) => T): null | T {
+ if (!fs.existsSync(dbPath)) {
+ return null
+ }
+
+ const db = new DatabaseSync(dbPath, { readOnly: true })
+
+ try {
+ return read(db)
+ } catch {
+ // Mid-WAL-checkpoint reads can fail transiently; callers poll.
+ return null
+ } finally {
+ db.close()
+ }
+}
+
+export interface SessionRow {
+ id: string
+ title: null | string
+ parent_session_id: null | string
+ end_reason: null | string
+}
+
+/** Every session row of the default profile, read-only, straight from state.db. */
+export function sessionRows(sandbox: CoreSandbox): SessionRow[] {
+ return (
+ withDb(
+ path.join(sandbox.hermesHome, 'state.db'),
+ db =>
+ db
+ .prepare('SELECT id, title, parent_session_id, end_reason FROM sessions ORDER BY started_at, id')
+ .all() as unknown as SessionRow[]
+ ) ?? []
+ )
+}
+
+/** Persisted message rows (role, content) of one session, oldest first, active rows only. */
+export function messageRows(sandbox: CoreSandbox, sessionId: string): { role: string; content: string }[] {
+ return (
+ withDb(
+ path.join(sandbox.hermesHome, 'state.db'),
+ db =>
+ db
+ .prepare(
+ "SELECT role, COALESCE(content, '') AS content FROM messages WHERE session_id = ? AND COALESCE(active, 1) = 1 ORDER BY id"
+ )
+ .all(sessionId) as unknown as { role: string; content: string }[]
+ ) ?? []
+ )
+}
+
+/** A 16x16 PNG with a unique payload chunk, so the bytes can be traced end to end. */
+export function uniquePng(tag: string): Buffer {
+ const crcTable = Array.from({ length: 256 }, (_, n) => {
+ let c = n
+
+ for (let k = 0; k < 8; k++) {
+ c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1
+ }
+
+ return c >>> 0
+ })
+
+ const crc = (buf: Buffer) => {
+ let c = 0xffffffff
+
+ for (const byte of buf) {
+ c = crcTable[(c ^ byte) & 0xff]! ^ (c >>> 8)
+ }
+
+ return (c ^ 0xffffffff) >>> 0
+ }
+
+ const chunk = (type: string, data: Buffer) => {
+ const len = Buffer.alloc(4)
+ len.writeUInt32BE(data.length)
+ const body = Buffer.concat([Buffer.from(type, 'ascii'), data])
+ const sum = Buffer.alloc(4)
+ sum.writeUInt32BE(crc(body))
+
+ return Buffer.concat([len, body, sum])
+ }
+
+ const size = 16
+ const ihdr = Buffer.alloc(13)
+ ihdr.writeUInt32BE(size, 0)
+ ihdr.writeUInt32BE(size, 4)
+ ihdr[8] = 8
+ ihdr[9] = 2 // truecolor RGB
+ const raw = Buffer.alloc(size * (1 + size * 3))
+
+ for (let y = 0; y < size; y++) {
+ for (let x = 0; x < size; x++) {
+ const at = y * (1 + size * 3) + 1 + x * 3
+ raw[at] = (x * 16) & 0xff
+ raw[at + 1] = (y * 16) & 0xff
+ raw[at + 2] = 0x80
+ }
+ }
+
+ return Buffer.concat([
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
+ chunk('IHDR', ihdr),
+ chunk('tEXt', Buffer.from(`Comment\0${tag}`, 'latin1')),
+ chunk('IDAT', zlib.deflateSync(raw)),
+ chunk('IEND', Buffer.alloc(0))
+ ])
+}
diff --git a/apps/desktop/e2e/core/remote-topology.spec.ts b/apps/desktop/e2e/core/remote-topology.spec.ts
new file mode 100644
index 00000000000..7ec590bc748
--- /dev/null
+++ b/apps/desktop/e2e/core/remote-topology.spec.ts
@@ -0,0 +1,205 @@
+/**
+ * Remote-backend topology: the Desktop attached by URL + token to a real
+ * `hermes serve` it did NOT spawn, running under a different HOME and
+ * filesystem root (./remote-helpers.ts). Only the LLM is faked.
+ *
+ * - first chat over the remote route: the turn persists in the BACKEND's
+ * state.db, and the client never starts a local backend;
+ * - attaching an image that exists only on the client sends its bytes, never
+ * the client path (#120730): the model receives the image, the client path
+ * never reaches the backend, no "image not found";
+ * - a sidebar rename survives the backend being killed and restarted
+ * (#121192): the title is in the backend's state.db and the sidebar still
+ * shows it after the app reconnects.
+ */
+
+import * as fs from 'node:fs'
+import * as path from 'node:path'
+
+import { expect, type Page, test } from '@playwright/test'
+
+import {
+ backendProcesses,
+ coreAppEnv,
+ createCoreSandbox,
+ currentSessionId,
+ launchCoreApp,
+ recordWebSockets,
+ send,
+ storedSessionForMarker,
+ waitForInteractive,
+ writeProviderHome
+} from './harness'
+import { assertTranscriptOracle, installDuplicateSampler, type OracleTarget } from './oracle'
+import { startScriptedProvider } from './provider'
+import { remoteEnv, sessionRows, startRemoteBackend, uniquePng } from './remote-helpers'
+
+const nonce = Math.random()
+ .toString(36)
+ .slice(2, 8)
+ .replace(/[^a-z0-9]/g, 'x')
+ .padEnd(4, 'q')
+
+const U = (n: number) => `U${n}-${nonce}`
+const A = (n: number) => `A${n}-${nonce}`
+
+function viewport(page: Page) {
+ return page.locator('[data-slot="aui_thread-viewport"]').filter({ visible: true }).first()
+}
+
+function imageTurnUser(body: any): any {
+ const messages: any[] = Array.isArray(body?.messages) ? body.messages : []
+
+ return [...messages].reverse().find(m => m?.role === 'user')
+}
+
+const dataUrlBytes = (url: string) => Buffer.from(/;base64,(.*)$/s.exec(url)?.[1] ?? '', 'base64')
+
+/** Every image part in the last user message of a provider request (main turn or vision call). */
+function imageParts(body: any): string[] {
+ const user = imageTurnUser(body)
+ const content = Array.isArray(user?.content) ? user.content : []
+
+ return content
+ .filter((part: any) => part?.type === 'image_url')
+ .map((part: any) => String(part.image_url?.url ?? part.image_url ?? ''))
+}
+
+/** The sidebar session row showing `text` (rows own a [data-row-actions] cluster; chat bubbles do not). */
+function sidebarRow(page: Page, text: string) {
+ return page.locator('*:has(> [data-row-actions])').filter({ hasText: text, visible: true }).first()
+}
+
+async function stubImagePicker(app: Awaited<ReturnType<typeof launchCoreApp>>['app'], filePath: string) {
+ await app.evaluate(({ dialog }, filePath) => {
+ ;(dialog as any).showOpenDialog = async () => ({ canceled: false, filePaths: [filePath] })
+ }, filePath)
+}
+
+test('remote backend: first chat, image bytes not client paths, rename across a backend restart', async () => {
+ const provider = await startScriptedProvider()
+ const backendBox = createCoreSandbox('remote-backend')
+ const clientBox = createCoreSandbox('remote-client')
+ writeProviderHome(backendBox.hermesHome, provider.url, 'agent:\n image_input_mode: native\n')
+ const backend = await startRemoteBackend(backendBox)
+ const { app, page } = await launchCoreApp(coreAppEnv(clientBox, remoteEnv(backend)))
+ const ws = recordWebSockets(page)
+
+ const finished = (marker: string) =>
+ expect
+ .poll(() => provider.completions.some(c => c.marker === marker && c.finished), {
+ timeout: 120_000,
+ message: `provider finished ${marker}`
+ })
+ .toBe(true)
+
+ const session: OracleTarget = { sessionId: '', expectUserMarkers: [] }
+
+ try {
+ await waitForInteractive(app, page)
+ await installDuplicateSampler(page)
+
+ await test.step('first chat goes to the remote backend, never a local one', async () => {
+ provider.script(U(1), [{ text: [`${A(1)} `, 'remote ', 'hello'] }])
+ await send(page, `${U(1)} hi remote`, 'Enter', ws)
+ await finished(U(1))
+ await expect(viewport(page)).toContainText(A(1))
+ await expect.poll(() => storedSessionForMarker(backendBox, 'default', U(1))).not.toBeNull()
+ session.sessionId = await currentSessionId(page)
+ session.expectUserMarkers.push(U(1))
+ await assertTranscriptOracle(page, ws, provider, session, 'remote first chat')
+ expect(new URL(ws.sockets[0]!.url).port, 'the socket dials the remote backend').toBe(String(backend.port))
+ expect(backendProcesses(clientBox), 'the client spawned no backend of its own').toEqual([])
+ expect(fs.existsSync(path.join(clientBox.hermesHome, 'state.db')), 'no client-side state.db').toBe(false)
+ })
+
+ await test.step('an image that exists only on the client reaches the model as bytes (#120730)', async () => {
+ const png = uniquePng(`client-only-${nonce}`)
+ const clientPath = path.join(clientBox.root, 'client-only-pictures', `shot-${nonce}.png`)
+ fs.mkdirSync(path.dirname(clientPath), { recursive: true })
+ fs.writeFileSync(clientPath, png)
+ await stubImagePicker(app, clientPath)
+ await page.locator('[data-slot="composer-root"] button:has(.codicon-add)').filter({ visible: true }).first().click()
+ await page.getByRole('menuitem', { name: /image/i }).first().click()
+ await expect(page.locator('[data-slot="composer-root"]').getByText(`shot-${nonce}.png`).first()).toBeVisible()
+
+ provider.script(U(2), [{ text: [`${A(2)} `, 'saw ', 'it'] }])
+ await send(page, `${U(2)} what is in this picture`, 'Enter', ws)
+ await finished(U(2))
+ await expect(viewport(page)).toContainText(A(2))
+ await expect(page.getByText(/image not found/i)).toHaveCount(0)
+
+ // The client read the file and shipped its bytes: exactly one byte-upload
+ // attach, never a path-based attach naming the client file.
+ const attaches = ws.sent.filter(f => f.method === 'image.attach' || f.method === 'image.attach_bytes')
+ expect(
+ attaches.map(f => f.method),
+ 'one byte upload, no path attach'
+ ).toEqual(['image.attach_bytes'])
+ expect(Buffer.from(String(attaches[0]!.params.content_base64), 'base64').equals(png)).toBe(true)
+
+ // The backend staged those bytes under ITS home, and the model saw that image.
+ const turn = provider.completions.find(c => c.marker === U(2))!
+ const user = imageTurnUser(turn.body)
+ const userText = typeof user?.content === 'string' ? user.content : JSON.stringify(user?.content ?? '')
+ const at = userText.indexOf(backendBox.hermesHome)
+ const staged = at >= 0 ? /^\S+?\.png/.exec(userText.slice(at))?.[0] : undefined
+ expect(staged, `the turn references a backend-side image path: ${userText.slice(0, 400)}`).toBeTruthy()
+ expect(fs.readFileSync(staged!).equals(png), 'backend-staged image is byte-identical').toBe(true)
+ const seen = provider.completions.flatMap(c => imageParts(c.body)).map(dataUrlBytes)
+ expect(
+ seen.some(bytes => bytes.equals(png)),
+ 'the model received the client image bytes'
+ ).toBe(true)
+
+ const everySent = JSON.stringify(provider.completions.map(c => c.body))
+ expect(everySent.includes(clientBox.root), 'no client-side path ever reached the backend').toBe(false)
+ const sentOnWire = JSON.stringify(ws.sent)
+ expect(sentOnWire.includes(`"path":"${clientPath}"`), 'the client path was never sent as an attach path').toBe(false)
+ session.expectUserMarkers.push(U(2))
+ })
+
+ await test.step('a sidebar rename survives a backend kill + restart (#121192)', async () => {
+ const title = `Renamed ${nonce}`
+ const row = sidebarRow(page, U(1))
+ await expect(row).toBeVisible({ timeout: 60_000 })
+ await row.click({ button: 'right' })
+ await page.getByRole('menuitem', { name: /rename/i }).first().click()
+ const input = page.getByRole('dialog').getByRole('textbox').first()
+ await expect(input).toBeVisible()
+ await input.fill(title)
+ await input.press('Enter')
+ await expect
+ .poll(() => sessionRows(backendBox).find(r => r.id === session.sessionId)?.title ?? null, {
+ message: 'rename persisted in the backend state.db'
+ })
+ .toBe(title)
+
+ await backend.restart()
+ await expect
+ .poll(() => sessionRows(backendBox).find(r => r.id === session.sessionId)?.title ?? null)
+ .toBe(title)
+ await page.reload()
+ await waitForInteractive(app, page)
+ await expect(sidebarRow(page, title)).toBeVisible({ timeout: 60_000 })
+
+ // The renamed session keeps working after the restart.
+ provider.script(U(3), [{ text: [`${A(3)} `, 'after ', 'restart'] }])
+ await page.evaluate(id => {
+ window.location.hash = `#/${encodeURIComponent(id)}`
+ }, session.sessionId)
+ await expect(viewport(page)).toContainText(A(2), { timeout: 60_000 })
+ await send(page, `${U(3)} still there`, 'Enter', ws)
+ await finished(U(3))
+ await expect
+ .poll(() => sessionRows(backendBox).find(r => r.id === session.sessionId)?.title ?? null)
+ .toBe(title)
+ })
+ } finally {
+ await app.close().catch(() => undefined)
+ await backend.kill()
+ await provider.close()
+ clientBox.cleanup()
+ backendBox.cleanup()
+ }
+})