fix(host): bound listDirectory levels at a configurable maxEntries

One list call now materializes at most maxEntries child rows (config,
default 1000 - GitHub's web-UI directory-listing bound). Candidates sort
before probing so a cut level keeps the name-sorted head and symlink
probing stops with the bound, and DirectoryListing carries a required
truncated flag on the seam and the wire so clients can state
incompleteness instead of silently missing tail entries.
This commit is contained in:
creatixchu
2026-07-29 03:45:26 +08:00
parent f56b9149e6
commit 5245182db2
22 changed files with 107 additions and 20 deletions

View File

@@ -47,6 +47,7 @@ export const hostListDirectoryValueSchema = z.object({
home: z.string(),
crumbs: z.array(directoryEntrySchema),
entries: z.array(directoryEntrySchema),
truncated: z.boolean(),
}) satisfies z.ZodType<Wire<ResponseValue<'host.listDirectory'>>>
/** host.createDirectory request payload: name must be one plain path segment. */

View File

@@ -28,6 +28,8 @@ export interface DirectoryListing {
crumbs: DirectoryEntry[]
/** Direct child directories, name-sorted; symlinks to directories included. */
entries: DirectoryEntry[]
/** True when the backend cut `entries` at its complete-result bound (the name-sorted tail is absent). */
truncated: boolean
}
/** Host-level unary methods. */

View File

@@ -159,6 +159,7 @@ const BROWSE_STUB: DirectoryPickerCapability = {
home: '/home/user',
crumbs: [{ name: '/', path: '/', hidden: false }],
entries: [{ name: 'projects', path: `${target}/projects`, hidden: false }],
truncated: false,
}
},
createDirectory: async (path, name) => {

View File

@@ -50,7 +50,7 @@ function scriptedApi(overrides: {
host: {
describe: r => ok(r, { version: '0-test', cwd: '/t', attachedSessions: 0 }),
pickDirectory: r => ok(r, { path: null }),
listDirectory: r => ok(r, { path: '/t', home: '/t', crumbs: [], entries: [] }),
listDirectory: r => ok(r, { path: '/t', home: '/t', crumbs: [], entries: [], truncated: false }),
createDirectory: r => ok(r, { path: '/t/new' }),
openPath: r => ok(r, { opened: true as const }),
...overrides.host,

View File

@@ -82,7 +82,7 @@ function fakeApi(overrides: Partial<{ muxFrames: MuxFrame[]; hostFrames: HostFra
return { rpcId: request.rpcId, result: { ok: true, value: { path: null } } }
},
async listDirectory(request) {
return { rpcId: request.rpcId, result: { ok: true, value: { path: '/w', home: '/w', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [] } } }
return { rpcId: request.rpcId, result: { ok: true, value: { path: '/w', home: '/w', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [], truncated: false } } }
},
async createDirectory(request) {
return { rpcId: request.rpcId, result: { ok: true, value: { path: '/w/new' } } }
@@ -224,7 +224,7 @@ describe('unary round trip (handler ⇄ client, no network)', () => {
const listed = await c.host.listDirectory({ path: '/w' })
expect(listed.result).toEqual({
ok: true,
value: { path: '/w', home: '/w', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [] },
value: { path: '/w', home: '/w', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [], truncated: false },
})
const home = await c.host.listDirectory({})
expect(home.result).toMatchObject({ ok: true, value: { home: '/w' } })

View File

@@ -231,8 +231,11 @@ describe('host domain schemas', () => {
home: '/home/u',
crumbs: [{ name: '/', path: '/', hidden: false }, { name: 'p', path: '/home/u/p', hidden: false }],
entries: [{ name: '.dot', path: '/home/u/p/.dot', hidden: true }],
truncated: false,
})
expect(listing.entries[0]?.hidden).toBe(true)
// The flag is part of the wire value, not an optional decoration.
expect(() => hostListDirectoryValueSchema.parse({ path: '/x', home: '/x', crumbs: [], entries: [] })).toThrow()
expect(hostCreateDirectoryRequestSchema.parse({ path: '/x', name: 'new' })).toEqual({ path: '/x', name: 'new' })
for (const name of ['', ' ', '.', '..', 'a/b', 'a\\b']) {
expect(() => hostCreateDirectoryRequestSchema.parse({ path: '/x', name })).toThrow()

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/host/directory-picker-browse/README.md
README.md: 632dfec3dac57cac9ea7a02225959fe6e3acf6a0
README.zh.md: 81a1eb53eac0d3b5a1ef8f2f98c4359ef6a4c5fd
README.md: 2f1994100f0fb8fcadae46094267057b3966197e
README.zh.md: a149133a13ca99f176680c68b4931b9673f4aaa8

View File

@@ -4,7 +4,7 @@ English | [中文](README.zh.md)
The **in-app browsing backend** of the [directory-picker seam](../directory-picker/README.md): `BrowseDirectoryPicker` registers `ctx.directoryPicker` with the `browse` capability — one-level directory listing and child-directory creation over Node's stdlib, which already carries the per-OS adaptation. Nothing renders on the host display, so this backend serves remote clients the native backend cannot.
Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject an explicit path that is not fully qualified — relative forms, and on Windows the rooted drive-less forms (`\foo`, `/foo`) and incomplete UNC prefixes (`\\`, `\\server`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md).
Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject an explicit path that is not fully qualified — relative forms, and on Windows the rooted drive-less forms (`\foo`, `/foo`) and incomplete UNC prefixes (`\\`, `\\server`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. One `list` call materializes at most `maxEntries` rows (config, default 1000 — the bound GitHub's web UI applies to directory listings): a cut level keeps the name-sorted head, counts hidden rows against the bound, stops probing once the bound is hit, and reports `truncated: true` so the client can say the level is incomplete. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md).
## Model Experience

View File

@@ -4,7 +4,7 @@
[目录选择 seam](../directory-picker/README.md) 的**应用内浏览后端**`BrowseDirectoryPicker``browse` 能力注册 `ctx.directoryPicker`——基于 Node 标准库(跨 OS 适配本就由它承担)提供单层目录列举与子目录创建。宿主屏幕上不渲染任何东西,因此该后端能服务 native 后端无法触及的远程客户端。
行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/``C:\``list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo``/foo`)与不完整的 UNC 前缀(`\\``\\server`)——报 `directory-unreadable``directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。
行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/``C:\``list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo``/foo`)与不完整的 UNC 前缀(`\\``\\server`)——报 `directory-unreadable``directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。单次 `list` 至多物化 `maxEntries` 行(配置项,默认 1000——GitHub 网页端对目录列举采用的同一上限):被截断的层级保留按名排序的头部、隐藏行计入上限、达到上限即停止探测,并报告 `truncated: true`,供客户端提示层级不完整。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。
## 模型体验

View File

@@ -12,6 +12,8 @@
import { mkdir, readdir, stat } from 'node:fs/promises'
import { homedir } from 'node:os'
import { basename, dirname, join, posix, resolve, win32 } from 'node:path'
import type { Context } from 'cordis'
import z from 'schemastery'
import {
DirectoryPicker, DirectoryPickerError,
} from '@deepseek-ai/dsh-host-directory-picker'
@@ -79,14 +81,35 @@ async function directoryRow(parent: string, name: string, isDirectory: boolean,
return { name, path, hidden: name.startsWith('.') }
}
/** Validated plugin configuration. */
export interface Config {
/** Complete-result bound of one listing level; see {@link BrowseDirectoryPicker.Config}. */
maxEntries: number
}
/** The `ctx.directoryPicker` browse implementation (stable capability object per service life). */
export default class BrowseDirectoryPicker extends DirectoryPicker {
/**
* `maxEntries` bounds the complete listing level a single `list` call may
* materialize and put on the wire: at most this many child-directory rows
* (hidden rows included), with `truncated` flagging a cut level. The
* default follows GitHub's web UI, which truncates directory listings at
* 1,000 entries.
*/
static Config: z<Config> = z.object({
maxEntries: z.natural().min(1).default(1000),
})
private readonly browseCapability: DirectoryPickerCapability = {
kind: 'browse',
list: path => this.list(path),
createDirectory: (path, name) => this.createDirectory(path, name),
}
constructor(ctx: Context, private readonly config: Config) {
super(ctx)
}
/**
* The browse interaction capability.
* @returns the stable `browse` capability object.
@@ -115,10 +138,22 @@ export default class BrowseDirectoryPicker extends DirectoryPicker {
} catch (error: unknown) {
throw new DirectoryPickerError('directory-unreadable', target, `cannot list ${target}: ${messageOf(error)}`)
}
const rows = await Promise.all(names.map(entry => directoryRow(target, entry.name, entry.isDirectory, entry.isSymbolicLink)))
const entries = rows.filter((row): row is DirectoryEntry => row !== null)
.sort((a, b) => a.name.localeCompare(b.name))
return { path: target, home, crumbs: ancestryCrumbs(target), entries }
// Sort candidates before probing so the bound keeps the name-sorted head
// of the level and probing (symlink stat) stops with the bound instead of
// touching every child of an oversized directory.
names.sort((a, b) => a.name.localeCompare(b.name))
const entries: DirectoryEntry[] = []
let truncated = false
for (const entry of names) {
const row = await directoryRow(target, entry.name, entry.isDirectory, entry.isSymbolicLink)
if (row === null) continue
if (entries.length === this.config.maxEntries) {
truncated = true
break
}
entries.push(row)
}
return { path: target, home, crumbs: ancestryCrumbs(target), entries, truncated }
}
private async createDirectory(path: string, name: string): Promise<string> {

View File

@@ -45,6 +45,27 @@ describe('BrowseDirectoryPicker', () => {
expect(listing.entries.map(entry => entry.hidden)).toEqual([true, false, false])
// Every entry path is absolute and host-joined — clients never join segments.
expect(listing.entries.every(entry => entry.path === join(root, entry.name))).toBe(true)
// Well under the default bound: the complete level, not a cut one.
expect(listing.truncated).toBe(false)
})
it('cuts a level at maxEntries keeping the name-sorted head, and flags the cut', async () => {
const ctx = new Context()
const fiber = ctx.plugin(BrowseDirectoryPicker, { maxEntries: 1 })
await fiber.await()
const bounded = ctx.get('directoryPicker')!.capability()
if (bounded.kind !== 'browse') throw new Error('browse backend must advertise the browse capability')
try {
const cut = await bounded.list(root)
expect(cut.entries.map(entry => entry.name)).toEqual(['.hidden-dir'])
expect(cut.truncated).toBe(true)
// Exactly at the bound is complete, not truncated.
const exact = await bounded.list(join(root, 'projects'))
expect(exact.entries.map(entry => entry.name)).toEqual(['harness'])
expect(exact.truncated).toBe(false)
} finally {
await fiber.dispose()
}
})
it('reports the ancestry as jump-target crumbs ending at the listed directory', async () => {

View File

@@ -47,6 +47,12 @@ export interface DirectoryListing {
crumbs: DirectoryEntry[]
/** Direct child directories, name-sorted; symlinks to directories included. */
entries: DirectoryEntry[]
/**
* True when the backend cut `entries` at its complete-result bound: the
* level has more child directories than reported, and the missing rows are
* the name-sorted tail (hidden rows count toward the bound).
*/
truncated: boolean
}
/**
@@ -59,7 +65,8 @@ export interface DirectoryPickerBrowseCapability {
/**
* List one directory level.
* @param path - absolute directory to list; absent lists the home directory.
* @returns the level's listing with ancestry.
* @returns the level's listing with ancestry; backends bound the complete
* result, and a cut level reports `truncated`.
* @throws {DirectoryPickerError} `directory-unreadable` when the target is not fully
* qualified (a wire value must never resolve against the host cwd or, on
* Windows, its current drive) or cannot be listed.