mirror of
https://github.com/deepseek-ai/deepseek-harness
synced 2026-08-15 21:04:50 +00:00
Merge remote-tracking branch 'origin/master' into codex/migrate-to-oxlint
This commit is contained in:
6
packages/host/README.i18n.yaml
Normal file
6
packages/host/README.i18n.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# 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/README.md
|
||||
README.md: d44770f70be16c12f44b78155089e092a3e9bba0
|
||||
README.zh.md: 2b6878b08be6489dcd510a0a0e0f0e833c2a8014
|
||||
15
packages/host/README.md
Normal file
15
packages/host/README.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# host/ — web-GUI host half
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
The host side of the dsh web GUI: the API gateway every client shape shares, and the plain HTTP server it rides on. The browser side lives in [`client/`](../client/README.md); the composed application is [`apps/cli`](../../apps/cli/cordis.yml) serving [`apps/web`](../../apps/web/). All **product** packages.
|
||||
|
||||
| Package | Role | ctx key |
|
||||
|---|---|---|
|
||||
| `apiproxy/` | The shared API gateway: the zero-Node TS wire contract (`src/api/`), the fetch carrier pair (`toFetchHandler` host-side, `AbstractApiClient` client-side), and the host implementation over `ctx.agents`/`ctx.workspace` | `ctx.apiProxy` |
|
||||
| `webserver/` | Plain HTTP route-registration carrier: `node:http` server listening on activation; routes register as named `exact`/`prefix` handlers | `ctx.httpServer` |
|
||||
| `directory-picker/` | Workspace-directory picking seam: discriminated `native`/`browse` capability the gateway's picker RPCs delegate to | `ctx.directoryPicker` |
|
||||
| `directory-picker-native/` | Dual-face native interaction: OS-chooser backend (osascript / PowerShell / Zenity+KDialog, host-display only) + the browser half filling ui-workspace's directory-flow slots | (registers `ctx.directoryPicker`) |
|
||||
| `directory-picker-browse/` | Dual-face browse interaction: listing/creation primitives over Node stdlib (remote-capable) + the browser half rendering the in-app Select Workspace Directory dialog | (registers `ctx.directoryPicker`) |
|
||||
|
||||
`apiproxy` is transport-agnostic by design — it registers no routes; carriers wrap `ctx.apiProxy` themselves. The HTTP carrier route (with its `/api` browser-trust fence) is mounted by [`client/connection`](../client/connection/README.md)'s node half, which is why that package lives in the client group: it owns both ends of the wire.
|
||||
15
packages/host/README.zh.md
Normal file
15
packages/host/README.zh.md
Normal file
@@ -0,0 +1,15 @@
|
||||
# host/ — web GUI 宿主半侧
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
dsh web GUI 的宿主侧:所有客户端形态共用的 API 网关,以及承载它的纯 HTTP 服务器。浏览器侧位于 [`client/`](../client/README.md);组合后的应用是 [`apps/cli`](../../apps/cli/cordis.yml),它负责服务 [`apps/web`](../../apps/web/)。全部为**产品**包。
|
||||
|
||||
| 包 | 角色 | ctx 键 |
|
||||
|---|---|---|
|
||||
| `apiproxy/` | 共享 API 网关:零 Node 依赖的 TS 协议契约(`src/api/`)、fetch 载体对(宿主侧 `toFetchHandler`、客户端侧 `AbstractApiClient`),以及基于 `ctx.agents`/`ctx.workspace` 的宿主实现 | `ctx.apiProxy` |
|
||||
| `webserver/` | 纯 HTTP 路由注册载体:激活即监听的 `node:http` 服务器;路由以命名的 `exact`/`prefix` 处理器注册 | `ctx.httpServer` |
|
||||
| `directory-picker/` | 工作区目录选择 seam:网关的 picker RPC 委托的可辨识 `native`/`browse` 能力 | `ctx.directoryPicker` |
|
||||
| `directory-picker-native/` | 双面原生交互:OS 选择器后端(osascript/PowerShell/Zenity+KDialog,仅宿主屏幕可用)+ 填入 ui-workspace 目录流 slot 的 browser half | (注册 `ctx.directoryPicker`) |
|
||||
| `directory-picker-browse/` | 双面浏览交互:基于 Node 标准库的列举/创建原语(可远程)+ 渲染应用内选择工作区目录对话框的 browser half | (注册 `ctx.directoryPicker`) |
|
||||
|
||||
`apiproxy` 在设计上与传输方式无关——它不注册任何路由;载体自行包装 `ctx.apiProxy`。HTTP 载体路由(连同其 `/api` 浏览器信任栅栏)由 [`client/connection`](../client/connection/README.md) 的 node 半侧挂载,这正是该包住在 client 组的原因:它拥有这条线的两端。
|
||||
@@ -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/apiproxy/README.md
|
||||
README.md: c20887b73b9b9deb278db30d34d84df07257d664
|
||||
README.zh.md: 18a2f97477e5f57127371429b0dd59ba01f04341
|
||||
README.md: ca4471454f5be5d3fcba38ce665d4fb3fbd85e74
|
||||
README.zh.md: 953539e1198a52b2bf7cdd9ca1b0d263cc2ae6f9
|
||||
|
||||
@@ -6,7 +6,7 @@ The API gateway every client shape shares: the TS contract (`src/api/`, zero Nod
|
||||
|
||||
## Contract layer (`/api`)
|
||||
|
||||
Wire messages form a four-quadrant discriminated union — who initiates × request/response — decoupled from the physical channel: `ClientRequest` (POST `/api/<method>` body), `ServerResponse` (that POST's response body), `ServerRequest` (SSE frame), `ClientResponse` (POST `/api/respond` body). Responses always echo the matching request's `rpcId` and never mint a new one. Method parameter/return structures live only in the domain interface signatures (`SessionsApi`, `HostApi`, `EventsApi`); `RpcMethodMap` registers the methods and every other position derives via `RequestPayload<K>`/`ResponseValue<K>`. Zod schemas anchor `satisfies z.ZodType<Wire<T>>` and parse at two levels: envelope first, business payload second, dispatched per method. Business errors ride `RpcResult`'s error branch (`RpcErrorDetailsMap` closes the code set); HTTP status expresses only the carrier.
|
||||
Wire messages form a four-quadrant discriminated union — who initiates × request/response — decoupled from the physical channel: `ClientRequest` (POST `/api/<method>` body), `ServerResponse` (that POST's response body), `ServerRequest` (SSE frame), `ClientResponse` (POST `/api/respond` body). Responses always echo the matching request's `rpcId` and never mint a new one. Method parameter/return structures live only in the domain interface signatures (`SessionsApi`, `HostApi`, `EventsApi`); `RpcMethodMap` registers the methods and every other position derives via `RequestPayload<K>`/`ResponseValue<K>`. Zod schemas anchor `satisfies z.ZodType<Wire<T>>` and parse at two levels: envelope first, business payload second, dispatched per method. Business errors ride `RpcResult`'s error branch (`RpcErrorDetailsMap` closes the code set); HTTP status expresses only the carrier. Every `/api` POST must declare the `application/json` media type — anything else is refused with 415 before dispatch, so cross-site "simple" requests (which browsers send without a CORS preflight) can never execute a side-effectful method blind.
|
||||
|
||||
The layering/protocol decisions are recorded in the [GUI layering and RPC protocol RFC](../../../.agents/notes/implemented/architecture/2026-07-19-gui-layering-and-rpc-protocol.md); the browser-side consumption architecture in the [web client architecture RFC](../../../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.md).
|
||||
|
||||
@@ -18,7 +18,7 @@ Session model routing is a session-domain contract. `session.models` returns the
|
||||
|
||||
Workspace and Session lists are separate reconnect baselines. `workspace.create` creates a unique name or adopts an existing directory, `workspace.delete` removes only the Workspace registration, `session.create` accepts an optional preallocated Session id, and `host/workspace-changed`, `host/workspace-removed`, plus `host/session-added` carry committed increments in either arrival order. Registration deletion preserves the directory and session logs; its Sessions remain in `session.list` and become Ungrouped. `SessionSummary.blank` and the `host/session-added` frame carry the derived zero-events bit: clients hide blank sessions and reuse them per workspace, flip blank on the first `host/session-status(running:true)`, and treat `session.list` as the reconnect authority; cold summaries are never blank because lazy persistence keeps never-appended sessions out of `list()`.
|
||||
|
||||
`host.pickDirectory` opens one native directory picker and returns its selected path, or `null` when the user cancels. Its host implementation invokes platform tools without a shell: `osascript` on macOS, an STA PowerShell `FolderBrowserDialog` on Windows, and Zenity with a KDialog fallback on Linux. The picker function is injectable for tests. This user-paced method is the sole unary call exempt from the default 30-second timeout; caller and connection aborts still propagate to the native process. The browser carrier separately restricts this privileged method to loopback, same-origin requests.
|
||||
Directory picking delegates to the composed `ctx.directoryPicker` backend ([the directory-picker seam](../directory-picker/README.md)); a method called outside the composed capability's kind fails with `directory-picker-unavailable` (the client needs no advertisement — the composed picker package's own client half renders the matching interaction). Under `native`, `host.pickDirectory` opens one native chooser and returns its selected path (`null` on cancel); this user-paced method is the sole unary call exempt from the default 30-second timeout, and caller/connection aborts still propagate to the native process. Under `browse`, `host.listDirectory` returns one name-sorted directory level with breadcrumb ancestry, a `home` anchor, and host-owned `hidden` flags (absent path = home directory), and `host.createDirectory` creates one validated child segment; the backend's typed failures map 1:1 onto the `directory-unreadable`/`directory-exists`/`directory-create-failed` codes. The browser carrier's prefix-wide trust fence (dsh-client-connection) covers all of these like every other `/api` request.
|
||||
|
||||
`host.openPath` opens a filesystem path with the operating system's default application (`open` on macOS, `Invoke-Item` on Windows, `xdg-open` on Linux). The opener is injectable for tests. The browser carrier applies the same loopback, same-origin restriction as `host.pickDirectory`.
|
||||
|
||||
@@ -41,4 +41,4 @@ None; this package neither assembles nor sends a provider request.
|
||||
- **`respond` routing is shipped, but pending-interaction state is host-side work** — the wire shape (POST `/api/respond`, `RpcReceipt`) is final; the pending table that makes late/duplicate answers meaningful lives in `src/api-proxy.ts` and is still minimal (questions only, no approvals).
|
||||
- **Reserved seams stay out of `RpcMethodMap`** — `session.fork`, `prompt.mode: 'inject'`, `task.list`, `host.listModels`, and a describe `hostInstanceId` are documented reservations; an unknown method fails loud at envelope parse rather than getting a not-implemented code.
|
||||
- **No protocol version field** — client and host ship together; `host.describe` gains a version negotiation field only when an independently released client exists.
|
||||
- **Linux native picker requires desktop tooling** — `host.pickDirectory` reports an actionable error when neither Zenity nor KDialog is installed; it does not fall back to a custom or typed-path browser.
|
||||
- **Linux native picker requires desktop tooling** — under the `native` capability, `host.pickDirectory` reports an actionable error when neither Zenity nor KDialog is installed; the browse backend is the composition-level fallback (see the [native backend README](../directory-picker-native/README.md)).
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
## 契约层(`/api`)
|
||||
|
||||
协议消息组成一个四象限可辨识联合:发起方 × 请求/响应,与物理通道解耦。四种消息分别是 `ClientRequest`(POST `/api/<method>` 的请求体)、`ServerResponse`(该 POST 的响应体)、`ServerRequest`(SSE 帧)和 `ClientResponse`(POST `/api/respond` 的请求体)。响应始终回显对应请求的 `rpcId`,绝不签发新值。方法的参数与返回值结构只存在于领域接口签名(`SessionsApi`、`HostApi`、`EventsApi`)中;`RpcMethodMap` 注册方法,其他所有位置均通过 `RequestPayload<K>`/`ResponseValue<K>` 派生。Zod schema 以 `satisfies z.ZodType<Wire<T>>` 锚定类型,并分两层解析:先解析信封,再解析业务载荷,随后按方法分发。业务错误由 `RpcResult` 的错误分支承载(`RpcErrorDetailsMap` 封闭错误码集合);HTTP 状态只表达载体层结果。
|
||||
协议消息组成一个四象限可辨识联合:发起方 × 请求/响应,与物理通道解耦。四种消息分别是 `ClientRequest`(POST `/api/<method>` 的请求体)、`ServerResponse`(该 POST 的响应体)、`ServerRequest`(SSE 帧)和 `ClientResponse`(POST `/api/respond` 的请求体)。响应始终回显对应请求的 `rpcId`,绝不签发新值。方法的参数与返回值结构只存在于领域接口签名(`SessionsApi`、`HostApi`、`EventsApi`)中;`RpcMethodMap` 注册方法,其他所有位置均通过 `RequestPayload<K>`/`ResponseValue<K>` 派生。Zod schema 以 `satisfies z.ZodType<Wire<T>>` 锚定类型,并分两层解析:先解析信封,再解析业务载荷,随后按方法分发。业务错误由 `RpcResult` 的错误分支承载(`RpcErrorDetailsMap` 封闭错误码集合);HTTP 状态只表达载体层结果。每个 `/api` POST 都必须声明 `application/json` 媒体类型——否则在分发前即以 415 拒绝,因此跨站"简单请求"(浏览器不经 CORS 预检就会发出)永远无法盲目执行有副作用的方法。
|
||||
|
||||
分层与协议决策记录在 [GUI 分层与 RPC 协议 RFC](../../../.agents/notes/implemented/architecture/2026-07-19-gui-layering-and-rpc-protocol.md)中;浏览器侧消费架构记录在 [Web 客户端架构 RFC](../../../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.md)中。
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
|
||||
Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.create` 会创建唯一名称或接纳现有目录,`workspace.delete` 只移除 Workspace 注册记录,`session.create` 接受可选的预分配 Session id,`host/workspace-changed`、`host/workspace-removed` 与 `host/session-added` 则以任意到达顺序携带已提交的增量。删除注册记录会保留目录和会话日志;相关 Session 仍留在 `session.list` 中,并进入 Ungrouped。`SessionSummary.blank` 与 `host/session-added` 帧携带派生的零事件位:客户端隐藏空白会话并按 workspace 复用它们,在首个 `host/session-status(running:true)` 时翻转 blank,并以 `session.list` 作为重连权威;冷会话摘要永远不是空白:惰性持久化让从未追加过事件的会话根本不出现在 `list()` 中。
|
||||
|
||||
`host.pickDirectory` 会打开一个原生目录选择器并返回选中的路径;用户取消时返回 `null`。宿主实现不经 shell 调用平台工具:macOS 使用 `osascript`,Windows 使用以 STA 模式运行的 PowerShell `FolderBrowserDialog`,Linux 使用 Zenity,并以 KDialog 作为回退。选择器函数可在测试中注入。该方法需等待用户完成操作,是唯一不受默认 30 秒超时限制的一元调用;调用方发出的中止信号和连接中止仍会传播至原生进程。浏览器载体另行将这一特权方法限制为仅接受来自回环地址的同源请求。
|
||||
目录选择委托给组合的 `ctx.directoryPicker` 后端([目录选择 seam](../directory-picker/README.md));调用组合能力 kind 之外的方法会以 `directory-picker-unavailable` 失败(客户端不需要广播——组合的选择器包自己的 client half 渲染匹配的交互)。在 `native` 下,`host.pickDirectory` 打开一个原生选择器并返回选中路径(取消为 `null`);该方法需等待用户完成操作,是唯一不受默认 30 秒超时限制的一元调用,调用方与连接的中止仍会传播至原生进程。在 `browse` 下,`host.listDirectory` 返回一个按名称排序的目录层级,携带面包屑祖先链、`home` 锚点与宿主判定的 `hidden` 标志(不带路径即家目录),`host.createDirectory` 创建一个经校验的子段;后端的类型化失败 1:1 映射为 `directory-unreadable`/`directory-exists`/`directory-create-failed` 错误码。浏览器载体的前缀级信任栅栏(dsh-client-connection)像覆盖其他所有 `/api` 请求一样覆盖上述全部方法。
|
||||
|
||||
`host.openPath` 会用操作系统的默认应用打开一个文件系统路径(macOS 为 `open`,Windows 为 `Invoke-Item`,Linux 为 `xdg-open`)。打开器可在测试中注入。浏览器载体对其施加与 `host.pickDirectory` 相同的回环、同源限制。
|
||||
|
||||
@@ -41,4 +41,4 @@ Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.cr
|
||||
- **`respond` 路由已经发布,但待处理交互状态仍属宿主侧工作**:协议形状(POST `/api/respond`、`RpcReceipt`)已经定型;使延迟或重复回答具有明确语义的待处理表位于 `src/api-proxy.ts`,目前仍很精简(只支持问题,不支持审批)。
|
||||
- **预留 seam 不进入 `RpcMethodMap`**:`session.fork`、`prompt.mode: 'inject'`、`task.list`、`host.listModels` 和描述字段 `hostInstanceId` 都是已记录的预留项;未知方法会在信封解析时直接失败,而不会返回「尚未实现」错误码。
|
||||
- **没有协议版本字段**:客户端与宿主一同发布;只有出现独立发布的客户端后,`host.describe` 才会增加版本协商字段。
|
||||
- **Linux 原生选择器依赖桌面工具**:Zenity 和 KDialog 均未安装时,`host.pickDirectory` 会给出包含解决建议的错误提示;它不会回退到自定义目录浏览器,也不会要求用户手动输入路径。
|
||||
- **Linux 原生选择器依赖桌面工具**:在 `native` 能力下,Zenity 和 KDialog 均未安装时,`host.pickDirectory` 会给出包含解决建议的错误提示;组合层面的回退是 browse 后端(见 [native 后端 README](../directory-picker-native/README.md))。
|
||||
|
||||
@@ -44,7 +44,9 @@
|
||||
"@deepseek-ai/dsh-brand": "workspace:^",
|
||||
"@deepseek-ai/dsh-commands": "workspace:^",
|
||||
"@deepseek-ai/dsh-goal": "workspace:^",
|
||||
"@deepseek-ai/dsh-host-directory-picker": "workspace:^",
|
||||
"@deepseek-ai/dsh-llm": "workspace:^",
|
||||
"@deepseek-ai/dsh-native-command": "workspace:^",
|
||||
"@deepseek-ai/dsh-session": "workspace:^",
|
||||
"@deepseek-ai/dsh-session-persistence": "workspace:^",
|
||||
"@deepseek-ai/dsh-session-projection": "workspace:^",
|
||||
|
||||
@@ -38,6 +38,12 @@ import type { GoalRef as CoreGoalRef } from '@deepseek-ai/dsh-goal'
|
||||
// Type-only edges: resolve `ctx.get('commands')`, the `commands/change` event, and `ctx.get('skills')`.
|
||||
import type {} from '@deepseek-ai/dsh-commands'
|
||||
import type {} from '@deepseek-ai/dsh-skill'
|
||||
import type { CallId } from '@deepseek-ai/dsh-llm/brand'
|
||||
import type { ApprovalOutcome, ApprovalRequestId } from '@deepseek-ai/dsh-user-approval'
|
||||
// Side-effect type import: resolves the `approval/request` waterfall and
|
||||
// `ctx.get('approval')` without a value dependency on the seam (optional composition).
|
||||
import type {} from '@deepseek-ai/dsh-user-approval'
|
||||
import { approvalResponsePayloadSchema } from './api/approvals.schema.ts'
|
||||
import { questionResponsePayloadSchema } from './api/questions.schema.ts'
|
||||
import type { ClientResponse, RpcError, RpcReceipt, RpcRequest, RpcResponse } from './api/rpc.ts'
|
||||
import { RpcId } from './api/rpc.ts'
|
||||
@@ -45,7 +51,7 @@ import type {
|
||||
AskUserQuestionAnswer, AskUserQuestionItem, AskUserQuestionRequest,
|
||||
} from '@deepseek-ai/dsh-user-interaction'
|
||||
import { UserInteractionError } from '@deepseek-ai/dsh-user-interaction'
|
||||
import { pickNativeDirectory } from './native-directory-picker.ts'
|
||||
import { DirectoryPickerError } from '@deepseek-ai/dsh-host-directory-picker'
|
||||
import { openNativePath } from './native-path-opener.ts'
|
||||
|
||||
/** Page size when history is called without maxMessages. */
|
||||
@@ -128,9 +134,9 @@ class FrameQueue<F> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Server-side frame mint: pure pushes get a fresh rpcId per frame (stable ids
|
||||
* for answerable frames belong to the approval/question registry, absent in
|
||||
* this minimal version).
|
||||
* Server-side frame mint: pure pushes get a fresh rpcId per frame (answerable
|
||||
* frames — approval/question requested — mint their stable id in their
|
||||
* pending registries instead).
|
||||
*/
|
||||
function frame<F>(payload: F): RpcRequest<F> {
|
||||
return { rpcId: RpcId(randomUUID()), payload }
|
||||
@@ -195,6 +201,14 @@ async function summarizeCold(persistence: SessionPersistence, meta: SessionHeade
|
||||
}
|
||||
}
|
||||
|
||||
/** Map a browse-primitive failure onto the wire error vocabulary (unknown throws stay internal). */
|
||||
function directoryError(error: unknown): RpcError {
|
||||
if (error instanceof DirectoryPickerError) {
|
||||
return { code: error.code, message: error.message, details: { path: error.path } }
|
||||
}
|
||||
return { code: 'internal', message: error instanceof Error ? error.message : String(error), details: {} }
|
||||
}
|
||||
|
||||
/** Resolved Host routing and project-directory defaults consumed by the API implementation. */
|
||||
export interface ApiProxyDefaults {
|
||||
provider: string
|
||||
@@ -203,14 +217,42 @@ export interface ApiProxyDefaults {
|
||||
cwd: string
|
||||
/** Parent directory for name-created workspaces. */
|
||||
workspaceRoot: string
|
||||
/** Native single-directory picker; injectable for carrier tests. */
|
||||
pickDirectory?: (signal: AbortSignal) => Promise<string | null>
|
||||
/** Native open-with-default-application; injectable for carrier tests. */
|
||||
openPath?: (path: string, signal: AbortSignal) => Promise<void>
|
||||
}
|
||||
|
||||
/** The tool/call payload fields the presenter path reads. */
|
||||
interface ToolCallData { callId: string; name: string; arguments: string }
|
||||
/**
|
||||
* One outstanding approval question: the stable server-request id, the frame
|
||||
* material replayed to late mux subscribers, and the resolver that settles the
|
||||
* answerer's promise back into `ctx.approval`.
|
||||
*/
|
||||
interface PendingApproval {
|
||||
rpcId: RpcId
|
||||
sessionId: SessionId
|
||||
approvalId: ApprovalRequestId
|
||||
toolName: string
|
||||
callId?: CallId
|
||||
reason?: string
|
||||
resolve(outcome: ApprovalOutcome): void
|
||||
}
|
||||
|
||||
/** Project a pending entry into its answerable mux frame (initial push and mux-open replay share it). */
|
||||
function requestedFrame(pending: PendingApproval): RpcRequest<MuxFrame> {
|
||||
return {
|
||||
rpcId: pending.rpcId,
|
||||
payload: {
|
||||
type: 'approval/requested',
|
||||
sessionId: pending.sessionId,
|
||||
approvalId: pending.approvalId,
|
||||
toolName: pending.toolName,
|
||||
...pending.callId === undefined ? {} : { callId: pending.callId },
|
||||
...pending.reason === undefined ? {} : { reason: pending.reason },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** One host-owned question wait, addressed by the stable server-request id. */
|
||||
interface PendingQuestion {
|
||||
rpcId: RpcId
|
||||
@@ -410,6 +452,7 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro
|
||||
/** Serializes path ownership checks with record creation across spellings. */
|
||||
let workspaceCreationChain = Promise.resolve()
|
||||
const pendingQuestions = new Map<RpcId, PendingQuestion>()
|
||||
const pendingApprovals = new Map<RpcId, PendingApproval>()
|
||||
const muxQueues = new Set<FrameQueue<RpcRequest<MuxFrame>>>()
|
||||
|
||||
/**
|
||||
@@ -558,6 +601,90 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro
|
||||
}
|
||||
}, 'api-proxy: user-interaction provider')
|
||||
|
||||
// --- Approval pending registry ------------------------------------------
|
||||
// The proxy is the approval channel for every agent this host owns: an ask
|
||||
// through `ctx.approval` becomes an answerable server-request on the mux
|
||||
// stream (stable rpcId), settled by POST /api/respond. The entry survives
|
||||
// client disconnects — mux-open replays still-pending requested frames with
|
||||
// the same rpcId (the refresh-recovery baseline) — and withdraws on the
|
||||
// ask's own abort signal (turn cancel), pushing `cancelled` to subscribers.
|
||||
if (ctx.get('approval') !== undefined) {
|
||||
// Teardown parity with the question provider above: a gateway disposed
|
||||
// while approvals are pending settles every entry as 'cancelled' (the
|
||||
// service's fail-closed vocabulary), so no ask promise dangles past the
|
||||
// proxy's lifetime and subscribers see the withdrawal.
|
||||
ctx.effect(() => () => {
|
||||
for (const pending of [...pendingApprovals.values()]) pending.resolve('cancelled')
|
||||
}, 'api-proxy: approval registry teardown')
|
||||
ctx.on('approval/request', (req, next) => {
|
||||
// Dispatch rides a microtask behind the service's own signal check: an
|
||||
// abort landing in that window would register the abort listener AFTER
|
||||
// the signal fired — never invoked, entry pending forever, zombie frame
|
||||
// on every mux replay. Settle synchronously instead of publishing.
|
||||
if (req.signal?.aborted === true) return Promise.resolve<ApprovalOutcome>('cancelled')
|
||||
// The audit pair `approval/asked` is already appended by the service
|
||||
// before dispatch, but dispatch rides a microtask: parallel tool calls
|
||||
// can append several asked events before any answerer runs. THIS
|
||||
// request's event is therefore the newest asked event that is still
|
||||
// undecided, unclaimed by another pending entry, and — when the ask
|
||||
// names a call — carries the same callId.
|
||||
const events = req.agent.session.events
|
||||
const claimed = new Set<ApprovalRequestId>()
|
||||
for (const entry of pendingApprovals.values()) claimed.add(entry.approvalId)
|
||||
const decided = new Set<ApprovalRequestId>()
|
||||
let approvalId: ApprovalRequestId | undefined
|
||||
for (let i = events.length - 1; i >= 0; i -= 1) {
|
||||
const event = events[i] as SessionEvent
|
||||
if (event.type === 'approval/decided') {
|
||||
decided.add(event.data.id)
|
||||
} else if (event.type === 'approval/asked') {
|
||||
if (decided.has(event.data.id) || claimed.has(event.data.id)) continue
|
||||
// Symmetric pairing: a callId-bearing ask only takes its own call's
|
||||
// record, and a callId-less ask only takes a callId-less record —
|
||||
// so neither shape can steal the other's audit id under parallel
|
||||
// asks. (Today every producer — the tool executor — passes callId;
|
||||
// the callId-less arm guards any future non-tool asker.)
|
||||
if ((req.callId ?? null) !== (event.data.callId ?? null)) continue
|
||||
approvalId = event.data.id
|
||||
break
|
||||
}
|
||||
}
|
||||
// No asked event means the request bypassed the service's audit path —
|
||||
// not this channel's question; delegate to the fail-closed default.
|
||||
if (approvalId === undefined) return next()
|
||||
const id = approvalId
|
||||
return new Promise<ApprovalOutcome>((resolve) => {
|
||||
const settle = (outcome: ApprovalOutcome): void => {
|
||||
/* v8 ignore next 3 -- defensive double-settle guard: respond() routes
|
||||
through the pending table (a settled id is not-pending before it can
|
||||
re-settle) and the first settle removes the abort listener, so no
|
||||
reachable path settles twice; kept against future settle callers. */
|
||||
if (!pendingApprovals.delete(pending.rpcId)) return
|
||||
req.signal?.removeEventListener('abort', onAbort)
|
||||
broadcast({ type: 'approval/resolved', sessionId: pending.sessionId, approvalId: id, outcome })
|
||||
// A cancelled ask was already settled by the service's own signal
|
||||
// race, which discards this late resolution; resolving is a no-op
|
||||
// there and keeps this promise from dangling forever.
|
||||
resolve(outcome)
|
||||
}
|
||||
const onAbort = (): void => { settle('cancelled') }
|
||||
const pending: PendingApproval = {
|
||||
rpcId: RpcId(randomUUID()),
|
||||
sessionId: req.agent.session.id,
|
||||
approvalId: id,
|
||||
toolName: req.toolName,
|
||||
...req.callId === undefined ? {} : { callId: req.callId },
|
||||
...req.reason === undefined ? {} : { reason: req.reason },
|
||||
resolve: settle,
|
||||
}
|
||||
pendingApprovals.set(pending.rpcId, pending)
|
||||
req.signal?.addEventListener('abort', onAbort, { once: true })
|
||||
const envelope = requestedFrame(pending)
|
||||
for (const queue of muxQueues) queue.push(envelope)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Gate the cold path on the store: an id absent from it, or naming a legacy
|
||||
* log without a cwd (pre-release stance: not served, no compatibility), is
|
||||
@@ -1090,8 +1217,16 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro
|
||||
},
|
||||
|
||||
async pickDirectory(request, signal) {
|
||||
const capability = ctx.directoryPicker.capability()
|
||||
if (capability.kind !== 'native') {
|
||||
return err(request, {
|
||||
code: 'directory-picker-unavailable',
|
||||
message: `host.pickDirectory needs the native capability; the composed picker serves "${capability.kind}"`,
|
||||
details: { capability: capability.kind },
|
||||
})
|
||||
}
|
||||
try {
|
||||
const path = await (defaults.pickDirectory ?? pickNativeDirectory)(signal)
|
||||
const path = await capability.pick(signal)
|
||||
return ok(request, { path })
|
||||
} catch (error: unknown) {
|
||||
if (signal.aborted) {
|
||||
@@ -1109,6 +1244,45 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro
|
||||
}
|
||||
},
|
||||
|
||||
async listDirectory(request, signal) {
|
||||
const capability = ctx.directoryPicker.capability()
|
||||
if (capability.kind !== 'browse') {
|
||||
return err(request, {
|
||||
code: 'directory-picker-unavailable',
|
||||
message: `host.listDirectory needs the browse capability; the composed picker serves "${capability.kind}"`,
|
||||
details: { capability: capability.kind },
|
||||
})
|
||||
}
|
||||
try {
|
||||
// The carrier's signal follows the caller: a disconnect or timeout
|
||||
// stops the backend's directory scan instead of outliving it.
|
||||
return ok(request, await capability.list(request.payload.path, signal))
|
||||
} catch (error: unknown) {
|
||||
// An abort is the caller's own timeout/disconnect, not a server
|
||||
// failure — same code pickDirectory and command.execute report.
|
||||
if (signal.aborted) {
|
||||
return err(request, { code: 'cancelled', message: 'directory listing was aborted', details: {} })
|
||||
}
|
||||
return err(request, directoryError(error))
|
||||
}
|
||||
},
|
||||
|
||||
async createDirectory(request) {
|
||||
const capability = ctx.directoryPicker.capability()
|
||||
if (capability.kind !== 'browse') {
|
||||
return err(request, {
|
||||
code: 'directory-picker-unavailable',
|
||||
message: `host.createDirectory needs the browse capability; the composed picker serves "${capability.kind}"`,
|
||||
details: { capability: capability.kind },
|
||||
})
|
||||
}
|
||||
try {
|
||||
return ok(request, { path: await capability.createDirectory(request.payload.path, request.payload.name) })
|
||||
} catch (error: unknown) {
|
||||
return err(request, directoryError(error))
|
||||
}
|
||||
},
|
||||
|
||||
async openPath(request, signal) {
|
||||
try {
|
||||
const open = defaults.openPath
|
||||
@@ -1281,6 +1455,9 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro
|
||||
},
|
||||
})
|
||||
}
|
||||
// Refresh recovery: still-pending approval questions replay with their
|
||||
// stable rpcId so a reconnecting client can still answer them.
|
||||
for (const pending of pendingApprovals.values()) queue.push(requestedFrame(pending))
|
||||
// Queue snapshot baseline (pendingQuestions precedent): frames replayed
|
||||
// in arrival order per session; a reconnecting client rebuilds its
|
||||
// queue view from these alone.
|
||||
@@ -1398,6 +1575,20 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro
|
||||
},
|
||||
|
||||
respond(message: ClientResponse): Promise<RpcReceipt> {
|
||||
// Route by the echoed rpcId (the wire correlation): approvals first,
|
||||
// then questions — the two registries share one id space of UUIDs.
|
||||
const approval = pendingApprovals.get(message.rpcId)
|
||||
if (approval !== undefined) {
|
||||
if (!message.result.ok) return Promise.resolve({ accepted: false, reason: 'bad-response' })
|
||||
const parsed = approvalResponsePayloadSchema.safeParse(message.result.value)
|
||||
// The payload's audit correlation must match the entry the rpcId routed
|
||||
// to — a mismatched answer is malformed, not merely late.
|
||||
if (!parsed.success || parsed.data.approvalId !== approval.approvalId || parsed.data.sessionId !== approval.sessionId) {
|
||||
return Promise.resolve({ accepted: false, reason: 'bad-response' })
|
||||
}
|
||||
approval.resolve(parsed.data.outcome)
|
||||
return Promise.resolve({ accepted: true })
|
||||
}
|
||||
const pending = pendingQuestions.get(message.rpcId)
|
||||
if (pending === undefined) return Promise.resolve({ accepted: false, reason: 'not-pending' })
|
||||
if (!message.result.ok) {
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
*/
|
||||
|
||||
import { z } from 'zod'
|
||||
import type { DirectoryEntry } from './host.ts'
|
||||
import type { RequestPayload, ResponseValue } from './rpc-map.ts'
|
||||
import type { Wire } from './rpc.schema.ts'
|
||||
|
||||
@@ -16,6 +17,8 @@ export const hostDescribeValueSchema = z.object({
|
||||
provider: z.string().optional(),
|
||||
model: z.string().optional(),
|
||||
attachedSessions: z.number().int().nonnegative(),
|
||||
// Open string, not a literal union: unknown kinds must survive the wire so
|
||||
// a merge-added capability can advertise (the client hides the affordance).
|
||||
}) satisfies z.ZodType<Wire<ResponseValue<'host.describe'>>>
|
||||
|
||||
/** host.pickDirectory request payload (empty object literal). */
|
||||
@@ -26,6 +29,41 @@ export const hostPickDirectoryValueSchema = z.object({
|
||||
path: z.string().nullable(),
|
||||
}) satisfies z.ZodType<Wire<ResponseValue<'host.pickDirectory'>>>
|
||||
|
||||
/** Directory row shared by listing entries and breadcrumb crumbs. */
|
||||
export const directoryEntrySchema = z.object({
|
||||
name: z.string(),
|
||||
path: z.string(),
|
||||
hidden: z.boolean(),
|
||||
}) satisfies z.ZodType<Wire<DirectoryEntry>>
|
||||
|
||||
/** host.listDirectory request payload; an absent path lists the home directory. */
|
||||
export const hostListDirectoryRequestSchema = z.object({
|
||||
path: z.string().optional(),
|
||||
}) satisfies z.ZodType<Wire<RequestPayload<'host.listDirectory'>>>
|
||||
|
||||
/** host.listDirectory response value. */
|
||||
export const hostListDirectoryValueSchema = z.object({
|
||||
path: z.string(),
|
||||
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. */
|
||||
export const hostCreateDirectoryRequestSchema = z.object({
|
||||
path: z.string(),
|
||||
name: z.string(),
|
||||
}).refine(
|
||||
payload => payload.name.trim() !== '' && payload.name !== '.' && payload.name !== '..'
|
||||
&& !/[/\\]/.test(payload.name),
|
||||
{ message: 'host.createDirectory requires a single non-blank path segment name' },
|
||||
) satisfies z.ZodType<Wire<RequestPayload<'host.createDirectory'>>>
|
||||
|
||||
/** host.createDirectory response value: the created directory's absolute path. */
|
||||
export const hostCreateDirectoryValueSchema = z.object({
|
||||
path: z.string(),
|
||||
}) satisfies z.ZodType<Wire<ResponseValue<'host.createDirectory'>>>
|
||||
/** host.openPath request payload. */
|
||||
export const hostOpenPathRequestSchema = z.object({
|
||||
path: z.string().min(1),
|
||||
|
||||
@@ -5,6 +5,33 @@
|
||||
|
||||
import type { RpcRequest, RpcResponse } from './rpc.ts'
|
||||
|
||||
/** One directory row of a listing: a child entry or a breadcrumb ancestor. */
|
||||
export interface DirectoryEntry {
|
||||
/** Base name shown in a browser row (a root crumb carries its full path). */
|
||||
name: string
|
||||
/** Absolute host path — the client never joins path segments itself. */
|
||||
path: string
|
||||
/** Hidden by the host platform's convention (dot-prefixed on POSIX); the client owns whether to show it. */
|
||||
hidden: boolean
|
||||
}
|
||||
|
||||
/** host.listDirectory response value: one directory level plus its ancestry. */
|
||||
export interface DirectoryListing {
|
||||
/** Absolute path of the listed directory. */
|
||||
path: string
|
||||
/** The host account's home directory (breadcrumb "Home" rooting). */
|
||||
home: string
|
||||
/**
|
||||
* Ancestor chain from the filesystem root to the listed directory
|
||||
* inclusive; every crumb is a jump target (crumb `hidden` is always false).
|
||||
*/
|
||||
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. */
|
||||
export interface HostApi {
|
||||
/**
|
||||
@@ -13,7 +40,7 @@ export interface HostApi {
|
||||
* directory (root for session persistence and tool execution); provider/model = the defaults
|
||||
* applied when a new agent doesn't specify them explicitly, absent when the host configures
|
||||
* no explicit default (the adapter falls back internally);
|
||||
* attachedSessions = count of currently attached sessions (those with a live agent).
|
||||
* attachedSessions = count of currently attached sessions (those with a live agent);
|
||||
*/
|
||||
describe(request: RpcRequest<{}>): Promise<RpcResponse<{
|
||||
version: string
|
||||
@@ -23,16 +50,42 @@ export interface HostApi {
|
||||
attachedSessions: number
|
||||
}>>
|
||||
|
||||
/** Open the operating system's single-directory picker; cancellation returns null. */
|
||||
/**
|
||||
* Open the operating system's single-directory picker; cancellation returns
|
||||
* null. Only served under the `native` capability.
|
||||
*/
|
||||
pickDirectory(
|
||||
request: RpcRequest<{}>,
|
||||
signal: AbortSignal,
|
||||
): Promise<RpcResponse<{ path: string | null }>>
|
||||
|
||||
/**
|
||||
* List one directory level for the in-app browser; an absent path lists the
|
||||
* host account's home directory. Only served under the `browse` capability;
|
||||
* unreadable or missing targets fail with `directory-unreadable`. The
|
||||
* carrier's request signal follows the caller, stopping the backend's scan
|
||||
* on disconnect or timeout.
|
||||
*/
|
||||
listDirectory(
|
||||
request: RpcRequest<{ path?: string }>,
|
||||
signal: AbortSignal,
|
||||
): Promise<RpcResponse<DirectoryListing>>
|
||||
|
||||
/**
|
||||
* Create one child directory under an existing parent (the browser's
|
||||
* "New folder"). Only served under the `browse` capability; an existing
|
||||
* child fails with `directory-exists`, every other filesystem failure with
|
||||
* `directory-create-failed`.
|
||||
*/
|
||||
createDirectory(
|
||||
request: RpcRequest<{ path: string; name: string }>,
|
||||
): Promise<RpcResponse<{ path: string }>>
|
||||
|
||||
/**
|
||||
* Open a filesystem path with the operating system's default application
|
||||
* (Finder / Explorer / xdg-open hand-off). The browser carrier restricts this
|
||||
* privileged method to loopback, same-origin requests.
|
||||
* (Finder / Explorer / xdg-open hand-off). The browser carrier's
|
||||
* prefix-wide trust fence covers this privileged method like every other
|
||||
* `/api` request.
|
||||
*/
|
||||
openPath(
|
||||
request: RpcRequest<{ path: string }>,
|
||||
|
||||
@@ -31,7 +31,7 @@ export type {
|
||||
HistoryEntry, ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning,
|
||||
ModelReasoningEffort, ModelTarget, SessionModels, SessionProjectionsBlock, SessionsApi, SessionSummary,
|
||||
} from './sessions.ts'
|
||||
export type { HostApi } from './host.ts'
|
||||
export type { DirectoryEntry, DirectoryListing, HostApi } from './host.ts'
|
||||
export type { WorkspaceApi, WorkspaceId, WorkspaceView } from './workspace.ts'
|
||||
export type { CommandsApi, CommandDescriptor } from './commands.ts'
|
||||
export type { SkillsApi, SkillEntry } from './skills.ts'
|
||||
|
||||
@@ -27,6 +27,8 @@ export interface RpcMethodMap {
|
||||
'session.cancel': SessionsApi['cancel']
|
||||
'host.describe': HostApi['describe']
|
||||
'host.pickDirectory': HostApi['pickDirectory']
|
||||
'host.listDirectory': HostApi['listDirectory']
|
||||
'host.createDirectory': HostApi['createDirectory']
|
||||
'host.openPath': HostApi['openPath']
|
||||
'workspace.list': WorkspaceApi['list']
|
||||
'workspace.create': WorkspaceApi['create']
|
||||
|
||||
@@ -42,6 +42,10 @@ export const rpcErrorSchema: z.ZodType<RpcError> = z.discriminatedUnion('code',
|
||||
z.object({ code: z.literal('workspace-invalid-path'), message: z.string(), details: z.object({ path: z.string() }) }),
|
||||
z.object({ code: z.literal('workspace-name-conflict'), message: z.string(), details: z.object({ name: z.string() }) }),
|
||||
z.object({ code: z.literal('workspace-move-invalid'), message: z.string(), details: z.object({ workspaceId: z.string(), sessionId: z.string(), beforeSessionId: z.string().optional() }) }),
|
||||
z.object({ code: z.literal('directory-unreadable'), message: z.string(), details: z.object({ path: z.string() }) }),
|
||||
z.object({ code: z.literal('directory-exists'), message: z.string(), details: z.object({ path: z.string() }) }),
|
||||
z.object({ code: z.literal('directory-create-failed'), message: z.string(), details: z.object({ path: z.string() }) }),
|
||||
z.object({ code: z.literal('directory-picker-unavailable'), message: z.string(), details: z.object({ capability: z.string() }) }),
|
||||
z.object({ code: z.literal('agent-busy'), message: z.string(), details: z.object({ reason: z.string() }) }),
|
||||
z.object({ code: z.literal('command-error'), message: z.string(), details: z.object({}) }),
|
||||
z.object({ code: z.literal('unknown-command'), message: z.string(), details: z.object({}) }),
|
||||
|
||||
@@ -39,6 +39,10 @@ export interface RpcErrorDetailsMap {
|
||||
'workspace-invalid-path': { path: string }
|
||||
'workspace-name-conflict': { name: string }
|
||||
'workspace-move-invalid': { workspaceId: string; sessionId: SessionId; beforeSessionId?: SessionId }
|
||||
'directory-unreadable': { path: string }
|
||||
'directory-exists': { path: string }
|
||||
'directory-create-failed': { path: string }
|
||||
'directory-picker-unavailable': { capability: string }
|
||||
'agent-busy': { reason: string }
|
||||
/** A known slash command reported a usage/state error; the message is the command's own text. */
|
||||
'command-error': {}
|
||||
|
||||
@@ -211,3 +211,4 @@ export const sessionCancelRequestSchema = z.object({
|
||||
export const sessionCancelValueSchema = z.object({
|
||||
accepted: z.literal(true),
|
||||
}) satisfies z.ZodType<Wire<ResponseValue<'session.cancel'>>>
|
||||
|
||||
|
||||
@@ -221,4 +221,5 @@ export interface SessionsApi {
|
||||
|
||||
/** Stops: clears both FIFOs + aborts the current step (1:1 with agent.cancel). */
|
||||
cancel(request: RpcRequest<{ sessionId: SessionId }>): Promise<RpcResponse<{ accepted: true }>>
|
||||
|
||||
}
|
||||
|
||||
@@ -14,7 +14,8 @@ import type { Wire } from '../api/rpc.schema.ts'
|
||||
import { rpcReceiptSchema, serverRequestSchema, serverResponseSchema } from '../api/rpc.schema.ts'
|
||||
import { hostFrameSchema, muxFrameSchema } from '../api/events.schema.ts'
|
||||
import {
|
||||
hostDescribeValueSchema, hostOpenPathValueSchema, hostPickDirectoryValueSchema,
|
||||
hostCreateDirectoryValueSchema, hostDescribeValueSchema,
|
||||
hostListDirectoryValueSchema, hostOpenPathValueSchema, hostPickDirectoryValueSchema,
|
||||
} from '../api/host.schema.ts'
|
||||
import {
|
||||
sessionCancelValueSchema,
|
||||
@@ -71,6 +72,8 @@ export interface IApiClient {
|
||||
host: {
|
||||
describe(payload: RequestPayload<'host.describe'>, signal?: AbortSignal): Promise<RpcResponse<ResponseValue<'host.describe'>>>
|
||||
pickDirectory(payload: RequestPayload<'host.pickDirectory'>, signal?: AbortSignal): Promise<RpcResponse<ResponseValue<'host.pickDirectory'>>>
|
||||
listDirectory(payload: RequestPayload<'host.listDirectory'>, signal?: AbortSignal): Promise<RpcResponse<ResponseValue<'host.listDirectory'>>>
|
||||
createDirectory(payload: RequestPayload<'host.createDirectory'>, signal?: AbortSignal): Promise<RpcResponse<ResponseValue<'host.createDirectory'>>>
|
||||
openPath(payload: RequestPayload<'host.openPath'>, signal?: AbortSignal): Promise<RpcResponse<ResponseValue<'host.openPath'>>>
|
||||
}
|
||||
workspace: {
|
||||
@@ -117,6 +120,8 @@ const UNARY_VALUE_SCHEMAS: { [K in keyof RpcMethodMap]: z.ZodType<Wire<ResponseV
|
||||
'session.cancel': sessionCancelValueSchema,
|
||||
'host.describe': hostDescribeValueSchema,
|
||||
'host.pickDirectory': hostPickDirectoryValueSchema,
|
||||
'host.listDirectory': hostListDirectoryValueSchema,
|
||||
'host.createDirectory': hostCreateDirectoryValueSchema,
|
||||
'host.openPath': hostOpenPathValueSchema,
|
||||
'workspace.list': workspaceListValueSchema,
|
||||
'workspace.create': workspaceCreateValueSchema,
|
||||
@@ -331,6 +336,8 @@ export abstract class AbstractApiClient implements IApiClient {
|
||||
// A native system dialog is user-paced and may legitimately stay open
|
||||
// longer than the normal unary deadline. Caller/connection aborts remain.
|
||||
pickDirectory: (payload, signal) => this.callUnary('host.pickDirectory', payload, signal, false),
|
||||
listDirectory: (payload, signal) => this.callUnary('host.listDirectory', payload, signal),
|
||||
createDirectory: (payload, signal) => this.callUnary('host.createDirectory', payload, signal),
|
||||
openPath: (payload, signal) => this.callUnary('host.openPath', payload, signal),
|
||||
}
|
||||
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
* Server side of the fetch carrier: maps an ApiProxy onto a pure
|
||||
* WHATWG Request->Response function. Two-level parse: full form (type/rpcId/method +
|
||||
* path==method) -> payload dispatched per method. HTTP status expresses only the carrier
|
||||
* (404 unknown path / 400 non-JSON body / 500 handler crash); business errors are always
|
||||
* 200 + ServerResponse.
|
||||
* (404 unknown path / 415 non-JSON media type / 400 non-JSON body / 500 handler crash);
|
||||
* business errors are always 200 + ServerResponse.
|
||||
*/
|
||||
|
||||
import { randomUUID } from 'node:crypto'
|
||||
@@ -24,7 +24,9 @@ import {
|
||||
sessionSelectModelRequestSchema,
|
||||
} from '../api/sessions.schema.ts'
|
||||
import {
|
||||
hostDescribeRequestSchema, hostOpenPathRequestSchema, hostPickDirectoryRequestSchema,
|
||||
hostCreateDirectoryRequestSchema, hostDescribeRequestSchema,
|
||||
hostListDirectoryRequestSchema, hostOpenPathRequestSchema,
|
||||
hostPickDirectoryRequestSchema,
|
||||
} from '../api/host.schema.ts'
|
||||
import {
|
||||
workspaceCreateRequestSchema,
|
||||
@@ -70,6 +72,8 @@ const UNARY_ROUTES: UnaryRoutes = {
|
||||
'session.cancel': { schema: sessionCancelRequestSchema, invoke: (api, r) => api.sessions.cancel(r) },
|
||||
'host.describe': { schema: hostDescribeRequestSchema, invoke: (api, r) => api.host.describe(r) },
|
||||
'host.pickDirectory': { schema: hostPickDirectoryRequestSchema, invoke: (api, r, signal) => api.host.pickDirectory(r, signal) },
|
||||
'host.listDirectory': { schema: hostListDirectoryRequestSchema, invoke: (api, r, signal) => api.host.listDirectory(r, signal) },
|
||||
'host.createDirectory': { schema: hostCreateDirectoryRequestSchema, invoke: (api, r) => api.host.createDirectory(r) },
|
||||
'host.openPath': { schema: hostOpenPathRequestSchema, invoke: (api, r, signal) => api.host.openPath(r, signal) },
|
||||
'workspace.list': { schema: workspaceListRequestSchema, invoke: (api, r) => api.workspace.list(r) },
|
||||
'workspace.create': { schema: workspaceCreateRequestSchema, invoke: (api, r) => api.workspace.create(r) },
|
||||
@@ -205,6 +209,17 @@ export function toFetchHandler(api: ApiProxy): { fetch: typeof fetch } {
|
||||
return new Response('not found', { status: 404 })
|
||||
}
|
||||
|
||||
// Cross-site write fence: browsers send "simple" POSTs (text/plain,
|
||||
// form encodings) without a CORS preflight, so a malicious page could
|
||||
// otherwise execute side-effectful RPCs blind — the response stays
|
||||
// unreadable cross-origin, but session.prompt would still run. Only the
|
||||
// JSON media type is accepted; anything else is forced into a preflight
|
||||
// this server never answers. 415 = carrier layer, like the 400 below.
|
||||
const mediaType = req.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase()
|
||||
if (mediaType !== 'application/json') {
|
||||
return new Response('content type must be application/json', { status: 415 })
|
||||
}
|
||||
|
||||
let body: unknown
|
||||
try {
|
||||
body = await req.json()
|
||||
|
||||
@@ -45,7 +45,7 @@ export interface Config {
|
||||
* project directory and the fallback parent for name-created Workspaces.
|
||||
*/
|
||||
export class ApiProxyService extends Service implements ApiProxy {
|
||||
static inject = ['agents', 'llm', 'sessions', 'tools', 'userInteraction', 'workspace']
|
||||
static inject = ['agents', 'directoryPicker', 'llm', 'sessions', 'tools', 'userInteraction', 'workspace']
|
||||
|
||||
static Config: z<Config> = z.object({
|
||||
provider: z.string().required(),
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
/** Shared no-shell `execFile` runner for native host dialogs and openers. */
|
||||
|
||||
import { execFile } from 'node:child_process'
|
||||
|
||||
/** Testable command boundary; native implementations never invoke a shell. */
|
||||
export type NativeCommandRunner = (
|
||||
command: string,
|
||||
args: readonly string[],
|
||||
signal: AbortSignal,
|
||||
) => Promise<{ stdout: string; stderr: string }>
|
||||
|
||||
/**
|
||||
* Run a host command with utf8 stdio, abort propagation, and Windows hide.
|
||||
* @param command - executable path or PATH name.
|
||||
* @param args - argv (never a shell string).
|
||||
* @param signal - caller/connection lifetime; abort terminates the child.
|
||||
* @returns captured stdout/stderr on exit 0.
|
||||
*/
|
||||
export const runNativeCommand: NativeCommandRunner = (command, args, signal) =>
|
||||
new Promise((resolve, reject) => {
|
||||
execFile(
|
||||
command,
|
||||
[...args],
|
||||
{ encoding: 'utf8', signal, windowsHide: true },
|
||||
(error, stdout, stderr) => {
|
||||
if (error !== null) {
|
||||
const failure = Object.assign(new Error(error.message, { cause: error }), {
|
||||
code: error.code,
|
||||
stdout,
|
||||
stderr,
|
||||
})
|
||||
reject(failure)
|
||||
return
|
||||
}
|
||||
resolve({ stdout, stderr })
|
||||
},
|
||||
)
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Cross-platform open-with-default-application used by the local GUI carrier. */
|
||||
|
||||
import { runNativeCommand, type NativeCommandRunner } from './native-command.ts'
|
||||
import { runNativeCommand, type NativeCommandRunner } from '@deepseek-ai/dsh-native-command'
|
||||
|
||||
/** Testable command boundary; native implementations never invoke a shell. */
|
||||
export type PathOpenerRunner = NativeCommandRunner
|
||||
|
||||
330
packages/host/apiproxy/tests/api-proxy-approval.spec.ts
Normal file
330
packages/host/apiproxy/tests/api-proxy-approval.spec.ts
Normal file
@@ -0,0 +1,330 @@
|
||||
/**
|
||||
* Approval pending registry over the proxy: an ask through `ctx.approval`
|
||||
* becomes an answerable `approval/requested` mux frame (stable rpcId, replayed
|
||||
* verbatim on a later mux open), `respond` routes by the echoed rpcId and
|
||||
* validates the audit correlation, and the ask's abort signal withdraws the
|
||||
* question with a broadcast `cancelled`.
|
||||
*/
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import AgentRegistry from '@deepseek-ai/dsh-agent'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import SessionStore from '@deepseek-ai/dsh-session'
|
||||
import SystemPrompt from '@deepseek-ai/dsh-system-prompt'
|
||||
import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
|
||||
import ApprovalService from '@deepseek-ai/dsh-user-approval'
|
||||
import type { ApprovalRequestId } from '@deepseek-ai/dsh-user-approval'
|
||||
import type { ApiProxy, MuxFrame, RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api'
|
||||
import type { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
|
||||
import { RpcId as mintRpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
|
||||
import { createApiProxy } from '../src/api-proxy.ts'
|
||||
|
||||
async function harness(): Promise<{ ctx: Context; api: ApiProxy }> {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SystemPrompt, { persona: '' })
|
||||
await ctx.plugin(UserInteractionService)
|
||||
await ctx.plugin(AgentRegistry)
|
||||
await ctx.plugin(ApprovalService)
|
||||
const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
|
||||
return { ctx, api }
|
||||
}
|
||||
|
||||
/** A minimal agent stand-in inside an open turn (the service only reaches `.session`). */
|
||||
function agentOf(ctx: Context): Agent {
|
||||
const session = ctx.sessions.create()
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
return { session } as unknown as Agent
|
||||
}
|
||||
|
||||
/** Open a mux stream and capture frames into an array (returns an on-demand waiter). */
|
||||
function openMux(api: ApiProxy, abort: AbortController): { frames: MuxFrame[]; envelopes: RpcRequest<MuxFrame>[]; waitFor(type: MuxFrame['type']): Promise<MuxFrame> } {
|
||||
const frames: MuxFrame[] = []
|
||||
const envelopes: RpcRequest<MuxFrame>[] = []
|
||||
const waiters: { type: MuxFrame['type']; resolve: (frame: MuxFrame) => void }[] = []
|
||||
void (async () => {
|
||||
for await (const envelope of api.events.mux({ rpcId: mintRpcId('t-mux'), payload: {} }, abort.signal)) {
|
||||
frames.push(envelope.payload)
|
||||
envelopes.push(envelope)
|
||||
for (let i = waiters.length - 1; i >= 0; i -= 1) {
|
||||
const waiter = waiters[i] as (typeof waiters)[number]
|
||||
if (waiter.type === envelope.payload.type) {
|
||||
waiters.splice(i, 1)
|
||||
waiter.resolve(envelope.payload)
|
||||
}
|
||||
}
|
||||
}
|
||||
})()
|
||||
return {
|
||||
frames,
|
||||
envelopes,
|
||||
waitFor: (type) => {
|
||||
const found = frames.find(frame => frame.type === type)
|
||||
if (found !== undefined) return Promise.resolve(found)
|
||||
return new Promise((resolve) => { waiters.push({ type, resolve }) })
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function requestedOf(frame: MuxFrame): Extract<MuxFrame, { type: 'approval/requested' }> {
|
||||
if (frame.type !== 'approval/requested') throw new Error(`expected approval/requested, got ${frame.type}`)
|
||||
return frame
|
||||
}
|
||||
|
||||
/** Wait until the stream delivered `count` frames of `type` (bounded poll; waitFor only covers the first). */
|
||||
async function waitForCount(mux: { frames: MuxFrame[] }, type: MuxFrame['type'], count: number): Promise<void> {
|
||||
for (let i = 0; i < 200 && mux.frames.filter(frame => frame.type === type).length < count; i += 1) {
|
||||
await new Promise(resolve => setTimeout(resolve, 5))
|
||||
}
|
||||
expect(mux.frames.filter(frame => frame.type === type).length).toBeGreaterThanOrEqual(count)
|
||||
}
|
||||
|
||||
function answer(rpcId: RpcId, sessionId: unknown, approvalId: ApprovalRequestId, outcome: 'allowed-once' | 'rejected'): Parameters<ApiProxy['respond']>[0] {
|
||||
return { type: 'client-response', rpcId, result: { ok: true, value: { sessionId, approvalId, outcome } } }
|
||||
}
|
||||
|
||||
describe('approval pending registry', () => {
|
||||
it('round-trips ask → requested frame → respond → outcome + resolved broadcast', async () => {
|
||||
const { ctx, api } = await harness()
|
||||
const abort = new AbortController()
|
||||
const mux = openMux(api, abort)
|
||||
const agent = agentOf(ctx)
|
||||
|
||||
const asked = ctx.approval.request({ agent, toolName: 'bash', reason: 'sandbox escalation' })
|
||||
const requested = requestedOf(await mux.waitFor('approval/requested'))
|
||||
expect(requested).toMatchObject({ toolName: 'bash', reason: 'sandbox escalation', sessionId: agent.session.id })
|
||||
|
||||
const envelope = mux.envelopes.find(e => e.payload.type === 'approval/requested') as RpcRequest<MuxFrame>
|
||||
const receipt = await api.respond(answer(envelope.rpcId, requested.sessionId, requested.approvalId, 'allowed-once'))
|
||||
expect(receipt).toEqual({ accepted: true })
|
||||
await expect(asked).resolves.toBe('allowed-once')
|
||||
|
||||
const resolved = await mux.waitFor('approval/resolved')
|
||||
expect(resolved).toMatchObject({ approvalId: requested.approvalId, outcome: 'allowed-once' })
|
||||
|
||||
// The question settled: a duplicate answer is late, not re-decidable.
|
||||
const dup = await api.respond(answer(envelope.rpcId, requested.sessionId, requested.approvalId, 'rejected'))
|
||||
expect(dup).toEqual({ accepted: false, reason: 'not-pending' })
|
||||
abort.abort()
|
||||
})
|
||||
|
||||
it('replays a still-pending requested frame (same rpcId) on a later mux open', async () => {
|
||||
const { ctx, api } = await harness()
|
||||
const first = new AbortController()
|
||||
const firstMux = openMux(api, first)
|
||||
const agent = agentOf(ctx)
|
||||
const asked = ctx.approval.request({ agent, toolName: 'write' })
|
||||
const requested = requestedOf(await firstMux.waitFor('approval/requested'))
|
||||
const firstEnvelope = firstMux.envelopes.find(e => e.payload.type === 'approval/requested') as RpcRequest<MuxFrame>
|
||||
first.abort()
|
||||
|
||||
// A fresh subscriber (refresh recovery) sees the same stable rpcId.
|
||||
const second = new AbortController()
|
||||
const secondMux = openMux(api, second)
|
||||
const replayed = requestedOf(await secondMux.waitFor('approval/requested'))
|
||||
const secondEnvelope = secondMux.envelopes.find(e => e.payload.type === 'approval/requested') as RpcRequest<MuxFrame>
|
||||
expect(secondEnvelope.rpcId).toBe(firstEnvelope.rpcId)
|
||||
expect(replayed.approvalId).toBe(requested.approvalId)
|
||||
|
||||
const receipt = await api.respond(answer(secondEnvelope.rpcId, replayed.sessionId, replayed.approvalId, 'rejected'))
|
||||
expect(receipt).toEqual({ accepted: true })
|
||||
await expect(asked).resolves.toBe('rejected')
|
||||
second.abort()
|
||||
})
|
||||
|
||||
it('rejects malformed and mismatched answers as bad-response, unknown ids as not-pending', async () => {
|
||||
const { ctx, api } = await harness()
|
||||
const abort = new AbortController()
|
||||
const mux = openMux(api, abort)
|
||||
const agent = agentOf(ctx)
|
||||
void ctx.approval.request({ agent, toolName: 'bash' })
|
||||
const requested = requestedOf(await mux.waitFor('approval/requested'))
|
||||
const envelope = mux.envelopes.find(e => e.payload.type === 'approval/requested') as RpcRequest<MuxFrame>
|
||||
|
||||
// Unknown rpcId: not routed to any pending entry.
|
||||
expect(await api.respond(answer(mintRpcId('ghost'), requested.sessionId, requested.approvalId, 'rejected')))
|
||||
.toEqual({ accepted: false, reason: 'not-pending' })
|
||||
// Error-branch result: the client can only answer with a value.
|
||||
expect(await api.respond({ type: 'client-response', rpcId: envelope.rpcId, result: { ok: false, error: { code: 'internal', message: 'x', details: {} } } }))
|
||||
.toEqual({ accepted: false, reason: 'bad-response' })
|
||||
// Wrong audit correlation: the rpcId routed, but the payload disagrees.
|
||||
expect(await api.respond(answer(envelope.rpcId, requested.sessionId, 'other-approval' as ApprovalRequestId, 'rejected')))
|
||||
.toEqual({ accepted: false, reason: 'bad-response' })
|
||||
// Malformed payload shape.
|
||||
expect(await api.respond({ type: 'client-response', rpcId: envelope.rpcId, result: { ok: true, value: { nonsense: 1 } } }))
|
||||
.toEqual({ accepted: false, reason: 'bad-response' })
|
||||
abort.abort()
|
||||
})
|
||||
|
||||
it('withdraws the question on the ask signal: cancelled outcome, resolved broadcast, late answer not-pending', async () => {
|
||||
const { ctx, api } = await harness()
|
||||
const abort = new AbortController()
|
||||
const mux = openMux(api, abort)
|
||||
const agent = agentOf(ctx)
|
||||
const cancel = new AbortController()
|
||||
const asked = ctx.approval.request({ agent, toolName: 'bash', signal: cancel.signal })
|
||||
const requested = requestedOf(await mux.waitFor('approval/requested'))
|
||||
const envelope = mux.envelopes.find(e => e.payload.type === 'approval/requested') as RpcRequest<MuxFrame>
|
||||
|
||||
cancel.abort()
|
||||
await expect(asked).resolves.toBe('cancelled')
|
||||
const resolved = await mux.waitFor('approval/resolved')
|
||||
expect(resolved).toMatchObject({ approvalId: requested.approvalId, outcome: 'cancelled' })
|
||||
expect(await api.respond(answer(envelope.rpcId, requested.sessionId, requested.approvalId, 'allowed-once')))
|
||||
.toEqual({ accepted: false, reason: 'not-pending' })
|
||||
abort.abort()
|
||||
})
|
||||
|
||||
it('an ask whose signal aborted before dispatch settles cancelled without publishing', async () => {
|
||||
// The service checks the signal, then dispatch rides a microtask: an
|
||||
// abort in that window must not register a dead listener and strand the
|
||||
// entry (zombie frame on every replay). Drive the waterfall directly
|
||||
// with a pre-aborted signal to hit the answerer's register-path guard.
|
||||
const { ctx, api } = await harness()
|
||||
const abort = new AbortController()
|
||||
const mux = openMux(api, abort)
|
||||
const session = ctx.sessions.create()
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
session.append('approval/asked', { id: 'pre-aborted' as ApprovalRequestId, toolName: 'bash' })
|
||||
const agent = { session } as unknown as Agent
|
||||
const cancelled = new AbortController()
|
||||
cancelled.abort()
|
||||
const outcome = await ctx.waterfall(
|
||||
'approval/request',
|
||||
{ agent, toolName: 'bash', signal: cancelled.signal },
|
||||
() => Promise.resolve('unavailable' as const),
|
||||
)
|
||||
expect(outcome).toBe('cancelled')
|
||||
// Nothing was published: a fresh mux open replays no approval frame.
|
||||
const abort2 = new AbortController()
|
||||
const mux2 = openMux(api, abort2)
|
||||
await new Promise(resolve => setTimeout(resolve, 10))
|
||||
expect(mux2.envelopes.some(e => e.payload.type === 'approval/requested')).toBe(false)
|
||||
abort2.abort()
|
||||
abort.abort()
|
||||
void mux
|
||||
})
|
||||
|
||||
it('gateway teardown settles pending approvals as cancelled (question-provider parity)', async () => {
|
||||
// Mount the proxy on its own fiber so disposal exercises the teardown
|
||||
// effect while an ask is still pending.
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
await ctx.plugin(SystemPrompt, { persona: '' })
|
||||
await ctx.plugin(UserInteractionService)
|
||||
await ctx.plugin(AgentRegistry)
|
||||
await ctx.plugin(ApprovalService)
|
||||
let api!: ApiProxy
|
||||
const fiber = ctx.plugin(Object.assign((fiberCtx: Context) => {
|
||||
api = createApiProxy(fiberCtx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' })
|
||||
}, { inject: ['sessions', 'agents', 'userInteraction', 'approval'] }))
|
||||
await fiber.await()
|
||||
const abort = new AbortController()
|
||||
const mux = openMux(api, abort)
|
||||
const asked = ctx.approval.request({ agent: agentOf(ctx), toolName: 'bash' })
|
||||
const requested = requestedOf(await mux.waitFor('approval/requested'))
|
||||
await fiber.dispose()
|
||||
await expect(asked).resolves.toBe('cancelled')
|
||||
const resolved = await mux.waitFor('approval/resolved')
|
||||
expect(resolved).toMatchObject({ approvalId: requested.approvalId, outcome: 'cancelled' })
|
||||
abort.abort()
|
||||
})
|
||||
|
||||
it('carries callId on the frame and ignores a late abort after the answer settled', async () => {
|
||||
const { ctx, api } = await harness()
|
||||
const abort = new AbortController()
|
||||
const mux = openMux(api, abort)
|
||||
const agent = agentOf(ctx)
|
||||
const cancel = new AbortController()
|
||||
const asked = ctx.approval.request({ agent, toolName: 'bash', callId: 'call-9' as never, signal: cancel.signal })
|
||||
const requested = requestedOf(await mux.waitFor('approval/requested'))
|
||||
expect(requested.callId).toBe('call-9')
|
||||
const envelope = mux.envelopes.find(e => e.payload.type === 'approval/requested') as RpcRequest<MuxFrame>
|
||||
expect(await api.respond(answer(envelope.rpcId, requested.sessionId, requested.approvalId, 'allowed-once')))
|
||||
.toEqual({ accepted: true })
|
||||
await expect(asked).resolves.toBe('allowed-once')
|
||||
// Late abort: the pending entry is gone; settle's delete-guard returns.
|
||||
cancel.abort()
|
||||
expect(mux.frames.filter(f => f.type === 'approval/resolved')).toHaveLength(1)
|
||||
abort.abort()
|
||||
})
|
||||
|
||||
it('pairs parallel asks by callId: each requested frame carries its own audit id', async () => {
|
||||
const { ctx, api } = await harness()
|
||||
const abort = new AbortController()
|
||||
const mux = openMux(api, abort)
|
||||
const agent = agentOf(ctx)
|
||||
// Both asks append their approval/asked audit events before either
|
||||
// answerer's microtask dispatch runs — the parallel tool-call window.
|
||||
const askA = ctx.approval.request({ agent, toolName: 'bash', callId: 'call-a' as never })
|
||||
const askB = ctx.approval.request({ agent, toolName: 'bash', callId: 'call-b' as never })
|
||||
await waitForCount(mux, 'approval/requested', 2)
|
||||
const frames = mux.envelopes.filter(e => e.payload.type === 'approval/requested')
|
||||
const frameA = frames.find(e => requestedOf(e.payload).callId === 'call-a') as RpcRequest<MuxFrame>
|
||||
const frameB = frames.find(e => requestedOf(e.payload).callId === 'call-b') as RpcRequest<MuxFrame>
|
||||
// Each frame claimed the asked event with its own callId, not merely the newest.
|
||||
const askedIdByCall = new Map(agent.session.events
|
||||
.filter(event => event.type === 'approval/asked')
|
||||
.map(event => [String(event.data.callId), event.data.id]))
|
||||
expect(requestedOf(frameA.payload).approvalId).toBe(askedIdByCall.get('call-a'))
|
||||
expect(requestedOf(frameB.payload).approvalId).toBe(askedIdByCall.get('call-b'))
|
||||
// Answers route back to the right ask through the pairing.
|
||||
expect(await api.respond(answer(frameB.rpcId, agent.session.id, requestedOf(frameB.payload).approvalId, 'rejected')))
|
||||
.toEqual({ accepted: true })
|
||||
expect(await api.respond(answer(frameA.rpcId, agent.session.id, requestedOf(frameA.payload).approvalId, 'allowed-once')))
|
||||
.toEqual({ accepted: true })
|
||||
await expect(askA).resolves.toBe('allowed-once')
|
||||
await expect(askB).resolves.toBe('rejected')
|
||||
abort.abort()
|
||||
})
|
||||
|
||||
it('gives parallel callId-less asks distinct audit ids (claimed-entry skip); both stay answerable', async () => {
|
||||
const { ctx, api } = await harness()
|
||||
const abort = new AbortController()
|
||||
const mux = openMux(api, abort)
|
||||
const agent = agentOf(ctx)
|
||||
const askA = ctx.approval.request({ agent, toolName: 'alpha' })
|
||||
const askB = ctx.approval.request({ agent, toolName: 'beta' })
|
||||
await waitForCount(mux, 'approval/requested', 2)
|
||||
const frames = mux.envelopes.filter(e => e.payload.type === 'approval/requested')
|
||||
const frameA = frames.find(e => requestedOf(e.payload).toolName === 'alpha') as RpcRequest<MuxFrame>
|
||||
const frameB = frames.find(e => requestedOf(e.payload).toolName === 'beta') as RpcRequest<MuxFrame>
|
||||
// Without a callId the pairing is heuristic, but never shared: the second
|
||||
// dispatch skips the id the first pending entry already claimed.
|
||||
expect(requestedOf(frameA.payload).approvalId).not.toBe(requestedOf(frameB.payload).approvalId)
|
||||
expect(await api.respond(answer(frameA.rpcId, agent.session.id, requestedOf(frameA.payload).approvalId, 'allowed-once')))
|
||||
.toEqual({ accepted: true })
|
||||
expect(await api.respond(answer(frameB.rpcId, agent.session.id, requestedOf(frameB.payload).approvalId, 'rejected')))
|
||||
.toEqual({ accepted: true })
|
||||
await expect(askA).resolves.toBe('allowed-once')
|
||||
await expect(askB).resolves.toBe('rejected')
|
||||
abort.abort()
|
||||
})
|
||||
|
||||
it('delegates a dispatch whose only asked candidate is already decided (stale re-dispatch)', async () => {
|
||||
const { ctx, api } = await harness()
|
||||
void api // the answerer is registered; the fake below bypasses the service
|
||||
// Bypass ApprovalService: a log whose sole asked event already has its
|
||||
// decided partner must not be re-claimed — the answerer delegates.
|
||||
const session = ctx.sessions.create()
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
session.append('approval/asked', { id: 'stale-ask' as ApprovalRequestId, toolName: 'bash' })
|
||||
session.append('approval/decided', { id: 'stale-ask' as ApprovalRequestId, outcome: 'rejected' })
|
||||
const agent = { session } as unknown as Agent
|
||||
const outcome = await ctx.waterfall('approval/request', { agent, toolName: 'bash' }, () => Promise.resolve('unavailable' as const))
|
||||
expect(outcome).toBe('unavailable')
|
||||
})
|
||||
|
||||
it('delegates an ask whose session log carries no asked audit event (foreign channel)', async () => {
|
||||
const { ctx, api } = await harness()
|
||||
void api // the answerer is registered; the fake below bypasses the audit path
|
||||
// Bypass ApprovalService: dispatch the waterfall directly with a session
|
||||
// that has no approval/asked event — the proxy answerer must call next().
|
||||
const session = ctx.sessions.create()
|
||||
session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } })
|
||||
const agent = { session } as unknown as Agent
|
||||
const outcome = await ctx.waterfall('approval/request', { agent, toolName: 'x' }, () => Promise.resolve('unavailable' as const))
|
||||
expect(outcome).toBe('unavailable')
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* The summary blank bit means "conversation not started" (no turn has run),
|
||||
* not "log empty": standalone plugin events — command lifecycle records,
|
||||
* plan/mode, session titles — never flip it, so running /plan or /goal on a
|
||||
* plan/mode, permission knob events, session titles — never flip it, so running /plan or /goal on a
|
||||
* fresh session keeps it list-hidden and reusable, while the first accepted
|
||||
* prompt's turn/start clears it. The host/session-added frame shares the
|
||||
* same predicate function (covered by the workspace spec's frame assertion).
|
||||
@@ -15,6 +15,10 @@ import SessionStore from '@deepseek-ai/dsh-session'
|
||||
import type { Session } from '@deepseek-ai/dsh-session'
|
||||
import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
|
||||
import { CommandId } from '@deepseek-ai/dsh-commands/brand'
|
||||
// Side-effect type imports: the knob-event SessionEventMap merges.
|
||||
import type {} from '@deepseek-ai/dsh-permission'
|
||||
import type {} from '@deepseek-ai/dsh-sandbox-policy'
|
||||
import type {} from '@deepseek-ai/dsh-user-approval'
|
||||
import type { ApiProxy, RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api'
|
||||
import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
|
||||
import { createApiProxy } from '@deepseek-ai/dsh-host-apiproxy'
|
||||
@@ -48,6 +52,10 @@ function appendStandalone(session: Session): void {
|
||||
session.append('session/title', {
|
||||
title: 'standalone title', messageSeqs: [], source: { kind: 'fallback' },
|
||||
})
|
||||
// The three permission knob events (a /permission switch on a fresh session).
|
||||
session.append('permission/preset', { preset: 'danger-full-access' })
|
||||
session.append('sandbox/mode', { mode: 'danger-full-access' })
|
||||
session.append('approval/policy', { policy: 'never' })
|
||||
}
|
||||
|
||||
async function listBlank(api: ApiProxy, id: string): Promise<boolean | undefined> {
|
||||
|
||||
@@ -3,13 +3,15 @@ import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import AgentRegistry, {} from '@deepseek-ai/dsh-agent'
|
||||
import AgentRegistry from '@deepseek-ai/dsh-agent'
|
||||
import type { Agent, AgentFactory } from '@deepseek-ai/dsh-agent'
|
||||
import SessionStore, { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type { Session } from '@deepseek-ai/dsh-session'
|
||||
import Storage from '@deepseek-ai/dsh-storage'
|
||||
import { DomainFacility } from '@deepseek-ai/dsh-storage-domain'
|
||||
import UserInteractionService from '@deepseek-ai/dsh-user-interaction'
|
||||
import { DirectoryPickerError } from '@deepseek-ai/dsh-host-directory-picker'
|
||||
import type { DirectoryPickerCapability } from '@deepseek-ai/dsh-host-directory-picker'
|
||||
import WorkspaceRegistry from '@deepseek-ai/dsh-workspace'
|
||||
import type { HostFrame, WorkspaceId } from '@deepseek-ai/dsh-host-apiproxy/api'
|
||||
import type { RpcRequest, RpcResponse } from '@deepseek-ai/dsh-host-apiproxy/api/rpc'
|
||||
@@ -57,10 +59,8 @@ function stubAgent(session: Session): Agent {
|
||||
/** Compose the API over real Session, Agent, Storage, Domain, and Workspace services. */
|
||||
async function harness(
|
||||
workspaceRoot = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-apiproxy-workspace-'))),
|
||||
extras: {
|
||||
pickDirectory?: (signal: AbortSignal) => Promise<string | null>
|
||||
openPath?: (path: string, signal: AbortSignal) => Promise<void>
|
||||
} = {},
|
||||
picker: DirectoryPickerCapability = { kind: 'native', pick: async () => null },
|
||||
extras: { openPath?: (path: string, signal: AbortSignal) => Promise<void> } = {},
|
||||
) {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SessionStore)
|
||||
@@ -95,31 +95,34 @@ async function harness(
|
||||
},
|
||||
}
|
||||
ctx.agents.setFactory(factory)
|
||||
// Structural picker fake: the gateway only reads capability(); a stable
|
||||
// object per harness mirrors the seam's stability contract.
|
||||
ctx.provide('directoryPicker', { capability: () => picker } as never)
|
||||
const api = createApiProxy(ctx, {
|
||||
provider: 'test',
|
||||
model: 'test-model',
|
||||
cwd: workspaceRoot,
|
||||
workspaceRoot,
|
||||
...extras.pickDirectory === undefined ? {} : { pickDirectory: extras.pickDirectory },
|
||||
...extras.openPath === undefined ? {} : { openPath: extras.openPath },
|
||||
})
|
||||
return { api, ctx, storageDomain, workspaceRoot }
|
||||
}
|
||||
|
||||
describe('host.pickDirectory', () => {
|
||||
it('returns a selected path or explicit cancellation from the injected native boundary', async () => {
|
||||
const selected = await harness(undefined, { pickDirectory: async () => '/tmp/project' })
|
||||
it('returns a selected path or explicit cancellation from the native capability', async () => {
|
||||
const selected = await harness(undefined, { kind: 'native', pick: async () => '/tmp/project' })
|
||||
expect((await selected.api.host.pickDirectory(request({}), new AbortController().signal)).result)
|
||||
.toEqual({ ok: true, value: { path: '/tmp/project' } })
|
||||
|
||||
const cancelled = await harness(undefined, { pickDirectory: async () => null })
|
||||
const cancelled = await harness(undefined, { kind: 'native', pick: async () => null })
|
||||
expect((await cancelled.api.host.pickDirectory(request({}), new AbortController().signal)).result)
|
||||
.toEqual({ ok: true, value: { path: null } })
|
||||
})
|
||||
|
||||
it('propagates abort into the native boundary as a cancelled RPC error', async () => {
|
||||
it('propagates abort into the native capability as a cancelled RPC error', async () => {
|
||||
const { api } = await harness(undefined, {
|
||||
pickDirectory: signal => new Promise((_resolve, reject) => {
|
||||
kind: 'native',
|
||||
pick: signal => new Promise((_resolve, reject) => {
|
||||
signal.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true })
|
||||
}),
|
||||
})
|
||||
@@ -128,12 +131,97 @@ describe('host.pickDirectory', () => {
|
||||
abort.abort()
|
||||
expect((await pending).result).toMatchObject({ ok: false, error: { code: 'cancelled' } })
|
||||
})
|
||||
|
||||
it('folds a non-abort native-chooser failure into an internal error', async () => {
|
||||
const { api } = await harness(undefined, { kind: 'native', pick: async () => { throw new Error('no chooser installed') } })
|
||||
const response = await api.host.pickDirectory(request({}), new AbortController().signal)
|
||||
expect(response.result).toMatchObject({ ok: false, error: { code: 'internal' } })
|
||||
})
|
||||
|
||||
it('refuses the native RPC under a browse composition', async () => {
|
||||
const { api } = await harness(undefined, BROWSE_STUB)
|
||||
const response = await api.host.pickDirectory(request({}), new AbortController().signal)
|
||||
expect(response.result).toMatchObject({
|
||||
ok: false,
|
||||
error: { code: 'directory-picker-unavailable', details: { capability: 'browse' } },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
/** Canned browse capability: one listing, one created path, typed failures on demand. */
|
||||
const BROWSE_STUB: DirectoryPickerCapability = {
|
||||
kind: 'browse',
|
||||
list: async (path) => {
|
||||
if (path === '/denied') throw new DirectoryPickerError('directory-unreadable', '/denied', 'cannot list /denied')
|
||||
const target = path ?? '/home/user'
|
||||
return {
|
||||
path: target,
|
||||
home: '/home/user',
|
||||
crumbs: [{ name: '/', path: '/', hidden: false }],
|
||||
entries: [{ name: 'projects', path: `${target}/projects`, hidden: false }],
|
||||
truncated: false,
|
||||
}
|
||||
},
|
||||
createDirectory: async (path, name) => {
|
||||
if (name === 'taken') throw new DirectoryPickerError('directory-exists', `${path}/${name}`, 'already exists')
|
||||
if (name === 'unwritable') throw new Error('disk detached')
|
||||
return `${path}/${name}`
|
||||
},
|
||||
}
|
||||
|
||||
describe('host.listDirectory / host.createDirectory', () => {
|
||||
it('serves listings and creation through the browse capability, defaulting to home', async () => {
|
||||
const { api } = await harness(undefined, BROWSE_STUB)
|
||||
const home = await api.host.listDirectory(request({}), new AbortController().signal)
|
||||
expect(home.result).toMatchObject({ ok: true, value: { path: '/home/user', home: '/home/user' } })
|
||||
const listed = await api.host.listDirectory(request({ path: '/home/user/projects' }), new AbortController().signal)
|
||||
expect(listed.result).toMatchObject({ ok: true, value: { path: '/home/user/projects' } })
|
||||
const created = await api.host.createDirectory(request({ path: '/home/user', name: 'fresh' }))
|
||||
expect(created.result).toEqual({ ok: true, value: { path: '/home/user/fresh' } })
|
||||
})
|
||||
|
||||
it('maps typed picker failures onto the wire error codes and folds unknown throws to internal', async () => {
|
||||
const { api } = await harness(undefined, BROWSE_STUB)
|
||||
expect((await api.host.listDirectory(request({ path: '/denied' }), new AbortController().signal)).result).toMatchObject({
|
||||
ok: false, error: { code: 'directory-unreadable', details: { path: '/denied' } },
|
||||
})
|
||||
expect((await api.host.createDirectory(request({ path: '/home/user', name: 'taken' }))).result).toMatchObject({
|
||||
ok: false, error: { code: 'directory-exists' },
|
||||
})
|
||||
expect((await api.host.createDirectory(request({ path: '/home/user', name: 'unwritable' }))).result).toMatchObject({
|
||||
ok: false, error: { code: 'internal' },
|
||||
})
|
||||
})
|
||||
|
||||
it('reports an aborted listing as cancelled, like the other signal-following RPCs', async () => {
|
||||
const { api } = await harness(undefined, {
|
||||
kind: 'browse',
|
||||
list: (_path, signal) => new Promise((_resolve, reject) => {
|
||||
signal?.addEventListener('abort', () => { reject(new Error('scan aborted')) }, { once: true })
|
||||
}),
|
||||
createDirectory: async () => '/never',
|
||||
})
|
||||
const abort = new AbortController()
|
||||
const pending = api.host.listDirectory(request({}), abort.signal)
|
||||
abort.abort()
|
||||
expect((await pending).result).toMatchObject({ ok: false, error: { code: 'cancelled' } })
|
||||
})
|
||||
|
||||
it('refuses the browse RPCs under a native composition', async () => {
|
||||
const { api } = await harness()
|
||||
expect((await api.host.listDirectory(request({}), new AbortController().signal)).result).toMatchObject({
|
||||
ok: false, error: { code: 'directory-picker-unavailable', details: { capability: 'native' } },
|
||||
})
|
||||
expect((await api.host.createDirectory(request({ path: '/x', name: 'y' }))).result).toMatchObject({
|
||||
ok: false, error: { code: 'directory-picker-unavailable', details: { capability: 'native' } },
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('host.openPath', () => {
|
||||
it('opens through the injected native boundary', async () => {
|
||||
const opened: string[] = []
|
||||
const { api } = await harness(undefined, {
|
||||
const { api } = await harness(undefined, undefined, {
|
||||
openPath: async (path) => { opened.push(path) },
|
||||
})
|
||||
expect((await api.host.openPath(request({ path: '/tmp/a.txt' }), new AbortController().signal)).result)
|
||||
@@ -142,7 +230,7 @@ describe('host.openPath', () => {
|
||||
})
|
||||
|
||||
it('propagates abort into the native boundary as a cancelled RPC error', async () => {
|
||||
const { api } = await harness(undefined, {
|
||||
const { api } = await harness(undefined, undefined, {
|
||||
openPath: (_path, signal) => new Promise((_resolve, reject) => {
|
||||
signal.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true })
|
||||
}),
|
||||
|
||||
@@ -53,6 +53,8 @@ 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: [], truncated: false }),
|
||||
createDirectory: r => ok(r, { path: '/t/new' }),
|
||||
openPath: r => ok(r, { opened: true as const }),
|
||||
...overrides.host,
|
||||
},
|
||||
@@ -151,7 +153,7 @@ describe('unary round trip', () => {
|
||||
it('rejects a method/path mismatch as bad-request', async () => {
|
||||
const handler = toFetchHandler(scriptedApi())
|
||||
const body = { type: 'client-request', rpcId: 'r1', method: 'session.create', payload: {} }
|
||||
const response = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', body: JSON.stringify(body) })
|
||||
const response = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
|
||||
expect(response.status).toBe(200)
|
||||
const parsed = await response.json() as { result: { ok: boolean; error?: { code: string; message: string } } }
|
||||
expect(parsed.result.ok).toBe(false)
|
||||
@@ -162,13 +164,13 @@ describe('unary round trip', () => {
|
||||
it('rejects a malformed envelope as bad-request, salvaging the rpcId or falling back to the sentinel', async () => {
|
||||
const handler = toFetchHandler(scriptedApi())
|
||||
// No salvageable rpcId → the fixed invalid-request sentinel keeps the response a valid ServerResponse.
|
||||
const noId = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', body: JSON.stringify({ nonsense: true }) })
|
||||
const noId = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ nonsense: true }) })
|
||||
expect(noId.status).toBe(200)
|
||||
const noIdParsed = await noId.json() as { rpcId: string; result: { ok: boolean } }
|
||||
expect(noIdParsed.result.ok).toBe(false)
|
||||
expect(noIdParsed.rpcId).toBe('invalid-request')
|
||||
// A string rpcId in the otherwise-bad body is salvaged for correlation.
|
||||
const withId = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', body: JSON.stringify({ rpcId: 'salvage-me', nonsense: true }) })
|
||||
const withId = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ rpcId: 'salvage-me', nonsense: true }) })
|
||||
const withIdParsed = await withId.json() as { rpcId: string; result: { ok: boolean } }
|
||||
expect(withIdParsed.result.ok).toBe(false)
|
||||
expect(withIdParsed.rpcId).toBe('salvage-me')
|
||||
@@ -177,16 +179,34 @@ describe('unary round trip', () => {
|
||||
it('maps carrier failures to HTTP statuses and the client throws transport failure', async () => {
|
||||
const handler = toFetchHandler(scriptedApi())
|
||||
// Unknown method → 404.
|
||||
const notFound = await handler.fetch('http://dsh.internal/api/no.such', { method: 'POST', body: '{}' })
|
||||
const notFound = await handler.fetch('http://dsh.internal/api/no.such', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' })
|
||||
expect(notFound.status).toBe(404)
|
||||
// Non-JSON body → 400.
|
||||
const badBody = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', body: '{oops' })
|
||||
const badBody = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{oops' })
|
||||
expect(badBody.status).toBe(400)
|
||||
// Impl crash → 500, and through the client that is a throw, not an err result.
|
||||
const crashing = scriptedApi({ sessions: { list: () => { throw new Error('impl exploded') } } })
|
||||
await expect(client(crashing).sessions.list({})).rejects.toThrow(/transport failure .*500/)
|
||||
})
|
||||
|
||||
it('rejects non-JSON media types before executing anything (cross-site simple-request fence)', async () => {
|
||||
const list = vi.fn((r: RpcRequest<{}>) => ok(r, { items: [] }))
|
||||
const handler = toFetchHandler(scriptedApi({ sessions: { list } }))
|
||||
const body = JSON.stringify({ type: 'client-request', rpcId: 'r1', method: 'session.list', payload: {} })
|
||||
// A "simple" browser POST (text/plain — sent with no CORS preflight) is
|
||||
// refused at the carrier before the impl runs.
|
||||
const plain = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', headers: { 'content-type': 'text/plain' }, body })
|
||||
expect(plain.status).toBe(415)
|
||||
// A string body with no explicit header defaults to text/plain — same fence.
|
||||
const unlabelled = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', body })
|
||||
expect(unlabelled.status).toBe(415)
|
||||
expect(list).not.toHaveBeenCalled()
|
||||
// Media-type parameters pass: the fence checks the type, not the exact string.
|
||||
const charset = await handler.fetch('http://dsh.internal/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json; charset=utf-8' }, body })
|
||||
expect(charset.status).toBe(200)
|
||||
expect(list).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('rejects when the transport never resolves within timeoutMs', async () => {
|
||||
// AbortSignal.timeout is immune to fake timers; a short real timeout keeps this fast.
|
||||
const never = new InProcessApiClient({
|
||||
@@ -495,7 +515,7 @@ describe('respond path', () => {
|
||||
it('returns bad-response for a malformed client-response without reaching the impl', async () => {
|
||||
const respond = vi.fn()
|
||||
const handler = toFetchHandler(scriptedApi({ respond }))
|
||||
const response = await handler.fetch('http://dsh.internal/api/respond', { method: 'POST', body: JSON.stringify({ type: 'client-response' }) })
|
||||
const response = await handler.fetch('http://dsh.internal/api/respond', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ type: 'client-response' }) })
|
||||
expect(await response.json()).toEqual({ accepted: false, reason: 'bad-response' })
|
||||
expect(respond).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -81,6 +81,12 @@ function fakeApi(overrides: Partial<{ muxFrames: MuxFrame[]; hostFrames: HostFra
|
||||
async pickDirectory(request) {
|
||||
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: [], truncated: false } } }
|
||||
},
|
||||
async createDirectory(request) {
|
||||
return { rpcId: request.rpcId, result: { ok: true, value: { path: '/w/new' } } }
|
||||
},
|
||||
async openPath(request) {
|
||||
return { rpcId: request.rpcId, result: { ok: true, value: { opened: true as const } } }
|
||||
},
|
||||
@@ -233,6 +239,19 @@ describe('unary round trip (handler ⇄ client, no network)', () => {
|
||||
expect(response.result).toEqual({ ok: true, value: { path: '/tmp/project' } })
|
||||
})
|
||||
|
||||
it('round-trips the browse listing and creation calls through the wire form', async () => {
|
||||
const c = client()
|
||||
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: [], truncated: false },
|
||||
})
|
||||
const home = await c.host.listDirectory({})
|
||||
expect(home.result).toMatchObject({ ok: true, value: { home: '/w' } })
|
||||
const created = await c.host.createDirectory({ path: '/w', name: 'fresh' })
|
||||
expect(created.result).toEqual({ ok: true, value: { path: '/w/new' } })
|
||||
})
|
||||
|
||||
it('round-trips host.openPath through the wire form', async () => {
|
||||
const api = fakeApi()
|
||||
let opened: string | undefined
|
||||
@@ -263,7 +282,7 @@ describe('unary round trip (handler ⇄ client, no network)', () => {
|
||||
const body = JSON.stringify({ type: 'client-request', rpcId: 'r-sig', method: 'command.execute', payload: { sessionId: 's', line: '/hang' } })
|
||||
// The fake's /hang settles only when the invoke-level signal aborts: a
|
||||
// completed response with the cancelled error proves req.signal reached it.
|
||||
const pending = handler.fetch(new Request('http://x/api/command.execute', { method: 'POST', body, signal: controller.signal }))
|
||||
const pending = handler.fetch(new Request('http://x/api/command.execute', { method: 'POST', headers: { 'content-type': 'application/json' }, body, signal: controller.signal }))
|
||||
controller.abort()
|
||||
const response = await pending
|
||||
const parsed = await response.json() as { rpcId: string; result: { ok: boolean; error?: { code: string } } }
|
||||
@@ -288,7 +307,7 @@ describe('unary round trip (handler ⇄ client, no network)', () => {
|
||||
const controller = new AbortController()
|
||||
const body = JSON.stringify({ type: 'client-request', rpcId: 'r-picker', method: 'host.pickDirectory', payload: {} })
|
||||
const pending = handler.fetch(new Request('http://x/api/host.pickDirectory', {
|
||||
method: 'POST', body, signal: controller.signal,
|
||||
method: 'POST', headers: { 'content-type': 'application/json' }, body, signal: controller.signal,
|
||||
}))
|
||||
controller.abort()
|
||||
const parsed = await (await pending).json() as { result: { error?: { code: string } } }
|
||||
@@ -300,18 +319,18 @@ describe('handler carrier-layer statuses', () => {
|
||||
const handler = toFetchHandler(fakeApi())
|
||||
|
||||
it('404s unknown paths and non-POST non-stream methods', async () => {
|
||||
expect((await handler.fetch(new Request('http://x/other', { method: 'POST', body: '{}' }))).status).toBe(404)
|
||||
expect((await handler.fetch(new Request('http://x/other', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' }))).status).toBe(404)
|
||||
expect((await handler.fetch(new Request('http://x/api/session.list', { method: 'GET' }))).status).toBe(404)
|
||||
expect((await handler.fetch(new Request('http://x/api/no.such', { method: 'POST', body: JSON.stringify({ type: 'client-request', rpcId: 'r', method: 'no.such', payload: {} }) }))).status).toBe(404)
|
||||
expect((await handler.fetch(new Request('http://x/api/no.such', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ type: 'client-request', rpcId: 'r', method: 'no.such', payload: {} }) }))).status).toBe(404)
|
||||
})
|
||||
|
||||
it('400s a non-JSON body', async () => {
|
||||
const response = await handler.fetch(new Request('http://x/api/session.list', { method: 'POST', body: 'not json' }))
|
||||
const response = await handler.fetch(new Request('http://x/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body: 'not json' }))
|
||||
expect(response.status).toBe(400)
|
||||
})
|
||||
|
||||
it('rejects a malformed envelope with bad-request and the invalid-request sentinel rpcId', async () => {
|
||||
const response = await handler.fetch(new Request('http://x/api/session.list', { method: 'POST', body: JSON.stringify({ nope: true }) }))
|
||||
const response = await handler.fetch(new Request('http://x/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ nope: true }) }))
|
||||
expect(response.status).toBe(200)
|
||||
const body = await response.json() as { rpcId: string; result: { ok: boolean; error?: { code: string } } }
|
||||
expect(body.rpcId).toBe('invalid-request')
|
||||
@@ -320,7 +339,7 @@ describe('handler carrier-layer statuses', () => {
|
||||
|
||||
it('rejects a method/path mismatch echoing the envelope rpcId', async () => {
|
||||
const body = JSON.stringify({ type: 'client-request', rpcId: 'r-9', method: 'session.cancel', payload: {} })
|
||||
const response = await handler.fetch(new Request('http://x/api/session.list', { method: 'POST', body }))
|
||||
const response = await handler.fetch(new Request('http://x/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body }))
|
||||
const parsed = await response.json() as { rpcId: string; result: { error?: { message: string } } }
|
||||
expect(parsed.rpcId).toBe('r-9')
|
||||
expect(parsed.result.error?.message).toContain('does not match path')
|
||||
@@ -328,7 +347,7 @@ describe('handler carrier-layer statuses', () => {
|
||||
|
||||
it('rejects an invalid payload with the zod issues attached', async () => {
|
||||
const body = JSON.stringify({ type: 'client-request', rpcId: 'r-10', method: 'session.cancel', payload: {} })
|
||||
const response = await handler.fetch(new Request('http://x/api/session.cancel', { method: 'POST', body }))
|
||||
const response = await handler.fetch(new Request('http://x/api/session.cancel', { method: 'POST', headers: { 'content-type': 'application/json' }, body }))
|
||||
const parsed = await response.json() as { result: { error?: { code: string; details: { issues: unknown[] } } } }
|
||||
expect(parsed.result.error?.code).toBe('bad-request')
|
||||
expect(parsed.result.error?.details.issues.length).toBeGreaterThan(0)
|
||||
@@ -337,23 +356,23 @@ describe('handler carrier-layer statuses', () => {
|
||||
it('500s when the impl itself throws', async () => {
|
||||
const crashing = toFetchHandler(fakeApi({ crashOn: 'session.list' }))
|
||||
const body = JSON.stringify({ type: 'client-request', rpcId: 'r-11', method: 'session.list', payload: {} })
|
||||
const response = await crashing.fetch(new Request('http://x/api/session.list', { method: 'POST', body }))
|
||||
const response = await crashing.fetch(new Request('http://x/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body }))
|
||||
expect(response.status).toBe(500)
|
||||
expect(await response.text()).toContain('impl crashed')
|
||||
})
|
||||
|
||||
it('routes /api/respond, rejecting malformed client-responses as a receipt', async () => {
|
||||
const good = JSON.stringify({ type: 'client-response', rpcId: 'known', result: { ok: true, value: null } })
|
||||
const goodReceipt: unknown = await (await handler.fetch(new Request('http://x/api/respond', { method: 'POST', body: good }))).json()
|
||||
const goodReceipt: unknown = await (await handler.fetch(new Request('http://x/api/respond', { method: 'POST', headers: { 'content-type': 'application/json' }, body: good }))).json()
|
||||
expect(goodReceipt).toEqual({ accepted: true })
|
||||
const bad = JSON.stringify({ type: 'client-request', rpcId: 'r', method: 'x', payload: {} })
|
||||
const badReceipt: unknown = await (await handler.fetch(new Request('http://x/api/respond', { method: 'POST', body: bad }))).json()
|
||||
const badReceipt: unknown = await (await handler.fetch(new Request('http://x/api/respond', { method: 'POST', headers: { 'content-type': 'application/json' }, body: bad }))).json()
|
||||
expect(badReceipt).toEqual({ accepted: false, reason: 'bad-response' })
|
||||
})
|
||||
|
||||
it('accepts (url, init) form fetch invocation', async () => {
|
||||
const body = JSON.stringify({ type: 'client-request', rpcId: 'r-12', method: 'session.list', payload: {} })
|
||||
const response = await handler.fetch('http://x/api/session.list', { method: 'POST', body })
|
||||
const response = await handler.fetch('http://x/api/session.list', { method: 'POST', headers: { 'content-type': 'application/json' }, body })
|
||||
expect(response.status).toBe(200)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -12,7 +12,11 @@ import {
|
||||
sessionModelsValueSchema, sessionPromptRequestSchema, sessionPromptValueSchema,
|
||||
sessionSelectModelRequestSchema, sessionSelectModelValueSchema, sessionSummarySchema,
|
||||
} from '../src/api/sessions.schema.ts'
|
||||
import { hostDescribeRequestSchema, hostDescribeValueSchema } from '../src/api/host.schema.ts'
|
||||
import {
|
||||
hostCreateDirectoryRequestSchema, hostCreateDirectoryValueSchema,
|
||||
hostDescribeRequestSchema, hostDescribeValueSchema,
|
||||
hostListDirectoryRequestSchema, hostListDirectoryValueSchema,
|
||||
} from '../src/api/host.schema.ts'
|
||||
import {
|
||||
workspaceCreateRequestSchema, workspaceCreateValueSchema, workspaceIdSchema,
|
||||
workspaceDeleteRequestSchema, workspaceDeleteValueSchema,
|
||||
@@ -227,6 +231,26 @@ describe('host domain schemas', () => {
|
||||
expect(value.attachedSessions).toBe(2)
|
||||
expect(hostDescribeValueSchema.parse({ version: '1', cwd: '/x', attachedSessions: 0 }).provider).toBeUndefined()
|
||||
})
|
||||
|
||||
it('validates the browse listing/creation payloads', () => {
|
||||
expect(hostListDirectoryRequestSchema.parse({})).toEqual({})
|
||||
expect(hostListDirectoryRequestSchema.parse({ path: '/x' })).toEqual({ path: '/x' })
|
||||
const listing = hostListDirectoryValueSchema.parse({
|
||||
path: '/home/u/p',
|
||||
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()
|
||||
}
|
||||
expect(hostCreateDirectoryValueSchema.parse({ path: '/x/new' })).toEqual({ path: '/x/new' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('workspace domain schemas', () => {
|
||||
|
||||
@@ -56,8 +56,14 @@
|
||||
{
|
||||
"path": "../../workspace/workspace"
|
||||
},
|
||||
{
|
||||
"path": "../directory-picker"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
},
|
||||
{
|
||||
"path": "../../util/native-command"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
6
packages/host/directory-picker-browse/README.i18n.yaml
Normal file
6
packages/host/directory-picker-browse/README.i18n.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# 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: 318380405214d5f25ad77e348c4e134a8981ffb3
|
||||
README.zh.md: 2f88f64cc2974b8535e34eb9798f512ea109b754
|
||||
23
packages/host/directory-picker-browse/README.md
Normal file
23
packages/host/directory-picker-browse/README.md
Normal file
@@ -0,0 +1,23 @@
|
||||
# @deepseek-ai/dsh-host-directory-picker-browse
|
||||
|
||||
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. One `list` call returns at most `maxEntries` rows (config, default 1000 — the bound GitHub's web UI applies to directory listings), and the level streams through a bounded window so memory stays O(maxEntries) no matter how many children the directory holds: a cut level keeps the name-sorted head, counts hidden rows against the bound, probes only windowed candidates, and reports `truncated: true` so the client can say the level is incomplete (a windowed broken symlink is not backfilled from beyond the window — the eviction already marks the level truncated); window insertion is binary with an O(1) full-window tail rejection, and `list` threads the caller's `AbortSignal` so a disconnect or timeout stops the scan instead of letting it outlive the caller. 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).
|
||||
|
||||
**Dual-face package**: the browser half (`./client`) fills [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes with the in-app **Select Workspace Directory** dialog (figma `Harness` 813-23126 family — Miller two-column view, breadcrumb with a click-to-edit path zone, nested New-folder dialog), driving `host.listDirectory`/`host.createDirectory` and registering its own locale namespace (`directory-browser`, zh default / en). One cordis.yml row therefore composes both sides of the browse interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind).
|
||||
|
||||
## Model Experience
|
||||
|
||||
None, as the backend serves the GUI host's directory selection; nothing here reaches a model request.
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
None; this package neither assembles nor sends a provider request.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
- **Windows hidden attribute is not read** — Node dirents do not expose `FILE_ATTRIBUTE_HIDDEN`, so `hidden` means dot-prefixed on every platform until a native probe is worth its cost.
|
||||
- **No drive-root enumeration** — on Windows the ancestry stops at the drive root; crossing drives waits for the browser UI's path-entry affordance rather than an enumeration primitive here.
|
||||
- **Whole-filesystem scope** — no per-deployment browse-root restriction; `workspace.create` accepts arbitrary paths today, so a root here would be UX scoping, not a boundary — deferred until a deployment needs it.
|
||||
23
packages/host/directory-picker-browse/README.zh.md
Normal file
23
packages/host/directory-picker-browse/README.zh.md
Normal file
@@ -0,0 +1,23 @@
|
||||
# @deepseek-ai/dsh-host-directory-picker-browse
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
[目录选择 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 或当前盘符之下。单次 `list` 至多返回 `maxEntries` 行(配置项,默认 1000——GitHub 网页端对目录列举采用的同一上限),且层级以流式方式经过一个有界窗口,无论目录有多少子项内存都保持 O(maxEntries):被截断的层级保留按名排序的头部、隐藏行计入上限、只探测窗口内候选,并报告 `truncated: true`,供客户端提示层级不完整(窗口内的断链符号链接不会从窗口外回填——发生过驱逐本身已把层级标记为截断);窗口插入为二分查找、满窗尾部单次比较即拒绝,且 `list` 透传调用方的 `AbortSignal`,断连或超时会停止扫描而不是让它在调用方离开后继续。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。
|
||||
|
||||
**双面包**:browser half(`./client`)以应用内 **选择工作区目录** 对话框(figma `Harness` 813-23126 家族——Miller 双列视图、带点击即编辑路径区的面包屑、嵌套新建文件夹对话框)填入 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞,驱动 `host.listDirectory`/`host.createDirectory`,并注册自己的 locale 命名空间(`directory-browser`,zh 默认/en)。因此一行 cordis.yml 同时组合浏览交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。
|
||||
|
||||
## 模型体验
|
||||
|
||||
无。该后端服务于 GUI 宿主的目录选择;这里没有任何内容进入模型请求。
|
||||
|
||||
#### KV 缓存影响
|
||||
|
||||
无;该包既不组装也不发送提供方请求。
|
||||
|
||||
## 已知限制与延期工作
|
||||
|
||||
- **不读取 Windows 隐藏属性**——Node 的 dirent 不暴露 `FILE_ATTRIBUTE_HIDDEN`,因此在所有平台上 `hidden` 都意味着点前缀,直到原生探测值回其成本为止。
|
||||
- **不枚举盘符根**——Windows 上祖先链止于盘符根;跨盘依赖浏览器 UI 的路径输入入口,而不是这里的枚举原语。
|
||||
- **全盘可浏览**——没有按部署限定的浏览根;`workspace.create` 今天就接受任意路径,这里的根只会是 UX 范围而非边界——等到有部署需要时再做。
|
||||
68
packages/host/directory-picker-browse/package.json
Normal file
68
packages/host/directory-picker-browse/package.json
Normal file
@@ -0,0 +1,68 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-host-directory-picker-browse",
|
||||
"description": "In-app browsing backend of the directory-picker seam (listing/creation primitives over the host filesystem)",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./invariant": {
|
||||
"types": "./lib/types/invariant.d.ts",
|
||||
"default": "./lib/invariant.js"
|
||||
},
|
||||
"./client": {
|
||||
"types": "./lib/types/client/index.d.ts",
|
||||
"default": "./lib/client.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/invariant.js",
|
||||
"lib/client.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"src"
|
||||
],
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"@deepseek-ai/dsh-host-directory-picker": "workspace:^",
|
||||
"clsx": "^2.0.0",
|
||||
"schemastery": "^3.18.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/dsh-client-locale": "^0.0.1",
|
||||
"@deepseek-ai/dsh-client-runtime": "^0.0.1",
|
||||
"@deepseek-ai/dsh-client-ui-primitives": "^0.0.1",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "^0.0.1",
|
||||
"@deepseek-ai/dsh-client-ui-workspace": "^0.0.1",
|
||||
"@deepseek-ai/dsh-invariants": "^0.0.1",
|
||||
"cordis": "^4.0.0-rc.7",
|
||||
"react": "^18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-client-locale": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-runtime": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-primitives": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-workspace": "workspace:^",
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
"@types/react": "~18.3.1",
|
||||
"cordis": "^4.0.0-rc.7",
|
||||
"react": "^18.2.0"
|
||||
},
|
||||
"dshClient": {
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-client-runtime",
|
||||
"@deepseek-ai/dsh-client-ui-workspace",
|
||||
"@deepseek-ai/dsh-client-locale"
|
||||
],
|
||||
"platform": "web"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
/* Directory-browser dialog (figma 813-23126 family). The shared Modal renders
|
||||
* headless here — mask, card, Escape only — and this module owns the figma
|
||||
* frame: 600×420 card (viewport-clamped), header (title + crumbs, l3 separator),
|
||||
* the one-or-two-column Miller content, and the bordered footer. */
|
||||
|
||||
/* Doubled class beats Modal's own .dialog regardless of stylesheet order. */
|
||||
/* Short viewports clamp the card: header/footer are flex-none and the
|
||||
* columns scroll, so shrinking the height keeps Open/Cancel reachable
|
||||
* instead of clipping them below a fixed overlay. */
|
||||
.dialog.dialog {
|
||||
width: min(600px, 100%);
|
||||
height: min(420px, calc(100dvh - 32px));
|
||||
padding: 0;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
/* Header block: pl24 pr14 pt22 pb12, 8px between title row and crumb row. */
|
||||
.header {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
flex: none;
|
||||
padding: 22px 14px 12px 24px;
|
||||
border-bottom: 1px solid var(--dsw-alias-border-l3);
|
||||
}
|
||||
|
||||
.title {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
min-height: 28px;
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
line-height: 24px;
|
||||
font-weight: 510;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.crumbBar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
min-height: 20px;
|
||||
}
|
||||
|
||||
/* Deep chains scroll inside the trail (the effect pins the tail into view)
|
||||
* so the edit zone to the right never leaves the bar. */
|
||||
/* The Miller columns keep their own row so a status/error line below never
|
||||
* competes with the fixed column widths for horizontal space. */
|
||||
/* A narrow viewport shrinks the dialog below two fixed panes; the row
|
||||
* scrolls horizontally (the effect pins the child pane into view) so
|
||||
* descent never hides behind the Modal's clipping. */
|
||||
.millerRow {
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
gap: 20px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.crumbTrail {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
overflow-x: auto;
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.crumbSeat {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
flex: none;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.crumb {
|
||||
border: none;
|
||||
background: transparent;
|
||||
padding: 0;
|
||||
max-width: 160px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
font-weight: 500;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.crumb:hover {
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.crumbChevron {
|
||||
flex: none;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
/* The empty remainder of the bar: invisible, but a real click target that
|
||||
* flips the bar into path-edit mode. */
|
||||
.crumbEditZone {
|
||||
flex: 1 0 34px;
|
||||
min-width: 34px;
|
||||
align-self: stretch;
|
||||
border: none;
|
||||
background: transparent;
|
||||
cursor: text;
|
||||
}
|
||||
|
||||
.pathInput {
|
||||
box-sizing: border-box;
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
height: 24px;
|
||||
padding: 0 8px;
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
border-radius: 8px;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
/* Miller content: pt16 px24; columns are 256 wide (or full width solo) with
|
||||
* the hairline divider centered between them; each column scrolls alone. */
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1 1 0;
|
||||
min-height: 0;
|
||||
padding: 16px 24px 0;
|
||||
}
|
||||
|
||||
.column {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
width: 256px;
|
||||
flex: none;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.columnWide {
|
||||
width: 100%;
|
||||
flex: 1 1 0;
|
||||
}
|
||||
|
||||
.divider {
|
||||
flex: none;
|
||||
width: 1px;
|
||||
background: var(--dsw-alias-border-l3);
|
||||
}
|
||||
|
||||
.rowSeat {
|
||||
display: flex;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.row {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
height: 28px;
|
||||
flex: none;
|
||||
padding: 4px;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.row:hover {
|
||||
background: var(--dsw-alias-interactive-bg-hover);
|
||||
}
|
||||
|
||||
/* Selection: pill fill + the open-folder glyph in the info accent. */
|
||||
.rowSelected,
|
||||
.rowSelected:hover {
|
||||
background: var(--dsw-alias-interactive-bg-active, var(--dsw-alias-interactive-bg-hover));
|
||||
}
|
||||
|
||||
.rowIcon {
|
||||
flex: none;
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.rowIconSelected {
|
||||
flex: none;
|
||||
color: var(--dsw-alias-button-info-fill);
|
||||
}
|
||||
|
||||
.rowName {
|
||||
flex: 1 1 0;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 13px;
|
||||
line-height: 20px;
|
||||
font-weight: 500;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.rowChevron {
|
||||
flex: none;
|
||||
color: var(--dsw-alias-label-tertiary);
|
||||
}
|
||||
|
||||
.status,
|
||||
.error {
|
||||
padding: 4px;
|
||||
font-size: 12px;
|
||||
line-height: 18px;
|
||||
}
|
||||
|
||||
.status {
|
||||
color: var(--dsw-alias-label-secondary);
|
||||
}
|
||||
|
||||
.error {
|
||||
color: var(--dsw-alias-state-error-primary);
|
||||
}
|
||||
|
||||
/* Footer: l3 separator on top, pt12 px24, New-folder pinned left; the fixed
|
||||
* card leaves the figma 28px below the 36px buttons. */
|
||||
.footerBar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
/* Narrow viewports wrap the confirm/cancel pair onto their own row
|
||||
* instead of clipping Open past the card's hidden overflow. */
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
flex: none;
|
||||
padding: 12px 24px 28px;
|
||||
border-top: 1px solid var(--dsw-alias-border-l3);
|
||||
}
|
||||
|
||||
.footerGap {
|
||||
flex: 1 1 0;
|
||||
}
|
||||
|
||||
.footerAction {
|
||||
min-width: 72px;
|
||||
}
|
||||
|
||||
/* Nested create dialog (figma 813:23278): a small centered card. */
|
||||
.createDialog.createDialog {
|
||||
width: min(380px, 100%);
|
||||
padding: 0;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.createBody {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 12px;
|
||||
padding: 22px 24px 20px;
|
||||
}
|
||||
|
||||
.createTitle {
|
||||
margin: 0;
|
||||
font-size: 16px;
|
||||
line-height: 24px;
|
||||
font-weight: 510;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.createIn {
|
||||
margin: 0;
|
||||
font-size: 14px;
|
||||
line-height: 22px;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.createInput {
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
height: 44px;
|
||||
padding: 7px 14px;
|
||||
border: 1px solid var(--dsw-alias-border-l2);
|
||||
border-radius: 22px;
|
||||
outline: none;
|
||||
background: transparent;
|
||||
font-size: 14px;
|
||||
line-height: 22px;
|
||||
color: var(--dsw-alias-label-primary);
|
||||
}
|
||||
|
||||
.createInput::placeholder {
|
||||
color: var(--dsw-alias-label-caption);
|
||||
}
|
||||
|
||||
.createActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
@@ -0,0 +1,503 @@
|
||||
/**
|
||||
* The in-app workspace-directory browser (figma Harness 813-23126 family): a
|
||||
* 600×420 dialog (clamped to short/narrow viewports — the Miller row scrolls
|
||||
* sideways, the columns scroll down) whose header carries the title, the selection-path
|
||||
* breadcrumb, and a click-to-edit path zone; below it a Miller view — one
|
||||
* full-width level until a row is selected, then two 256px columns (level |
|
||||
* selected folder's children) around a hairline divider. Selecting in the
|
||||
* right column shifts the view one level deeper. "New folder" opens a nested
|
||||
* create dialog targeting the selected folder (or the level itself) and
|
||||
* selects the created folder. Open adopts the selected folder, falling back
|
||||
* to the listed level. Pure consumer of the injected browse calls — the
|
||||
* owning flow decides what "Open" means and owns the workspace-creation
|
||||
* error surface. Hidden entries are host-flagged and filtered here (a
|
||||
* show-hidden toggle is deferred work, client-side only).
|
||||
*/
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import clsx from 'clsx'
|
||||
import {
|
||||
Button, IconChevronRightOutline14, IconFolderClose16, IconFolderOpen16, IconPlusOutline16, Modal,
|
||||
} from '@deepseek-ai/dsh-client-ui-primitives'
|
||||
import type { DirectoryEntry, DirectoryListing } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { DirectoryBrowseError } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { Translate } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import css from './DirectoryBrowser.module.css'
|
||||
|
||||
/** Owner-supplied browser props: browse calls, pick semantics, and copy. */
|
||||
export interface DirectoryBrowserProps {
|
||||
/** Dialog visibility (owner-local; closed unmounts nothing but resets on reopen). */
|
||||
open: boolean
|
||||
/** List one directory level (absent path = the Host home directory); the signal aborts a superseded scan on the wire. */
|
||||
listDirectory: (path?: string, signal?: AbortSignal) => Promise<DirectoryListing>
|
||||
/** Create one child directory under an existing parent. */
|
||||
createDirectory: (path: string, name: string) => Promise<string>
|
||||
/** The operator confirmed a directory (the selection, else the listed level). */
|
||||
onOpen: (path: string) => void
|
||||
/** Close without picking (mask, Escape, Cancel). */
|
||||
onClose: () => void
|
||||
/** The owner's confirm is in flight: Open disables, the view freezes. */
|
||||
busy: boolean
|
||||
/** Localized copy. */
|
||||
t: Translate
|
||||
}
|
||||
|
||||
/** Failure text: the Host business message when typed, else the throw's text. */
|
||||
function failureText(error: unknown): string {
|
||||
if (error instanceof DirectoryBrowseError) return error.rpcError.message
|
||||
return error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
|
||||
/**
|
||||
* Breadcrumb rows for display: inside the home subtree the chain starts at a
|
||||
* localized Home crumb; outside it the full ancestry shows, the root labeled
|
||||
* by its own path.
|
||||
*/
|
||||
function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryEntry[] {
|
||||
const homeIndex = listing.crumbs.findIndex(crumb => crumb.path === listing.home)
|
||||
if (homeIndex === -1) return listing.crumbs
|
||||
const tail = listing.crumbs.slice(homeIndex + 1)
|
||||
return [{ name: homeLabel, path: listing.home, hidden: false }, ...tail]
|
||||
}
|
||||
|
||||
/** One column of folder rows (the Miller view renders one or two of these). */
|
||||
function LevelColumn({ entries, selectedPath, busy, onPick, wide }: {
|
||||
entries: readonly DirectoryEntry[]
|
||||
selectedPath: string | null
|
||||
busy: boolean
|
||||
onPick: (entry: DirectoryEntry) => void
|
||||
wide: boolean
|
||||
}) {
|
||||
return (
|
||||
<div className={clsx(css.column, wide && css.columnWide)} role="list">
|
||||
{entries.filter(entry => !entry.hidden).map((entry) => {
|
||||
const selected = entry.path === selectedPath
|
||||
return (
|
||||
// The wrapper carries the list semantics; the row keeps its NATIVE
|
||||
// button role so assistive technology exposes an actionable control.
|
||||
<span key={entry.path} role="listitem" className={css.rowSeat}>
|
||||
<button
|
||||
type="button"
|
||||
aria-current={selected || undefined}
|
||||
className={clsx(css.row, selected && css.rowSelected)}
|
||||
disabled={busy}
|
||||
onClick={() => { onPick(entry) }}
|
||||
>
|
||||
{selected
|
||||
? <IconFolderOpen16 size={16} className={css.rowIconSelected} />
|
||||
: <IconFolderClose16 size={16} className={css.rowIcon} />}
|
||||
<span className={css.rowName}>{entry.name}</span>
|
||||
<IconChevronRightOutline14 size={12} className={css.rowChevron} />
|
||||
</button>
|
||||
</span>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Render the directory-browser dialog.
|
||||
* @param props - owner-controlled browser props.
|
||||
* @returns the dialog element (null while closed, via Modal).
|
||||
*/
|
||||
export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, onClose, busy, t }: DirectoryBrowserProps) {
|
||||
// Miller state: the listed level, the selected row in it, and the selected
|
||||
// folder's own listing (the right column; null while nothing is selected).
|
||||
const [parent, setParent] = useState<DirectoryListing | null>(null)
|
||||
const [selected, setSelected] = useState<DirectoryEntry | null>(null)
|
||||
const [child, setChild] = useState<DirectoryListing | null>(null)
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string | null>(null)
|
||||
// Path-edit state: null = breadcrumb mode; a string = the draft being typed.
|
||||
const [pathDraft, setPathDraft] = useState<string | null>(null)
|
||||
// Create-folder state: null = closed; a string = the nested dialog's draft.
|
||||
const [folderDraft, setFolderDraft] = useState<string | null>(null)
|
||||
const [creatingFolder, setCreatingFolder] = useState(false)
|
||||
const [createError, setCreateError] = useState<string | null>(null)
|
||||
const requestSeq = useRef(0)
|
||||
// The in-flight listing's controller: superseding intent aborts the wire
|
||||
// request too — the Host stops scanning — instead of only discarding the
|
||||
// eventual result while the scan keeps consuming host resources.
|
||||
const scanController = useRef<AbortController | null>(null)
|
||||
// Bumped on every open/close edge: settlements from a previous open (a
|
||||
// pending creation included) must never mutate a reopened dialog.
|
||||
const openGeneration = useRef(0)
|
||||
// Deep ancestry overflows the trail; keep its tail (the current directory
|
||||
// and the edit zone beside it) in view whenever the chain changes.
|
||||
const crumbTrailRef = useRef<HTMLSpanElement | null>(null)
|
||||
// IME confirmation (Enter selecting a candidate) must not submit either
|
||||
// text input; the same guard the workspace-name inputs carry, shared by
|
||||
// the path editor and the folder-name input.
|
||||
const composingRef = useRef(false)
|
||||
// HMR/unmount invalidation: a completion from a disposed flow must not
|
||||
// update state or issue follow-up requests from a dead component.
|
||||
useEffect(() => () => {
|
||||
requestSeq.current += 1
|
||||
openGeneration.current += 1
|
||||
scanController.current?.abort()
|
||||
}, [])
|
||||
const compositionGuard = {
|
||||
onCompositionStart: () => { composingRef.current = true },
|
||||
onCompositionEnd: () => { composingRef.current = false },
|
||||
}
|
||||
|
||||
/** Newer intent wins: invalidate the pending listing's settlement AND abort its wire request. */
|
||||
const supersede = useCallback((): number => {
|
||||
scanController.current?.abort()
|
||||
scanController.current = null
|
||||
return ++requestSeq.current
|
||||
}, [])
|
||||
|
||||
/** Launch one listing under a fresh controller so a later supersession can abort it. */
|
||||
const launchListing = useCallback((path: string | undefined): { seq: number; scan: Promise<DirectoryListing> } => {
|
||||
const seq = supersede()
|
||||
const controller = new AbortController()
|
||||
scanController.current = controller
|
||||
return { seq, scan: listDirectory(path, controller.signal) }
|
||||
}, [supersede, listDirectory])
|
||||
|
||||
/** Replace the whole view with one freshly listed level (no selection). */
|
||||
const navigate = useCallback((path?: string) => {
|
||||
const { seq, scan } = launchListing(path)
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
scan.then((next) => {
|
||||
if (seq !== requestSeq.current) return
|
||||
setParent(next)
|
||||
setSelected(null)
|
||||
setChild(null)
|
||||
setLoading(false)
|
||||
setPathDraft(null)
|
||||
}, (reason: unknown) => {
|
||||
if (seq !== requestSeq.current) return
|
||||
setLoading(false)
|
||||
setError(failureText(reason))
|
||||
})
|
||||
}, [launchListing])
|
||||
|
||||
/** Select a row of the listed level and preview its children on the right. */
|
||||
const select = useCallback((entry: DirectoryEntry) => {
|
||||
const { seq, scan } = launchListing(entry.path)
|
||||
setSelected(entry)
|
||||
setChild(null)
|
||||
setLoading(true)
|
||||
setError(null)
|
||||
scan.then((next) => {
|
||||
if (seq !== requestSeq.current) return
|
||||
setChild(next)
|
||||
setLoading(false)
|
||||
}, (reason: unknown) => {
|
||||
if (seq !== requestSeq.current) return
|
||||
setLoading(false)
|
||||
setError(failureText(reason))
|
||||
// An unreadable selection cannot be the committing target while the
|
||||
// breadcrumb still names the level: fall back to the single pane.
|
||||
setSelected(null)
|
||||
})
|
||||
}, [launchListing])
|
||||
|
||||
/** A right-column pick advances the view one level: child becomes the level. */
|
||||
const advance = useCallback((entry: DirectoryEntry) => {
|
||||
/* v8 ignore next -- narrowing guard: the right column only renders with a child listing. */
|
||||
if (child === null) return
|
||||
setParent(child)
|
||||
select(entry)
|
||||
}, [child, select])
|
||||
|
||||
// Every open starts fresh at the Host home directory; closing invalidates
|
||||
// any in-flight response so a late arrival cannot repopulate a closed dialog.
|
||||
useEffect(() => {
|
||||
openGeneration.current += 1
|
||||
if (open) {
|
||||
setParent(null)
|
||||
setSelected(null)
|
||||
setChild(null)
|
||||
setCreatingFolder(false)
|
||||
navigate()
|
||||
return
|
||||
}
|
||||
supersede()
|
||||
setError(null)
|
||||
setPathDraft(null)
|
||||
setFolderDraft(null)
|
||||
setCreateError(null)
|
||||
}, [open, navigate, supersede])
|
||||
|
||||
/** The folder a create or Open acts on: the selection, else the listed level. */
|
||||
const targetPath = selected?.path ?? parent?.path ?? null
|
||||
const targetName = selected?.name
|
||||
?? (parent === null ? '' : (displayCrumbs(parent, t('browser.home')).at(-1)?.name ?? parent.path))
|
||||
|
||||
const confirmCreate = (): void => {
|
||||
/* v8 ignore next -- reentry fence: the nested dialog only renders with a target and disables while creating. */
|
||||
if (targetPath === null || folderDraft === null || creatingFolder) return
|
||||
// Trim only rejects an all-whitespace draft; the Host gets the original
|
||||
// spelling — the backend accepts any non-blank single segment verbatim,
|
||||
// and trimming here would create (and select) a different sibling.
|
||||
const name = folderDraft
|
||||
if (name.trim() === '') return
|
||||
setCreatingFolder(true)
|
||||
setCreateError(null)
|
||||
const generation = openGeneration.current
|
||||
createDirectory(targetPath, name).then((createdPath) => {
|
||||
// A settlement from a closed (possibly reopened) flow must not touch
|
||||
// the fresh dialog or issue a relist against the stale target.
|
||||
if (generation !== openGeneration.current) return
|
||||
setCreatingFolder(false)
|
||||
setFolderDraft(null)
|
||||
// Land like a right-column pick (figma 802:57446 → 813:23278 flow): the
|
||||
// create target becomes the listed level and the new folder its selection.
|
||||
const { seq, scan } = launchListing(targetPath)
|
||||
setLoading(true)
|
||||
scan.then((level) => {
|
||||
/* v8 ignore next -- same fence as navigate/select; the modal blocks superseding input */
|
||||
if (seq !== requestSeq.current) return
|
||||
setParent(level)
|
||||
setLoading(false)
|
||||
select({ name, path: createdPath, hidden: false })
|
||||
}, (reason: unknown) => {
|
||||
/* v8 ignore next -- same fence as navigate/select; the modal blocks superseding input */
|
||||
if (seq !== requestSeq.current) return
|
||||
setLoading(false)
|
||||
setError(failureText(reason))
|
||||
})
|
||||
}, (reason: unknown) => {
|
||||
if (generation !== openGeneration.current) return
|
||||
setCreatingFolder(false)
|
||||
setCreateError(failureText(reason))
|
||||
})
|
||||
}
|
||||
|
||||
// After the hooks: a closed dialog renders nothing and evaluates no copy.
|
||||
const crumbSource = child ?? parent
|
||||
const crumbs = crumbSource === null ? [] : displayCrumbs(crumbSource, t('browser.home'))
|
||||
const crumbTail = crumbs.at(-1)?.path
|
||||
useEffect(() => {
|
||||
const trail = crumbTrailRef.current
|
||||
if (trail !== null) trail.scrollLeft = trail.scrollWidth
|
||||
}, [crumbTail])
|
||||
// On viewports too narrow for both fixed panes the Miller row scrolls;
|
||||
// whenever a child preview lands, pin it into view the way the crumb tail
|
||||
// pins — otherwise descent is unreachable on a phone-width window.
|
||||
const millerRowRef = useRef<HTMLDivElement | null>(null)
|
||||
const childPath = child?.path
|
||||
useEffect(() => {
|
||||
const row = millerRowRef.current
|
||||
if (row !== null && childPath !== undefined) row.scrollLeft = row.scrollWidth
|
||||
}, [childPath])
|
||||
|
||||
if (!open) return null
|
||||
const twoPane = selected !== null
|
||||
// The nested create dialog owns the interaction while open: Modal has no
|
||||
// focus trap, so every parent control goes inert (Shift-Tab or AT must not
|
||||
// close, adopt, or retarget underneath the child).
|
||||
const parentInert = busy || folderDraft !== null
|
||||
// An uncommitted path draft makes targetPath stale relative to the header:
|
||||
// committing actions must not act on the previous selection/listing while
|
||||
// a different path is displayed.
|
||||
const draftPending = pathDraft !== null
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
// Escape and mask reach every mounted Modal's document listener; while
|
||||
// the nested create dialog is up only that topmost dialog may close
|
||||
// (its own guard keeps an in-flight creation open), and an in-flight
|
||||
// adoption pins the flow — dismissing it would leave the owner's
|
||||
// createWorkspace to land after an apparent cancel.
|
||||
onClose={() => { if (folderDraft === null && !busy) onClose() }}
|
||||
title={t('browser.title')}
|
||||
className={clsx(css.dialog)}
|
||||
headless
|
||||
>
|
||||
<div className={css.header}>
|
||||
<h2 className={css.title}>{t('browser.title')}</h2>
|
||||
<div className={css.crumbBar}>
|
||||
{pathDraft === null
|
||||
? (
|
||||
<>
|
||||
<span className={css.crumbTrail} role="navigation" ref={crumbTrailRef}>
|
||||
{crumbs.map((crumb, index) => (
|
||||
<span key={crumb.path} className={css.crumbSeat}>
|
||||
{index > 0 && <IconChevronRightOutline14 size={12} className={css.crumbChevron} />}
|
||||
<button
|
||||
type="button"
|
||||
className={css.crumb}
|
||||
disabled={parentInert}
|
||||
onClick={() => { navigate(crumb.path) }}
|
||||
>
|
||||
{crumb.name}
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
{/* The empty zone right of the crumbs is the path-edit affordance. */}
|
||||
<button
|
||||
type="button"
|
||||
className={css.crumbEditZone}
|
||||
aria-label={t('browser.editPath')}
|
||||
// Stays available with no listed level: when the home
|
||||
// listing itself fails, typing an absolute path is the one
|
||||
// remaining way forward.
|
||||
disabled={parentInert}
|
||||
onClick={() => {
|
||||
// Opening the editor supersedes any pending listing: a
|
||||
// settlement landing before the first keystroke would
|
||||
// otherwise close the editor via navigate's draft reset.
|
||||
supersede()
|
||||
setLoading(false)
|
||||
setPathDraft(selected?.path ?? parent?.path ?? '')
|
||||
}}
|
||||
/>
|
||||
</>
|
||||
)
|
||||
: (
|
||||
<input
|
||||
className={css.pathInput}
|
||||
value={pathDraft}
|
||||
aria-label={t('browser.editPath')}
|
||||
autoFocus
|
||||
disabled={parentInert}
|
||||
onChange={(event) => {
|
||||
// Editing the draft supersedes any in-flight navigation:
|
||||
// its completion must neither clear the newer text nor
|
||||
// repopulate the view with the older path.
|
||||
supersede()
|
||||
setLoading(false)
|
||||
setPathDraft(event.target.value)
|
||||
}}
|
||||
{...compositionGuard}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' && !composingRef.current) {
|
||||
event.preventDefault()
|
||||
// Trim only detects a blank draft; the Host gets the
|
||||
// original text — a real directory name may end in
|
||||
// whitespace, and trimming would list its sibling.
|
||||
if (pathDraft.trim() !== '') navigate(pathDraft)
|
||||
}
|
||||
if (event.key === 'Escape') {
|
||||
event.stopPropagation()
|
||||
// Cancel also withdraws a navigation the editor already
|
||||
// launched: its late success must not jump to the
|
||||
// cancelled path, so the pending request is superseded
|
||||
// and the view leaves the loading state.
|
||||
supersede()
|
||||
setLoading(false)
|
||||
setPathDraft(null)
|
||||
setError(null)
|
||||
// Editing may have superseded the selection's preview
|
||||
// request; a selection with no preview would render a
|
||||
// half-empty two-pane view, so cancel falls back to the
|
||||
// single-pane level.
|
||||
if (child === null) setSelected(null)
|
||||
// With no level listed yet (the editor superseded the
|
||||
// initial home listing), plain cancellation would leave a
|
||||
// permanently blank picker: restart the home listing.
|
||||
if (parent === null) navigate()
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
<div className={css.content}>
|
||||
<div className={css.millerRow} ref={millerRowRef}>
|
||||
{parent !== null && (
|
||||
<LevelColumn
|
||||
entries={parent.entries}
|
||||
selectedPath={selected?.path ?? null}
|
||||
busy={parentInert}
|
||||
onPick={select}
|
||||
wide={!twoPane}
|
||||
/>
|
||||
)}
|
||||
{twoPane && <span className={css.divider} />}
|
||||
{twoPane && child !== null && (
|
||||
<LevelColumn
|
||||
entries={child.entries}
|
||||
selectedPath={null}
|
||||
busy={parentInert}
|
||||
onPick={advance}
|
||||
wide={false}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{loading && <div className={css.status} role="status">{t('browser.loading')}</div>}
|
||||
{/* The backend bounds a level at its complete-result limit; say so
|
||||
* whenever a visible pane was cut instead of letting the tail of a
|
||||
* huge directory go silently missing. */}
|
||||
{(parent?.truncated === true || child?.truncated === true) && !loading
|
||||
&& <div className={css.status} role="status">{t('browser.truncated')}</div>}
|
||||
{error !== null && <div className={css.error} role="alert">{error}</div>}
|
||||
</div>
|
||||
<div className={css.footerBar}>
|
||||
<Button
|
||||
variant="outline"
|
||||
icon={<IconPlusOutline16 size={14} />}
|
||||
disabled={parent === null || loading || parentInert || draftPending}
|
||||
onClick={() => {
|
||||
setFolderDraft('')
|
||||
setCreateError(null)
|
||||
}}
|
||||
>
|
||||
{t('browser.newFolder')}
|
||||
</Button>
|
||||
<span className={css.footerGap} />
|
||||
<Button variant="outline" className={clsx(css.footerAction)} disabled={parentInert} onClick={onClose}>{t('browser.cancel')}</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
className={clsx(css.footerAction)}
|
||||
disabled={targetPath === null || loading || parentInert || draftPending}
|
||||
/* v8 ignore next -- narrowing guard: Open disables while no target exists. */
|
||||
onClick={() => { if (targetPath !== null) onOpen(targetPath) }}
|
||||
>
|
||||
{t('browser.open')}
|
||||
</Button>
|
||||
</div>
|
||||
{/* Nested create dialog (figma 813:23278): names one folder inside the target. */}
|
||||
<Modal
|
||||
open={folderDraft !== null}
|
||||
onClose={() => { if (!creatingFolder) setFolderDraft(null) }}
|
||||
title={t('browser.newFolder')}
|
||||
className={clsx(css.createDialog)}
|
||||
headless
|
||||
>
|
||||
<div className={css.createBody}>
|
||||
<h3 className={css.createTitle}>{t('browser.newFolder')}</h3>
|
||||
<p className={css.createIn}>{t('browser.createIn', { name: targetName })}</p>
|
||||
<input
|
||||
className={css.createInput}
|
||||
value={folderDraft ?? ''}
|
||||
aria-label={t('browser.folderName')}
|
||||
placeholder={t('browser.untitledFolder')}
|
||||
autoFocus
|
||||
disabled={creatingFolder}
|
||||
onChange={(event) => { setFolderDraft(event.target.value) }}
|
||||
{...compositionGuard}
|
||||
onKeyDown={(event) => {
|
||||
if (event.key === 'Enter' && !composingRef.current) {
|
||||
event.preventDefault()
|
||||
confirmCreate()
|
||||
}
|
||||
if (event.key === 'Escape') {
|
||||
event.stopPropagation()
|
||||
if (!creatingFolder) setFolderDraft(null)
|
||||
}
|
||||
}}
|
||||
/>
|
||||
{createError !== null && <div className={css.error} role="alert">{createError}</div>}
|
||||
<div className={css.createActions}>
|
||||
<Button variant="outline" disabled={creatingFolder} onClick={() => { setFolderDraft(null) }}>{t('browser.cancel')}</Button>
|
||||
<Button
|
||||
variant="primary"
|
||||
disabled={creatingFolder || folderDraft === null || folderDraft.trim() === ''}
|
||||
onClick={confirmCreate}
|
||||
>
|
||||
{t('browser.create')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</Modal>
|
||||
)
|
||||
}
|
||||
43
packages/host/directory-picker-browse/src/client/flow.ts
Normal file
43
packages/host/directory-picker-browse/src/client/flow.ts
Normal file
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* The browse picking occupant (package-internal; the `./client` surface
|
||||
* exposes only the Loader exports). Same-package tests exercise it directly
|
||||
* through this module.
|
||||
*/
|
||||
import { createElement } from 'react'
|
||||
import type { ReactElement } from 'react'
|
||||
import type { DirectoryListing } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { Translate } from '@deepseek-ai/dsh-client-locale/client'
|
||||
// Type-only: the owner contract of the directory-flow holes.
|
||||
import type { DirectoryFlowOwnerProps } from '@deepseek-ai/dsh-client-ui-workspace/client'
|
||||
import { DirectoryBrowser } from './DirectoryBrowser.tsx'
|
||||
|
||||
/** Injected face: the browse wire calls and copy the dialog drives (bound in apply's closure). */
|
||||
export interface BrowseFlowInjected {
|
||||
/** List one directory level (absent path = the Host home directory); the signal aborts a superseded scan. */
|
||||
listDirectory: (path?: string, signal?: AbortSignal) => Promise<DirectoryListing>
|
||||
/** Create one child directory under an existing parent. */
|
||||
createDirectory: (path: string, name: string) => Promise<string>
|
||||
/** Localized dialog copy (this package's namespace). */
|
||||
t: Translate
|
||||
}
|
||||
|
||||
/**
|
||||
* Flow occupant: adapts the hole's owner conversation onto the browser
|
||||
* dialog — a confirmed directory is the picked path, dismissal is the
|
||||
* cancellation. Browse failures (unreadable targets, create conflicts) stay
|
||||
* inside the dialog's own alert surfaces, so the owner's `onError` arm is
|
||||
* never driven by this occupant.
|
||||
* @param props - owner conversation plus the injected browse face.
|
||||
* @returns the dialog element (renders nothing while closed).
|
||||
*/
|
||||
export function BrowseDirectoryFlow(props: DirectoryFlowOwnerProps & BrowseFlowInjected): ReactElement {
|
||||
return createElement(DirectoryBrowser, {
|
||||
open: props.open,
|
||||
busy: props.busy,
|
||||
listDirectory: props.listDirectory,
|
||||
createDirectory: props.createDirectory,
|
||||
t: props.t,
|
||||
onOpen: props.onPicked,
|
||||
onClose: props.onCancel,
|
||||
})
|
||||
}
|
||||
91
packages/host/directory-picker-browse/src/client/index.ts
Normal file
91
packages/host/directory-picker-browse/src/client/index.ts
Normal file
@@ -0,0 +1,91 @@
|
||||
/**
|
||||
* Browser half of the browse directory-picker backend: fills ui-workspace's
|
||||
* two directory-flow holes with the in-app Select Workspace Directory dialog
|
||||
* (figma `Harness` 813-23126 family), driving the node half's
|
||||
* `host.listDirectory`/`host.createDirectory` primitives. Mounting this
|
||||
* package therefore composes both sides of the browse interaction with one
|
||||
* cordis.yml row; no client code branches on a capability kind. The dialog's
|
||||
* copy is locale-registered here — the flow package owns its own strings.
|
||||
*/
|
||||
import { deferGroupRegistration } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
// Type-only: pulls the SlotMap merge declaring the directory-flow holes.
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-workspace/client'
|
||||
import type { BrowseFlowInjected } from './flow.ts'
|
||||
import { BrowseDirectoryFlow } from './flow.ts'
|
||||
|
||||
/** Locale namespace owning the browser dialog's copy. */
|
||||
const LOCALE_NS = 'directory-browser'
|
||||
|
||||
/** Required services (cordis fiber inject): the slot registry, the wire-facing workspace service, and locale. */
|
||||
export const inject = ['slots', 'workspaces', 'locale']
|
||||
|
||||
/**
|
||||
* Client plugin body: register the dialog's dictionaries and the browse flow
|
||||
* into both directory-flow holes (declaration-aware deferral — the declaring
|
||||
* ui-workspace entries may activate later, and an HMR collapse re-declares).
|
||||
* @param ctx - client root context.
|
||||
*/
|
||||
export function apply(ctx: ClientContext): void {
|
||||
ctx.effect(() => {
|
||||
// The two dictionaries land as a unit: if the second registration hits a
|
||||
// rival owner of the namespace, the first rolls back before the throw —
|
||||
// a failed activation must not squat the namespace's other locale.
|
||||
const disposers: (() => void)[] = []
|
||||
const dictionaries: [locale: string, dict: Record<string, string>][] = [
|
||||
['zh', {
|
||||
'browser.title': '选择工作区目录',
|
||||
'browser.home': '主目录',
|
||||
'browser.newFolder': '新建文件夹',
|
||||
'browser.folderName': '文件夹名称',
|
||||
'browser.createIn': '在"{name}"中新建文件夹',
|
||||
'browser.untitledFolder': '未命名文件夹',
|
||||
'browser.create': '创建',
|
||||
'browser.cancel': '取消',
|
||||
'browser.open': '打开',
|
||||
'browser.editPath': '编辑路径',
|
||||
'browser.loading': '加载中…',
|
||||
'browser.truncated': '文件夹过多,仅显示开头部分。',
|
||||
}],
|
||||
['en', {
|
||||
'browser.title': 'Select Workspace Directory',
|
||||
'browser.home': 'Home',
|
||||
'browser.newFolder': 'New folder',
|
||||
'browser.folderName': 'Folder name',
|
||||
'browser.createIn': 'New folder in "{name}"',
|
||||
'browser.untitledFolder': 'Untitled folder',
|
||||
'browser.create': 'Create',
|
||||
'browser.cancel': 'Cancel',
|
||||
'browser.open': 'Open',
|
||||
'browser.editPath': 'Edit path',
|
||||
'browser.loading': 'Loading…',
|
||||
'browser.truncated': 'Too many folders to list; only the beginning is shown.',
|
||||
}],
|
||||
]
|
||||
try {
|
||||
for (const [locale, dict] of dictionaries) disposers.push(ctx.locale.register(LOCALE_NS, locale, dict))
|
||||
} catch (error) {
|
||||
for (const dispose of disposers.reverse()) dispose()
|
||||
throw error
|
||||
}
|
||||
return () => { for (const dispose of disposers) dispose() }
|
||||
}, 'directory-picker-browse: dialog dictionaries')
|
||||
|
||||
const injected = (): BrowseFlowInjected => ({
|
||||
listDirectory: (path, signal) => ctx.workspaces.listDirectory(path, signal),
|
||||
createDirectory: (path, name) => ctx.workspaces.createDirectory(path, name),
|
||||
t: ctx.locale.bind(LOCALE_NS),
|
||||
})
|
||||
ctx.effect(() => {
|
||||
// One occupant, both holes, as a unit: construction or late conflicts
|
||||
// (holes declared after rival providers activated) roll the whole pair
|
||||
// back and fail loud — semantics owned by deferGroupRegistration.
|
||||
const group = deferGroupRegistration(
|
||||
ctx.slots,
|
||||
['conversation.hero.workspace.directoryFlow', 'sidebar.workspaces.directoryFlow'] as const,
|
||||
BrowseDirectoryFlow,
|
||||
name => ctx.slots.register({ name, inject: injected }, BrowseDirectoryFlow),
|
||||
)
|
||||
return () => { group.dispose() }
|
||||
}, 'directory-picker-browse: flow registrations')
|
||||
}
|
||||
6
packages/host/directory-picker-browse/src/css-modules.d.ts
vendored
Normal file
6
packages/host/directory-picker-browse/src/css-modules.d.ts
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
declare module '*.module.css' {
|
||||
const classes: Record<string, string>
|
||||
export default classes
|
||||
}
|
||||
|
||||
declare module '*.css'
|
||||
324
packages/host/directory-picker-browse/src/index.ts
Normal file
324
packages/host/directory-picker-browse/src/index.ts
Normal file
@@ -0,0 +1,324 @@
|
||||
/**
|
||||
* Browse backend of the directory-picker seam: registers `ctx.directoryPicker`
|
||||
* with the `browse` capability — one-level directory listing and child-directory
|
||||
* creation over the host filesystem via Node's stdlib (which already carries
|
||||
* the per-OS adaptation). Nothing renders on the host display, so this backend
|
||||
* serves remote clients the dialog backend cannot. Policy decisions (hidden
|
||||
* entries flagged but returned, symlinks followed, whole-filesystem scope) are
|
||||
* recorded in the directory-picker seam Agent Note.
|
||||
* @module @deepseek-ai/dsh-host-directory-picker-browse
|
||||
*/
|
||||
|
||||
import { mkdir, opendir, 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'
|
||||
import type {
|
||||
DirectoryEntry, DirectoryListing, DirectoryPickerCapability,
|
||||
} from '@deepseek-ai/dsh-host-directory-picker'
|
||||
|
||||
/**
|
||||
* Ancestor chain from the filesystem root to `target` inclusive — the
|
||||
* breadcrumb rows of a listing, every one a jump target.
|
||||
*/
|
||||
function ancestryCrumbs(target: string): DirectoryEntry[] {
|
||||
const crumbs: DirectoryEntry[] = []
|
||||
let current = target
|
||||
for (;;) {
|
||||
const parent = dirname(current)
|
||||
// basename of a root is '' — label the root crumb by its full path ('/', 'C:\').
|
||||
crumbs.unshift({ name: parent === current ? current : basename(current), path: current, hidden: false })
|
||||
if (parent === current) return crumbs
|
||||
current = parent
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the path names one fixed filesystem location regardless of
|
||||
* process state: POSIX-absolute on POSIX; on Windows only drive-qualified
|
||||
* (`C:\…`) or complete UNC (`\\server\share…`) forms. Rooted drive-less
|
||||
* forms (`\foo`, `/foo`) and incomplete UNC prefixes (`\\`, `\\server`)
|
||||
* pass `isAbsolute` yet still resolve against the process's current drive.
|
||||
* @param path - candidate path.
|
||||
* @param platform - replaces `process.platform` for deterministic tests.
|
||||
* @returns whether the path is fully qualified on the platform.
|
||||
*/
|
||||
export function fullyQualified(path: string, platform: NodeJS.Platform = process.platform): boolean {
|
||||
return platform === 'win32'
|
||||
? win32.isAbsolute(path) && /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(path)
|
||||
: posix.isAbsolute(path)
|
||||
}
|
||||
|
||||
/** One streamed listing candidate: the dirent facts a row needs, nothing else retained. */
|
||||
export interface ListingCandidate {
|
||||
/** Base name within the streamed level. */
|
||||
name: string
|
||||
/** Dirent says directory (no probe needed). */
|
||||
isDirectory: boolean
|
||||
/** Dirent says symlink (enterability needs a stat probe). */
|
||||
isSymbolicLink: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a streamed candidate into the name-sorted bounded window, evicting
|
||||
* the name-largest candidate when the window exceeds `keep`. Memory over an
|
||||
* arbitrarily large level therefore stays O(keep) regardless of how many
|
||||
* children the directory holds.
|
||||
* @param window - the name-ascending window, mutated in place.
|
||||
* @param candidate - the streamed candidate to place.
|
||||
* @param keep - the window bound.
|
||||
* @returns true when an eviction happened (the level has candidates beyond the window).
|
||||
*/
|
||||
export function boundedInsert(window: ListingCandidate[], candidate: ListingCandidate, keep: number): boolean {
|
||||
// Full window, name at or beyond the tail: one comparison rejects, so an
|
||||
// oversized level costs O(1) per candidate past the head instead of a
|
||||
// window scan (100k children against a 1,001 window must not approach
|
||||
// 10^8 comparisons).
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- a full window (length === keep >= 1) has a tail
|
||||
if (window.length === keep && candidate.name.localeCompare(window[window.length - 1]!.name) >= 0) return true
|
||||
// Binary insertion keeps a retained candidate at O(log keep) comparisons.
|
||||
let lo = 0
|
||||
let hi = window.length
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >>> 1
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- bounded by the loop condition
|
||||
if (candidate.name.localeCompare(window[mid]!.name) < 0) hi = mid
|
||||
else lo = mid + 1
|
||||
}
|
||||
window.splice(lo, 0, candidate)
|
||||
if (window.length <= keep) return false
|
||||
window.pop()
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Await `operation`, but reject with the signal's reason the moment it
|
||||
* aborts. Node's filesystem reads are not retractable, so the operation
|
||||
* itself keeps running against a handle the caller then closes — its late
|
||||
* settlement is swallowed here so an abandoned read cannot surface as an
|
||||
* unhandled rejection.
|
||||
* @param operation - the in-flight filesystem step.
|
||||
* @param signal - caller lifetime; absent means plain awaiting.
|
||||
* @returns the operation's value.
|
||||
*/
|
||||
export function raceAbort<T>(operation: Promise<T>, signal: AbortSignal | undefined): Promise<T> {
|
||||
if (signal === undefined) return operation
|
||||
return new Promise<T>((resolve, reject) => {
|
||||
const onAbort = (): void => {
|
||||
operation.catch(() => {
|
||||
// Abandoned read: its handle is being closed by the aborting caller,
|
||||
// and the abort reason already carried the outcome.
|
||||
})
|
||||
reject(asError(signal.reason))
|
||||
}
|
||||
if (signal.aborted) {
|
||||
onAbort()
|
||||
return
|
||||
}
|
||||
signal.addEventListener('abort', onAbort, { once: true })
|
||||
operation.then(
|
||||
(value) => {
|
||||
signal.removeEventListener('abort', onAbort)
|
||||
resolve(value)
|
||||
},
|
||||
(reason: unknown) => {
|
||||
signal.removeEventListener('abort', onAbort)
|
||||
reject(asError(reason))
|
||||
},
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
/** The thrown value as an Error (wire/abort reasons may be anything). */
|
||||
function asError(reason: unknown): Error {
|
||||
return reason instanceof Error ? reason : new Error(String(reason))
|
||||
}
|
||||
|
||||
/* v8 ignore start -- a close failure of an abandoned handle has no consumer, and forcing one needs a filesystem torn down mid-request. */
|
||||
/** Swallow the close failure of a handle its caller already departed. */
|
||||
function swallowCloseFailure(): void {}
|
||||
/* v8 ignore stop */
|
||||
|
||||
/** Message text of an unknown thrown value. */
|
||||
function messageOf(error: unknown): string {
|
||||
/* v8 ignore next -- node:fs rejects with Error instances; the String arm only satisfies the unknown narrowing. */
|
||||
return error instanceof Error ? error.message : String(error)
|
||||
}
|
||||
|
||||
/**
|
||||
* One listing row for a dirent, following symlinks to directories; null for
|
||||
* non-directories and broken/cyclic links (skipped silently — the browser
|
||||
* shows what can be entered, and a broken link cannot).
|
||||
*/
|
||||
async function directoryRow(
|
||||
parent: string, name: string, isDirectory: boolean, isSymbolicLink: boolean, signal: AbortSignal | undefined,
|
||||
): Promise<DirectoryEntry | null> {
|
||||
const path = join(parent, name)
|
||||
let enterable = isDirectory
|
||||
if (!enterable && isSymbolicLink) {
|
||||
try {
|
||||
// The probe races the caller too: a symlink target on a stalled
|
||||
// network filesystem must not keep a departed caller's request alive.
|
||||
enterable = (await raceAbort(stat(path), signal)).isDirectory()
|
||||
} catch {
|
||||
/* v8 ignore next 2 -- an abort landing mid-probe needs a stalled stat; the per-candidate check in list covers the settled path. */
|
||||
if (signal?.aborted) throw asError(signal.reason)
|
||||
// Broken or cyclic symlink: stat is the probe, failure means "not enterable".
|
||||
return null
|
||||
}
|
||||
}
|
||||
if (!enterable) return null
|
||||
// POSIX hidden convention; Windows' hidden attribute is not exposed by
|
||||
// dirents (Known Limitations). The client owns whether hidden rows show.
|
||||
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, signal) => this.list(path, signal),
|
||||
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.
|
||||
*/
|
||||
capability(): DirectoryPickerCapability {
|
||||
return this.browseCapability
|
||||
}
|
||||
|
||||
private async list(path?: string, signal?: AbortSignal): Promise<DirectoryListing> {
|
||||
const home = homedir()
|
||||
// The seam contract takes fully qualified paths only; resolve() would
|
||||
// silently rebase a relative or empty wire value under the host process
|
||||
// cwd (or, for rooted drive-less Windows forms, its current drive).
|
||||
if (path !== undefined && !fullyQualified(path)) {
|
||||
throw new DirectoryPickerError('directory-unreadable', path, `cannot list "${path}": not a fully qualified path`)
|
||||
}
|
||||
const target = resolve(path ?? home)
|
||||
// Stream the level (opendir, one dirent at a time) into a name-sorted
|
||||
// window of maxEntries + 1 candidates: memory stays bounded no matter how
|
||||
// many children the directory holds, the window keeps the name-sorted
|
||||
// head, and the +1 slot lets an in-window extra row prove the cut. A
|
||||
// window candidate that turns out non-enterable (broken symlink) is not
|
||||
// backfilled from beyond the window — an eviction already marks the
|
||||
// level truncated, which stays the honest answer.
|
||||
const keep = this.config.maxEntries + 1
|
||||
const window: ListingCandidate[] = []
|
||||
let evicted = false
|
||||
try {
|
||||
// Every filesystem await races the caller's signal: a stalled
|
||||
// opendir/read on a network filesystem must not keep a departed
|
||||
// caller's scan alive, and an already-aborted request rejects even
|
||||
// when the level is empty.
|
||||
const opening = opendir(target)
|
||||
const level = await raceAbort(opening, signal).catch((error: unknown) => {
|
||||
// The abandoned open can still mint a handle after the abort won;
|
||||
// close it so a departed caller cannot leak a descriptor. (A lost
|
||||
// race against opendir's own rejection has nothing to close, and
|
||||
// the close's own failure is swallowed — the request already
|
||||
// returned, so a cleanup error has no consumer.)
|
||||
void opening.then(dir => dir.close().catch(swallowCloseFailure), () => {
|
||||
// Already rejected: raceAbort surfaced or swallowed it.
|
||||
})
|
||||
throw error
|
||||
})
|
||||
try {
|
||||
for (;;) {
|
||||
const dirent = await raceAbort(level.read(), signal)
|
||||
if (dirent === null) break
|
||||
// Only rows a browser could enter contend for the window; dirent
|
||||
// says "directory" outright, a symlink needs the later stat probe.
|
||||
if (!dirent.isDirectory() && !dirent.isSymbolicLink()) continue
|
||||
const candidate = { name: dirent.name, isDirectory: dirent.isDirectory(), isSymbolicLink: dirent.isSymbolicLink() }
|
||||
if (boundedInsert(window, candidate, keep)) evicted = true
|
||||
}
|
||||
} finally {
|
||||
// Manual read() never auto-closes; close on every exit. The aborted
|
||||
// exit must not await it — Node queues close behind any in-flight
|
||||
// read, so awaiting would chain the departed caller back onto the
|
||||
// very stall the abort escaped (the abandoned read's settlement is
|
||||
// already swallowed by raceAbort).
|
||||
const closing = level.close()
|
||||
/* v8 ignore next 3 -- an abort between open and close needs a stalled read; the abandoned-close arm has no observable outcome. */
|
||||
if (signal?.aborted) {
|
||||
closing.catch(swallowCloseFailure)
|
||||
} else {
|
||||
await closing
|
||||
}
|
||||
}
|
||||
} catch (error: unknown) {
|
||||
// An abort is the caller's own reason, not an unreadable directory.
|
||||
signal?.throwIfAborted()
|
||||
throw new DirectoryPickerError('directory-unreadable', target, `cannot list ${target}: ${messageOf(error)}`)
|
||||
}
|
||||
const entries: DirectoryEntry[] = []
|
||||
let truncated = evicted
|
||||
for (const candidate of window) {
|
||||
// A caller that departed between reads and probes stops before the
|
||||
// next probe (each probe's own await is raced inside directoryRow).
|
||||
signal?.throwIfAborted()
|
||||
const row = await directoryRow(target, candidate.name, candidate.isDirectory, candidate.isSymbolicLink, signal)
|
||||
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> {
|
||||
// Same fully-qualified fence as list: never rebase a parent under the
|
||||
// cwd or the current drive.
|
||||
if (!fullyQualified(path)) {
|
||||
throw new DirectoryPickerError('directory-create-failed', path, `cannot create under "${path}": not a fully qualified parent path`)
|
||||
}
|
||||
const parent = resolve(path)
|
||||
// The backend owns segment validation (the wire schema also refuses these,
|
||||
// but direct service consumers must hit the same fence).
|
||||
if (name.trim() === '' || name === '.' || name === '..' || /[/\\]/.test(name)) {
|
||||
throw new DirectoryPickerError('directory-create-failed', join(parent, name), `"${name}" is not a single path segment`)
|
||||
}
|
||||
const target = join(parent, name)
|
||||
try {
|
||||
// Non-recursive: the parent is the directory the browser is showing, so
|
||||
// a missing parent is a real failure, not a level to invent.
|
||||
await mkdir(target)
|
||||
return target
|
||||
} catch (error: unknown) {
|
||||
if (typeof error === 'object' && error !== null && 'code' in error && error.code === 'EEXIST') {
|
||||
throw new DirectoryPickerError('directory-exists', target, `${target} already exists`)
|
||||
}
|
||||
throw new DirectoryPickerError('directory-create-failed', target, `cannot create ${target}: ${messageOf(error)}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
25
packages/host/directory-picker-browse/src/invariant.ts
Normal file
25
packages/host/directory-picker-browse/src/invariant.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Package-owned invariant companion for the browse directory-picker backend.
|
||||
* @module @deepseek-ai/dsh-host-directory-picker-browse/invariant
|
||||
*/
|
||||
|
||||
import type { Context } from 'cordis'
|
||||
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/dsh-host-directory-picker-browse'
|
||||
|
||||
/** Cordis companion plugin name. */
|
||||
export const name = 'host-directory-picker-browse-invariant'
|
||||
/** Service required before the companion can reserve package ownership. */
|
||||
export const inject = ['invariants']
|
||||
|
||||
/** No runtime invariant: each list/create is one stateless filesystem round trip; the filesystem itself is the authoritative state. */
|
||||
const install: InvariantInstaller = () => {}
|
||||
|
||||
/**
|
||||
* Register the browse directory-picker invariant companion.
|
||||
* @param ctx - Cordis context carrying the invariant service.
|
||||
* @returns the installed registration's disposer after setup succeeds.
|
||||
*/
|
||||
export const apply = (ctx: Context): Promise<() => void> =>
|
||||
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
|
||||
214
packages/host/directory-picker-browse/tests/client-flow.spec.tsx
Normal file
214
packages/host/directory-picker-browse/tests/client-flow.spec.tsx
Normal file
@@ -0,0 +1,214 @@
|
||||
// @vitest-environment jsdom
|
||||
import { Context } from 'cordis'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { cleanup, render, screen } from '@testing-library/react'
|
||||
import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { DirectoryListing } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { LocaleService } from '@deepseek-ai/dsh-client-locale/client'
|
||||
import type { DirectoryFlowOwnerProps } from '@deepseek-ai/dsh-client-ui-workspace/client'
|
||||
import { apply, inject } from '../src/client/index.ts'
|
||||
import { BrowseDirectoryFlow } from '../src/client/flow.ts'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const HOLES = ['conversation.hero.workspace.directoryFlow', 'sidebar.workspaces.directoryFlow'] as const
|
||||
|
||||
const HOME = '/home/u'
|
||||
const homeListing: DirectoryListing = {
|
||||
path: HOME,
|
||||
home: HOME,
|
||||
crumbs: [{ name: '/', path: '/', hidden: false }, { name: 'u', path: HOME, hidden: false }],
|
||||
entries: [{ name: 'Documents', path: `${HOME}/Documents`, hidden: false }],
|
||||
truncated: false,
|
||||
}
|
||||
|
||||
async function bench() {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SlotsService).await()
|
||||
ctx.provide('locale', new LocaleService(ctx))
|
||||
const listDirectory = vi.fn(async (): Promise<DirectoryListing> => homeListing)
|
||||
const createDirectory = vi.fn(async (path: string, name: string) => `${path}/${name}`)
|
||||
ctx.provide('workspaces', { listDirectory, createDirectory } as never)
|
||||
const slots = ctx.get('slots') as SlotsService
|
||||
const declare = () => slots.register({
|
||||
name: 'root',
|
||||
children: Object.fromEntries(HOLES.map(name => [name, { kind: 'single', scope: 'root' }])),
|
||||
} as never, () => null)
|
||||
return { ctx, slots, listDirectory, createDirectory, declare }
|
||||
}
|
||||
|
||||
function owner(overrides: Partial<DirectoryFlowOwnerProps> = {}): DirectoryFlowOwnerProps {
|
||||
return {
|
||||
open: true, busy: false,
|
||||
onPicked: vi.fn(), onCancel: vi.fn(), onError: vi.fn(),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('directory-picker-browse client half', () => {
|
||||
it('declares the services it drives', () => {
|
||||
expect(inject).toEqual(['slots', 'workspaces', 'locale'])
|
||||
})
|
||||
|
||||
it('fills both directory-flow holes for declarations before or after apply, and leaves with its fiber', async () => {
|
||||
const before = await bench()
|
||||
before.declare()
|
||||
const fiber = before.ctx.plugin({ inject: [...inject], apply })
|
||||
await fiber.await()
|
||||
for (const hole of HOLES) expect(before.slots.entries(hole)).toHaveLength(1)
|
||||
// Registry-contribution disposal proof: the fiber going down empties the holes.
|
||||
await fiber.dispose()
|
||||
for (const hole of HOLES) expect(before.slots.entries(hole)).toHaveLength(0)
|
||||
|
||||
const after = await bench()
|
||||
await after.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
for (const hole of HOLES) expect(after.slots.entries(hole)).toHaveLength(0)
|
||||
after.declare()
|
||||
await Promise.resolve()
|
||||
for (const hole of HOLES) expect(after.slots.entries(hole)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('rolls back the first deferral when the second hole is already occupied', async () => {
|
||||
const b = await bench()
|
||||
b.declare()
|
||||
// Foreign occupant in the SECOND registered hole: the pair construction
|
||||
// throws after the first deferral installed its subscription.
|
||||
b.slots.register({ name: HOLES[1] } as never, () => null)
|
||||
const rejections: unknown[] = []
|
||||
const onUnhandled = (reason: unknown): void => { rejections.push(reason) }
|
||||
process.on('unhandledRejection', onUnhandled)
|
||||
try {
|
||||
const fiber = b.ctx.plugin({ inject: [...inject], apply })
|
||||
await expect(fiber.await()).rejects.toThrow(/already has a registration/)
|
||||
// A leaked first deferral would now race this probe registration and
|
||||
// throw from its orphaned subscription against the HERO hole; the
|
||||
// rollback leaves only the activation failure itself (cordis re-raises
|
||||
// the apply throw as a late rejection — installFailLoud's contract).
|
||||
const disposeProbe = b.slots.register({ name: HOLES[0] } as never, () => null)
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
expect(rejections.map(String).filter(text => text.includes(HOLES[0]))).toEqual([])
|
||||
disposeProbe()
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled)
|
||||
}
|
||||
})
|
||||
|
||||
it('rolls back wholesale and reports loudly when a rival provider wins after deferred activation', async () => {
|
||||
const b = await bench()
|
||||
const rejections: unknown[] = []
|
||||
const onUnhandled = (reason: unknown): void => { rejections.push(reason) }
|
||||
process.on('unhandledRejection', onUnhandled)
|
||||
process.on('uncaughtException', onUnhandled)
|
||||
try {
|
||||
// This provider activates BEFORE any hole exists: both deferrals wait.
|
||||
await b.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
b.declare()
|
||||
// A rival occupies both holes ahead of the pending microtask flush.
|
||||
b.slots.register({ name: HOLES[0] } as never, () => null)
|
||||
b.slots.register({ name: HOLES[1] } as never, () => null)
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
// The rival keeps both holes; this provider rolled back wholesale and
|
||||
// surfaced the conflict on the fail-loud channel — no partial mix.
|
||||
for (const hole of HOLES) expect(b.slots.entries(hole)).toHaveLength(1)
|
||||
expect(rejections.map(String).join('\n')).toContain('already has a registration')
|
||||
|
||||
// Non-Error conflicts wrap before the loud rethrow (same channel).
|
||||
const c = await bench()
|
||||
await c.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
const original = c.slots.register.bind(c.slots)
|
||||
const slotsAny = c.slots as { register: typeof original }
|
||||
slotsAny.register = ((options: never, component: never) => {
|
||||
if ((options as { name?: string }).name === HOLES[0]) throw 'string conflict'
|
||||
return original(options, component)
|
||||
}) as typeof original
|
||||
c.declare()
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
expect(rejections.map(String).join('\n')).toContain('string conflict')
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled)
|
||||
process.off('uncaughtException', onUnhandled)
|
||||
}
|
||||
})
|
||||
|
||||
it('rolls back the zh dictionary when a rival already owns the namespace en slot', async () => {
|
||||
const b = await bench()
|
||||
b.declare()
|
||||
const locale = b.ctx.get('locale') as LocaleService
|
||||
const disposeRival = locale.register('directory-browser', 'en', { 'browser.title': 'rival' })
|
||||
const rejections: unknown[] = []
|
||||
const onUnhandled = (reason: unknown): void => { rejections.push(reason) }
|
||||
// cordis re-raises the apply throw as a late rejection (installFailLoud's contract).
|
||||
process.on('unhandledRejection', onUnhandled)
|
||||
try {
|
||||
const fiber = b.ctx.plugin({ inject: [...inject], apply })
|
||||
await expect(fiber.await()).rejects.toThrow(/already has locale/)
|
||||
// The zh registration rolled back with the failure: once the rival
|
||||
// leaves, a fresh registrant owns the whole namespace again.
|
||||
disposeRival()
|
||||
const disposeZh = locale.register('directory-browser', 'zh', { 'browser.title': '空闲' })
|
||||
disposeZh()
|
||||
} finally {
|
||||
await new Promise(resolve => setTimeout(resolve, 0))
|
||||
process.off('unhandledRejection', onUnhandled)
|
||||
}
|
||||
})
|
||||
|
||||
it('registers the dialog dictionaries and binds this package namespace', async () => {
|
||||
const b = await bench()
|
||||
b.declare()
|
||||
await b.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
const entry = b.slots.entries(HOLES[0])[0]!
|
||||
const injected = (entry.inject as () => { t: (key: string) => string })()
|
||||
// zh is the shipped default locale.
|
||||
expect(injected.t('browser.title')).toBe('选择工作区目录')
|
||||
expect(injected.t('browser.newFolder')).toBe('新建文件夹')
|
||||
})
|
||||
|
||||
it('drives the injected browse calls through the hole entry', async () => {
|
||||
const b = await bench()
|
||||
b.declare()
|
||||
await b.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
const entry = b.slots.entries(HOLES[1])[0]!
|
||||
const injected = (entry.inject as () => {
|
||||
listDirectory: (path?: string) => Promise<DirectoryListing>
|
||||
createDirectory: (path: string, name: string) => Promise<string>
|
||||
})()
|
||||
await expect(injected.listDirectory()).resolves.toBe(homeListing)
|
||||
await expect(injected.createDirectory(HOME, 'fresh')).resolves.toBe(`${HOME}/fresh`)
|
||||
expect(b.listDirectory).toHaveBeenCalledOnce()
|
||||
expect(b.createDirectory).toHaveBeenCalledWith(HOME, 'fresh')
|
||||
})
|
||||
|
||||
it('adapts the owner conversation onto the dialog: confirm picks, dismissal cancels', async () => {
|
||||
const props = owner()
|
||||
const listDirectory = vi.fn(async (): Promise<DirectoryListing> => homeListing)
|
||||
const t = (key: string): string => key
|
||||
render(
|
||||
<BrowseDirectoryFlow
|
||||
{...props}
|
||||
listDirectory={listDirectory}
|
||||
createDirectory={vi.fn(async () => '')}
|
||||
t={t}
|
||||
/>,
|
||||
)
|
||||
// The dialog opened at home; its confirm (browser.open) adopts the listed level.
|
||||
const openButton = await screen.findByRole('button', { name: 'browser.open' })
|
||||
openButton.click()
|
||||
expect(props.onPicked).toHaveBeenCalledWith(HOME)
|
||||
screen.getByRole('button', { name: 'browser.cancel' }).click()
|
||||
expect(props.onCancel).toHaveBeenCalled()
|
||||
expect(props.onError).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('renders nothing while the flow is closed', () => {
|
||||
const view = render(
|
||||
<BrowseDirectoryFlow
|
||||
{...owner({ open: false })}
|
||||
listDirectory={vi.fn(async () => homeListing)}
|
||||
createDirectory={vi.fn(async () => '')}
|
||||
t={key => key}
|
||||
/>,
|
||||
)
|
||||
expect(view.container.innerHTML).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,792 @@
|
||||
// @vitest-environment jsdom
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import type { DirectoryListing } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { DirectoryBrowseError } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import { DirectoryBrowser } from '../src/client/DirectoryBrowser.tsx'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const HOME = '/home/u'
|
||||
const DOCS = `${HOME}/Documents`
|
||||
const HARNESS = `${DOCS}/harness`
|
||||
|
||||
/** Listing fake over a tiny fixed tree; unknown paths reject like the Host. */
|
||||
function listingFor(path?: string): DirectoryListing {
|
||||
const target = path ?? HOME
|
||||
const tree: Record<string, DirectoryListing> = {
|
||||
[HOME]: {
|
||||
path: HOME,
|
||||
home: HOME,
|
||||
crumbs: [
|
||||
{ name: '/', path: '/', hidden: false },
|
||||
{ name: 'home', path: '/home', hidden: false },
|
||||
{ name: 'u', path: HOME, hidden: false },
|
||||
],
|
||||
entries: [
|
||||
{ name: '.config', path: `${HOME}/.config`, hidden: true },
|
||||
{ name: 'Documents', path: DOCS, hidden: false },
|
||||
],
|
||||
truncated: false,
|
||||
},
|
||||
[DOCS]: {
|
||||
path: DOCS,
|
||||
home: HOME,
|
||||
crumbs: [
|
||||
{ name: '/', path: '/', hidden: false },
|
||||
{ name: 'home', path: '/home', hidden: false },
|
||||
{ name: 'u', path: HOME, hidden: false },
|
||||
{ name: 'Documents', path: DOCS, hidden: false },
|
||||
],
|
||||
entries: [{ name: 'harness', path: HARNESS, hidden: false }],
|
||||
truncated: false,
|
||||
},
|
||||
[HARNESS]: {
|
||||
path: HARNESS,
|
||||
home: HOME,
|
||||
crumbs: [
|
||||
{ name: '/', path: '/', hidden: false },
|
||||
{ name: 'home', path: '/home', hidden: false },
|
||||
{ name: 'u', path: HOME, hidden: false },
|
||||
{ name: 'Documents', path: DOCS, hidden: false },
|
||||
{ name: 'harness', path: HARNESS, hidden: false },
|
||||
],
|
||||
entries: [],
|
||||
truncated: false,
|
||||
},
|
||||
}
|
||||
const found = tree[target]
|
||||
if (found === undefined) {
|
||||
throw new DirectoryBrowseError({ code: 'directory-unreadable', message: `cannot list ${target}`, details: { path: target } })
|
||||
}
|
||||
return found
|
||||
}
|
||||
|
||||
function mount(overrides: Partial<Parameters<typeof DirectoryBrowser>[0]> = {}) {
|
||||
const listDirectory = vi.fn(async (path?: string) => listingFor(path))
|
||||
const createDirectory = vi.fn(async (path: string, name: string) => `${path}/${name}`)
|
||||
const onOpen = vi.fn()
|
||||
const onClose = vi.fn()
|
||||
const props = {
|
||||
open: true,
|
||||
listDirectory,
|
||||
createDirectory,
|
||||
onOpen,
|
||||
onClose,
|
||||
busy: false,
|
||||
t: (key: string, params?: Record<string, unknown>) => (params === undefined ? key : `${key}:${String(params.name)}`),
|
||||
...overrides,
|
||||
}
|
||||
const view = render(<DirectoryBrowser {...props} />)
|
||||
return { view, props, listDirectory, createDirectory, onOpen, onClose }
|
||||
}
|
||||
|
||||
/** The rendered level columns, left-to-right. */
|
||||
function columns(): HTMLElement[] {
|
||||
return screen.getAllByRole('list')
|
||||
}
|
||||
|
||||
/** The actionable button inside a listitem seat (rows keep native button semantics). */
|
||||
function rowButton(item: HTMLElement): HTMLButtonElement {
|
||||
return within(item).getByRole<HTMLButtonElement>('button')
|
||||
}
|
||||
|
||||
describe('DirectoryBrowser', () => {
|
||||
it('opens at the Host home as one wide column, hides hidden entries, and roots the crumbs at Home', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
expect(b.listDirectory).toHaveBeenCalledWith(undefined, expect.any(AbortSignal))
|
||||
expect(columns()).toHaveLength(1)
|
||||
expect(screen.getByRole('listitem').textContent).toBe('Documents')
|
||||
expect(screen.queryByText('.config')).toBeNull()
|
||||
expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy()
|
||||
expect(screen.queryByRole('button', { name: '/' })).toBeNull()
|
||||
})
|
||||
|
||||
it('selects a row into the two-pane view: children preview right, crumbs follow the selection', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
await waitFor(() => { expect(columns()).toHaveLength(2) })
|
||||
const [level, preview] = columns()
|
||||
const selectedRow = within(level!).getByRole('listitem')
|
||||
expect(selectedRow.textContent).toBe('Documents')
|
||||
expect(rowButton(selectedRow).getAttribute('aria-current')).toBe('true')
|
||||
expect(within(preview!).getByRole('listitem').textContent).toBe('harness')
|
||||
expect(b.listDirectory).toHaveBeenLastCalledWith(DOCS, expect.any(AbortSignal))
|
||||
expect(within(screen.getByRole('navigation')).getByRole('button', { name: 'Documents' })).toBeTruthy()
|
||||
})
|
||||
|
||||
it('advances one level when a right-column row is picked', async () => {
|
||||
mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
await waitFor(() => { expect(columns()).toHaveLength(2) })
|
||||
fireEvent.click(rowButton(within(columns()[1]!).getByRole('listitem')))
|
||||
await waitFor(() => { expect(screen.getByRole('button', { name: 'harness' })).toBeTruthy() })
|
||||
const [level] = columns()
|
||||
const selectedRow = within(level!).getByRole('listitem')
|
||||
expect(selectedRow.textContent).toBe('harness')
|
||||
expect(rowButton(selectedRow).getAttribute('aria-current')).toBe('true')
|
||||
})
|
||||
|
||||
it('aborts a superseded listing on the wire, and the in-flight one on close', async () => {
|
||||
const signals: (AbortSignal | undefined)[] = []
|
||||
const gates: (() => void)[] = []
|
||||
const listDirectory = vi.fn((path?: string, signal?: AbortSignal) => {
|
||||
signals.push(signal)
|
||||
if (signals.length === 1) return Promise.resolve(listingFor(path))
|
||||
// Later listings hang until released: supersession must abort them
|
||||
// on the wire, not merely discard their eventual results.
|
||||
return new Promise<DirectoryListing>((resolve) => { gates.push(() => { resolve(listingFor(path)) }) })
|
||||
})
|
||||
const b = mount({ listDirectory })
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
expect(signals).toHaveLength(2)
|
||||
// A crumb jump supersedes the hanging preview: its request aborts.
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.home' }))
|
||||
expect(signals[1]?.aborted).toBe(true)
|
||||
expect(signals[2]?.aborted).toBe(false)
|
||||
// Closing the dialog aborts the still-pending navigation too.
|
||||
b.view.rerender(<DirectoryBrowser {...b.props} listDirectory={listDirectory} open={false} />)
|
||||
expect(signals[2]?.aborted).toBe(true)
|
||||
})
|
||||
|
||||
it('jumps back through a crumb into a fresh single-column level', async () => {
|
||||
mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
await waitFor(() => { expect(columns()).toHaveLength(2) })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.home' }))
|
||||
await waitFor(() => { expect(columns()).toHaveLength(1) })
|
||||
expect(screen.getByRole('listitem').textContent).toBe('Documents')
|
||||
expect(rowButton(screen.getByRole('listitem')).getAttribute('aria-current')).toBeNull()
|
||||
})
|
||||
|
||||
it('opens the selection, else the listed level; Cancel closes; busy freezes Open', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.open' }))
|
||||
expect(b.onOpen).toHaveBeenCalledWith(HOME)
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
await waitFor(() => { expect(columns()).toHaveLength(2) })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.open' }))
|
||||
expect(b.onOpen).toHaveBeenLastCalledWith(DOCS)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.cancel' }))
|
||||
expect(b.onClose).toHaveBeenCalled()
|
||||
|
||||
const busy = mount({ busy: true })
|
||||
await waitFor(() => { expect(busy.listDirectory).toHaveBeenCalled() })
|
||||
expect(screen.getAllByRole<HTMLButtonElement>('button', { name: 'browser.open' }).at(-1)!.disabled).toBe(true)
|
||||
})
|
||||
|
||||
it('edits the path from the crumb bar: Enter navigates, Escape restores, blank is ignored', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' }))
|
||||
const input = screen.getByLabelText<HTMLInputElement>('browser.editPath')
|
||||
expect(input.value).toBe(HOME)
|
||||
fireEvent.change(input, { target: { value: DOCS } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') })
|
||||
expect(columns()).toHaveLength(1)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' }))
|
||||
const again = screen.getByLabelText<HTMLInputElement>('browser.editPath')
|
||||
fireEvent.change(again, { target: { value: ' ' } })
|
||||
fireEvent.keyDown(again, { key: 'Enter' })
|
||||
expect(b.listDirectory).toHaveBeenCalledTimes(2)
|
||||
fireEvent.keyDown(again, { key: 'Escape' })
|
||||
expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull()
|
||||
})
|
||||
|
||||
it('restarts the home listing when Escape cancels an edit opened before any level listed', async () => {
|
||||
// The initial home listing hangs; Edit Path supersedes it while parent
|
||||
// is still null, and Escape must not strand a blank picker.
|
||||
let settled = false
|
||||
const gate = new Promise<never>(() => {})
|
||||
const listDirectory = vi.fn(async (path?: string) => {
|
||||
if (!settled) { settled = true; return gate }
|
||||
return listingFor(path)
|
||||
})
|
||||
mount({ listDirectory })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' }))
|
||||
const input = screen.getByLabelText<HTMLInputElement>('browser.editPath')
|
||||
expect(input.value).toBe('')
|
||||
fireEvent.keyDown(input, { key: 'Escape' })
|
||||
// Cancellation relaunched the home listing instead of leaving neither
|
||||
// rows nor status behind.
|
||||
await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('Documents') })
|
||||
expect(listDirectory).toHaveBeenCalledTimes(2)
|
||||
expect(listDirectory).toHaveBeenLastCalledWith(undefined, expect.any(AbortSignal))
|
||||
})
|
||||
|
||||
it('passes the entered path to the Host untrimmed (trim only gates blank drafts)', async () => {
|
||||
const listDirectory = vi.fn(async (path?: string) => listingFor(path))
|
||||
mount({ listDirectory })
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' }))
|
||||
const input = screen.getByLabelText<HTMLInputElement>('browser.editPath')
|
||||
fireEvent.change(input, { target: { value: `${DOCS} ` } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
// A trailing space may name a real directory; trimming would list its sibling.
|
||||
await waitFor(() => { expect(listDirectory).toHaveBeenLastCalledWith(`${DOCS} `, expect.any(AbortSignal)) })
|
||||
})
|
||||
|
||||
it('surfaces an unreadable target as an alert and keeps the edit open for correction', async () => {
|
||||
mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' }))
|
||||
const input = screen.getByLabelText('browser.editPath')
|
||||
fireEvent.change(input, { target: { value: '/nope' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('cannot list /nope') })
|
||||
expect(screen.getByLabelText('browser.editPath')).toBeTruthy()
|
||||
expect(screen.getByRole('listitem').textContent).toBe('Documents')
|
||||
})
|
||||
|
||||
it('folds non-typed failures into readable text (Error message, String otherwise)', async () => {
|
||||
const b = mount({ listDirectory: vi.fn(async () => { throw new Error('socket down') }) })
|
||||
await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('socket down') })
|
||||
b.view.rerender(<DirectoryBrowser {...b.props} open={false} />)
|
||||
const raw = mount({ listDirectory: vi.fn(async () => { throw 'raw failure' }) })
|
||||
await waitFor(() => { expect(screen.getAllByRole('alert').at(-1)!.textContent).toBe('raw failure') })
|
||||
expect(raw.onOpen).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('renders the full ancestry when the level sits outside the home subtree', async () => {
|
||||
const outside: DirectoryListing = {
|
||||
path: '/srv/data',
|
||||
home: HOME,
|
||||
crumbs: [
|
||||
{ name: '/', path: '/', hidden: false },
|
||||
{ name: 'srv', path: '/srv', hidden: false },
|
||||
{ name: 'data', path: '/srv/data', hidden: false },
|
||||
],
|
||||
entries: [],
|
||||
truncated: false,
|
||||
}
|
||||
mount({ listDirectory: vi.fn(async () => outside) })
|
||||
await waitFor(() => { expect(screen.getByRole('button', { name: 'data' })).toBeTruthy() })
|
||||
expect(screen.getByRole('button', { name: '/' })).toBeTruthy()
|
||||
expect(screen.queryByRole('button', { name: 'browser.home' })).toBeNull()
|
||||
})
|
||||
|
||||
it('scopes Escape to the topmost dialog: the nested create closes first, the browser only after', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
expect(screen.getByLabelText('browser.folderName')).toBeTruthy()
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
// The nested dialog consumed Escape; the browser stays up.
|
||||
expect(screen.queryByLabelText('browser.folderName')).toBeNull()
|
||||
expect(b.onClose).not.toHaveBeenCalled()
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
expect(b.onClose).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('keeps both dialogs open when Escape lands during an in-flight creation', async () => {
|
||||
let resolve!: (path: string) => void
|
||||
const createDirectory = vi.fn(() => new Promise<string>((settle) => { resolve = settle }))
|
||||
const b = mount({ createDirectory })
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
fireEvent.change(screen.getByLabelText('browser.folderName'), { target: { value: 'pending' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.create' }))
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
// The in-flight fence holds the nested dialog, and the browser must not
|
||||
// fall out from under it either.
|
||||
expect(screen.getByLabelText('browser.folderName')).toBeTruthy()
|
||||
expect(b.onClose).not.toHaveBeenCalled()
|
||||
await act(async () => { resolve(`${HOME}/pending`) })
|
||||
})
|
||||
|
||||
it('keeps New folder disabled while the post-create relist is still loading', async () => {
|
||||
const pending: (() => void)[] = []
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
// Every listing after the create hangs until drained: the button must not
|
||||
// offer a second create against a target the pending relist/select
|
||||
// sequence is about to change.
|
||||
const fresh: DirectoryListing = {
|
||||
path: `${HOME}/fresh`, home: HOME,
|
||||
crumbs: [...listingFor(HOME).crumbs, { name: 'fresh', path: `${HOME}/fresh`, hidden: false }],
|
||||
entries: [],
|
||||
truncated: false,
|
||||
}
|
||||
b.listDirectory.mockImplementation((path?: string) =>
|
||||
new Promise<DirectoryListing>((settle) => {
|
||||
pending.push(() => { settle(path === `${HOME}/fresh` ? fresh : listingFor(path)) })
|
||||
}))
|
||||
fireEvent.change(screen.getByLabelText('browser.folderName'), { target: { value: 'fresh' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.create' }))
|
||||
await waitFor(() => { expect(screen.queryByLabelText('browser.folderName')).toBeNull() })
|
||||
expect(screen.getByRole<HTMLButtonElement>('button', { name: 'browser.newFolder' }).disabled).toBe(true)
|
||||
// Drain the relist and the follow-up selection listing; only then does
|
||||
// the affordance return.
|
||||
await act(async () => { for (const settle of pending.splice(0)) settle() })
|
||||
await act(async () => { for (const settle of pending.splice(0)) settle() })
|
||||
expect(screen.getByRole<HTMLButtonElement>('button', { name: 'browser.newFolder' }).disabled).toBe(false)
|
||||
})
|
||||
|
||||
it('keeps path entry available when the home listing fails', async () => {
|
||||
const listDirectory = vi.fn(async (): Promise<DirectoryListing> => {
|
||||
throw new DirectoryBrowseError({ code: 'directory-unreadable', message: 'home unreadable', details: { path: HOME } })
|
||||
})
|
||||
mount({ listDirectory })
|
||||
await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('home unreadable') })
|
||||
// With no listed level, typing an absolute path is the one way forward.
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' }))
|
||||
const input = screen.getByLabelText('browser.editPath')
|
||||
fireEvent.change(input, { target: { value: DOCS } })
|
||||
listDirectory.mockImplementation(async (path?: string) => listingFor(path))
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
await waitFor(() => { expect(screen.getByText('harness')).toBeTruthy() })
|
||||
})
|
||||
|
||||
it('disables Open and New folder while a path draft is uncommitted', async () => {
|
||||
mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' }))
|
||||
// targetPath still names the previous listing; committing actions must
|
||||
// not act on it while a different path is displayed in the header.
|
||||
expect(screen.getByRole<HTMLButtonElement>('button', { name: 'browser.open' }).disabled).toBe(true)
|
||||
expect(screen.getByRole<HTMLButtonElement>('button', { name: 'browser.newFolder' }).disabled).toBe(true)
|
||||
fireEvent.keyDown(screen.getByLabelText('browser.editPath'), { key: 'Escape' })
|
||||
expect(screen.getByRole<HTMLButtonElement>('button', { name: 'browser.open' }).disabled).toBe(false)
|
||||
})
|
||||
|
||||
it('ignores Enter while an IME composition is active in either input', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
// Path editor: a composing Enter confirms the candidate, not the path.
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' }))
|
||||
const pathInput = screen.getByLabelText('browser.editPath')
|
||||
fireEvent.change(pathInput, { target: { value: DOCS } })
|
||||
const listCalls = b.listDirectory.mock.calls.length
|
||||
fireEvent.compositionStart(pathInput)
|
||||
fireEvent.keyDown(pathInput, { key: 'Enter' })
|
||||
expect(b.listDirectory.mock.calls.length).toBe(listCalls)
|
||||
fireEvent.compositionEnd(pathInput)
|
||||
fireEvent.keyDown(pathInput, { key: 'Enter' })
|
||||
await waitFor(() => { expect(b.listDirectory).toHaveBeenLastCalledWith(DOCS, expect.any(AbortSignal)) })
|
||||
// Create dialog: same guard.
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
const nameInput = screen.getByLabelText('browser.folderName')
|
||||
fireEvent.change(nameInput, { target: { value: '新建' } })
|
||||
fireEvent.compositionStart(nameInput)
|
||||
fireEvent.keyDown(nameInput, { key: 'Enter' })
|
||||
expect(b.createDirectory).not.toHaveBeenCalled()
|
||||
fireEvent.compositionEnd(nameInput)
|
||||
fireEvent.keyDown(nameInput, { key: 'Enter' })
|
||||
await waitFor(() => { expect(b.createDirectory).toHaveBeenCalledWith(DOCS, '新建') })
|
||||
})
|
||||
|
||||
it('surfaces a two-pane navigation failure as an alert below the columns', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
await waitFor(() => { expect(columns()).toHaveLength(2) })
|
||||
b.listDirectory.mockImplementation(async () => {
|
||||
throw new DirectoryBrowseError({ code: 'directory-unreadable', message: 'denied', details: { path: HOME } })
|
||||
})
|
||||
fireEvent.click(within(screen.getByRole('navigation')).getByRole('button', { name: 'browser.home' }))
|
||||
await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('denied') })
|
||||
// Both panes survive the failure; the alert renders in the flow, not as a
|
||||
// third column competing for the fixed widths.
|
||||
expect(columns()).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('keeps the editor open when a pending listing settles right after Edit Path was clicked', async () => {
|
||||
const pending: ((listing: DirectoryListing) => void)[] = []
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
// A crumb navigation hangs; the user opens the editor before it settles.
|
||||
b.listDirectory.mockImplementation(() =>
|
||||
new Promise<DirectoryListing>((settle) => { pending.push(settle) }))
|
||||
fireEvent.click(within(screen.getByRole('navigation')).getByRole('button', { name: 'browser.home' }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' }))
|
||||
expect(screen.getByLabelText('browser.editPath')).toBeTruthy()
|
||||
await act(async () => { pending.shift()!(listingFor(HOME)) })
|
||||
// The superseded settlement must not close the editor underneath the user.
|
||||
expect(screen.getByLabelText('browser.editPath')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('ignores a pending navigation that settles after Escape cancelled the editor', async () => {
|
||||
const pending: ((listing: DirectoryListing) => void)[] = []
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' }))
|
||||
const input = screen.getByLabelText('browser.editPath')
|
||||
b.listDirectory.mockImplementation(() =>
|
||||
new Promise<DirectoryListing>((settle) => { pending.push(settle) }))
|
||||
fireEvent.change(input, { target: { value: DOCS } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
fireEvent.keyDown(input, { key: 'Escape' })
|
||||
// The cancelled navigation settling late must not jump the view to DOCS.
|
||||
await act(async () => { pending.shift()!(listingFor(DOCS)) })
|
||||
expect(screen.queryByText('harness')).toBeNull()
|
||||
expect(screen.getByText('Documents')).toBeTruthy()
|
||||
expect(screen.queryByRole('status')).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps a newer path edit when an older slow navigation settles', async () => {
|
||||
const pending: ((listing: DirectoryListing) => void)[] = []
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' }))
|
||||
const input = screen.getByLabelText('browser.editPath')
|
||||
b.listDirectory.mockImplementation(() =>
|
||||
new Promise<DirectoryListing>((settle) => { pending.push(settle) }))
|
||||
fireEvent.change(input, { target: { value: DOCS } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
// The user keeps typing while the lookup hangs; the older completion must
|
||||
// neither clear this newer draft nor swap the view to the older path.
|
||||
fireEvent.change(input, { target: { value: `${DOCS}/har` } })
|
||||
await act(async () => { pending.shift()!(listingFor(DOCS)) })
|
||||
expect(screen.getByLabelText<HTMLInputElement>('browser.editPath').value).toBe(`${DOCS}/har`)
|
||||
expect(screen.queryByText('harness')).toBeNull()
|
||||
})
|
||||
|
||||
it('keeps an intact selection preview when a path edit is cancelled', async () => {
|
||||
mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
await waitFor(() => { expect(columns()).toHaveLength(2) })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' }))
|
||||
fireEvent.keyDown(screen.getByLabelText('browser.editPath'), { key: 'Escape' })
|
||||
// Nothing was superseded: the two-pane view survives the cancel.
|
||||
expect(columns()).toHaveLength(2)
|
||||
})
|
||||
|
||||
it('falls back to the single-pane level when a path edit superseded the preview and was cancelled', async () => {
|
||||
const pending: ((listing: DirectoryListing) => void)[] = []
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
// Selection starts a preview that never lands (superseded below).
|
||||
b.listDirectory.mockImplementation(() =>
|
||||
new Promise<DirectoryListing>((settle) => { pending.push(settle) }))
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' }))
|
||||
const input = screen.getByLabelText('browser.editPath')
|
||||
fireEvent.change(input, { target: { value: `${DOCS}/x` } })
|
||||
fireEvent.keyDown(input, { key: 'Escape' })
|
||||
// No half-empty two-pane residue: back to the single wide level.
|
||||
expect(columns()).toHaveLength(1)
|
||||
expect(screen.getByRole('button', { name: 'browser.editPath' })).toBeTruthy()
|
||||
})
|
||||
|
||||
it('drops a creation that settles after the browser unmounted', async () => {
|
||||
let settleCreate!: (path: string) => void
|
||||
const createDirectory = vi.fn(() => new Promise<string>((settle) => { settleCreate = settle }))
|
||||
const b = mount({ createDirectory })
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
fireEvent.change(screen.getByLabelText('browser.folderName'), { target: { value: 'slow' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.create' }))
|
||||
const listCalls = b.listDirectory.mock.calls.length
|
||||
b.view.unmount()
|
||||
// The dead flow must not issue the post-create relist.
|
||||
await act(async () => { settleCreate(`${HOME}/slow`) })
|
||||
expect(b.listDirectory.mock.calls.length).toBe(listCalls)
|
||||
})
|
||||
|
||||
it('clears the selection when its preview listing fails', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
b.listDirectory.mockImplementation(async () => {
|
||||
throw new DirectoryBrowseError({ code: 'directory-unreadable', message: 'denied', details: { path: DOCS } })
|
||||
})
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('denied') })
|
||||
// The breadcrumb names the level, so the level must be the committing
|
||||
// target: no half-selected two-pane state survives the failure.
|
||||
expect(columns()).toHaveLength(1)
|
||||
expect(rowButton(screen.getByRole('listitem')).getAttribute('aria-current')).toBeNull()
|
||||
})
|
||||
|
||||
it('ignores dismissal while adoption is busy', async () => {
|
||||
const b = mount({ busy: true })
|
||||
await waitFor(() => { expect(screen.getByRole('dialog')).toBeTruthy() })
|
||||
fireEvent.keyDown(document, { key: 'Escape' })
|
||||
expect(b.onClose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('makes every parent control inert while the nested create dialog is open', async () => {
|
||||
mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
// Modal traps no focus: Shift-Tab/AT reach the parent, so closing,
|
||||
// adopting, and retargeting must all disable underneath the child. Both
|
||||
// dialogs carry a cancel: the parent's disables, the child's stays live.
|
||||
const cancels = screen.getAllByRole<HTMLButtonElement>('button', { name: 'browser.cancel' })
|
||||
expect(cancels.map(button => button.disabled).sort()).toEqual([false, true])
|
||||
expect(screen.getByRole<HTMLButtonElement>('button', { name: 'browser.open' }).disabled).toBe(true)
|
||||
expect(screen.getByRole<HTMLButtonElement>('button', { name: 'browser.editPath' }).disabled).toBe(true)
|
||||
for (const row of screen.getAllByRole('listitem')) {
|
||||
expect(rowButton(row).disabled).toBe(true)
|
||||
}
|
||||
})
|
||||
|
||||
it('drops a creation failure that lands after the flow closed and reopened', async () => {
|
||||
let rejectCreate!: (reason: unknown) => void
|
||||
const createDirectory = vi.fn(() => new Promise<string>((_settle, reject) => { rejectCreate = reject }))
|
||||
const b = mount({ createDirectory })
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
fireEvent.change(screen.getByLabelText('browser.folderName'), { target: { value: 'slow' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.create' }))
|
||||
b.view.rerender(<DirectoryBrowser {...b.props} open={false} />)
|
||||
b.view.rerender(<DirectoryBrowser {...b.props} open />)
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
// The stale failure must not surface an alert inside the fresh flow.
|
||||
await act(async () => { rejectCreate(new Error('too late')) })
|
||||
expect(screen.queryByText('too late')).toBeNull()
|
||||
})
|
||||
|
||||
it('drops a creation that settles after the flow closed and reopened', async () => {
|
||||
let settleCreate!: (path: string) => void
|
||||
const createDirectory = vi.fn(() => new Promise<string>((settle) => { settleCreate = settle }))
|
||||
const b = mount({ createDirectory })
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
fireEvent.change(screen.getByLabelText('browser.folderName'), { target: { value: 'slow' } })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.create' }))
|
||||
b.view.rerender(<DirectoryBrowser {...b.props} open={false} />)
|
||||
b.view.rerender(<DirectoryBrowser {...b.props} open />)
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
const listCallsBefore = b.listDirectory.mock.calls.length
|
||||
// The stale settlement must not relist the old target or reopen the
|
||||
// nested dialog's state inside the fresh flow.
|
||||
await act(async () => { settleCreate(`${HOME}/slow`) })
|
||||
expect(b.listDirectory.mock.calls.length).toBe(listCallsBefore)
|
||||
expect(screen.queryByLabelText('browser.folderName')).toBeNull()
|
||||
expect(screen.getByText('Documents')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('passes the folder name to the Host untrimmed (trim only gates blank drafts)', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
const input = screen.getByLabelText('browser.folderName')
|
||||
fireEvent.change(input, { target: { value: 'project ' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
// A trailing space may be the wanted spelling; trimming would create a sibling.
|
||||
await waitFor(() => { expect(b.createDirectory).toHaveBeenCalledWith(HOME, 'project ') })
|
||||
})
|
||||
|
||||
it('creates a folder through the nested dialog and lands with it selected', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
await waitFor(() => { expect(columns()).toHaveLength(2) })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
// The nested dialog names the create target (the selected folder).
|
||||
expect(screen.getByText('browser.createIn:Documents')).toBeTruthy()
|
||||
// The created folder becomes listable (like the real backend after mkdir).
|
||||
b.listDirectory.mockImplementation(async (path?: string) => {
|
||||
if (path === `${DOCS}/fresh`) {
|
||||
return {
|
||||
path: `${DOCS}/fresh`, home: HOME,
|
||||
crumbs: [...listingFor(DOCS).crumbs, { name: 'fresh', path: `${DOCS}/fresh`, hidden: false }],
|
||||
entries: [],
|
||||
truncated: false,
|
||||
}
|
||||
}
|
||||
if (path === DOCS) {
|
||||
const docs = listingFor(DOCS)
|
||||
return { ...docs, entries: [...docs.entries, { name: 'fresh', path: `${DOCS}/fresh`, hidden: false }] }
|
||||
}
|
||||
return listingFor(path)
|
||||
})
|
||||
const input = screen.getByLabelText('browser.folderName')
|
||||
fireEvent.change(input, { target: { value: 'fresh' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
await waitFor(() => { expect(b.createDirectory).toHaveBeenCalledWith(DOCS, 'fresh') })
|
||||
// The create target became the level and the new folder its selection.
|
||||
await waitFor(() => {
|
||||
expect(within(screen.getByRole('navigation')).getByRole('button', { name: 'Documents' })).toBeTruthy()
|
||||
const level = columns()[0]!
|
||||
const rows = within(level).getAllByRole('listitem')
|
||||
expect(rows.some(row => row.textContent === 'fresh' && rowButton(row).getAttribute('aria-current') === 'true')).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the nested dialog open on a creation failure and cancels cleanly', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
b.createDirectory.mockRejectedValueOnce(
|
||||
new DirectoryBrowseError({ code: 'directory-exists', message: 'taken already', details: { path: `${HOME}/x` } }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
expect(screen.getByText('browser.createIn:browser.home')).toBeTruthy()
|
||||
const input = screen.getByLabelText('browser.folderName')
|
||||
// A blank name never submits.
|
||||
fireEvent.change(input, { target: { value: ' ' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
expect(b.createDirectory).not.toHaveBeenCalled()
|
||||
fireEvent.change(input, { target: { value: 'x' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('taken already') })
|
||||
fireEvent.keyDown(screen.getByLabelText('browser.folderName'), { key: 'Escape' })
|
||||
await waitFor(() => { expect(screen.queryByLabelText('browser.folderName')).toBeNull() })
|
||||
|
||||
// The nested Cancel button and the nested mask both close only the child dialog.
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
const nested = screen.getByRole('dialog', { name: 'browser.newFolder' })
|
||||
fireEvent.click(within(nested).getByRole('button', { name: 'browser.cancel' }))
|
||||
await waitFor(() => { expect(screen.queryByLabelText('browser.folderName')).toBeNull() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
const masks = document.querySelectorAll('[aria-hidden="true"]')
|
||||
fireEvent.click(masks[masks.length - 1]!)
|
||||
await waitFor(() => { expect(screen.queryByLabelText('browser.folderName')).toBeNull() })
|
||||
expect(screen.getByRole('dialog', { name: 'browser.title' })).toBeTruthy()
|
||||
})
|
||||
|
||||
it('surfaces a post-create relist failure on the browser surface', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
// Creation succeeds, but relisting the target fails afterwards.
|
||||
b.listDirectory.mockRejectedValueOnce(new Error('level vanished'))
|
||||
const input = screen.getByLabelText('browser.folderName')
|
||||
fireEvent.change(input, { target: { value: 'fresh' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('level vanished') })
|
||||
})
|
||||
|
||||
it('drops a stale child listing that resolves after a crumb jump', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
let resolveSlow!: (value: DirectoryListing) => void
|
||||
const slow = new Promise<DirectoryListing>((settle) => { resolveSlow = settle })
|
||||
b.listDirectory.mockReturnValueOnce(slow)
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.home' }))
|
||||
await waitFor(() => { expect(b.listDirectory).toHaveBeenCalledTimes(3) })
|
||||
await waitFor(() => { expect(columns()).toHaveLength(1) })
|
||||
resolveSlow(listingFor(DOCS))
|
||||
await new Promise(settle => setTimeout(settle, 0))
|
||||
// The superseded selection preview did not reopen the second pane.
|
||||
expect(columns()).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('drops a stale failure that rejects after a newer navigation', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
let rejectSlow!: (reason: unknown) => void
|
||||
const slow = new Promise<DirectoryListing>((_settle, fail) => { rejectSlow = fail })
|
||||
b.listDirectory.mockReturnValueOnce(slow)
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.home' }))
|
||||
await waitFor(() => { expect(b.listDirectory).toHaveBeenCalledTimes(3) })
|
||||
rejectSlow(new Error('too late to matter'))
|
||||
await new Promise(settle => setTimeout(settle, 0))
|
||||
expect(screen.queryByRole('alert')).toBeNull()
|
||||
expect(screen.getByRole('listitem').textContent).toBe('Documents')
|
||||
})
|
||||
|
||||
it('drops a stale navigation failure that rejects after a newer jump', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
await waitFor(() => { expect(columns()).toHaveLength(2) })
|
||||
let rejectSlow!: (reason: unknown) => void
|
||||
const slow = new Promise<DirectoryListing>((_settle, fail) => { rejectSlow = fail })
|
||||
b.listDirectory.mockReturnValueOnce(slow)
|
||||
// A slow crumb jump superseded by a second jump.
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.home' }))
|
||||
fireEvent.click(within(screen.getByRole('navigation')).getByRole('button', { name: 'Documents' }))
|
||||
await waitFor(() => { expect(b.listDirectory).toHaveBeenCalledTimes(4) })
|
||||
rejectSlow(new Error('late nav failure'))
|
||||
await new Promise(settle => setTimeout(settle, 0))
|
||||
expect(screen.queryByRole('alert')).toBeNull()
|
||||
})
|
||||
|
||||
it('drops a stale navigation listing that resolves after a newer jump', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
await waitFor(() => { expect(columns()).toHaveLength(2) })
|
||||
let resolveSlow!: (value: DirectoryListing) => void
|
||||
const slow = new Promise<DirectoryListing>((settle) => { resolveSlow = settle })
|
||||
b.listDirectory.mockReturnValueOnce(slow)
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.home' }))
|
||||
fireEvent.click(within(screen.getByRole('navigation')).getByRole('button', { name: 'Documents' }))
|
||||
await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') })
|
||||
resolveSlow(listingFor(undefined))
|
||||
await new Promise(settle => setTimeout(settle, 0))
|
||||
// The stale home listing did not replace the newer Documents level.
|
||||
expect(screen.getByRole('listitem').textContent).toBe('harness')
|
||||
})
|
||||
|
||||
it('names the create target by its path when the level reports no crumbs', async () => {
|
||||
const bare: DirectoryListing = { path: '/srv/data', home: HOME, crumbs: [], entries: [], truncated: false }
|
||||
mount({ listDirectory: vi.fn(async () => bare) })
|
||||
await waitFor(() => { expect(screen.getByRole('button', { name: 'browser.newFolder' })).toBeTruthy() })
|
||||
await waitFor(() => {
|
||||
expect(screen.getByRole<HTMLButtonElement>('button', { name: 'browser.newFolder' }).disabled).toBe(false)
|
||||
})
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
expect(screen.getByText('browser.createIn:/srv/data')).toBeTruthy()
|
||||
})
|
||||
|
||||
it('refuses to close the nested dialog while the creation is in flight', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
let settleCreate!: (path: string) => void
|
||||
b.createDirectory.mockReturnValueOnce(new Promise<string>((settle) => { settleCreate = settle }))
|
||||
fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' }))
|
||||
const input = screen.getByLabelText('browser.folderName')
|
||||
fireEvent.change(input, { target: { value: 'slow' } })
|
||||
fireEvent.keyDown(input, { key: 'Enter' })
|
||||
// Escape and the mask are both inert while creating.
|
||||
fireEvent.keyDown(screen.getByLabelText('browser.folderName'), { key: 'Escape' })
|
||||
const masks = document.querySelectorAll('[aria-hidden="true"]')
|
||||
fireEvent.click(masks[masks.length - 1]!)
|
||||
expect(screen.getByLabelText('browser.folderName')).toBeTruthy()
|
||||
settleCreate(`${HOME}/slow`)
|
||||
await waitFor(() => { expect(screen.queryByLabelText('browser.folderName')).toBeNull() })
|
||||
})
|
||||
|
||||
it('says a level is incomplete when the backend cut it at its bound', async () => {
|
||||
const cut = { ...listingFor(HOME), truncated: true }
|
||||
mount({ listDirectory: vi.fn(async () => cut) })
|
||||
await screen.findByText('browser.truncated')
|
||||
})
|
||||
|
||||
it('flags a truncated child preview under a complete level', async () => {
|
||||
mount({
|
||||
listDirectory: vi.fn(async (path?: string) =>
|
||||
(path === DOCS ? { ...listingFor(DOCS), truncated: true } : listingFor(path))),
|
||||
})
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
expect(screen.queryByText('browser.truncated')).toBeNull()
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
await waitFor(() => { expect(columns()).toHaveLength(2) })
|
||||
await screen.findByText('browser.truncated')
|
||||
})
|
||||
|
||||
it('pins the child pane into view when its preview lands (narrow viewports scroll the miller row)', async () => {
|
||||
mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
const row = document.querySelector('[class*=millerRow]') as HTMLElement
|
||||
// jsdom does no layout: stub the overflow width the effect pins against.
|
||||
Object.defineProperty(row, 'scrollWidth', { value: 640, configurable: true })
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
await waitFor(() => { expect(columns()).toHaveLength(2) })
|
||||
await waitFor(() => { expect(row.scrollLeft).toBe(640) })
|
||||
})
|
||||
|
||||
it('starts back at home on reopen', async () => {
|
||||
const b = mount()
|
||||
await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() })
|
||||
fireEvent.click(rowButton(screen.getByRole('listitem')))
|
||||
await waitFor(() => { expect(columns()).toHaveLength(2) })
|
||||
b.view.rerender(<DirectoryBrowser {...b.props} open={false} />)
|
||||
b.view.rerender(<DirectoryBrowser {...b.props} open />)
|
||||
await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('Documents') })
|
||||
expect(columns()).toHaveLength(1)
|
||||
expect(b.listDirectory).toHaveBeenLastCalledWith(undefined, expect.any(AbortSignal))
|
||||
})
|
||||
})
|
||||
231
packages/host/directory-picker-browse/tests/service.spec.ts
Normal file
231
packages/host/directory-picker-browse/tests/service.spec.ts
Normal file
@@ -0,0 +1,231 @@
|
||||
/** Behavior of the browse backend over a real temporary directory tree. */
|
||||
|
||||
import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
|
||||
import { homedir, tmpdir } from 'node:os'
|
||||
import { basename, join } from 'node:path'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import { DirectoryPickerError } from '@deepseek-ai/dsh-host-directory-picker'
|
||||
import type { DirectoryPickerBrowseCapability } from '@deepseek-ai/dsh-host-directory-picker'
|
||||
import BrowseDirectoryPicker, { boundedInsert, fullyQualified, raceAbort } from '../src/index.ts'
|
||||
import type { ListingCandidate } from '../src/index.ts'
|
||||
|
||||
let root: string
|
||||
let capability: DirectoryPickerBrowseCapability
|
||||
let dispose: () => Promise<void>
|
||||
|
||||
beforeAll(async () => {
|
||||
root = await mkdtemp(join(tmpdir(), 'dsh-browse-'))
|
||||
await mkdir(join(root, 'projects'))
|
||||
await mkdir(join(root, 'projects', 'harness'))
|
||||
await mkdir(join(root, '.hidden-dir'))
|
||||
await writeFile(join(root, 'notes.txt'), 'not a directory')
|
||||
await symlink(join(root, 'projects'), join(root, 'linked'), 'junction')
|
||||
await symlink(join(root, 'gone'), join(root, 'broken'), 'junction')
|
||||
try {
|
||||
await symlink(join(root, 'notes.txt'), join(root, 'file-link'))
|
||||
} catch {
|
||||
// Windows denies unprivileged file symlinks; the file-link row only
|
||||
// feeds the POSIX lanes' coverage of the symlink-to-file arm, and every
|
||||
// assertion below expects it to be filtered out anyway.
|
||||
}
|
||||
|
||||
const ctx = new Context()
|
||||
const fiber = ctx.plugin(BrowseDirectoryPicker)
|
||||
await fiber.await()
|
||||
const picked = ctx.get('directoryPicker')!.capability()
|
||||
if (picked.kind !== 'browse') throw new Error('browse backend must advertise the browse capability')
|
||||
capability = picked
|
||||
dispose = () => fiber.dispose()
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await dispose()
|
||||
await rm(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
describe('BrowseDirectoryPicker', () => {
|
||||
it('lists directories only, flags hidden rows, follows symlinks, skips broken links, sorts by name', async () => {
|
||||
const listing = await capability.list(root)
|
||||
expect(listing.path).toBe(root)
|
||||
expect(listing.home).toBe(homedir())
|
||||
expect(listing.entries.map(entry => entry.name)).toEqual(['.hidden-dir', 'linked', 'projects'])
|
||||
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)
|
||||
// A level that fits the window but exceeds the bound (two rows, bound
|
||||
// one): the in-window extra row proves the cut without any eviction.
|
||||
await mkdir(join(root, 'projects', 'harness', 'a'))
|
||||
await mkdir(join(root, 'projects', 'harness', 'b'))
|
||||
const inWindow = await bounded.list(join(root, 'projects', 'harness'))
|
||||
expect(inWindow.entries.map(entry => entry.name)).toEqual(['a'])
|
||||
expect(inWindow.truncated).toBe(true)
|
||||
} finally {
|
||||
await fiber.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('stops the scan with the caller: an aborted signal rejects with its own reason', async () => {
|
||||
const gone = new AbortController()
|
||||
gone.abort(new Error('caller left'))
|
||||
// The abort surfaces as-is, not dressed as an unreadable directory —
|
||||
// and rejects even before any level row is read.
|
||||
await expect(capability.list(root, gone.signal)).rejects.toThrow('caller left')
|
||||
// The abandoned open that still succeeds is closed, not leaked.
|
||||
await new Promise(resolve => setTimeout(resolve, 10))
|
||||
// Aborted against a missing target: the abandoned open rejects on its
|
||||
// own and there is nothing to close.
|
||||
await expect(capability.list(join(root, 'no-such-dir'), gone.signal)).rejects.toThrow('caller left')
|
||||
await new Promise(resolve => setTimeout(resolve, 10))
|
||||
// A live signal leaves a normal listing untouched — the reads and the
|
||||
// symlink probes race it without ever losing.
|
||||
const live = new AbortController()
|
||||
const complete = await capability.list(root, live.signal)
|
||||
expect(complete.truncated).toBe(false)
|
||||
expect(complete.entries.map(entry => entry.name)).toContain('linked')
|
||||
// A live signal changes nothing about ordinary failures.
|
||||
const missing = join(root, 'no-such-dir')
|
||||
const failure = await capability.list(missing, live.signal).catch((error: unknown) => error)
|
||||
expect(failure).toBeInstanceOf(DirectoryPickerError)
|
||||
expect((failure as DirectoryPickerError).code).toBe('directory-unreadable')
|
||||
})
|
||||
|
||||
it('raceAbort follows the operation until the signal wins, and swallows the abandoned settlement', async () => {
|
||||
// No signal / settled operations: plain passthrough, listener removed.
|
||||
await expect(raceAbort(Promise.resolve('ok'), undefined)).resolves.toBe('ok')
|
||||
const live = new AbortController()
|
||||
await expect(raceAbort(Promise.resolve('ok'), live.signal)).resolves.toBe('ok')
|
||||
// Failure passthrough keeps the operation's own error.
|
||||
await expect(raceAbort(Promise.reject(new Error('raw failure')), live.signal)).rejects.toThrow('raw failure')
|
||||
// The abort wins over a pending operation and carries its own reason;
|
||||
// the operation's late rejection is swallowed, never unhandled.
|
||||
const rejections: unknown[] = []
|
||||
const onUnhandled = (reason: unknown): void => { rejections.push(reason) }
|
||||
process.on('unhandledRejection', onUnhandled)
|
||||
try {
|
||||
let rejectLate!: (reason: unknown) => void
|
||||
const pending = new Promise<never>((_resolve, reject) => { rejectLate = reject })
|
||||
const controller = new AbortController()
|
||||
const raced = raceAbort(pending, controller.signal)
|
||||
// A bare-string abort reason exercises the Error wrap.
|
||||
controller.abort('caller left')
|
||||
await expect(raced).rejects.toThrow('caller left')
|
||||
rejectLate(new Error('late read failure'))
|
||||
await new Promise(resolve => setTimeout(resolve, 10))
|
||||
expect(rejections).toEqual([])
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled)
|
||||
}
|
||||
})
|
||||
|
||||
it('boundedInsert keeps the window name-sorted and bounded, reporting evictions', () => {
|
||||
const candidate = (name: string): ListingCandidate => ({ name, isDirectory: true, isSymbolicLink: false })
|
||||
const window: ListingCandidate[] = []
|
||||
expect(boundedInsert(window, candidate('m'), 2)).toBe(false)
|
||||
expect(boundedInsert(window, candidate('z'), 2)).toBe(false)
|
||||
// A smaller name lands in place and pushes the current largest out.
|
||||
expect(boundedInsert(window, candidate('a'), 2)).toBe(true)
|
||||
expect(window.map(entry => entry.name)).toEqual(['a', 'm'])
|
||||
// A name at or beyond the full window's tail rejects on one comparison.
|
||||
expect(boundedInsert(window, candidate('t'), 2)).toBe(true)
|
||||
expect(window.map(entry => entry.name)).toEqual(['a', 'm'])
|
||||
expect(boundedInsert(window, candidate('m'), 2)).toBe(true)
|
||||
expect(window.map(entry => entry.name)).toEqual(['a', 'm'])
|
||||
})
|
||||
|
||||
it('reports the ancestry as jump-target crumbs ending at the listed directory', async () => {
|
||||
const listing = await capability.list(join(root, 'projects'))
|
||||
const tail = listing.crumbs.at(-1)!
|
||||
expect(tail).toMatchObject({ name: 'projects', path: join(root, 'projects'), hidden: false })
|
||||
expect(listing.crumbs.at(-2)!.path).toBe(root)
|
||||
expect(listing.crumbs.at(-2)!.name).toBe(basename(root))
|
||||
// The chain starts at the filesystem root, whose crumb is labeled by its full path.
|
||||
expect(listing.crumbs[0]!.name).toBe(listing.crumbs[0]!.path)
|
||||
})
|
||||
|
||||
it('lists the home directory when no path is given', async () => {
|
||||
const listing = await capability.list()
|
||||
expect(listing.path).toBe(homedir())
|
||||
})
|
||||
|
||||
it('throws directory-unreadable for a missing target', async () => {
|
||||
const missing = join(root, 'no-such-dir')
|
||||
const failure = await capability.list(missing).catch((error: unknown) => error)
|
||||
expect(failure).toBeInstanceOf(DirectoryPickerError)
|
||||
expect((failure as DirectoryPickerError).code).toBe('directory-unreadable')
|
||||
expect((failure as DirectoryPickerError).path).toBe(missing)
|
||||
})
|
||||
|
||||
it('classifies fully qualified paths per platform (drive-less rooted Windows forms rejected)', () => {
|
||||
expect(fullyQualified('/home/x', 'linux')).toBe(true)
|
||||
expect(fullyQualified('x/y', 'darwin')).toBe(false)
|
||||
expect(fullyQualified('C:\\projects', 'win32')).toBe(true)
|
||||
expect(fullyQualified('C:/projects', 'win32')).toBe(true)
|
||||
expect(fullyQualified('\\\\server\\share', 'win32')).toBe(true)
|
||||
expect(fullyQualified('//server/share/deep', 'win32')).toBe(true)
|
||||
// Rooted but drive-less: isAbsolute accepts these, yet resolve() would
|
||||
// inject the process's current drive.
|
||||
expect(fullyQualified('\\foo', 'win32')).toBe(false)
|
||||
expect(fullyQualified('/foo', 'win32')).toBe(false)
|
||||
expect(fullyQualified('C:relative', 'win32')).toBe(false)
|
||||
// Incomplete UNC prefixes collapse to drive-relative roots under resolve().
|
||||
expect(fullyQualified('\\\\', 'win32')).toBe(false)
|
||||
expect(fullyQualified('\\\\server', 'win32')).toBe(false)
|
||||
expect(fullyQualified('\\\\server\\', 'win32')).toBe(false)
|
||||
})
|
||||
|
||||
it('rejects non-absolute paths instead of rebasing them under the process cwd', async () => {
|
||||
for (const relative of ['', 'projects', './projects', '..']) {
|
||||
const listFailure = await capability.list(relative).catch((error: unknown) => error)
|
||||
expect(listFailure).toBeInstanceOf(DirectoryPickerError)
|
||||
expect((listFailure as DirectoryPickerError).code).toBe('directory-unreadable')
|
||||
expect((listFailure as DirectoryPickerError).path).toBe(relative)
|
||||
const createFailure = await capability.createDirectory(relative, 'child').catch((error: unknown) => error)
|
||||
expect(createFailure).toBeInstanceOf(DirectoryPickerError)
|
||||
expect((createFailure as DirectoryPickerError).code).toBe('directory-create-failed')
|
||||
expect((createFailure as DirectoryPickerError).path).toBe(relative)
|
||||
}
|
||||
})
|
||||
|
||||
it('creates one child directory and surfaces it in the next listing', async () => {
|
||||
const created = await capability.createDirectory(root, 'fresh')
|
||||
expect(created).toBe(join(root, 'fresh'))
|
||||
const listing = await capability.list(root)
|
||||
expect(listing.entries.map(entry => entry.name)).toContain('fresh')
|
||||
})
|
||||
|
||||
it('refuses an existing child with directory-exists', async () => {
|
||||
const failure = await capability.createDirectory(root, 'projects').catch((error: unknown) => error)
|
||||
expect(failure).toBeInstanceOf(DirectoryPickerError)
|
||||
expect((failure as DirectoryPickerError).code).toBe('directory-exists')
|
||||
})
|
||||
|
||||
it('refuses non-segment names and other filesystem failures with directory-create-failed', async () => {
|
||||
for (const name of ['', ' ', '.', '..', 'a/b', 'a\\b']) {
|
||||
const failure = await capability.createDirectory(root, name).catch((error: unknown) => error)
|
||||
expect(failure).toBeInstanceOf(DirectoryPickerError)
|
||||
expect((failure as DirectoryPickerError).code).toBe('directory-create-failed')
|
||||
}
|
||||
// Missing parent is a real failure, not a level to invent.
|
||||
const missingParent = await capability.createDirectory(join(root, 'no-such-dir'), 'child').catch((error: unknown) => error)
|
||||
expect((missingParent as DirectoryPickerError).code).toBe('directory-create-failed')
|
||||
})
|
||||
})
|
||||
36
packages/host/directory-picker-browse/tsconfig.json
Normal file
36
packages/host/directory-picker-browse/tsconfig.json
Normal file
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.client.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types",
|
||||
"types": [
|
||||
"node"
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../directory-picker"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
},
|
||||
{
|
||||
"path": "../../client/ui-slots"
|
||||
},
|
||||
{
|
||||
"path": "../../client/ui-primitives"
|
||||
},
|
||||
{
|
||||
"path": "../../client/locale"
|
||||
},
|
||||
{
|
||||
"path": "../../client/runtime"
|
||||
},
|
||||
{
|
||||
"path": "../../client/ui-workspace"
|
||||
}
|
||||
]
|
||||
}
|
||||
3
packages/host/directory-picker-browse/tsdown.config.ts
Normal file
3
packages/host/directory-picker-browse/tsdown.config.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { clientBundle } from '../../client/tsdown.client.ts'
|
||||
|
||||
export default clientBundle('@deepseek-ai/dsh-host-directory-picker-browse', ['lib/types/index.js', 'lib/types/invariant.js'])
|
||||
6
packages/host/directory-picker-native/README.i18n.yaml
Normal file
6
packages/host/directory-picker-native/README.i18n.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# 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-native/README.md
|
||||
README.md: 0b54c651d4f5382021d0f8832ab4f1146b7652c8
|
||||
README.zh.md: e5ac2762a691a16a7e6d9d6dd9aefc70a59dcd4f
|
||||
19
packages/host/directory-picker-native/README.md
Normal file
19
packages/host/directory-picker-native/README.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# @deepseek-ai/dsh-host-directory-picker-native
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
The **native-OS-chooser backend** of the [directory-picker seam](../directory-picker/README.md): `NativeDirectoryPicker` registers `ctx.directoryPicker` with the `native` capability, whose `pick(signal)` opens one native chooser per call and resolves the chosen absolute path (`null` on cancel). Platform tools run without a shell: `osascript` on macOS, an STA PowerShell `FolderBrowserDialog` on Windows, and Zenity with a KDialog fallback on Linux; the caller's abort terminates the native process. Only viable when the operator sits at the host's display — remote deployments compose [`-browse`](../directory-picker-browse/README.md) instead. The command boundary (`DirectoryPickerRunner`) and platform facts are injectable for deterministic tests. The shared no-shell subprocess runner lives in [`dsh-native-command`](../../util/native-command/README.md).
|
||||
|
||||
**Dual-face package**: the browser half (`./client`) registers a renderless flow occupant into [ui-workspace's](../../client/ui-workspace/README.md) two directory-flow holes — each `open` request drives `host.pickDirectory` and reports the one outcome (picked path / cancel / failure) through the hole's owner conversation. One cordis.yml row therefore composes both sides of the native interaction; the client carries no capability-kind branching, and mounting a second flow package fails at load (the holes are `single` kind).
|
||||
|
||||
## Model Experience
|
||||
|
||||
None, as the backend serves the GUI host's directory selection; nothing here reaches a model request.
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
None; this package neither assembles nor sends a provider request.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
- **Linux requires desktop tooling** — with neither Zenity nor KDialog installed, `pick` rejects with an actionable error; it does not fall back to a typed-path prompt (the browse backend is that fallback at the composition level).
|
||||
19
packages/host/directory-picker-native/README.zh.md
Normal file
19
packages/host/directory-picker-native/README.zh.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# @deepseek-ai/dsh-host-directory-picker-native
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
[目录选择 seam](../directory-picker/README.md) 的**原生 OS 选择器后端**:`NativeDirectoryPicker` 以 `native` 能力注册 `ctx.directoryPicker`,其 `pick(signal)` 每次调用打开一个原生选择器并解析出所选绝对路径(取消时为 `null`)。平台工具不经 shell 调用:macOS 使用 `osascript`,Windows 使用以 STA 模式运行的 PowerShell `FolderBrowserDialog`,Linux 使用 Zenity 并以 KDialog 回退;调用方的中止信号会终止原生进程。只有操作者坐在宿主屏幕前时才可用——远程部署应组合 [`-browse`](../directory-picker-browse/README.md)。命令边界(`DirectoryPickerRunner`)与平台事实可注入,便于确定性测试。共享的免 shell 子进程运行器位于 [`dsh-native-command`](../../util/native-command/README.md)。
|
||||
|
||||
**双面包**:browser half(`./client`)向 [ui-workspace](../../client/ui-workspace/README.md) 的两个目录流洞注册一个无渲染的流程占用者——每次 `open` 请求驱动 `host.pickDirectory`,并经洞的 owner 会话上报唯一结果(所选路径/取消/失败)。因此一行 cordis.yml 同时组合原生交互的两侧;client 侧不含任何能力 kind 分支,挂载第二个流程包会在加载期失败(洞为 `single` kind)。
|
||||
|
||||
## 模型体验
|
||||
|
||||
无。该后端服务于 GUI 宿主的目录选择;这里没有任何内容进入模型请求。
|
||||
|
||||
#### KV 缓存影响
|
||||
|
||||
无;该包既不组装也不发送提供方请求。
|
||||
|
||||
## 已知限制与延期工作
|
||||
|
||||
- **Linux 依赖桌面工具**——Zenity 与 KDialog 均未安装时,`pick` 以包含解决建议的错误拒绝;它不会回退为手输路径提示(组合层面的回退是 browse 后端)。
|
||||
62
packages/host/directory-picker-native/package.json
Normal file
62
packages/host/directory-picker-native/package.json
Normal file
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-host-directory-picker-native",
|
||||
"description": "Native-OS-chooser backend of the directory-picker seam for the DeepSeek Harness web GUI host",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./invariant": {
|
||||
"types": "./lib/types/invariant.d.ts",
|
||||
"default": "./lib/invariant.js"
|
||||
},
|
||||
"./client": {
|
||||
"types": "./lib/types/client/index.d.ts",
|
||||
"default": "./lib/client.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/invariant.js",
|
||||
"lib/client.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"src"
|
||||
],
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"@deepseek-ai/dsh-host-directory-picker": "workspace:^",
|
||||
"@deepseek-ai/dsh-native-command": "workspace:^"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/dsh-client-runtime": "^0.0.1",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "^0.0.1",
|
||||
"@deepseek-ai/dsh-client-ui-workspace": "^0.0.1",
|
||||
"@deepseek-ai/dsh-invariants": "^0.0.1",
|
||||
"cordis": "^4.0.0-rc.7",
|
||||
"react": "^18.2.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-client-runtime": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-slots": "workspace:^",
|
||||
"@deepseek-ai/dsh-client-ui-workspace": "workspace:^",
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
"@types/react": "~18.3.1",
|
||||
"cordis": "^4.0.0-rc.7",
|
||||
"react": "^18.2.0"
|
||||
},
|
||||
"dshClient": {
|
||||
"inject": [
|
||||
"@deepseek-ai/dsh-client-runtime",
|
||||
"@deepseek-ai/dsh-client-ui-workspace"
|
||||
],
|
||||
"platform": "web"
|
||||
}
|
||||
}
|
||||
65
packages/host/directory-picker-native/src/client/flow.ts
Normal file
65
packages/host/directory-picker-native/src/client/flow.ts
Normal file
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* The native picking occupant (package-internal; the `./client` surface
|
||||
* exposes only the Loader exports). Same-package tests exercise it directly
|
||||
* through this module.
|
||||
*/
|
||||
import { useEffect, useRef } from 'react'
|
||||
import type { ReactElement } from 'react'
|
||||
// Type-only: the owner contract of the directory-flow holes.
|
||||
import type { DirectoryFlowOwnerProps } from '@deepseek-ai/dsh-client-ui-workspace/client'
|
||||
|
||||
/** Injected face: the wire call the flow drives (bound in apply's closure). */
|
||||
export interface NativeFlowInjected {
|
||||
/** Ask the local Host to open its native single-directory chooser. */
|
||||
pick: () => Promise<string | null>
|
||||
}
|
||||
|
||||
/**
|
||||
* Renderless flow occupant: each rising `open` edge runs exactly one pick and
|
||||
* reports exactly one outcome; the ref arms once per open so re-renders (and
|
||||
* an adoption keeping `open` true while `busy`) never launch a second
|
||||
* chooser. The owner withdrawing `open` re-arms the next request.
|
||||
* @param props - owner conversation plus the injected pick call.
|
||||
* @returns nothing — the native chooser renders on the host display.
|
||||
*/
|
||||
export function NativeDirectoryFlow(props: DirectoryFlowOwnerProps & NativeFlowInjected): ReactElement | null {
|
||||
const { open, pick } = props
|
||||
const armed = useRef(false)
|
||||
// Callbacks ride a ref so the settled pick reports through the owner's
|
||||
// latest handlers, not the ones captured when the chooser opened.
|
||||
const outcome = useRef(props)
|
||||
outcome.current = props
|
||||
// Unmount (HMR replacing the occupant) discards settlements wholesale: the
|
||||
// dead instance must neither adopt a path nor drive the owner's error
|
||||
// surface. The wire carries no per-request abort, so the host-side chooser
|
||||
// survives until answered — its answer just lands nowhere; the replacement
|
||||
// instance re-arms under the owner's still-open request. An injected-face
|
||||
// identity change alone (re-registration) keeps the pending settlement:
|
||||
// the chooser on the host display is still the same dialog.
|
||||
const alive = useRef(true)
|
||||
useEffect(() => {
|
||||
// StrictMode's development replay runs the cleanup once before the real
|
||||
// lifetime: re-arm on setup or every outcome would be discarded.
|
||||
alive.current = true
|
||||
return () => { alive.current = false }
|
||||
}, [])
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
armed.current = false
|
||||
return
|
||||
}
|
||||
if (armed.current) return
|
||||
armed.current = true
|
||||
pick().then(
|
||||
(path) => {
|
||||
if (!alive.current) return
|
||||
if (path === null) outcome.current.onCancel(); else outcome.current.onPicked(path)
|
||||
},
|
||||
(reason: unknown) => {
|
||||
if (!alive.current) return
|
||||
outcome.current.onError(reason instanceof Error ? reason.message : String(reason))
|
||||
},
|
||||
)
|
||||
}, [open, pick])
|
||||
return null
|
||||
}
|
||||
41
packages/host/directory-picker-native/src/client/index.ts
Normal file
41
packages/host/directory-picker-native/src/client/index.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
/**
|
||||
* Browser half of the native directory-picker backend: fills ui-workspace's
|
||||
* two directory-flow holes with a renderless occupant that answers each
|
||||
* `open` by driving `host.pickDirectory` (the node half's OS chooser) and
|
||||
* reporting the one outcome — picked path, cancellation, or failure — back
|
||||
* through the owner conversation. Mounting this package therefore composes
|
||||
* both sides of the native interaction with one cordis.yml row; no client
|
||||
* code branches on a capability kind.
|
||||
*/
|
||||
import { deferGroupRegistration } from '@deepseek-ai/dsh-client-ui-slots'
|
||||
import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
// Type-only: pulls the SlotMap merge declaring the directory-flow holes.
|
||||
import type {} from '@deepseek-ai/dsh-client-ui-workspace/client'
|
||||
import type { NativeFlowInjected } from './flow.ts'
|
||||
import { NativeDirectoryFlow } from './flow.ts'
|
||||
|
||||
|
||||
/** Required services (cordis fiber inject): the slot registry and the wire-facing workspace service. */
|
||||
export const inject = ['slots', 'workspaces']
|
||||
|
||||
/**
|
||||
* Client plugin body: register the renderless native flow into both
|
||||
* directory-flow holes (declaration-aware deferral — the declaring
|
||||
* ui-workspace entries may activate later, and an HMR collapse re-declares).
|
||||
* @param ctx - client root context.
|
||||
*/
|
||||
export function apply(ctx: ClientContext): void {
|
||||
const injected = (): NativeFlowInjected => ({ pick: () => ctx.workspaces.pickDirectory() })
|
||||
ctx.effect(() => {
|
||||
// One occupant, both holes, as a unit: construction or late conflicts
|
||||
// (holes declared after rival providers activated) roll the whole pair
|
||||
// back and fail loud — semantics owned by deferGroupRegistration.
|
||||
const group = deferGroupRegistration(
|
||||
ctx.slots,
|
||||
['conversation.hero.workspace.directoryFlow', 'sidebar.workspaces.directoryFlow'] as const,
|
||||
NativeDirectoryFlow,
|
||||
name => ctx.slots.register({ name, inject: injected }, NativeDirectoryFlow),
|
||||
)
|
||||
return () => { group.dispose() }
|
||||
}, 'directory-picker-native: flow registrations')
|
||||
}
|
||||
33
packages/host/directory-picker-native/src/index.ts
Normal file
33
packages/host/directory-picker-native/src/index.ts
Normal file
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* Native backend of the directory-picker seam: registers `ctx.directoryPicker`
|
||||
* with the `native` capability, opening one native OS chooser on the host
|
||||
* display per pick (macOS `osascript`, Windows STA PowerShell
|
||||
* `FolderBrowserDialog`, Linux Zenity with a KDialog fallback). Only viable
|
||||
* when the operator sits at the host's screen; remote deployments compose the
|
||||
* browse backend instead.
|
||||
* @module @deepseek-ai/dsh-host-directory-picker-native
|
||||
*/
|
||||
|
||||
import { DirectoryPicker } from '@deepseek-ai/dsh-host-directory-picker'
|
||||
import type { DirectoryPickerCapability } from '@deepseek-ai/dsh-host-directory-picker'
|
||||
import { pickNativeDirectory } from './native-picker.ts'
|
||||
|
||||
export type { DirectoryPickerInternals, DirectoryPickerRunner } from './native-picker.ts'
|
||||
export { pickNativeDirectory } from './native-picker.ts'
|
||||
|
||||
/** The `ctx.directoryPicker` native implementation (stable capability object per service life). */
|
||||
export default class NativeDirectoryPicker extends DirectoryPicker {
|
||||
private readonly nativeCapability: DirectoryPickerCapability = {
|
||||
kind: 'native',
|
||||
/* v8 ignore next -- pure forward to pickNativeDirectory (its spec owns behavior); invoking here opens a real chooser. */
|
||||
pick: signal => pickNativeDirectory(signal),
|
||||
}
|
||||
|
||||
/**
|
||||
* The native interaction capability.
|
||||
* @returns the stable `native` capability object.
|
||||
*/
|
||||
capability(): DirectoryPickerCapability {
|
||||
return this.nativeCapability
|
||||
}
|
||||
}
|
||||
25
packages/host/directory-picker-native/src/invariant.ts
Normal file
25
packages/host/directory-picker-native/src/invariant.ts
Normal file
@@ -0,0 +1,25 @@
|
||||
/**
|
||||
* Package-owned invariant companion for the native directory-picker backend.
|
||||
* @module @deepseek-ai/dsh-host-directory-picker-native/invariant
|
||||
*/
|
||||
|
||||
import type { Context } from 'cordis'
|
||||
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/dsh-host-directory-picker-native'
|
||||
|
||||
/** Cordis companion plugin name. */
|
||||
export const name = 'host-directory-picker-native-invariant'
|
||||
/** Service required before the companion can reserve package ownership. */
|
||||
export const inject = ['invariants']
|
||||
|
||||
/** No runtime invariant: each pick is one stateless subprocess round trip; the chooser outcome is only the returned path. */
|
||||
const install: InvariantInstaller = () => {}
|
||||
|
||||
/**
|
||||
* Register the native directory-picker invariant companion.
|
||||
* @param ctx - Cordis context carrying the invariant service.
|
||||
* @returns the installed registration's disposer after setup succeeds.
|
||||
*/
|
||||
export const apply = (ctx: Context): Promise<() => void> =>
|
||||
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
|
||||
@@ -1,6 +1,6 @@
|
||||
/** Cross-platform native single-directory picker used by the local GUI carrier. */
|
||||
/** Cross-platform native single-directory chooser behind the native backend's capability. */
|
||||
|
||||
import { runNativeCommand, type NativeCommandRunner } from './native-command.ts'
|
||||
import { runNativeCommand, type NativeCommandRunner } from '@deepseek-ai/dsh-native-command'
|
||||
|
||||
/** Testable command boundary; native implementations never invoke a shell. */
|
||||
export type DirectoryPickerRunner = NativeCommandRunner
|
||||
219
packages/host/directory-picker-native/tests/client-flow.spec.tsx
Normal file
219
packages/host/directory-picker-native/tests/client-flow.spec.tsx
Normal file
@@ -0,0 +1,219 @@
|
||||
// @vitest-environment jsdom
|
||||
import { Context } from 'cordis'
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { act, cleanup, render } from '@testing-library/react'
|
||||
import { afterEach } from 'vitest'
|
||||
import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
|
||||
import type { DirectoryFlowOwnerProps } from '@deepseek-ai/dsh-client-ui-workspace/client'
|
||||
import { apply, inject } from '../src/client/index.ts'
|
||||
import { NativeDirectoryFlow } from '../src/client/flow.ts'
|
||||
|
||||
afterEach(cleanup)
|
||||
|
||||
const HOLES = ['conversation.hero.workspace.directoryFlow', 'sidebar.workspaces.directoryFlow'] as const
|
||||
|
||||
async function bench() {
|
||||
const ctx = new Context()
|
||||
await ctx.plugin(SlotsService).await()
|
||||
const pickDirectory = vi.fn(async (): Promise<string | null> => '/tmp/picked')
|
||||
ctx.provide('workspaces', { pickDirectory } as never)
|
||||
const slots = ctx.get('slots') as SlotsService
|
||||
const declare = () => slots.register({
|
||||
name: 'root',
|
||||
children: Object.fromEntries(HOLES.map(name => [name, { kind: 'single', scope: 'root' }])),
|
||||
} as never, () => null)
|
||||
return { ctx, slots, pickDirectory, declare }
|
||||
}
|
||||
|
||||
function owner(overrides: Partial<DirectoryFlowOwnerProps> = {}): DirectoryFlowOwnerProps {
|
||||
return {
|
||||
open: true, busy: false,
|
||||
onPicked: vi.fn(), onCancel: vi.fn(), onError: vi.fn(),
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
describe('directory-picker-native client half', () => {
|
||||
it('declares the services it drives', () => {
|
||||
expect(inject).toEqual(['slots', 'workspaces'])
|
||||
})
|
||||
|
||||
it('fills both directory-flow holes for declarations before or after apply, and leaves with its fiber', async () => {
|
||||
const before = await bench()
|
||||
before.declare()
|
||||
const fiber = before.ctx.plugin({ inject: [...inject], apply })
|
||||
await fiber.await()
|
||||
for (const hole of HOLES) expect(before.slots.entries(hole)).toHaveLength(1)
|
||||
// Registry-contribution disposal proof: the fiber going down empties the holes.
|
||||
await fiber.dispose()
|
||||
for (const hole of HOLES) expect(before.slots.entries(hole)).toHaveLength(0)
|
||||
|
||||
const after = await bench()
|
||||
await after.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
for (const hole of HOLES) expect(after.slots.entries(hole)).toHaveLength(0)
|
||||
after.declare()
|
||||
await Promise.resolve()
|
||||
for (const hole of HOLES) expect(after.slots.entries(hole)).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('rolls back wholesale and reports loudly when a rival provider wins after deferred activation', async () => {
|
||||
const b = await bench()
|
||||
const rejections: unknown[] = []
|
||||
const onUnhandled = (reason: unknown): void => { rejections.push(reason) }
|
||||
// queueMicrotask throws surface as uncaughtException, not a rejection.
|
||||
process.on('unhandledRejection', onUnhandled)
|
||||
process.on('uncaughtException', onUnhandled)
|
||||
try {
|
||||
// This provider activates BEFORE any hole exists: both deferrals wait.
|
||||
// (Duplicate rows of the SAME package converge silently — the deferral
|
||||
// skips a hole its own component already occupies; the conflict needs
|
||||
// a rival provider.)
|
||||
await b.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
b.declare()
|
||||
// A rival occupies both holes ahead of the pending microtask flush.
|
||||
b.slots.register({ name: HOLES[0] } as never, () => null)
|
||||
b.slots.register({ name: HOLES[1] } as never, () => null)
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
// The rival keeps both holes; this provider rolled back wholesale and
|
||||
// surfaced the conflict on the fail-loud channel — no partial mix.
|
||||
for (const hole of HOLES) expect(b.slots.entries(hole)).toHaveLength(1)
|
||||
expect(rejections.map(String).join('\n')).toContain('already has a registration')
|
||||
|
||||
// Non-Error conflicts wrap before the loud rethrow (same channel).
|
||||
const c = await bench()
|
||||
await c.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
const original = c.slots.register.bind(c.slots)
|
||||
const slotsAny = c.slots as { register: typeof original }
|
||||
slotsAny.register = ((options: never, component: never) => {
|
||||
if ((options as { name?: string }).name === HOLES[0]) throw 'string conflict'
|
||||
return original(options, component)
|
||||
}) as typeof original
|
||||
c.declare()
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
expect(rejections.map(String).join('\n')).toContain('string conflict')
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled)
|
||||
process.off('uncaughtException', onUnhandled)
|
||||
}
|
||||
})
|
||||
|
||||
it('rolls back the first deferral when the second hole is already occupied', async () => {
|
||||
const b = await bench()
|
||||
b.declare()
|
||||
// Foreign occupant in the SECOND registered hole: the pair construction
|
||||
// throws after the first deferral installed its subscription.
|
||||
b.slots.register({ name: HOLES[1] } as never, () => null)
|
||||
const rejections: unknown[] = []
|
||||
const onUnhandled = (reason: unknown): void => { rejections.push(reason) }
|
||||
process.on('unhandledRejection', onUnhandled)
|
||||
try {
|
||||
const fiber = b.ctx.plugin({ inject: [...inject], apply })
|
||||
await expect(fiber.await()).rejects.toThrow(/already has a registration/)
|
||||
// A leaked first deferral would now race this probe registration and
|
||||
// throw from its orphaned subscription against the HERO hole; the
|
||||
// rollback leaves only the activation failure itself (cordis re-raises
|
||||
// the apply throw as a late rejection — installFailLoud's contract).
|
||||
const disposeProbe = b.slots.register({ name: HOLES[0] } as never, () => null)
|
||||
await new Promise(resolve => setTimeout(resolve, 20))
|
||||
expect(rejections.map(String).filter(text => text.includes(HOLES[0]))).toEqual([])
|
||||
disposeProbe()
|
||||
} finally {
|
||||
process.off('unhandledRejection', onUnhandled)
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects a second flow occupant at load (single-kind hole)', async () => {
|
||||
const b = await bench()
|
||||
b.declare()
|
||||
await b.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
expect(() => b.slots.register({ name: HOLES[0] } as never, () => null))
|
||||
.toThrow(/already has a registration/)
|
||||
})
|
||||
|
||||
it('drives the injected pick through the hole entry and reports the picked path', async () => {
|
||||
const b = await bench()
|
||||
b.declare()
|
||||
await b.ctx.plugin({ inject: [...inject], apply }).await()
|
||||
const entry = b.slots.entries(HOLES[0])[0]!
|
||||
const injected = (entry.inject as () => { pick: () => Promise<string | null> })()
|
||||
await expect(injected.pick()).resolves.toBe('/tmp/picked')
|
||||
expect(b.pickDirectory).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('runs one pick per open edge and reports the path to the latest onPicked', async () => {
|
||||
let resolve!: (path: string | null) => void
|
||||
const pick = vi.fn(() => new Promise<string | null>((settle) => { resolve = settle }))
|
||||
const first = owner()
|
||||
const view = render(<NativeDirectoryFlow {...first} pick={pick} />)
|
||||
expect(pick).toHaveBeenCalledOnce()
|
||||
// Re-renders while open (busy flips, handler identity changes) must not relaunch the chooser.
|
||||
const second = owner()
|
||||
view.rerender(<NativeDirectoryFlow {...second} busy pick={pick} />)
|
||||
expect(pick).toHaveBeenCalledOnce()
|
||||
// Even a fresh injected face (re-registration re-runs the inject factory)
|
||||
// must not relaunch while the same request is still open.
|
||||
const replacedPick = vi.fn(() => new Promise<string | null>(() => {}))
|
||||
view.rerender(<NativeDirectoryFlow {...second} busy pick={replacedPick} />)
|
||||
expect(replacedPick).not.toHaveBeenCalled()
|
||||
await act(async () => { resolve('/tmp/project') })
|
||||
expect(second.onPicked).toHaveBeenCalledWith('/tmp/project')
|
||||
expect(first.onPicked).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('discards a settlement that lands after the flow unmounted', async () => {
|
||||
let resolve!: (path: string | null) => void
|
||||
const pick = vi.fn(() => new Promise<string | null>((settle) => { resolve = settle }))
|
||||
const props = owner()
|
||||
const view = render(<NativeDirectoryFlow {...props} pick={pick} />)
|
||||
expect(pick).toHaveBeenCalledOnce()
|
||||
view.unmount()
|
||||
// The dead instance must neither adopt nor error; the owner's callbacks
|
||||
// stay untouched by the orphaned chooser's answer.
|
||||
await act(async () => { resolve('/tmp/late') })
|
||||
expect(props.onPicked).not.toHaveBeenCalled()
|
||||
expect(props.onCancel).not.toHaveBeenCalled()
|
||||
expect(props.onError).not.toHaveBeenCalled()
|
||||
|
||||
// The failure arm is discarded the same way.
|
||||
let reject!: (reason: unknown) => void
|
||||
const failing = vi.fn(() => new Promise<string | null>((_settle, rejectPick) => { reject = rejectPick }))
|
||||
const late = owner()
|
||||
const failingView = render(<NativeDirectoryFlow {...late} pick={failing} />)
|
||||
failingView.unmount()
|
||||
await act(async () => { reject(new Error('too late')) })
|
||||
expect(late.onError).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports null as cancellation and re-arms after the owner withdraws open', async () => {
|
||||
const pick = vi.fn(async () => null as string | null)
|
||||
const props = owner()
|
||||
const view = render(<NativeDirectoryFlow {...props} pick={pick} />)
|
||||
await act(async () => {})
|
||||
expect(props.onCancel).toHaveBeenCalledOnce()
|
||||
expect(props.onPicked).not.toHaveBeenCalled()
|
||||
// Withdraw and reopen: a fresh request runs a fresh pick.
|
||||
view.rerender(<NativeDirectoryFlow {...props} open={false} pick={pick} />)
|
||||
view.rerender(<NativeDirectoryFlow {...props} pick={pick} />)
|
||||
await act(async () => {})
|
||||
expect(pick).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('folds pick failures into onError messages', async () => {
|
||||
const props = owner()
|
||||
render(<NativeDirectoryFlow {...props} pick={vi.fn(async () => { throw new Error('no chooser installed') })} />)
|
||||
await act(async () => {})
|
||||
expect(props.onError).toHaveBeenCalledWith('no chooser installed')
|
||||
|
||||
const nonError = owner()
|
||||
render(<NativeDirectoryFlow {...nonError} pick={vi.fn(async () => { throw 'denied' })} />)
|
||||
await act(async () => {})
|
||||
expect(nonError.onError).toHaveBeenCalledWith('denied')
|
||||
})
|
||||
|
||||
it('renders nothing while closed and while open', () => {
|
||||
const closed = render(<NativeDirectoryFlow {...owner({ open: false })} pick={vi.fn(async () => null)} />)
|
||||
expect(closed.container.innerHTML).toBe('')
|
||||
const opened = render(<NativeDirectoryFlow {...owner()} pick={vi.fn(async () => null)} />)
|
||||
expect(opened.container.innerHTML).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -15,7 +15,7 @@ const { execFileMock } = vi.hoisted(() => ({ execFileMock: vi.fn<ExecFileMock>()
|
||||
vi.mock('node:child_process', () => ({ execFile: execFileMock }))
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
import { pickNativeDirectory, type DirectoryPickerRunner } from '../src/native-directory-picker.ts'
|
||||
import { pickNativeDirectory, type DirectoryPickerRunner } from '../src/native-picker.ts'
|
||||
|
||||
function failure(code: string | number, stderr = ''): Error {
|
||||
return Object.assign(new Error(`command failed: ${String(code)}`), { code, stderr })
|
||||
21
packages/host/directory-picker-native/tests/service.spec.ts
Normal file
21
packages/host/directory-picker-native/tests/service.spec.ts
Normal file
@@ -0,0 +1,21 @@
|
||||
/** Registration/capability behavior of the native backend (the seam's cordis half). */
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import NativeDirectoryPicker from '../src/index.ts'
|
||||
|
||||
describe('NativeDirectoryPicker', () => {
|
||||
it('registers ctx.directoryPicker with a stable native capability and leaves with its fiber', async () => {
|
||||
const ctx = new Context()
|
||||
const fiber = ctx.plugin(NativeDirectoryPicker)
|
||||
await fiber.await()
|
||||
const picker = ctx.get('directoryPicker')
|
||||
expect(picker).toBeInstanceOf(NativeDirectoryPicker)
|
||||
const capability = picker!.capability()
|
||||
expect(capability.kind).toBe('native')
|
||||
// Stability: consumers may capture the capability object across calls.
|
||||
expect(picker!.capability()).toBe(capability)
|
||||
await fiber.dispose()
|
||||
expect(ctx.get('directoryPicker')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
33
packages/host/directory-picker-native/tsconfig.json
Normal file
33
packages/host/directory-picker-native/tsconfig.json
Normal file
@@ -0,0 +1,33 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.client.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types",
|
||||
"types": [
|
||||
"node"
|
||||
]
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../directory-picker"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
},
|
||||
{
|
||||
"path": "../../util/native-command"
|
||||
},
|
||||
{
|
||||
"path": "../../client/ui-slots"
|
||||
},
|
||||
{
|
||||
"path": "../../client/runtime"
|
||||
},
|
||||
{
|
||||
"path": "../../client/ui-workspace"
|
||||
}
|
||||
]
|
||||
}
|
||||
3
packages/host/directory-picker-native/tsdown.config.ts
Normal file
3
packages/host/directory-picker-native/tsdown.config.ts
Normal file
@@ -0,0 +1,3 @@
|
||||
import { clientBundle } from '../../client/tsdown.client.ts'
|
||||
|
||||
export default clientBundle('@deepseek-ai/dsh-host-directory-picker-native', ['lib/types/index.js', 'lib/types/invariant.js'])
|
||||
6
packages/host/directory-picker/README.i18n.yaml
Normal file
6
packages/host/directory-picker/README.i18n.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# 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/README.md
|
||||
README.md: 8ef8889c875f5b1d07c015ddef819591041c8d7f
|
||||
README.zh.md: 8aefffa7b29a47205ea42d0d1df742d1e1b2502d
|
||||
19
packages/host/directory-picker/README.md
Normal file
19
packages/host/directory-picker/README.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# @deepseek-ai/dsh-host-directory-picker
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
The **workspace-directory picking seam** for the web-GUI host: an abstract `DirectoryPicker` service (`ctx.directoryPicker`) whose single contract method `capability()` returns a discriminated capability describing how an operator selects a directory. Backends differ in interaction shape, not just mechanism, so the seam models the shapes explicitly instead of one method set: `{ kind: 'native', pick(signal) }` opens one native OS chooser on the host display ([`-native`](../directory-picker-native/README.md)); `{ kind: 'browse', list(path?), createDirectory(path, name) }` serves listing/creation primitives an in-app browser drives, which works for remote clients no OS chooser can reach ([`-browse`](../directory-picker-browse/README.md)). Consumers switch on `capability().kind`; the union derives from the merge-extensible `DirectoryPickerCapabilities` map (a new backend declaration-merges its shape there), and the documented default for an unknown kind is to hide the picking affordance rather than fail. The capability object must be stable for the service lifetime. The client side mirrors the seam without a wire advertisement: each backend package is dual-face, its browser half registering the matching picking interaction into ui-workspace's directory-flow slots — so one composition row swaps both the host capability and the client flow together.
|
||||
|
||||
Browse primitives fail with the typed `DirectoryPickerError` (`directory-unreadable` / `directory-exists` / `directory-create-failed`, each carrying the subject `path`), which the consuming gateway maps 1:1 onto wire error codes. `DirectoryEntry` rows carry a host-owned `hidden` flag (POSIX dot convention) so display policy stays client-side; `DirectoryListing.crumbs` is the ancestor chain from the filesystem root, every crumb a jump target. Design rationale, the `ctx.fs` separation, and the policy decisions live in [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md).
|
||||
|
||||
## Model Experience
|
||||
|
||||
None, as the seam serves the GUI host's directory selection; nothing here reaches a model request.
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
None; this package neither assembles nor sends a provider request.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
- **No multi-root vocabulary** — the browse contract exposes one ancestry chain per listing; per-deployment root scoping (and Windows drive-root enumeration above a drive) waits for a consumer that needs it, per the seam Agent Note.
|
||||
19
packages/host/directory-picker/README.zh.md
Normal file
19
packages/host/directory-picker/README.zh.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# @deepseek-ai/dsh-host-directory-picker
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
web GUI 宿主的**工作区目录选择 seam**:抽象服务 `DirectoryPicker`(`ctx.directoryPicker`),唯一契约方法 `capability()` 返回一个可辨识能力对象,描述操作者以何种方式选择目录。后端之间的差异在交互形态而不只是机制,因此 seam 显式建模形态而非统一方法集:`{ kind: 'native', pick(signal) }` 在宿主屏幕上打开一个原生 OS 选择器([`-native`](../directory-picker-native/README.md));`{ kind: 'browse', list(path?), createDirectory(path, name) }` 提供应用内浏览器驱动的列举/创建原语,可服务任何 OS 对话框都触及不到的远程客户端([`-browse`](../directory-picker-browse/README.md))。消费方按 `capability().kind` 分支;联合类型由可合并扩展的 `DirectoryPickerCapabilities` 映射派生(新后端在其中声明合并自己的形态),未知 kind 的文档化默认行为是隐藏选择入口而非失败。能力对象在服务生命周期内必须保持稳定。client 侧以镜像方式承接该 seam 而不经 wire 广播:每个后端包都是双面包,其 browser half 把匹配的选取交互注册进 ui-workspace 的目录流 slot——因此一行组合同时切换宿主能力与 client 流程。
|
||||
|
||||
浏览原语以带类型的 `DirectoryPickerError` 失败(`directory-unreadable`/`directory-exists`/`directory-create-failed`,各自携带主体 `path`),消费网关将其 1:1 映射为协议错误码。`DirectoryEntry` 行携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示策略留在客户端;`DirectoryListing.crumbs` 是从文件系统根开始的祖先链,每个 crumb 都是跳转目标。设计依据、与 `ctx.fs` 的切分、策略裁决见[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。
|
||||
|
||||
## 模型体验
|
||||
|
||||
无。该 seam 服务于 GUI 宿主的目录选择;这里没有任何内容进入模型请求。
|
||||
|
||||
#### KV 缓存影响
|
||||
|
||||
无;该包既不组装也不发送提供方请求。
|
||||
|
||||
## 已知限制与延期工作
|
||||
|
||||
- **没有多根词汇**——浏览契约每次列举只暴露一条祖先链;按部署限定可浏览根(以及 Windows 盘符之上的根枚举)等到出现需要它的消费方再做,见 seam Agent Note。
|
||||
37
packages/host/directory-picker/package.json
Normal file
37
packages/host/directory-picker/package.json
Normal file
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@deepseek-ai/dsh-host-directory-picker",
|
||||
"description": "Abstract workspace-directory picking seam (ctx.directoryPicker) for the DeepSeek Harness web GUI host",
|
||||
"version": "0.0.1",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"main": "lib/index.js",
|
||||
"types": "lib/types/index.d.ts",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./lib/types/index.d.ts",
|
||||
"default": "./lib/index.js"
|
||||
},
|
||||
"./invariant": {
|
||||
"types": "./lib/types/invariant.d.ts",
|
||||
"default": "./lib/invariant.js"
|
||||
},
|
||||
"./src/*": "./src/*",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"lib/index.js",
|
||||
"lib/invariant.js",
|
||||
"lib/types/**/*.d.ts",
|
||||
"lib/types/**/*.d.ts.map",
|
||||
"src"
|
||||
],
|
||||
"license": "BSD-3-Clause",
|
||||
"peerDependencies": {
|
||||
"@deepseek-ai/dsh-invariants": "^0.0.1",
|
||||
"cordis": "^4.0.0-rc.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/dsh-invariants": "workspace:^",
|
||||
"cordis": "^4.0.0-rc.7"
|
||||
}
|
||||
}
|
||||
143
packages/host/directory-picker/src/index.ts
Normal file
143
packages/host/directory-picker/src/index.ts
Normal file
@@ -0,0 +1,143 @@
|
||||
/**
|
||||
* The `ctx.directoryPicker` seam: how the web-GUI host lets an operator
|
||||
* select a workspace directory. Backends differ in interaction shape, not
|
||||
* just mechanism, so the service exposes a discriminated capability instead
|
||||
* of one method set: a `native` backend opens one OS chooser on the
|
||||
* host's display, while a `browse` backend serves listing/creation primitives
|
||||
* for an in-app browser (and thereby works for remote clients no OS dialog
|
||||
* can reach). Consumers switch on `capability().kind`; the union is
|
||||
* merge-extensible, and the documented default for an unknown kind is to
|
||||
* hide the picking affordance rather than fail.
|
||||
* @module @deepseek-ai/dsh-host-directory-picker
|
||||
*/
|
||||
|
||||
import { Context, Service } from 'cordis'
|
||||
|
||||
/** The native interaction: one OS directory chooser on the host display. */
|
||||
export interface DirectoryPickerNativeCapability {
|
||||
kind: 'native'
|
||||
/**
|
||||
* Open the chooser and wait for the operator.
|
||||
* @param signal - caller/connection lifetime; abort terminates the chooser.
|
||||
* @returns the chosen absolute path, or null when the operator cancels.
|
||||
*/
|
||||
pick(signal: AbortSignal): Promise<string | null>
|
||||
}
|
||||
|
||||
/** One directory row: a listing child or a breadcrumb ancestor. */
|
||||
export interface DirectoryEntry {
|
||||
/** Base name shown in a browser row (a root crumb carries its full path). */
|
||||
name: string
|
||||
/** Absolute host path — clients never join path segments themselves. */
|
||||
path: string
|
||||
/** Hidden by the host platform's convention (dot-prefixed on POSIX); the client owns whether to show it. */
|
||||
hidden: boolean
|
||||
}
|
||||
|
||||
/** One directory level plus its ancestry, as a browse backend reports it. */
|
||||
export interface DirectoryListing {
|
||||
/** Absolute path of the listed directory. */
|
||||
path: string
|
||||
/** The host account's home directory (breadcrumb "Home" rooting). */
|
||||
home: string
|
||||
/**
|
||||
* Ancestor chain from the filesystem root to the listed directory
|
||||
* inclusive; every crumb is a jump target (crumb `hidden` is always false).
|
||||
*/
|
||||
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
|
||||
}
|
||||
|
||||
/**
|
||||
* The browse interaction: listing/creation primitives an in-app browser
|
||||
* drives one level at a time. Works for remote clients — nothing renders on
|
||||
* the host display.
|
||||
*/
|
||||
export interface DirectoryPickerBrowseCapability {
|
||||
kind: 'browse'
|
||||
/**
|
||||
* List one directory level.
|
||||
* @param path - absolute directory to list; absent lists the home directory.
|
||||
* @param signal - caller lifetime; abort stops the scan (a stalled network
|
||||
* directory must not outlive a disconnected caller) and rejects with the
|
||||
* abort reason.
|
||||
* @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.
|
||||
*/
|
||||
list(path?: string, signal?: AbortSignal): Promise<DirectoryListing>
|
||||
/**
|
||||
* Create one child directory under an existing parent.
|
||||
* @param path - absolute existing parent directory.
|
||||
* @param name - single non-blank path segment (no separators, not `.`/`..`).
|
||||
* @returns the created directory's absolute path.
|
||||
* @throws {DirectoryPickerError} `directory-exists` for an existing child,
|
||||
* `directory-create-failed` for a parent that is not fully qualified or any other failure.
|
||||
*/
|
||||
createDirectory(path: string, name: string): Promise<string>
|
||||
}
|
||||
|
||||
/**
|
||||
* Merge-extensible registry of interaction shapes keyed by capability kind: a
|
||||
* new backend declaration-merges its shape here (the entry's `kind` literal
|
||||
* must equal its key) instead of editing this package.
|
||||
*/
|
||||
export interface DirectoryPickerCapabilities {
|
||||
native: DirectoryPickerNativeCapability
|
||||
browse: DirectoryPickerBrowseCapability
|
||||
}
|
||||
|
||||
/** Union of interaction shapes a backend can provide, derived from the merge-extensible {@link DirectoryPickerCapabilities} map. */
|
||||
export type DirectoryPickerCapability = DirectoryPickerCapabilities[keyof DirectoryPickerCapabilities]
|
||||
|
||||
/** Closed failure vocabulary of the browse primitives (mirrored onto the wire by consumers). */
|
||||
export type DirectoryPickerErrorCode = 'directory-unreadable' | 'directory-exists' | 'directory-create-failed'
|
||||
|
||||
/** Typed failure thrown by browse primitives so consumers can map business codes without string matching. */
|
||||
export class DirectoryPickerError extends Error {
|
||||
/**
|
||||
* @param code - closed business code of the failure.
|
||||
* @param path - the absolute path the failure is about.
|
||||
* @param message - operator-facing description.
|
||||
*/
|
||||
constructor(readonly code: DirectoryPickerErrorCode, readonly path: string, message: string) {
|
||||
super(message)
|
||||
this.name = 'DirectoryPickerError'
|
||||
}
|
||||
}
|
||||
|
||||
declare module 'cordis' {
|
||||
interface Context {
|
||||
directoryPicker: DirectoryPicker
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Abstract directory-picking service. Subclass, implement `capability()`, and
|
||||
* load the subclass as a plugin — it registers as `ctx.directoryPicker` (one
|
||||
* implementation per context; loading a second throws, cordis' standard
|
||||
* duplicate-service behavior). The capability object must be stable for the
|
||||
* service lifetime: consumers may capture it across calls.
|
||||
*/
|
||||
export abstract class DirectoryPicker extends Service {
|
||||
constructor(ctx: Context) {
|
||||
super(ctx, 'directoryPicker')
|
||||
}
|
||||
|
||||
/**
|
||||
* The backend's interaction capability.
|
||||
* @returns the discriminated capability consumers switch on.
|
||||
*/
|
||||
abstract capability(): DirectoryPickerCapability
|
||||
}
|
||||
|
||||
export default DirectoryPicker
|
||||
22
packages/host/directory-picker/src/invariant.ts
Normal file
22
packages/host/directory-picker/src/invariant.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
/** Package-owned invariant companion for the directory-picker seam. @module @deepseek-ai/dsh-host-directory-picker/invariant */
|
||||
|
||||
import type { Context } from 'cordis'
|
||||
import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants'
|
||||
|
||||
const PACKAGE_NAME = '@deepseek-ai/dsh-host-directory-picker'
|
||||
|
||||
/** Cordis companion plugin name. */
|
||||
export const name = 'host-directory-picker-invariant'
|
||||
/** Service required before the companion can reserve package ownership. */
|
||||
export const inject = ['invariants']
|
||||
|
||||
/** No runtime invariant: this stateless seam owns the capability vocabulary, while backends and the RPC consumer own observations. */
|
||||
const install: InvariantInstaller = () => {}
|
||||
|
||||
/**
|
||||
* Register the directory-picker invariant companion.
|
||||
* @param ctx - Cordis context carrying the invariant service.
|
||||
* @returns the installed registration's disposer after setup succeeds.
|
||||
*/
|
||||
export const apply = (ctx: Context): Promise<() => void> =>
|
||||
Promise.resolve(ctx.invariants.register(PACKAGE_NAME, install))
|
||||
35
packages/host/directory-picker/tests/seam.spec.ts
Normal file
35
packages/host/directory-picker/tests/seam.spec.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
/** Contract behavior the seam itself owns: registration identity and typed failures. */
|
||||
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { Context } from 'cordis'
|
||||
import { DirectoryPicker, DirectoryPickerError } from '../src/index.ts'
|
||||
import type { DirectoryPickerCapability } from '../src/index.ts'
|
||||
|
||||
/** Minimal concrete backend: all a subclass owes the abstract class is capability(). */
|
||||
class StubPicker extends DirectoryPicker {
|
||||
private readonly stub: DirectoryPickerCapability = { kind: 'native', pick: async () => null }
|
||||
capability(): DirectoryPickerCapability {
|
||||
return this.stub
|
||||
}
|
||||
}
|
||||
|
||||
describe('DirectoryPicker seam', () => {
|
||||
it('registers a subclass as ctx.directoryPicker and leaves with its fiber', async () => {
|
||||
const ctx = new Context()
|
||||
const fiber = ctx.plugin(StubPicker)
|
||||
await fiber.await()
|
||||
expect(ctx.get('directoryPicker')).toBeInstanceOf(StubPicker)
|
||||
expect(ctx.get('directoryPicker')!.capability().kind).toBe('native')
|
||||
await fiber.dispose()
|
||||
expect(ctx.get('directoryPicker')).toBeUndefined()
|
||||
})
|
||||
|
||||
it('carries the business code and subject path on DirectoryPickerError', () => {
|
||||
const failure = new DirectoryPickerError('directory-exists', '/home/u/x', '/home/u/x already exists')
|
||||
expect(failure.name).toBe('DirectoryPickerError')
|
||||
expect(failure.code).toBe('directory-exists')
|
||||
expect(failure.path).toBe('/home/u/x')
|
||||
expect(failure.message).toContain('already exists')
|
||||
expect(failure).toBeInstanceOf(Error)
|
||||
})
|
||||
})
|
||||
21
packages/host/directory-picker/tsconfig.json
Normal file
21
packages/host/directory-picker/tsconfig.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"extends": "../../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"rootDir": "src",
|
||||
"outDir": "lib/types"
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"references": [
|
||||
{
|
||||
"path": "../../../vendor/cosmokit"
|
||||
},
|
||||
{
|
||||
"path": "../../../vendor/cordis"
|
||||
},
|
||||
{
|
||||
"path": "../../support/invariants"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
|
||||
# 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
|
||||
README.md: c589c32c4e641e188f19ac6c5ad2e88e3eb79be3
|
||||
README.zh.md: 767195086b90a76160d87865caebf514ca75b0e3
|
||||
# pnpm run verify-translation-pairing --write packages/host/webserver/README.md
|
||||
README.md: e715e4452ddb808f36e6b097eee0fda7b8d0bfb0
|
||||
README.zh.md: 05e7e10d7815c8f26bb90597b38b7c6b83a86dbc
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
English | [中文](README.zh.md)
|
||||
|
||||
Plain HTTP route-registration plugin (default-exported `WebServerService`, config `{host, port, distIndex}`): a `node:http` server that listens on activation and provides `ctx.webServer` — `register(route)` adds a named `exact`/`prefix` route (duplicate `(kind, path)` throws: route patterns are a composition-level contract, so a collision is a misconfiguration; the returned disposer removes the route), `tapIndex(transform)` adds an index.html transform applied in registration order, and `port` reads the listening port (the OS-assigned value when `port` is 0). The match order is fixed — exact over the whole table, then longest prefix, then the static dist fallback with the locked semantics: traversal outside the dist root is 403, any miss falls back to `index.html` with HTTP 200 (SPA routing), unknown extensions ship as octet-stream, non-GET/HEAD is 405. Registration order carries no request-facing semantics.
|
||||
Plain HTTP route-registration plugin (default-exported `HttpServerService`, config `{host, port, distIndex}`): a `node:http` server that listens on activation and provides `ctx.httpServer` — `register(route)` adds a named `exact`/`prefix` route (duplicate `(kind, path)` throws: route patterns are a composition-level contract, so a collision is a misconfiguration; the returned disposer removes the route), `tapIndex(transform)` adds an index.html transform applied in registration order, and `port` reads the listening port (the OS-assigned value when `port` is 0). The match order is fixed — exact over the whole table, then longest prefix, then the static dist fallback with the locked semantics: traversal outside the dist root is 403, any miss falls back to `index.html` with HTTP 200 (SPA routing), unknown extensions ship as octet-stream, non-GET/HEAD is 405. Registration order carries no request-facing semantics.
|
||||
|
||||
The package knows no harness concepts: the `/api` bridge is the connection plugin's route, plugin bundles and the HMR event stream are the modules/hmr plugins' routes. `host` accepts only `127.0.0.1` (default posture) and `0.0.0.0` (deliberate network exposure); `distIndex` is an assembly fact the composing app resolves and injects, never self-resolved (dist location is workspace knowledge of the app). Web (browser) shape only — Electron loads dist over `file://` and carries fetch over an IPC bridge, not this server. This package never prints; the URL line belongs to the shell.
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
朴素的 HTTP 路由注册插件(默认导出 `WebServerService`,配置为 `{host, port, distIndex}`):一个在激活时开始监听的 `node:http` 服务器,提供 `ctx.webServer`。`register(route)` 添加具名的 `exact`/`prefix` 路由;重复的 `(kind, path)` 会抛错,因为路由模式是组合层契约,冲突即配置错误;返回的 disposer 会移除该路由。`tapIndex(transform)` 添加按注册顺序应用的 index.html 转换,`port` 读取正在监听的端口(当 `port` 为 0 时读取 OS 分配的值)。匹配顺序固定不变:先在整张表中匹配精确路由,再匹配最长前缀,最后回退到静态 dist,并遵循固定语义:越出 dist 根目录的遍历返回 403,任何未命中项都以 HTTP 200 回退到 `index.html`(SPA 路由),未知扩展名按 octet-stream 提供,GET/HEAD 之外的方法返回 405。注册顺序不承载任何面向请求的语义。
|
||||
朴素的 HTTP 路由注册插件(默认导出 `HttpServerService`,配置为 `{host, port, distIndex}`):一个在激活时开始监听的 `node:http` 服务器,提供 `ctx.httpServer`。`register(route)` 添加具名的 `exact`/`prefix` 路由;重复的 `(kind, path)` 会抛错,因为路由模式是组合层契约,冲突即配置错误;返回的 disposer 会移除该路由。`tapIndex(transform)` 添加按注册顺序应用的 index.html 转换,`port` 读取正在监听的端口(当 `port` 为 0 时读取 OS 分配的值)。匹配顺序固定不变:先在整张表中匹配精确路由,再匹配最长前缀,最后回退到静态 dist,并遵循固定语义:越出 dist 根目录的遍历返回 403,任何未命中项都以 HTTP 200 回退到 `index.html`(SPA 路由),未知扩展名按 octet-stream 提供,GET/HEAD 之外的方法返回 405。注册顺序不承载任何面向请求的语义。
|
||||
|
||||
该包不了解任何 harness 概念:`/api` 桥接是 connection 插件的路由,插件 bundle 与 HMR(热模块替换)事件流则是 modules/hmr 插件的路由。`host` 只接受 `127.0.0.1`(默认姿态)和 `0.0.0.0`(有意向网络开放);`distIndex` 是由组合应用解析并注入的组装事实,绝不会自行解析,因为 dist 位置属于应用的工作区知识。该服务器只服务 Web(浏览器)形态;Electron 通过 `file://` 加载 dist,并经 IPC 桥接承载 fetch,而不使用本服务器。该包从不打印内容;URL 行属于 shell。
|
||||
|
||||
|
||||
Reference in New Issue
Block a user