Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(security): measure a path against the folder it opens, not its name (OH-15, OH-16)

0xken15419a4cfbbea5
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index a31920a39..2bc2dcaa8 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -834,7 +834,8 @@ describe('BackendSocket outbound queue', () => {
type: 'git_project_info', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-request' } },
} })
await vi.waitFor(() => expect(wrap).toHaveBeenCalledWith('viewer-a', 'git_project_info_result', 'preview-1', preview))
- expect(read).toHaveBeenCalledWith('/remote/workspace', { refresh })
+ // The fence travels with the request — no registered agents here, so it is the home folder alone.
+ expect(read).toHaveBeenCalledWith('/remote/workspace', { refresh, knownRoots: [] })
expect(parseSent(ws)).toContainEqual(expect.objectContaining({ targetConnId: 'viewer-a', frame: {
type: 'git_project_info_result', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-preview' } },
} }))
@@ -906,7 +907,7 @@ describe('BackendSocket outbound queue', () => {
type: 'git_project_info', payload: { __e2e: { v: 1, k: 'p', n: 1, ct: 'encrypted-request' } },
} })
await vi.waitFor(() => expect(wrap).toHaveBeenCalledWith('viewer-a', 'git_project_info_result', 'git-error', { error: 'UNAVAILABLE' }))
- expect(read).toHaveBeenCalledWith('', { refresh: false })
+ expect(read).toHaveBeenCalledWith('', { refresh: false, knownRoots: [] })
await socket.stop()
})
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index a3277fcd7..cf13d7661 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -72,7 +72,6 @@ import { routeVoiceTask } from './lib/voiceRouter.js'
import { tailFile } from './lib/sessions.js'
import { stoppedAgents } from './lib/stoppedAgents.js'
import { messagesToEvents, windowRawLines, subagentStatsFromRawLines, type SessionEvent } from './lib/normalize.js'
-import { listFileTree, readProjectFile } from './lib/files.js'
import { MediaPreviewError, readMediaPreviewChunk } from './lib/mediaPreview.js'
import { ViewerForwarder } from './lib/viewerForwarder.js'
import { InteractiveViewers } from './lib/interactiveViewer.js'
@@ -2713,17 +2712,6 @@ export class BackendSocket {
return
}
- case 'agent_files': {
- // SourceTree list — rooted at the tmux session's working dir.
- const projectId = payload.agentId as string | undefined
- if (!projectId) { reply(type, requestId, { error: 'MISSING_AGENT_ID' }); return }
- const s = registry.resolve(projectId)
- if (!s?.cwd) { reply(type, requestId, { error: 'AGENT_NOT_FOUND' }); return }
- try { reply(type, requestId, { files: listFileTree(s.cwd) }) }
- catch (e) { reply(type, requestId, { error: e instanceof Error ? e.message : 'FILE_TREE_ERROR' }) }
- return
- }
-
case 'git_pull_request': {
const id = payload.agentId
const agent = typeof id === 'string' ? registry.resolve(id) : undefined
@@ -2745,7 +2733,10 @@ export class BackendSocket {
case 'git_project_info': {
const path = typeof payload.path === 'string' ? payload.path : ''
- void readGitProject(path, { refresh: payload.refresh === true })
+ // Same root set as project_preview below: the browsable home, widened by the workspaces
+ // agents are running in, so a repo outside both is not somewhere this daemon runs git.
+ void readGitProject(path, { refresh: payload.refresh === true,
+ knownRoots: registry.list().flatMap(agent => agent.cwd ? [agent.cwd] : []) })
.then(result => reply(type, requestId, result))
.catch(() => reply(type, requestId, { error: 'UNAVAILABLE' }))
return
@@ -2793,23 +2784,20 @@ export class BackendSocket {
}
case 'agent_read_file': {
- // Text reads keep their ≤5 MB guard; media uses bounded binary chunks.
+ // Media previews, in bounded binary chunks. The text mode this RPC also used to serve was
+ // read by nothing — every client has always asked with `media: true` — so it is gone rather
+ // than carrying a second, laxer file reader (lib/mediaPreview.ts).
const projectId = payload.agentId as string | undefined
const path = payload.path as string | undefined
if (!projectId || !path) { reply(type, requestId, { error: 'MISSING_AGENT_OR_PATH' }); return }
+ if (payload.media !== true) { reply(type, requestId, { error: 'UNSUPPORTED', detail: 'agent_read_file serves media previews only' }); return }
const s = registry.resolve(projectId)
if (!s?.cwd) { reply(type, requestId, { error: 'AGENT_NOT_FOUND' }); return }
- if (payload.media === true) {
- if (typeof path !== 'string') { reply(type, requestId, { error: 'MEDIA_INVALID_REQUEST' }); return }
- try {
- reply(type, requestId, { ...await readMediaPreviewChunk(s.cwd, path, payload.offset, payload.revision) })
- } catch (error) {
- reply(type, requestId, { error: error instanceof MediaPreviewError ? error.message : 'MEDIA_READ_FAILED' })
- }
- return
+ try {
+ reply(type, requestId, { ...await readMediaPreviewChunk(s.cwd, path, payload.offset, payload.revision) })
+ } catch (error) {
+ reply(type, requestId, { error: error instanceof MediaPreviewError ? error.message : 'MEDIA_READ_FAILED' })
}
- try { reply(type, requestId, { path, content: readProjectFile(s.cwd, path) }) }
- catch (e) { reply(type, requestId, { error: e instanceof Error ? e.message : 'NOT_FOUND' }) }
return
}
diff --git a/cli/src/config/env.ts b/cli/src/config/env.ts
index e7f4f3de9..33f3204fb 100644
--- a/cli/src/config/env.ts
+++ b/cli/src/config/env.ts
@@ -136,7 +136,9 @@ const envSchema = z.object({
AUTONOMOUS_ENV: z.enum(['prod', 'stag']).default('prod'),
// Web app base URL — used to print the agent's chat link on `adapter start`. Local: http://localhost:3000.
WEB_URL: z.string().default('https://harness.autonomous.ai'),
- // Set to '1' to let the New Agent folder browser (fs_list_dir) list directories outside $HOME.
+ // Set to '1' to lift the path fences shared by lib/pathContainment.ts: the New Agent folder browser
+ // (fs_list_dir), the project preview, git_project_info, and media previews all stop measuring what
+ // they were asked for against the folders they are allowed to read.
// Off by default so a fat-fingered path or a compromised relay hop can't walk the whole filesystem.
HARNESS_FS_BROWSE_UNRESTRICTED: z.string().optional(),
// Where Claude Code writes its per-session JSONL transcripts.
diff --git a/cli/src/lib/files.ts b/cli/src/lib/files.ts
deleted file mode 100644
index cadf9cc7f..000000000
--- a/cli/src/lib/files.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-/**
- * Project file listing + reading for the remote agent's SourceTree ("Files" panel).
- * Root = the tmux session's working dir. Mirrors the hosted runtime’s tree/ignore/hidden-path rules
- * (ProjectService.readDirRecursive / readFile) and ADDS the file-view guard: only files ≤ 5 MB and
- * only text files (binary → rejected). Self-contained — no dependencies outside this package.
- */
-
-import { readdirSync, statSync, readFileSync } from 'fs'
-import { join, resolve, sep, basename } from 'path'
-
-export interface FileNode {
- name: string
- type: 'file' | 'dir'
- size?: number
- children?: FileNode[]
-}
-
-export const MAX_FILE_BYTES = 5 * 1024 * 1024 // 5 MiB
-
-// Exact-name ignores (kept in sync with the hosted runtime’s readDirRecursive). Any dot-prefixed entry
-// (`.git`, `.next`, `.vite`, `.claude`, `.env`, `.node_modules`, …) is excluded separately below,
-// so only the non-dot names need listing here.
-const EXCLUDE = new Set(['node_modules', 'dist', 'logs', 'CLAUDE.md'])
-
-/** Hidden entry: any name starting with a dot (e.g. `.git`, `.env`, `.node_modules`). */
-const isHidden = (name: string): boolean => name.startsWith('.')
-
-// Soft caps so a giant arbitrary user dir can't hang / flood the walk (the hosted runtime has none, but the
-// remote root is an arbitrary machine dir).
-const MAX_NODES = 20_000
-const MAX_DEPTH = 12
-
-/** Recursive eager file tree under `root`, excluding EXCLUDE names, dirs-before-files sorted. */
-export function listFileTree(root: string): FileNode[] {
- let count = 0
- let truncated = false
-
- const walk = (dir: string, depth: number): FileNode[] => {
- if (depth > MAX_DEPTH || count >= MAX_NODES) { truncated = true; return [] }
- let entries
- try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return [] }
- const nodes: FileNode[] = []
- for (const entry of entries) {
- if (isHidden(entry.name) || EXCLUDE.has(entry.name)) continue
- if (count >= MAX_NODES) { truncated = true; break }
- count++
- const full = join(dir, entry.name)
- if (entry.isDirectory()) {
- nodes.push({ name: entry.name, type: 'dir', children: walk(full, depth + 1) })
- } else if (entry.isFile()) {
- let size = 0
- try { size = statSync(full).size } catch { /* ignore */ }
- nodes.push({ name: entry.name, type: 'file', size })
- }
- }
- return nodes.sort((a, b) => (a.type !== b.type ? (a.type === 'dir' ? -1 : 1) : a.name.localeCompare(b.name)))
- }
-
- const tree = walk(root, 0)
- if (truncated) console.warn(`[files] tree truncated at ${count} nodes for ${root}`)
- return tree
-}
-
-/** First 8 KB has a NUL byte → treat as binary (git/grep heuristic; extension-agnostic). */
-function isBinary(buf: Buffer): boolean {
- const n = Math.min(buf.length, 8192)
- for (let i = 0; i < n; i++) if (buf[i] === 0) return true
- return false
-}
-
-/**
- * Read one project file. Throws a bare error CODE on any rule violation:
- * NOT_FOUND | FILE_TOO_LARGE | NOT_TEXT
- */
-export function readProjectFile(root: string, relPath: string): string {
- // Hidden/internal blocks (mirror the hosted runtime). Any dot-prefixed path segment (`.env`, `.git/…`,
- // `.claude/…`, and `..`) is hidden from the tree, so it must not be readable directly either.
- if (
- basename(relPath) === 'CLAUDE.md' ||
- relPath.startsWith('logs/') ||
- relPath.split(/[/\\]/).some((seg) => seg.startsWith('.'))
- ) {
- throw new Error('NOT_FOUND')
- }
- // Path-traversal safety: the resolved path must stay under root.
- const rootResolved = resolve(root)
- const full = resolve(rootResolved, relPath)
- if (full !== rootResolved && !full.startsWith(rootResolved + sep)) throw new Error('NOT_FOUND')
-
- let st
- try { st = statSync(full) } catch { throw new Error('NOT_FOUND') }
- if (!st.isFile()) throw new Error('NOT_FOUND')
- if (st.size > MAX_FILE_BYTES) throw new Error('FILE_TOO_LARGE')
-
- let buf: Buffer
- try { buf = readFileSync(full) } catch { throw new Error('NOT_FOUND') }
- if (isBinary(buf)) throw new Error('NOT_TEXT')
- return buf.toString('utf-8')
-}
diff --git a/cli/src/lib/fsBrowse.spec.ts b/cli/src/lib/fsBrowse.spec.ts
index a4deadfdf..1cac3a004 100644
--- a/cli/src/lib/fsBrowse.spec.ts
+++ b/cli/src/lib/fsBrowse.spec.ts
@@ -1,5 +1,5 @@
import { afterAll, describe, expect, it } from 'vitest'
-import { mkdirSync, mkdtempSync, chmodSync, rmSync, writeFileSync } from 'fs'
+import { mkdirSync, mkdtempSync, chmodSync, rmSync, symlinkSync, writeFileSync } from 'fs'
import { homedir, tmpdir } from 'os'
import { join } from 'path'
import { listDir } from './fsBrowse.js'
@@ -43,6 +43,14 @@ describe('listDir', () => {
expect(listDir(tmpdir())).toEqual({ error: 'FORBIDDEN' })
})
+ it('rejects a link that is named inside $HOME but points out of it', () => {
+ // The whole point of the fence: the name sits under home, the directory it opens does not.
+ const escape = join(root, 'escape')
+ symlinkSync(tmpdir(), escape)
+ expect(listDir(escape)).toEqual({ error: 'FORBIDDEN' })
+ expect(listDir(join(escape, '.'))).toEqual({ error: 'FORBIDDEN' })
+ })
+
it('reports NOT_FOUND for a missing directory', () => {
expect(listDir(join(root, 'does-not-exist'))).toEqual({ error: 'NOT_FOUND' })
})
diff --git a/cli/src/lib/fsBrowse.ts b/cli/src/lib/fsBrowse.ts
index 04ce6b6b5..8682a960c 100644
--- a/cli/src/lib/fsBrowse.ts
+++ b/cli/src/lib/fsBrowse.ts
@@ -1,7 +1,7 @@
-import { readdirSync, statSync } from 'fs'
+import { readdirSync, realpathSync, statSync } from 'fs'
import { homedir } from 'os'
-import { isAbsolute, resolve, sep } from 'path'
-import { env } from '../config/env.js'
+import { isAbsolute, resolve } from 'path'
+import { withinRootsSync } from './pathContainment.js'
export interface DirEntry { name: string; isDir: true }
export interface ListDirResult { path: string; entries: DirEntry[]; truncated: boolean }
@@ -13,18 +13,27 @@ const MAX_ENTRIES = 2_000
/** Restrict browsing to under the user's home directory by default — the machine a user runs
* `harness` on is "theirs", but a fat-fingered path (or a compromised relay hop) walking arbitrary
- * system directories is still worth guarding against. Same opt-out convention as CLAUDE_PATH etc. */
-function isAllowed(path: string): boolean {
- if (env.HARNESS_FS_BROWSE_UNRESTRICTED === '1') return true
- const home = resolve(homedir())
- return path === home || path.startsWith(home + sep)
+ * system directories is still worth guarding against. Same opt-out convention as CLAUDE_PATH etc.
+ *
+ * Measured on the REAL path: a link inside the home folder is named inside it while pointing
+ * anywhere, so the caller resolves before asking (lib/pathContainment.ts). */
+function isAllowed(real: string): boolean {
+ return withinRootsSync(real, [homedir()])
}
/** One-level directory listing (folders only) rooted at `path`, or `homedir()` when omitted. */
export function listDir(path: string): ListDirResult | ListDirError {
const target = path || homedir()
if (!isAbsolute(target)) return { error: 'INVALID_PATH' }
- const resolved = resolve(target)
+ // Two spellings of one folder: the browser keeps showing the path the person picked, while the
+ // fence — and every read below it — uses the folder that path actually opens.
+ const requested = resolve(target)
+ let resolved: string
+ try {
+ resolved = realpathSync(requested)
+ } catch (e) {
+ return { error: (e as NodeJS.ErrnoException).code === 'EACCES' ? 'PERMISSION_DENIED' : 'NOT_FOUND' }
+ }
if (!isAllowed(resolved)) return { error: 'FORBIDDEN' }
let st
@@ -49,5 +58,5 @@ export function listDir(path: string): ListDirResult | ListDirError {
}
dirs.sort((a, b) => a.name.localeCompare(b.name))
const truncated = dirs.length > MAX_ENTRIES
- return { path: resolved, entries: truncated ? dirs.slice(0, MAX_ENTRIES) : dirs, truncated }
+ return { path: requested, entries: truncated ? dirs.slice(0, MAX_ENTRIES) : dirs, truncated }
}
diff --git a/cli/src/lib/gitProject.spec.ts b/cli/src/lib/gitProject.spec.ts
index c21abaa45..5df450f95 100644
--- a/cli/src/lib/gitProject.spec.ts
+++ b/cli/src/lib/gitProject.spec.ts
@@ -1,5 +1,5 @@
import { execFile } from 'node:child_process'
-import { mkdir, mkdtemp, readFile, realpath, rm, writeFile } from 'node:fs/promises'
+import { mkdir, mkdtemp, readFile, realpath, rm, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { promisify } from 'node:util'
@@ -16,6 +16,10 @@ const exec = promisify(execFile)
describe('launch Git preparation', { timeout: 30_000 }, () => {
let root: string, repo: string
const git = async (...args: string[]) => (await exec('git', ['-C', repo, ...args])).stdout.trim()
+ /** The fixture builds its repos in the temp directory, outside the browsable home, so each read
+ * names that root — exactly as the daemon names the workspaces its agents are running in. */
+ const read = (path: string, options: { refresh?: boolean } = {}) =>
+ readGitProject(path, { ...options, knownRoots: [root] })
beforeEach(async () => {
root = await mkdtemp(join(tmpdir(), 'harness-git-test-'))
repo = join(root, 'project with spaces')
@@ -53,21 +57,39 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
const hook = join(root, 'fsmonitor.sh')
await writeFile(hook, `#!/bin/sh\ntouch '${marker}'\n`, { mode: 0o755 })
await git('config', 'core.fsmonitor', hook)
- await readGitProject(repo)
+ await read(repo)
await prepare('branch', 'refs/heads/feature')
await expect(readFile(marker)).rejects.toThrow()
})
it('reads local and remote branches without switching or creating anything', async () => {
- expect(await readGitProject(repo)).toMatchObject({ isGit: true, branch: 'main', branches: [
+ expect(await read(repo)).toMatchObject({ isGit: true, branch: 'main', branches: [
{ ref: 'refs/heads/feature', name: 'feature', remote: false },
{ ref: 'refs/heads/main', name: 'main', remote: false },
{ ref: 'refs/remotes/origin/feature', name: 'origin/feature', remote: true },
] })
expect(await git('branch', '--show-current')).toBe('main')
expect(await git('worktree', 'list', '--porcelain')).not.toContain('harness/')
- expect(await readGitProject(root)).toMatchObject({ isGit: false })
- expect(await readGitProject('relative/path')).toEqual({ error: 'INVALID_PATH' })
+ expect(await read(root)).toMatchObject({ isGit: false })
+ expect(await read('relative/path')).toEqual({ error: 'INVALID_PATH' })
+ })
+
+ it('runs git only inside the browsable home and the workspaces it was given', async () => {
+ // No known roots: the fixture's repo is in the temp directory, outside the home folder.
+ expect(await readGitProject(repo)).toEqual({ error: 'FORBIDDEN' })
+ expect(await readGitProject(repo, { knownRoots: [root] })).toMatchObject({ isGit: true })
+ // Named inside an allowed root, pointing outside it: the real path is what decides.
+ const outside = await mkdtemp(join(tmpdir(), 'harness-git-outside-'))
+ const allowed = await mkdtemp(join(tmpdir(), 'harness-git-allowed-'))
+ try {
+ await symlink(repo, join(allowed, 'link'))
+ expect(await readGitProject(join(allowed, 'link'), { knownRoots: [allowed] })).toEqual({ error: 'FORBIDDEN' })
+ // Gone, not refused: a deleted folder answers the way running git in it always did.
+ expect(await readGitProject(join(outside, 'gone'), { knownRoots: [outside] })).toEqual({ isGit: false, branches: [] })
+ } finally {
+ await rm(outside, { recursive: true, force: true })
+ await rm(allowed, { recursive: true, force: true })
+ }
})
it('discovers a newly pushed branch without fetching objects, then fetches only on Start', async () => {
@@ -83,8 +105,8 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
await git('push', 'origin', 'feat/toolbar-onboarding')
await writeFile(join(clone, 'src', 'value'), 'unsaved local work')
const refs = await there('show-ref')
- expect((await readGitProject(clone) as any).branches.map((b: any) => b.name)).not.toContain('origin/feat/toolbar-onboarding')
- const info = await readGitProject(clone, { refresh: true })
+ expect((await read(clone) as any).branches.map((b: any) => b.name)).not.toContain('origin/feat/toolbar-onboarding')
+ const info = await read(clone, { refresh: true })
expect(info).toMatchObject({ refreshed: true, branch: 'main', branches: expect.arrayContaining([
{ ref: 'refs/remotes/origin/feat/toolbar-onboarding', name: 'origin/feat/toolbar-onboarding', remote: true },
]) })
@@ -101,7 +123,7 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
await git('clone', '--bare', repo, remote)
await git('remote', 'add', 'origin', join(root, 'missing.git'))
await git('remote', 'add', 'upstream', remote)
- const info = await readGitProject(repo, { refresh: true })
+ const info = await read(repo, { refresh: true })
expect(info).toMatchObject({ refreshed: false, branches: expect.arrayContaining([
{ ref: 'refs/remotes/origin/feature', name: 'origin/feature', remote: true },
{ ref: 'refs/remotes/upstream/main', name: 'upstream/main', remote: true },
@@ -114,7 +136,7 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
await git('clone', '--bare', repo, remote)
await git('remote', 'add', 'origin', remote)
await exec('git', ['-C', remote, 'branch', '-D', 'feature'])
- const info = await readGitProject(repo, { refresh: true }) as { branches: Array<{ name: string }> }
+ const info = await read(repo, { refresh: true }) as { branches: Array<{ name: string }> }
expect(info.branches.map(b => b.name)).toContain('feature')
expect(info.branches.map(b => b.name)).not.toContain('origin/feature')
expect(await git('show-ref', '--verify', 'refs/remotes/origin/feature')).toBeTruthy()
@@ -210,7 +232,7 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
const made = await prepare('worktree', 'refs/heads/feature', repo, { branchName: 'quiet-owl', branchMode: 'placeholder' })
expect(await current(made)).toBe('quiet-owl')
expect(await git('config', '--get', 'branch.quiet-owl.harness')).toBe('placeholder')
- const info = await readGitProject(repo) as { branches: Array<{ name: string; harness?: true }> }
+ const info = await read(repo) as { branches: Array<{ name: string; harness?: true }> }
expect(info.branches.filter(b => b.harness).map(b => b.name).sort()).toEqual(['fix/login', 'quiet-owl'])
await expect(prepare('worktree', 'refs/heads/feature', repo, { branchName: 'fix/login' })).rejects.toMatchObject({ code: 'BRANCH_EXISTS' })
await expect(prepare('worktree', 'refs/heads/feature', repo, { branchName: 'bad..name' })).rejects.toMatchObject({ code: 'INVALID_BRANCH' })
@@ -312,7 +334,7 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
await git('remote', 'add', 'origin', origin)
await git('fetch', '--quiet', 'origin')
await git('remote', 'set-head', 'origin', 'main')
- expect(await readGitProject(repo)).toMatchObject({ defaultRef: 'refs/remotes/origin/main' })
+ expect(await read(repo)).toMatchObject({ defaultRef: 'refs/remotes/origin/main' })
await exec('git', ['clone', '--quiet', origin, upstream])
const up = (...args: string[]) => exec('git', ['-C', upstream, '-c', 'user.name=Test', '-c', '[email protected]', '-c', 'commit.gpgsign=false', '-c', 'core.hooksPath=/dev/null', ...args])
await writeFile(join(upstream, 'src', 'value'), 'pushed')
@@ -350,13 +372,13 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
it('reads a linked worktree as its repository, and a worktree started from one joins the same repository', async () => {
const linked = await prepare('worktree', 'refs/heads/feature', repo, { branchName: 'harness/linked' })
- const info = await readGitProject(join(linked, 'src'))
+ const info = await read(join(linked, 'src'))
expect(info).toMatchObject({ isGit: true, branch: 'harness/linked', mainBranch: 'main' })
expect(await realpath((info as { mainFolder: string }).mainFolder)).toBe(await realpath(join(repo, 'src')))
const branches = (info as { branches: Array<{ name: string; worktree?: string }> }).branches
expect(await realpath(branches.find(branch => branch.name === 'harness/linked')!.worktree!)).toBe(await realpath(linked))
expect(await realpath(branches.find(branch => branch.name === 'main')!.worktree!)).toBe(await realpath(repo))
- expect(await readGitProject(repo)).not.toHaveProperty('mainFolder')
+ expect(await read(repo)).not.toHaveProperty('mainFolder')
expect(await prepare('worktree', 'refs/heads/main', linked, { branchName: 'harness/second' })).toBe(join(worktrees(), 'second'))
})
@@ -399,7 +421,7 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
const empty = join(root, 'empty')
await mkdir(empty)
await exec('git', ['-C', empty, 'init', '-b', 'main'])
- expect(await readGitProject(empty)).toMatchObject({ isGit: true, branch: 'main', branches: [] })
+ expect(await read(empty)).toMatchObject({ isGit: true, branch: 'main', branches: [] })
await expect(prepareProjectFolder({ source: 'worktree', gitSource: empty }, options()))
.rejects.toMatchObject({ code: 'GIT_PROJECT_UNAVAILABLE' })
})
@@ -427,7 +449,7 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
it('supports detached HEAD, default worktree names, and switching back to a local branch', async () => {
await git('checkout', '--detach', 'HEAD')
- expect(await readGitProject(repo)).toMatchObject({ isGit: true, branch: null })
+ expect(await read(repo)).toMatchObject({ isGit: true, branch: null })
const path = await prepareGitProject(repo, { root, worktree: true })
expect(await readFile(join(path, 'src', 'value'), 'utf8')).toBe('main')
expect(path).toMatch(/\/worktrees\/project with spaces\/[a-z]+-[a-z]+(-\d+)?$/)
@@ -437,12 +459,12 @@ describe('launch Git preparation', { timeout: 30_000 }, () => {
it('distinguishes an unavailable Git executable from a non-Git folder', async () => {
vi.stubEnv('PATH', join(root, 'missing-binaries'))
- expect(await readGitProject(repo)).toEqual({ error: 'GIT_UNAVAILABLE' })
+ expect(await read(repo)).toEqual({ error: 'GIT_UNAVAILABLE' })
})
it('reports unreadable refs instead of silently treating the repository as non-Git', async () => {
await writeFile(join(repo, '.git', 'packed-refs'), 'invalid packed refs\n')
- expect(await readGitProject(repo)).toEqual({ error: 'GIT_UNAVAILABLE' })
+ expect(await read(repo)).toEqual({ error: 'GIT_UNAVAILABLE' })
})
it('rejects a subfolder that became a file on the selected branch', async () => {
diff --git a/cli/src/lib/gitProject.ts b/cli/src/lib/gitProject.ts
index 57ae93258..2a8d028ad 100644
--- a/cli/src/lib/gitProject.ts
+++ b/cli/src/lib/gitProject.ts
@@ -1,8 +1,10 @@
import { execFile } from 'node:child_process'
import { cp, lstat, mkdir, realpath, stat, writeFile } from 'node:fs/promises'
+import { homedir } from 'node:os'
import { basename, dirname, isAbsolute, join, normalize } from 'node:path'
import { promisify } from 'node:util'
import { placeholderBranch, plausibleBranchName, worktreeFolderName } from './agentNames.js'
+import { withinRoots } from './pathContainment.js'
const exec = promisify(execFile)
@@ -89,8 +91,22 @@ async function refreshBranches(path: string): Promise<Map<string, string[] | nul
/** Cached choices are immediate. A picker can separately request a bounded
* remote refresh, including branches excluded by a single-branch clone. */
-export async function readGitProject(path: string, options: { refresh?: boolean } = {}) {
- if (!validGitPath(path)) return { error: 'INVALID_PATH' }
+/**
+ * Reads a repository's shape for the New Harness form. `knownRoots` widens the browsable home with
+ * the workspaces agents are already running in; leaving it out still fences to the home folder, so a
+ * caller can never accidentally ask this to run git anywhere on the machine.
+ *
+ * `path` is resolved before anything runs: git would follow a symlink out of the allowed folders
+ * whatever the name said, so the containment is measured on the real path and git is pointed at it.
+ */
+export async function readGitProject(requested: string, options: { refresh?: boolean; knownRoots?: string[] } = {}) {
+ if (!validGitPath(requested)) return { error: 'INVALID_PATH' }
+ let path: string
+ // A folder that is gone reads as "not a Git project", which is what running git in it used to
+ // report (exit 128) — a deleted folder is not a malformed request.
+ try { path = await realpath(requested) } catch { return { isGit: false, branches: [] } }
+ // Same word and same roots as projectPreview's fence, so the two read alike.
+ if (!(await withinRoots(path, [homedir(), ...(options.knownRoots ?? [])]))) return { error: 'FORBIDDEN' }
let root: string
try { root = await git(path, ['rev-parse', '--show-toplevel']) }
catch (error) {
diff --git a/cli/src/lib/mediaPreview.spec.ts b/cli/src/lib/mediaPreview.spec.ts
index 22e9ddc5c..a14c93bf6 100644
--- a/cli/src/lib/mediaPreview.spec.ts
+++ b/cli/src/lib/mediaPreview.spec.ts
@@ -3,13 +3,16 @@ import { mkdir, mkdtemp, open, rm, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { pathToFileURL } from 'node:url'
-import { readProjectFile } from './files.js'
import { MEDIA_PREVIEW_CHUNK_BYTES, MEDIA_PREVIEW_MAX_BYTES, readMediaPreviewChunk } from './mediaPreview.js'
describe('remote media preview reads', () => {
let root: string
const pngHeader = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])
beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'harness-media-test-')) })
+ /** The agent's workspace as the ONLY root — the fixture root lives in the temp directory, which is
+ * an allowed root by default, so a containment case has to say it means the workspace alone. */
+ const workspaceOnly = (cwd: string, target: string, offset = 0) =>
+ readMediaPreviewChunk(cwd, target, offset, undefined, [])
afterEach(async () => { await rm(root, { recursive: true, force: true }) })
it('reassembles exact bytes across bounded reads with one stable revision', async () => {
@@ -31,7 +34,7 @@ describe('remote media preview reads', () => {
expect(Buffer.concat(chunks)).toEqual(image)
})
- it('reads absolute and file URI artifacts outside the agent cwd', async () => {
+ it('reads an absolute or file:// artifact from a temp folder outside the agent cwd', async () => {
const path = join(root, '100% ảnh #1.png')
await writeFile(path, pngHeader)
for (const target of [path, pathToFileURL(path).href]) {
@@ -52,11 +55,20 @@ describe('remote media preview reads', () => {
expect(Buffer.from((await readMediaPreviewChunk(root, filename, 0)).contentBase64, 'base64')).toEqual(bytes)
})
- it('preserves the existing text reader restrictions', async () => {
- await writeFile(join(root, 'image.png'), Buffer.concat([pngHeader, Buffer.from([0])]))
+ it('refuses an absolute path that lands outside every root', async () => {
+ // A real media file the daemon can read, in a folder that is neither the workspace nor a temp one.
+ const elsewhere = await mkdtemp(join(tmpdir(), 'harness-media-elsewhere-'))
+ try {
+ await writeFile(join(elsewhere, 'private.png'), pngHeader)
+ await expect(readMediaPreviewChunk(root, join(elsewhere, 'private.png'), 0, undefined, []))
+ .rejects.toThrow('MEDIA_INVALID_REQUEST')
+ } finally {
+ await rm(elsewhere, { recursive: true, force: true })
+ }
+ })
+
+ it('serves media only, never an arbitrary text file', async () => {
await writeFile(join(root, 'source.txt'), 'hello')
- expect(readProjectFile(root, 'source.txt')).toBe('hello')
- expect(() => readProjectFile(root, 'image.png')).toThrow('NOT_TEXT')
await expect(readMediaPreviewChunk(root, 'source.txt', 0)).rejects.toThrow('MEDIA_UNSUPPORTED')
})
@@ -80,13 +92,23 @@ describe('remote media preview reads', () => {
await expect(readMediaPreviewChunk(root, path, MEDIA_PREVIEW_CHUNK_BYTES, first.revision)).rejects.toThrow('MEDIA_CHANGED')
})
- it('keeps relative symlink targets inside the agent workspace', async () => {
+ it('judges a symlink by what it points at, however the target is spelled', async () => {
const workspace = join(root, 'workspace')
await mkdir(workspace)
await writeFile(join(root, 'outside.png'), pngHeader)
await symlink(join(root, 'outside.png'), join(workspace, 'linked.png'))
- await expect(readMediaPreviewChunk(workspace, 'linked.png', 0)).rejects.toThrow('MEDIA_INVALID_REQUEST')
+ await writeFile(join(workspace, 'inside.png'), pngHeader)
+ // A RELATIVE target is a promise about the workspace, so it is held to it whatever the roots are
+ // and whatever the link says — this is the case the string fence used to catch by spelling alone.
+ for (const target of ['linked.png', '../outside.png']) {
+ await expect(readMediaPreviewChunk(workspace, target, 0)).rejects.toThrow('MEDIA_INVALID_REQUEST')
+ await expect(workspaceOnly(workspace, target)).rejects.toThrow('MEDIA_INVALID_REQUEST')
+ }
+ expect((await workspaceOnly(workspace, 'inside.png')).totalBytes).toBe(pngHeader.length)
+ // An ABSOLUTE target may name an artifact elsewhere — but only inside a root. The fixture sits in
+ // the temp directory, which is one; with the workspace alone it is refused.
expect((await readMediaPreviewChunk(workspace, join(root, 'outside.png'), 0)).totalBytes).toBe(pngHeader.length)
+ await expect(workspaceOnly(workspace, join(root, 'outside.png'))).rejects.toThrow('MEDIA_INVALID_REQUEST')
})
it('refuses a missing file and an empty file', async () => {
@@ -106,8 +128,10 @@ describe('remote media preview reads', () => {
await expect(readMediaPreviewChunk(root, 'image.png', offset)).rejects.toThrow('MEDIA_INVALID_REQUEST')
})
- it.each(['../outside.png', 'file://other-host/tmp/photo.png', 'https://example.com/photo.png', 'bad\0.png'])('refuses invalid target %s', async (target) => {
- await expect(readMediaPreviewChunk(root, target, 0)).rejects.toThrow('MEDIA_INVALID_REQUEST')
+ // `../outside.png` is refused too, but by containment rather than by shape — see the symlink test,
+ // which points it at a file that exists.
+ it.each(['file://other-host/tmp/photo.png', 'https://example.com/photo.png', 'bad\0.png'])('refuses invalid target %s', async (target) => {
+ await expect(workspaceOnly(root, target)).rejects.toThrow('MEDIA_INVALID_REQUEST')
})
it('requires the first revision for every subsequent chunk', async () => {
diff --git a/cli/src/lib/mediaPreview.ts b/cli/src/lib/mediaPreview.ts
index 82f641858..f66ca63b8 100644
--- a/cli/src/lib/mediaPreview.ts
+++ b/cli/src/lib/mediaPreview.ts
@@ -2,8 +2,9 @@ import { createHash } from 'node:crypto'
import { constants, type BigIntStats } from 'node:fs'
import { open, realpath } from 'node:fs/promises'
import { homedir } from 'node:os'
-import { basename, extname, isAbsolute, resolve, sep } from 'node:path'
+import { basename, extname, isAbsolute, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
+import { tempRoots, withinRoots } from './pathContainment.js'
// Base64 inside an E2EE JSON envelope stays below 256 KiB per reply. The client
// requests bounded chunks, so neither machine holds an entire video in memory.
@@ -22,11 +23,14 @@ const extensions = new Set([
function fail(code: string): never { throw new MediaPreviewError(code) }
-/** A media-only variant of agent_read_file, not a relaxation of its text-file
- * guard. Absolute paths are intentional: agent artifacts often live in /tmp.
- * Relative paths stay under the selected agent's working folder; ~ and file://
- * are resolved on the machine that owns the file, never on the viewing machine. */
-function resolveTarget(root: string, target: string): { path: string; relative: boolean } {
+/** Normalises what the client asked for into one absolute path on THIS machine: `~` and `file://`
+ * are resolved here, on the machine that owns the file, never on the viewing machine.
+ *
+ * Containment is deliberately NOT done here — only `realpath` can say where a path lands, so the
+ * caller resolves it first. What IS decided here is how much the request is allowed to ask for: a
+ * relative path is a promise about the workspace and is held to it, while an absolute one may name
+ * an artifact the agent dropped elsewhere. Either way the promise is measured on the real path. */
+function resolveTarget(root: string, target: string): { path: string; workspaceOnly: boolean } {
if (!target || target.length > 4096 || /[\x00-\x1f\x7f]/.test(target)) fail('MEDIA_INVALID_REQUEST')
let path = target
if (/^file:/i.test(path)) {
@@ -41,13 +45,7 @@ function resolveTarget(root: string, target: string): { path: string; relative:
}
if (path.startsWith('~/')) path = resolve(homedir(), path.slice(2))
if (!extensions.has(extname(path).toLowerCase())) fail('MEDIA_UNSUPPORTED')
- const relative = !isAbsolute(path)
- if (relative) {
- const base = resolve(root)
- path = resolve(base, path)
- if (!path.startsWith(base.endsWith(sep) ? base : base + sep)) fail('MEDIA_INVALID_REQUEST')
- }
- return { path, relative }
+ return isAbsolute(path) ? { path, workspaceOnly: false } : { path: resolve(root, path), workspaceOnly: true }
}
/** Check content as well as the suffix, so a renamed text/credential file does
@@ -99,27 +97,33 @@ export interface MediaPreviewChunk {
contentBase64: string
}
-/** Stateless bounded reads: cancelling stops future requests, and disconnects
- * leave no file handles or transfer sessions behind on the remote machine. */
+/**
+ * Stateless bounded reads: cancelling stops future requests, and disconnects leave no file handles or
+ * transfer sessions behind on the remote machine.
+ *
+ * A relative target never leaves `root`, the selected agent's working folder. An absolute one may
+ * also name `extraRoots` — by default the temp directories agents drop artifacts into — so a chart
+ * written to /tmp still opens. A caller that wants the workspace alone passes `[]`.
+ *
+ * Both checks run on the REAL path, so a symlink planted in the workspace cannot walk out of it
+ * (lib/pathContainment.ts).
+ */
export async function readMediaPreviewChunk(
root: string,
target: string,
offset: unknown,
expectedRevision?: unknown,
+ extraRoots: readonly string[] = tempRoots(),
): Promise<MediaPreviewChunk> {
if (typeof offset !== 'number' || !Number.isSafeInteger(offset) || offset < 0
|| offset % MEDIA_PREVIEW_CHUNK_BYTES !== 0
|| (offset > 0 && (typeof expectedRevision !== 'string' || !/^[a-f0-9]{64}$/.test(expectedRevision)))) {
fail('MEDIA_INVALID_REQUEST')
}
- const requested = resolveTarget(root, target)
- const requestedPath = requested.path
+ const { path: requestedPath, workspaceOnly } = resolveTarget(root, target)
try {
const canonicalPath = await realpath(requestedPath)
- if (requested.relative) {
- const base = await realpath(root)
- if (!canonicalPath.startsWith(base.endsWith(sep) ? base : base + sep)) fail('MEDIA_INVALID_REQUEST')
- }
+ if (!(await withinRoots(canonicalPath, workspaceOnly ? [root] : [root, ...extraRoots]))) fail('MEDIA_INVALID_REQUEST')
// Resolve symlinks once, then refuse a last-component swap. NONBLOCK avoids
// hanging on a FIFO before fstat can reject anything other than a file.
const file = await open(canonicalPath, constants.O_RDONLY | constants.O_NONBLOCK | constants.O_NOFOLLOW)
diff --git a/cli/src/lib/pathContainment.spec.ts b/cli/src/lib/pathContainment.spec.ts
new file mode 100644
index 000000000..d1088c025
--- /dev/null
+++ b/cli/src/lib/pathContainment.spec.ts
@@ -0,0 +1,55 @@
+import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it } from 'vitest'
+import { env } from '../config/env.js'
+import { tempRoots, within, withinRoots } from './pathContainment.js'
+
+let root: string
+const unrestricted = env.HARNESS_FS_BROWSE_UNRESTRICTED
+beforeEach(async () => {
+ root = await realpath(await mkdtemp(join(tmpdir(), 'harness-containment-')))
+ env.HARNESS_FS_BROWSE_UNRESTRICTED = undefined
+})
+afterEach(async () => {
+ await rm(root, { recursive: true, force: true })
+ env.HARNESS_FS_BROWSE_UNRESTRICTED = unrestricted
+})
+
+it('counts a root itself and what is under it, and nothing else', () => {
+ expect(within('/a/b', '/a/b')).toBe(true)
+ expect(within('/a/b', '/a/b/c/d')).toBe(true)
+ // The reason this is `relative()` and not `startsWith`: a sibling shares the prefix.
+ expect(within('/a/b', '/a/bc')).toBe(false)
+ expect(within('/a/b', '/a')).toBe(false)
+ expect(within('/a/b', '/other')).toBe(false)
+})
+
+it('measures the target against roots resolved through their symlinks', async () => {
+ const real = join(root, 'real')
+ await mkdir(real)
+ await writeFile(join(real, 'file'), 'x')
+ const link = join(root, 'link')
+ await symlink(real, link)
+ // The root is named by its link; a file inside the folder it points at is still inside it.
+ expect(await withinRoots(join(real, 'file'), [link])).toBe(true)
+ expect(await withinRoots(join(root, 'elsewhere'), [real])).toBe(false)
+})
+
+it('refuses when no root resolves, rather than allowing everything', async () => {
+ expect(await withinRoots(join(root, 'file'), [])).toBe(false)
+ expect(await withinRoots(join(root, 'file'), [join(root, 'not-there')])).toBe(false)
+ // One good root among unresolvable ones still admits what is inside it.
+ expect(await withinRoots(join(root, 'file'), [join(root, 'not-there'), root])).toBe(true)
+})
+
+it('honours the folder-browser opt-out', async () => {
+ expect(await withinRoots('/etc/passwd', [root])).toBe(false)
+ env.HARNESS_FS_BROWSE_UNRESTRICTED = '1'
+ expect(await withinRoots('/etc/passwd', [root])).toBe(true)
+})
+
+it('names both temp directories, because macOS has a private one and agents still write /tmp', () => {
+ expect(tempRoots()).toContain(tmpdir())
+ expect(tempRoots()).toContain('/tmp')
+})
diff --git a/cli/src/lib/pathContainment.ts b/cli/src/lib/pathContainment.ts
new file mode 100644
index 000000000..7a18dfa69
--- /dev/null
+++ b/cli/src/lib/pathContainment.ts
@@ -0,0 +1,61 @@
+/**
+ * One containment check for every RPC that reads or browses this machine's filesystem.
+ *
+ * The rule these all got wrong at least once: a path is only inside a folder if the FILE IT RESOLVES
+ * TO is inside it. `resolve()` rewrites `..` and `./` as text and knows nothing about symlinks, so a
+ * link sitting inside an allowed folder passes a string check while the read lands anywhere on disk.
+ * Every caller therefore resolves its target with `realpath` FIRST and only then asks `within`.
+ *
+ * The roots differ per RPC because what they hand back differs — `mediaPreview` returns the bytes of
+ * a file, `gitProject` and `projectPreview` return a repository's shape — so each names its own set
+ * rather than sharing one global allowance.
+ */
+import { realpathSync } from 'node:fs'
+import { realpath } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { isAbsolute, relative } from 'node:path'
+import { env } from '../config/env.js'
+
+/**
+ * Whether `path` IS `root` or sits below it. Both are compared as text, so both must already be real
+ * paths — handing this a path straight from a client checks the name of a symlink, not its target.
+ *
+ * `relative()` rather than `startsWith`, because `/a/bc` starts with `/a/b` and is not inside it.
+ */
+export function within(root: string, path: string): boolean {
+ const rel = relative(root, path)
+ return rel === '' || (rel !== '..' && !rel.startsWith('../') && !isAbsolute(rel))
+}
+
+/**
+ * Whether the real path `target` is inside any of `roots`. Roots are resolved here, so a root given
+ * as a symlink still matches the files under it.
+ *
+ * A root that cannot be resolved is dropped rather than compared, which makes an empty or entirely
+ * unresolvable set refuse everything — the failure of this check is always a refusal, never an
+ * allowance. `HARNESS_FS_BROWSE_UNRESTRICTED=1` is the same opt-out the folder browser has always had.
+ */
+export async function withinRoots(target: string, roots: readonly string[]): Promise<boolean> {
+ if (env.HARNESS_FS_BROWSE_UNRESTRICTED === '1') return true
+ const resolved = await Promise.all(roots.map((root) => realpath(root).catch(() => '')))
+ return resolved.some((root) => root && within(root, target))
+}
+
+/**
+ * `withinRoots` for the one caller that must stay synchronous: the folder browser is `readdirSync`
+ * and `statSync` throughout (lib/fsBrowse.ts), and one more syscall on that thread costs nothing.
+ */
+export function withinRootsSync(target: string, roots: readonly string[]): boolean {
+ if (env.HARNESS_FS_BROWSE_UNRESTRICTED === '1') return true
+ return roots.some((root) => {
+ try { return within(realpathSync(root), target) } catch { return false }
+ })
+}
+
+/**
+ * Where agents drop the files they make. macOS gives each user a private `/var/folders/…` as
+ * `tmpdir()`, but an agent told to "save it to /tmp" writes to `/tmp` itself, so both are roots.
+ */
+export function tempRoots(): string[] {
+ return [tmpdir(), '/tmp']
+}
diff --git a/cli/src/lib/projectPreview.ts b/cli/src/lib/projectPreview.ts
index 79f585ed4..ff03a2d0f 100644
--- a/cli/src/lib/projectPreview.ts
+++ b/cli/src/lib/projectPreview.ts
@@ -2,15 +2,11 @@ import { execFile } from 'node:child_process'
import { open, opendir, realpath, stat } from 'node:fs/promises'
import { constants } from 'node:fs'
import { homedir } from 'node:os'
-import { isAbsolute, join, relative } from 'node:path'
+import { isAbsolute, join } from 'node:path'
import { promisify } from 'node:util'
-import { env } from '../config/env.js'
+import { withinRoots } from './pathContainment.js'
const exec = promisify(execFile)
-const within = (root: string, path: string) => {
- const rel = relative(root, path)
- return rel === '' || (rel !== '..' && !rel.startsWith('../') && !isAbsolute(rel))
-}
/** Existing local content only. Paths/README symlinks stay inside the browsable
* home or an agent's known workspace; all Git commands are read-only/bounded. */
@@ -18,8 +14,7 @@ export async function projectPreview(path: string, knownRoots: string[] = []) {
if (!isAbsolute(path) || path.length > 4096 || /[\x00-\x1f\x7f]/.test(path)) return { error: 'INVALID_PATH' }
try {
const target = await realpath(path)
- const roots = await Promise.all([homedir(), ...knownRoots].map(root => realpath(root).catch(() => '')))
- if (env.HARNESS_FS_BROWSE_UNRESTRICTED !== '1' && !roots.some(root => root && within(root, target))) return { error: 'FORBIDDEN' }
+ if (!(await withinRoots(target, [homedir(), ...knownRoots]))) return { error: 'FORBIDDEN' }
if (!(await stat(target)).isDirectory()) return { error: 'NOT_FOUND' }
const files: string[] = []
let readme: string | undefined
diff --git a/desktop/design/agent-lifecycle-map.md b/desktop/design/agent-lifecycle-map.md
index a8037581a..9d4307217 100644
--- a/desktop/design/agent-lifecycle-map.md
+++ b/desktop/design/agent-lifecycle-map.md
@@ -35,7 +35,6 @@ three pushes discussed below run in the opposite direction.
| `agents_list` | No mutation | None | Reads `registry.advertised()` (verified available terminal routes). `includeStopped: true` merges eligible archive records into the response without adding stale routes back to the live registry. |
| `agent_create_status` | No mutation | None | Reads a separate durable operation receipt, optionally resolving its resulting live row. Does not launch or recreate a registry entry. |
| `agent_recent` | No mutation | None | Resolves Harness ID to engine `sessionId` and reads stored recaps/recent user asks. Providers resolve through the live registry or the archive, so recaps and recent asks work before Open. |
-| `agent_files` | No mutation | None | Reads the live row's `cwd`, then lists project files. No registry change. |
| `agent_read_file` | No mutation | None | Reads the live row's `cwd`, then a bounded project file/media chunk. No registry change. |
| `agent_resume` **(this PR)** | Keep a verified running runtime; otherwise allocate a new session and pane for saved work | `claude --resume <savedSessionId>` / `codex resume <savedSessionId>`; no fresh fallback | Return a verified running engine. Otherwise reserve the operation, restore the **same Harness ID and conversation ID** on a new route with no stale PID and `launch: starting`, and await the exact conversation hook from the new process. Keep the saved record on failure. No fresh fallback. |
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 61a1f674f..f0d7684bc 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -7395,7 +7395,7 @@ class AppNotifier extends ChangeNotifier {
'MEDIA_CHANGED' => 'The file changed while downloading. Wait for it to finish generating and try again.',
'MEDIA_UNSUPPORTED' => 'This file is not a supported image or video.',
'MEDIA_INVALID_REQUEST' =>
- 'Use a full path or a path inside this agent’s working folder.',
+ 'This file is outside the folders Harness reads for this agent. Use one in its working folder or a temp folder.',
'AGENT_NOT_FOUND' =>
'This agent is no longer available. Reconnect and try again.',
'NOT_TEXT' || 'FILE_TOO_LARGE' => 'Update the Harness CLI on this remote machine to open media previews.',
diff --git a/docs/cli.md b/docs/cli.md
index 43882ed80..618589335 100644
--- a/docs/cli.md
+++ b/docs/cli.md
@@ -43,7 +43,7 @@ and answers them with `<type>_result`. Selecting one of your other machines prox
through this daemon's link to it.
What it answers: `agents_list`, `agent_create`, `agent_restart`, `agent_retarget`, `agent_delete`,
-`agent_update`, `agent_recent`, `agent_files`, `agent_read_file` (text, or media in 128 KiB chunks),
+`agent_update`, `agent_recent`, `agent_read_file` (media previews, in 128 KiB chunks),
`fs_list_dir`, `engines_probe`, `codex_profiles_list`, `codex_profile_link`, `models_list`,
`usage_read`, `question_response`, `voice_route`, `message`, `cancel`, and `terminal_open` for a
binary terminal channel with scroll, resync and paste. The same frames travel from the web client
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 58043b7a4..a21638cf7 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -3308,7 +3308,7 @@ class AppNotifier extends ChangeNotifier {
'MEDIA_CHANGED' => 'The file changed while downloading. Wait for it to finish generating and try again.',
'MEDIA_UNSUPPORTED' => 'This file is not a supported image or video.',
'MEDIA_INVALID_REQUEST' =>
- 'Use a full path or a path inside this harness’s working folder.',
+ 'This file is outside the folders Harness reads for this harness. Use one in its working folder or a temp folder.',
'AGENT_NOT_FOUND' =>
'This harness is no longer available. Reconnect and try again.',
'NOT_TEXT' || 'FILE_TOO_LARGE' => 'Update the Harness CLI on this remote machine to open media previews.',
diff --git a/mobile/test/app_state_agent_rpcs_test.dart b/mobile/test/app_state_agent_rpcs_test.dart
index 742ac5d0d..b1d690d8a 100644
--- a/mobile/test/app_state_agent_rpcs_test.dart
+++ b/mobile/test/app_state_agent_rpcs_test.dart
@@ -1378,7 +1378,7 @@ void main() {
('MEDIA_TOO_LARGE', '512 MB'),
('MEDIA_CHANGED', 'changed while downloading'),
('MEDIA_UNSUPPORTED', 'not a supported'),
- ('MEDIA_INVALID_REQUEST', 'full path'),
+ ('MEDIA_INVALID_REQUEST', 'outside the folders'),
('AGENT_NOT_FOUND', 'harness is no longer available'),
('NOT_TEXT', 'Update the Harness CLI'),
('WHATEVER', 'could not read this file'),