From f0410d592d1b32f810437cd82d93b96a2581ae71 Mon Sep 17 00:00:00 2001 From: Turtle Date: Fri, 24 Jul 2026 13:39:00 +0800 Subject: [PATCH 01/93] feat(web): permission presets and approval answering for the web UI MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The web host now composes the sandboxed product path (sandbox-local + sandbox-policy behind bash-sandbox/fs-sandbox, with user-approval and permission on top); BootHostOptions.sandbox carries the deployment defaults (workspace-write + ask). createApiProxy owns the approval pending registry: a ctx.approval ask becomes an answerable approval/requested mux frame with a stable rpcId, replayed verbatim on every mux open until settled; respond routes by the echoed rpcId, validates the ApprovalResponsePayload audit correlation, and broadcasts approval/resolved; the ask's abort signal withdraws the question as cancelled. session.permissions / session.setPermission project ctx.permission into a protocol-owned PermissionOption select; idle switches are held last-write-wins and flushed into the next prompted turn (the ACP bridge's anchoring pattern). The shared hasOpenTurn fold moved to dsh-session, deduplicating the private copies in user-approval, the ACP bridge, and the proxy. Client, per the designer draft: a pending approval takes over the composer (ApprovalPanel replaces the InputBar — amber strip, justification headline, paired command, one-shot refuse/allow, keyed by rpcId so a queued second approval remounts live; the resolved frame restores the composer); the sidebar session row shows an amber waiting-approval dot that outranks the running ring (manager-tracked approvalId set, idempotent under mux-open replays, cleared per connection generation, lit for uninstantiated sessions too); the permission selector is a composer bottom-row chip over an invisible native select, with a presentation-only title-case transform (workspace-write renders as Workspace Write; wire names untouched). Question placeholders stay in the message flow. The connection fixture mirrors the host behavior for keyless browser acceptance. --- ...7-23-web-permission-and-approval.i18n.yaml | 6 + .../2026-07-23-web-permission-and-approval.md | 33 +++ ...26-07-23-web-permission-and-approval.zh.md | 33 +++ apps/web/tests/smoke-fixture.e2e.ts | 38 ++- docs/config-catalog.md | 2 +- docs/cordis-catalog/events.md | 10 +- docs/cordis-catalog/services.md | 4 +- docs/event-producer-consumer.md | 12 +- docs/persistence-catalog.md | 6 +- packages/client/connection/src/client/api.ts | 2 +- .../client/connection/src/client/fixture.ts | 62 +++- .../client/connection/src/client/index.ts | 2 +- packages/client/connection/tests/fake-api.ts | 8 + .../client/connection/tests/fixture.spec.ts | 57 ++++ packages/client/runtime/src/client/index.ts | 10 +- .../runtime/src/client/sessions/lineage.ts | 9 +- .../runtime/src/client/sessions/manager.ts | 31 +- .../runtime/src/client/sessions/service.ts | 3 + .../runtime/src/client/sessions/session.ts | 25 ++ packages/client/runtime/tests/fake-api.ts | 9 + packages/client/runtime/tests/manager.spec.ts | 39 +++ packages/client/runtime/tests/session.spec.ts | 24 ++ packages/client/ui-conversation/README.md | 5 +- .../ui-conversation/src/client/apply.ts | 29 +- .../src/client/chat/ChatView.tsx | 4 +- .../src/client/chat/PendingCard.module.css | 18 +- .../src/client/chat/PendingCard.tsx | 23 +- .../src/client/contract/slots.ts | 68 ++++- .../client/skeleton/ApprovalPanel.module.css | 107 +++++++ .../src/client/skeleton/ApprovalPanel.tsx | 71 +++++ .../src/client/skeleton/ConversationRoot.tsx | 4 +- .../src/client/skeleton/InputBar.tsx | 7 +- .../skeleton/PermissionSelect.module.css | 49 ++++ .../src/client/skeleton/PermissionSelect.tsx | 88 ++++++ .../tests/apply-inject.spec.tsx | 30 ++ .../tests/chat-branch-tails.spec.tsx | 6 +- .../tests/chat-stats-bash-sample.spec.tsx | 6 +- .../tests/chat-toolview-slot.spec.tsx | 9 +- .../ui-conversation/tests/chat-view.spec.tsx | 13 +- .../tests/skeleton-branches.spec.tsx | 4 + .../ui-conversation/tests/skeleton.spec.tsx | 2 + packages/client/ui-sidebar/README.md | 2 +- .../client/ui-sidebar/src/client/Rows.tsx | 6 +- packages/client/ui-sidebar/src/client/tree.ts | 3 + .../client/ui-sidebar/tests/apply.spec.tsx | 2 +- .../ui-sidebar/tests/sidebar-root.spec.tsx | 15 + packages/client/ui-sidebar/tests/tree.spec.ts | 2 + .../client/ui-trajectory/tests/views.spec.tsx | 2 + packages/core/session/src/index.ts | 19 ++ packages/core/session/tests/session.spec.ts | 12 + packages/host/apiproxy/README.md | 2 +- packages/host/apiproxy/src/api/index.ts | 2 +- packages/host/apiproxy/src/api/rpc-map.ts | 2 + .../host/apiproxy/src/api/sessions.schema.ts | 31 +- packages/host/apiproxy/src/api/sessions.ts | 35 +++ packages/host/apiproxy/src/fetch/client.ts | 8 + packages/host/apiproxy/src/fetch/handler.ts | 4 + .../apiproxy/tests/client-handler.spec.ts | 2 + .../host/apiproxy/tests/fetch-carrier.spec.ts | 10 +- packages/host/runtime/README.md | 8 +- packages/host/runtime/package.json | 9 +- packages/host/runtime/src/api-proxy.ts | 195 ++++++++++++- packages/host/runtime/src/boot.ts | 41 ++- .../runtime/tests/api-proxy-approval.spec.ts | 275 ++++++++++++++++++ .../tests/api-proxy-permission.spec.ts | 152 ++++++++++ packages/host/runtime/tsconfig.json | 19 +- packages/ui/acp/src/index.ts | 15 +- packages/ui/user-approval/src/index.ts | 17 +- pnpm-lock.yaml | 25 +- 69 files changed, 1744 insertions(+), 139 deletions(-) create mode 100644 .agents/notes/implemented/feature/2026-07-23-web-permission-and-approval.i18n.yaml create mode 100644 .agents/notes/implemented/feature/2026-07-23-web-permission-and-approval.md create mode 100644 .agents/notes/implemented/feature/2026-07-23-web-permission-and-approval.zh.md create mode 100644 packages/client/ui-conversation/src/client/skeleton/ApprovalPanel.module.css create mode 100644 packages/client/ui-conversation/src/client/skeleton/ApprovalPanel.tsx create mode 100644 packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css create mode 100644 packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx create mode 100644 packages/host/runtime/tests/api-proxy-approval.spec.ts create mode 100644 packages/host/runtime/tests/api-proxy-permission.spec.ts diff --git a/.agents/notes/implemented/feature/2026-07-23-web-permission-and-approval.i18n.yaml b/.agents/notes/implemented/feature/2026-07-23-web-permission-and-approval.i18n.yaml new file mode 100644 index 0000000000..4d686731fe --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-23-web-permission-and-approval.i18n.yaml @@ -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 +2026-07-23-web-permission-and-approval.md: cd402a039e55e7a24a038055dab5793aa0d08438 +2026-07-23-web-permission-and-approval.zh.md: ce4964789bc94a0962796bb2f5fbf1a94e8f5145 diff --git a/.agents/notes/implemented/feature/2026-07-23-web-permission-and-approval.md b/.agents/notes/implemented/feature/2026-07-23-web-permission-and-approval.md new file mode 100644 index 0000000000..cd402a039e --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-23-web-permission-and-approval.md @@ -0,0 +1,33 @@ +# Agent Note: Web UI permission presets and approval answering + +Status: implemented + +English | [中文](2026-07-23-web-permission-and-approval.zh.md) + +## Problem + +The web host booted an unconfined agent: `bootHost` composed `dsh-bash-local` and `dsh-fs-local`, so every web session ran with full file access, no approval channel, and no permission control — while the ACP composition had shipped the complete sandboxed product path (sandbox provider + policy home + confined bash/fs + approval + presets) for months. The web wire contract had already reserved the seats — `approval/requested`/`approval/resolved` mux frames, `POST /api/respond` with `ApprovalResponsePayload`, client-side `pendingBuffers` — but the host `respond` was a stub, no answerer bridged `ctx.approval` to the stream, no RPC exposed the permission select, and the PendingCard rendered approvals as visible-but-unanswerable. + +## Decision + +The web host composes the same sandboxed product path as the acp-agent composition: `dsh-sandbox-local`, `dsh-sandbox-policy`, `dsh-bash-sandbox`, `dsh-fs-sandbox`, `dsh-user-approval`, and `dsh-permission`, with `BootHostOptions.sandbox` supplying the deployment defaults (`mode`, default `workspace-write`; `approvalPolicy`, default `ask`). + +`createApiProxy` owns the approval pending registry. Its `approval/request` waterfall answerer reads the approval id from the session's just-appended `approval/asked` audit event (an ask with no audit event is a foreign channel and delegates), mints one stable rpcId per question, broadcasts the answerable `approval/requested` frame to every open mux stream, and replays still-pending frames verbatim on each mux open — the refresh-recovery baseline the contract already promised. `respond` routes by the echoed rpcId, validates `ApprovalResponsePayload` with the existing zod schema, cross-checks the payload's audit correlation against the routed entry, resolves the answerer, and broadcasts `approval/resolved`; the ask's abort signal withdraws the question as `cancelled`. + +The permission select rides two new unary RPCs, `session.permissions` and `session.setPermission`, projecting `ctx.permission` into a protocol-owned `PermissionOption` DTO (the ACP bridge precedent: each protocol owns its presentation shape). A permission-less composition serves an empty select and clients hide the control. Idle switches are held last-write-wins in a proxy-side pending map and flushed on `agent/prompt-submit`, because knob events must stay turn-enclosed for durable replay; the shared `hasOpenTurn` fold moved to `dsh-session` and replaced the private copies in `dsh-user-approval`, the ACP bridge, and the proxy. + +Client-side, `Session` gained `permissions` and `setPermission`, and approval answering rides the runtime's `PendingWait` carrier. Per the designer draft, a pending approval takes over the composer: `ApprovalPanel` registers as a selector-routed entry of the conversation-declared `conversation.composer` chain (the ui-question pattern), replacing the InputBar with the justification headline, the paired command, and one-shot refuse/allow buttons; the `PendingApproval` domain face in ui-conversation's contract owns the `ApprovalResponsePayload` wire encoding over the carrier, and the broadcast resolved frame settles the wait and restores the composer. Question placeholders stay in the message flow. The sidebar mirrors the blocked state with an amber warning dot that outranks the running ring: the manager tracks per-session outstanding approvalIds (idempotent under mux-open replays, cleared per connection generation so the reopen replay is authoritative) rather than reading Session instances, so the dot lights for sessions never instantiated. The composer's bottom-row chip hosts the `PermissionSelect` control fed through the conversation inject face. The connection fixture mirrors the host: its resident approval is answerable once, and its permission select persists per session. + +## Alternatives considered + +**Reuse the ACP `session/set_config_option` shape on the web wire.** Rejected: the web contract's unary method registry (`RpcMethodMap` + per-method zod schemas) is its own dialect; a generic config-option surface would bypass the compiler-locked schema table for one select. A dedicated method pair keeps both sides derivable from the signature. + +**A session event for pending approvals instead of a proxy-side registry.** Rejected: approval requests are transient interaction state, not durable session data — the `approval/asked`/`decided` audit pair already logs the durable half. Persisting requested frames would re-ask dead questions on replay. + +**Registering the answerer only when a mux subscriber exists.** Rejected: the pending entry must survive client disconnects (refresh recovery is the point), so the registry outlives any one stream; a subscriber-gated answerer would fail asks closed during a reload window. + +**Optimistic card removal on click.** Rejected: the broadcast resolved frame is the truth; removing on click would hide a question that a rejected receipt or transport failure left standing. The panel disables its buttons locally and re-arms them on failure instead. + +## Consequences + +Web sessions now start confined (`workspace-write` + `ask` by default) and a sandbox-denial escalation reaches the browser as an answerable card; the deployment can widen or narrow the default through `BootHostOptions.sandbox` without touching the assembly. Question answering shipped separately through the same registry pattern (ui-question over the question pending table). The permission select reads once per mount; live refresh from another client's switch is deferred. Coverage: proxy registry and permission RPC unit suites, session-object and fixture unit suites, and the keyless web smoke exercises the fixture-mode approval answer and preset switch in a real browser. diff --git a/.agents/notes/implemented/feature/2026-07-23-web-permission-and-approval.zh.md b/.agents/notes/implemented/feature/2026-07-23-web-permission-and-approval.zh.md new file mode 100644 index 0000000000..ce4964789b --- /dev/null +++ b/.agents/notes/implemented/feature/2026-07-23-web-permission-and-approval.zh.md @@ -0,0 +1,33 @@ +# Agent Note: Web UI 权限预设与审批应答 + +Status: implemented + +[English](2026-07-23-web-permission-and-approval.md) | 中文 + +## 问题 + +Web 承载层启动的是一个不受限的 agent(智能体):`bootHost` 组合了 `dsh-bash-local` 与 `dsh-fs-local`,因此每个 Web 会话都以完整文件访问权限运行,既无审批通道,也无权限管控——而 ACP 组合早在数月前就已交付完整的沙箱化产品路径(沙箱提供方 + 策略归属 + 受限的 bash/fs + 审批 + 预设)。Web 协议契约其实早已预留了对应位置——`approval/requested`/`approval/resolved` 的 mux 帧、携带 `ApprovalResponsePayload` 的 `POST /api/respond`、client 侧的 `pendingBuffers`——但 host 的 `respond` 只是一个 stub,没有应答者把 `ctx.approval` 桥接到流上,没有 RPC 暴露权限选择,PendingCard 把审批渲染成可见却无法应答的样子。 + +## 决策 + +Web 承载层组合与 acp-agent 相同的沙箱化产品路径:`dsh-sandbox-local`、`dsh-sandbox-policy`、`dsh-bash-sandbox`、`dsh-fs-sandbox`、`dsh-user-approval` 与 `dsh-permission`,由 `BootHostOptions.sandbox` 提供部署默认值(`mode`,默认 `workspace-write`;`approvalPolicy`,默认 `ask`)。 + +`createApiProxy` 拥有审批 pending 注册表。它的 `approval/request` waterfall(瀑布式事件)应答者从会话刚追加的 `approval/asked` 审计事件中读取审批 id(没有审计事件的 ask 属于外部通道,予以委托),为每个问题 mint 一个稳定的 rpcId,向每个打开的 mux 流广播可应答的 `approval/requested` 帧,并在每次 mux 打开时原样重放仍处于 pending 的帧——这正是契约早已承诺的刷新恢复基线。`respond` 按回显的 rpcId 路由,用既有的 zod schema 校验 `ApprovalResponsePayload`,将载荷的审计关联与所路由的条目交叉核对,解析应答者,并广播 `approval/resolved`;ask 的中断信号会以 `cancelled` 撤回该问题。 + +权限选择依托两个新的一元 RPC,`session.permissions` 与 `session.setPermission`,把 `ctx.permission` 投影为一个由协议拥有的 `PermissionOption` DTO(沿用 ACP bridge 的先例:每个协议拥有自己的呈现形状)。无权限的组合提供空的选择项,client 隐藏该控件。空闲期的切换以后写胜出(last-write-wins)的方式保存在 proxy 侧的 pending map 中,并在 `agent/prompt-submit` 时冲刷,因为旋钮事件必须保持轮次内闭合以支持持久回放;共享的 `hasOpenTurn` 折叠迁入 `dsh-session`,取代了 `dsh-user-approval`、ACP bridge 与 proxy 中各自的私有副本。 + +在 client 侧,`Session` 新增了 `permissions` 与 `setPermission`,审批应答则依托运行时的 `PendingWait` 载体。按照设计师草稿,处于 pending 的审批会接管 composer:`ApprovalPanel` 注册为由会话声明的 `conversation.composer` 链中一个按选择器路由的条目(即 ui-question 模式),以理由标题、配对的命令与一次性的拒绝/允许按钮取代 InputBar;ui-conversation 契约中的 `PendingApproval` 领域面拥有 `ApprovalResponsePayload` 在该载体上的协议编码(wire encoding),广播的 resolved 帧使该等待落定并恢复 composer。问题占位符仍留在消息流中。侧边栏用一枚琥珀色警示圆点同步呈现这一阻塞状态,且其优先级高于表示运行中的圆环:manager 跟踪每个会话尚未解决的 approvalId(对 mux 打开时的回放幂等,并按连接代次清除,以保证重开后的回放才是权威依据),而非读取 Session 实例,因此从未实例化过的会话也能点亮该圆点。composer 底行的 chip 经会话注入面挂载 `PermissionSelect` 控件。连接 fixture(测试前置数据)与 host 保持一致:它的常驻审批可应答一次,其权限选择项按会话持久保存。 + +## 曾考虑的替代方案 + +**在 Web 协议上复用 ACP 的 `session/set_config_option` 形状。** 不予采纳:Web 契约的一元方法注册表(`RpcMethodMap` + 逐方法的 zod schema)是它自成一体的方言;一个通用的 config-option 接口会为一个选择项绕开编译期锁定的 schema 表。一对专用方法让两侧都能从签名推导得出。 + +**用一个会话事件承载 pending 审批,而非 proxy 侧注册表。** 不予采纳:审批请求是瞬态的交互状态,而非持久的会话数据——`approval/asked`/`decided` 审计对已经记录了持久的那一半。持久化 requested 帧会在回放时重新问出已经作废的问题。 + +**仅在存在 mux 订阅者时才注册应答者。** 不予采纳:pending 条目必须在 client 断连后依然存活(刷新恢复正是要点所在),因此注册表的生命周期长于任何单个流;一个受订阅者门控的应答者,会让在重载窗口期间关闭的 ask 落空。 + +**点击即乐观移除卡片。** 不予采纳:广播的 resolved 帧才是真相;点击即移除会隐藏一个因拒绝回执或传输失败而仍然悬置的问题。面板改为在本地禁用其按钮,并在失败时重新启用。 + +## 后果 + +Web 会话现在从受限状态启动(默认 `workspace-write` + `ask`),一次沙箱拒绝的升级会以可应答的卡片形式抵达浏览器;部署方可以通过 `BootHostOptions.sandbox` 放宽或收紧默认值,无需触动装配。问题应答已通过同一注册表模式单独交付(ui-question 基于问题 pending 表)。权限选择在每次挂载时读取一次;来自另一个 client 切换的实时刷新暂缓实现。覆盖情况:proxy 注册表与权限 RPC 的单元测试套件、会话对象与 fixture 的单元测试套件,以及无密钥 Web 冒烟测试在真实浏览器中演练 fixture 模式的审批应答与预设切换。 diff --git a/apps/web/tests/smoke-fixture.e2e.ts b/apps/web/tests/smoke-fixture.e2e.ts index 0726d14c8b..423e42f14d 100644 --- a/apps/web/tests/smoke-fixture.e2e.ts +++ b/apps/web/tests/smoke-fixture.e2e.ts @@ -280,9 +280,45 @@ describe('web boot chain success pass (keyless, nine real bundles, ?fixture)', ( await composer.getByRole('checkbox', { name: 'Agent 产品判断' }).press('Enter') await composer.waitFor({ state: 'detached' }) + // The composer does not fall back to the InputBar yet: fx-alpha's resident + // approval is still pending, so the approval takeover elects next (the + // approval scenario below answers it and watches the InputBar return). + await page.locator('[data-approval-key]').waitFor({ state: 'visible', timeout: 10_000 }) + }) + + it('answers the composer-takeover approval panel; the InputBar returns on the resolved frame', async () => { + onTestFailed(() => saveFailureShot(page, 'smoke-approval-answer')) + // fx-alpha carries the resident pending approval; the session is already + // selected by the previous scenario. With the question settled, the + // approval owns the composer slot — no textarea is mounted. + const panel = page.locator('[data-approval-key]') + await panel.waitFor({ state: 'visible', timeout: 10_000 }) + expect(await panel.getByText('等待审批').count()).toBe(1) + expect(await page.locator('textarea').count()).toBe(0) + // Sidebar mirrors the blocked state: the session row shows the amber + // warning dot in place of the running ring. + expect(await page.locator('[role="treeitem"] [data-state="warning"]').count()).toBeGreaterThan(0) + await panel.getByRole('button', { name: '允许一次' }).click() + // The broadcast resolved frame removes the panel and restores the + // composer; the sidebar dot clears with it. + await panel.waitFor({ state: 'detached', timeout: 5000 }) const restoredInput = page.locator('textarea[placeholder]') - await restoredInput.waitFor() + await restoredInput.waitFor({ state: 'visible', timeout: 5000 }) expect(await restoredInput.getAttribute('placeholder')).toBe('回复生成中,可停止后再输入') + await expect.poll(() => page.locator('[role="treeitem"] [data-state="warning"]').count(), { timeout: 5000 }).toBe(0) + }) + + it('switches the permission preset through the composer select', async () => { + onTestFailed(() => saveFailureShot(page, 'smoke-permission-select')) + const select = page.locator('select').filter({ hasText: 'Workspace Write' }).first() + await select.waitFor({ state: 'visible', timeout: 10_000 }) + expect(await select.inputValue()).toBe('workspace-write') + await select.selectOption('danger-full-access') + // The control disables during the round trip and adopts the confirmed + // value; host-side persistence across re-reads is covered by the fixture + // unit suite (fixture.spec.ts permissions/setPermission). + await expect.poll(() => select.inputValue(), { timeout: 5000 }).toBe('danger-full-access') + await expect.poll(() => select.isDisabled(), { timeout: 5000 }).toBe(false) }) it('stayed clean: no page errors across the whole load chain', () => { diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 49a0a1510f..75b9f56eed 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -1719,7 +1719,7 @@ export interface Config { export type ApprovalPolicy = 'ask' | 'never' ``` -Source: [`packages/ui/user-approval/src/index.ts:198`](../packages/ui/user-approval/src/index.ts) +Source: [`packages/ui/user-approval/src/index.ts:183`](../packages/ui/user-approval/src/index.ts) ## `@deepseek-ai/dsh-web` diff --git a/docs/cordis-catalog/events.md b/docs/cordis-catalog/events.md index 6becfd9434..1602ee6b1e 100644 --- a/docs/cordis-catalog/events.md +++ b/docs/cordis-catalog/events.md @@ -420,7 +420,7 @@ Ask composed answerers for one decision. Return an outcome to claim the request Types: [ApprovalOutcome](../core-data-structures/approval.md) · [ApprovalRequest](../core-data-structures/approval.md) · [ApprovalService](../core-data-structures/approval.md) · [Scoped](../core-data-structures/scope.md) -Source: [`packages/ui/user-approval/src/index.ts:30`](../../packages/ui/user-approval/src/index.ts) +Source: [`packages/ui/user-approval/src/index.ts:31`](../../packages/ui/user-approval/src/index.ts) ## `commands/*` @@ -572,7 +572,7 @@ Creation announcement during session publication. A synchronous throw vetoes and Types: [Scoped](../core-data-structures/scope.md) · [Session](../core-data-structures/session.md) -Source: [`packages/core/session/src/index.ts:79`](../../packages/core/session/src/index.ts) +Source: [`packages/core/session/src/index.ts:98`](../../packages/core/session/src/index.ts) ### `session/disposed` — emit @@ -593,7 +593,7 @@ Emitted once when an announced session leaves the store, including publication r Types: [Scoped](../core-data-structures/scope.md) · [Session](../core-data-structures/session.md) -Source: [`packages/core/session/src/index.ts:89`](../../packages/core/session/src/index.ts) +Source: [`packages/core/session/src/index.ts:108`](../../packages/core/session/src/index.ts) ### `session/event` — emit @@ -616,7 +616,7 @@ Post-commit, fire-and-forget append feed. The listener snapshot resolves before Types: [Scoped](../core-data-structures/scope.md) · [Session](../core-data-structures/session.md) · [SessionEvent](../core-data-structures/core.md) -Source: [`packages/core/session/src/index.ts:101`](../../packages/core/session/src/index.ts) +Source: [`packages/core/session/src/index.ts:120`](../../packages/core/session/src/index.ts) ### `session/flush` — parallel @@ -637,7 +637,7 @@ Awaited parallel durability checkpoint: every listener runs and the caller await Types: [Scoped](../core-data-structures/scope.md) · [Session](../core-data-structures/session.md) -Source: [`packages/core/session/src/index.ts:111`](../../packages/core/session/src/index.ts) +Source: [`packages/core/session/src/index.ts:130`](../../packages/core/session/src/index.ts) ## `subagent/*` diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 5858799e7c..ca7ab31b9d 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -246,7 +246,7 @@ async request(req: ApprovalRequest): Promise Types: [ApprovalOutcome](../core-data-structures/approval.md) · [ApprovalRequest](../core-data-structures/approval.md) -Source: [`packages/ui/user-approval/src/index.ts:213`](../../packages/ui/user-approval/src/index.ts) +Source: [`packages/ui/user-approval/src/index.ts:198`](../../packages/ui/user-approval/src/index.ts) ## `ctx.bash` — `BashExecutor` (abstract seam) @@ -1246,7 +1246,7 @@ fork(source: SessionForkSource, boundary?: number, childSessionId?: SessionId): Types: [CreateSessionOptions](../core-data-structures/persistence.md) · [OutOfBandSessionEventType](../core-data-structures/session.md) · [Session](../core-data-structures/session.md) · [SessionEvent](../core-data-structures/core.md) · [SessionEventMap](../core-data-structures/session.md) · [SessionId](../core-data-structures/core.md) · [TurnTrigger](../core-data-structures/session.md) -Source: [`packages/core/session/src/index.ts:605`](../../packages/core/session/src/index.ts) +Source: [`packages/core/session/src/index.ts:624`](../../packages/core/session/src/index.ts) ## `ctx.sessionTitle` — `SessionTitleService` diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index 179ad0dcee..291bae5122 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -14,7 +14,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `agent/error` | `emit` | [`packages/core/agent/src/types.ts:365`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-session`](../packages/goal/goal-session), `runtime`, [`tui`](../packages/ui/tui) | | `agent/post-step` | `serial` | [`packages/core/agent/src/types.ts:315`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`compact-basic`](../packages/compact/compact-basic), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy) | | `agent/pre-step` | `serial` | [`packages/core/agent/src/types.ts:246`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`time-context`](../packages/context/time-context), [`user-approval`](../packages/ui/user-approval) | -| `agent/prompt-submit` | `waterfall` | [`packages/core/agent/src/types.ts:262`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`acp`](../packages/ui/acp), [`goal-session`](../packages/goal/goal-session), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard) | +| `agent/prompt-submit` | `waterfall` | [`packages/core/agent/src/types.ts:262`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`acp`](../packages/ui/acp), [`goal-session`](../packages/goal/goal-session), [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode), [`repeat-tool-guard`](../packages/guard/repeat-tool-guard), `runtime` | | `agent/queued` | `emit` | [`packages/core/agent/src/types.ts:207`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emit`) | [`goal-session`](../packages/goal/goal-session), [`tui`](../packages/ui/tui) | | `agent/request` | `waterfall` | [`packages/core/agent/src/types.ts:276`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`agent`](../packages/core/agent) | | `agent/request-error` | `waterfall` | [`packages/core/agent/src/types.ts:330`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`compact-basic`](../packages/compact/compact-basic), [`llm-retry`](../packages/llm/llm-retry), [`plan-mode`](../packages/plan/plan-mode) | @@ -24,17 +24,17 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `agent/step-result` | `waterfall` | [`packages/core/agent/src/types.ts:303`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | - | | `agent/turn-continuation` | `waterfall` | [`packages/core/agent/src/types.ts:341`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`waterfall`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex), [`plan-mode`](../packages/plan/plan-mode) | | `agent/turn-stop` | `serial` | [`packages/core/agent/src/types.ts:352`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`subagent-inprocess`](../packages/subagent/subagent-inprocess), [`tool-goal`](../packages/goal/tool-goal) | -| `approval/request` | `waterfall` | [`packages/ui/user-approval/src/index.ts:30`](../packages/ui/user-approval/src/index.ts) | [`user-approval`](../packages/ui/user-approval) (`waterfall`) | [`acp`](../packages/ui/acp) | +| `approval/request` | `waterfall` | [`packages/ui/user-approval/src/index.ts:31`](../packages/ui/user-approval/src/index.ts) | [`user-approval`](../packages/ui/user-approval) (`waterfall`) | [`acp`](../packages/ui/acp), `runtime` | | `commands/change` | `emit` | [`packages/ui/commands/src/index.ts:103`](../packages/ui/commands/src/index.ts) | [`commands`](../packages/ui/commands) (`events.dispatch`) | [`acp`](../packages/ui/acp), [`tui`](../packages/ui/tui) | | `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:62`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-policy`](../packages/fs/fs-policy) | | `fs/observed` | `emit` | [`packages/fs/fs/src/index.ts:71`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`emit`) | [`fs-policy`](../packages/fs/fs-policy) | | `fs/write-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:54`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-policy`](../packages/fs/fs-policy) | | `goal/changed` | `emit` | [`packages/goal/goal/src/types.ts:167`](../packages/goal/goal/src/types.ts) | [`goal`](../packages/goal/goal) (`emit`) | [`goal-session`](../packages/goal/goal-session) | | `llm/stream` | `waterfall` | [`packages/llm/llm/src/index.ts:52`](../packages/llm/llm/src/index.ts) | [`llm`](../packages/llm/llm) (`waterfall`) | [`agent-loop`](../packages/core/agent-loop), [`llm`](../packages/llm/llm), [`llm-replay`](../packages/support/llm-replay), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`session-title`](../packages/session-title/session-title) | -| `session/created` | `emit` | [`packages/core/session/src/index.ts:79`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`compact`](../packages/compact/compact), [`goal`](../packages/goal/goal), [`hook-protocol`](../packages/hooks/hook-protocol), [`jsonrpc`](../packages/ui/jsonrpc), [`llm-retry`](../packages/llm/llm-retry), `runtime`, [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`user-approval`](../packages/ui/user-approval) | -| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:89`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `runtime`, [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title) | -| `session/event` | `emit` | [`packages/core/session/src/index.ts:101`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/ui/acp), [`cli-demo`](../packages/examples/cli-demo), [`compact`](../packages/compact/compact), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`jsonrpc`](../packages/ui/jsonrpc), `runtime`, [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title), [`token-meter`](../packages/llm/token-meter), [`tui`](../packages/ui/tui), [`user-approval`](../packages/ui/user-approval), [`workspace-context`](../packages/context/workspace-context) | -| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:111`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence`](../packages/session-persistence/session-persistence) | +| `session/created` | `emit` | [`packages/core/session/src/index.ts:98`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`compact`](../packages/compact/compact), [`goal`](../packages/goal/goal), [`hook-protocol`](../packages/hooks/hook-protocol), [`jsonrpc`](../packages/ui/jsonrpc), [`llm-retry`](../packages/llm/llm-retry), `runtime`, [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`user-approval`](../packages/ui/user-approval) | +| `session/disposed` | `emit` | [`packages/core/session/src/index.ts:108`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`agent-loop`](../packages/core/agent-loop), `runtime`, [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title) | +| `session/event` | `emit` | [`packages/core/session/src/index.ts:120`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`acp`](../packages/ui/acp), [`cli-demo`](../packages/examples/cli-demo), [`compact`](../packages/compact/compact), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`jsonrpc`](../packages/ui/jsonrpc), `runtime`, [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title), [`token-meter`](../packages/llm/token-meter), [`tui`](../packages/ui/tui), [`user-approval`](../packages/ui/user-approval), [`workspace-context`](../packages/context/workspace-context) | +| `session/flush` | `parallel` | [`packages/core/session/src/index.ts:130`](../packages/core/session/src/index.ts) | [`session`](../packages/core/session) (`events.dispatch`) | [`session-persistence`](../packages/session-persistence/session-persistence) | | `subagent/end` | `emit` | [`packages/subagent/subagent/src/index.ts:139`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`jsonrpc`](../packages/ui/jsonrpc), [`subagent`](../packages/subagent/subagent) | | `subagent/provider-added` | `emit` | [`packages/subagent/subagent/src/index.ts:113`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`emit`) | [`subagent`](../packages/subagent/subagent), [`tool-subagent`](../packages/subagent/tool-subagent) | | `subagent/provider-removed` | `emit` | [`packages/subagent/subagent/src/index.ts:119`](../packages/subagent/subagent/src/index.ts) | [`subagent`](../packages/subagent/subagent) (`events.dispatch`) | [`subagent`](../packages/subagent/subagent), [`tool-subagent`](../packages/subagent/tool-subagent) | diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 8c1d815bc0..7a1d5ecfb6 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -106,7 +106,7 @@ Sources: [`packages/core/session/src/types.ts:317`](../packages/core/session/src Types: [CallId](core-data-structures/core.md) -Source: [`packages/ui/user-approval/src/index.ts:44`](../packages/ui/user-approval/src/index.ts) +Source: [`packages/ui/user-approval/src/index.ts:45`](../packages/ui/user-approval/src/index.ts) #### `approval/decided` — log-only @@ -122,7 +122,7 @@ Source: [`packages/ui/user-approval/src/index.ts:44`](../packages/ui/user-approv } ``` -Source: [`packages/ui/user-approval/src/index.ts:55`](../packages/ui/user-approval/src/index.ts) +Source: [`packages/ui/user-approval/src/index.ts:56`](../packages/ui/user-approval/src/index.ts) #### `approval/policy` — log-only @@ -138,7 +138,7 @@ Source: [`packages/ui/user-approval/src/index.ts:55`](../packages/ui/user-approv 'approval/policy': { policy: ApprovalPolicy } ``` -Source: [`packages/ui/user-approval/src/index.ts:67`](../packages/ui/user-approval/src/index.ts) +Source: [`packages/ui/user-approval/src/index.ts:68`](../packages/ui/user-approval/src/index.ts) ### `assistant/*` diff --git a/packages/client/connection/src/client/api.ts b/packages/client/connection/src/client/api.ts index c7e1ed5c68..033d801243 100644 --- a/packages/client/connection/src/client/api.ts +++ b/packages/client/connection/src/client/api.ts @@ -7,7 +7,7 @@ export type { ApiProxy, SessionsApi, SessionSummary, HostApi, EventsApi, MuxFrame, HostFrame, - ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, ToolEventView, + ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, PermissionOption, ToolEventView, } from '@deepseek-ai/dsh-host-apiproxy/api' export type { ToolCallView, ToolResultView } from '@deepseek-ai/dsh-tools/presentation' export type { diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 7585ca9fba..5ca929eb2d 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -299,10 +299,19 @@ export function createFixtureApi(): ApiProxy { let nextSession = 1 let nextRpc = 1 const mint = (): ReturnType => RpcId(`fx-rpc-${nextRpc++}`) - /** Resident pending approval (stable rpcId: every mux open replays the same id, matching host replay semantics). */ + /** Resident pending approval (stable rpcId: every mux open replays the same id while unanswered, matching host replay semantics). */ const pendingApprovalRpcId = mint() + const pendingApprovalId = 'fx-approval-1' as Extract['approvalId'] + /** Cleared once answered through respond; replay stops and approval/resolved is broadcast. */ + let approvalPending = true const pendingQuestionRpcId = mint() let questionPending = true + /** Per-session permission preset (fixture mirror of the host permission select). */ + const permissionValues = new Map() + const PERMISSION_OPTIONS = [ + { value: 'workspace-write', name: 'workspace-write', description: 'Write inside the workspace and permitted temporary directories; wider retries require approval.' }, + { value: 'danger-full-access', name: 'danger-full-access', description: 'Full file access without approval prompts.' }, + ] const fixtureQuestions: Extract['questions'] = [ { id: 'harness-profile', @@ -522,6 +531,24 @@ export function createFixtureApi(): ApiProxy { } return ok(request, { accepted: true as const }) }, + permissions: (request) => { + const { sessionId: id } = request.payload + if (summaryOf(id) === undefined) { + return err(request, { code: 'session-not-found', message: `no session ${id}`, details: { sessionId: id } }) + } + return ok(request, { options: PERMISSION_OPTIONS, currentValue: permissionValues.get(id) ?? 'workspace-write' }) + }, + setPermission: (request) => { + const { sessionId: id, value } = request.payload + if (summaryOf(id) === undefined) { + return err(request, { code: 'session-not-found', message: `no session ${id}`, details: { sessionId: id } }) + } + if (!PERMISSION_OPTIONS.some(option => option.value === value)) { + return err(request, { code: 'bad-request', message: `unknown permission value ${JSON.stringify(value)}`, details: { issues: [] } }) + } + permissionValues.set(id, value) + return ok(request, { currentValue: value }) + }, }, host: { describe: request => ok(request, { version: '0.0.0-fixture', cwd: '/tmp/fixture', attachedSessions: 1 }), @@ -539,14 +566,16 @@ export function createFixtureApi(): ApiProxy { const title = titleFrameOf(s.sessionId, logs.get(s.sessionId) ?? []) if (title !== undefined) conn.push({ rpcId: mint(), payload: title }) } - conn.push({ - rpcId: pendingApprovalRpcId, - payload: { - type: 'approval/requested', sessionId: sid('fx-alpha'), - approvalId: 'fx-approval-1' as MuxFrame extends never ? never : Extract['approvalId'], - toolName: 'dangerous_tool', reason: 'fixture 常驻占位审批(可见不可答)', - }, - }) + if (approvalPending) { + conn.push({ + rpcId: pendingApprovalRpcId, + payload: { + type: 'approval/requested', sessionId: sid('fx-alpha'), + approvalId: pendingApprovalId, + toolName: 'dangerous_tool', reason: 'fixture 常驻审批(可答:批准/拒绝后消失)', + }, + }) + } if (questionPending) { conn.push({ rpcId: pendingQuestionRpcId, @@ -584,6 +613,19 @@ export function createFixtureApi(): ApiProxy { }, }, respond(message: ClientResponse): Promise { + // Same routing discipline as the host: rpcId first, then the payload's + // audit correlation; a settled or unknown id is not-pending. + if (message.rpcId === pendingApprovalRpcId) { + if (!approvalPending) return Promise.resolve({ accepted: false, reason: 'not-pending' }) + if (!message.result.ok) return Promise.resolve({ accepted: false, reason: 'bad-response' }) + const value = message.result.value as { approvalId?: unknown; outcome?: unknown } + if (value.approvalId !== pendingApprovalId || (value.outcome !== 'allowed-once' && value.outcome !== 'rejected')) { + return Promise.resolve({ accepted: false, reason: 'bad-response' }) + } + approvalPending = false + emitMux({ type: 'approval/resolved', sessionId: sid('fx-alpha'), approvalId: pendingApprovalId, outcome: value.outcome }) + return Promise.resolve({ accepted: true }) + } if (!questionPending || message.rpcId !== pendingQuestionRpcId) { return Promise.resolve({ accepted: false, reason: 'not-pending' }) } @@ -633,6 +675,8 @@ export class FixtureApiClient extends AbstractApiClient { case 'session.history': return this.api.sessions.history(request) case 'session.prompt': return this.api.sessions.prompt(request) case 'session.cancel': return this.api.sessions.cancel(request) + case 'session.permissions': return this.api.sessions.permissions(request) + case 'session.setPermission': return this.api.sessions.setPermission(request) case 'host.describe': return this.api.host.describe(request) } } diff --git a/packages/client/connection/src/client/index.ts b/packages/client/connection/src/client/index.ts index b017d1c9e2..fa2ddf9bdc 100644 --- a/packages/client/connection/src/client/index.ts +++ b/packages/client/connection/src/client/index.ts @@ -15,7 +15,7 @@ import { WebApiClient } from './web-api-client.ts' // ---- Contract re-exports (browser-safe apiproxy channels + core types) ---- export type { ApiProxy, SessionsApi, SessionSummary, HostApi, EventsApi, MuxFrame, HostFrame, - ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, ToolEventView, + ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, PermissionOption, ToolEventView, ToolCallView, ToolResultView, RpcRequest, RpcResponse, RpcResult, RpcError, RpcErrorCode, ClientRequest, ServerResponse, ServerRequest, ClientResponse, RpcMessage, RpcReceipt, diff --git a/packages/client/connection/tests/fake-api.ts b/packages/client/connection/tests/fake-api.ts index af5743bf9a..0bdef3432d 100644 --- a/packages/client/connection/tests/fake-api.ts +++ b/packages/client/connection/tests/fake-api.ts @@ -49,6 +49,12 @@ export class FakeApiClient implements IApiClient { onPrompt: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) onCancel: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) + onPermissions: (payload: unknown) => + Promise> = + () => Promise.resolve(ok({ options: [], currentValue: 'custom' })) + + onSetPermission: (payload: { sessionId: SessionId; value: string }) => Promise> = + payload => Promise.resolve(ok({ currentValue: payload.value })) onDescribe: (payload: unknown) => Promise> = () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 })) @@ -65,6 +71,8 @@ export class FakeApiClient implements IApiClient { this.record('session.history', payload, this.onHistory(payload)), prompt: (payload: unknown) => this.record('session.prompt', payload, this.onPrompt(payload)), cancel: (payload: unknown) => this.record('session.cancel', payload, this.onCancel(payload)), + permissions: (payload: unknown) => this.record('session.permissions', payload, this.onPermissions(payload)), + setPermission: (payload: { sessionId: SessionId; value: string }) => this.record('session.setPermission', payload, this.onSetPermission(payload)), } readonly host: IApiClient['host'] = { diff --git a/packages/client/connection/tests/fixture.spec.ts b/packages/client/connection/tests/fixture.spec.ts index ac32955c36..187869e42d 100644 --- a/packages/client/connection/tests/fixture.spec.ts +++ b/packages/client/connection/tests/fixture.spec.ts @@ -255,6 +255,61 @@ describe('createFixtureApi', () => { })).toEqual({ accepted: true }) }) + it('respond answers the resident approval once: routing, validation, resolved broadcast, then not-pending', async () => { + const api = createFixtureApi() + // Discover the resident approval's stable rpcId from the mux baseline. + const abort = new AbortController() + const seen: { rpcId: string; frame: MuxFrame }[] = [] + const consuming = (async () => { + for await (const envelope of api.events.mux(req({}), abort.signal)) seen.push({ rpcId: envelope.rpcId, frame: envelope.payload }) + })() + await vi.waitFor(() => { + expect(seen.some(s => s.frame.type === 'approval/requested')).toBe(true) + }) + const requested = seen.find(s => s.frame.type === 'approval/requested') + if (requested === undefined || requested.frame.type !== 'approval/requested') throw new Error('unreachable') + const approvalId = requested.frame.approvalId + + // Routed but malformed answers. + expect(await api.respond({ type: 'client-response', rpcId: RpcId(requested.rpcId), result: { ok: false, error: { code: 'internal', message: 'x', details: {} } } })) + .toEqual({ accepted: false, reason: 'bad-response' }) + expect(await api.respond({ type: 'client-response', rpcId: RpcId(requested.rpcId), result: { ok: true, value: { approvalId: 'wrong', outcome: 'rejected' } } })) + .toEqual({ accepted: false, reason: 'bad-response' }) + expect(await api.respond({ type: 'client-response', rpcId: RpcId(requested.rpcId), result: { ok: true, value: { approvalId, outcome: 'maybe' } } })) + .toEqual({ accepted: false, reason: 'bad-response' }) + // The real answer settles the question and broadcasts resolved. + expect(await api.respond({ type: 'client-response', rpcId: RpcId(requested.rpcId), result: { ok: true, value: { sessionId: sid('fx-alpha'), approvalId, outcome: 'allowed-once' } } })) + .toEqual({ accepted: true }) + await vi.waitFor(() => { + expect(seen.some(s => s.frame.type === 'approval/resolved' && s.frame.outcome === 'allowed-once')).toBe(true) + }) + // Settled: a duplicate answer is late, and a fresh mux open replays nothing. + expect(await api.respond({ type: 'client-response', rpcId: RpcId(requested.rpcId), result: { ok: true, value: { sessionId: sid('fx-alpha'), approvalId, outcome: 'rejected' } } })) + .toEqual({ accepted: false, reason: 'not-pending' }) + abort.abort() + await consuming + const abort2 = new AbortController() + const replayed = await collect(api.events.mux(req({}), abort2.signal), abort2, frames => frames.length === 2) + expect(replayed.some(f => f.type === 'approval/requested')).toBe(false) + }) + + it('permissions/setPermission mirror the host select: read, switch, validation', async () => { + const api = createFixtureApi() + const read = await api.sessions.permissions(req({ sessionId: sid('fx-alpha') })) + expect(read.result).toMatchObject({ ok: true, value: { currentValue: 'workspace-write' } }) + const switched = await api.sessions.setPermission(req({ sessionId: sid('fx-alpha'), value: 'danger-full-access' })) + expect(switched.result).toMatchObject({ ok: true, value: { currentValue: 'danger-full-access' } }) + const reread = await api.sessions.permissions(req({ sessionId: sid('fx-alpha') })) + expect(reread.result).toMatchObject({ ok: true, value: { currentValue: 'danger-full-access' } }) + // Validation: ghost session and unknown value. + const ghostRead = await api.sessions.permissions(req({ sessionId: sid('fx-ghost') })) + expect(ghostRead.result.ok).toBe(false) + const ghostSwitch = await api.sessions.setPermission(req({ sessionId: sid('fx-ghost'), value: 'workspace-write' })) + expect(ghostSwitch.result.ok).toBe(false) + const unknown = await api.sessions.setPermission(req({ sessionId: sid('fx-alpha'), value: 'nope' })) + expect(unknown.result.ok).toBe(false) + }) + it('describe answers the fixture identity', async () => { const api = createFixtureApi() const response = await api.host.describe(req({})) @@ -345,6 +400,8 @@ describe('FixtureApiClient (protocol-level fake carrier)', () => { expect((await client.sessions.history({ sessionId: id })).result.ok).toBe(true) expect((await client.sessions.prompt({ sessionId: id, mode: 'queue', content: [{ type: 'text', text: '嗨' }] })).result.ok).toBe(true) expect((await client.sessions.cancel({ sessionId: id })).result.ok).toBe(true) + expect((await client.sessions.permissions({ sessionId: id })).result.ok).toBe(true) + expect((await client.sessions.setPermission({ sessionId: id, value: 'danger-full-access' })).result.ok).toBe(true) expect((await client.host.describe({})).result.ok).toBe(true) }) diff --git a/packages/client/runtime/src/client/index.ts b/packages/client/runtime/src/client/index.ts index 33097d4573..65f378684d 100644 --- a/packages/client/runtime/src/client/index.ts +++ b/packages/client/runtime/src/client/index.ts @@ -38,7 +38,15 @@ export type { // PendingWait is a value export: tests construct fixture waits directly. export { PendingWait } from './sessions/pending.ts' export type { PendingInteraction, PendingKind, PendingPayloads } from './sessions/pending.ts' -export type { SessionId } from '@deepseek-ai/dsh-client-connection/client' +export type { PermissionOption, SessionId } from '@deepseek-ai/dsh-client-connection/client' + +/** The permission select material as the object layer serves it to UI plugins. */ +export interface PermissionSelect { + /** Switchable presets plus (when derived) the current-only `custom`. */ + options: { value: string; name: string; description?: string }[] + /** The effective current value (`custom` when knobs match no preset). */ + currentValue: string +} // ---- Narrowed aliases (the single narrowing point of the slot type chain: // ui-slots/web-react stay generic and dependency-inverted; the client-tree diff --git a/packages/client/runtime/src/client/sessions/lineage.ts b/packages/client/runtime/src/client/sessions/lineage.ts index c6bd572ea7..fb6a85704b 100644 --- a/packages/client/runtime/src/client/sessions/lineage.ts +++ b/packages/client/runtime/src/client/sessions/lineage.ts @@ -9,7 +9,7 @@ export interface TitledSessionSummary extends SessionSummary { title?: string } -/** One flattened session-list row (summary + lineage indent depth). */ +/** One flattened session-list row (summary + lineage indent depth + live pending-approval bit). */ export interface SessionListEntry { sessionId: SessionId title?: string @@ -17,6 +17,8 @@ export interface SessionListEntry { running: boolean parentSessionId?: SessionId cwd?: string + /** An approval question is pending on this session (mux-frame derived; the sidebar's amber dot). */ + waitingApproval: boolean /** Lineage indent depth: root = 0; the UI just multiplies by the indent width. */ depth: number } @@ -25,9 +27,10 @@ export interface SessionListEntry { * summaries -> flat list with lineage indentation (pure; roots by updatedAt * desc, DFS children in the same order, orphans degrade to roots). * @param summaries - the host's session.list items. + * @param waitingApproval - sessions with a pending approval question (manager-owned live fact; absent = false). * @returns display rows in render order. */ -export function flattenLineage(summaries: readonly TitledSessionSummary[]): SessionListEntry[] { +export function flattenLineage(summaries: readonly TitledSessionSummary[], waitingApproval?: ReadonlySet): SessionListEntry[] { const byId = new Map() for (const s of summaries) byId.set(s.sessionId, s) @@ -54,7 +57,7 @@ export function flattenLineage(summaries: readonly TitledSessionSummary[]): Sess return } visited.add(s.sessionId) - out.push({ ...s, depth }) + out.push({ ...s, waitingApproval: waitingApproval?.has(s.sessionId) ?? false, depth }) const kids = children.get(s.sessionId) if (kids === undefined) return kids.sort(byUpdatedDesc) diff --git a/packages/client/runtime/src/client/sessions/manager.ts b/packages/client/runtime/src/client/sessions/manager.ts index b65935a97d..f13600f037 100644 --- a/packages/client/runtime/src/client/sessions/manager.ts +++ b/packages/client/runtime/src/client/sessions/manager.ts @@ -36,6 +36,11 @@ export class SessionManager { * drop-and-backfill path; replayed and cleared on instantiation. Bounded per session (these * frames are low-frequency; overflow drops oldest) and dropped on session-removed (audit S7). */ private readonly pendingBuffers = new Map[]>() + /** Outstanding approval questions per session, keyed by approvalId (idempotent under mux-open + * replays of the same requested frame). Manager-owned rather than read off Session instances + * because the sidebar must light up for sessions never instantiated. Cleared per connection + * generation — the reopen replay re-adds still-pending questions — and on session-removed. */ + private readonly waitingApprovals = new Map>() private readonly titleSnapshots = new Map() private summaries: SessionSummary[] = [] private listState: 'idle' | 'loading' | 'error' = 'idle' @@ -186,6 +191,22 @@ export class SessionManager { this.notifier.markDirty() } } + // List-level waiting-approval bit (the sidebar amber dot): tracked here for + // every session, instantiated or not; approvalId keys make replays idempotent. + if (frame.type === 'approval/requested') { + let ids = this.waitingApprovals.get(frame.sessionId) + if (ids === undefined) this.waitingApprovals.set(frame.sessionId, ids = new Set()) + if (!ids.has(frame.approvalId)) { + ids.add(frame.approvalId) + this.notifier.markDirty() + } + } else if (frame.type === 'approval/resolved') { + const ids = this.waitingApprovals.get(frame.sessionId) + if (ids !== undefined && ids.delete(frame.approvalId)) { + if (ids.size === 0) this.waitingApprovals.delete(frame.sessionId) + this.notifier.markDirty() + } + } const session = this.sessions.get(frame.sessionId) if (session === undefined) { // Approval/question frames never hit history: buffer for replay on instantiation; @@ -232,6 +253,7 @@ export class SessionManager { this.summaries = this.summaries.filter(s => s.sessionId !== frame.sessionId) this.sessions.get(frame.sessionId)?.handleRemoved() // instance survives (resident-instance rule), only flagged in the snapshot this.pendingBuffers.delete(frame.sessionId) // a removed session's buffered frames must not replay on a future instantiation + this.waitingApprovals.delete(frame.sessionId) // a removed session cannot wait on anyone this.titleSnapshots.delete(frame.sessionId) this.notifier.markDirty() return @@ -254,6 +276,12 @@ export class SessionManager { /** After each connection generation (first connect included): refresh the list + resync opened instances (reconnect = rebuild). */ handleConnected(): void { + // Approvals resolved while disconnected send no frame: drop the bits and + // let the mux-open replay re-add every still-pending question. + if (this.waitingApprovals.size > 0) { + this.waitingApprovals.clear() + this.notifier.markDirty() + } void this.refreshList() for (const session of this.sessions.values()) void session.resync() } @@ -265,13 +293,14 @@ export class SessionManager { ? summary : { ...summary, title: title.title, updatedAt: Math.max(summary.updatedAt, title.updatedAt) } }) - const fresh = flattenLineage(merged) + const fresh = flattenLineage(merged, new Set(this.waitingApprovals.keys())) const items = fresh.map((entry) => { const prev = this.entryCache.get(entry.sessionId) if ( prev !== undefined && prev.updatedAt === entry.updatedAt && prev.running === entry.running && prev.parentSessionId === entry.parentSessionId && prev.cwd === entry.cwd && prev.title === entry.title && prev.depth === entry.depth + && prev.waitingApproval === entry.waitingApproval ) return prev this.entryCache.set(entry.sessionId, entry) return entry diff --git a/packages/client/runtime/src/client/sessions/service.ts b/packages/client/runtime/src/client/sessions/service.ts index d8a6f05762..daf81d102f 100644 --- a/packages/client/runtime/src/client/sessions/service.ts +++ b/packages/client/runtime/src/client/sessions/service.ts @@ -32,6 +32,8 @@ export interface SessionSummary { cwd?: string parentId?: SessionId running: boolean + /** An approval question is pending on this session (sidebar amber-dot state). */ + waitingApproval: boolean updatedAt: number } @@ -310,6 +312,7 @@ export class SessionsService { id: entry.sessionId, displayTitle: displayTitleOf(entry.title, entry.cwd, entry.sessionId), running: entry.running, + waitingApproval: entry.waitingApproval, updatedAt: entry.updatedAt, ...(entry.title !== undefined ? { title: entry.title } : {}), ...(entry.cwd !== undefined ? { cwd: entry.cwd } : {}), diff --git a/packages/client/runtime/src/client/sessions/session.ts b/packages/client/runtime/src/client/sessions/session.ts index 6b773e0903..741716f44a 100644 --- a/packages/client/runtime/src/client/sessions/session.ts +++ b/packages/client/runtime/src/client/sessions/session.ts @@ -128,6 +128,31 @@ export class Session implements ObservableSnapshot { return result } + /** + * Read the permission select (options + effective current value). + * @returns the select material, or the error branch on failure. + */ + async permissions(): Promise> { + try { + return (await this.api.sessions.permissions({ sessionId: this.sessionId })).result + } catch (error) { + return transportError(error) + } + } + + /** + * Switch the permission preset. + * @param value - a preset value advertised by {@link Session.permissions} (never `custom`). + * @returns the confirmed current value, or the error branch on failure. + */ + async setPermission(value: string): Promise> { + try { + return (await this.api.sessions.setPermission({ sessionId: this.sessionId, value })).result + } catch (error) { + return transportError(error) + } + } + /** First open: pull the tail page (idempotent — in-flight/already-open returns the existing promise). */ open(): Promise { if (this.openState === 'open') return Promise.resolve() diff --git a/packages/client/runtime/tests/fake-api.ts b/packages/client/runtime/tests/fake-api.ts index 25f12c2b70..5ec6f4737f 100644 --- a/packages/client/runtime/tests/fake-api.ts +++ b/packages/client/runtime/tests/fake-api.ts @@ -52,6 +52,13 @@ export class FakeApiClient implements IApiClient { onPrompt: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) onCancel: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) + onPermissions: (payload: unknown) => + Promise> = + () => Promise.resolve(ok({ options: [], currentValue: 'custom' })) + + onSetPermission: (payload: { sessionId: SessionId; value: string }) => Promise> = + payload => Promise.resolve(ok({ currentValue: payload.value })) + onDescribe: (payload: unknown) => Promise> = () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 })) @@ -68,6 +75,8 @@ export class FakeApiClient implements IApiClient { this.record('session.history', payload, this.onHistory(payload)), prompt: (payload: unknown) => this.record('session.prompt', payload, this.onPrompt(payload)), cancel: (payload: unknown) => this.record('session.cancel', payload, this.onCancel(payload)), + permissions: (payload: unknown) => this.record('session.permissions', payload, this.onPermissions(payload)), + setPermission: (payload: { sessionId: SessionId; value: string }) => this.record('session.setPermission', payload, this.onSetPermission(payload)), } readonly host: IApiClient['host'] = { diff --git a/packages/client/runtime/tests/manager.spec.ts b/packages/client/runtime/tests/manager.spec.ts index d37ef6dbce..64c01247e2 100644 --- a/packages/client/runtime/tests/manager.spec.ts +++ b/packages/client/runtime/tests/manager.spec.ts @@ -281,3 +281,42 @@ describe('connected generation', () => { }) }) }) + +describe('waiting-approval list bit', () => { + it('lights on requested, survives replay duplicates, and clears on resolved — without instantiation', () => { + const manager = new SessionManager(new FakeApiClient()) + manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1 } }) + expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(false) + manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } }) + expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(true) + // Mux-open replay of the same question (same approvalId) is idempotent. + manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } }) + expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(true) + manager.handleMuxEnvelope({ rpcId: 'rx' as never, payload: { type: 'approval/resolved', sessionId: S1, approvalId: 'ap1' as never, outcome: 'allowed-once' as never } }) + expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(false) + }) + + it('clears only when the last outstanding question resolves; session-removed drops the bit', () => { + const manager = new SessionManager(new FakeApiClient()) + manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1 } }) + manager.handleMuxEnvelope({ rpcId: 'r1' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'a1' as never, toolName: 'rm' } }) + manager.handleMuxEnvelope({ rpcId: 'r2' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'a2' as never, toolName: 'rm' } }) + manager.handleMuxEnvelope({ rpcId: 'rx' as never, payload: { type: 'approval/resolved', sessionId: S1, approvalId: 'a1' as never, outcome: 'rejected' as never } }) + expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(true) + manager.handleMuxEnvelope({ rpcId: 'ry' as never, payload: { type: 'approval/resolved', sessionId: S1, approvalId: 'a2' as never, outcome: 'rejected' as never } }) + expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(false) + // Removed sessions drop their bit outright. + manager.handleMuxEnvelope({ rpcId: 'r3' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'a3' as never, toolName: 'rm' } }) + manager.handleHostEnvelope({ rpcId: 'h2' as never, payload: { type: 'host/session-removed', sessionId: S1 } }) + expect(manager.getListSnapshot().items).toHaveLength(0) + }) + + it('drops stale bits on reconnect — the reopen replay re-adds still-pending questions', () => { + const manager = new SessionManager(new FakeApiClient()) + manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1 } }) + manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } }) + expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(true) + manager.handleConnected() // resolved-while-disconnected questions send no frame + expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(false) + }) +}) diff --git a/packages/client/runtime/tests/session.spec.ts b/packages/client/runtime/tests/session.spec.ts index b980a674fe..8678096856 100644 --- a/packages/client/runtime/tests/session.spec.ts +++ b/packages/client/runtime/tests/session.spec.ts @@ -669,3 +669,27 @@ describe('reference stability (the memo contract)', () => { expect(resolved.pending).toBe(after.pending) }) }) + +describe('permissions / setPermission', () => { + it('passes the select read and switch through with the session id', async () => { + const { api, session } = makeSession() + api.onPermissions = () => Promise.resolve(ok({ options: [{ value: 'workspace-write', name: 'workspace-write' }], currentValue: 'workspace-write' })) + const read = await session.permissions() + expect(read.ok).toBe(true) + if (read.ok) expect(read.value.currentValue).toBe('workspace-write') + expect(api.callsOf('session.permissions')).toMatchObject([{ sessionId: SID }]) + + const switched = await session.setPermission('danger-full-access') + expect(switched.ok).toBe(true) + if (switched.ok) expect(switched.value.currentValue).toBe('danger-full-access') + expect(api.callsOf('session.setPermission')).toMatchObject([{ sessionId: SID, value: 'danger-full-access' }]) + }) + + it('folds transport failures into the error branch', async () => { + const { api, session } = makeSession() + api.onPermissions = () => Promise.reject(new Error('down')) + api.onSetPermission = () => Promise.reject(new Error('down')) + expect((await session.permissions()).ok).toBe(false) + expect((await session.setPermission('x')).ok).toBe(false) + }) +}) diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index ebd7474298..75967f46a4 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -4,6 +4,8 @@ Conversation domain: skeleton (header/tabs/composer/empty state), chat view (gro The view ring IS a slot: the conversation registration declares the `'conversation.view'` list slot (session scope) in its `children` table, ConversationRoot renders the active entry through its renderSlot share (`only: `), and view tabs project from the ring ledger's registration options (`id`/`order`/`label`). The chat view is this package's own ring entry; other plugins (ui-trajectory) contribute tabs through plain `ctx.slots.register` — the former package-local view registry (`registerView`/`ViewEntry`/`ConversationViewMap` and the chrome attachment table) is retired, with per-view chrome dissolved into the view components themselves. +Approvals take over the composer through the chain this package declares: `ApprovalPanel` registers as a selector-routed `'conversation.composer'` entry (the ui-question pattern) and occupies the composer in place of the InputBar while an approval wait is pending (amber strip, justification headline, paired command line from the running call's args, one-shot refuse/allow). The `PendingApproval` domain face in `contract/slots.ts` owns the wire encoding — the `ApprovalResponsePayload` value with the audit correlation — over the runtime's `PendingWait` carrier; the broadcast `approval/resolved` frame settles the wait and restores the composer. The sidebar mirrors the blocked state: the session row's amber warning dot (a manager-tracked `waitingApproval` list bit, lit for uninstantiated sessions too) outranks the running ring until the question resolves. Question placeholders remain in the message flow as display-only PendingCards while ui-question owns the answering takeover. The composer's bottom-row chip mounts the permission-preset select (`PermissionSelect`), fed by the injected `permissions`/`setPermission` callbacks over the object layer's session RPCs; empty options (a permission-less host) hide the control, and the derived `custom` value renders as current-only. + Generic tool rows classify the built-in bash, read, search, write, and edit names into dedicated visual variants. The filesystem variants render the edit icon and `Write · ` or `Edit · ` summary while retaining the shared row-to-details interaction. Tool rows are slots too — the standalone tool ring (`ToolViewRegistry`/`ctx.toolviews`/outlet) is retired. The chat entry declares the keyed `'conversation.chat.toolview'` hole (session scope; the key space is runtime-open); its render site dispatches per row via `entryKey: toolName` with `GenericToolCard` as the call-site `fallback`. The owner payload is the uniform `ToolRowOwnerProps` (`callId`/`toolName`/`block`/`openDetails`) and `ToolRowProps` pre-composes it with the session standard kit. A registrant is a plain plugin: `ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)` with `inject: ['slots', 'conversation']` as the load-order seam (apply mounts ConversationService after the chat registration, so the service being present guarantees the slot is declared); session differentiation happens inside the component (`useSessions` reading `parentId` — the bash sample is the third-party-posture exemplar). Trajectory/waterfall toolview slots share this shape and land with their own render sites (RendersCheck rejects a declaration nobody renders). @@ -26,4 +28,5 @@ None; this package neither assembles nor sends a provider request. - **Details panel is the minimal form** — selected call args/result raw display; the Input/Output/Metadata switch, Prev/Next stepping, and See-in-trajectory deep link are deferred. - **Assistant footer extensions (IconActions row, per-message paging) are reserved slots** — drawn in the design, not implemented. - **The sparkle icon for the others tool row is a hand-drawn approximation** — the design glyph's vector geometry is not exportable locally; promotion into ui-primitives waits on an exact export. -- **Approval cards are display-only placeholders** — question requests answer through the composer chain (ui-question), while web-side approval answering is the P-II approvals project. +- **The permission select reads once per mount** — a host-side preset change from another client surfaces only after a session re-select; live knob-event-driven refresh is deferred. +- **The approval panel's "Always allow this type" is deferred** — durable grants need a grant-storage design; only allow-once/reject answer today. diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 372eb36c80..f17e32d1ee 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -15,12 +15,13 @@ import type { SessionId, SessionsService } from '@deepseek-ai/dsh-client-runtime import type {} from '@deepseek-ai/dsh-client-ui-layout/client' import type { ViewTab } from './contract/views.ts' import type { - ChatViewInjected, ConversationInjected, DetailsInjected, EmptyStateInjected, + ApprovalWait, ChatViewInjected, ComposerChainProps, ConversationInjected, DetailsInjected, EmptyStateInjected, } from './contract/slots.ts' import { createChatStore } from './stores.ts' import { ConversationService } from './service.ts' import { ChatView } from './chat/ChatView.tsx' import { bashToolviewSample } from './toolviews/bash-sample.tsx' +import { ApprovalPanel } from './skeleton/ApprovalPanel.tsx' import { ConversationRoot } from './skeleton/ConversationRoot.tsx' import { DetailsPanel } from './skeleton/DetailsPanel.tsx' import { EmptyState } from './skeleton/EmptyState.tsx' @@ -37,6 +38,11 @@ function scopedConversation(sessions: SessionsService, id: SessionId): Conversat return conversation } +/** Chain routing: claim the composer while an approval wait is pending (pure — owner props only). */ +function selectApproval({ interactions }: ComposerChainProps): ApprovalWait | null { + return interactions.find((i): i is ApprovalWait => i.kind === 'approval') ?? null +} + /** * Client plugin body. * @param ctx - client root context. @@ -104,10 +110,31 @@ export function apply(ctx: Context): void { }) }, open: (target: SessionId) => { sessions.open(target) }, + permissions: async () => { + const result = await sessions.manager.get(sessionId).permissions() + // Empty options = permission-less host composition: hide the control + // rather than show an empty select (deployment shape, not an error). + if (!result.ok || result.value.options.length === 0) return null + return result.value + }, + setPermission: async (value) => { + const result = await sessions.manager.get(sessionId).setPermission(value) + return result.ok ? result.value.currentValue : null + }, } }, }, ConversationRoot) + // The approval takeover: a selector-routed entry of the chain this package + // just declared (the ui-question registration pattern; the entry lives here + // because approval answering is core conversation UX, not an optional tool). + // Zero business face — data and verbs both ride the matched carrier. + // priority 1: question takeovers (default 0) win when both kinds are + // pending — a question is a conversation the model is waiting on, while an + // approval only blocks one tool call; answering the question first cannot + // strand the approval (it re-elects the moment the question resolves). + slots.register({ name: 'conversation.composer', select: selectApproval, priority: 1 }, ApprovalPanel) + // The chat view: first entry of the ring this package just declared. // Declaring the keyed toolview hole here is claiming it: ChatView is the // only component authorized to render per-tool rows. Shares the chat diff --git a/packages/client/ui-conversation/src/client/chat/ChatView.tsx b/packages/client/ui-conversation/src/client/chat/ChatView.tsx index 8023acddde..23f822ee19 100644 --- a/packages/client/ui-conversation/src/client/chat/ChatView.tsx +++ b/packages/client/ui-conversation/src/client/chat/ChatView.tsx @@ -254,7 +254,9 @@ export function ChatView({ useSession, useStore, renderSlot, openDetails, loadOl ))} )} - {pending.map((item) => )} + {/* Approvals take over the composer (ApprovalPanel); only question + placeholders remain in the flow. */} + {pending.filter((item) => item.kind === 'question').map((item) => )} diff --git a/packages/client/ui-conversation/src/client/chat/PendingCard.module.css b/packages/client/ui-conversation/src/client/chat/PendingCard.module.css index 2318c88c94..cb17b4387c 100644 --- a/packages/client/ui-conversation/src/client/chat/PendingCard.module.css +++ b/packages/client/ui-conversation/src/client/chat/PendingCard.module.css @@ -1,4 +1,4 @@ -/* Amber pending strip (approval waiting = warn semantic, figma state colors). */ +/* Amber pending strip (question waiting = warn semantic, figma state colors). */ .card { margin: 6px 0; @@ -13,19 +13,3 @@ font-weight: 500; color: var(--dsw-alias-label-primary); } - -.mono { - font-family: var(--ds-font-family-code); -} - -.reason { - margin-top: 4px; - font-size: 12px; - color: var(--dsw-alias-label-secondary); -} - -.hint { - margin-top: 6px; - font-size: 11px; - color: var(--dsw-alias-label-tertiary); -} diff --git a/packages/client/ui-conversation/src/client/chat/PendingCard.tsx b/packages/client/ui-conversation/src/client/chat/PendingCard.tsx index b6825aed9a..c5a5ead161 100644 --- a/packages/client/ui-conversation/src/client/chat/PendingCard.tsx +++ b/packages/client/ui-conversation/src/client/chat/PendingCard.tsx @@ -1,6 +1,7 @@ -// PendingCard: approval/question placeholder card (visible, not answerable — -// the composer-takeover approval panel is a P-II item; wire pending semantics -// already exist so the flow must show them). +// PendingCard: question pending placeholder in the message flow (visible +// while the question composer owns the takeover slot elsewhere). Approvals +// do not render here: they take over the composer (skeleton ApprovalPanel) +// per the designer draft. import { memo } from 'react' import type { PendingInteraction } from '@deepseek-ai/dsh-client-runtime/client' @@ -8,24 +9,14 @@ import { JsonBlock } from '@deepseek-ai/dsh-client-ui-primitives' import css from './PendingCard.module.css' export interface PendingCardProps { - item: PendingInteraction + item: Extract } export const PendingCard = memo(function PendingCard({ item }: PendingCardProps) { return (
- {item.kind === 'approval' ? ( - <> -
等待审批:{item.payload.toolName}
- {item.payload.reason !== undefined &&
{item.payload.reason}
} - - ) : ( - <> -
等待回答({item.payload.questions.length} 题)
- - - )} -
请在原客户端处理(web 端作答后续里程碑提供)
+
等待回答({item.payload.questions.length} 题)
+
) }) diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index ffbc13ff59..fa8a493135 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -11,7 +11,7 @@ * here. */ import type { PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' -import type { PendingInteraction, SessionId, ToolCallBlock } from '@deepseek-ai/dsh-client-runtime/client' +import type { PendingInteraction, PendingWait, PermissionSelect, SessionId, ToolCallBlock } from '@deepseek-ai/dsh-client-runtime/client' import type { createChatStore } from '../stores.ts' import type { CallId, SelectionTarget, ViewTab } from './views.ts' @@ -113,6 +113,10 @@ export interface ConversationInjected { stop(): void /** Navigate to another session (breadcrumb ancestors). */ open(id: SessionId): void + /** Read the permission select (options + effective current value); null hides the control. */ + permissions(): Promise + /** Switch the permission preset; resolves the confirmed value, or null on failure (caller keeps the old value). */ + setPermission(value: string): Promise } /** @@ -132,6 +136,68 @@ export type ConversationSlotProps = PropsRuntime<'conversation'> & PropsRenderSlots<'conversation.view' | 'conversation.composer'> & PropsStore & ConversationInjected +/** The pending approval carrier the owner dispatches into the composer chain. */ +export type ApprovalWait = PendingWait<'approval'> + +/** + * Approval domain face over the carrier (the ui-question PendingQuestion + * pattern): render identity and question material forwarded transparently; + * answer owns the wire encoding — the ApprovalResponsePayload value shape + * with the audit correlation the host reconciles — and turns a rejected + * carrier receipt into a thrown error. Minted per carrier via useMemo. + */ +export class PendingApproval { + /** + * @param wait - the runtime carrier for one pending approval question. + */ + constructor(private readonly wait: ApprovalWait) {} + + /** Opaque render identity (React key / one-shot latch remount axis), forwarded from the carrier. */ + get key(): string { + return this.wait.key + } + + /** The tool the question is about (headline fallback), forwarded from the carrier payload. */ + get toolName(): string { + return this.wait.payload.toolName + } + + /** The asker's human-readable WHY (headline when present), forwarded from the carrier payload. */ + get reason(): string | undefined { + return this.wait.payload.reason + } + + /** The paired tool call's id when the ask names one (command-line lookup key), forwarded from the carrier payload. */ + get callId(): string | undefined { + return this.wait.payload.callId + } + + /** + * Deliver the user's decision; a rejected carrier receipt throws. Panel + * removal stays frame-driven: the broadcast `approval/resolved` settles the + * wait and drops it from the pending list. + * @param outcome - the only two client-answerable outcomes. + */ + async answer(outcome: 'allowed-once' | 'rejected'): Promise { + const receipt = await this.wait.respond({ + ok: true, + value: { sessionId: this.wait.sessionId, approvalId: this.wait.payload.approvalId, outcome }, + }) + if (!receipt.accepted) { + throw new Error(`approval response rejected: ${receipt.reason}`) + } + } +} + +/** + * Full approval-composer props: the framework runtime share (chain currency + + * session/global standard kit) plus the chain `matched` share — the entry's + * selector result, already narrowed to the approval carrier. No injected + * share: the carrier plus the domain face above carry the whole behavior + * surface; the paired command line derives from useSession in-component. + */ +export type ApprovalComposerProps = PropsRuntime<'conversation.composer'> & { matched: ApprovalWait } + /** * Injected share of the chat view entry: the two callbacks whose targets live * outside the view (layout orchestration; the session object layer). diff --git a/packages/client/ui-conversation/src/client/skeleton/ApprovalPanel.module.css b/packages/client/ui-conversation/src/client/skeleton/ApprovalPanel.module.css new file mode 100644 index 0000000000..c3d8ef47bd --- /dev/null +++ b/packages/client/ui-conversation/src/client/skeleton/ApprovalPanel.module.css @@ -0,0 +1,107 @@ +/* Composer-takeover approval panel (draft approval.png): the same floating + capsule footprint as the InputBar card, with an amber header band, the + justification headline, a muted command line, and right-aligned actions. + Warn semantics ride the alias state tokens; no hardcoded colors. */ + +/* Mirrors InputBar .root so the takeover is a content swap, not a layout jump. */ +.root { + display: flex; + flex-direction: column; + align-items: center; + padding: 8px 32px 12px; +} + +.card { + overflow: hidden; + width: 100%; + max-width: 776px; + border: 1px solid var(--dsw-alias-state-warn-secondary); + border-radius: 20px; + background: var(--dsw-specific-input-major); + box-shadow: var(--dsw-shadow-lv2); +} + +/* Tinted full-width header band. */ +.strip { + display: flex; + align-items: center; + gap: 8px; + padding: 10px 16px; + background: var(--dsw-alias-state-warn-tertiary); + color: var(--dsw-alias-state-warn-primary); + font-size: 13px; + line-height: 18px; +} + +.dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: var(--dsw-alias-state-warn-primary); +} + +.body { + display: flex; + flex-direction: column; + gap: 6px; + padding: 12px 16px 14px; +} + +/* The model's justification is the panel's message, not a footnote. */ +.headline { + color: var(--dsw-alias-label-primary); + font-size: 15px; + font-weight: 500; + line-height: 24px; +} + +.command { + color: var(--dsw-alias-label-tertiary); + font-family: var(--ds-font-family-code); + font-size: 13px; + line-height: 20px; + word-break: break-all; +} + +.actionRow { + display: flex; + justify-content: flex-end; + gap: 8px; + margin-top: 8px; +} + +.allow, +.reject { + padding: 6px 16px; + border-radius: 10px; + font-size: 13px; + line-height: 18px; + cursor: pointer; +} + +.allow:disabled, +.reject:disabled { + opacity: 0.5; + cursor: default; +} + +/* Primary action: filled ink (draft's rightmost emphasis, minus the dropped + always-allow button). */ +.allow { + border: none; + background: var(--dsw-alias-label-primary); + color: var(--dsw-alias-label-primary-foreground); +} + +/* Secondary: quiet outline. */ +.reject { + border: 1px solid var(--dsw-alias-border-l2-darkmode-thin); + background: transparent; + color: var(--dsw-alias-label-secondary); +} + +.reject:hover:not(:disabled) { + background: var(--dsw-alias-interactive-bg-hover-danger); + color: var(--dsw-alias-state-error-primary); + border-color: transparent; +} diff --git a/packages/client/ui-conversation/src/client/skeleton/ApprovalPanel.tsx b/packages/client/ui-conversation/src/client/skeleton/ApprovalPanel.tsx new file mode 100644 index 0000000000..7b8d52a6ec --- /dev/null +++ b/packages/client/ui-conversation/src/client/skeleton/ApprovalPanel.tsx @@ -0,0 +1,71 @@ +// ApprovalPanel: the composer-takeover approval prompt (designer draft +// approval.png), registered as a selector-routed entry of the +// conversation-declared composer chain. While an approval question is +// pending, this panel occupies the composer slot in place of the InputBar: +// an amber "Waiting for approval" strip on the card top, the model's +// justification as the headline, the paired command in muted code text, and +// a right-aligned refuse/allow action row. One-shot: the buttons disable +// after a click and the panel leaves (the InputBar returns) on the broadcast +// resolved frame. The draft's "Always allow this type" is deferred with +// grant storage. + +import { useMemo, useState } from 'react' +import type { RunningToolCall } from '@deepseek-ai/dsh-client-runtime/client' +import { PendingApproval, type ApprovalComposerProps } from '../contract/slots.ts' +import css from './ApprovalPanel.module.css' + +/** Extract the shell command from an approval's paired running call (bash-family args carry `command`); undefined hides the line. */ +export function commandOf(call: RunningToolCall | undefined): string | undefined { + if (call === undefined) return undefined + try { + const args = JSON.parse(call.argsRaw) as Record + return typeof args.command === 'string' ? args.command : undefined + } catch { + // Unparseable model args: the panel still renders, just without the command line. + return undefined + } +} + +/** + * Composer takeover boundary: mints the domain face on the carrier's stable + * identity and remounts the flow per request key, so the one-shot answered + * latch never leaks to the next pending approval. + * @param props - the selector-matched pending approval carrier plus the framework standard kit. + * @returns The approval prompt for this request. + */ +export function ApprovalPanel(props: ApprovalComposerProps) { + const approval = useMemo(() => new PendingApproval(props.matched), [props.matched]) + const command = props.useSession(s => commandOf( + approval.callId === undefined ? undefined : s.runningCalls.find(call => call.callId === approval.callId))) + return +} + +function ApprovalFlow({ pending, command }: { pending: PendingApproval; command?: string }) { + // Local one-shot latch: the panel leaves only when the resolved frame + // lands; until then the buttons must not re-fire. An answer failure + // (rejected receipt / transport) re-arms them for retry. + const [answered, setAnswered] = useState(false) + const answer = (outcome: 'allowed-once' | 'rejected'): void => { + setAnswered(true) + void pending.answer(outcome).catch(() => { setAnswered(false) }) + } + return ( +
+
+
等待审批
+
+
{pending.reason ?? `工具 ${pending.toolName} 请求越权执行`}
+ {command !== undefined &&
{command}
} +
+ + +
+
+
+
+ ) +} diff --git a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx index 59346a557b..d904c73b68 100644 --- a/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/ConversationRoot.tsx @@ -15,6 +15,7 @@ import type { SessionId, SessionListState, SessionSummary } from '@deepseek-ai/d import type { ConversationSlotProps } from '../contract/slots.ts' import { InputBar } from './InputBar.tsx' import type { InputBarError } from './InputBar.tsx' +import { PermissionSelect } from './PermissionSelect.tsx' import css from './ConversationRoot.module.css' /** Full props = the automatic shares & injected share — composed by reference @@ -38,7 +39,7 @@ function deriveAncestry(list: SessionListState, id: SessionId): readonly Session export function ConversationRoot({ sessionId, useSession, useSessions, useStore, actions, renderSlot, renderSlotChain, - views, send, stop, open, + views, send, stop, open, permissions, setPermission, }: ConversationRootProps) { useSyncExternalStore(views.subscribe, views.version) const tabs = views.list() @@ -68,6 +69,7 @@ export function ConversationRoot({ disabled={removed} error={error} variant="composer" + controls={} onDraftChange={actions.setDraft} onSend={(mode) => { send(draft, mode) }} onStop={stop} diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index 04d1dd867d..551ce70cac 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -30,6 +30,8 @@ export interface InputBarProps { placeholder?: string /** Optional leading accessory row above the textarea (kept for callers; empty state no longer uses it). */ accessory?: ReactNode + /** Host-wired access-mode control (the composer mounts the permission chip here); replaces the visual-only placeholder. */ + controls?: ReactNode onDraftChange: (text: string) => void onSend: (mode: 'queue' | 'steer') => void onStop: () => void @@ -56,7 +58,7 @@ const MODEL_OPTIONS: readonly SelectOption[] = [ ] export function InputBar({ - draft, running, disabled, error, variant, placeholder, accessory, onDraftChange, onSend, onStop, + draft, running, disabled, error, variant, placeholder, accessory, controls, onDraftChange, onSend, onStop, }: InputBarProps) { const empty = draft.trim() === '' const inputRef = useRef(null) @@ -177,7 +179,8 @@ export function InputBar({
{renderSelect('Plan mode', planId, PLAN_OPTIONS, setPlanId)} - {renderSelect('Access mode', readonlyId, READONLY_OPTIONS, setReadonlyId)} + {/* The wired permission chip supersedes the visual-only Access placeholder. */} + {controls ?? renderSelect('Access mode', readonlyId, READONLY_OPTIONS, setReadonlyId)}
diff --git a/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css new file mode 100644 index 0000000000..dd5986992c --- /dev/null +++ b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css @@ -0,0 +1,49 @@ +/* Composer bottom-row permission chip (draft start.jpeg `Read-only ∨`): a + quiet text chip with a chevron; hover paints the standard interactive pill. + The native select is stretched invisibly over the chip so the platform + dropdown does the menu work — keyboard/AT semantics come free. */ + +.root { + position: relative; + display: inline-flex; + align-items: center; +} + +.chip { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 6px 8px; + border-radius: 8px; + color: var(--dsw-alias-label-secondary); + font-size: 14px; + line-height: 20px; + pointer-events: none; /* the overlaid select owns the interaction */ +} + +.root:hover .chip { + background: var(--dsw-alias-interactive-bg-hover); +} + +.chevron { + color: var(--dsw-alias-label-caption); +} + +/* Invisible native select stretched over the chip: real menu, zero drawing. */ +.select { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + opacity: 0; + border: none; + cursor: pointer; +} + +.select:disabled { + cursor: default; +} + +.root:has(.select:disabled) .chip { + opacity: 0.5; +} diff --git a/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx new file mode 100644 index 0000000000..a32e2af037 --- /dev/null +++ b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx @@ -0,0 +1,88 @@ +// PermissionSelect: the composer bottom-row permission chip (draft +// start.jpeg's `Read-only ∨` control). Options and the current value load on +// mount from the injected permissions() callback; empty options +// (permission-less host composition) render nothing. The visible chip is +// presentation only — an invisible native select stretched over it owns the +// menu and interaction. A switch disables the control until the host +// confirms, then adopts the confirmed value (`custom` is shown as the current +// value but never offered as a target — the host already omits it from +// switchable options; a stale-select failure restores the previous value). + +import { useEffect, useRef, useState } from 'react' +import type { PermissionSelect as PermissionSelectData } from '@deepseek-ai/dsh-client-runtime/client' +import css from './PermissionSelect.module.css' + +/** + * Display transform: kebab-case machine names render as title-case labels + * (`workspace-write` → `Workspace Write`). Presentation-only — the wire + * vocabulary and the host's advertised names are untouched; a host-configured + * name that is not kebab-case (contains spaces or uppercase) passes through. + */ +function displayName(name: string): string { + if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(name)) return name + return name.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ') +} + +export interface PermissionSelectProps { + /** Read the select material; null hides the control. */ + permissions: () => Promise + /** Switch the preset; resolves the confirmed value, or null on failure. */ + setPermission: (value: string) => Promise +} + +export function PermissionSelect({ permissions, setPermission }: PermissionSelectProps) { + const [data, setData] = useState(null) + const [switching, setSwitching] = useState(false) + // Unmount guard: the load/switch promises outlive a session switch's remount. + const aliveRef = useRef(true) + useEffect(() => { + aliveRef.current = true + void permissions().then((loaded) => { + if (aliveRef.current) setData(loaded) + }) + return () => { + aliveRef.current = false + } + }, [permissions]) + + if (data === null) return null + + const onChange = (value: string): void => { + if (value === data.currentValue) return + setSwitching(true) + const previous = data + setData({ ...data, currentValue: value }) + void setPermission(value).then((confirmed) => { + if (!aliveRef.current) return + setSwitching(false) + if (confirmed === null) setData(previous) + else setData({ ...previous, currentValue: confirmed }) + }) + } + + const current = data.options.find(option => option.value === data.currentValue) + + return ( + + ) +} diff --git a/packages/client/ui-conversation/tests/apply-inject.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.spec.tsx index edd9f7d54d..aa06d6853e 100644 --- a/packages/client/ui-conversation/tests/apply-inject.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.spec.tsx @@ -61,6 +61,10 @@ async function bench() { () => Promise.resolve({ ok: true, value: { accepted: true } })), cancel: vi.fn<() => Promise<{ ok: boolean; value?: object; error?: { code: string; message: string } }>>( () => Promise.resolve({ ok: true, value: { accepted: true } })), + permissions: vi.fn<() => Promise<{ ok: boolean; value?: { options: { value: string; name: string }[]; currentValue: string }; error?: { code: string; message: string } }>>( + () => Promise.resolve({ ok: true, value: { options: [{ value: 'workspace-write', name: 'workspace-write' }], currentValue: 'workspace-write' } })), + setPermission: vi.fn<() => Promise<{ ok: boolean; value?: { currentValue: string }; error?: { code: string; message: string } }>>( + () => Promise.resolve({ ok: true, value: { currentValue: 'danger-full-access' } })), } const scopes = new Map() const mint = (id: SessionId): Context => { @@ -143,6 +147,32 @@ describe('conversation slot inject surface', () => { expect(b.sessionFake.loadOlder).toHaveBeenCalledTimes(1) }) + it('permissions/setPermission thread the object layer; empty options and failures fold to null', async () => { + const b = await bench() + const { injected } = b.conversationSurface(ROOT) + expect(await injected.permissions()).toMatchObject({ currentValue: 'workspace-write' }) + expect(await injected.setPermission('danger-full-access')).toBe('danger-full-access') + // Empty options (permission-less host) and the error branch both hide the control. + b.sessionFake.permissions.mockResolvedValueOnce({ ok: true, value: { options: [], currentValue: 'custom' } }) + expect(await injected.permissions()).toBeNull() + b.sessionFake.permissions.mockResolvedValueOnce({ ok: false, error: { code: 'internal', message: 'x' } }) + expect(await injected.permissions()).toBeNull() + b.sessionFake.setPermission.mockResolvedValueOnce({ ok: false, error: { code: 'bad-request', message: 'x' } }) + expect(await injected.setPermission('nope')).toBeNull() + }) + + it('registers the approval takeover on the composer chain: routing selector, no inject face', async () => { + const b = await bench() + const entry = b.slots.entries('conversation.composer')[0]! + expect(entry.inject).toBeUndefined() + // The selector narrows the chain currency: approval wait in → that wait; none → null. + const select = entry.select as (owner: { interactions: readonly { kind: string }[] }) => unknown + const approval = { kind: 'approval' } + expect(select({ interactions: [{ kind: 'question' }, approval] })).toBe(approval) + expect(select({ interactions: [{ kind: 'question' }] })).toBeNull() + expect(select({ interactions: [] })).toBeNull() + }) + it('send trims, optimistically clears through actions, restores on failure without clobbering new typing', async () => { const b = await bench() const { instance, injected } = b.conversationSurface(ROOT) diff --git a/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx b/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx index be50356185..95565add35 100644 --- a/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-branch-tails.spec.tsx @@ -44,11 +44,11 @@ describe('MessageItem arms', () => { }) describe('small branch tails', () => { - it('PendingCard approval reason renders when present', () => { + it('PendingCard renders the question count', () => { const view = render( - ['payload'], vi.fn())} />, + ['payload'], vi.fn())} />, ) - expect(view.getByText('careful')).toBeTruthy() + expect(view.getByText(/等待回答(1 题)/)).toBeTruthy() }) it('AssistantMarkdown single-line reasoning summary skips the newline cut', () => { diff --git a/packages/client/ui-conversation/tests/chat-stats-bash-sample.spec.tsx b/packages/client/ui-conversation/tests/chat-stats-bash-sample.spec.tsx index 4d3383b2d1..383bc92883 100644 --- a/packages/client/ui-conversation/tests/chat-stats-bash-sample.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-stats-bash-sample.spec.tsx @@ -123,8 +123,8 @@ describe('bash sample row', () => { return createSnapshotStore({ ids: [ROOT, CHILD], byId: { - [ROOT]: { id: ROOT, title: 'r', displayTitle: 'r', running: false, updatedAt: 0 }, - [CHILD]: { id: CHILD, title: 'c', displayTitle: 'c', parentId: ROOT, running: false, updatedAt: 0 }, + [ROOT]: { id: ROOT, title: 'r', displayTitle: 'r', running: false, waitingApproval: false, updatedAt: 0 }, + [CHILD]: { id: CHILD, title: 'c', displayTitle: 'c', parentId: ROOT, running: false, waitingApproval: false, updatedAt: 0 }, }, current: undefined, } as SessionListState) @@ -158,7 +158,7 @@ describe('bash sample row', () => { const orphan = 'late-child' as SessionId store.update((d) => { d.ids.push(orphan) - d.byId[orphan] = { id: orphan, title: 'l', displayTitle: 'l', running: false, updatedAt: 0 } + d.byId[orphan] = { id: orphan, title: 'l', displayTitle: 'l', running: false, waitingApproval: false, updatedAt: 0 } }) const view = render() expect(view.container.querySelector('[data-sample="bash-global"]')).not.toBeNull() diff --git a/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx b/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx index 5d2b3408a2..2fa9224a95 100644 --- a/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx @@ -75,7 +75,14 @@ async function bench(nodes: ToolResultNode[]) { const layout = { openDetails: vi.fn(), closeDetails: vi.fn() } ctx.provide('sessions', { list, - manager: { get: () => ({ loadOlder: vi.fn() }) }, + manager: { + get: () => ({ + loadOlder: vi.fn(), + // The mounted PermissionSelect loads on mount; empty options hide the control. + permissions: vi.fn(() => Promise.resolve({ ok: true, value: { options: [], currentValue: 'custom' } })), + setPermission: vi.fn(() => Promise.resolve({ ok: false, error: { code: 'bad-request', message: 'unused', details: { issues: [] } } })), + }), + }, scope: () => ({ get: () => scoped }), cell: (id: string) => (id === SID ? cell : undefined), create: vi.fn(), diff --git a/packages/client/ui-conversation/tests/chat-view.spec.tsx b/packages/client/ui-conversation/tests/chat-view.spec.tsx index 3f1db55199..314080f9be 100644 --- a/packages/client/ui-conversation/tests/chat-view.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-view.spec.tsx @@ -342,12 +342,17 @@ describe('ChatView', () => { expect(lv.getByText('载入历史…')).toBeTruthy() }) - it('pending interactions render placeholder cards', () => { + it('question waits render placeholder cards; approvals leave the flow (composer takeover)', () => { const h = makeHarness({ - pending: [new PendingWait('approval', RpcId('r1'), SID, - { approvalId: 'ap1', toolName: 'bash' } as PendingWait<'approval'>['payload'], vi.fn())], + pending: [ + new PendingWait('approval', RpcId('r1'), SID, + { approvalId: 'ap1', toolName: 'bash' } as PendingWait<'approval'>['payload'], vi.fn()), + new PendingWait('question', RpcId('r2'), SID, + { questions: [{ id: 'q1', question: '选择' }] } as PendingWait<'question'>['payload'], vi.fn()), + ], }) const view = render() - expect(view.getByText(/等待审批/)).toBeTruthy() + expect(view.getByText(/等待回答(1 题)/)).toBeTruthy() + expect(view.queryByText(/等待审批/)).toBeNull() }) }) diff --git a/packages/client/ui-conversation/tests/skeleton-branches.spec.tsx b/packages/client/ui-conversation/tests/skeleton-branches.spec.tsx index 4eb70ea39f..9231211a47 100644 --- a/packages/client/ui-conversation/tests/skeleton-branches.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton-branches.spec.tsx @@ -82,6 +82,8 @@ describe('ConversationRoot branches', () => { send={vi.fn()} stop={vi.fn()} open={open} + permissions={() => Promise.resolve(null)} + setPermission={() => Promise.resolve(null)} />, ) return { view, open, chat } @@ -141,6 +143,8 @@ describe('ConversationRoot branches', () => { send={vi.fn()} stop={vi.fn()} open={vi.fn()} + permissions={() => Promise.resolve(null)} + setPermission={() => Promise.resolve(null)} />, ) expect(view.getByTestId('view-body')).toBeTruthy() diff --git a/packages/client/ui-conversation/tests/skeleton.spec.tsx b/packages/client/ui-conversation/tests/skeleton.spec.tsx index a598803a25..f7cce649e7 100644 --- a/packages/client/ui-conversation/tests/skeleton.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.spec.tsx @@ -221,6 +221,8 @@ describe('ConversationRoot', () => { send={send} stop={stop} open={open} + permissions={() => Promise.resolve(null)} + setPermission={() => Promise.resolve(null)} />) return { ui, chat, send, stop, open, renderSlot } } diff --git a/packages/client/ui-sidebar/README.md b/packages/client/ui-sidebar/README.md index c165455b1a..af56b1ac7d 100644 --- a/packages/client/ui-sidebar/README.md +++ b/packages/client/ui-sidebar/README.md @@ -18,6 +18,6 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work -- **State dots have two live data states (running/none)** — the done/error/amber sources arrive with P-II approvals and notifications; the four-color primitive is already wired. +- **State dots have three live data states (running/amber approval-waiting/none)** — the done/error sources arrive with notifications; the four-color primitive is already wired. - **Group-by menu ships by-workspace only** — Update/Status grouping strategies are drawn without specs and deferred. - **"New task completed" unread marking is local viewing state** — completion-time > last-seen never reaches the host. diff --git a/packages/client/ui-sidebar/src/client/Rows.tsx b/packages/client/ui-sidebar/src/client/Rows.tsx index 53f8bbe14f..541e2c9388 100644 --- a/packages/client/ui-sidebar/src/client/Rows.tsx +++ b/packages/client/ui-sidebar/src/client/Rows.tsx @@ -102,7 +102,11 @@ export function SessionRowItem({ row, selected, now, onOpen, onToggle }: { ) : } - {row.running && } + {/* Waiting-approval (amber) outranks the running ring: the session is + blocked on the user, which is the more actionable fact. */} + + {row.waitingApproval ? : row.running && } + {row.title} {formatRelativeTime(row.updatedAt, now)} diff --git a/packages/client/ui-sidebar/src/client/tree.ts b/packages/client/ui-sidebar/src/client/tree.ts index 021c7e9276..a37a61cf75 100644 --- a/packages/client/ui-sidebar/src/client/tree.ts +++ b/packages/client/ui-sidebar/src/client/tree.ts @@ -38,6 +38,8 @@ export interface SessionRow { hasChildren: boolean expanded: boolean running: boolean + /** An approval question is pending (amber warning dot outranks the running ring). */ + waitingApproval: boolean updatedAt: number } @@ -159,6 +161,7 @@ function sessionRow(g: Group, s: SessionSummary, depth: number, hasChildren: boo hasChildren, expanded, running: s.running, + waitingApproval: s.waitingApproval, updatedAt: s.updatedAt, } } diff --git a/packages/client/ui-sidebar/tests/apply.spec.tsx b/packages/client/ui-sidebar/tests/apply.spec.tsx index 44fdae18f8..1757a9623a 100644 --- a/packages/client/ui-sidebar/tests/apply.spec.tsx +++ b/packages/client/ui-sidebar/tests/apply.spec.tsx @@ -23,7 +23,7 @@ async function bench() { await ctx.plugin(SlotsService).await() const list = createSnapshotStore({ ids: [sid('a')], - byId: { [sid('a')]: { id: sid('a'), title: 'alpha', displayTitle: 'alpha', cwd: '/proj', running: false, updatedAt: 1 } }, + byId: { [sid('a')]: { id: sid('a'), title: 'alpha', displayTitle: 'alpha', cwd: '/proj', running: false, waitingApproval: false, updatedAt: 1 } }, current: undefined, }) const sessions = { diff --git a/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx b/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx index 71416aef36..437f2398b1 100644 --- a/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx +++ b/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx @@ -31,6 +31,7 @@ interface SummaryInit { cwd?: string parentId?: string running?: boolean + waitingApproval?: boolean updatedAt?: number } @@ -40,6 +41,7 @@ function summary(init: SummaryInit): SessionSummary { title: init.title ?? init.id, displayTitle: init.title ?? init.id, running: init.running ?? false, + waitingApproval: init.waitingApproval ?? false, updatedAt: init.updatedAt ?? 0, } if (init.cwd !== undefined) s.cwd = init.cwd @@ -290,4 +292,17 @@ describe('SidebarRoot', () => { expect(busyRow.querySelector('[data-state="ongoing"]')).toBeTruthy() expect(idleRow.querySelector('[data-state="ongoing"]')).toBeNull() }) + + it('waiting-approval shows the amber warning dot and outranks the running ring', () => { + mount( + summary({ id: 'blocked', title: 'blocked one', cwd: '/p', running: true, waitingApproval: true, updatedAt: 2 }), + summary({ id: 'busy', title: 'busy one', cwd: '/p', running: true, updatedAt: 1 }), + ) + act(() => { fireEvent.click(screen.getByText('p')) }) + const blockedRow = screen.getByText('blocked one').closest('[role="treeitem"]')! + const busyRow = screen.getByText('busy one').closest('[role="treeitem"]')! + expect(blockedRow.querySelector('[data-state="warning"]')).toBeTruthy() + expect(blockedRow.querySelector('[data-state="ongoing"]')).toBeNull() + expect(busyRow.querySelector('[data-state="ongoing"]')).toBeTruthy() + }) }) diff --git a/packages/client/ui-sidebar/tests/tree.spec.ts b/packages/client/ui-sidebar/tests/tree.spec.ts index 037a2a82ac..79a8afefa0 100644 --- a/packages/client/ui-sidebar/tests/tree.spec.ts +++ b/packages/client/ui-sidebar/tests/tree.spec.ts @@ -15,6 +15,7 @@ interface SummaryInit { cwd?: string parentId?: string running?: boolean + waitingApproval?: boolean updatedAt?: number } @@ -23,6 +24,7 @@ function summary(init: SummaryInit): SessionSummary { id: sid(init.id), displayTitle: init.displayTitle ?? init.title ?? init.id, running: init.running ?? false, + waitingApproval: init.waitingApproval ?? false, updatedAt: init.updatedAt ?? 0, } if (init.title !== undefined) s.title = init.title diff --git a/packages/client/ui-trajectory/tests/views.spec.tsx b/packages/client/ui-trajectory/tests/views.spec.tsx index 4818e67db5..d77c1cdf74 100644 --- a/packages/client/ui-trajectory/tests/views.spec.tsx +++ b/packages/client/ui-trajectory/tests/views.spec.tsx @@ -144,6 +144,8 @@ function mount(slots: SlotsService, nodes: ConversationSnapshot['nodes'] = NODES send={vi.fn()} stop={vi.fn()} open={vi.fn()} + permissions={() => Promise.resolve(null)} + setPermission={() => Promise.resolve(null)} />, ) } diff --git a/packages/core/session/src/index.ts b/packages/core/session/src/index.ts index 9c5831bb18..e00babb648 100644 --- a/packages/core/session/src/index.ts +++ b/packages/core/session/src/index.ts @@ -59,6 +59,25 @@ export function findLastMessageTurnEnd( return latest } +/** + * Whether the log currently sits inside an open turn (a `turn/start` not yet + * closed by a `turn/end`). The turn is the durable log's commit/replay + * boundary: a bare event appended between turns is indistinguishable from a + * crash tail and silently dropped on reload, so writers of turn-enclosed + * events (approval audit pairs, permission/sandbox knob switches) gate on + * this fold and hold idle writes until the next turn opens. + * @param events - session events, or an owned suffix, to inspect. + * @returns true when the last turn boundary event is a `turn/start`. + */ +export function hasOpenTurn(events: readonly SessionEvent[]): boolean { + for (let index = events.length - 1; index >= 0; index -= 1) { + const type = (events[index] as SessionEvent).type + if (type === 'turn/start') return true + if (type === 'turn/end') return false + } + return false +} + declare module 'cordis' { interface Context { sessions: SessionStore diff --git a/packages/core/session/tests/session.spec.ts b/packages/core/session/tests/session.spec.ts index d880153dd3..83a2fa1172 100644 --- a/packages/core/session/tests/session.spec.ts +++ b/packages/core/session/tests/session.spec.ts @@ -4,6 +4,7 @@ import { CallId } from '@deepseek-ai/dsh-llm' import SessionStore, { displayPromptContent, findLastMessageTurnEnd, + hasOpenTurn, SESSION_FORMAT_VERSION, Session, SessionEvent, @@ -91,6 +92,17 @@ describe('Session', () => { expect(findLastMessageTurnEnd(session.events)).toBe(messageEnd) }) + it('reports an open turn only between turn/start and its turn/end', () => { + const session = new Session(SessionId('open-turn')) + expect(hasOpenTurn(session.events)).toBe(false) + session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) + expect(hasOpenTurn(session.events)).toBe(true) + session.append('user/message', { content: [{ type: 'text', text: 'x' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) + expect(hasOpenTurn(session.events)).toBe(true) + session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) + expect(hasOpenTurn(session.events)).toBe(false) + }) + it('round-trips the coarse aborted turn outcome', () => { const session = new Session(SessionId('aborted')) session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index 1badfe65e8..9a2df36b47 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -24,6 +24,6 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work -- **`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 `dsh-host-runtime` and is still a stub there. +- **`respond` is routed by host-side pending tables** — the wire shape (POST `/api/respond`, `RpcReceipt`) is final here; the approval and question registries that make late/duplicate answers meaningful live in `dsh-host-runtime`. - **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. diff --git a/packages/host/apiproxy/src/api/index.ts b/packages/host/apiproxy/src/api/index.ts index c2fbb0d189..242c5f20a9 100644 --- a/packages/host/apiproxy/src/api/index.ts +++ b/packages/host/apiproxy/src/api/index.ts @@ -19,7 +19,7 @@ export interface ApiProxy { } // ---- Domain interfaces and payload entities ---- -export type { HistoryEntry, SessionsApi, SessionSummary } from './sessions.ts' +export type { HistoryEntry, PermissionOption, SessionsApi, SessionSummary } from './sessions.ts' export type { HostApi } from './host.ts' export type { EventsApi, MuxFrame, HostFrame, ToolCallView, ToolEventView, ToolResultView } from './events.ts' export type { ApprovalResponsePayload } from './approvals.ts' diff --git a/packages/host/apiproxy/src/api/rpc-map.ts b/packages/host/apiproxy/src/api/rpc-map.ts index b37cc062ff..6ada97d673 100644 --- a/packages/host/apiproxy/src/api/rpc-map.ts +++ b/packages/host/apiproxy/src/api/rpc-map.ts @@ -15,6 +15,8 @@ export interface RpcMethodMap { 'session.history': SessionsApi['history'] 'session.prompt': SessionsApi['prompt'] 'session.cancel': SessionsApi['cancel'] + 'session.permissions': SessionsApi['permissions'] + 'session.setPermission': SessionsApi['setPermission'] 'host.describe': HostApi['describe'] } diff --git a/packages/host/apiproxy/src/api/sessions.schema.ts b/packages/host/apiproxy/src/api/sessions.schema.ts index 3edf0e6014..4c3da79dc9 100644 --- a/packages/host/apiproxy/src/api/sessions.schema.ts +++ b/packages/host/apiproxy/src/api/sessions.schema.ts @@ -9,7 +9,7 @@ import { z } from 'zod' import type { SessionEvent, SessionId } from '@deepseek-ai/dsh-session/types' import type { RequestPayload, ResponseValue } from './rpc-map.ts' import type { Wire } from './rpc.schema.ts' -import type { HistoryEntry, SessionSummary } from './sessions.ts' +import type { HistoryEntry, PermissionOption, SessionSummary } from './sessions.ts' import type { ToolEventView } from './events.ts' /** SessionId: one brand cast after shape validation (the only cast point in this domain). */ @@ -108,3 +108,32 @@ export const sessionCancelRequestSchema = z.object({ export const sessionCancelValueSchema = z.object({ accepted: z.literal(true), }) satisfies z.ZodType>> + +/** One permission select option (a preset table key, or the derived `custom`). */ +export const permissionOptionSchema = z.object({ + value: z.string(), + name: z.string(), + description: z.string().optional(), +}) satisfies z.ZodType> + +/** session.permissions request payload. */ +export const sessionPermissionsRequestSchema = z.object({ + sessionId: sessionIdSchema, +}) satisfies z.ZodType>> + +/** session.permissions response value. */ +export const sessionPermissionsValueSchema = z.object({ + options: z.array(permissionOptionSchema), + currentValue: z.string(), +}) satisfies z.ZodType>> + +/** session.setPermission request payload. */ +export const sessionSetPermissionRequestSchema = z.object({ + sessionId: sessionIdSchema, + value: z.string(), +}) satisfies z.ZodType>> + +/** session.setPermission response value. */ +export const sessionSetPermissionValueSchema = z.object({ + currentValue: z.string(), +}) satisfies z.ZodType>> diff --git a/packages/host/apiproxy/src/api/sessions.ts b/packages/host/apiproxy/src/api/sessions.ts index 393303f817..b2c56405e2 100644 --- a/packages/host/apiproxy/src/api/sessions.ts +++ b/packages/host/apiproxy/src/api/sessions.ts @@ -44,6 +44,21 @@ export interface SessionSummary { cwd?: string } +/** + * One selectable permission preset (or the derived `custom` state) as the + * client renders it. Protocol-owned DTO (the ACP bridge precedent: each + * protocol owns its presentation shape); the host projects it from + * `ctx.permission` without exposing that service's types on the wire. + */ +export interface PermissionOption { + /** The machine value (`session.setPermission` vocabulary): a preset table key, or `custom`. */ + value: string + /** The display label. */ + name: string + /** One user-facing sentence on what the value means. */ + description?: string +} + /** Session-domain unary methods (the map keys session.* of RpcMethodMap). */ export interface SessionsApi { /** Lists persisted sessions (updatedAt descending). v1 returns everything; cursor is a reserved seat, unimplemented. */ @@ -70,4 +85,24 @@ export interface SessionsApi { /** Stops: clears both FIFOs + aborts the current step (1:1 with agent.cancel). */ cancel(request: RpcRequest<{ sessionId: SessionId }>): Promise> + + /** + * Reads the session's permission select: every switchable preset plus the + * effective current value (`custom` when the knobs match no preset — shown, + * never a switch target). A host composed without the permission service + * returns empty options and `custom`; clients hide the control. + */ + permissions(request: RpcRequest<{ sessionId: SessionId }>): + Promise> + + /** + * Switches the session's permission preset. Mirrors the ACP bridge's + * turn-anchoring: inside an open turn the knob events append immediately; + * idle switches are held last-write-wins and flushed into the next prompted + * turn (approval-policy and sandbox-mode events must stay turn-enclosed for + * durable replay). A current-value echo is acknowledged without recording. + * Unknown values and a permission-less composition are bad-request. + */ + setPermission(request: RpcRequest<{ sessionId: SessionId; value: string }>): + Promise> } diff --git a/packages/host/apiproxy/src/fetch/client.ts b/packages/host/apiproxy/src/fetch/client.ts index 901cf7bd2a..79941033bd 100644 --- a/packages/host/apiproxy/src/fetch/client.ts +++ b/packages/host/apiproxy/src/fetch/client.ts @@ -19,7 +19,9 @@ import { sessionCreateValueSchema, sessionHistoryValueSchema, sessionListValueSchema, + sessionPermissionsValueSchema, sessionPromptValueSchema, + sessionSetPermissionValueSchema, } from '../api/sessions.schema.ts' /** @@ -44,6 +46,8 @@ export interface IApiClient { history(payload: RequestPayload<'session.history'>, signal?: AbortSignal): Promise>> prompt(payload: RequestPayload<'session.prompt'>, signal?: AbortSignal): Promise>> cancel(payload: RequestPayload<'session.cancel'>, signal?: AbortSignal): Promise>> + permissions(payload: RequestPayload<'session.permissions'>, signal?: AbortSignal): Promise>> + setPermission(payload: RequestPayload<'session.setPermission'>, signal?: AbortSignal): Promise>> } host: { describe(payload: RequestPayload<'host.describe'>, signal?: AbortSignal): Promise>> @@ -66,6 +70,8 @@ const UNARY_VALUE_SCHEMAS: { [K in keyof RpcMethodMap]: z.ZodType this.callUnary('session.history', payload, signal), prompt: (payload, signal) => this.callUnary('session.prompt', payload, signal), cancel: (payload, signal) => this.callUnary('session.cancel', payload, signal), + permissions: (payload, signal) => this.callUnary('session.permissions', payload, signal), + setPermission: (payload, signal) => this.callUnary('session.setPermission', payload, signal), } readonly host: IApiClient['host'] = { diff --git a/packages/host/apiproxy/src/fetch/handler.ts b/packages/host/apiproxy/src/fetch/handler.ts index 03b9f6500f..085238ac0f 100644 --- a/packages/host/apiproxy/src/fetch/handler.ts +++ b/packages/host/apiproxy/src/fetch/handler.ts @@ -19,7 +19,9 @@ import { sessionCreateRequestSchema, sessionHistoryRequestSchema, sessionListRequestSchema, + sessionPermissionsRequestSchema, sessionPromptRequestSchema, + sessionSetPermissionRequestSchema, } from '../api/sessions.schema.ts' import { hostDescribeRequestSchema } from '../api/host.schema.ts' @@ -43,6 +45,8 @@ const UNARY_ROUTES: UnaryRoutes = { 'session.history': { schema: sessionHistoryRequestSchema, invoke: (api, r) => api.sessions.history(r) }, 'session.prompt': { schema: sessionPromptRequestSchema, invoke: (api, r) => api.sessions.prompt(r) }, 'session.cancel': { schema: sessionCancelRequestSchema, invoke: (api, r) => api.sessions.cancel(r) }, + 'session.permissions': { schema: sessionPermissionsRequestSchema, invoke: (api, r) => api.sessions.permissions(r) }, + 'session.setPermission': { schema: sessionSetPermissionRequestSchema, invoke: (api, r) => api.sessions.setPermission(r) }, 'host.describe': { schema: hostDescribeRequestSchema, invoke: (api, r) => api.host.describe(r) }, } diff --git a/packages/host/apiproxy/tests/client-handler.spec.ts b/packages/host/apiproxy/tests/client-handler.spec.ts index 25af7e2f75..e39d8d553a 100644 --- a/packages/host/apiproxy/tests/client-handler.spec.ts +++ b/packages/host/apiproxy/tests/client-handler.spec.ts @@ -31,6 +31,8 @@ function scriptedApi(overrides: { history: r => ok(r, { events: [], hasMore: false }), prompt: r => ok(r, { accepted: true as const }), cancel: r => ok(r, { accepted: true as const }), + permissions: r => ok(r, { options: [], currentValue: 'custom' }), + setPermission: r => ok(r, { currentValue: r.payload.value }), ...overrides.sessions, }, host: { describe: r => ok(r, { version: '0-test', cwd: '/t', attachedSessions: 0 }), ...overrides.host }, diff --git a/packages/host/apiproxy/tests/fetch-carrier.spec.ts b/packages/host/apiproxy/tests/fetch-carrier.spec.ts index d097daecef..5272c65b9e 100644 --- a/packages/host/apiproxy/tests/fetch-carrier.spec.ts +++ b/packages/host/apiproxy/tests/fetch-carrier.spec.ts @@ -36,6 +36,12 @@ function fakeApi(overrides: Partial<{ muxFrames: MuxFrame[]; hostFrames: HostFra async cancel(request) { return { rpcId: request.rpcId, result: { ok: true, value: { accepted: true as const } } } }, + async permissions(request) { + return { rpcId: request.rpcId, result: { ok: true, value: { options: [], currentValue: 'custom' } } } + }, + async setPermission(request) { + return { rpcId: request.rpcId, result: { ok: true, value: { currentValue: request.payload.value } } } + }, }, host: { async describe(request) { @@ -75,11 +81,13 @@ describe('unary round trip (handler ⇄ client, no network)', () => { if (!response.result.ok) expect(response.result.error.code).toBe('session-not-found') }) - it('covers create/prompt/cancel/describe passthrough', async () => { + it('covers create/prompt/cancel/permissions/setPermission/describe passthrough', async () => { const c = client() expect((await c.sessions.create({})).result.ok).toBe(true) expect((await c.sessions.prompt({ sessionId: 's' as never, mode: 'queue', content: [{ type: 'text', text: 'x' }] })).result.ok).toBe(true) expect((await c.sessions.cancel({ sessionId: 's' as never })).result.ok).toBe(true) + expect((await c.sessions.permissions({ sessionId: 's' as never })).result.ok).toBe(true) + expect((await c.sessions.setPermission({ sessionId: 's' as never, value: 'workspace-write' })).result.ok).toBe(true) expect((await c.host.describe({})).result.ok).toBe(true) }) }) diff --git a/packages/host/runtime/README.md b/packages/host/runtime/README.md index f7cf7d9de8..c1817d8c6f 100644 --- a/packages/host/runtime/README.md +++ b/packages/host/runtime/README.md @@ -1,6 +1,6 @@ # @deepseek-ai/dsh-host-runtime -Host runtime assembly for `dsh`: `bootHost` composes the core plugin spine (LLM service + DeepSeek adapter, sessions with JSONL persistence and immediate fallback titles, optional first-message model summaries, system prompt, tools, agents, agent loop, workspace instructions, local bash, and the provider-neutral user-interaction service), `createApiProxy` implements the [`dsh-host-apiproxy`](../apiproxy/README.md) contract over that composition, and `startHost` is the one-step shell seam returning `{ api, handler, defaults, ctx, dispose }`. +Host runtime assembly for `dsh`: `bootHost` composes the core plugin spine (LLM service + DeepSeek adapter, sessions with JSONL persistence and immediate fallback titles, optional first-message model summaries, system prompt, tools, agents, agent loop, workspace instructions, the provider-neutral user-interaction service, and the sandboxed product path — `dsh-sandbox-local` + `dsh-sandbox-policy` behind the confined `dsh-bash-sandbox`/`dsh-fs-sandbox` families, with `dsh-user-approval` and `dsh-permission` on top), `createApiProxy` implements the [`dsh-host-apiproxy`](../apiproxy/README.md) contract over that composition, and `startHost` is the one-step shell seam returning `{ api, handler, defaults, ctx, dispose }`. Which plugins mount and with what defaults is decided only here — shells must not `ctx.plugin` to alter the assembly. `RunningHost.ctx` is a formal seam with exactly two sanctioned uses: mounting protocol front-door plugins (e.g. a future `dsh acp`) and headless session-event subscription; consuming clients must not bypass `api` through it. @@ -15,11 +15,15 @@ Which plugins mount and with what defaults is decided only here — shells must | `cwd` | `process.cwd()` | Default project directory for a session whose create request omits `cwd`. | | `sessionTitle` | 5 words / 40 fallback bytes / 80 accepted bytes | Deterministic fallback and accepted-title limits. | | `sessionTitleLlm` | disabled | `true` enables the 5-word / 10-CJK-character, 4,096-input-byte, 64-output-token, 60-second first-message policy; an explicit config overrides it. An omitted route inherits the logged main-request provider and model. | +| `sandbox.mode` | `'workspace-write'` | File-sandbox mode sessions start from (`ctx.sandboxPolicy` default; per-session switches ride `sandbox/mode` events). | +| `sandbox.approvalPolicy` | `'ask'` | Approval policy for sessions without an `approval/policy` override. | ## ApiProxy implementation notes Unary methods take the narrow `RpcRequest

` and echo `request.rpcId`; a prompt's rpcId rides `MessageSource` into the `user/message` event so clients can promote optimistic echoes. `history`/`prompt` on a cold session implicitly resume it, deduplicating concurrent calls through an in-flight table; `history` paginates backwards on message boundaries (never mid-message). The mux stream replays a `session/subscribed` baseline per attached session and every still-pending question with its original rpcId. Question responses, including blank per-item answers, are validated against the owning session and exact request before an atomic first-wins claim; answer, whole-request cancellation, owner abort, and provider disposal broadcast `question/resolved`. The host stream carries session lifecycle, running flips, and `agent/error` as the only outlet for live failures with no turn position. +The proxy is also the approval channel for the agents this host owns: an ask through `ctx.approval` becomes an answerable `approval/requested` mux frame with a stable rpcId held in a pending table, replayed verbatim on every mux open until settled. `respond` routes by the echoed rpcId (approvals first, then questions), validates the `ApprovalResponsePayload` audit correlation at the wire boundary, resolves the answerer, and broadcasts `approval/resolved`; the ask's own abort signal withdraws the question as `cancelled`. `session.permissions`/`session.setPermission` project `ctx.permission` (empty select when not composed); idle switches are held last-write-wins and flushed into the next prompted turn on `agent/prompt-submit`, because knob events must stay turn-enclosed for durable replay (the ACP bridge's anchoring pattern). + ## Model Experience Indirectly, through the non-blocking first-message title request owned by [`dsh-session-title-llm`](../../session-title/session-title-llm/README.md) when `sessionTitleLlm` is enabled, the provider/model defaults injected into created and resumed agents, the other model-facing plugins `bootHost` mounts, and the logged [workspace-instruction prefix](../../context/workspace-context/README.md#prompt-shape) when `workspaceContext` is enabled. @@ -30,6 +34,6 @@ No main-request invalidation; when enabled, the auxiliary title request has its ## Known Limitations and Deferred Work -- **Question waits are process-memory state** — browser reconnects recover them, but a host process restart aborts the owning tool call instead of restoring the wait from persistence. +- **Question and approval waits are process-memory state** — browser reconnects recover them, but a host process restart aborts the owning tool call instead of restoring the wait from persistence. - **`host.describe.version` is a placeholder** — it does not yet report the `apps/cli` package version. - **The assembly is fixed** — per-deployment plugin selection (user profile, log sinks, alternative persistence) has a documented home here but no configuration surface yet. diff --git a/packages/host/runtime/package.json b/packages/host/runtime/package.json index 94a544fb74..47327683b8 100644 --- a/packages/host/runtime/package.json +++ b/packages/host/runtime/package.json @@ -31,13 +31,17 @@ "@cordisjs/plugin-timer": "workspace:^", "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-loop": "workspace:^", - "@deepseek-ai/dsh-bash-local": "workspace:^", + "@deepseek-ai/dsh-bash-sandbox": "workspace:^", "@deepseek-ai/dsh-compact-basic": "workspace:^", - "@deepseek-ai/dsh-fs-local": "workspace:^", "@deepseek-ai/dsh-fs-policy": "workspace:^", + "@deepseek-ai/dsh-fs-sandbox": "workspace:^", "@deepseek-ai/dsh-host-apiproxy": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-llm-deepseek": "workspace:^", + "@deepseek-ai/dsh-permission": "workspace:^", + "@deepseek-ai/dsh-sandbox": "workspace:^", + "@deepseek-ai/dsh-sandbox-local": "workspace:^", + "@deepseek-ai/dsh-sandbox-policy": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-persistence": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", @@ -63,6 +67,7 @@ "@deepseek-ai/dsh-tool-todo": "workspace:^", "@deepseek-ai/dsh-tool-workflow": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", + "@deepseek-ai/dsh-user-approval": "workspace:^", "@deepseek-ai/dsh-user-interaction": "workspace:^", "@deepseek-ai/dsh-workflow-workerthread": "workspace:^", "@deepseek-ai/dsh-workspace-context": "workspace:^" diff --git a/packages/host/runtime/src/api-proxy.ts b/packages/host/runtime/src/api-proxy.ts index 3792d17da3..4cf8af1d65 100644 --- a/packages/host/runtime/src/api-proxy.ts +++ b/packages/host/runtime/src/api-proxy.ts @@ -1,19 +1,31 @@ /** - * Host-side ApiProxy implementation. Signature discipline: unary takes the - * narrow RpcRequest

and echoes request.rpcId on the RpcResponse. + * Host-side ApiProxy implementation. Unary methods, both streams, and the + * pending-interaction registries are real: the approval registry turns + * `ctx.approval` asks into answerable `approval/requested` mux frames and the + * question provider does the same for `ask_user_question`; both are answered + * through `respond` (routed by the echoed rpcId). Signature discipline: unary + * takes the narrow RpcRequest

and echoes request.rpcId on the RpcResponse. */ import { randomUUID } from 'node:crypto' import { mkdir, stat } from 'node:fs/promises' import type { Context } from 'cordis' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' +import type { CallId } from '@deepseek-ai/dsh-llm' import type { ContentBlock, MessageSource } from '@deepseek-ai/dsh-llm' +import { hasOpenTurn } from '@deepseek-ai/dsh-session' import type { JsonValue, Session, SessionEvent, SessionHeader, SessionId } from '@deepseek-ai/dsh-session' import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence' import { foldSessionTitle } from '@deepseek-ai/dsh-session-title' +import type { ApprovalOutcome, ApprovalRequestId } from '@deepseek-ai/dsh-user-approval' +// Side-effect type imports: resolve `ctx.approval` / `ctx.get('permission')` +// without value dependencies on the seams (both are optional compositions here). +import type {} from '@deepseek-ai/dsh-user-approval' +import type {} from '@deepseek-ai/dsh-permission' import type { ApiProxy, HistoryEntry, HostFrame, MuxFrame, QuestionResponsePayload, SessionSummary, ToolEventView, } from '@deepseek-ai/dsh-host-apiproxy/api' +import { approvalResponsePayloadSchema } from '@deepseek-ai/dsh-host-apiproxy/api/approvals.schema' import { questionResponsePayloadSchema } from '@deepseek-ai/dsh-host-apiproxy/api/questions.schema' import type { ClientResponse, RpcError, RpcReceipt, RpcRequest, RpcResponse } from '@deepseek-ai/dsh-host-apiproxy/api/rpc' import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc' @@ -183,6 +195,36 @@ interface ToolCallData { callId: string; name: string; arguments: string } /** The tool/result payload fields the presenter path reads. */ interface ToolResultData { callId: string; content: ContentBlock[]; isError: boolean; meta?: JsonValue } +/** + * 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 { + 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 @@ -283,6 +325,7 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro /** Implicit resume of cold sessions, deduplicating concurrent calls (follows the jsonrpc sessionCreations precedent). */ const resumes = new Map>() const pendingQuestions = new Map() + const pendingApprovals = new Map() const muxQueues = new Set>>() /** Send one transient frame to every connected mux consumer. */ @@ -341,6 +384,95 @@ 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) { + ctx.on('approval/request', (req, next) => { + // 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() + for (const entry of pendingApprovals.values()) claimed.add(entry.approvalId) + const decided = new Set() + 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 + if (req.callId !== undefined && event.data.callId !== req.callId) 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((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) + }) + }) + } + + // --- Permission switch anchoring ---------------------------------------- + // Knob events (`permission/preset`, `sandbox/mode`, `approval/policy`) must + // be turn-enclosed for durable replay, so an idle switch is held here + // last-write-wins and flushed when the next prompted turn opens (the ACP + // bridge's pendingSwitches pattern; prompt-submit is inside the new turn but + // before prompt assembly, so the switch is visible to that turn's request). + const pendingSwitches = new Map() + ctx.on('agent/prompt-submit', (agent, _content, _source, _signal, next) => { + const preset = pendingSwitches.get(agent.session.id) + if (preset !== undefined) { + pendingSwitches.delete(agent.session.id) + const presets = ctx.get('permission') + /* v8 ignore next -- a pending preset exists only if setPermission saw the + service; it cannot unmount between that and the next turn here. */ + if (presets !== undefined) presets.set(agent.session, preset) + } + return next() + }) + ctx.on('session/disposed', (session: Session) => { + pendingSwitches.delete(session.id) + }) + /** * 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 @@ -468,6 +600,48 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro agent.cancel() return Promise.resolve(ok(request, { accepted: true as const })) }, + + async permissions(request) { + const { sessionId } = request.payload + const presets = ctx.get('permission') + // A permission-less composition advertises an empty select (client + // hides the control) rather than erroring — the control's absence is + // deployment shape, not a caller mistake. + if (presets === undefined) return ok(request, { options: [], currentValue: 'custom' }) + const found = await agentFor(sessionId) + if ('error' in found) return err(request, found.error) + const events = found.agent.session.events + const currentValue = pendingSwitches.get(sessionId) ?? presets.current(events) + const options = [ + ...presets.names.map(name => presets.optionOf(name)), + // `custom` echoes the current derived state but is never a target. + ...currentValue === 'custom' ? [presets.optionOf('custom')] : [], + ] + return ok(request, { options, currentValue }) + }, + + async setPermission(request) { + const { sessionId, value } = request.payload + const presets = ctx.get('permission') + if (presets === undefined) { + return err(request, { code: 'bad-request', message: 'no permission service is composed on this host', details: { issues: [] } }) + } + const found = await agentFor(sessionId) + if ('error' in found) return err(request, found.error) + const agent = found.agent + // A current-value echo is acknowledged without recording a switch. + const current = pendingSwitches.get(sessionId) ?? presets.current(agent.session.events) + if (value === current) return ok(request, { currentValue: value }) + if (!presets.names.includes(value)) { + return err(request, { code: 'bad-request', message: `unknown permission value ${JSON.stringify(value)}`, details: { issues: [] } }) + } + // Turn-anchoring (the ACP bridge pattern): knob events must be enclosed + // by the durable log's turn boundary, so an idle switch is held + // last-write-wins and flushed into the next prompted turn. + if (hasOpenTurn(agent.session.events)) presets.set(agent.session, value) + else pendingSwitches.set(sessionId, value) + return ok(request, { currentValue: value }) + }, }, host: { @@ -499,6 +673,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)) // Per-session open-call table for result-view pairing. Bounded by the // per-turn call count: entries clear on turn/end; a table miss (stream // opened mid-turn) backscans the session's in-memory events instead. @@ -564,6 +741,20 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro }, respond(message: ClientResponse): Promise { + // 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) { diff --git a/packages/host/runtime/src/boot.ts b/packages/host/runtime/src/boot.ts index c0960ab678..3417956f62 100644 --- a/packages/host/runtime/src/boot.ts +++ b/packages/host/runtime/src/boot.ts @@ -18,11 +18,17 @@ import TaskService from '@deepseek-ai/dsh-tasks' import AgentLoop from '@deepseek-ai/dsh-agent-loop' import * as LlmDeepSeek from '@deepseek-ai/dsh-llm-deepseek' import SessionPersistenceJsonl from '@deepseek-ai/dsh-session-persistence-jsonl' -import LocalBashExecutor from '@deepseek-ai/dsh-bash-local' +import SandboxLocal from '@deepseek-ai/dsh-sandbox-local' +import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' +import type { SandboxMode } from '@deepseek-ai/dsh-sandbox' +import SandboxBashExecutor from '@deepseek-ai/dsh-bash-sandbox' +import ApprovalService from '@deepseek-ai/dsh-user-approval' +import type { ApprovalPolicy } from '@deepseek-ai/dsh-user-approval' +import PermissionService from '@deepseek-ai/dsh-permission' import * as toolBash from '@deepseek-ai/dsh-tool-bash' import * as toolTodo from '@deepseek-ai/dsh-tool-todo' import * as toolTasks from '@deepseek-ai/dsh-tool-tasks' -import FsLocal from '@deepseek-ai/dsh-fs-local' +import FsSandbox from '@deepseek-ai/dsh-fs-sandbox' import * as fsPolicy from '@deepseek-ai/dsh-fs-policy' import * as toolFs from '@deepseek-ai/dsh-tool-fs' import * as toolFsSearch from '@deepseek-ai/dsh-tool-fs-search' @@ -73,6 +79,17 @@ export interface BootHostOptions { sessionTitle?: SessionTitleConfig /** Opt-in first-message model-title policy; `true` selects host defaults and an explicit config overrides them. */ sessionTitleLlm?: true | SessionTitleLlmConfig + /** + * Sandbox/approval composition knobs. The host always composes the confined + * bash + fs families over `ctx.sandboxPolicy` (the acp-agent composition); + * these fields choose the deployment defaults every session starts from. + */ + sandbox?: { + /** File-sandbox mode sessions start from (default `workspace-write`). */ + mode?: SandboxMode + /** Approval policy for sessions without an override (default `ask`). */ + approvalPolicy?: ApprovalPolicy + } /** * Default project directory for sessions created without an explicit cwd * (defaults to the host process working directory). A session's cwd is its @@ -131,16 +148,30 @@ export async function bootHost(options: BootHostOptions): Promise { await ctx.plugin(AgentLoop, { agents: [] }) await ctx.plugin(LlmDeepSeek, {}) await ctx.plugin(SessionPersistenceJsonl, { root: options.persistenceRoot }) - await ctx.plugin(LocalBashExecutor, {}) + // The sandboxed product path (the acp-agent composition, sandbox Agent + // Note): per-platform runner provider, the shared policy home, the confined + // bash executor, and the approval seam its escalation asks through. Sessions + // start from the configured default mode; per-session switches ride the + // `sandbox/mode` / `approval/policy` events written by ctx.permission. + await ctx.plugin(SandboxLocal, {}) + await ctx.plugin(SandboxPolicy, { + mode: options.sandbox?.mode ?? 'workspace-write', + workspaceRoot: defaults.cwd, + }) + await ctx.plugin(SandboxBashExecutor, {}) + await ctx.plugin(ApprovalService, { policy: options.sandbox?.approvalPolicy ?? 'ask' }) // Tool suite mirroring the demo:repl composition (repl-agent/cordis.yml + // the agent-spine bundle) so web sessions get the same coding-agent tool // face; deviations are noted inline. await ctx.plugin(toolBash, {}) + // Presets over the two knobs (requires the confining executor + approval). + await ctx.plugin(PermissionService, {}) await ctx.plugin(toolTodo) await ctx.plugin(toolTasks, {}) // fs paths resolve against the host default project rather than the raw - // process cwd — the same source create() injects into session.cwd. - await ctx.plugin(FsLocal, { cwd: defaults.cwd }) + // process cwd — the same source create() injects into session.cwd. The + // sandboxed backend fences write/edit by the same policy as bash. + await ctx.plugin(FsSandbox, { cwd: defaults.cwd }) await ctx.plugin(fsPolicy) await ctx.plugin(toolFs, {}) await ctx.plugin(toolFsSearch, {}) diff --git a/packages/host/runtime/tests/api-proxy-approval.spec.ts b/packages/host/runtime/tests/api-proxy-approval.spec.ts new file mode 100644 index 0000000000..e0cb0c71e5 --- /dev/null +++ b/packages/host/runtime/tests/api-proxy-approval.spec.ts @@ -0,0 +1,275 @@ +/** + * 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' }) + 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[]; waitFor(type: MuxFrame['type']): Promise } { + const frames: MuxFrame[] = [] + const envelopes: RpcRequest[] = [] + 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 { + 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 { + 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[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 + 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 + 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 + 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 + + // 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 + + 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('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 + 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 + const frameB = frames.find(e => requestedOf(e.payload).callId === 'call-b') as RpcRequest + // 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 + const frameB = frames.find(e => requestedOf(e.payload).toolName === 'beta') as RpcRequest + // 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') + }) +}) diff --git a/packages/host/runtime/tests/api-proxy-permission.spec.ts b/packages/host/runtime/tests/api-proxy-permission.spec.ts new file mode 100644 index 0000000000..472a49a52b --- /dev/null +++ b/packages/host/runtime/tests/api-proxy-permission.spec.ts @@ -0,0 +1,152 @@ +/** + * Permission select over the proxy: permissions() projects the preset table + * plus the derived current value (custom shown only when derived), + * setPermission() validates against the table and anchors idle switches to + * the next prompted turn (the ACP bridge's pendingSwitches pattern), and a + * permission-less composition serves an empty select instead of an error. + */ + +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 PermissionService from '@deepseek-ai/dsh-permission' +import type { ApiProxy, RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api' +import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc' +import type { SessionId } from '@deepseek-ai/dsh-session' +import { createApiProxy } from '../src/api-proxy.ts' + +let nextRpc = 1 +function request

(payload: P): RpcRequest

{ + return { rpcId: RpcId(`req-${String(nextRpc++)}`), payload } +} + +async function harness(options: { permission?: boolean } = {}): Promise<{ ctx: Context; api: ApiProxy; sessionId: SessionId }> { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SystemPrompt, { persona: '' }) + await ctx.plugin(UserInteractionService) + await ctx.plugin(AgentRegistry) + if (options.permission !== false) { + // The permission service requires a confining executor fact + approval. + ctx.provide('bash', { + sandboxMode: 'workspace-write', + resolve() { throw new Error('permission proxy tests do not execute bash') }, + run() { throw new Error('permission proxy tests do not execute bash') }, + start() { throw new Error('permission proxy tests do not execute bash') }, + }) + await ctx.plugin(ApprovalService) + await ctx.plugin(PermissionService, {}) + } + const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp' }) + // No agent-loop in this harness: register a bare live agent directly (the + // proxy only reaches `.session`); api-proxy-view.spec.ts precedent. + const session = ctx.sessions.create() + ctx.agents.register({ id: session.id, session, status: 'idle', ctx } as Agent) + return { ctx, api, sessionId: session.id } +} + +function expectOk(response: { result: { ok: true; value: T } | { ok: false } }): T { + expect(response.result.ok).toBe(true) + if (!response.result.ok) throw new Error('unreachable') + return response.result.value +} + +describe('session.permissions', () => { + it('projects the preset table with the effective current value; custom is absent when a preset matches', async () => { + const { api, sessionId } = await harness() + const value = expectOk<{ options: { value: string }[]; currentValue: string }>( + await api.sessions.permissions(request({ sessionId }))) + expect(value.currentValue).toBe('workspace-write') + expect(value.options.map(o => o.value)).toEqual(['workspace-write', 'danger-full-access']) + }) + + it('serves an empty select (custom) on a permission-less composition', async () => { + const { api, sessionId } = await harness({ permission: false }) + const value = expectOk<{ options: unknown[]; currentValue: string }>( + await api.sessions.permissions(request({ sessionId }))) + expect(value).toEqual({ options: [], currentValue: 'custom' }) + }) + + it('appends the derived custom option when the knobs match no preset', async () => { + const { ctx, api, sessionId } = await harness() + const agent = ctx.agents.get(sessionId) + agent?.session.append('sandbox/mode', { mode: 'read-only' }) + const value = expectOk<{ options: { value: string }[]; currentValue: string }>( + await api.sessions.permissions(request({ sessionId }))) + expect(value.currentValue).toBe('custom') + expect(value.options.map(o => o.value)).toEqual(['workspace-write', 'danger-full-access', 'custom']) + }) + + it('propagates the agentFor error for a ghost session (persistence-less harness: internal)', async () => { + // The not-found/internal split is agentFor's documented gate and already + // covered by the history specs; here only the pass-through matters. + const { api } = await harness() + const response = await api.sessions.permissions(request({ sessionId: 'session-void' as SessionId })) + expect(response.result.ok).toBe(false) + }) +}) + +describe('session.setPermission', () => { + it('holds an idle switch pending (visible in permissions()) and flushes it into the next prompted turn', async () => { + const { ctx, api, sessionId } = await harness() + const agent = ctx.agents.get(sessionId) + expect(agent).toBeDefined() + const switched = expectOk<{ currentValue: string }>( + await api.sessions.setPermission(request({ sessionId, value: 'danger-full-access' }))) + expect(switched.currentValue).toBe('danger-full-access') + // No turn open: nothing appended yet; the pending value masks the fold. + expect(agent?.session.events.some(e => e.type === 'permission/preset')).toBe(false) + const echoed = expectOk<{ currentValue: string }>( + await api.sessions.permissions(request({ sessionId }))) + expect(echoed.currentValue).toBe('danger-full-access') + + // The waterfall flush path: prompt-submit inside the new turn writes through. + agent?.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) + await ctx.waterfall('agent/prompt-submit', agent as never, [], { kind: 'user' } as never, new AbortController().signal, () => Promise.resolve({ kind: 'allow' as const })) + expect(agent?.session.events.map(e => e.type)).toContain('permission/preset') + expect(agent?.session.events.map(e => e.type)).toContain('sandbox/mode') + expect(agent?.session.events.map(e => e.type)).toContain('approval/policy') + }) + + it('writes through immediately inside an open turn', async () => { + const { ctx, api, sessionId } = await harness() + const agent = ctx.agents.get(sessionId) + agent?.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) + expectOk(await api.sessions.setPermission(request({ sessionId, value: 'danger-full-access' }))) + expect(agent?.session.events.map(e => e.type)).toContain('permission/preset') + }) + + it('acknowledges a current-value echo without recording a switch', async () => { + const { ctx, api, sessionId } = await harness() + const agent = ctx.agents.get(sessionId) + agent?.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) + const echoed = expectOk<{ currentValue: string }>( + await api.sessions.setPermission(request({ sessionId, value: 'workspace-write' }))) + expect(echoed.currentValue).toBe('workspace-write') + expect(agent?.session.events.some(e => e.type === 'permission/preset')).toBe(false) + }) + + it('propagates the agentFor error for a ghost session', async () => { + const { api } = await harness() + const response = await api.sessions.setPermission(request({ sessionId: 'session-void' as SessionId, value: 'workspace-write' })) + expect(response.result.ok).toBe(false) + }) + + it('rejects unknown values (custom included) and a permission-less composition as bad-request', async () => { + const { api, sessionId } = await harness() + for (const value of ['custom', 'nope']) { + const response = await api.sessions.setPermission(request({ sessionId, value })) + expect(response.result.ok).toBe(false) + if (!response.result.ok) expect(response.result.error.code).toBe('bad-request') + } + const bare = await harness({ permission: false }) + const response = await bare.api.sessions.setPermission(request({ sessionId: bare.sessionId, value: 'workspace-write' })) + expect(response.result.ok).toBe(false) + if (!response.result.ok) expect(response.result.error.code).toBe('bad-request') + }) +}) diff --git a/packages/host/runtime/tsconfig.json b/packages/host/runtime/tsconfig.json index aee28b5371..da3d934a17 100644 --- a/packages/host/runtime/tsconfig.json +++ b/packages/host/runtime/tsconfig.json @@ -48,16 +48,31 @@ "path": "../../session-persistence/session-persistence-jsonl" }, { - "path": "../../bash/bash-local" + "path": "../../bash/bash-sandbox" }, { "path": "../../bash/tool-bash" }, + { + "path": "../../sandbox/sandbox" + }, + { + "path": "../../sandbox/sandbox-local" + }, + { + "path": "../../sandbox/sandbox-policy" + }, + { + "path": "../../ui/user-approval" + }, + { + "path": "../../ui/permission" + }, { "path": "../../compact/compact-basic" }, { - "path": "../../fs/fs-local" + "path": "../../fs/fs-sandbox" }, { "path": "../../fs/fs-policy" diff --git a/packages/ui/acp/src/index.ts b/packages/ui/acp/src/index.ts index 8a731a1bf6..74127261bd 100644 --- a/packages/ui/acp/src/index.ts +++ b/packages/ui/acp/src/index.ts @@ -60,7 +60,7 @@ import { } from '@deepseek-ai/dsh-agent' import type {} from '@deepseek-ai/dsh-commands' import { encodeSessionReferenceUri } from '@deepseek-ai/dsh-session-reference' -import { displayPromptContent, SessionId, type JsonValue } from '@deepseek-ai/dsh-session' +import { displayPromptContent, hasOpenTurn, SessionId, type JsonValue } from '@deepseek-ai/dsh-session' // Side-effect type import: resolves `ctx.get('permission')` to the service. import type {} from '@deepseek-ai/dsh-permission' import type { SessionEvent, TodoItem, TurnEndReason } from '@deepseek-ai/dsh-session' @@ -708,17 +708,6 @@ export function apply(ctx: Context, config: AcpConfig): void { }] } - /** Whether the log has an open turn in which a config switch can be enclosed. */ - const isTurnOpen = (agent: Agent): boolean => { - const events = agent.session.events - for (let index = events.length - 1; index >= 0; index -= 1) { - const type = (events[index] as SessionEvent).type - if (type === 'turn/start') return true - if (type === 'turn/end') return false - } - return false - } - /** Anchor last-write-wins idle switches into a just-opened turn. */ const flushPendingSwitches = (rec: SessionRecord): void => { const pending = rec.pendingSwitches @@ -1159,7 +1148,7 @@ export function apply(ctx: Context, config: AcpConfig): void { if (!presets.names.includes(params.value)) { throw invalidParams(`unknown permission value ${JSON.stringify(params.value)}`) } - if (isTurnOpen(rec.agent)) presets.set(rec.agent.session, params.value) + if (hasOpenTurn(rec.agent.session.events)) presets.set(rec.agent.session, params.value) else rec.pendingSwitches.preset = params.value break } diff --git a/packages/ui/user-approval/src/index.ts b/packages/ui/user-approval/src/index.ts index 329fad33a7..45247b5d3f 100644 --- a/packages/ui/user-approval/src/index.ts +++ b/packages/ui/user-approval/src/index.ts @@ -11,6 +11,7 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import type { CallId } from '@deepseek-ai/dsh-llm' import { scopeTarget } from '@deepseek-ai/dsh-scope' import type { Scoped } from '@deepseek-ai/dsh-scope' +import { hasOpenTurn } from '@deepseek-ai/dsh-session' import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-system-prompt' @@ -138,22 +139,6 @@ export function effectiveApprovalPolicy(events: readonly SessionEvent[]): Approv return undefined } -/** - * Whether the log currently sits inside an open turn (a `turn/start` not yet - * closed by a `turn/end`) — the {@link ApprovalService.request} precondition. - * The audit pair must be turn-enclosed: the turn is the durable log's - * commit/replay boundary, so a bare event appended between turns is - * indistinguishable from a crash tail and silently dropped on reload. - */ -function hasOpenTurn(events: readonly SessionEvent[]): boolean { - for (let index = events.length - 1; index >= 0; index -= 1) { - const type = (events[index] as SessionEvent).type - if (type === 'turn/start') return true - if (type === 'turn/end') return false - } - return false -} - /** * Append the sole durable representation of a session policy override. Invalid * values throw before the log changes; consumers fold the new value on each read. diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 21eb750454..5083d449ab 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2091,18 +2091,18 @@ importers: '@deepseek-ai/dsh-agent-loop': specifier: workspace:^ version: link:../../core/agent-loop - '@deepseek-ai/dsh-bash-local': + '@deepseek-ai/dsh-bash-sandbox': specifier: workspace:^ - version: link:../../bash/bash-local + version: link:../../bash/bash-sandbox '@deepseek-ai/dsh-compact-basic': specifier: workspace:^ version: link:../../compact/compact-basic - '@deepseek-ai/dsh-fs-local': - specifier: workspace:^ - version: link:../../fs/fs-local '@deepseek-ai/dsh-fs-policy': specifier: workspace:^ version: link:../../fs/fs-policy + '@deepseek-ai/dsh-fs-sandbox': + specifier: workspace:^ + version: link:../../fs/fs-sandbox '@deepseek-ai/dsh-host-apiproxy': specifier: workspace:^ version: link:../apiproxy @@ -2112,6 +2112,18 @@ importers: '@deepseek-ai/dsh-llm-deepseek': specifier: workspace:^ version: link:../../llm/llm-deepseek + '@deepseek-ai/dsh-permission': + specifier: workspace:^ + version: link:../../ui/permission + '@deepseek-ai/dsh-sandbox': + specifier: workspace:^ + version: link:../../sandbox/sandbox + '@deepseek-ai/dsh-sandbox-local': + specifier: workspace:^ + version: link:../../sandbox/sandbox-local + '@deepseek-ai/dsh-sandbox-policy': + specifier: workspace:^ + version: link:../../sandbox/sandbox-policy '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session @@ -2187,6 +2199,9 @@ importers: '@deepseek-ai/dsh-tools': specifier: workspace:^ version: link:../../core/tools + '@deepseek-ai/dsh-user-approval': + specifier: workspace:^ + version: link:../../ui/user-approval '@deepseek-ai/dsh-user-interaction': specifier: workspace:^ version: link:../../ui/user-interaction From d2fea6d7894593d4a64f85bb1a1474f2996f6fec Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 14:40:13 +0800 Subject: [PATCH 02/93] fix(apiproxy): refuse non-JSON media types on /api POST bodies MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Browsers send "simple" POSTs (text/plain, form encodings) without a CORS preflight, so a malicious page could execute side-effectful RPCs blind — the response stays unreadable cross-origin, but session.prompt would still run. The carrier now answers 415 unless the declared media type is application/json, forcing every cross-site attempt into a preflight this server never answers. Raw-fetch specs gain the header; a new handler case proves the fence rejects before the impl runs. --- packages/host/apiproxy/README.i18n.yaml | 4 +-- packages/host/apiproxy/README.md | 2 +- packages/host/apiproxy/README.zh.md | 2 +- packages/host/apiproxy/src/fetch/handler.ts | 15 ++++++++-- .../apiproxy/tests/client-handler.spec.ts | 30 +++++++++++++++---- .../host/apiproxy/tests/fetch-carrier.spec.ts | 24 +++++++-------- 6 files changed, 53 insertions(+), 24 deletions(-) diff --git a/packages/host/apiproxy/README.i18n.yaml b/packages/host/apiproxy/README.i18n.yaml index 28ff470c0b..ede79d610b 100644 --- a/packages/host/apiproxy/README.i18n.yaml +++ b/packages/host/apiproxy/README.i18n.yaml @@ -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: d6db9a9541b0727b61dbe501f7234564ffef139e -README.zh.md: 4175c8fdb98aad2882718a2c95cd9e45825d787d +README.md: 63294100cd0dc62f9822a3ca9678c1034880169f +README.zh.md: 251b4b0356da5f1fb518d133a92f484da957b951 diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index d6db9a9541..63294100cd 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -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/` 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`/`ResponseValue`. Zod schemas anchor `satisfies z.ZodType>` 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/` 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`/`ResponseValue`. Zod schemas anchor `satisfies z.ZodType>` 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). diff --git a/packages/host/apiproxy/README.zh.md b/packages/host/apiproxy/README.zh.md index 4175c8fdb9..251b4b0356 100644 --- a/packages/host/apiproxy/README.zh.md +++ b/packages/host/apiproxy/README.zh.md @@ -6,7 +6,7 @@ ## 契约层(`/api`) -协议消息组成一个四象限可辨识联合:发起方 × 请求/响应,与物理通道解耦。四种消息分别是 `ClientRequest`(POST `/api/` 的请求体)、`ServerResponse`(该 POST 的响应体)、`ServerRequest`(SSE 帧)和 `ClientResponse`(POST `/api/respond` 的请求体)。响应始终回显对应请求的 `rpcId`,绝不签发新值。方法的参数与返回值结构只存在于领域接口签名(`SessionsApi`、`HostApi`、`EventsApi`)中;`RpcMethodMap` 注册方法,其他所有位置均通过 `RequestPayload`/`ResponseValue` 派生。Zod schema 以 `satisfies z.ZodType>` 锚定类型,并分两层解析:先解析信封,再解析业务载荷,随后按方法分发。业务错误由 `RpcResult` 的错误分支承载(`RpcErrorDetailsMap` 封闭错误码集合);HTTP 状态只表达载体层结果。 +协议消息组成一个四象限可辨识联合:发起方 × 请求/响应,与物理通道解耦。四种消息分别是 `ClientRequest`(POST `/api/` 的请求体)、`ServerResponse`(该 POST 的响应体)、`ServerRequest`(SSE 帧)和 `ClientResponse`(POST `/api/respond` 的请求体)。响应始终回显对应请求的 `rpcId`,绝不签发新值。方法的参数与返回值结构只存在于领域接口签名(`SessionsApi`、`HostApi`、`EventsApi`)中;`RpcMethodMap` 注册方法,其他所有位置均通过 `RequestPayload`/`ResponseValue` 派生。Zod schema 以 `satisfies z.ZodType>` 锚定类型,并分两层解析:先解析信封,再解析业务载荷,随后按方法分发。业务错误由 `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)中。 diff --git a/packages/host/apiproxy/src/fetch/handler.ts b/packages/host/apiproxy/src/fetch/handler.ts index f0535dc939..8160f9d69a 100644 --- a/packages/host/apiproxy/src/fetch/handler.ts +++ b/packages/host/apiproxy/src/fetch/handler.ts @@ -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' @@ -188,6 +188,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() diff --git a/packages/host/apiproxy/tests/client-handler.spec.ts b/packages/host/apiproxy/tests/client-handler.spec.ts index 2dbc962a00..0885b7b896 100644 --- a/packages/host/apiproxy/tests/client-handler.spec.ts +++ b/packages/host/apiproxy/tests/client-handler.spec.ts @@ -138,7 +138,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) @@ -149,13 +149,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') @@ -164,16 +164,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({ @@ -421,7 +439,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() }) diff --git a/packages/host/apiproxy/tests/fetch-carrier.spec.ts b/packages/host/apiproxy/tests/fetch-carrier.spec.ts index 0e6dc8dc4a..318dbc970e 100644 --- a/packages/host/apiproxy/tests/fetch-carrier.spec.ts +++ b/packages/host/apiproxy/tests/fetch-carrier.spec.ts @@ -223,7 +223,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 } } } @@ -248,7 +248,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 } } } @@ -260,18 +260,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') @@ -280,7 +280,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') @@ -288,7 +288,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) @@ -297,23 +297,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) }) }) From 01d68dee4e995a402fa6ebd7dcc511266e0c6300 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 14:56:45 +0800 Subject: [PATCH 03/93] fix(connection): fence every /api request behind one browser-trust check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The only browser-trust guard covered host.pickDirectory, while the consequential methods (session.prompt drives bash) accepted any Host — open to DNS rebinding, where a rebound page reads and writes the API as if same-origin and only the Host header betrays the attacker's domain. The pickDirectory-specific loopback guard becomes a prefix-wide fence: Host must be loopback or an exact host[:port] from the new trustedHosts config, an attached Origin must equal that authority, and explicit cross-site markers are refused; requests without browser markers (curl, tests, native clients) pass, because without a browser there is no confused deputy. The loopback-socket check is dropped — binding policy expresses reachability, and the fence is not an auth layer. The Agent Note records the full threat model and the alternatives. --- ...07-28-api-browser-trust-boundary.i18n.yaml | 6 + .../2026-07-28-api-browser-trust-boundary.md | 31 +++++ ...026-07-28-api-browser-trust-boundary.zh.md | 31 +++++ docs/config-catalog.md | 20 +++- packages/client/connection/README.i18n.yaml | 6 +- packages/client/connection/README.md | 4 + packages/client/connection/README.zh.md | 4 + packages/client/connection/package.json | 3 +- .../connection/src/api-request-trust.ts | 71 +++++++++++ packages/client/connection/src/index.ts | 31 ++++- .../connection/src/native-dialog-request.ts | 52 -------- .../tests/api-request-trust.spec.ts | 60 ++++++++++ .../tests/native-dialog-request.spec.ts | 57 --------- .../client/connection/tests/node-half.spec.ts | 112 ++++++++++++------ packages/host/apiproxy/README.i18n.yaml | 4 +- packages/host/apiproxy/README.md | 2 +- packages/host/apiproxy/README.zh.md | 2 +- pnpm-lock.yaml | 3 + 18 files changed, 339 insertions(+), 160 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md create mode 100644 .agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md create mode 100644 packages/client/connection/src/api-request-trust.ts delete mode 100644 packages/client/connection/src/native-dialog-request.ts create mode 100644 packages/client/connection/tests/api-request-trust.spec.ts delete mode 100644 packages/client/connection/tests/native-dialog-request.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml new file mode 100644 index 0000000000..11973b755f --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml @@ -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 .agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md +2026-07-28-api-browser-trust-boundary.md: c620f1a65e3890bbd2580415e55b25436fefe36e +2026-07-28-api-browser-trust-boundary.zh.md: 0452eff1017b2f70a00e67c5cfce8dba3a840539 diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md new file mode 100644 index 0000000000..c620f1a65e --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md @@ -0,0 +1,31 @@ +# Agent Note: One carrier-level browser-trust boundary for the whole /api surface + +Status: implemented + +English | [中文](2026-07-28-api-browser-trust-boundary.zh.md) + +## Problem + +The web GUI host serves `/api` over plain HTTP (default `127.0.0.1:3080`, `--host 0.0.0.0` supported), and the surface includes remote-code-execution-grade methods — `session.prompt` drives an agent that runs bash. A browser turns the operator into a confused deputy against such a local API in two classic ways: a malicious page fires a "simple" cross-site POST (`text/plain` — sent without a CORS preflight) whose side effects execute even though the response stays unreadable, and a DNS-rebound origin talks to the socket as if same-origin, making CORS inapplicable entirely, with only the `Host` header betraying the attacker's domain. Before this decision the system's only browser-trust check (`isTrustedNativeDialogRequest`: loopback socket + same-origin + loopback Host) guarded exactly one cosmetic route — `host.pickDirectory`, whose native dialog pops on the host's screen — while every consequential method was unguarded. Guarding per-RPC also could not survive the upcoming in-app directory browser, whose whole point is serving legitimately remote clients that a loopback rule would refuse. + +## Decision + +Enforce browser trust once, at the carrier, for the entire `/api` prefix — two halves in two stacked PRs: + +- **Media-type fence (dsh-host-apiproxy)**: every `/api` POST must declare `application/json`, else 415 before parsing. Cross-site "simple" requests thereby stop existing: any cross-site attempt is forced into a CORS preflight this server never answers. +- **Authority fence (dsh-client-connection, `src/api-request-trust.ts`)**: `Host` must be loopback or an exact `host[:port]` from the plugin's `trustedHosts` config (rebinding defense); an attached `Origin` must equal that authority; `sec-fetch-site: cross-site` is refused outright. Requests without browser markers pass — a non-browser client is the principal itself, not a deputy. `host.pickDirectory` loses its bespoke guard and rides the same fence. + +Two boundaries stay deliberately out of scope: reachability is the webserver binding's policy (`host: 127.0.0.1 | 0.0.0.0`), and authentication for genuinely remote deployments is deferred work recorded in the connection README — the fence is a confused-deputy defense, not an auth layer. The old guard's loopback-socket check was dropped rather than generalized: with binding expressing reachability and `trustedHosts` naming remote authorities, the socket address adds nothing a header fence does not already cover. + +## Alternatives considered + +- **Per-RPC guards (status quo extended).** Rejected: the guard list trails the method list forever, the highest-value methods were already unguarded, and a loopback rule on browse RPCs would break the remote deployments they exist for. +- **CORS headers + credential omission.** Rejected: we never want cross-origin reads at all, so answering preflights only widens the surface; refusing them is strictly stronger and simpler. +- **Auth tokens now.** Rejected for this change: token minting/storage/rotation is real product surface; the fence closes the browser-deputy holes today without pre-deciding the auth design. + +## Consequences + +- Any future `/api` method is covered by construction; there is no per-route trust decision left to forget. +- Non-loopback deployments must declare their serving authorities in `trustedHosts` or browsers are refused; plain curl-shape automation is unaffected either way. +- Clients must label POST bodies `application/json` (ours always did; raw-fetch tests gained the header). +- The trusted-network assumption of an unauthenticated `0.0.0.0` deployment is now documented instead of implicit. diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md new file mode 100644 index 0000000000..0452eff101 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md @@ -0,0 +1,31 @@ +# Agent Note:整个 /api 面共用一道载体级浏览器信任边界 + +状态:已实现 + +[English](2026-07-28-api-browser-trust-boundary.md) | 中文 + +## 问题 + +Web GUI 宿主以纯 HTTP 提供 `/api`(默认 `127.0.0.1:3080`,支持 `--host 0.0.0.0`),而这个面上有远程代码执行级别的方法——`session.prompt` 驱动的 agent 可以运行 bash。浏览器会用两种经典方式把操作者变成攻击此类本地 API 的"混淆代理人":恶意页面发出跨站"简单请求" POST(`text/plain`——不经 CORS 预检即发出),其副作用照常执行、只是响应不可读;以及 DNS rebinding 后的源以"同源"身份直连 socket,CORS 整体失效,只有 `Host` 头会暴露攻击者的域名。在本决策之前,系统里唯一的浏览器信任检查(`isTrustedNativeDialogRequest`:回环 socket + 同源 + 回环 Host)只守着一个装饰性的路由——`host.pickDirectory`,其原生对话框弹在宿主屏幕上——而所有真正要命的方法都在裸奔。按 RPC 逐个设防也活不过即将到来的应用内目录浏览器:它存在的意义就是服务合法的远程客户端,回环规则恰恰会拒绝它们。 + +## 决策 + +在载体层对整个 `/api` 前缀一次性执行浏览器信任检查——两半各占一个栈式 PR: + +- **媒体类型栅栏(dsh-host-apiproxy)**:每个 `/api` POST 必须声明 `application/json`,否则在解析前以 415 拒绝。跨站"简单请求"由此不复存在:任何跨站尝试都被逼进一次本服务器从不应答的 CORS 预检。 +- **权威栅栏(dsh-client-connection,`src/api-request-trust.ts`)**:`Host` 必须是回环地址,或与插件 `trustedHosts` 配置中的某个 `host[:port]` 精确匹配(rebinding 防御);若带 `Origin` 则必须与该权威完全一致;`sec-fetch-site: cross-site` 一律拒绝。不带浏览器标头的请求放行——非浏览器客户端是委托人本人,不是代理人。`host.pickDirectory` 失去专属守卫,与其他请求同栅而行。 + +两条边界刻意留在范围之外:可达性归 webserver 绑定配置(`host: 127.0.0.1 | 0.0.0.0`)管辖;真正远程部署的认证是延期工作,记录在 connection README——这道栅栏是混淆代理人防御,不是认证层。旧守卫的回环 socket 检查被放弃而非泛化:绑定表达可达性、`trustedHosts` 点名远程权威之后,socket 地址提供不了头部栅栏覆盖不到的任何东西。 + +## 曾考虑的替代方案 + +- **按 RPC 设防(延续现状)。** 否决:守卫清单永远追着方法清单跑,价值最高的方法本来就没被守住,而 browse RPC 上的回环规则会破坏它们为之存在的远程部署。 +- **CORS 头 + 省略凭据。** 否决:我们根本不想要任何跨源读取,应答预检只会扩大暴露面;拒绝预检严格更强也更简单。 +- **现在就上认证令牌。** 在本变更中否决:令牌的签发/存储/轮换是真实的产品面;栅栏今天就能封死浏览器代理人漏洞,无需预先决定认证设计。 + +## 后果 + +- 未来任何 `/api` 方法天然在覆盖范围内;不存在会被遗忘的按路由信任决定。 +- 非回环部署必须在 `trustedHosts` 中声明服务权威,否则浏览器会被拒绝;curl 形态的自动化不受影响。 +- 客户端必须给 POST 体标注 `application/json`(我们自己的客户端一向如此;裸 fetch 测试补上了该头)。 +- 无认证 `0.0.0.0` 部署的"信任网络"假设从隐含变为成文。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index b89a49529c..d30aff1f02 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -270,6 +270,25 @@ Depends on: [`agentCore`](../packages/examples/agent-spine-demo/src/index.ts) · Source: [`packages/examples/cli-demo/src/index.ts:26`](../packages/examples/cli-demo/src/index.ts) +## `@deepseek-ai/dsh-client-connection` + +Requires: `httpServer` · `apiProxy` + +```ts config-catalog +/** Plugin config: the deployment's non-loopback serving authorities. */ +export interface ConnectionConfig { + /** + * Exact `host[:port]` authorities this deployment serves beyond loopback. + * The /api trust fence refuses any request whose Host is neither loopback + * nor listed here, so a non-loopback (`0.0.0.0`) deployment must declare + * the names it is reached by. + */ + trustedHosts?: string[] +} +``` + +Source: [`packages/client/connection/src/index.ts:20`](../packages/client/connection/src/index.ts) + ## `@deepseek-ai/dsh-client-hmr` Requires: `clientModuleHost` · `httpServer` @@ -2143,7 +2162,6 @@ Source: [`packages/context/workspace-context/src/config.ts:17`](../packages/cont These load from a `cordis.yml` entry with no `config:` block; they declare no config surface. - `@deepseek-ai/dsh-agent` ([`packages/core/agent/src/index.ts`](../packages/core/agent/src/index.ts)) -- `@deepseek-ai/dsh-client-connection` — requires `httpServer` · `apiProxy` ([`packages/client/connection/src/index.ts`](../packages/client/connection/src/index.ts)) - `@deepseek-ai/dsh-client-locale` ([`packages/client/locale/src/index.ts`](../packages/client/locale/src/index.ts)) - `@deepseek-ai/dsh-client-modules` — requires `httpServer` · `loader` ([`packages/client/modules/src/index.ts`](../packages/client/modules/src/index.ts)) - `@deepseek-ai/dsh-client-runtime` ([`packages/client/runtime/src/index.ts`](../packages/client/runtime/src/index.ts)) diff --git a/packages/client/connection/README.i18n.yaml b/packages/client/connection/README.i18n.yaml index 0dd8860d65..5c5a825a27 100644 --- a/packages/client/connection/README.i18n.yaml +++ b/packages/client/connection/README.i18n.yaml @@ -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: 80228a180faba0c556ff720e999b29b5bb1635b6 -README.zh.md: f4b857886bfafa891ceb1bd6b79b27e1fb725819 +# pnpm run verify-translation-pairing --write packages/client/connection/README.md +README.md: a301b85d707d17d1e8159655b540556eee5c9d83 +README.zh.md: 88d7aa806167033308a9913053f621ecea07c3d8 diff --git a/packages/client/connection/README.md b/packages/client/connection/README.md index 80228a180f..a301b85d70 100644 --- a/packages/client/connection/README.md +++ b/packages/client/connection/README.md @@ -4,6 +4,10 @@ English | [中文](README.zh.md) Wire consumer layer: the client plugin's apply mounts `ctx.connection` (shared api client + single-consumer stream-loop starter); the export face carries the wire contract types, the `AbstractApiClient` seam, and the loop's sink/config types. The platform subclasses (WebApiClient/FixtureApiClient), the ConnectionController loop, and the fixture data source are package-internal — apply selects and drives them; tests reach them via src. Contract: api-contracts v3 §3. +## /api browser-trust fence + +The node half guards every request under `/api` before bridging (`src/api-request-trust.ts`): the `Host` header must be a loopback authority or an exact `host[:port]` entry from the plugin's `trustedHosts` config (DNS-rebinding defense), an attached `Origin` must equal that authority, and an explicit `sec-fetch-site: cross-site` marker is refused. Requests without browser markers (curl, tests, native clients) pass — without a browser there is no confused deputy. Failures answer plain 403 before any RPC dispatch. A non-loopback (`--host 0.0.0.0`) deployment must therefore list the authorities it is reached by in `trustedHosts`; the fence is deliberately not an authentication layer — reachability policy stays with the webserver binding, and auth remains deferred work. Decision record: [the api browser-trust boundary Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md). + ## Keyless fixture Any `fixture` query parameter selects the in-memory carrier. `fixture=empty` starts with no Workspace or Session; `fixturePrompt=reject` rejects prompts before acceptance; `fixtureAttach=fail` publishes a Session but rejects its Workspace attachment; `fixtureSessionCreate=drop-response` publishes and frames a Session before dropping the create response; and `fixtureFrames=workspace-first` reverses the default session-first create-frame order. Workspace creation by name/path and caller-preallocated SessionIds remain deterministic enough for assembled Web tests to reconcile list and frame arrival. diff --git a/packages/client/connection/README.zh.md b/packages/client/connection/README.zh.md index f4b857886b..88d7aa8061 100644 --- a/packages/client/connection/README.zh.md +++ b/packages/client/connection/README.zh.md @@ -4,6 +4,10 @@ 协议消费层:客户端插件的 apply 会挂载 `ctx.connection`(共享 API 客户端 + 单消费方流循环启动器);导出表层携带协议契约类型、`AbstractApiClient` seam,以及循环的 sink/配置类型。平台子类(WebApiClient/FixtureApiClient)、ConnectionController 循环和 fixture 数据源都属于包内部:apply 负责选择并驱动它们,测试则通过 src 访问。契约:api-contracts v3 §3。 +## /api 浏览器信任栅栏 + +node 半侧在桥接前守卫 `/api` 下的每个请求(`src/api-request-trust.ts`):`Host` 头必须是回环地址权威,或与插件 `trustedHosts` 配置中的某个 `host[:port]` 精确匹配(DNS rebinding 防御);若带有 `Origin` 则必须与该权威完全一致;显式的 `sec-fetch-site: cross-site` 标记一律拒绝。不带浏览器标头的请求(curl、测试、原生客户端)直接放行——没有浏览器就不存在"混淆代理人"。失败在任何 RPC 分发之前以纯 403 应答。因此非回环(`--host 0.0.0.0`)部署必须在 `trustedHosts` 中列出自己被访问时使用的权威;这道栅栏刻意不承担认证职责——可达性策略归 webserver 绑定配置,认证仍是延期工作。决策记录:[api 浏览器信任边界 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md)。 + ## 无密钥 fixture 任何 `fixture` 查询参数都会选择内存载体。`fixture=empty` 启动时不含 Workspace 或 Session;`fixturePrompt=reject` 在接受前拒绝提示词;`fixtureAttach=fail` 发布 Session 但拒绝将其附加到 Workspace;`fixtureSessionCreate=drop-response` 在丢弃创建响应前发布 Session 并为其发出帧;`fixtureFrames=workspace-first` 则反转默认的 Session 优先创建帧顺序。按名称/路径创建 Workspace 以及由调用方预先分配 SessionId,均具有足够的确定性,组装后的 Web 测试可以据此协调列表与帧的到达。 diff --git a/packages/client/connection/package.json b/packages/client/connection/package.json index c26cafb143..76aee0f06e 100644 --- a/packages/client/connection/package.json +++ b/packages/client/connection/package.json @@ -32,7 +32,8 @@ "@deepseek-ai/dsh-host-apiproxy": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", - "@deepseek-ai/dsh-tools": "workspace:^" + "@deepseek-ai/dsh-tools": "workspace:^", + "schemastery": "^3.18.0" }, "files": [ "lib/index.js", diff --git a/packages/client/connection/src/api-request-trust.ts b/packages/client/connection/src/api-request-trust.ts new file mode 100644 index 0000000000..37819b9fb9 --- /dev/null +++ b/packages/client/connection/src/api-request-trust.ts @@ -0,0 +1,71 @@ +/** + * Browser-trust fence for every /api request. Defends the two confused-deputy + * paths a browser opens against a local HTTP API — DNS rebinding (Host names + * the attacker's domain while the socket reaches this server) and cross-site + * requests fired from a malicious page — without blocking non-browser clients + * (no browser markers → no deputy to confuse) or legitimately remote browsers + * (their authority is declared via `trustedHosts`). Network reachability and + * authentication stay out of scope: binding policy belongs to the webserver + * config, and this fence is not an auth layer. + */ + +import type { IncomingHttpHeaders } from 'node:http' + +/** The request facts the fence reads (structural subset of IncomingMessage). */ +interface ApiTrustRequest { + headers: IncomingHttpHeaders +} + +function header(headers: IncomingHttpHeaders, name: string): string | undefined { + const value = headers[name] + return typeof value === 'string' ? value : undefined +} + +function isLoopbackHostname(hostname: string): boolean { + if (hostname === 'localhost' || hostname === '[::1]') return true + const parts = hostname.split('.') + return parts.length === 4 + && parts[0] === '127' + && parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255) +} + +/** Hostname of a Host-header authority (port stripped, lowercased, IPv6 bracketed), or undefined when unparsable. */ +function authorityHostname(authority: string): string | undefined { + try { + // http: is a WHATWG "special scheme": parsing yields a non-empty hostname or throws. + return new URL(`http://${authority}`).hostname + } catch { + return undefined + } +} + +/** + * Decide whether one /api request may reach the RPC bridge. + * @param request - node HTTP request facts (headers). + * @param trustedHosts - exact non-loopback `host[:port]` authorities this deployment serves. + * @returns true when the Host is ours and any browser markers are same-origin. + */ +export function isTrustedApiRequest(request: ApiTrustRequest, trustedHosts: readonly string[]): boolean { + // Host fence (DNS-rebinding defense): the browser fills Host from the URL it + // believes it is talking to, so a rebound page carries the attacker's domain + // here even though the socket lands on this server. + const host = header(request.headers, 'host') + if (host === undefined) return false + const hostname = authorityHostname(host) + if (hostname === undefined) return false + if (!isLoopbackHostname(hostname) && !trustedHosts.includes(host)) return false + // Cross-site fence: modern browsers label the initiator relationship on + // every fetch; an explicit cross-site marker is refused regardless of Origin. + if (header(request.headers, 'sec-fetch-site') === 'cross-site') return false + // Origin fence: when a browser attaches an Origin it must be exactly this + // authority. Absent Origin = non-browser client (curl, tests, native shells) + // — allowed, because without a browser there is no confused deputy. The + // literal "null" (sandboxed iframes, file: pages) is an opaque origin, refused. + const origin = header(request.headers, 'origin') + if (origin === undefined) return true + try { + return new URL(origin).host === host + } catch { + return false + } +} diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index bc73e0e054..77f463149e 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -1,11 +1,12 @@ /** Host HTTP bridge for browser-client RPC. */ import type { Context } from 'cordis' +import z from 'schemastery' // Activates the httpServer Context merge used below. import type { WebRoute } from '@deepseek-ai/dsh-host-webserver' import { toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy' import { API_PATH } from './api-path.ts' import { bridge } from './http-bridge.ts' -import { isTrustedNativeDialogRequest } from './native-dialog-request.ts' +import { isTrustedApiRequest } from './api-request-trust.ts' export { API_PATH } from './api-path.ts' @@ -15,19 +16,37 @@ export const name = 'client-connection' /** Services required before mounting the route. */ export const inject = ['httpServer', 'apiProxy'] +/** Plugin config: the deployment's non-loopback serving authorities. */ +export interface ConnectionConfig { + /** + * Exact `host[:port]` authorities this deployment serves beyond loopback. + * The /api trust fence refuses any request whose Host is neither loopback + * nor listed here, so a non-loopback (`0.0.0.0`) deployment must declare + * the names it is reached by. + */ + trustedHosts?: string[] +} + +export const Config: z = z.object({ + trustedHosts: z.array(String).default([]), +}) + /** - * Mounts the API gateway under the browser transport prefix. + * Mounts the API gateway under the browser transport prefix. Every request on + * the prefix passes the browser-trust fence first (DNS-rebinding and + * cross-site defense — [api-request-trust](./api-request-trust.ts)). * @param ctx - Host plugin context. + * @param config - resolved plugin config (schema defaults applied). */ -export function apply(ctx: Context): void { +export function apply(ctx: Context, config?: ConnectionConfig): void { + // The Loader resolves schema defaults; hand-built test contexts may pass none. + const trustedHosts = config?.trustedHosts ?? [] const apiHandler = toFetchHandler(ctx.apiProxy) const route: WebRoute = { kind: 'prefix', path: API_PATH, handler: async (req, res) => { - const pathname = new URL(req.url ?? '/', 'http://dsh.internal').pathname - if (pathname === `${API_PATH}/host.pickDirectory` - && !isTrustedNativeDialogRequest(req)) { + if (!isTrustedApiRequest(req, trustedHosts)) { res.writeHead(403) res.end('forbidden') return diff --git a/packages/client/connection/src/native-dialog-request.ts b/packages/client/connection/src/native-dialog-request.ts deleted file mode 100644 index fe91bbae2d..0000000000 --- a/packages/client/connection/src/native-dialog-request.ts +++ /dev/null @@ -1,52 +0,0 @@ -/** Trust check for browser requests that can open an operating-system dialog. */ - -import type { IncomingHttpHeaders } from 'node:http' - -interface NativeDialogRequest { - headers: IncomingHttpHeaders - socket: { remoteAddress?: string | undefined } -} - -function header(headers: IncomingHttpHeaders, name: string): string | undefined { - const value = headers[name] - return typeof value === 'string' ? value : undefined -} - -function isLoopback(address: string | undefined): boolean { - if (address === undefined) return false - if (address === '::1') return true - const ipv4 = address.startsWith('::ffff:') ? address.slice('::ffff:'.length) : address - const first = ipv4.split('.')[0] - return first === '127' -} - -function isLoopbackHostname(hostname: string): boolean { - if (hostname === 'localhost' || hostname === '[::1]' || hostname === '::1') return true - const parts = hostname.split('.') - return parts.length === 4 - && parts[0] === '127' - && parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255) -} - -/** - * Require a local socket plus browser-controlled same-origin metadata. - * @param request - the node HTTP request facts used by the carrier guard. - * @returns true only for a same-origin browser request whose peer and URL are loopback. - */ -export function isTrustedNativeDialogRequest(request: NativeDialogRequest): boolean { - if (!isLoopback(request.socket.remoteAddress)) return false - if (header(request.headers, 'sec-fetch-site') !== 'same-origin') return false - const origin = header(request.headers, 'origin') - const host = header(request.headers, 'host') - if (origin === undefined || host === undefined) return false - try { - const parsed = new URL(origin) - const hostUrl = new URL(`http://${host}`) - return (parsed.protocol === 'http:' || parsed.protocol === 'https:') - && parsed.host === host - && isLoopbackHostname(parsed.hostname) - && isLoopbackHostname(hostUrl.hostname) - } catch { - return false - } -} diff --git a/packages/client/connection/tests/api-request-trust.spec.ts b/packages/client/connection/tests/api-request-trust.spec.ts new file mode 100644 index 0000000000..eab878e734 --- /dev/null +++ b/packages/client/connection/tests/api-request-trust.spec.ts @@ -0,0 +1,60 @@ +/** Behavior of the /api browser-trust fence (rebinding + cross-site defense). */ + +import { describe, expect, it } from 'vitest' +import { isTrustedApiRequest } from '../src/api-request-trust.ts' + +function request(headers: Record): { headers: Record } { + return { headers } +} + +describe('isTrustedApiRequest', () => { + it('accepts loopback Hosts in every spelling, with and without ports', () => { + for (const host of ['localhost', 'localhost:3080', '127.0.0.1', '127.0.0.1:3080', '127.8.9.10:80', '[::1]', '[::1]:3080', 'LOCALHOST:3080']) { + expect(isTrustedApiRequest(request({ host }), [])).toBe(true) + } + }) + + it('accepts non-browser requests (no Origin, no sec-fetch-site) — curl, tests, native clients', () => { + expect(isTrustedApiRequest(request({ host: '127.0.0.1:3080' }), [])).toBe(true) + }) + + it('refuses a rebound Host: the attacker domain names the socket it did not expect', () => { + expect(isTrustedApiRequest(request({ + host: 'evil.example:3080', + origin: 'http://evil.example:3080', + 'sec-fetch-site': 'same-origin', + }), [])).toBe(false) + }) + + it('accepts a declared public authority only on exact host[:port] match', () => { + const headers = { host: 'harness.internal:3080', origin: 'http://harness.internal:3080' } + expect(isTrustedApiRequest(request(headers), ['harness.internal:3080'])).toBe(true) + expect(isTrustedApiRequest(request(headers), ['harness.internal'])).toBe(false) + expect(isTrustedApiRequest(request(headers), [])).toBe(false) + }) + + it('refuses cross-origin browser markers even on a loopback Host', () => { + // Origin present and different → cross-site request that survived preflight rules. + expect(isTrustedApiRequest(request({ host: '127.0.0.1:3080', origin: 'http://evil.example' }), [])).toBe(false) + // Explicit cross-site label → refused regardless of Origin. + expect(isTrustedApiRequest(request({ host: '127.0.0.1:3080', 'sec-fetch-site': 'cross-site' }), [])).toBe(false) + // Opaque origin (sandboxed iframe, file: page) parses to no authority. + expect(isTrustedApiRequest(request({ host: '127.0.0.1:3080', origin: 'null' }), [])).toBe(false) + }) + + it('accepts a same-origin browser request', () => { + expect(isTrustedApiRequest(request({ + host: 'localhost:3080', + origin: 'http://localhost:3080', + 'sec-fetch-site': 'same-origin', + }), [])).toBe(true) + }) + + it('refuses malformed authorities', () => { + expect(isTrustedApiRequest(request({}), [])).toBe(false) + expect(isTrustedApiRequest(request({ host: '' }), [])).toBe(false) + expect(isTrustedApiRequest(request({ host: 'bad host' }), [])).toBe(false) + expect(isTrustedApiRequest(request({ host: '127.0.0.999' }), [])).toBe(false) + expect(isTrustedApiRequest(request({ host: '128.0.0.1' }), [])).toBe(false) + }) +}) diff --git a/packages/client/connection/tests/native-dialog-request.spec.ts b/packages/client/connection/tests/native-dialog-request.spec.ts deleted file mode 100644 index 1a3d70dd15..0000000000 --- a/packages/client/connection/tests/native-dialog-request.spec.ts +++ /dev/null @@ -1,57 +0,0 @@ -import type { IncomingHttpHeaders } from 'node:http' -import { describe, expect, it } from 'vitest' -import { isTrustedNativeDialogRequest } from '../src/native-dialog-request.ts' - -function request( - remoteAddress: string | undefined, - headers: IncomingHttpHeaders = { - host: '127.0.0.1:3080', - origin: 'http://127.0.0.1:3080', - 'sec-fetch-site': 'same-origin', - }, -) { - return { socket: { remoteAddress }, headers } -} - -describe('native dialog request trust', () => { - it('accepts loopback same-origin browser requests', () => { - expect(isTrustedNativeDialogRequest(request('127.0.0.1'))).toBe(true) - expect(isTrustedNativeDialogRequest(request('::1', { - host: '[::1]:3080', origin: 'http://[::1]:3080', 'sec-fetch-site': 'same-origin', - }))).toBe(true) - expect(isTrustedNativeDialogRequest(request('::ffff:127.0.0.1'))).toBe(true) - expect(isTrustedNativeDialogRequest(request('127.0.0.1', { - host: 'localhost:3080', origin: 'http://localhost:3080', 'sec-fetch-site': 'same-origin', - }))).toBe(true) - expect(isTrustedNativeDialogRequest(request('127.0.0.2', { - host: '127.0.0.2:3080', origin: 'https://127.0.0.2:3080', 'sec-fetch-site': 'same-origin', - }))).toBe(true) - }) - - it('rejects remote sockets and requests without matching browser metadata', () => { - expect(isTrustedNativeDialogRequest(request('192.168.1.5'))).toBe(false) - expect(isTrustedNativeDialogRequest(request(undefined))).toBe(false) - expect(isTrustedNativeDialogRequest(request('127.0.0.1', { - host: '127.0.0.1:3080', origin: 'http://evil.example', 'sec-fetch-site': 'cross-site', - }))).toBe(false) - expect(isTrustedNativeDialogRequest(request('127.0.0.1', { - host: '127.0.0.1:3080', origin: 'http://localhost:3080', 'sec-fetch-site': 'same-origin', - }))).toBe(false) - expect(isTrustedNativeDialogRequest(request('127.0.0.1', { host: '127.0.0.1:3080' }))).toBe(false) - expect(isTrustedNativeDialogRequest(request('127.0.0.1', { - origin: 'http://127.0.0.1:3080', 'sec-fetch-site': 'same-origin', - }))).toBe(false) - expect(isTrustedNativeDialogRequest(request('127.0.0.1', { - host: 'attacker.example:3080', origin: 'http://attacker.example:3080', 'sec-fetch-site': 'same-origin', - }))).toBe(false) - expect(isTrustedNativeDialogRequest(request('127.0.0.1', { - host: '127.0.0.1:3080', origin: 'ftp://127.0.0.1:3080', 'sec-fetch-site': 'same-origin', - }))).toBe(false) - expect(isTrustedNativeDialogRequest(request('127.0.0.1', { - host: '127.999.0.1:3080', origin: 'http://127.999.0.1:3080', 'sec-fetch-site': 'same-origin', - }))).toBe(false) - expect(isTrustedNativeDialogRequest(request('127.0.0.1', { - host: '[invalid', origin: 'http://[invalid', 'sec-fetch-site': 'same-origin', - }))).toBe(false) - }) -}) diff --git a/packages/client/connection/tests/node-half.spec.ts b/packages/client/connection/tests/node-half.spec.ts index 86af61ba0d..a492a7a9c0 100644 --- a/packages/client/connection/tests/node-half.spec.ts +++ b/packages/client/connection/tests/node-half.spec.ts @@ -1,4 +1,6 @@ /** Node half: registers the /api prefix route bridging to the api gateway. */ +import { EventEmitter } from 'node:events' +import { Readable } from 'node:stream' import { Context } from 'cordis' import { describe, expect, it } from 'vitest' import type { IncomingMessage, ServerResponse } from 'node:http' @@ -6,46 +8,84 @@ import type { ApiProxy } from '@deepseek-ai/dsh-host-apiproxy/api' import type { HttpServerService, WebRoute } from '@deepseek-ai/dsh-host-webserver' import { API_PATH, apply, inject } from '../src/index.ts' +/** Structural httpServer fake: the plugin only touches register(). */ +function fakeHttpServer(routes: WebRoute[]): Pick { + return { + register(route) { + routes.push(route) + return () => { routes.splice(routes.indexOf(route), 1) } + }, + tapIndex: () => () => {}, + port: 0, + } +} + +/** Bodyless GET carrying the given headers (enough for the trust fence + bridge). */ +function fakeRequest(headers: Record): IncomingMessage { + const request = Readable.from([]) as unknown as IncomingMessage + Object.assign(request, { url: `${API_PATH}/session.list`, method: 'GET', headers }) + return request +} + +/** Response recorder compatible with both the fence's short-circuit and the bridge. */ +function fakeResponse(): { response: ServerResponse; state: { status?: number; body?: unknown } } { + const state: { status?: number; body?: unknown } = {} + const response = Object.assign(new EventEmitter(), { + writableEnded: false, + writeHead(value: number) { state.status = value; return this }, + write() { return true }, + end(this: { writableEnded: boolean }, value?: unknown) { + if (value !== undefined) state.body = value + this.writableEnded = true + return this + }, + }) as unknown as ServerResponse + return { response, state } +} + +async function mounted(config?: { trustedHosts?: string[] }): Promise<{ routes: WebRoute[]; dispose: () => Promise }> { + const ctx = new Context() + const routes: WebRoute[] = [] + ctx.provide('httpServer', fakeHttpServer(routes) as HttpServerService) + ctx.provide('apiProxy', {} as unknown as ApiProxy) + const fiber = ctx.plugin({ inject: [...inject], apply }, config) + await fiber.await() + return { routes, dispose: () => fiber.dispose() } +} + describe('connection node half', () => { it('registers the /api prefix route and removes it with the fiber', async () => { - const ctx = new Context() - const routes: WebRoute[] = [] - // Structural fake: the plugin only touches register(); the service class - // carries private state a literal cannot (and need not) reproduce. - const httpServer: Pick = { - register(route) { - routes.push(route) - return () => { routes.splice(routes.indexOf(route), 1) } - }, - tapIndex: () => () => {}, - port: 0, - } - ctx.provide('httpServer', httpServer as HttpServerService) - ctx.provide('apiProxy', {} as unknown as ApiProxy) - - const fiber = ctx.plugin({ inject: [...inject], apply }) - await fiber.await() + const { routes, dispose } = await mounted() expect(routes).toHaveLength(1) expect(routes[0]).toMatchObject({ kind: 'prefix', path: API_PATH }) - - let status: number | undefined - let body: unknown - const deniedRequest = { - url: '/api/host.pickDirectory', - headers: { - host: 'harness.example', origin: 'http://harness.example', 'sec-fetch-site': 'same-origin', - }, - socket: { remoteAddress: '192.168.1.8' }, - } as unknown as IncomingMessage - const deniedResponse = { - writeHead(value: number) { status = value; return this }, - end(value?: unknown) { body = value; return this }, - } as unknown as ServerResponse - await routes[0]!.handler(deniedRequest, deniedResponse) - expect(status).toBe(403) - expect(body).toBe('forbidden') - - await fiber.dispose() + await dispose() expect(routes).toHaveLength(0) }) + + it('refuses an untrusted Host on any /api path before the bridge runs', async () => { + const { routes, dispose } = await mounted() + const { response, state } = fakeResponse() + await routes[0]!.handler(fakeRequest({ + host: 'harness.example', origin: 'http://harness.example', 'sec-fetch-site': 'same-origin', + }), response) + expect(state.status).toBe(403) + expect(state.body).toBe('forbidden') + await dispose() + }) + + it('passes loopback and declared-authority requests through to the bridge', async () => { + const { routes, dispose } = await mounted({ trustedHosts: ['harness.example:3080'] }) + // Loopback, no browser markers (curl shape): the fence passes; the carrier + // answers 404 for a GET unary path — proof the bridge ran. + const loopback = fakeResponse() + await routes[0]!.handler(fakeRequest({ host: '127.0.0.1:3080' }), loopback.response) + expect(loopback.state.status).toBe(404) + // Declared public authority, same-origin browser shape. + const declared = fakeResponse() + await routes[0]!.handler(fakeRequest({ + host: 'harness.example:3080', origin: 'http://harness.example:3080', 'sec-fetch-site': 'same-origin', + }), declared.response) + expect(declared.state.status).toBe(404) + await dispose() + }) }) diff --git a/packages/host/apiproxy/README.i18n.yaml b/packages/host/apiproxy/README.i18n.yaml index ede79d610b..bfda016b16 100644 --- a/packages/host/apiproxy/README.i18n.yaml +++ b/packages/host/apiproxy/README.i18n.yaml @@ -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: 63294100cd0dc62f9822a3ca9678c1034880169f -README.zh.md: 251b4b0356da5f1fb518d133a92f484da957b951 +README.md: 2f51aa23e2639e2e98dfdd8aaf71e807d641c3dc +README.zh.md: 687e60879702a762d9e85295789b77daea4bd4ac diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index 63294100cd..2f51aa23e2 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -16,7 +16,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. +`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's prefix-wide trust fence (dsh-client-connection) covers this method like every other `/api` request. `session.history` pages on message boundaries, and its tail page (no `beforeSeq`) carries two session-level extras the page window cannot supply: the in-flight partial's chunk events, and `todos` — the latest `todo/write` whole-list projection over the full log. Older pages omit `todos` because the projection is session-level, not per-page; a tail response that omits it means the whole log holds no `todo/write`, so clients read the absent field as the empty plan rather than as unchanged state. diff --git a/packages/host/apiproxy/README.zh.md b/packages/host/apiproxy/README.zh.md index 251b4b0356..687e608797 100644 --- a/packages/host/apiproxy/README.zh.md +++ b/packages/host/apiproxy/README.zh.md @@ -16,7 +16,7 @@ mux 流会在每个已附加会话的订阅基线之后,以及对应的实时 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 秒超时限制的一元调用;调用方发出的中止信号和连接中止仍会传播至原生进程。浏览器载体另行将这一特权方法限制为仅接受来自回环地址的同源请求。 +`host.pickDirectory` 会打开一个原生目录选择器并返回选中的路径;用户取消时返回 `null`。宿主实现不经 shell 调用平台工具:macOS 使用 `osascript`,Windows 使用以 STA 模式运行的 PowerShell `FolderBrowserDialog`,Linux 使用 Zenity,并以 KDialog 作为回退。选择器函数可在测试中注入。该方法需等待用户完成操作,是唯一不受默认 30 秒超时限制的一元调用;调用方发出的中止信号和连接中止仍会传播至原生进程。浏览器载体的前缀级信任栅栏(dsh-client-connection)像覆盖其他所有 `/api` 请求一样覆盖该方法。 `session.history` 按消息边界分页,其尾页(不带 `beforeSeq`)额外携带两项页窗口本身无法提供的会话级数据:进行中局部消息的 chunk 事件,以及 `todos`——整份日志上最后一次 `todo/write` 的整表投影。较早的页面不带 `todos`,因为该投影是会话级而非分页级的;尾页响应缺少该字段意味着整份日志中没有任何 `todo/write`,因此客户端要把缺失字段读作空计划,而不是读作「状态未变」。 diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index b9538051cd..f8343b2404 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -797,6 +797,9 @@ importers: '@deepseek-ai/dsh-tools': specifier: workspace:^ version: link:../../core/tools + schemastery: + specifier: ^3.18.0 + version: 3.18.0 devDependencies: '@deepseek-ai/dsh-host-webserver': specifier: workspace:^ From d1ce22e7ad142f99dba86f94de0c353b43bc5a57 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 15:04:59 +0800 Subject: [PATCH 04/93] doc(packages): add the host/ and client/ group READMEs and table rows MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Both web-GUI groups shipped without the group README that the packages table names as each group's canonical package/ctx-key map, and without rows in that table. Adds both bilingual pairs, the two table rows (ceiling 835→870: two genuinely new product groups joined the canonical table at minimal row width), and fixes webserver README drift (WebServerService/ctx.webServer → HttpServerService/ctx.httpServer, matching src/index.ts). --- packages/README.i18n.yaml | 4 +-- packages/README.md | 2 ++ packages/README.zh.md | 2 ++ packages/client/README.i18n.yaml | 6 +++++ packages/client/README.md | 34 ++++++++++++++++++++++++ packages/client/README.zh.md | 34 ++++++++++++++++++++++++ packages/host/README.i18n.yaml | 6 +++++ packages/host/README.md | 12 +++++++++ packages/host/README.zh.md | 12 +++++++++ packages/host/webserver/README.i18n.yaml | 6 ++--- packages/host/webserver/README.md | 2 +- packages/host/webserver/README.zh.md | 2 +- scripts/doc-budgets.manifest.json | 2 +- 13 files changed, 116 insertions(+), 8 deletions(-) create mode 100644 packages/client/README.i18n.yaml create mode 100644 packages/client/README.md create mode 100644 packages/client/README.zh.md create mode 100644 packages/host/README.i18n.yaml create mode 100644 packages/host/README.md create mode 100644 packages/host/README.zh.md diff --git a/packages/README.i18n.yaml b/packages/README.i18n.yaml index 5dd168f03e..2415b8c578 100644 --- a/packages/README.i18n.yaml +++ b/packages/README.i18n.yaml @@ -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/README.md -README.md: d16e395a42e491461c0862227205931894c27e39 -README.zh.md: 3fb4181ce7ae7b0d79a13ca4358b9df39d83ef1f +README.md: ed1c2b65ef53793baf905791179b474c2f696637 +README.zh.md: 14c91a5e1899e1df6c9ceedb274423a4b8e12461 diff --git a/packages/README.md b/packages/README.md index d16e395a42..ed1c2b65ef 100644 --- a/packages/README.md +++ b/packages/README.md @@ -43,6 +43,8 @@ Packages live at `packages///`; groups are containers, while names r | [`sdk/`](sdk/README.md) | Project SDK tooling | Product — stable surface | | [`acp/`](acp/README.md) | Automation-only Agent Client Protocol server | Product — stable surface | | [`ui/`](ui/README.md) | Human/client integrations: TUI and JSON-RPC, approval/interaction seams, ask-user tool | Product — stable surface | +| [`host/`](host/README.md) | Web-GUI host half: shared API gateway + HTTP route server | Product — stable surface | +| [`client/`](client/README.md) | Web-GUI browser half: shell, wire consumer, object services, slot system, `ui-*` feature plugins | Product — stable surface | | [`examples/`](examples/README.md) | Demo bundles (agent-spine + TUI/CLI/ACP/JSON-RPC bins) leaves load | Support — example infra | | [`support/`](support/README.md) | Support infrastructure (testkits, invariants, replay, Loader smokes) | Support — lower compatibility expectations | | [`util/`](util/README.md) | Low-level zero-dependency utilities shared across groups (`Branded`, Harness home/path helpers, timeout, retention) | Support — small, stable, harness-dep-free | diff --git a/packages/README.zh.md b/packages/README.zh.md index 3fb4181ce7..14c91a5e18 100644 --- a/packages/README.zh.md +++ b/packages/README.zh.md @@ -43,6 +43,8 @@ | [`sdk/`](sdk/README.md) | 项目 SDK 工具 | 产品:稳定表面 | | [`acp/`](acp/README.md) | 仅面向自动化的 Agent Client Protocol 服务器 | 产品:稳定表面 | | [`ui/`](ui/README.md) | 人类/客户端集成:TUI 与 JSON-RPC、批准/交互 seam、用户问答工具 | 产品:稳定表面 | +| [`host/`](host/README.md) | web GUI 宿主半侧:共享 API 网关 + HTTP 路由服务器 | 产品:稳定表面 | +| [`client/`](client/README.md) | web GUI 浏览器半侧:shell、协议消费层、对象服务、slot 系统、`ui-*` 特性插件 | 产品:稳定表面 | | [`examples/`](examples/README.md) | 演示组合包(agent-spine + TUI/CLI/ACP/JSON-RPC bin),由叶节点加载 | 支持:示例基础设施 | | [`support/`](support/README.md) | 支持基础设施(testkit、不变式、回放、Loader 冒烟测试) | 支持:兼容性预期较低 | | [`util/`](util/README.md) | 组间共享的低层零依赖工具(`Branded`、Harness home/路径辅助函数、超时、保留策略) | 支持:小型、稳定、无 harness 依赖 | diff --git a/packages/client/README.i18n.yaml b/packages/client/README.i18n.yaml new file mode 100644 index 0000000000..0bac8a9924 --- /dev/null +++ b/packages/client/README.i18n.yaml @@ -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/client/README.md +README.md: b111d67fa49e06227e324a33bd53417ad28c3a5b +README.zh.md: b498008eb82f6ab357718f2af761f38e51140ef8 diff --git a/packages/client/README.md b/packages/client/README.md new file mode 100644 index 0000000000..b111d67fa4 --- /dev/null +++ b/packages/client/README.md @@ -0,0 +1,34 @@ +# client/ — web-GUI browser half + +English | [中文](README.zh.md) + +The browser side of the dsh web GUI: shell kernel, module system, wire consumer, React-free object services, the slot system, and the `ui-*` feature-plugin roster. Authoring rules live in [AGENTS.md](AGENTS.md); the host half is [`host/`](../host/README.md). All **product** packages, named `@deepseek-ai/dsh-client-`. + +| Package | Role | ctx key / slot | +|---|---|---| +| `web/` | Shell kernel: `AppWebEntry` runs the two-stage boot over the host-pushed entry graph | (boots the tree) | +| `modules/` | Client module system: browser peer of Node's ESM loader as a lazy CJS table under the vendored cordis Loader | (module face) | +| `web-react/` | Shell-side React glue: `createSlotRenderer` + `SessionProvider` render seats | (renderer install) | +| `connection/` | Wire consumer both ends: browser `ctx.connection` (shared api client + stream loop) and the node half mounting the `/api` route with its browser-trust fence | `ctx.connection` | +| `runtime/` | Client cordis boot and React-free object services: slots, Sessions, Workspaces, per-session bindings | `ctx.slots` `ctx.sessions` `ctx.workspaces` | +| `hmr/` | Dev-only hot reload for fetch-arrival client plugins (`--dev` graphs) | (dev entry) | +| `locale/` | Browser locale preference (`zh`/`en`) plus the ns×locale dictionary registry | `ctx.locale` | +| `ui-slots/` | Slot registry pure core: SlotMap merging, single `register` API, the four-share props family | (types + core) | +| `ui-theme/` | Theme preference over the `--dsw-*` token stylesheets (`light`/`dark`/`system`) | `ctx.theme` | +| `ui-primitives/` | Pure React atoms: icons, Button/Pill/Menu/Modal/Input, markdown family | (component library) | +| `ui-layout/` | Shell three-column AppFrame; declares `sidebar` / `conversation` / `details` / `conversation.empty` | `ctx.layout` | +| `ui-sidebar/` | Sidebar shell: Workspace/session rail, search, collapse; declares `sidebar.workspaces` | (slot host) | +| `ui-workspace/` | Shared Workspace picker: browser region + hero picker over the same creation flow | (fills `sidebar.workspaces`, `conversation.hero.workspace`) | +| `ui-conversation/` | Conversation domain: skeleton, chat view, input dock, per-tool row slots | (slot host) | +| `ui-trajectory/` | Trajectory/Waterfall view tabs; the minimal pure-consumer plugin exemplar | (fills `conversation.view`) | +| `ui-command/` | Command surface: session-keyed directory cache, `/` source, three-kind dispatch | `ctx.command` | +| `ui-slash/` | Input trigger pipeline: `/` and `@` detection, grouped candidate menu, source roster | `ctx.slash` | +| `ui-skill/` | `/`-trigger skill reference source over the `skill.list` RPC | (registers into `ctx.slash`) | +| `ui-subagent/` | `@`-trigger subagent reference source over the sessions snapshot | (registers into `ctx.slash`) | +| `ui-model/` | Model selection: `/model` popupSelect + the composer model seat over `ModelService` | `ctx.models` | +| `ui-question/` | Web `ask_user_question`: host half mounts the tool, browser half fills the composer seat | (fills `conversation.composer`) | +| `ui-settings/` | Settings shell: trigger chrome + modal panel; declares the `settings.*` slots | (slot host) | +| `ui-settings-general/` | Settings ownerless copy: chrome content + General section skeleton | (fills `settings.*`) | +| `ui-models/` | Models settings nav entry (content column lands in a later phase) | (fills `settings.section`) | + +Feature UI composes only through the slot system (`ctx.slots.register`) — the [slot system standard](../../.agents/notes/implemented/architecture/2026-07-22-slot-type-chain-implementation.md) is the definitive model; the [web client architecture note](../../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.md) owns the loading chain and object layer. diff --git a/packages/client/README.zh.md b/packages/client/README.zh.md new file mode 100644 index 0000000000..b498008eb8 --- /dev/null +++ b/packages/client/README.zh.md @@ -0,0 +1,34 @@ +# client/ — web GUI 浏览器半侧 + +[English](README.md) | 中文 + +dsh web GUI 的浏览器侧:shell 内核、模块系统、协议消费层、无 React 依赖的对象服务、slot 系统,以及 `ui-*` 特性插件阵列。编写规则见 [AGENTS.md](AGENTS.md);宿主半侧是 [`host/`](../host/README.md)。全部为**产品**包,命名为 `@deepseek-ai/dsh-client-`。 + +| 包 | 角色 | ctx 键/slot | +|---|---|---| +| `web/` | shell 内核:`AppWebEntry` 基于宿主推送的条目图运行两阶段启动 | (启动整棵树) | +| `modules/` | 客户端模块系统:Node ESM 加载器的浏览器对等物,是 vendored cordis Loader 之下的惰性 CJS 表 | (模块面) | +| `web-react/` | shell 侧 React 胶水:`createSlotRenderer` + `SessionProvider` 渲染座位 | (渲染器安装) | +| `connection/` | 协议两端的消费者:浏览器侧 `ctx.connection`(共享 api 客户端 + 流循环),node 半侧挂载带浏览器信任栅栏的 `/api` 路由 | `ctx.connection` | +| `runtime/` | 客户端 cordis 启动与无 React 对象服务:slots、Session、Workspace、逐会话绑定 | `ctx.slots` `ctx.sessions` `ctx.workspaces` | +| `hmr/` | 仅开发用的 fetch 到达型客户端插件热重载(`--dev` 图) | (开发条目) | +| `locale/` | 浏览器语言偏好(`zh`/`en`)与 ns×locale 词典注册表 | `ctx.locale` | +| `ui-slots/` | slot 注册表纯核心:SlotMap 合并、单一 `register` API、四份额 props 族 | (类型 + 核心) | +| `ui-theme/` | 基于 `--dsw-*` token 样式表的主题偏好(`light`/`dark`/`system`) | `ctx.theme` | +| `ui-primitives/` | 纯 React 原子:图标、Button/Pill/Menu/Modal/Input、markdown 族 | (组件库) | +| `ui-layout/` | shell 三栏 AppFrame;声明 `sidebar`/`conversation`/`details`/`conversation.empty` | `ctx.layout` | +| `ui-sidebar/` | 侧栏 shell:Workspace/会话栏、搜索、折叠;声明 `sidebar.workspaces` | (slot 宿主) | +| `ui-workspace/` | 共享 Workspace 选择器:浏览区域 + hero 选择器共用同一创建流程 | (填充 `sidebar.workspaces`、`conversation.hero.workspace`) | +| `ui-conversation/` | 会话域:骨架、聊天视图、输入坞、逐工具行 slot | (slot 宿主) | +| `ui-trajectory/` | Trajectory/Waterfall 视图标签;最小纯消费者插件范例 | (填充 `conversation.view`) | +| `ui-command/` | 命令面:按会话键控的目录缓存、`/` 源、三类分发 | `ctx.command` | +| `ui-slash/` | 输入触发流水线:光标下的 `/` 与 `@` 检测、分组候选菜单、源名册 | `ctx.slash` | +| `ui-skill/` | 基于 `skill.list` RPC 的 `/` 触发技能引用源 | (注册进 `ctx.slash`) | +| `ui-subagent/` | 基于会话快照的 `@` 触发子代理引用源 | (注册进 `ctx.slash`) | +| `ui-model/` | 模型选择:`/model` popupSelect + 输入坞模型座位,均由 `ModelService` 驱动 | `ctx.models` | +| `ui-question/` | Web `ask_user_question`:宿主半侧挂载工具,浏览器半侧填充输入坞座位 | (填充 `conversation.composer`) | +| `ui-settings/` | 设置 shell:触发 chrome + 模态面板;声明 `settings.*` slot | (slot 宿主) | +| `ui-settings-general/` | 设置的无主文案:chrome 内容 + General 分区骨架 | (填充 `settings.*`) | +| `ui-models/` | 模型设置导航项(内容列留待后续阶段) | (填充 `settings.section`) | + +特性 UI 只通过 slot 系统组合(`ctx.slots.register`)——[slot 系统标准](../../.agents/notes/implemented/architecture/2026-07-22-slot-type-chain-implementation.md)是权威模型;[web 客户端架构 Note](../../.agents/notes/implemented/architecture/2026-07-19-gui-web-client-architecture.md) 拥有加载链与对象层。 diff --git a/packages/host/README.i18n.yaml b/packages/host/README.i18n.yaml new file mode 100644 index 0000000000..b406dd394e --- /dev/null +++ b/packages/host/README.i18n.yaml @@ -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: 61e50cb64b95932085342b01a22d029cf8d5a228 +README.zh.md: 3109eccf89ee4c2d4d01be546e3ee9ead9084edc diff --git a/packages/host/README.md b/packages/host/README.md new file mode 100644 index 0000000000..61e50cb64b --- /dev/null +++ b/packages/host/README.md @@ -0,0 +1,12 @@ +# 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` | + +`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. diff --git a/packages/host/README.zh.md b/packages/host/README.zh.md new file mode 100644 index 0000000000..3109eccf89 --- /dev/null +++ b/packages/host/README.zh.md @@ -0,0 +1,12 @@ +# 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` | + +`apiproxy` 在设计上与传输方式无关——它不注册任何路由;载体自行包装 `ctx.apiProxy`。HTTP 载体路由(连同其 `/api` 浏览器信任栅栏)由 [`client/connection`](../client/connection/README.md) 的 node 半侧挂载,这正是该包住在 client 组的原因:它拥有这条线的两端。 diff --git a/packages/host/webserver/README.i18n.yaml b/packages/host/webserver/README.i18n.yaml index 9addd33a69..40d5fcf9d3 100644 --- a/packages/host/webserver/README.i18n.yaml +++ b/packages/host/webserver/README.i18n.yaml @@ -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 diff --git a/packages/host/webserver/README.md b/packages/host/webserver/README.md index c589c32c4e..e715e4452d 100644 --- a/packages/host/webserver/README.md +++ b/packages/host/webserver/README.md @@ -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. diff --git a/packages/host/webserver/README.zh.md b/packages/host/webserver/README.zh.md index 767195086b..05e7e10d78 100644 --- a/packages/host/webserver/README.zh.md +++ b/packages/host/webserver/README.zh.md @@ -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。 diff --git a/scripts/doc-budgets.manifest.json b/scripts/doc-budgets.manifest.json index 4cae854147..ea8cb380c9 100644 --- a/scripts/doc-budgets.manifest.json +++ b/scripts/doc-budgets.manifest.json @@ -7,5 +7,5 @@ "docs/testing.md": 1100, "examples/AGENTS.md": 310, "packages/AGENTS.md": 675, - "packages/README.md": 835 + "packages/README.md": 870 } From 01eea07bab1b73dac380919c8dafa94fa5adc9ba Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 15:40:02 +0800 Subject: [PATCH 05/93] fix(connection): keep LAN serving working under the /api browser-trust fence Markerless requests pass on any Host (a non-browser sender is the principal and forges headers anyway); browser Host matching gains port-less entries and WHATWG normalization; dsh derives LAN IP-literal authorities for an all-interfaces bind and web grows --trusted-host for named ones. --- ...07-28-api-browser-trust-boundary.i18n.yaml | 4 +- .../2026-07-28-api-browser-trust-boundary.md | 4 +- ...026-07-28-api-browser-trust-boundary.zh.md | 4 +- apps/cli/README.i18n.yaml | 6 +- apps/cli/README.md | 2 +- apps/cli/README.zh.md | 2 +- apps/cli/src/app-cli-entry.ts | 41 +++++++++++++ apps/cli/src/args.ts | 5 ++ apps/cli/src/bin.ts | 2 +- apps/cli/src/web.ts | 19 +++---- apps/cli/tests/args.spec.ts | 3 + apps/cli/tests/trusted-hosts.spec.ts | 40 +++++++++++++ docs/config-catalog.md | 9 +-- packages/client/connection/README.i18n.yaml | 4 +- packages/client/connection/README.md | 2 +- packages/client/connection/README.zh.md | 2 +- .../connection/src/api-request-trust.ts | 57 +++++++++++++------ packages/client/connection/src/index.ts | 9 +-- .../tests/api-request-trust.spec.ts | 45 ++++++++++----- .../client/connection/tests/node-half.spec.ts | 5 ++ 20 files changed, 199 insertions(+), 66 deletions(-) create mode 100644 apps/cli/tests/trusted-hosts.spec.ts diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml index 11973b755f..68473ee893 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml @@ -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 .agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md -2026-07-28-api-browser-trust-boundary.md: c620f1a65e3890bbd2580415e55b25436fefe36e -2026-07-28-api-browser-trust-boundary.zh.md: 0452eff1017b2f70a00e67c5cfce8dba3a840539 +2026-07-28-api-browser-trust-boundary.md: 45a332fcfe59fb930a85cfc595dd02c5fe12a5d7 +2026-07-28-api-browser-trust-boundary.zh.md: 731d6c81f71a2f50b716e52e278f2c53ad62a04b diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md index c620f1a65e..45a332fcfe 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md @@ -13,7 +13,7 @@ The web GUI host serves `/api` over plain HTTP (default `127.0.0.1:3080`, `--hos Enforce browser trust once, at the carrier, for the entire `/api` prefix — two halves in two stacked PRs: - **Media-type fence (dsh-host-apiproxy)**: every `/api` POST must declare `application/json`, else 415 before parsing. Cross-site "simple" requests thereby stop existing: any cross-site attempt is forced into a CORS preflight this server never answers. -- **Authority fence (dsh-client-connection, `src/api-request-trust.ts`)**: `Host` must be loopback or an exact `host[:port]` from the plugin's `trustedHosts` config (rebinding defense); an attached `Origin` must equal that authority; `sec-fetch-site: cross-site` is refused outright. Requests without browser markers pass — a non-browser client is the principal itself, not a deputy. `host.pickDirectory` loses its bespoke guard and rides the same fence. +- **Authority fence (dsh-client-connection, `src/api-request-trust.ts`)**: requests without browser markers (no `Origin`, no `sec-fetch-site`) pass on any Host — a non-browser client is the principal itself, not a deputy, and forges every header anyway, so fencing it buys nothing and breaks non-browser LAN automation. For browser requests, `Host` must be loopback or match a `trustedHosts` entry (exact on `host:port`, any port on port-less entries, WHATWG-normalized; rebinding defense); an attached `Origin` must equal that authority; `sec-fetch-site: cross-site` is refused outright. `host.pickDirectory` loses its bespoke guard and rides the same fence. Two boundaries stay deliberately out of scope: reachability is the webserver binding's policy (`host: 127.0.0.1 | 0.0.0.0`), and authentication for genuinely remote deployments is deferred work recorded in the connection README — the fence is a confused-deputy defense, not an auth layer. The old guard's loopback-socket check was dropped rather than generalized: with binding expressing reachability and `trustedHosts` naming remote authorities, the socket address adds nothing a header fence does not already cover. @@ -26,6 +26,6 @@ Two boundaries stay deliberately out of scope: reachability is the webserver bin ## Consequences - Any future `/api` method is covered by construction; there is no per-route trust decision left to forget. -- Non-loopback deployments must declare their serving authorities in `trustedHosts` or browsers are refused; plain curl-shape automation is unaffected either way. +- Non-loopback deployments must have their serving authorities trusted or browsers are refused. The dsh CLI keeps its advertised `--host 0.0.0.0` LAN URL working by deriving the machine's LAN IP literals into the connection row (port-less entries — an IP-literal Host cannot be a rebound name, and the bound port may be OS-assigned) and offers `dsh web --trusted-host` for named authorities; compositions the CLI does not boot declare `trustedHosts` themselves. Plain curl-shape automation is unaffected everywhere. - Clients must label POST bodies `application/json` (ours always did; raw-fetch tests gained the header). - The trusted-network assumption of an unauthenticated `0.0.0.0` deployment is now documented instead of implicit. diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md index 0452eff101..731d6c81f7 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md @@ -13,7 +13,7 @@ Web GUI 宿主以纯 HTTP 提供 `/api`(默认 `127.0.0.1:3080`,支持 `--ho 在载体层对整个 `/api` 前缀一次性执行浏览器信任检查——两半各占一个栈式 PR: - **媒体类型栅栏(dsh-host-apiproxy)**:每个 `/api` POST 必须声明 `application/json`,否则在解析前以 415 拒绝。跨站"简单请求"由此不复存在:任何跨站尝试都被逼进一次本服务器从不应答的 CORS 预检。 -- **权威栅栏(dsh-client-connection,`src/api-request-trust.ts`)**:`Host` 必须是回环地址,或与插件 `trustedHosts` 配置中的某个 `host[:port]` 精确匹配(rebinding 防御);若带 `Origin` 则必须与该权威完全一致;`sec-fetch-site: cross-site` 一律拒绝。不带浏览器标头的请求放行——非浏览器客户端是委托人本人,不是代理人。`host.pickDirectory` 失去专属守卫,与其他请求同栅而行。 +- **权威栅栏(dsh-client-connection,`src/api-request-trust.ts`)**:不带浏览器标记的请求(无 `Origin`、无 `sec-fetch-site`)在任何 Host 上都放行——非浏览器客户端是委托人本人,不是代理人,且本就可以伪造任何请求头,对它设栅一无所获,反而会打断非浏览器的 LAN 自动化。对浏览器请求,`Host` 必须是回环地址,或与某个 `trustedHosts` 条目匹配(带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,均经 WHATWG 归一化;rebinding 防御);若带 `Origin` 则必须与该权威完全一致;`sec-fetch-site: cross-site` 一律拒绝。`host.pickDirectory` 失去专属守卫,与其他请求同栅而行。 两条边界刻意留在范围之外:可达性归 webserver 绑定配置(`host: 127.0.0.1 | 0.0.0.0`)管辖;真正远程部署的认证是延期工作,记录在 connection README——这道栅栏是混淆代理人防御,不是认证层。旧守卫的回环 socket 检查被放弃而非泛化:绑定表达可达性、`trustedHosts` 点名远程权威之后,socket 地址提供不了头部栅栏覆盖不到的任何东西。 @@ -26,6 +26,6 @@ Web GUI 宿主以纯 HTTP 提供 `/api`(默认 `127.0.0.1:3080`,支持 `--ho ## 后果 - 未来任何 `/api` 方法天然在覆盖范围内;不存在会被遗忘的按路由信任决定。 -- 非回环部署必须在 `trustedHosts` 中声明服务权威,否则浏览器会被拒绝;curl 形态的自动化不受影响。 +- 非回环部署的服务权威必须获得信任,否则浏览器会被拒绝。dsh CLI 通过把本机 LAN IP 字面量推导进 connection 行(不带端口的条目——IP 字面量 Host 不可能是被重绑的域名,且绑定端口可能由操作系统分配)来保住它广告出的 `--host 0.0.0.0` LAN URL,并提供 `dsh web --trusted-host` 声明具名权威;CLI 不参与引导的组合自行声明 `trustedHosts`。curl 形态的自动化在任何地方都不受影响。 - 客户端必须给 POST 体标注 `application/json`(我们自己的客户端一向如此;裸 fetch 测试补上了该头)。 - 无认证 `0.0.0.0` 部署的"信任网络"假设从隐含变为成文。 diff --git a/apps/cli/README.i18n.yaml b/apps/cli/README.i18n.yaml index abe51abc2f..3322014ad5 100644 --- a/apps/cli/README.i18n.yaml +++ b/apps/cli/README.i18n.yaml @@ -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: 42d2a9641cf5d497c9aae45d9f60fce4498addb9 -README.zh.md: 0a62f8bb72e2cf2dbe045d28b81768bf4df800de +# pnpm run verify-translation-pairing --write apps/cli/README.md +README.md: f5e52382fb86ecd6b96b84b90b310514285f1904 +README.zh.md: b2089c67d751a25c6443a5e15b53266c728e5156 diff --git a/apps/cli/README.md b/apps/cli/README.md index 42d2a9641c..f5e52382fb 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) The `dsh` command-line entry follows the `apps/` assembly tier: `apps/*` are product assemblies over `packages/*` libraries. Plain `dsh` boots the interactive TUI coding agent, `dsh -p "task"` runs one headless turn, and `dsh web` serves the browser UI. -Argv is parsed once through a [Commander](https://github.com/tj/commander.js) adapter ([`src/args.ts`](src/args.ts)): one program whose default (no subcommand) is the TUI/headless surface (`--config`, `-p`/`--prompt`, `--resume`) and whose `web` subcommand is the browser UI. `src/bin.ts` switches on the resolved mode and dynamic-imports only that mode's module. `dsh --help` lists every mode and `dsh web --help` renders the web usage, `dsh --version` prints this app's version, and an unknown option or a mistyped `--resume` fails loud (stderr, exit 1) instead of misrouting. `dsh web`'s `--host`/`--port` are unvalidated pass-through overrides: the `dsh-host-webserver` schema is the single source of both the default (the shipped `cordis.yml` value when a flag is absent) and validity, and rejects a bad value at boot. +Argv is parsed once through a [Commander](https://github.com/tj/commander.js) adapter ([`src/args.ts`](src/args.ts)): one program whose default (no subcommand) is the TUI/headless surface (`--config`, `-p`/`--prompt`, `--resume`) and whose `web` subcommand is the browser UI. `src/bin.ts` switches on the resolved mode and dynamic-imports only that mode's module. `dsh --help` lists every mode and `dsh web --help` renders the web usage, `dsh --version` prints this app's version, and an unknown option or a mistyped `--resume` fails loud (stderr, exit 1) instead of misrouting. `dsh web`'s `--host`/`--port` are unvalidated pass-through overrides: the `dsh-host-webserver` schema is the single source of both the default (the shipped `cordis.yml` value when a flag is absent) and validity, and rejects a bad value at boot. `--trusted-host` appends named authorities for the /api browser-trust fence; an all-interfaces bind additionally derives the machine's LAN IP literals itself ([`src/app-cli-entry.ts`](src/app-cli-entry.ts)), so the printed LAN URL works without flags. The TUI surface: diff --git a/apps/cli/README.zh.md b/apps/cli/README.zh.md index 0a62f8bb72..b2089c67d7 100644 --- a/apps/cli/README.zh.md +++ b/apps/cli/README.zh.md @@ -4,7 +4,7 @@ `dsh` 命令行入口遵循 `apps/` 组装层:`apps/*` 是位于 `packages/*` 库之上的产品组装。直接运行 `dsh` 会启动交互式 TUI 编码 agent(智能体),`dsh -p "task"` 运行一个无头轮次,`dsh web` 则提供浏览器 UI。 -Argv 只会通过 [Commander](https://github.com/tj/commander.js) 适配器([`src/args.ts`](src/args.ts))解析一次:同一个程序的默认形式(无子命令)是 TUI/无头界面(`--config`、`-p`/`--prompt`、`--resume`),`web` 子命令则是浏览器 UI。`src/bin.ts` 按解析后的 mode 分支,仅动态导入该 mode 的模块。`dsh --help` 列出所有 mode,`dsh web --help` 渲染 Web 用法,`dsh --version` 打印此应用的版本;未知选项或拼错的 `--resume` 会明确报错(stderr,退出码 1),而不会被错路由。`dsh web` 的 `--host`/`--port` 是未验证的直通覆盖:`dsh-host-webserver` schema 是默认值(标志缺失时使用已交付的 `cordis.yml` 值)和有效性的唯一真源,并在启动时拒绝错误值。 +Argv 只会通过 [Commander](https://github.com/tj/commander.js) 适配器([`src/args.ts`](src/args.ts))解析一次:同一个程序的默认形式(无子命令)是 TUI/无头界面(`--config`、`-p`/`--prompt`、`--resume`),`web` 子命令则是浏览器 UI。`src/bin.ts` 按解析后的 mode 分支,仅动态导入该 mode 的模块。`dsh --help` 列出所有 mode,`dsh web --help` 渲染 Web 用法,`dsh --version` 打印此应用的版本;未知选项或拼错的 `--resume` 会明确报错(stderr,退出码 1),而不会被错路由。`dsh web` 的 `--host`/`--port` 是未验证的直通覆盖:`dsh-host-webserver` schema 是默认值(标志缺失时使用已交付的 `cordis.yml` 值)和有效性的唯一真源,并在启动时拒绝错误值。`--trusted-host` 为 /api 浏览器信任栅栏追加具名权威;全接口绑定还会自行推导本机的 LAN IP 字面量([`src/app-cli-entry.ts`](src/app-cli-entry.ts)),因此打印出的 LAN URL 无需任何标志即可使用。 TUI 界面: diff --git a/apps/cli/src/app-cli-entry.ts b/apps/cli/src/app-cli-entry.ts index 344c66e2b3..1002b45660 100644 --- a/apps/cli/src/app-cli-entry.ts +++ b/apps/cli/src/app-cli-entry.ts @@ -9,6 +9,7 @@ import { readFileSync } from 'node:fs' import { createRequire } from 'node:module' +import { networkInterfaces } from 'node:os' import { join, resolve } from 'node:path' import { pathToFileURL } from 'node:url' import { Context } from 'cordis' @@ -25,6 +26,38 @@ import type {} from '@deepseek-ai/dsh-host-webserver' const PROFILE_DIR = '.dsh-tmp-profile' const PROFILE_FILE = 'config.json' +/** The webserver schema's all-interfaces bind literal: gates LAN-authority derivation here and the printed LAN URL in web.ts. */ +export const ALL_INTERFACES_HOST = '0.0.0.0' + +/** + * Non-internal IPv4 interface addresses of this machine — the IP-literal + * authorities an all-interfaces bind is reachable by on the LAN. + * @returns the addresses in interface order (possibly empty). + */ +export function lanIPv4Addresses(): string[] { + return Object.values(networkInterfaces()).flat() + .filter((iface): iface is NonNullable => iface !== undefined && iface.family === 'IPv4' && !iface.internal) + .map(iface => iface.address) +} + +/** + * Authorities the /api browser-trust fence must accept for one invocation: + * the machine's LAN IP literals when the effective bind is all-interfaces + * (advertised by the printed LAN URL, so they must not answer 403), followed + * by the explicit extras. Derived entries are port-less IP literals — DNS + * rebinding needs an attacker-controlled name, so an IP-literal Host is safe + * on any port, and the bound port may be OS-assigned, unknowable pre-boot. + * @param bindHost - the effective webserver bind host (CLI flag, else the yml default). + * @param extra - `--trusted-host` values, in argv order. + * @returns the connection row's `trustedHosts` value (possibly empty). + */ +export function resolveTrustedHosts(bindHost: string | undefined, extra: readonly string[]): string[] { + return [ + ...bindHost === ALL_INTERFACES_HOST ? lanIPv4Addresses() : [], + ...extra, + ] +} + /** One profile-json key mapped onto a yml row's config field. */ interface ProfileMapping { jsonPath: string @@ -79,6 +112,8 @@ export interface AppCLIEntryOptions { port?: number /** Parent directory for name-created Workspaces; undefined uses the gateway's cwd fallback. */ workspaceRoot?: string + /** Extra authorities for the /api browser-trust fence (`host` or `host:port`), appended to the derived LAN IP literals. */ + trustedHosts?: string[] } /** @@ -152,6 +187,12 @@ export class AppCLIEntry { if (this.options.port !== undefined) put('webserver', 'port', this.options.port) if (this.options.workspaceRoot !== undefined) put('api-gateway', 'workspaceRoot', this.options.workspaceRoot) + // Source 2b: authorities for the /api browser-trust fence (rationale on + // resolveTrustedHosts). + const ymlHost = (rows.get('webserver')?.config as { host?: string } | undefined)?.host + const trustedHosts = resolveTrustedHosts(this.options.host ?? ymlHost, this.options.trustedHosts ?? []) + if (trustedHosts.length > 0) put('connection', 'trustedHosts', trustedHosts) + // Source 3: the frontend dist — an assembly fact of this app, never yml // user config. Workspace knowledge stays here. put('webserver', 'distIndex', this.resolveDistIndex()) diff --git a/apps/cli/src/args.ts b/apps/cli/src/args.ts index 9fd0f4d9bf..b929dc73f2 100644 --- a/apps/cli/src/args.ts +++ b/apps/cli/src/args.ts @@ -40,6 +40,8 @@ interface WebInvocation { port?: number dev: boolean workspaceRoot?: string + /** Extra authorities for the /api browser-trust fence (`host` or `host:port`); LAN IP literals are derived, not listed here. */ + trustedHosts?: string[] } /** The resolved `dsh` invocation: exactly one mode. `--help`/`--version`/errors exit inside {@link parseDshArgs}. */ @@ -51,6 +53,7 @@ interface WebOptions { port?: string dev?: boolean workspaceRoot?: string + trustedHost?: string[] } /** @@ -66,6 +69,7 @@ function resolveWeb(options: WebOptions): WebInvocation { ...options.port !== undefined && { port: Number(options.port) }, dev: options.dev === true, ...options.workspaceRoot !== undefined && { workspaceRoot: options.workspaceRoot }, + ...options.trustedHost !== undefined && { trustedHosts: options.trustedHost }, } } @@ -117,6 +121,7 @@ export function parseDshArgs(argv: readonly string[], version: string): DshInvoc .option('--port ', 'override the config listen port (0 requests an OS-assigned port)') .option('--dev', 'mount the client HMR driver and watch plugin bundles for rebuilds') .option('--workspace-root ', 'parent directory for name-created workspaces') + .option('--trusted-host ', 'extra authority the /api browser-trust fence accepts (host or host:port; repeatable)') .action((options: WebOptions) => { // Commander parses the parent (default-surface) options on either side of // the subcommand into `program.opts()`. `web` shares none of them, so a diff --git a/apps/cli/src/bin.ts b/apps/cli/src/bin.ts index f9e1eefc9b..88dbece55a 100644 --- a/apps/cli/src/bin.ts +++ b/apps/cli/src/bin.ts @@ -30,7 +30,7 @@ const invocation = parseDshArgs(process.argv.slice(2), readVersion()) switch (invocation.mode) { case 'web': { const { runWeb } = await import('./web.ts') - await runWeb(invocation.host, invocation.port, invocation.dev, invocation.workspaceRoot) + await runWeb(invocation.host, invocation.port, invocation.dev, invocation.workspaceRoot, invocation.trustedHosts) break } case 'headless': { diff --git a/apps/cli/src/web.ts b/apps/cli/src/web.ts index 31282c8f5f..3d7fc29ab4 100644 --- a/apps/cli/src/web.ts +++ b/apps/cli/src/web.ts @@ -6,17 +6,14 @@ * gates them at boot. */ -import { networkInterfaces } from 'node:os' import { fileURLToPath } from 'node:url' -import { AppCLIEntry } from './app-cli-entry.ts' +import { ALL_INTERFACES_HOST, AppCLIEntry, lanIPv4Addresses } from './app-cli-entry.ts' const CONFIG_PATH = fileURLToPath(new URL('../cordis.yml', import.meta.url)) -// Display-only mirrors of the webserver schema's allowed hosts: the loopback -// address the local URL always prints, and the all-interfaces value that gates -// LAN-address discovery. Not a source of truth — the schema is. +// Display-only mirror of the webserver schema's loopback host: the address the +// local URL always prints. Not a source of truth — the schema is. const LOOPBACK_HOST = '127.0.0.1' -const ALL_INTERFACES_HOST = '0.0.0.0' /** * Serve the browser UI from the shipped config tree. `host`/`port` are passed @@ -25,12 +22,14 @@ const ALL_INTERFACES_HOST = '0.0.0.0' * @param port - the listen port (`0` requests an OS-assigned port), or `undefined` to keep the config default. * @param dev - mount the client HMR driver and watch plugin bundles for rebuilds. * @param workspaceRoot - parent directory for name-created workspaces, or `undefined` for the gateway's cwd fallback. + * @param trustedHosts - extra authorities for the /api browser-trust fence, or `undefined` for the derived LAN literals alone. */ export async function runWeb( host: string | undefined, port: number | undefined, dev: boolean, workspaceRoot: string | undefined, + trustedHosts: string[] | undefined, ): Promise { const entry = new AppCLIEntry({ configPath: CONFIG_PATH, @@ -38,6 +37,7 @@ export async function runWeb( ...host !== undefined && { host }, ...port !== undefined && { port }, ...workspaceRoot !== undefined && { workspaceRoot }, + ...trustedHosts !== undefined && { trustedHosts }, }) const { ctx, port: boundPort } = await entry.run() @@ -48,12 +48,9 @@ export async function runWeb( void Promise.resolve(ctx.fiber.dispose()).finally(() => { process.exit(code) }) } - const lanCandidate = host === ALL_INTERFACES_HOST - ? Object.values(networkInterfaces()).flat() - .find(iface => iface !== undefined && iface.family === 'IPv4' && !iface.internal) - : undefined + const lanCandidate = host === ALL_INTERFACES_HOST ? lanIPv4Addresses()[0] : undefined const localUrl = `http://${LOOPBACK_HOST}:${boundPort}` - console.log(`dsh web: ${localUrl}${lanCandidate === undefined ? '' : ` (LAN: http://${lanCandidate.address}:${boundPort})`}`) + console.log(`dsh web: ${localUrl}${lanCandidate === undefined ? '' : ` (LAN: http://${lanCandidate}:${boundPort})`}`) process.on('SIGTERM', () => { shutdown(0) }) process.on('SIGINT', () => { shutdown(130) }) diff --git a/apps/cli/tests/args.spec.ts b/apps/cli/tests/args.spec.ts index 052e96e9a0..45830eee30 100644 --- a/apps/cli/tests/args.spec.ts +++ b/apps/cli/tests/args.spec.ts @@ -35,6 +35,9 @@ describe('parseDshArgs', () => { // at boot); the adapter only coerces the port string to a number. expect(parse(['web', '--host', '0.0.0.0', '--port', '8080', '--dev', '--workspace-root', '/w'])) .toEqual({ mode: 'web', host: '0.0.0.0', port: 8080, dev: true, workspaceRoot: '/w' }) + // --trusted-host is variadic and repeatable; authorities pass through unvalidated. + expect(parse(['web', '--trusted-host', 'harness.internal:3080', 'lab.internal', '--trusted-host', '10.0.0.9'])) + .toEqual({ mode: 'web', dev: false, trustedHosts: ['harness.internal:3080', 'lab.internal', '10.0.0.9'] }) }) it('exits nonzero instead of silently starting fresh or dropping inputs', () => { diff --git a/apps/cli/tests/trusted-hosts.spec.ts b/apps/cli/tests/trusted-hosts.spec.ts new file mode 100644 index 0000000000..1ed0f602b8 --- /dev/null +++ b/apps/cli/tests/trusted-hosts.spec.ts @@ -0,0 +1,40 @@ +/** LAN-authority derivation for the /api browser-trust fence (`resolveTrustedHosts`). */ + +import { afterEach, describe, expect, it, vi } from 'vitest' +import { lanIPv4Addresses, resolveTrustedHosts } from '../src/app-cli-entry.ts' + +vi.mock('node:os', () => ({ + networkInterfaces: () => ({ + lo0: [ + { family: 'IPv4', internal: true, address: '127.0.0.1' }, + ], + en0: [ + { family: 'IPv6', internal: false, address: 'fe80::1' }, + { family: 'IPv4', internal: false, address: '192.168.1.5' }, + ], + en1: [ + { family: 'IPv4', internal: false, address: '10.0.0.7' }, + ], + utun0: undefined, + }), +})) + +afterEach(() => { vi.restoreAllMocks() }) + +describe('lanIPv4Addresses', () => { + it('returns only non-internal IPv4 addresses, in interface order', () => { + expect(lanIPv4Addresses()).toEqual(['192.168.1.5', '10.0.0.7']) + }) +}) + +describe('resolveTrustedHosts', () => { + it('derives port-less LAN IP literals for an all-interfaces bind, ahead of the extras', () => { + expect(resolveTrustedHosts('0.0.0.0', ['harness.internal:3080'])) + .toEqual(['192.168.1.5', '10.0.0.7', 'harness.internal:3080']) + }) + + it('derives nothing for a loopback or unresolved bind — extras alone stand', () => { + expect(resolveTrustedHosts('127.0.0.1', [])).toEqual([]) + expect(resolveTrustedHosts(undefined, ['lab.internal'])).toEqual(['lab.internal']) + }) +}) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index d30aff1f02..6155c418e0 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -278,10 +278,11 @@ Requires: `httpServer` · `apiProxy` /** Plugin config: the deployment's non-loopback serving authorities. */ export interface ConnectionConfig { /** - * Exact `host[:port]` authorities this deployment serves beyond loopback. - * The /api trust fence refuses any request whose Host is neither loopback - * nor listed here, so a non-loopback (`0.0.0.0`) deployment must declare - * the names it is reached by. + * Authorities this deployment serves beyond loopback: exact `host:port`, or + * port-less `host` matching any port. The /api trust fence refuses any + * browser request whose Host is neither loopback nor listed here, so a + * non-loopback (`0.0.0.0`) deployment must declare the names it is reached + * by (the dsh CLI derives the machine's LAN IP literals itself). */ trustedHosts?: string[] } diff --git a/packages/client/connection/README.i18n.yaml b/packages/client/connection/README.i18n.yaml index 5c5a825a27..8310adac83 100644 --- a/packages/client/connection/README.i18n.yaml +++ b/packages/client/connection/README.i18n.yaml @@ -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/client/connection/README.md -README.md: a301b85d707d17d1e8159655b540556eee5c9d83 -README.zh.md: 88d7aa806167033308a9913053f621ecea07c3d8 +README.md: 94b9b3c8d4bde30cedf56e31d83efe9f5f1dd87c +README.zh.md: 844a2ef030378c32994f7459792db98c779f24b7 diff --git a/packages/client/connection/README.md b/packages/client/connection/README.md index a301b85d70..94b9b3c8d4 100644 --- a/packages/client/connection/README.md +++ b/packages/client/connection/README.md @@ -6,7 +6,7 @@ Wire consumer layer: the client plugin's apply mounts `ctx.connection` (shared a ## /api browser-trust fence -The node half guards every request under `/api` before bridging (`src/api-request-trust.ts`): the `Host` header must be a loopback authority or an exact `host[:port]` entry from the plugin's `trustedHosts` config (DNS-rebinding defense), an attached `Origin` must equal that authority, and an explicit `sec-fetch-site: cross-site` marker is refused. Requests without browser markers (curl, tests, native clients) pass — without a browser there is no confused deputy. Failures answer plain 403 before any RPC dispatch. A non-loopback (`--host 0.0.0.0`) deployment must therefore list the authorities it is reached by in `trustedHosts`; the fence is deliberately not an authentication layer — reachability policy stays with the webserver binding, and auth remains deferred work. Decision record: [the api browser-trust boundary Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md). +The node half guards every request under `/api` before bridging (`src/api-request-trust.ts`). Requests without browser markers (no `Origin`, no `sec-fetch-site` — curl, tests, native clients) pass on any Host: without a browser there is no confused deputy, and such a sender forges every header anyway. For browser requests, the `Host` header must be a loopback authority or match a `trustedHosts` entry — exact on `host:port` entries, any port on port-less entries, both sides compared through WHATWG normalization (DNS-rebinding defense); an attached `Origin` must equal that authority, and an explicit `sec-fetch-site: cross-site` marker is refused. Failures answer plain 403 before any RPC dispatch. A non-loopback (`--host 0.0.0.0`) deployment therefore needs its serving authorities trusted: the dsh CLI derives the machine's LAN IP literals itself and its `--trusted-host` flag declares named ones, so `trustedHosts` in cordis.yml is for compositions the CLI does not boot. The fence is deliberately not an authentication layer — reachability policy stays with the webserver binding, and auth remains deferred work. Decision record: [the api browser-trust boundary Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md). ## Keyless fixture diff --git a/packages/client/connection/README.zh.md b/packages/client/connection/README.zh.md index 88d7aa8061..844a2ef030 100644 --- a/packages/client/connection/README.zh.md +++ b/packages/client/connection/README.zh.md @@ -6,7 +6,7 @@ ## /api 浏览器信任栅栏 -node 半侧在桥接前守卫 `/api` 下的每个请求(`src/api-request-trust.ts`):`Host` 头必须是回环地址权威,或与插件 `trustedHosts` 配置中的某个 `host[:port]` 精确匹配(DNS rebinding 防御);若带有 `Origin` 则必须与该权威完全一致;显式的 `sec-fetch-site: cross-site` 标记一律拒绝。不带浏览器标头的请求(curl、测试、原生客户端)直接放行——没有浏览器就不存在"混淆代理人"。失败在任何 RPC 分发之前以纯 403 应答。因此非回环(`--host 0.0.0.0`)部署必须在 `trustedHosts` 中列出自己被访问时使用的权威;这道栅栏刻意不承担认证职责——可达性策略归 webserver 绑定配置,认证仍是延期工作。决策记录:[api 浏览器信任边界 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md)。 +node 半侧在桥接前守卫 `/api` 下的每个请求(`src/api-request-trust.ts`)。不带浏览器标记的请求(无 `Origin`、无 `sec-fetch-site`——curl、测试、原生客户端)在任何 Host 上都放行:没有浏览器就不存在"混淆代理人",且这类发送方本就可以伪造任何请求头。对浏览器请求,`Host` 头必须是回环地址权威,或与某个 `trustedHosts` 条目匹配——带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,两侧均经 WHATWG 归一化后比较(DNS rebinding 防御);若带有 `Origin` 则必须与该权威完全一致;显式的 `sec-fetch-site: cross-site` 标记一律拒绝。失败在任何 RPC 分发之前以纯 403 应答。因此非回环(`--host 0.0.0.0`)部署需要让自己的服务权威被信任:dsh CLI 会自行推导本机的 LAN IP 字面量,其 `--trusted-host` flag 用于声明具名权威,所以 cordis.yml 中的 `trustedHosts` 面向 CLI 不参与引导的组合。这道栅栏刻意不承担认证职责——可达性策略归 webserver 绑定配置,认证仍是延期工作。决策记录:[api 浏览器信任边界 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md)。 ## 无密钥 fixture diff --git a/packages/client/connection/src/api-request-trust.ts b/packages/client/connection/src/api-request-trust.ts index 37819b9fb9..11dc6d7621 100644 --- a/packages/client/connection/src/api-request-trust.ts +++ b/packages/client/connection/src/api-request-trust.ts @@ -3,10 +3,11 @@ * paths a browser opens against a local HTTP API — DNS rebinding (Host names * the attacker's domain while the socket reaches this server) and cross-site * requests fired from a malicious page — without blocking non-browser clients - * (no browser markers → no deputy to confuse) or legitimately remote browsers - * (their authority is declared via `trustedHosts`). Network reachability and - * authentication stay out of scope: binding policy belongs to the webserver - * config, and this fence is not an auth layer. + * (no browser markers → no deputy to confuse, and a native client forges Host + * freely anyway) or legitimately remote browsers (their authority is declared + * via `trustedHosts`, or derived by the composing app for IP-literal LAN + * serving). Network reachability and authentication stay out of scope: binding + * policy belongs to the webserver config, and this fence is not an auth layer. */ import type { IncomingHttpHeaders } from 'node:http' @@ -29,42 +30,64 @@ function isLoopbackHostname(hostname: string): boolean { && parts.every(part => /^\d{1,3}$/.test(part) && Number(part) <= 255) } -/** Hostname of a Host-header authority (port stripped, lowercased, IPv6 bracketed), or undefined when unparsable. */ -function authorityHostname(authority: string): string | undefined { +/** Normalized URL of a Host-header authority (hostname lowercased, default port stripped, IPv6 bracketed), or undefined when unparsable. */ +function parseAuthority(authority: string): URL | undefined { try { // http: is a WHATWG "special scheme": parsing yields a non-empty hostname or throws. - return new URL(`http://${authority}`).hostname + return new URL(`http://${authority}`) } catch { return undefined } } +/** + * Whether the request authority matches a `trustedHosts` entry. An entry with + * an explicit port matches that exact authority; a port-less entry matches the + * hostname on any port (the shape the CLI derives for IP-literal LAN serving, + * where the bound port may be OS-assigned). Both sides compare through WHATWG + * normalization, so case and a redundant `:80` never decide trust. + */ +function isTrustedAuthority(hostUrl: URL, trustedHosts: readonly string[]): boolean { + return trustedHosts.some((entry) => { + const entryUrl = parseAuthority(entry) + if (entryUrl === undefined) return false + return /:\d+$/.test(entry) + ? entryUrl.host === hostUrl.host + : entryUrl.hostname === hostUrl.hostname + }) +} + /** * Decide whether one /api request may reach the RPC bridge. * @param request - node HTTP request facts (headers). - * @param trustedHosts - exact non-loopback `host[:port]` authorities this deployment serves. - * @returns true when the Host is ours and any browser markers are same-origin. + * @param trustedHosts - non-loopback authorities this deployment serves: exact `host:port`, or port-less `host` matching any port. + * @returns true for requests without browser markers, and for browser requests whose Host is ours and whose markers are same-origin. */ export function isTrustedApiRequest(request: ApiTrustRequest, trustedHosts: readonly string[]): boolean { + // Marker gate: Origin and sec-fetch-site exist only when a browser is the + // sender's deputy. Absent both, the sender is the principal itself (curl, + // tests, native shells) and could forge every header below — fencing it + // would add nothing and would break non-browser LAN automation. + const origin = header(request.headers, 'origin') + const secFetchSite = header(request.headers, 'sec-fetch-site') + if (origin === undefined && secFetchSite === undefined) return true // Host fence (DNS-rebinding defense): the browser fills Host from the URL it // believes it is talking to, so a rebound page carries the attacker's domain // here even though the socket lands on this server. const host = header(request.headers, 'host') if (host === undefined) return false - const hostname = authorityHostname(host) - if (hostname === undefined) return false - if (!isLoopbackHostname(hostname) && !trustedHosts.includes(host)) return false + const hostUrl = parseAuthority(host) + if (hostUrl === undefined) return false + if (!isLoopbackHostname(hostUrl.hostname) && !isTrustedAuthority(hostUrl, trustedHosts)) return false // Cross-site fence: modern browsers label the initiator relationship on // every fetch; an explicit cross-site marker is refused regardless of Origin. - if (header(request.headers, 'sec-fetch-site') === 'cross-site') return false + if (secFetchSite === 'cross-site') return false // Origin fence: when a browser attaches an Origin it must be exactly this - // authority. Absent Origin = non-browser client (curl, tests, native shells) - // — allowed, because without a browser there is no confused deputy. The + // authority (compared through the same normalization as the Host). The // literal "null" (sandboxed iframes, file: pages) is an opaque origin, refused. - const origin = header(request.headers, 'origin') if (origin === undefined) return true try { - return new URL(origin).host === host + return new URL(origin).host === hostUrl.host } catch { return false } diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index 77f463149e..1bc39ed3ba 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -19,10 +19,11 @@ export const inject = ['httpServer', 'apiProxy'] /** Plugin config: the deployment's non-loopback serving authorities. */ export interface ConnectionConfig { /** - * Exact `host[:port]` authorities this deployment serves beyond loopback. - * The /api trust fence refuses any request whose Host is neither loopback - * nor listed here, so a non-loopback (`0.0.0.0`) deployment must declare - * the names it is reached by. + * Authorities this deployment serves beyond loopback: exact `host:port`, or + * port-less `host` matching any port. The /api trust fence refuses any + * browser request whose Host is neither loopback nor listed here, so a + * non-loopback (`0.0.0.0`) deployment must declare the names it is reached + * by (the dsh CLI derives the machine's LAN IP literals itself). */ trustedHosts?: string[] } diff --git a/packages/client/connection/tests/api-request-trust.spec.ts b/packages/client/connection/tests/api-request-trust.spec.ts index eab878e734..5dc2d14b1b 100644 --- a/packages/client/connection/tests/api-request-trust.spec.ts +++ b/packages/client/connection/tests/api-request-trust.spec.ts @@ -8,14 +8,19 @@ function request(headers: Record): { headers: Record } describe('isTrustedApiRequest', () => { - it('accepts loopback Hosts in every spelling, with and without ports', () => { - for (const host of ['localhost', 'localhost:3080', '127.0.0.1', '127.0.0.1:3080', '127.8.9.10:80', '[::1]', '[::1]:3080', 'LOCALHOST:3080']) { - expect(isTrustedApiRequest(request({ host }), [])).toBe(true) + it('accepts every request without browser markers — curl, tests, native clients, on any Host', () => { + // No Origin and no sec-fetch-site → the sender is the principal itself + // (it forges Host freely anyway); this is the LAN-serving shape a Host + // fence must not break. + for (const host of ['127.0.0.1:3080', '192.168.1.5:3080', 'harness.example', undefined]) { + expect(isTrustedApiRequest(request(host === undefined ? {} : { host }), [])).toBe(true) } }) - it('accepts non-browser requests (no Origin, no sec-fetch-site) — curl, tests, native clients', () => { - expect(isTrustedApiRequest(request({ host: '127.0.0.1:3080' }), [])).toBe(true) + it('accepts loopback Hosts in every spelling, with and without ports, for browser requests', () => { + for (const host of ['localhost', 'localhost:3080', '127.0.0.1', '127.0.0.1:3080', '127.8.9.10:80', '[::1]', '[::1]:3080', 'LOCALHOST:3080']) { + expect(isTrustedApiRequest(request({ host, origin: `http://${host}` }), [])).toBe(true) + } }) it('refuses a rebound Host: the attacker domain names the socket it did not expect', () => { @@ -26,13 +31,22 @@ describe('isTrustedApiRequest', () => { }), [])).toBe(false) }) - it('accepts a declared public authority only on exact host[:port] match', () => { + it('accepts a declared public authority: exact on host:port entries, any port on port-less entries', () => { const headers = { host: 'harness.internal:3080', origin: 'http://harness.internal:3080' } expect(isTrustedApiRequest(request(headers), ['harness.internal:3080'])).toBe(true) - expect(isTrustedApiRequest(request(headers), ['harness.internal'])).toBe(false) + expect(isTrustedApiRequest(request(headers), ['harness.internal'])).toBe(true) + expect(isTrustedApiRequest(request(headers), ['harness.internal:9999'])).toBe(false) expect(isTrustedApiRequest(request(headers), [])).toBe(false) }) + it('matches Host, Origin, and trusted entries through WHATWG normalization (case, default port)', () => { + expect(isTrustedApiRequest(request({ host: 'Harness.INTERNAL:3080', origin: 'http://harness.internal:3080' }), ['harness.internal:3080'])).toBe(true) + expect(isTrustedApiRequest(request({ host: 'harness.internal', origin: 'http://harness.internal' }), ['HARNESS.internal:80'])).toBe(true) + // An unparsable entry never matches; it must not poison the rest of the list. + expect(isTrustedApiRequest(request({ host: 'harness.internal', origin: 'http://harness.internal' }), ['bad entry', 'harness.internal'])).toBe(true) + expect(isTrustedApiRequest(request({ host: 'harness.internal', origin: 'http://harness.internal' }), ['bad entry'])).toBe(false) + }) + it('refuses cross-origin browser markers even on a loopback Host', () => { // Origin present and different → cross-site request that survived preflight rules. expect(isTrustedApiRequest(request({ host: '127.0.0.1:3080', origin: 'http://evil.example' }), [])).toBe(false) @@ -42,19 +56,22 @@ describe('isTrustedApiRequest', () => { expect(isTrustedApiRequest(request({ host: '127.0.0.1:3080', origin: 'null' }), [])).toBe(false) }) - it('accepts a same-origin browser request', () => { + it('accepts a same-origin browser request, with or without an Origin header', () => { expect(isTrustedApiRequest(request({ host: 'localhost:3080', origin: 'http://localhost:3080', 'sec-fetch-site': 'same-origin', }), [])).toBe(true) + // Origin-less browser shapes (same-origin GETs) still carry sec-fetch-site. + expect(isTrustedApiRequest(request({ host: 'localhost:3080', 'sec-fetch-site': 'same-origin' }), [])).toBe(true) }) - it('refuses malformed authorities', () => { - expect(isTrustedApiRequest(request({}), [])).toBe(false) - expect(isTrustedApiRequest(request({ host: '' }), [])).toBe(false) - expect(isTrustedApiRequest(request({ host: 'bad host' }), [])).toBe(false) - expect(isTrustedApiRequest(request({ host: '127.0.0.999' }), [])).toBe(false) - expect(isTrustedApiRequest(request({ host: '128.0.0.1' }), [])).toBe(false) + it('refuses malformed or untrusted authorities on browser requests', () => { + const markers = { 'sec-fetch-site': 'same-origin' } + expect(isTrustedApiRequest(request({ ...markers }), [])).toBe(false) + expect(isTrustedApiRequest(request({ ...markers, host: '' }), [])).toBe(false) + expect(isTrustedApiRequest(request({ ...markers, host: 'bad host' }), [])).toBe(false) + expect(isTrustedApiRequest(request({ ...markers, host: '127.0.0.999' }), [])).toBe(false) + expect(isTrustedApiRequest(request({ ...markers, host: '128.0.0.1' }), [])).toBe(false) }) }) diff --git a/packages/client/connection/tests/node-half.spec.ts b/packages/client/connection/tests/node-half.spec.ts index a492a7a9c0..59c8c34ce2 100644 --- a/packages/client/connection/tests/node-half.spec.ts +++ b/packages/client/connection/tests/node-half.spec.ts @@ -80,6 +80,11 @@ describe('connection node half', () => { const loopback = fakeResponse() await routes[0]!.handler(fakeRequest({ host: '127.0.0.1:3080' }), loopback.response) expect(loopback.state.status).toBe(404) + // Undeclared LAN authority, no browser markers: the `--host 0.0.0.0` curl + // shape must reach the bridge even with an empty-by-default trust list. + const lan = fakeResponse() + await routes[0]!.handler(fakeRequest({ host: '192.168.1.5:3080' }), lan.response) + expect(lan.state.status).toBe(404) // Declared public authority, same-origin browser shape. const declared = fakeResponse() await routes[0]!.handler(fakeRequest({ From 7fd2abd8283cd6ca5eeac37de35fa287af6a4919 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 15:44:53 +0800 Subject: [PATCH 06/93] feat(host): directory-picker capability seam with dialog and browse backends MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The web GUI's folder picking was hardwired to one interaction: a native OS chooser compiled into the gateway, unusable for remote deployments and swappable only by editing apiproxy source. Directory picking becomes a three-package capability seam in packages/host: ctx.directoryPicker returns a discriminated capability — dialog (the extracted native chooser; host-display only) or browse (new: one-level listing + child creation over Node stdlib, hidden flags host-stamped, symlinks followed, ancestry crumbs; remote-capable). The gateway injects the seam, advertises the kind via host.describe.directoryPicker, serves host.listDirectory / host.createDirectory under browse, and answers directory-picker-unavailable across kinds. cordis.yml is the swap point; apps/cli keeps dialog mounted, so behavior is unchanged until the in-app browser PR flips the default. The connection fixture serves a deterministic browse tree; WorkspacesService gains the browse calls the browser UI will drive. Decision record: .agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md --- ...directory-picker-capability-seam.i18n.yaml | 6 + ...-07-28-directory-picker-capability-seam.md | 36 ++++++ ...-28-directory-picker-capability-seam.zh.md | 36 ++++++ apps/cli/cordis.yml | 5 + apps/cli/package.json | 3 +- docs/capability-seams.md | 9 ++ docs/config-catalog.md | 5 +- docs/cordis-catalog/services.md | 14 ++ docs/module-graph.md | 9 ++ packages/client/connection/src/client/api.ts | 1 + .../client/connection/src/client/fixture.ts | 69 +++++++++- .../client/connection/src/client/index.ts | 1 + .../connection/tests/connection.spec.ts | 4 +- packages/client/connection/tests/fake-api.ts | 17 ++- packages/client/runtime/src/client/index.ts | 6 +- .../runtime/src/client/workspaces/service.ts | 51 +++++++- packages/client/runtime/tests/fake-api.ts | 17 ++- .../runtime/tests/workspaces-service.spec.ts | 34 ++++- .../cordis/tool-cordis/src/api-catalog.ts | 30 +++++ packages/host/README.i18n.yaml | 4 +- packages/host/README.md | 3 + packages/host/README.zh.md | 3 + packages/host/apiproxy/README.i18n.yaml | 4 +- packages/host/apiproxy/README.md | 4 +- packages/host/apiproxy/README.zh.md | 4 +- packages/host/apiproxy/package.json | 1 + packages/host/apiproxy/src/api-proxy.ts | 55 +++++++- packages/host/apiproxy/src/api/host.schema.ts | 37 ++++++ packages/host/apiproxy/src/api/host.ts | 62 ++++++++- packages/host/apiproxy/src/api/index.ts | 2 +- packages/host/apiproxy/src/api/rpc-map.ts | 2 + packages/host/apiproxy/src/api/rpc.schema.ts | 4 + packages/host/apiproxy/src/api/rpc.ts | 4 + packages/host/apiproxy/src/fetch/client.ts | 11 +- packages/host/apiproxy/src/fetch/handler.ts | 7 +- packages/host/apiproxy/src/index.ts | 2 +- .../tests/api-proxy-workspace.spec.ts | 98 ++++++++++++-- .../apiproxy/tests/client-handler.spec.ts | 4 +- .../host/apiproxy/tests/fetch-carrier.spec.ts | 8 +- .../host/apiproxy/tests/rpc-schemas.spec.ts | 28 +++- packages/host/apiproxy/tsconfig.json | 3 + .../directory-picker-browse/README.i18n.yaml | 6 + .../host/directory-picker-browse/README.md | 21 +++ .../host/directory-picker-browse/README.zh.md | 21 +++ .../host/directory-picker-browse/package.json | 40 ++++++ .../host/directory-picker-browse/src/index.ts | 122 ++++++++++++++++++ .../directory-picker-browse/src/invariant.ts | 25 ++++ .../tests/service.spec.ts | 96 ++++++++++++++ .../directory-picker-browse/tsconfig.json | 24 ++++ .../directory-picker-dialog/README.i18n.yaml | 6 + .../host/directory-picker-dialog/README.md | 17 +++ .../host/directory-picker-dialog/README.zh.md | 17 +++ .../host/directory-picker-dialog/package.json | 40 ++++++ .../host/directory-picker-dialog/src/index.ts | 33 +++++ .../directory-picker-dialog/src/invariant.ts | 25 ++++ .../src/native-picker.ts} | 2 +- .../tests/native-picker.spec.ts} | 2 +- .../tests/service.spec.ts | 21 +++ .../directory-picker-dialog/tsconfig.json | 24 ++++ .../host/directory-picker/README.i18n.yaml | 6 + packages/host/directory-picker/README.md | 19 +++ packages/host/directory-picker/README.zh.md | 19 +++ packages/host/directory-picker/package.json | 37 ++++++ packages/host/directory-picker/src/index.ts | 118 +++++++++++++++++ .../host/directory-picker/src/invariant.ts | 22 ++++ .../host/directory-picker/tests/seam.spec.ts | 35 +++++ packages/host/directory-picker/tsconfig.json | 21 +++ pnpm-lock.yaml | 41 ++++++ scripts/gen-cordis-catalog.ts | 1 + scripts/gen-doc-graphs.ts | 9 ++ .../verify-package-readme-model-experience.ts | 3 + tsconfig.base.json | 6 + tsconfig.host.json | 3 + 73 files changed, 1536 insertions(+), 49 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md create mode 100644 .agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md create mode 100644 packages/host/directory-picker-browse/README.i18n.yaml create mode 100644 packages/host/directory-picker-browse/README.md create mode 100644 packages/host/directory-picker-browse/README.zh.md create mode 100644 packages/host/directory-picker-browse/package.json create mode 100644 packages/host/directory-picker-browse/src/index.ts create mode 100644 packages/host/directory-picker-browse/src/invariant.ts create mode 100644 packages/host/directory-picker-browse/tests/service.spec.ts create mode 100644 packages/host/directory-picker-browse/tsconfig.json create mode 100644 packages/host/directory-picker-dialog/README.i18n.yaml create mode 100644 packages/host/directory-picker-dialog/README.md create mode 100644 packages/host/directory-picker-dialog/README.zh.md create mode 100644 packages/host/directory-picker-dialog/package.json create mode 100644 packages/host/directory-picker-dialog/src/index.ts create mode 100644 packages/host/directory-picker-dialog/src/invariant.ts rename packages/host/{apiproxy/src/native-directory-picker.ts => directory-picker-dialog/src/native-picker.ts} (97%) rename packages/host/{apiproxy/tests/native-directory-picker.spec.ts => directory-picker-dialog/tests/native-picker.spec.ts} (99%) create mode 100644 packages/host/directory-picker-dialog/tests/service.spec.ts create mode 100644 packages/host/directory-picker-dialog/tsconfig.json create mode 100644 packages/host/directory-picker/README.i18n.yaml create mode 100644 packages/host/directory-picker/README.md create mode 100644 packages/host/directory-picker/README.zh.md create mode 100644 packages/host/directory-picker/package.json create mode 100644 packages/host/directory-picker/src/index.ts create mode 100644 packages/host/directory-picker/src/invariant.ts create mode 100644 packages/host/directory-picker/tests/seam.spec.ts create mode 100644 packages/host/directory-picker/tsconfig.json diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml new file mode 100644 index 0000000000..ccef0728d9 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml @@ -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 .agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md +2026-07-28-directory-picker-capability-seam.md: 8d9d34e7aed4525b243380a4a90801fe59bfc213 +2026-07-28-directory-picker-capability-seam.zh.md: 282f3905c3551912915088f70247260310f442cb diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md new file mode 100644 index 0000000000..8d9d34e7ae --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md @@ -0,0 +1,36 @@ +# Agent Note: A capability-discriminated directory-picker seam for the web-GUI host + +Status: implemented + +English | [中文](2026-07-28-directory-picker-capability-seam.zh.md) + +## Problem + +The web GUI's "Open local folder" flow was hardwired to one interaction: `host.pickDirectory` invoked a native OS chooser compiled into `dsh-host-apiproxy` (private module, test-only injection seam). That shape cannot serve remote deployments — no OS dialog reaches a browser on another machine — and the planned in-app directory browser (Figma `Harness` 802-56979) needs listing/creation primitives, which are a different interaction contract, not a different implementation of the same one. Swapping interactions required editing gateway source, against the repo's everything-is-a-plugin stance. + +## Decision + +A three-package capability seam in `packages/host/` — `directory-picker` (interface), `directory-picker-dialog`, `directory-picker-browse` (backends) — with one contract method: `capability()` returns a **discriminated union**, `{ kind: 'dialog', pick(signal) }` or `{ kind: 'browse', list(path?), createDirectory(path, name) }`. The gateway (`dsh-host-apiproxy`) injects `directoryPicker`, advertises the kind through `host.describe.directoryPicker`, serves the matching RPCs, and answers `directory-picker-unavailable` for the other kind; the client branches on the advertised kind and hides the affordance for unknown kinds (merge-extensible default). Composition (`cordis.yml`) is the swap point; the union is discriminated because the backends differ in *interaction shape* — flattening them into one method set would force every backend to fake the other's shape. + +Placement and policy rulings folded into this decision: + +- **Not the `ctx.fs` seam.** `packages/fs/` is the model/session-facing storage stack (policy events, sandbox-swappable backends). Riding it would couple GUI browsing to the model's confinement backend — swapping `fs-sandbox` for the model must never change GUI behavior — and OS facts (home anchoring, hidden conventions) are not storage primitives. The picker seam stays presentation-free and model-free; `packages/host/` is its consumer-domain home. +- **Dependency survey (hand-roll vs adopt).** Node's stdlib *is* the maintained cross-platform OS layer (`readdir(withFileTypes)`, `homedir`, path semantics); surveyed alternatives fail the dependency bar — file-manager packages (`node-file-manager`, `files-and-folders`, Syncfusion's provider) are whole HTTP apps (fit), drive-letter helpers (`drivelist` native addon, `windows-drive-letters` ~7y stale) fail health/proportionality. The browse backend is a thin adapter over stdlib. +- **Hidden entries: return-and-flag.** The host stamps `hidden` (POSIX dot convention) and returns everything; the client filters. Display policy stays client-side, and the planned show-hidden toggle becomes a client-only change. Windows' `FILE_ATTRIBUTE_HIDDEN` is not exposed by dirents — documented limitation until a native probe pays for itself. +- **Symlinks: follow for enterability.** `stat` probes symlinks (broken/cyclic → skipped); crumbs keep the logical path the operator navigated, and `workspace.create` already canonicalizes via realpath at adoption. +- **Whole-filesystem scope, no roots config.** `workspace.create` accepts arbitrary paths and the API serves bash-driving methods, so a browse root would be UX scoping, not a boundary; configurability without a consumer fails the evidence bar. Deferred until a deployment needs it. +- **The dialog backend stays.** Plugin-form was the point: multiple providers can serve the seam (an Electron shell would provide `dialog` natively). The backend names changed from mechanism (`native`/`local` — both run locally) to interaction (`-dialog`/`-browse`). + +## Alternatives considered + +- **Extend `ctx.fs` with browse methods.** Rejected: authority-domain coupling above; also a listing-for-display contract (hidden flags, crumbs, home anchor) does not belong on a storage seam. +- **One uniform seam method set (`pick(): path`).** Rejected: an in-app browser cannot be served behind a single host-side call — the browsing loop lives in the client and needs primitives on the wire; the dialog cannot implement primitives. The interaction difference is irreducible, hence the discriminant. +- **Direct stdlib calls inside apiproxy (no seam).** Rejected: keeps the gateway the only swap point (source edits), loses fixture/test backends, and contradicts the plugin doctrine that motivated the work. +- **Adopting a file-manager/drive-enumeration dependency.** Rejected per the survey above; recorded here as the dependency policy requires. + +## Consequences + +- `cordis.yml` chooses the interaction; `apps/cli` currently mounts `-dialog` (unchanged behavior), and the in-app browser PR flips the default to `-browse` with the GUI branching on `describe`. +- The wire gains `host.listDirectory`/`host.createDirectory`, four error codes, and the `describe.directoryPicker` field; the connection fixture serves a deterministic browse tree for keyless assembled tests. +- A future interaction (or an Electron `dialog` provider) is one backend package plus a client branch — no gateway surgery. +- `ApiProxyDefaults.pickDirectory` (test-only injection) is gone; tests provide a stub `ctx.directoryPicker` like any other service. diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md new file mode 100644 index 0000000000..282f3905c3 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md @@ -0,0 +1,36 @@ +# Agent Note:web GUI 宿主的能力可辨识目录选择 seam + +状态:已实现 + +[English](2026-07-28-directory-picker-capability-seam.md) | 中文 + +## 问题 + +web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pickDirectory` 调用编译进 `dsh-host-apiproxy` 的原生 OS 选择器(私有模块,仅测试注入缝)。这个形态服务不了远程部署——没有任何 OS 对话框能弹到另一台机器的浏览器里——而计划中的应用内目录浏览器(Figma `Harness` 802-56979)需要列举/创建原语,那是**另一种交互契约**,不是同一契约的另一种实现。想换交互只能改网关源码,违背仓库"一切皆插件"的立场。 + +## 决策 + +在 `packages/host/` 落一个三包能力 seam——`directory-picker`(接口)、`directory-picker-dialog`、`directory-picker-browse`(后端)——唯一契约方法 `capability()` 返回**可辨识联合**:`{ kind: 'dialog', pick(signal) }` 或 `{ kind: 'browse', list(path?), createDirectory(path, name) }`。网关(`dsh-host-apiproxy`)注入 `directoryPicker`,经 `host.describe.directoryPicker` 广播 kind,提供对应的 RPC,另一种 kind 的调用以 `directory-picker-unavailable` 应答;客户端按广播的 kind 分支,未知 kind 隐藏入口(可合并扩展的默认分支)。组合(`cordis.yml`)就是换装点;联合之所以可辨识,是因为后端差异在**交互形态**——压平成统一方法集会逼每个后端伪装另一方的形态。 + +并入本决策的位置与策略裁决: + +- **不用 `ctx.fs` seam。** `packages/fs/` 是面向模型/会话的存储栈(policy 事件、sandbox 可换后端)。骑上去会把 GUI 浏览耦合进模型的限制后端——为模型换 `fs-sandbox` 绝不能改变 GUI 行为——而 OS 事实(home 锚定、隐藏约定)也不是存储原语。picker seam 保持无展示、无模型;`packages/host/` 是它消费方域的家。 +- **依赖调研(手写 vs 引入)。** Node 标准库本身就是维护中的跨平台 OS 层(`readdir(withFileTypes)`、`homedir`、路径语义);调研过的替代品都过不了依赖门槛——文件管理器包(`node-file-manager`、`files-and-folders`、Syncfusion 的 provider)是整套 HTTP 应用(契合度不过),盘符工具(原生插件 `drivelist`、约七年未更的 `windows-drive-letters`)健康度/比例失当。browse 后端是标准库上的薄适配。 +- **隐藏条目:返回并打标。** 宿主标注 `hidden`(POSIX 点前缀约定)并返回全部条目;客户端过滤。展示策略留在客户端,计划中的"显示隐藏"开关变成纯客户端改动。Windows 的 `FILE_ATTRIBUTE_HIDDEN` 不被 dirent 暴露——记为限制,直到原生探测值回其成本。 +- **符号链接:为可进入性而跟随。** 用 `stat` 探测符号链接(断链/循环→跳过);面包屑保留操作者导航的逻辑路径,`workspace.create` 在接纳时本就做 realpath 规范化。 +- **全盘可浏览,不做 roots 配置。** `workspace.create` 接受任意路径且 API 本就提供驱动 bash 的方法,浏览根只会是 UX 范围而非边界;没有消费方的可配置性过不了证据门槛。等到有部署需要再做。 +- **dialog 后端保留。** 插件化正是目的:多方都能提供该 seam(Electron 壳可以原生提供 `dialog`)。后端命名从机制(`native`/`local`——两者都在本机运行)改为交互(`-dialog`/`-browse`)。 + +## 曾考虑的替代方案 + +- **给 `ctx.fs` 增加浏览方法。** 否决:上述权限域耦合;且面向展示的列举契约(hidden 标志、面包屑、home 锚点)不属于存储 seam。 +- **统一方法集的 seam(`pick(): path`)。** 否决:应用内浏览器无法藏在一次宿主侧调用后面——浏览循环在客户端,需要协议上的原语;而对话框实现不了原语。交互差异不可约,故用判别标签。 +- **apiproxy 里直接调标准库(不建 seam)。** 否决:换装点仍是改网关源码,失去 fixture/测试后端,与促成这项工作的插件教义相悖。 +- **引入文件管理器/盘符枚举依赖。** 按上文调研否决;依赖政策要求记录于此。 + +## 后果 + +- `cordis.yml` 决定交互形态;`apps/cli` 当前挂 `-dialog`(行为不变),应用内浏览器 PR 将把默认翻到 `-browse` 并让 GUI 按 `describe` 分支。 +- 协议新增 `host.listDirectory`/`host.createDirectory`、四个错误码与 `describe.directoryPicker` 字段;connection fixture 提供确定性浏览树供无密钥组装测试使用。 +- 未来的新交互(或 Electron 的 `dialog` 提供方)只是一个后端包加一个客户端分支——无需网关手术。 +- `ApiProxyDefaults.pickDirectory`(仅测试注入)删除;测试像提供其他服务一样提供 stub `ctx.directoryPicker`。 diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index 5397c08746..1ca28ecdaa 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -233,6 +233,11 @@ # The API gateway: the transport-agnostic dispatch face every client shape # shares. provider/model are the host default routing — the profile json's # mapping target (user config overrides these engineering defaults). +# Directory-picking backend consumed by the gateway's host.* picker RPCs. +# Swap point: mount '-browse' instead for the in-app browser (remote-capable). +- id: directory-picker + name: '@deepseek-ai/dsh-host-directory-picker-dialog' + - id: api-gateway name: '@deepseek-ai/dsh-host-apiproxy' config: diff --git a/apps/cli/package.json b/apps/cli/package.json index cd3edd2dd1..90b51e0397 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -48,13 +48,13 @@ "@deepseek-ai/dsh-fs-local": "workspace:^", "@deepseek-ai/dsh-fs-policy": "workspace:^", "@deepseek-ai/dsh-host-apiproxy": "workspace:^", + "@deepseek-ai/dsh-host-directory-picker-dialog": "workspace:^", "@deepseek-ai/dsh-host-webserver": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-llm-deepseek": "workspace:^", "@deepseek-ai/dsh-llm-retry": "workspace:^", "@deepseek-ai/dsh-paths": "workspace:^", "@deepseek-ai/dsh-plan-mode": "workspace:^", - "@deepseek-ai/dsh-subprocess-local": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", "@deepseek-ai/dsh-session-title": "workspace:^", @@ -69,6 +69,7 @@ "@deepseek-ai/dsh-subagent": "workspace:^", "@deepseek-ai/dsh-subagent-fork": "workspace:^", "@deepseek-ai/dsh-subagent-spawn": "workspace:^", + "@deepseek-ai/dsh-subprocess-local": "workspace:^", "@deepseek-ai/dsh-system-prompt": "workspace:^", "@deepseek-ai/dsh-tasks-local": "workspace:^", "@deepseek-ai/dsh-timeout-policy": "workspace:^", diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 9093f41f15..5cedd97dba 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -136,6 +136,10 @@ flowchart LR svc_spillStore["ctx.spillStore
Spill storage seam"] pkg_spill_local["spill-local"] pkg_spill_policy["spill-policy"] + pkg_directory_picker["directory-picker"] + svc_directoryPicker["ctx.directoryPicker
Workspace-directory picking seam"] + pkg_directory_picker_dialog["directory-picker-dialog"] + pkg_directory_picker_browse["directory-picker-browse"] pkg_webserver["webserver"] svc_httpServer["ctx.httpServer
HTTP route registration"] pkg_connection["connection"] @@ -159,6 +163,9 @@ flowchart LR pkg_compact --> svc_compact pkg_compact_basic --> svc_compact pkg_compact_tool_result_prune --> svc_toolResultPrune + pkg_directory_picker --> svc_directoryPicker + pkg_directory_picker_browse --> svc_directoryPicker + pkg_directory_picker_dialog --> svc_directoryPicker pkg_fs --> svc_fs pkg_fs_local --> svc_fs pkg_fs_sandbox --> svc_fs @@ -235,6 +242,7 @@ flowchart LR svc_codeRuntime --> pkg_tools svc_commands --> pkg_tui svc_compact --> pkg_compact_basic + svc_directoryPicker --> pkg_apiproxy svc_fs --> pkg_tool_fs svc_httpServer --> pkg_connection svc_httpServer --> pkg_hmr @@ -348,6 +356,7 @@ flowchart LR | `ctx.tasks` | `seam` | [`tasks`](../packages/tasks/tasks) | [`tasks-local`](../packages/tasks/tasks-local) | [`tool-bash`](../packages/bash/tool-bash), [`tool-pty`](../packages/pty/tool-pty), [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-tasks`](../packages/tasks/tool-tasks) | - | Producers (background bash, PTY sends, and subagent delegations) register running work; tool-tasks is the model-facing control surface that reads, lists, and kills it; tasks-local is the process-local registry. | | `ctx.web` | `seam` | [`web`](../packages/web/web) | [`web-search-exa`](../packages/web/web-search-exa), [`web-search-perplexity`](../packages/web/web-search-perplexity), [`web-search-deepseek`](../packages/web/web-search-deepseek), [`web-fetch-local`](../packages/web/web-fetch-local) | [`tool-web`](../packages/web/tool-web) | - | Search and fetch providers register into one ctx.web seam; tool-web owns the stable model-facing names. | | `ctx.spillStore` | `seam` | [`spill`](../packages/spill/spill) | [`spill-local`](../packages/spill/spill-local) | [`spill-policy`](../packages/spill/spill-policy) | - | The backend saves oversized tool text and returns a model-facing locator plus retrieval hint; spill-policy is the tools/post-execute consumer that decides when to spill. | +| `ctx.directoryPicker` | `seam` | `directory-picker` | `directory-picker-dialog`, `directory-picker-browse` | `apiproxy` | - | Discriminated interaction capability: the dialog backend opens one native OS chooser on the host display, the browse backend serves listing/creation primitives for the in-app browser; the gateway advertises the kind via host.describe. | | `ctx.httpServer` | `core` | `webserver` | - | `connection`, `modules`, `hmr` | - | Plain node:http carrier: named-route registry, index transform taps, and the static dist fallback; web-transport plugins register their own routes. | | `ctx.clientModuleHost` | `core` | `modules` | - | `hmr` | - | Composes the __DSH_BOOT__ entry graph from an incremental dshClient scan, serves plugin bundles, and notifies rebuilt/graph-changed subscribers. | | `ctx.workflows` | `seam` | [`workflow`](../packages/workflow/workflow) | [`workflow-workerthread`](../packages/workflow/workflow-workerthread) | [`tool-workflow`](../packages/workflow/tool-workflow), [`tool-ralph`](../packages/workflow/tool-ralph) | - | One engine per context (bash shape, no named-provider registry); the general workflow and fixed Ralph consumers start runs whose agent() calls fan out through ctx.subagents. | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index d30aff1f02..7d10c920c6 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -505,7 +505,7 @@ Source: [`packages/hooks/hooks-codex/src/index.ts:43`](../packages/hooks/hooks-c ## `@deepseek-ai/dsh-host-apiproxy` -Requires: `agents` · `llm` · `sessions` · `tools` · `userInteraction` · `workspace` +Requires: `agents` · `directoryPicker` · `llm` · `sessions` · `tools` · `userInteraction` · `workspace` ```ts config-catalog /** Gateway plugin config: host-level agent routing and Workspace creation root. */ @@ -2184,6 +2184,8 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co - `@deepseek-ai/dsh-commands` ([`packages/ui/commands/src/index.ts`](../packages/ui/commands/src/index.ts)) - `@deepseek-ai/dsh-fs-policy` ([`packages/fs/fs-policy/src/index.ts`](../packages/fs/fs-policy/src/index.ts)) - `@deepseek-ai/dsh-goal-session` — requires `agents` · `goals` · `sessions` ([`packages/goal/goal-session/src/index.ts`](../packages/goal/goal-session/src/index.ts)) +- `@deepseek-ai/dsh-host-directory-picker-browse` ([`packages/host/directory-picker-browse/src/index.ts`](../packages/host/directory-picker-browse/src/index.ts)) +- `@deepseek-ai/dsh-host-directory-picker-dialog` ([`packages/host/directory-picker-dialog/src/index.ts`](../packages/host/directory-picker-dialog/src/index.ts)) - `@deepseek-ai/dsh-llm` ([`packages/llm/llm/src/index.ts`](../packages/llm/llm/src/index.ts)) - `@deepseek-ai/dsh-lsp` ([`packages/lsp/lsp/src/index.ts`](../packages/lsp/lsp/src/index.ts)) - `@deepseek-ai/dsh-pty` ([`packages/pty/pty/src/index.ts`](../packages/pty/pty/src/index.ts)) @@ -2230,6 +2232,7 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them. - `@deepseek-ai/dsh-client-web-react` ([`packages/client/web-react/src/index.ts`](../packages/client/web-react/src/index.ts)) - `@deepseek-ai/dsh-helper` ([`packages/sdk/helper/src/index.ts`](../packages/sdk/helper/src/index.ts)) - `@deepseek-ai/dsh-hook-protocol` ([`packages/hooks/hook-protocol/src/index.ts`](../packages/hooks/hook-protocol/src/index.ts)) +- `@deepseek-ai/dsh-host-directory-picker` ([`packages/host/directory-picker/src/index.ts`](../packages/host/directory-picker/src/index.ts)) - `@deepseek-ai/dsh-jsonrpc-demo` ([`packages/examples/jsonrpc-demo/src/index.ts`](../packages/examples/jsonrpc-demo/src/index.ts)) - `@deepseek-ai/dsh-llm-mock-server` ([`packages/support/llm-mock-server/src/index.ts`](../packages/support/llm-mock-server/src/index.ts)) - `@deepseek-ai/dsh-loader-smoke` ([`packages/support/loader-smoke/src/index.ts`](../packages/support/loader-smoke/src/index.ts)) diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 75464938b0..eb212207b3 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -469,6 +469,20 @@ Types: [CompactionResult](../core-data-structures/compaction.md) · [CompactionT Source: [`packages/compact/compact/src/index.ts:54`](../../packages/compact/compact/src/index.ts) +## `ctx.directoryPicker` — `DirectoryPicker` (abstract seam) + +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. + +```ts cordis-catalog +/** + * The backend's interaction capability. + * @returns the discriminated capability consumers switch on. + */ +abstract capability(): DirectoryPickerCapability +``` + +Source: [`packages/host/directory-picker/src/index.ts:108`](../../packages/host/directory-picker/src/index.ts) + ## `ctx.fs` — `FileSystem` (abstract seam) Abstract filesystem provider. Targets must preserve identity across aliases; reads expose regular UTF-8 text or typed errors, listings are stable and content-free, and mutations are atomic. Optional guards add stale protection without changing the unguarded provider contract. diff --git a/docs/module-graph.md b/docs/module-graph.md index f69b89e379..03f4bee072 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -182,6 +182,9 @@ flowchart TD end subgraph group_host["packages/host"] pkg_host_apiproxy["host-apiproxy"] + pkg_host_directory_picker["host-directory-picker"] + pkg_host_directory_picker_browse["host-directory-picker-browse"] + pkg_host_directory_picker_dialog["host-directory-picker-dialog"] pkg_host_webserver["host-webserver"] end subgraph group_lsp["packages/lsp"] @@ -257,6 +260,9 @@ flowchart TD pkg_code_runtime --> pkg_invariants pkg_jsonrpc_demo --> pkg_invariants pkg_host_apiproxy --> pkg_invariants + pkg_host_directory_picker --> pkg_invariants + pkg_host_directory_picker_browse --> pkg_invariants + pkg_host_directory_picker_dialog --> pkg_invariants pkg_host_webserver --> pkg_invariants pkg_storage --> pkg_invariants pkg_subprocess --> pkg_invariants @@ -924,6 +930,9 @@ flowchart TD | [`code-runtime`](../packages/code-runtime/code-runtime) | `code-runtime` | [`invariants`](../packages/support/invariants) | | [`jsonrpc-demo`](../packages/examples/jsonrpc-demo) | `examples` | [`invariants`](../packages/support/invariants) | | [`host-apiproxy`](../packages/host/apiproxy) | `host` | [`invariants`](../packages/support/invariants) | +| [`host-directory-picker`](../packages/host/directory-picker) | `host` | [`invariants`](../packages/support/invariants) | +| [`host-directory-picker-browse`](../packages/host/directory-picker-browse) | `host` | [`invariants`](../packages/support/invariants) | +| [`host-directory-picker-dialog`](../packages/host/directory-picker-dialog) | `host` | [`invariants`](../packages/support/invariants) | | [`host-webserver`](../packages/host/webserver) | `host` | [`invariants`](../packages/support/invariants) | | [`storage`](../packages/storage/storage) | `storage` | [`invariants`](../packages/support/invariants) | | [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`invariants`](../packages/support/invariants) | diff --git a/packages/client/connection/src/client/api.ts b/packages/client/connection/src/client/api.ts index a1380c4b58..b68a7c1565 100644 --- a/packages/client/connection/src/client/api.ts +++ b/packages/client/connection/src/client/api.ts @@ -8,6 +8,7 @@ export type { ApiProxy, SessionsApi, SessionSummary, HostApi, EventsApi, MuxFrame, HostFrame, ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, ToolEventView, + DirectoryEntry, DirectoryListing, DirectoryPickerKind, WorkspaceApi, WorkspaceId, WorkspaceView, CommandsApi, CommandDescriptor, CommandExecuteResult, SkillsApi, SkillEntry, ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning, diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 5c7befd8c9..a490f0d27d 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -419,6 +419,37 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { updatedAt: fixtureEpoch, }] let nextWorkspace = 1 + + // In-memory browse tree behind the fixture's `browse` picker capability — + // deterministic content mirroring the design mock so assembled Web tests + // and snapshots can walk it. Leaves are materialized lazily: a child listed + // by its parent lists as empty until something is created inside it. + const FIXTURE_HOME = '/home/fixture' + const directoryTree = new Map([ + ['/', ['home']], + ['/home', ['fixture']], + [FIXTURE_HOME, ['Documents', 'Downloads', '.config']], + [`${FIXTURE_HOME}/Documents`, [ + 'project', 'deepseek-iOS', 'deepseek-android', 'deepseek-platform', + 'deepseek-web', 'deepseek-harness', 'deepseek-app', 'deepseek-landing-blog', + ]], + ]) + const childrenOf = (path: string): string[] | undefined => { + const known = directoryTree.get(path) + if (known !== undefined) return known + const parent = path.slice(0, path.lastIndexOf('/')) || '/' + const name = path.slice(path.lastIndexOf('/') + 1) + return directoryTree.get(parent)?.includes(name) === true ? [] : undefined + } + const crumbsOf = (path: string): { name: string; path: string; hidden: boolean }[] => { + const crumbs = [{ name: '/', path: '/', hidden: false }] + let acc = '' + for (const segment of path.split('/').filter(Boolean)) { + acc += `/${segment}` + crumbs.push({ name: segment, path: acc, hidden: false }) + } + return crumbs + } const mint = (): ReturnType => RpcId(`fx-rpc-${nextRpc++}`) /** Resident pending approval (stable rpcId: every mux open replays the same id, matching host replay semantics). */ const pendingApprovalRpcId = mint() @@ -774,8 +805,40 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { }, }, host: { - describe: request => ok(request, { version: '0.0.0-fixture', cwd: '/tmp/fixture', attachedSessions }), - pickDirectory: request => ok(request, { path: null }), + describe: request => ok(request, { version: '0.0.0-fixture', cwd: '/tmp/fixture', attachedSessions, directoryPicker: 'browse' as const }), + pickDirectory: request => err(request, { + code: 'directory-picker-unavailable', + message: 'the fixture host serves the browse capability', + details: { capability: 'browse' }, + }), + listDirectory: (request) => { + const target = request.payload.path ?? FIXTURE_HOME + const children = childrenOf(target) + if (children === undefined) { + return err(request, { code: 'directory-unreadable', message: `cannot list ${target}: not in the fixture tree`, details: { path: target } }) + } + return ok(request, { + path: target, + home: FIXTURE_HOME, + crumbs: crumbsOf(target), + entries: [...children].sort((a, b) => a.localeCompare(b)) + .map(name => ({ name, path: target === '/' ? `/${name}` : `${target}/${name}`, hidden: name.startsWith('.') })), + }) + }, + createDirectory: (request) => { + const parent = request.payload.path + const children = childrenOf(parent) + if (children === undefined) { + return err(request, { code: 'directory-create-failed', message: `missing parent ${parent}`, details: { path: parent } }) + } + const target = `${parent}/${request.payload.name}` + if (children.includes(request.payload.name)) { + return err(request, { code: 'directory-exists', message: `${target} already exists`, details: { path: target } }) + } + directoryTree.set(parent, [...children, request.payload.name]) + directoryTree.set(target, []) + return ok(request, { path: target }) + }, }, workspace: { list: request => ok(request, { items: workspaces.map(w => ({ ...w })) }), @@ -1027,6 +1090,8 @@ export class FixtureApiClient extends AbstractApiClient { case 'session.cancel': return this.api.sessions.cancel(request) case 'host.describe': return this.api.host.describe(request) case 'host.pickDirectory': return this.api.host.pickDirectory(request, new AbortController().signal) + case 'host.listDirectory': return this.api.host.listDirectory(request) + case 'host.createDirectory': return this.api.host.createDirectory(request) case 'workspace.list': return this.api.workspace.list(request) case 'workspace.create': return this.api.workspace.create(request) case 'workspace.rename': return this.api.workspace.rename(request) diff --git a/packages/client/connection/src/client/index.ts b/packages/client/connection/src/client/index.ts index 0e50d8617f..8e29b0b02e 100644 --- a/packages/client/connection/src/client/index.ts +++ b/packages/client/connection/src/client/index.ts @@ -13,6 +13,7 @@ import { WebApiClient } from './web-api-client.ts' export type { ApiProxy, SessionsApi, SessionSummary, HostApi, EventsApi, MuxFrame, HostFrame, ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, ToolEventView, + DirectoryEntry, DirectoryListing, DirectoryPickerKind, ToolCallView, ToolResultView, WorkspaceApi, WorkspaceId, WorkspaceView, CommandsApi, CommandDescriptor, CommandExecuteResult, SkillsApi, SkillEntry, ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning, diff --git a/packages/client/connection/tests/connection.spec.ts b/packages/client/connection/tests/connection.spec.ts index 4de4a31f25..bce6fce2ce 100644 --- a/packages/client/connection/tests/connection.spec.ts +++ b/packages/client/connection/tests/connection.spec.ts @@ -75,7 +75,7 @@ describe('connection lifecycle', () => { try { await vi.waitFor(() => { expect(describeCalls).toBe(2) }) // retried after backoff expect(connected).toBe(0) // never announced during the failed generation - gate.resolve(ok({ version: '0', cwd: '/f', attachedSessions: 0 })) + gate.resolve(ok({ version: '0', cwd: '/f', attachedSessions: 0, directoryPicker: 'browse' as const })) await vi.waitFor(() => { expect(connected).toBe(1) }) } finally { controller.stop() @@ -199,7 +199,7 @@ describe('connection lifecycle', () => { controller.start() try { await vi.waitFor(() => { expect(describeCalls).toBe(3) }) - gate.resolve(ok({ version: '0', cwd: '/f', attachedSessions: 0 })) + gate.resolve(ok({ version: '0', cwd: '/f', attachedSessions: 0, directoryPicker: 'browse' as const })) await vi.waitFor(() => { expect(connected).toBe(1) }) expect(states).toEqual(['reconnecting', 'connected']) // two failures, one reconnecting emission } finally { diff --git a/packages/client/connection/tests/fake-api.ts b/packages/client/connection/tests/fake-api.ts index 1bb49b19fb..06e62cf7a4 100644 --- a/packages/client/connection/tests/fake-api.ts +++ b/packages/client/connection/tests/fake-api.ts @@ -62,11 +62,22 @@ export class FakeApiClient implements IApiClient { payload => Promise.resolve(ok({ selected: { provider: payload.provider, model: payload.model } })) onPrompt: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) onCancel: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) - onDescribe: (payload: unknown) => Promise> = - () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 })) + onDescribe: (payload: unknown) => Promise> = + () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0, directoryPicker: 'browse' as const })) onPickDirectory: (payload: unknown) => Promise> = () => Promise.resolve(ok({ path: null })) + onListDirectory: (payload: unknown) => Promise> = + () => Promise.resolve(ok({ path: '/home/fake', home: '/home/fake', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [] })) + + onCreateDirectory: (payload: unknown) => Promise> = + () => Promise.resolve(ok({ path: '/home/fake/new' })) + private readonly muxConns: StreamConn[] = [] private readonly hostConns: StreamConn[] = [] @@ -88,6 +99,8 @@ export class FakeApiClient implements IApiClient { readonly host: IApiClient['host'] = { describe: payload => this.record('host.describe', payload, this.onDescribe(payload)), pickDirectory: payload => this.record('host.pickDirectory', payload, this.onPickDirectory(payload)), + listDirectory: payload => this.record('host.listDirectory', payload, this.onListDirectory(payload)), + createDirectory: payload => this.record('host.createDirectory', payload, this.onCreateDirectory(payload)), } readonly workspace: IApiClient['workspace'] = { diff --git a/packages/client/runtime/src/client/index.ts b/packages/client/runtime/src/client/index.ts index ec39ce9e1c..8e693c3514 100644 --- a/packages/client/runtime/src/client/index.ts +++ b/packages/client/runtime/src/client/index.ts @@ -13,7 +13,7 @@ export type { RootOwnerProps } from './slots.ts' export { SessionCreateError, SessionsService, scopeOf, workspaceTitleOf } from './sessions/service.ts' export { createScope } from './agents/scope.ts' export type { AgentScopeHandle } from './agents/scope.ts' -export { WorkspaceCreateError, WorkspacesService } from './workspaces/service.ts' +export { DirectoryBrowseError, WorkspaceCreateError, WorkspacesService } from './workspaces/service.ts' export type { Session } from './sessions/session.ts' export type { SessionBinding, SessionListState, SessionProvideContribution, SessionProvideDescriptor, SessionSummary, @@ -21,7 +21,9 @@ export type { export type { SessionListPhase } from './sessions/manager.ts' export type { WorkspaceListPhase } from './workspaces/manager.ts' export type { WorkspaceListState } from './workspaces/service.ts' -export type { WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-connection/client' +export type { + DirectoryEntry, DirectoryListing, DirectoryPickerKind, WorkspaceId, WorkspaceView, +} from '@deepseek-ai/dsh-client-connection/client' // Runtime owns the snapshot store; web-react only binds it to React. export { createSnapshotStore, defineStore, shallowEqual } from './contract/store.ts' export type { diff --git a/packages/client/runtime/src/client/workspaces/service.ts b/packages/client/runtime/src/client/workspaces/service.ts index fe345801c6..14ecace381 100644 --- a/packages/client/runtime/src/client/workspaces/service.ts +++ b/packages/client/runtime/src/client/workspaces/service.ts @@ -2,7 +2,8 @@ import type { Context } from 'cordis' import type { - IApiClient, RpcError, SessionId, WorkspaceId, WorkspaceView, + DirectoryListing, DirectoryPickerKind, IApiClient, RpcError, + SessionId, WorkspaceId, WorkspaceView, } from '@deepseek-ai/dsh-client-connection/client' import type { SnapshotStore } from '../contract/store.ts' import { createSnapshotStore } from '../contract/store.ts' @@ -29,6 +30,14 @@ export class WorkspaceCreateError extends Error { } } +/** Structured browse failure so the directory browser can branch on Host business codes. */ +export class DirectoryBrowseError extends Error { + constructor(readonly rpcError: RpcError) { + super(`directory browse failed: ${rpcError.code}: ${rpcError.message}`) + this.name = 'DirectoryBrowseError' + } +} + /** Real Workspace object layer and Host actions. */ export class WorkspacesService { /** UI-facing immutable projection; the manager remains wire truth. */ @@ -171,7 +180,7 @@ export class WorkspacesService { } /** - * Open the Host's native directory picker. + * Open the Host's native directory picker (the `dialog` capability). * @returns the selected path, or null when the user cancelled. */ async pickDirectory(): Promise { @@ -182,6 +191,44 @@ export class WorkspacesService { return response.result.value.path } + /** + * The directory-picking interaction the Host composed — the fact the picker + * UI branches on (`dialog` opens the native chooser; `browse` opens the + * in-app browser). Read per flow open: one describe round trip, no cache to + * go stale across reconnects. + * @returns the Host's advertised picker kind. + */ + async directoryPickerKind(): Promise { + const response = await this.api.host.describe({}) + if (!response.result.ok) { + throw new Error(`host describe failed: ${response.result.error.message}`) + } + return response.result.value.directoryPicker + } + + /** + * List one directory level through the Host's `browse` capability. + * @param path - absolute directory to list; absent lists the Host home directory. + * @returns the level's listing with breadcrumb ancestry. + */ + async listDirectory(path?: string): Promise { + const response = await this.api.host.listDirectory(path === undefined ? {} : { path }) + if (!response.result.ok) throw new DirectoryBrowseError(response.result.error) + return response.result.value + } + + /** + * Create one child directory through the Host's `browse` capability. + * @param path - absolute existing parent directory. + * @param name - single non-blank path segment. + * @returns the created directory's absolute path. + */ + async createDirectory(path: string, name: string): Promise { + const response = await this.api.host.createDirectory({ path, name }) + if (!response.result.ok) throw new DirectoryBrowseError(response.result.error) + return response.result.value.path + } + /** * Rename a Workspace. * @param workspaceId - target workspace. diff --git a/packages/client/runtime/tests/fake-api.ts b/packages/client/runtime/tests/fake-api.ts index a5eecd0cf5..98a222d9ae 100644 --- a/packages/client/runtime/tests/fake-api.ts +++ b/packages/client/runtime/tests/fake-api.ts @@ -80,11 +80,22 @@ export class FakeApiClient implements IApiClient { payload => Promise.resolve(ok({ selected: { provider: payload.provider, model: payload.model } })) onPrompt: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) onCancel: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) - onDescribe: (payload: unknown) => Promise> = - () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 })) + onDescribe: (payload: unknown) => Promise> = + () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0, directoryPicker: 'browse' as const })) onPickDirectory: (payload: unknown) => Promise> = () => Promise.resolve(ok({ path: null })) + onListDirectory: (payload: unknown) => Promise> = + () => Promise.resolve(ok({ path: '/home/fake', home: '/home/fake', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [] })) + + onCreateDirectory: (payload: unknown) => Promise> = + () => Promise.resolve(ok({ path: '/home/fake/new' })) + private readonly muxConns: StreamConn[] = [] private readonly hostConns: StreamConn[] = [] @@ -106,6 +117,8 @@ export class FakeApiClient implements IApiClient { readonly host: IApiClient['host'] = { describe: (payload: unknown) => this.record('host.describe', payload, this.onDescribe(payload)), pickDirectory: (payload: unknown) => this.record('host.pickDirectory', payload, this.onPickDirectory(payload)), + listDirectory: (payload: unknown) => this.record('host.listDirectory', payload, this.onListDirectory(payload)), + createDirectory: (payload: unknown) => this.record('host.createDirectory', payload, this.onCreateDirectory(payload)), } onWorkspaceList: (payload: unknown) => Promise> = () => Promise.resolve(ok({ items: [] })) diff --git a/packages/client/runtime/tests/workspaces-service.spec.ts b/packages/client/runtime/tests/workspaces-service.spec.ts index 5327066651..7fda11f54f 100644 --- a/packages/client/runtime/tests/workspaces-service.spec.ts +++ b/packages/client/runtime/tests/workspaces-service.spec.ts @@ -3,7 +3,7 @@ import { describe, expect, it } from 'vitest' import type { SessionId, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-connection/client' import { SessionsService } from '../src/client/sessions/service.ts' import { WorkspaceManager } from '../src/client/workspaces/manager.ts' -import { WorkspaceCreateError, WorkspacesService } from '../src/client/workspaces/service.ts' +import { DirectoryBrowseError, WorkspaceCreateError, WorkspacesService } from '../src/client/workspaces/service.ts' import { FakeApiClient, deferred, err, ok } from './fake-api.ts' const sid = (id: string): SessionId => id as SessionId @@ -234,6 +234,38 @@ describe('WorkspacesService', () => { api.onPickDirectory = () => Promise.resolve(ok({ path: null })) await expect(workspaces.pickDirectory()).resolves.toBeNull() expect(api.callsOf('host.pickDirectory')).toEqual([{}, {}]) + api.onPickDirectory = () => Promise.resolve(err({ code: 'internal', message: 'no chooser', details: {} })) + await expect(workspaces.pickDirectory()).rejects.toThrow(/no chooser/) + }) + + it('reads the picker kind from describe per call, failing loud on an unreachable host', async () => { + const ctx = new Context() + const api = new FakeApiClient() + const workspaces = new WorkspacesService(ctx, api, new SessionsService(ctx, api)) + await expect(workspaces.directoryPickerKind()).resolves.toBe('browse') + api.onDescribe = () => Promise.resolve(err({ code: 'internal', message: 'down', details: {} })) + await expect(workspaces.directoryPickerKind()).rejects.toThrow(/host describe failed/) + }) + + it('passes listings and creation through the browse wire, wrapping business failures', async () => { + const ctx = new Context() + const api = new FakeApiClient() + const workspaces = new WorkspacesService(ctx, api, new SessionsService(ctx, api)) + const listing = { path: '/home/u', home: '/home/u', crumbs: [{ name: '/', path: '/', hidden: false }], entries: [{ name: 'p', path: '/home/u/p', hidden: false }] } + api.onListDirectory = () => Promise.resolve(ok(listing)) + await expect(workspaces.listDirectory()).resolves.toEqual(listing) + await expect(workspaces.listDirectory('/home/u')).resolves.toEqual(listing) + // The optional path is omitted from the payload, not sent as undefined. + expect(api.callsOf('host.listDirectory')).toEqual([{}, { path: '/home/u' }]) + api.onListDirectory = () => Promise.resolve(err({ code: 'directory-unreadable', message: 'denied', details: { path: '/x' } })) + const listFailure = workspaces.listDirectory('/x') + await expect(listFailure).rejects.toBeInstanceOf(DirectoryBrowseError) + await expect(listFailure).rejects.toMatchObject({ rpcError: { code: 'directory-unreadable' } }) + + await expect(workspaces.createDirectory('/home/u', 'fresh')).resolves.toBe('/home/fake/new') + expect(api.callsOf('host.createDirectory')).toEqual([{ path: '/home/u', name: 'fresh' }]) + api.onCreateDirectory = () => Promise.resolve(err({ code: 'directory-exists', message: 'taken', details: { path: '/home/u/fresh' } })) + await expect(workspaces.createDirectory('/home/u', 'fresh')).rejects.toMatchObject({ rpcError: { code: 'directory-exists' } }) }) it('deletes a Workspace or preserves it when the Host rejects deletion', async () => { diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index 084652ea26..04b2e60ef0 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -260,6 +260,16 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'directoryPicker', + summary: 'Abstract directory-picking service.', + methods: [ + { + signature: 'abstract capability(): DirectoryPickerCapability', + jsDoc: '/**\n * The backend\'s interaction capability.\n * @returns the discriminated capability consumers switch on.\n */', + }, + ], + }, { key: 'fs', summary: 'Abstract filesystem provider.', @@ -1581,6 +1591,26 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'DiffResultView', declaration: 'export interface DiffResultView {\n card: \'diff\';\n title?: string;\n diffs: FileDiff[];\n}', }, + { + name: 'DirectoryEntry', + declaration: 'export interface DirectoryEntry {\n name: string;\n path: string;\n hidden: boolean;\n}', + }, + { + name: 'DirectoryListing', + declaration: 'export interface DirectoryListing {\n path: string;\n home: string;\n crumbs: DirectoryEntry[];\n entries: DirectoryEntry[];\n}', + }, + { + name: 'DirectoryPickerBrowseCapability', + declaration: 'export interface DirectoryPickerBrowseCapability {\n kind: \'browse\';\n list(path?: string): Promise;\n createDirectory(path: string, name: string): Promise;\n}', + }, + { + name: 'DirectoryPickerCapability', + declaration: 'export type DirectoryPickerCapability = DirectoryPickerDialogCapability | DirectoryPickerBrowseCapability;', + }, + { + name: 'DirectoryPickerDialogCapability', + declaration: 'export interface DirectoryPickerDialogCapability {\n kind: \'dialog\';\n pick(signal: AbortSignal): Promise;\n}', + }, { name: 'Domain', declaration: 'export interface Domain {\n readonly name: string;\n readonly global: DomainGlobalHandleOf;\n table(name: N): KvTable, TableValueOf>;\n close(): Promise;\n}', diff --git a/packages/host/README.i18n.yaml b/packages/host/README.i18n.yaml index b406dd394e..9421dce1c5 100644 --- a/packages/host/README.i18n.yaml +++ b/packages/host/README.i18n.yaml @@ -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/README.md -README.md: 61e50cb64b95932085342b01a22d029cf8d5a228 -README.zh.md: 3109eccf89ee4c2d4d01be546e3ee9ead9084edc +README.md: 81c483674c0d30847318b8fd9014bd8bb7d341c2 +README.zh.md: 8b5ecd89ff4b1407cfa8c2bad63c77412b5fd16c diff --git a/packages/host/README.md b/packages/host/README.md index 61e50cb64b..81c483674c 100644 --- a/packages/host/README.md +++ b/packages/host/README.md @@ -8,5 +8,8 @@ The host side of the dsh web GUI: the API gateway every client shape shares, and |---|---|---| | `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 `dialog`/`browse` capability the gateway's picker RPCs delegate to | `ctx.directoryPicker` | +| `directory-picker-dialog/` | Native-OS-chooser backend (osascript / PowerShell / Zenity+KDialog); host-display only | (registers `ctx.directoryPicker`) | +| `directory-picker-browse/` | In-app browsing backend: listing/creation primitives over Node stdlib; remote-capable | (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. diff --git a/packages/host/README.zh.md b/packages/host/README.zh.md index 3109eccf89..8b5ecd89ff 100644 --- a/packages/host/README.zh.md +++ b/packages/host/README.zh.md @@ -8,5 +8,8 @@ dsh web GUI 的宿主侧:所有客户端形态共用的 API 网关,以及承 |---|---|---| | `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 委托的可辨识 `dialog`/`browse` 能力 | `ctx.directoryPicker` | +| `directory-picker-dialog/` | 原生 OS 选择器后端(osascript/PowerShell/Zenity+KDialog);仅宿主屏幕可用 | (注册 `ctx.directoryPicker`) | +| `directory-picker-browse/` | 应用内浏览后端:基于 Node 标准库的列举/创建原语;支持远程 | (注册 `ctx.directoryPicker`) | `apiproxy` 在设计上与传输方式无关——它不注册任何路由;载体自行包装 `ctx.apiProxy`。HTTP 载体路由(连同其 `/api` 浏览器信任栅栏)由 [`client/connection`](../client/connection/README.md) 的 node 半侧挂载,这正是该包住在 client 组的原因:它拥有这条线的两端。 diff --git a/packages/host/apiproxy/README.i18n.yaml b/packages/host/apiproxy/README.i18n.yaml index bfda016b16..55fe86c794 100644 --- a/packages/host/apiproxy/README.i18n.yaml +++ b/packages/host/apiproxy/README.i18n.yaml @@ -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: 2f51aa23e2639e2e98dfdd8aaf71e807d641c3dc -README.zh.md: 687e60879702a762d9e85295789b77daea4bd4ac +README.md: 7c53e6dc9ac5758fce91d8b39abbfab6641384d1 +README.zh.md: 5089935fe545bfc6ac3ddb39b9a2a25b50e1ceab diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index 2f51aa23e2..7c53e6dc9a 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -16,7 +16,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's prefix-wide trust fence (dsh-client-connection) covers this method like every other `/api` request. +Directory picking delegates to the composed `ctx.directoryPicker` backend ([the directory-picker seam](../directory-picker/README.md)); `host.describe.directoryPicker` advertises the capability kind the client renders for, and a method called outside the advertised kind fails with `directory-picker-unavailable`. Under `dialog`, `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. `session.history` pages on message boundaries, and its tail page (no `beforeSeq`) carries two session-level extras the page window cannot supply: the in-flight partial's chunk events, and `todos` — the latest `todo/write` whole-list projection over the full log. Older pages omit `todos` because the projection is session-level, not per-page; a tail response that omits it means the whole log holds no `todo/write`, so clients read the absent field as the empty plan rather than as unchanged state. @@ -39,4 +39,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 `dialog` capability, `host.pickDirectory` reports an actionable error when neither Zenity nor KDialog is installed; the browse backend is the composition-level fallback (see the [dialog backend README](../directory-picker-dialog/README.md)). diff --git a/packages/host/apiproxy/README.zh.md b/packages/host/apiproxy/README.zh.md index 687e608797..5089935fe5 100644 --- a/packages/host/apiproxy/README.zh.md +++ b/packages/host/apiproxy/README.zh.md @@ -16,7 +16,7 @@ mux 流会在每个已附加会话的订阅基线之后,以及对应的实时 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 秒超时限制的一元调用;调用方发出的中止信号和连接中止仍会传播至原生进程。浏览器载体的前缀级信任栅栏(dsh-client-connection)像覆盖其他所有 `/api` 请求一样覆盖该方法。 +目录选择委托给组合的 `ctx.directoryPicker` 后端([目录选择 seam](../directory-picker/README.md));`host.describe.directoryPicker` 广播客户端应按其渲染的能力 kind,调用广播之外的方法会以 `directory-picker-unavailable` 失败。在 `dialog` 下,`host.pickDirectory` 打开一个原生选择器并返回选中路径(取消为 `null`);该方法需等待用户完成操作,是唯一不受默认 30 秒超时限制的一元调用,调用方与连接的中止仍会传播至原生进程。在 `browse` 下,`host.listDirectory` 返回一个按名称排序的目录层级,携带面包屑祖先链、`home` 锚点与宿主判定的 `hidden` 标志(不带路径即家目录),`host.createDirectory` 创建一个经校验的子段;后端的类型化失败 1:1 映射为 `directory-unreadable`/`directory-exists`/`directory-create-failed` 错误码。浏览器载体的前缀级信任栅栏(dsh-client-connection)像覆盖其他所有 `/api` 请求一样覆盖上述全部方法。 `session.history` 按消息边界分页,其尾页(不带 `beforeSeq`)额外携带两项页窗口本身无法提供的会话级数据:进行中局部消息的 chunk 事件,以及 `todos`——整份日志上最后一次 `todo/write` 的整表投影。较早的页面不带 `todos`,因为该投影是会话级而非分页级的;尾页响应缺少该字段意味着整份日志中没有任何 `todo/write`,因此客户端要把缺失字段读作空计划,而不是读作「状态未变」。 @@ -39,4 +39,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 原生选择器依赖桌面工具**:在 `dialog` 能力下,Zenity 和 KDialog 均未安装时,`host.pickDirectory` 会给出包含解决建议的错误提示;组合层面的回退是 browse 后端(见 [dialog 后端 README](../directory-picker-dialog/README.md))。 diff --git a/packages/host/apiproxy/package.json b/packages/host/apiproxy/package.json index 0c7107a1f9..676f3ac319 100644 --- a/packages/host/apiproxy/package.json +++ b/packages/host/apiproxy/package.json @@ -43,6 +43,7 @@ "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-brand": "workspace:^", "@deepseek-ai/dsh-commands": "workspace:^", + "@deepseek-ai/dsh-host-directory-picker": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-persistence": "workspace:^", diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index 58922284be..6e302e3e57 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -39,7 +39,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' /** Page size when history is called without maxMessages. */ const DEFAULT_MAX_MESSAGES = 50 @@ -193,6 +193,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 @@ -201,8 +209,6 @@ 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 } /** The tool/call payload fields the presenter path reads. */ @@ -990,12 +996,21 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro provider: defaults.provider, model: defaults.model, attachedSessions: ctx.agents.list().length, + directoryPicker: ctx.directoryPicker.capability().kind, })) }, async pickDirectory(request, signal) { + const capability = ctx.directoryPicker.capability() + if (capability.kind !== 'dialog') { + return err(request, { + code: 'directory-picker-unavailable', + message: `host.pickDirectory needs the dialog 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) { @@ -1012,6 +1027,38 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro }) } }, + + async listDirectory(request) { + 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 { + return ok(request, await capability.list(request.payload.path)) + } catch (error: unknown) { + 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)) + } + }, }, commands: { diff --git a/packages/host/apiproxy/src/api/host.schema.ts b/packages/host/apiproxy/src/api/host.schema.ts index c7353c4360..a73b659970 100644 --- a/packages/host/apiproxy/src/api/host.schema.ts +++ b/packages/host/apiproxy/src/api/host.schema.ts @@ -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,7 @@ export const hostDescribeValueSchema = z.object({ provider: z.string().optional(), model: z.string().optional(), attachedSessions: z.number().int().nonnegative(), + directoryPicker: z.union([z.literal('dialog'), z.literal('browse')]), }) satisfies z.ZodType>> /** host.pickDirectory request payload (empty object literal). */ @@ -25,3 +27,38 @@ export const hostPickDirectoryRequestSchema = z.object({}) satisfies z.ZodType>> + +/** 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> + +/** host.listDirectory request payload; an absent path lists the home directory. */ +export const hostListDirectoryRequestSchema = z.object({ + path: z.string().optional(), +}) satisfies z.ZodType>> + +/** host.listDirectory response value. */ +export const hostListDirectoryValueSchema = z.object({ + path: z.string(), + home: z.string(), + crumbs: z.array(directoryEntrySchema), + entries: z.array(directoryEntrySchema), +}) satisfies z.ZodType>> + +/** 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>> + +/** host.createDirectory response value: the created directory's absolute path. */ +export const hostCreateDirectoryValueSchema = z.object({ + path: z.string(), +}) satisfies z.ZodType>> diff --git a/packages/host/apiproxy/src/api/host.ts b/packages/host/apiproxy/src/api/host.ts index e3573346f4..abdb3c468b 100644 --- a/packages/host/apiproxy/src/api/host.ts +++ b/packages/host/apiproxy/src/api/host.ts @@ -5,6 +5,40 @@ import type { RpcRequest, RpcResponse } from './rpc.ts' +/** + * The composed directory-picker interaction the host serves (mirror of the + * `ctx.directoryPicker` capability kind): `dialog` = one native OS chooser on + * the host display (`host.pickDirectory`); `browse` = in-app listing/creation + * primitives (`host.listDirectory`/`host.createDirectory`). Calling a method + * outside the advertised kind fails with `directory-picker-unavailable`. + */ +export type DirectoryPickerKind = 'dialog' | 'browse' + +/** 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[] +} + /** Host-level unary methods. */ export interface HostApi { /** @@ -13,7 +47,8 @@ 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); + * directoryPicker = the composed picker interaction the client renders for. */ describe(request: RpcRequest<{}>): Promise> - /** 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 `dialog` capability. + */ pickDirectory( request: RpcRequest<{}>, signal: AbortSignal, ): Promise> + + /** + * 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`. + */ + listDirectory( + request: RpcRequest<{ path?: string }>, + ): Promise> + + /** + * 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> } diff --git a/packages/host/apiproxy/src/api/index.ts b/packages/host/apiproxy/src/api/index.ts index ad5fbd3bf0..84cd8f8252 100644 --- a/packages/host/apiproxy/src/api/index.ts +++ b/packages/host/apiproxy/src/api/index.ts @@ -29,7 +29,7 @@ export type { HistoryEntry, ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning, ModelReasoningEffort, ModelTarget, SessionModels, SessionsApi, SessionSummary, } from './sessions.ts' -export type { HostApi } from './host.ts' +export type { DirectoryEntry, DirectoryListing, DirectoryPickerKind, HostApi } from './host.ts' export type { WorkspaceApi, WorkspaceId, WorkspaceView } from './workspace.ts' export type { CommandsApi, CommandDescriptor, CommandExecuteResult } from './commands.ts' export type { SkillsApi, SkillEntry } from './skills.ts' diff --git a/packages/host/apiproxy/src/api/rpc-map.ts b/packages/host/apiproxy/src/api/rpc-map.ts index d98a7c01b3..668ecfc5c7 100644 --- a/packages/host/apiproxy/src/api/rpc-map.ts +++ b/packages/host/apiproxy/src/api/rpc-map.ts @@ -26,6 +26,8 @@ export interface RpcMethodMap { 'session.cancel': SessionsApi['cancel'] 'host.describe': HostApi['describe'] 'host.pickDirectory': HostApi['pickDirectory'] + 'host.listDirectory': HostApi['listDirectory'] + 'host.createDirectory': HostApi['createDirectory'] 'workspace.list': WorkspaceApi['list'] 'workspace.create': WorkspaceApi['create'] 'workspace.rename': WorkspaceApi['rename'] diff --git a/packages/host/apiproxy/src/api/rpc.schema.ts b/packages/host/apiproxy/src/api/rpc.schema.ts index 300cc210b6..b3632798fb 100644 --- a/packages/host/apiproxy/src/api/rpc.schema.ts +++ b/packages/host/apiproxy/src/api/rpc.schema.ts @@ -42,6 +42,10 @@ export const rpcErrorSchema: z.ZodType = 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('internal'), message: z.string(), details: z.object({}) }), ]) as unknown as z.ZodType diff --git a/packages/host/apiproxy/src/api/rpc.ts b/packages/host/apiproxy/src/api/rpc.ts index 52b2f503dd..c1eb4c06f0 100644 --- a/packages/host/apiproxy/src/api/rpc.ts +++ b/packages/host/apiproxy/src/api/rpc.ts @@ -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 } 'internal': {} } diff --git a/packages/host/apiproxy/src/fetch/client.ts b/packages/host/apiproxy/src/fetch/client.ts index 62bef32b29..912d98c477 100644 --- a/packages/host/apiproxy/src/fetch/client.ts +++ b/packages/host/apiproxy/src/fetch/client.ts @@ -13,7 +13,10 @@ import { RpcId } from '../api/rpc.ts' 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, hostPickDirectoryValueSchema } from '../api/host.schema.ts' +import { + hostCreateDirectoryValueSchema, hostDescribeValueSchema, + hostListDirectoryValueSchema, hostPickDirectoryValueSchema, +} from '../api/host.schema.ts' import { sessionCancelValueSchema, sessionCreateValueSchema, @@ -61,6 +64,8 @@ export interface IApiClient { host: { describe(payload: RequestPayload<'host.describe'>, signal?: AbortSignal): Promise>> pickDirectory(payload: RequestPayload<'host.pickDirectory'>, signal?: AbortSignal): Promise>> + listDirectory(payload: RequestPayload<'host.listDirectory'>, signal?: AbortSignal): Promise>> + createDirectory(payload: RequestPayload<'host.createDirectory'>, signal?: AbortSignal): Promise>> } workspace: { list(payload: RequestPayload<'workspace.list'>, signal?: AbortSignal): Promise>> @@ -98,6 +103,8 @@ const UNARY_VALUE_SCHEMAS: { [K in keyof RpcMethodMap]: z.ZodType 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), } readonly workspace: IApiClient['workspace'] = { diff --git a/packages/host/apiproxy/src/fetch/handler.ts b/packages/host/apiproxy/src/fetch/handler.ts index 8160f9d69a..29d57b3b55 100644 --- a/packages/host/apiproxy/src/fetch/handler.ts +++ b/packages/host/apiproxy/src/fetch/handler.ts @@ -23,7 +23,10 @@ import { sessionPromptRequestSchema, sessionSelectModelRequestSchema, } from '../api/sessions.schema.ts' -import { hostDescribeRequestSchema, hostPickDirectoryRequestSchema } from '../api/host.schema.ts' +import { + hostCreateDirectoryRequestSchema, hostDescribeRequestSchema, + hostListDirectoryRequestSchema, hostPickDirectoryRequestSchema, +} from '../api/host.schema.ts' import { workspaceCreateRequestSchema, workspaceDeleteRequestSchema, @@ -60,6 +63,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) => api.host.listDirectory(r) }, + 'host.createDirectory': { schema: hostCreateDirectoryRequestSchema, invoke: (api, r) => api.host.createDirectory(r) }, 'workspace.list': { schema: workspaceListRequestSchema, invoke: (api, r) => api.workspace.list(r) }, 'workspace.create': { schema: workspaceCreateRequestSchema, invoke: (api, r) => api.workspace.create(r) }, 'workspace.rename': { schema: workspaceRenameRequestSchema, invoke: (api, r) => api.workspace.rename(r) }, diff --git a/packages/host/apiproxy/src/index.ts b/packages/host/apiproxy/src/index.ts index e7ef6c7332..44944e539a 100644 --- a/packages/host/apiproxy/src/index.ts +++ b/packages/host/apiproxy/src/index.ts @@ -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 = z.object({ provider: z.string().required(), diff --git a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts index c6354db928..9572c76b23 100644 --- a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts @@ -10,6 +10,8 @@ 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,7 +59,7 @@ 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-'))), - pickDirectory?: (signal: AbortSignal) => Promise, + picker: DirectoryPickerCapability = { kind: 'dialog', pick: async () => null }, ) { const ctx = new Context() await ctx.plugin(SessionStore) @@ -92,36 +94,114 @@ 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, - ...pickDirectory === undefined ? {} : { pickDirectory }, }) 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, async () => '/tmp/project') + it('returns a selected path or explicit cancellation from the dialog capability', async () => { + const selected = await harness(undefined, { kind: 'dialog', 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, async () => null) + const cancelled = await harness(undefined, { kind: 'dialog', 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 () => { - const { api } = await harness(undefined, signal => new Promise((_resolve, reject) => { - signal.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true }) - })) + it('propagates abort into the dialog capability as a cancelled RPC error', async () => { + const { api } = await harness(undefined, { + kind: 'dialog', + pick: signal => new Promise((_resolve, reject) => { + signal.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true }) + }), + }) const abort = new AbortController() const pending = api.host.pickDirectory(request({}), abort.signal) abort.abort() expect((await pending).result).toMatchObject({ ok: false, error: { code: 'cancelled' } }) }) + + it('folds a non-abort dialog failure into an internal error', async () => { + const { api } = await harness(undefined, { kind: 'dialog', 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 dialog 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 }], + } + }, + 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({})) + expect(home.result).toMatchObject({ ok: true, value: { path: '/home/user', home: '/home/user' } }) + const listed = await api.host.listDirectory(request({ path: '/home/user/projects' })) + 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' }))).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('refuses the browse RPCs under a dialog composition and advertises the kind in describe', async () => { + const { api } = await harness() + expect((await api.host.describe(request({}))).result).toMatchObject({ ok: true, value: { directoryPicker: 'dialog' } }) + expect((await api.host.listDirectory(request({}))).result).toMatchObject({ + ok: false, error: { code: 'directory-picker-unavailable', details: { capability: 'dialog' } }, + }) + expect((await api.host.createDirectory(request({ path: '/x', name: 'y' }))).result).toMatchObject({ + ok: false, error: { code: 'directory-picker-unavailable', details: { capability: 'dialog' } }, + }) + const browse = await harness(undefined, BROWSE_STUB) + expect((await browse.api.host.describe(request({}))).result).toMatchObject({ ok: true, value: { directoryPicker: 'browse' } }) + }) }) describe('workspace.create', () => { diff --git a/packages/host/apiproxy/tests/client-handler.spec.ts b/packages/host/apiproxy/tests/client-handler.spec.ts index 0885b7b896..dc92128487 100644 --- a/packages/host/apiproxy/tests/client-handler.spec.ts +++ b/packages/host/apiproxy/tests/client-handler.spec.ts @@ -48,8 +48,10 @@ function scriptedApi(overrides: { ...overrides.sessions, }, host: { - describe: r => ok(r, { version: '0-test', cwd: '/t', attachedSessions: 0 }), + describe: r => ok(r, { version: '0-test', cwd: '/t', attachedSessions: 0, directoryPicker: 'browse' as const }), pickDirectory: r => ok(r, { path: null }), + listDirectory: r => ok(r, { path: '/t', home: '/t', crumbs: [], entries: [] }), + createDirectory: r => ok(r, { path: '/t/new' }), ...overrides.host, }, workspace: { diff --git a/packages/host/apiproxy/tests/fetch-carrier.spec.ts b/packages/host/apiproxy/tests/fetch-carrier.spec.ts index 318dbc970e..a0645f4750 100644 --- a/packages/host/apiproxy/tests/fetch-carrier.spec.ts +++ b/packages/host/apiproxy/tests/fetch-carrier.spec.ts @@ -75,11 +75,17 @@ function fakeApi(overrides: Partial<{ muxFrames: MuxFrame[]; hostFrames: HostFra }, host: { async describe(request) { - return { rpcId: request.rpcId, result: { ok: true, value: { version: 'v', cwd: '/w', attachedSessions: 0 } } } + return { rpcId: request.rpcId, result: { ok: true, value: { version: 'v', cwd: '/w', attachedSessions: 0, directoryPicker: 'dialog' as const } } } }, 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: [] } } } + }, + async createDirectory(request) { + return { rpcId: request.rpcId, result: { ok: true, value: { path: '/w/new' } } } + }, }, workspace: { async list(request) { diff --git a/packages/host/apiproxy/tests/rpc-schemas.spec.ts b/packages/host/apiproxy/tests/rpc-schemas.spec.ts index 9f1309b476..f64883c85b 100644 --- a/packages/host/apiproxy/tests/rpc-schemas.spec.ts +++ b/packages/host/apiproxy/tests/rpc-schemas.spec.ts @@ -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, @@ -204,9 +208,27 @@ describe('sessions domain schemas', () => { describe('host domain schemas', () => { it('validates describe request/value', () => { expect(hostDescribeRequestSchema.parse({})).toEqual({}) - const value = hostDescribeValueSchema.parse({ version: '1', cwd: '/x', provider: 'p', model: 'm', attachedSessions: 2 }) + const value = hostDescribeValueSchema.parse({ version: '1', cwd: '/x', provider: 'p', model: 'm', attachedSessions: 2, directoryPicker: 'dialog' }) expect(value.attachedSessions).toBe(2) - expect(hostDescribeValueSchema.parse({ version: '1', cwd: '/x', attachedSessions: 0 }).provider).toBeUndefined() + expect(hostDescribeValueSchema.parse({ version: '1', cwd: '/x', attachedSessions: 0, directoryPicker: 'browse' }).provider).toBeUndefined() + expect(() => hostDescribeValueSchema.parse({ version: '1', cwd: '/x', attachedSessions: 0, directoryPicker: 'other' })).toThrow() + }) + + 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 }], + }) + expect(listing.entries[0]?.hidden).toBe(true) + 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' }) }) }) diff --git a/packages/host/apiproxy/tsconfig.json b/packages/host/apiproxy/tsconfig.json index f5aabb1cf8..100cbe2893 100644 --- a/packages/host/apiproxy/tsconfig.json +++ b/packages/host/apiproxy/tsconfig.json @@ -50,6 +50,9 @@ { "path": "../../workspace/workspace" }, + { + "path": "../directory-picker" + }, { "path": "../../support/invariants" } diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml new file mode 100644 index 0000000000..fea6c71d41 --- /dev/null +++ b/packages/host/directory-picker-browse/README.i18n.yaml @@ -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: f86f74acf4922d490b23c033a281436f1a428f13 +README.zh.md: 0d240630a8b21003c5285bc75e93aac9adf36d92 diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md new file mode 100644 index 0000000000..f86f74acf4 --- /dev/null +++ b/packages/host/directory-picker-browse/README.md @@ -0,0 +1,21 @@ +# @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 dialog 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. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). + +## Model Experience + +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. diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md new file mode 100644 index 0000000000..0d240630a8 --- /dev/null +++ b/packages/host/directory-picker-browse/README.zh.md @@ -0,0 +1,21 @@ +# @deepseek-ai/dsh-host-directory-picker-browse + +[English](README.md) | 中文 + +[目录选择 seam](../directory-picker/README.md) 的**应用内浏览后端**:`BrowseDirectoryPicker` 以 `browse` 能力注册 `ctx.directoryPicker`——基于 Node 标准库(跨 OS 适配本就由它承担)提供单层目录列举与子目录创建。宿主屏幕上不渲染任何东西,因此该后端能服务 dialog 后端无法触及的远程客户端。 + +行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 + +## 模型体验 + +无。该后端服务于 GUI 宿主的目录选择;这里没有任何内容进入模型请求。 + +#### KV 缓存影响 + +无;该包既不组装也不发送提供方请求。 + +## 已知限制与延期工作 + +- **不读取 Windows 隐藏属性**——Node 的 dirent 不暴露 `FILE_ATTRIBUTE_HIDDEN`,因此在所有平台上 `hidden` 都意味着点前缀,直到原生探测值回其成本为止。 +- **不枚举盘符根**——Windows 上祖先链止于盘符根;跨盘依赖浏览器 UI 的路径输入入口,而不是这里的枚举原语。 +- **全盘可浏览**——没有按部署限定的浏览根;`workspace.create` 今天就接受任意路径,这里的根只会是 UX 范围而非边界——等到有部署需要时再做。 diff --git a/packages/host/directory-picker-browse/package.json b/packages/host/directory-picker-browse/package.json new file mode 100644 index 0000000000..c1e8626bed --- /dev/null +++ b/packages/host/directory-picker-browse/package.json @@ -0,0 +1,40 @@ +{ + "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" + }, + "./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", + "dependencies": { + "@deepseek-ai/dsh-host-directory-picker": "workspace:^" + }, + "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" + } +} diff --git a/packages/host/directory-picker-browse/src/index.ts b/packages/host/directory-picker-browse/src/index.ts new file mode 100644 index 0000000000..5f2a9429c0 --- /dev/null +++ b/packages/host/directory-picker-browse/src/index.ts @@ -0,0 +1,122 @@ +/** + * 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, readdir, stat } from 'node:fs/promises' +import { homedir } from 'node:os' +import { basename, dirname, join, resolve } from 'node:path' +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 + } +} + +/** 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): Promise { + const path = join(parent, name) + let enterable = isDirectory + if (!enterable && isSymbolicLink) { + try { + enterable = (await stat(path)).isDirectory() + } catch { + // 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('.') } +} + +/** The `ctx.directoryPicker` browse implementation (stable capability object per service life). */ +export default class BrowseDirectoryPicker extends DirectoryPicker { + private readonly browseCapability: DirectoryPickerCapability = { + kind: 'browse', + list: path => this.list(path), + createDirectory: (path, name) => this.createDirectory(path, name), + } + + /** + * The browse interaction capability. + * @returns the stable `browse` capability object. + */ + capability(): DirectoryPickerCapability { + return this.browseCapability + } + + private async list(path?: string): Promise { + const home = homedir() + const target = resolve(path ?? home) + let names: { name: string; isDirectory: boolean; isSymbolicLink: boolean }[] + try { + const dirents = await readdir(target, { withFileTypes: true }) + names = dirents.map(dirent => ({ + name: dirent.name, + isDirectory: dirent.isDirectory(), + isSymbolicLink: dirent.isSymbolicLink(), + })) + } catch (error: unknown) { + throw new DirectoryPickerError('directory-unreadable', target, `cannot list ${target}: ${messageOf(error)}`) + } + const rows = await Promise.all(names.map(entry => directoryRow(target, entry.name, entry.isDirectory, entry.isSymbolicLink))) + const entries = rows.filter((row): row is DirectoryEntry => row !== null) + .sort((a, b) => a.name.localeCompare(b.name)) + return { path: target, home, crumbs: ancestryCrumbs(target), entries } + } + + private async createDirectory(path: string, name: string): Promise { + 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)}`) + } + } +} diff --git a/packages/host/directory-picker-browse/src/invariant.ts b/packages/host/directory-picker-browse/src/invariant.ts new file mode 100644 index 0000000000..ba4bfe7b13 --- /dev/null +++ b/packages/host/directory-picker-browse/src/invariant.ts @@ -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)) diff --git a/packages/host/directory-picker-browse/tests/service.spec.ts b/packages/host/directory-picker-browse/tests/service.spec.ts new file mode 100644 index 0000000000..3833395c11 --- /dev/null +++ b/packages/host/directory-picker-browse/tests/service.spec.ts @@ -0,0 +1,96 @@ +/** 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 from '../src/index.ts' + +let root: string +let capability: DirectoryPickerBrowseCapability +let dispose: () => Promise + +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') + + 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) + }) + + 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('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') + }) +}) diff --git a/packages/host/directory-picker-browse/tsconfig.json b/packages/host/directory-picker-browse/tsconfig.json new file mode 100644 index 0000000000..99ca673189 --- /dev/null +++ b/packages/host/directory-picker-browse/tsconfig.json @@ -0,0 +1,24 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../directory-picker" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/host/directory-picker-dialog/README.i18n.yaml b/packages/host/directory-picker-dialog/README.i18n.yaml new file mode 100644 index 0000000000..3cd3d36702 --- /dev/null +++ b/packages/host/directory-picker-dialog/README.i18n.yaml @@ -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-dialog/README.md +README.md: fe07303557da6b27bb89eb761efba5555c4308c0 +README.zh.md: 214259264d5385ddad1ea6425149c53e31de55d0 diff --git a/packages/host/directory-picker-dialog/README.md b/packages/host/directory-picker-dialog/README.md new file mode 100644 index 0000000000..fe07303557 --- /dev/null +++ b/packages/host/directory-picker-dialog/README.md @@ -0,0 +1,17 @@ +# @deepseek-ai/dsh-host-directory-picker-dialog + +English | [中文](README.zh.md) + +The **native-OS-dialog backend** of the [directory-picker seam](../directory-picker/README.md): `DialogDirectoryPicker` registers `ctx.directoryPicker` with the `dialog` 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. + +## 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). diff --git a/packages/host/directory-picker-dialog/README.zh.md b/packages/host/directory-picker-dialog/README.zh.md new file mode 100644 index 0000000000..214259264d --- /dev/null +++ b/packages/host/directory-picker-dialog/README.zh.md @@ -0,0 +1,17 @@ +# @deepseek-ai/dsh-host-directory-picker-dialog + +[English](README.md) | 中文 + +[目录选择 seam](../directory-picker/README.md) 的**原生 OS 对话框后端**:`DialogDirectoryPicker` 以 `dialog` 能力注册 `ctx.directoryPicker`,其 `pick(signal)` 每次调用打开一个原生选择器并解析出所选绝对路径(取消时为 `null`)。平台工具不经 shell 调用:macOS 使用 `osascript`,Windows 使用以 STA 模式运行的 PowerShell `FolderBrowserDialog`,Linux 使用 Zenity 并以 KDialog 回退;调用方的中止信号会终止原生进程。只有操作者坐在宿主屏幕前时才可用——远程部署应组合 [`-browse`](../directory-picker-browse/README.md)。命令边界(`DirectoryPickerRunner`)与平台事实可注入,便于确定性测试。 + +## 模型体验 + +无。该后端服务于 GUI 宿主的目录选择;这里没有任何内容进入模型请求。 + +#### KV 缓存影响 + +无;该包既不组装也不发送提供方请求。 + +## 已知限制与延期工作 + +- **Linux 依赖桌面工具**——Zenity 与 KDialog 均未安装时,`pick` 以包含解决建议的错误拒绝;它不会回退为手输路径提示(组合层面的回退是 browse 后端)。 diff --git a/packages/host/directory-picker-dialog/package.json b/packages/host/directory-picker-dialog/package.json new file mode 100644 index 0000000000..94b22e6feb --- /dev/null +++ b/packages/host/directory-picker-dialog/package.json @@ -0,0 +1,40 @@ +{ + "name": "@deepseek-ai/dsh-host-directory-picker-dialog", + "description": "Native-OS-dialog 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" + }, + "./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", + "dependencies": { + "@deepseek-ai/dsh-host-directory-picker": "workspace:^" + }, + "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" + } +} diff --git a/packages/host/directory-picker-dialog/src/index.ts b/packages/host/directory-picker-dialog/src/index.ts new file mode 100644 index 0000000000..bc9814a5e7 --- /dev/null +++ b/packages/host/directory-picker-dialog/src/index.ts @@ -0,0 +1,33 @@ +/** + * Dialog backend of the directory-picker seam: registers `ctx.directoryPicker` + * with the `dialog` 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-dialog + */ + +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` dialog implementation (stable capability object per service life). */ +export default class DialogDirectoryPicker extends DirectoryPicker { + private readonly dialogCapability: DirectoryPickerCapability = { + kind: 'dialog', + /* v8 ignore next -- pure forward to pickNativeDirectory (its spec owns behavior); invoking here opens a real chooser. */ + pick: signal => pickNativeDirectory(signal), + } + + /** + * The dialog interaction capability. + * @returns the stable `dialog` capability object. + */ + capability(): DirectoryPickerCapability { + return this.dialogCapability + } +} diff --git a/packages/host/directory-picker-dialog/src/invariant.ts b/packages/host/directory-picker-dialog/src/invariant.ts new file mode 100644 index 0000000000..cbd3e63517 --- /dev/null +++ b/packages/host/directory-picker-dialog/src/invariant.ts @@ -0,0 +1,25 @@ +/** + * Package-owned invariant companion for the dialog directory-picker backend. + * @module @deepseek-ai/dsh-host-directory-picker-dialog/invariant + */ + +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-host-directory-picker-dialog' + +/** Cordis companion plugin name. */ +export const name = 'host-directory-picker-dialog-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 dialog outcome is only the returned path. */ +const install: InvariantInstaller = () => {} + +/** + * Register the dialog 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)) diff --git a/packages/host/apiproxy/src/native-directory-picker.ts b/packages/host/directory-picker-dialog/src/native-picker.ts similarity index 97% rename from packages/host/apiproxy/src/native-directory-picker.ts rename to packages/host/directory-picker-dialog/src/native-picker.ts index 8bc0bc99ce..a9602dc020 100644 --- a/packages/host/apiproxy/src/native-directory-picker.ts +++ b/packages/host/directory-picker-dialog/src/native-picker.ts @@ -1,4 +1,4 @@ -/** Cross-platform native single-directory picker used by the local GUI carrier. */ +/** Cross-platform native single-directory chooser behind the dialog backend's capability. */ import { execFile } from 'node:child_process' diff --git a/packages/host/apiproxy/tests/native-directory-picker.spec.ts b/packages/host/directory-picker-dialog/tests/native-picker.spec.ts similarity index 99% rename from packages/host/apiproxy/tests/native-directory-picker.spec.ts rename to packages/host/directory-picker-dialog/tests/native-picker.spec.ts index 783a67a04b..87e25ff877 100644 --- a/packages/host/apiproxy/tests/native-directory-picker.spec.ts +++ b/packages/host/directory-picker-dialog/tests/native-picker.spec.ts @@ -15,7 +15,7 @@ const { execFileMock } = vi.hoisted(() => ({ execFileMock: vi.fn() 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 }) diff --git a/packages/host/directory-picker-dialog/tests/service.spec.ts b/packages/host/directory-picker-dialog/tests/service.spec.ts new file mode 100644 index 0000000000..f56f93ec41 --- /dev/null +++ b/packages/host/directory-picker-dialog/tests/service.spec.ts @@ -0,0 +1,21 @@ +/** Registration/capability behavior of the dialog backend (the seam's cordis half). */ + +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import DialogDirectoryPicker from '../src/index.ts' + +describe('DialogDirectoryPicker', () => { + it('registers ctx.directoryPicker with a stable dialog capability and leaves with its fiber', async () => { + const ctx = new Context() + const fiber = ctx.plugin(DialogDirectoryPicker) + await fiber.await() + const picker = ctx.get('directoryPicker') + expect(picker).toBeInstanceOf(DialogDirectoryPicker) + const capability = picker!.capability() + expect(capability.kind).toBe('dialog') + // Stability: consumers may capture the capability object across calls. + expect(picker!.capability()).toBe(capability) + await fiber.dispose() + expect(ctx.get('directoryPicker')).toBeUndefined() + }) +}) diff --git a/packages/host/directory-picker-dialog/tsconfig.json b/packages/host/directory-picker-dialog/tsconfig.json new file mode 100644 index 0000000000..99ca673189 --- /dev/null +++ b/packages/host/directory-picker-dialog/tsconfig.json @@ -0,0 +1,24 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cosmokit" + }, + { + "path": "../../../vendor/cordis" + }, + { + "path": "../directory-picker" + }, + { + "path": "../../support/invariants" + } + ] +} diff --git a/packages/host/directory-picker/README.i18n.yaml b/packages/host/directory-picker/README.i18n.yaml new file mode 100644 index 0000000000..0d5c753e92 --- /dev/null +++ b/packages/host/directory-picker/README.i18n.yaml @@ -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: c1a801cf72f128e6e5ef668c5e28e03ad2284868 +README.zh.md: c352b35b70dfa835aecfcb5ffec2a9ac46f25c42 diff --git a/packages/host/directory-picker/README.md b/packages/host/directory-picker/README.md new file mode 100644 index 0000000000..c1a801cf72 --- /dev/null +++ b/packages/host/directory-picker/README.md @@ -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: 'dialog', pick(signal) }` opens one native OS chooser on the host display ([`-dialog`](../directory-picker-dialog/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 dialog can reach ([`-browse`](../directory-picker-browse/README.md)). 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. The capability object must be stable for the service lifetime. + +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. diff --git a/packages/host/directory-picker/README.zh.md b/packages/host/directory-picker/README.zh.md new file mode 100644 index 0000000000..c352b35b70 --- /dev/null +++ b/packages/host/directory-picker/README.zh.md @@ -0,0 +1,19 @@ +# @deepseek-ai/dsh-host-directory-picker + +[English](README.md) | 中文 + +web GUI 宿主的**工作区目录选择 seam**:抽象服务 `DirectoryPicker`(`ctx.directoryPicker`),唯一契约方法 `capability()` 返回一个可辨识能力对象,描述操作者以何种方式选择目录。后端之间的差异在交互形态而不只是机制,因此 seam 显式建模形态而非统一方法集:`{ kind: 'dialog', pick(signal) }` 在宿主屏幕上打开一个原生 OS 选择器([`-dialog`](../directory-picker-dialog/README.md));`{ kind: 'browse', list(path?), createDirectory(path, name) }` 提供应用内浏览器驱动的列举/创建原语,可服务任何 OS 对话框都触及不到的远程客户端([`-browse`](../directory-picker-browse/README.md))。消费方按 `capability().kind` 分支;联合类型可合并扩展,未知 kind 的文档化默认行为是隐藏选择入口而非失败。能力对象在服务生命周期内必须保持稳定。 + +浏览原语以带类型的 `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。 diff --git a/packages/host/directory-picker/package.json b/packages/host/directory-picker/package.json new file mode 100644 index 0000000000..17d68c141b --- /dev/null +++ b/packages/host/directory-picker/package.json @@ -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" + } +} diff --git a/packages/host/directory-picker/src/index.ts b/packages/host/directory-picker/src/index.ts new file mode 100644 index 0000000000..5e184b36e1 --- /dev/null +++ b/packages/host/directory-picker/src/index.ts @@ -0,0 +1,118 @@ +/** + * 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 `dialog` backend opens one native 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 dialog interaction: one native OS directory chooser on the host display. */ +export interface DirectoryPickerDialogCapability { + kind: 'dialog' + /** + * 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 +} + +/** 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[] +} + +/** + * 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. + * @returns the level's listing with ancestry. + * @throws {DirectoryPickerError} `directory-unreadable` when the target cannot be listed. + */ + list(path?: string): Promise + /** + * 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` otherwise. + */ + createDirectory(path: string, name: string): Promise +} + +/** Union of interaction shapes a backend can provide (merge-extensible: grows with backends). */ +export type DirectoryPickerCapability = DirectoryPickerDialogCapability | DirectoryPickerBrowseCapability + +/** 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 +} diff --git a/packages/host/directory-picker/src/invariant.ts b/packages/host/directory-picker/src/invariant.ts new file mode 100644 index 0000000000..9128850f3b --- /dev/null +++ b/packages/host/directory-picker/src/invariant.ts @@ -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)) diff --git a/packages/host/directory-picker/tests/seam.spec.ts b/packages/host/directory-picker/tests/seam.spec.ts new file mode 100644 index 0000000000..4e7a799fa4 --- /dev/null +++ b/packages/host/directory-picker/tests/seam.spec.ts @@ -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: 'dialog', 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('dialog') + 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) + }) +}) diff --git a/packages/host/directory-picker/tsconfig.json b/packages/host/directory-picker/tsconfig.json new file mode 100644 index 0000000000..9966c8ca8a --- /dev/null +++ b/packages/host/directory-picker/tsconfig.json @@ -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" + } + ] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f8343b2404..a47a1ea140 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -212,6 +212,9 @@ importers: '@deepseek-ai/dsh-host-apiproxy': specifier: workspace:^ version: link:../../packages/host/apiproxy + '@deepseek-ai/dsh-host-directory-picker-dialog': + specifier: workspace:^ + version: link:../../packages/host/directory-picker-dialog '@deepseek-ai/dsh-host-webserver': specifier: workspace:^ version: link:../../packages/host/webserver @@ -2652,6 +2655,9 @@ importers: '@deepseek-ai/dsh-commands': specifier: workspace:^ version: link:../../ui/commands + '@deepseek-ai/dsh-host-directory-picker': + specifier: workspace:^ + version: link:../directory-picker '@deepseek-ai/dsh-llm': specifier: workspace:^ version: link:../../llm/llm @@ -2699,6 +2705,41 @@ importers: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + packages/host/directory-picker: + devDependencies: + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + + packages/host/directory-picker-browse: + dependencies: + '@deepseek-ai/dsh-host-directory-picker': + specifier: workspace:^ + version: link:../directory-picker + devDependencies: + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + + packages/host/directory-picker-dialog: + dependencies: + '@deepseek-ai/dsh-host-directory-picker': + specifier: workspace:^ + version: link:../directory-picker + devDependencies: + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + packages/host/webserver: dependencies: schemastery: diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 86ef6d8477..8b4f0cf6fd 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -226,6 +226,7 @@ const TYPE_LINK_EXEMPTIONS: Readonly> = { BashEnvContributor: 'service-local extension type is owned by packages/bash/tool-bash/src/index.ts', BashEnvVariableInfo: 'service-local metadata type is owned by packages/bash/tool-bash/src/index.ts', CompactAgentContext: 'compaction service input is owned by packages/compact/compact/src/index.ts', + DirectoryPickerCapability: 'picker interaction contract is owned by packages/host/directory-picker/README.md', CreateAgentOptions: 'agent creation contract is owned by packages/core/agent/README.md', Domain: 'domain interface is owned by packages/storage/storage-domain/README.md', DomainChanged: 'event-local snapshot is owned by packages/storage/storage-domain/src/events.ts', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 1d4a7e447d..1348ba425a 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -408,6 +408,15 @@ const SERVICE_ROLES: ServiceRole[] = [ consumers: ['spill-policy'], note: 'The backend saves oversized tool text and returns a model-facing locator plus retrieval hint; spill-policy is the tools/post-execute consumer that decides when to spill.', }, + { + key: 'directoryPicker', + pkg: 'directory-picker', + title: 'Workspace-directory picking seam', + mode: 'seam', + implementations: ['directory-picker-dialog', 'directory-picker-browse'], + consumers: ['apiproxy'], + note: 'Discriminated interaction capability: the dialog backend opens one native OS chooser on the host display, the browse backend serves listing/creation primitives for the in-app browser; the gateway advertises the kind via host.describe.', + }, { key: 'httpServer', pkg: 'webserver', diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 13dc2def8d..79100a4c9e 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -73,6 +73,9 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/fs/fs-sandbox': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-fs.' }, 'packages/hooks/hook-protocol': { kind: 'indirect', reason: 'Only the hook bridge plugins render decoded hook output to a model.' }, 'packages/host/apiproxy': { kind: 'none', reason: 'The wire contract and fetch carriers move already-composed messages and register no model surface.' }, + 'packages/host/directory-picker': { kind: 'none', reason: 'The GUI-host picking seam registers no model surface.' }, + 'packages/host/directory-picker-browse': { kind: 'none', reason: 'The GUI-host picking backend registers no model surface.' }, + 'packages/host/directory-picker-dialog': { kind: 'none', reason: 'The GUI-host picking backend registers no model surface.' }, 'packages/host/webserver': { kind: 'none', reason: 'The HTTP carrier bridges browser and API handler and registers no model surface.' }, 'packages/llm/llm': { kind: 'none', reason: 'The adapter registry forwards already-assembled requests unchanged.' }, 'packages/llm/token-meter': { kind: 'indirect', reason: 'The measurement service leaves model-visible changes to its consumers.' }, diff --git a/tsconfig.base.json b/tsconfig.base.json index d4beec7afa..51b6e938dd 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -99,6 +99,12 @@ // tsconfig.client.json) stay explicit — TS project references have no // wildcard form. "@deepseek-ai/dsh-host-apiproxy": ["./packages/host/apiproxy/src"], + "@deepseek-ai/dsh-host-directory-picker": ["./packages/host/directory-picker/src"], + "@deepseek-ai/dsh-host-directory-picker/*": ["./packages/host/directory-picker/src/*"], + "@deepseek-ai/dsh-host-directory-picker-browse": ["./packages/host/directory-picker-browse/src"], + "@deepseek-ai/dsh-host-directory-picker-browse/*": ["./packages/host/directory-picker-browse/src/*"], + "@deepseek-ai/dsh-host-directory-picker-dialog": ["./packages/host/directory-picker-dialog/src"], + "@deepseek-ai/dsh-host-directory-picker-dialog/*": ["./packages/host/directory-picker-dialog/src/*"], "@deepseek-ai/dsh-host-apiproxy/client": ["./packages/host/apiproxy/src/fetch/client.ts"], "@deepseek-ai/dsh-host-apiproxy/*": ["./packages/host/apiproxy/src/*"], "@deepseek-ai/dsh-host-webserver": ["./packages/host/webserver/src"], diff --git a/tsconfig.host.json b/tsconfig.host.json index 9cf2a86bda..98a51dda19 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -163,6 +163,9 @@ { "path": "./packages/hooks/hooks-codex" }, { "path": "./packages/mcp/mcp-client" }, { "path": "./packages/host/apiproxy" }, + { "path": "./packages/host/directory-picker" }, + { "path": "./packages/host/directory-picker-browse" }, + { "path": "./packages/host/directory-picker-dialog" }, { "path": "./packages/host/webserver" }, { "path": "./packages/sdk/sdk-client" }, { "path": "./packages/sdk/helper" }, From b9cbe2f029fedf77222d9f02b8cfe2b9cfc30f14 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 15:57:02 +0800 Subject: [PATCH 07/93] fix(connection): fail the load on a trustedHosts entry that is not a bare authority WHATWG parsing would quietly read a hostname out of harness.internal/path or user@harness.internal, authorizing the typo's hostname; other typos would sit silently ignored until requests 403. Refuse every URL part beyond host[:port] at plugin load. --- ...07-28-api-browser-trust-boundary.i18n.yaml | 4 ++-- .../2026-07-28-api-browser-trust-boundary.md | 2 +- ...026-07-28-api-browser-trust-boundary.zh.md | 2 +- docs/config-catalog.md | 3 ++- packages/client/connection/README.i18n.yaml | 4 ++-- packages/client/connection/README.md | 2 +- packages/client/connection/README.zh.md | 2 +- .../connection/src/api-request-trust.ts | 15 ++++++++++++ packages/client/connection/src/index.ts | 8 +++++-- .../tests/api-request-trust.spec.ts | 13 +++++++++- .../client/connection/tests/node-half.spec.ts | 24 +++++++++++++++++++ 11 files changed, 67 insertions(+), 12 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml index 68473ee893..1e10e92f49 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml @@ -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 .agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md -2026-07-28-api-browser-trust-boundary.md: 45a332fcfe59fb930a85cfc595dd02c5fe12a5d7 -2026-07-28-api-browser-trust-boundary.zh.md: 731d6c81f71a2f50b716e52e278f2c53ad62a04b +2026-07-28-api-browser-trust-boundary.md: 4dd913bb73da3b24073c020ff80fdfa83b44a812 +2026-07-28-api-browser-trust-boundary.zh.md: 0be817aca9dde68588959d2cd622639d90d9f993 diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md index 45a332fcfe..4dd913bb73 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md @@ -13,7 +13,7 @@ The web GUI host serves `/api` over plain HTTP (default `127.0.0.1:3080`, `--hos Enforce browser trust once, at the carrier, for the entire `/api` prefix — two halves in two stacked PRs: - **Media-type fence (dsh-host-apiproxy)**: every `/api` POST must declare `application/json`, else 415 before parsing. Cross-site "simple" requests thereby stop existing: any cross-site attempt is forced into a CORS preflight this server never answers. -- **Authority fence (dsh-client-connection, `src/api-request-trust.ts`)**: requests without browser markers (no `Origin`, no `sec-fetch-site`) pass on any Host — a non-browser client is the principal itself, not a deputy, and forges every header anyway, so fencing it buys nothing and breaks non-browser LAN automation. For browser requests, `Host` must be loopback or match a `trustedHosts` entry (exact on `host:port`, any port on port-less entries, WHATWG-normalized; rebinding defense); an attached `Origin` must equal that authority; `sec-fetch-site: cross-site` is refused outright. `host.pickDirectory` loses its bespoke guard and rides the same fence. +- **Authority fence (dsh-client-connection, `src/api-request-trust.ts`)**: requests without browser markers (no `Origin`, no `sec-fetch-site`) pass on any Host — a non-browser client is the principal itself, not a deputy, and forges every header anyway, so fencing it buys nothing and breaks non-browser LAN automation. For browser requests, `Host` must be loopback or match a `trustedHosts` entry (exact on `host:port`, any port on port-less entries, WHATWG-normalized; rebinding defense); an attached `Origin` must equal that authority; `sec-fetch-site: cross-site` is refused outright. A `trustedHosts` entry that is not a bare authority fails the plugin load — WHATWG parsing would otherwise quietly authorize the hostname inside a typo. `host.pickDirectory` loses its bespoke guard and rides the same fence. Two boundaries stay deliberately out of scope: reachability is the webserver binding's policy (`host: 127.0.0.1 | 0.0.0.0`), and authentication for genuinely remote deployments is deferred work recorded in the connection README — the fence is a confused-deputy defense, not an auth layer. The old guard's loopback-socket check was dropped rather than generalized: with binding expressing reachability and `trustedHosts` naming remote authorities, the socket address adds nothing a header fence does not already cover. diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md index 731d6c81f7..0be817aca9 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md @@ -13,7 +13,7 @@ Web GUI 宿主以纯 HTTP 提供 `/api`(默认 `127.0.0.1:3080`,支持 `--ho 在载体层对整个 `/api` 前缀一次性执行浏览器信任检查——两半各占一个栈式 PR: - **媒体类型栅栏(dsh-host-apiproxy)**:每个 `/api` POST 必须声明 `application/json`,否则在解析前以 415 拒绝。跨站"简单请求"由此不复存在:任何跨站尝试都被逼进一次本服务器从不应答的 CORS 预检。 -- **权威栅栏(dsh-client-connection,`src/api-request-trust.ts`)**:不带浏览器标记的请求(无 `Origin`、无 `sec-fetch-site`)在任何 Host 上都放行——非浏览器客户端是委托人本人,不是代理人,且本就可以伪造任何请求头,对它设栅一无所获,反而会打断非浏览器的 LAN 自动化。对浏览器请求,`Host` 必须是回环地址,或与某个 `trustedHosts` 条目匹配(带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,均经 WHATWG 归一化;rebinding 防御);若带 `Origin` 则必须与该权威完全一致;`sec-fetch-site: cross-site` 一律拒绝。`host.pickDirectory` 失去专属守卫,与其他请求同栅而行。 +- **权威栅栏(dsh-client-connection,`src/api-request-trust.ts`)**:不带浏览器标记的请求(无 `Origin`、无 `sec-fetch-site`)在任何 Host 上都放行——非浏览器客户端是委托人本人,不是代理人,且本就可以伪造任何请求头,对它设栅一无所获,反而会打断非浏览器的 LAN 自动化。对浏览器请求,`Host` 必须是回环地址,或与某个 `trustedHosts` 条目匹配(带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,均经 WHATWG 归一化;rebinding 防御);若带 `Origin` 则必须与该权威完全一致;`sec-fetch-site: cross-site` 一律拒绝。不是纯权威的 `trustedHosts` 条目会让插件加载失败——否则 WHATWG 解析会悄悄授权笔误里的 hostname。`host.pickDirectory` 失去专属守卫,与其他请求同栅而行。 两条边界刻意留在范围之外:可达性归 webserver 绑定配置(`host: 127.0.0.1 | 0.0.0.0`)管辖;真正远程部署的认证是延期工作,记录在 connection README——这道栅栏是混淆代理人防御,不是认证层。旧守卫的回环 socket 检查被放弃而非泛化:绑定表达可达性、`trustedHosts` 点名远程权威之后,socket 地址提供不了头部栅栏覆盖不到的任何东西。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 6155c418e0..5a7f63c85f 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -282,7 +282,8 @@ export interface ConnectionConfig { * port-less `host` matching any port. The /api trust fence refuses any * browser request whose Host is neither loopback nor listed here, so a * non-loopback (`0.0.0.0`) deployment must declare the names it is reached - * by (the dsh CLI derives the machine's LAN IP literals itself). + * by (the dsh CLI derives the machine's LAN IP literals itself). An entry + * that is not a bare authority fails the plugin load. */ trustedHosts?: string[] } diff --git a/packages/client/connection/README.i18n.yaml b/packages/client/connection/README.i18n.yaml index 8310adac83..f0775848d3 100644 --- a/packages/client/connection/README.i18n.yaml +++ b/packages/client/connection/README.i18n.yaml @@ -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/client/connection/README.md -README.md: 94b9b3c8d4bde30cedf56e31d83efe9f5f1dd87c -README.zh.md: 844a2ef030378c32994f7459792db98c779f24b7 +README.md: 591e8361c1d28fab909bfe4a4f176fa1887edd93 +README.zh.md: bd772b2ab0f36abc8dbce35d30f55b40e53d0756 diff --git a/packages/client/connection/README.md b/packages/client/connection/README.md index 94b9b3c8d4..591e8361c1 100644 --- a/packages/client/connection/README.md +++ b/packages/client/connection/README.md @@ -6,7 +6,7 @@ Wire consumer layer: the client plugin's apply mounts `ctx.connection` (shared a ## /api browser-trust fence -The node half guards every request under `/api` before bridging (`src/api-request-trust.ts`). Requests without browser markers (no `Origin`, no `sec-fetch-site` — curl, tests, native clients) pass on any Host: without a browser there is no confused deputy, and such a sender forges every header anyway. For browser requests, the `Host` header must be a loopback authority or match a `trustedHosts` entry — exact on `host:port` entries, any port on port-less entries, both sides compared through WHATWG normalization (DNS-rebinding defense); an attached `Origin` must equal that authority, and an explicit `sec-fetch-site: cross-site` marker is refused. Failures answer plain 403 before any RPC dispatch. A non-loopback (`--host 0.0.0.0`) deployment therefore needs its serving authorities trusted: the dsh CLI derives the machine's LAN IP literals itself and its `--trusted-host` flag declares named ones, so `trustedHosts` in cordis.yml is for compositions the CLI does not boot. The fence is deliberately not an authentication layer — reachability policy stays with the webserver binding, and auth remains deferred work. Decision record: [the api browser-trust boundary Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md). +The node half guards every request under `/api` before bridging (`src/api-request-trust.ts`). Requests without browser markers (no `Origin`, no `sec-fetch-site` — curl, tests, native clients) pass on any Host: without a browser there is no confused deputy, and such a sender forges every header anyway. For browser requests, the `Host` header must be a loopback authority or match a `trustedHosts` entry — exact on `host:port` entries, any port on port-less entries, both sides compared through WHATWG normalization (DNS-rebinding defense); an attached `Origin` must equal that authority, and an explicit `sec-fetch-site: cross-site` marker is refused. A `trustedHosts` entry that is not a bare `host[:port]` authority fails the plugin load loudly — WHATWG parsing would otherwise quietly authorize the hostname inside a typo like `harness.internal/path`. Failures answer plain 403 before any RPC dispatch. A non-loopback (`--host 0.0.0.0`) deployment therefore needs its serving authorities trusted: the dsh CLI derives the machine's LAN IP literals itself and its `--trusted-host` flag declares named ones, so `trustedHosts` in cordis.yml is for compositions the CLI does not boot. The fence is deliberately not an authentication layer — reachability policy stays with the webserver binding, and auth remains deferred work. Decision record: [the api browser-trust boundary Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md). ## Keyless fixture diff --git a/packages/client/connection/README.zh.md b/packages/client/connection/README.zh.md index 844a2ef030..bd772b2ab0 100644 --- a/packages/client/connection/README.zh.md +++ b/packages/client/connection/README.zh.md @@ -6,7 +6,7 @@ ## /api 浏览器信任栅栏 -node 半侧在桥接前守卫 `/api` 下的每个请求(`src/api-request-trust.ts`)。不带浏览器标记的请求(无 `Origin`、无 `sec-fetch-site`——curl、测试、原生客户端)在任何 Host 上都放行:没有浏览器就不存在"混淆代理人",且这类发送方本就可以伪造任何请求头。对浏览器请求,`Host` 头必须是回环地址权威,或与某个 `trustedHosts` 条目匹配——带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,两侧均经 WHATWG 归一化后比较(DNS rebinding 防御);若带有 `Origin` 则必须与该权威完全一致;显式的 `sec-fetch-site: cross-site` 标记一律拒绝。失败在任何 RPC 分发之前以纯 403 应答。因此非回环(`--host 0.0.0.0`)部署需要让自己的服务权威被信任:dsh CLI 会自行推导本机的 LAN IP 字面量,其 `--trusted-host` flag 用于声明具名权威,所以 cordis.yml 中的 `trustedHosts` 面向 CLI 不参与引导的组合。这道栅栏刻意不承担认证职责——可达性策略归 webserver 绑定配置,认证仍是延期工作。决策记录:[api 浏览器信任边界 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md)。 +node 半侧在桥接前守卫 `/api` 下的每个请求(`src/api-request-trust.ts`)。不带浏览器标记的请求(无 `Origin`、无 `sec-fetch-site`——curl、测试、原生客户端)在任何 Host 上都放行:没有浏览器就不存在"混淆代理人",且这类发送方本就可以伪造任何请求头。对浏览器请求,`Host` 头必须是回环地址权威,或与某个 `trustedHosts` 条目匹配——带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,两侧均经 WHATWG 归一化后比较(DNS rebinding 防御);若带有 `Origin` 则必须与该权威完全一致;显式的 `sec-fetch-site: cross-site` 标记一律拒绝。不是纯 `host[:port]` 权威的 `trustedHosts` 条目会让插件加载大声失败——否则 WHATWG 解析会悄悄授权 `harness.internal/path` 这类笔误里的 hostname。失败在任何 RPC 分发之前以纯 403 应答。因此非回环(`--host 0.0.0.0`)部署需要让自己的服务权威被信任:dsh CLI 会自行推导本机的 LAN IP 字面量,其 `--trusted-host` flag 用于声明具名权威,所以 cordis.yml 中的 `trustedHosts` 面向 CLI 不参与引导的组合。这道栅栏刻意不承担认证职责——可达性策略归 webserver 绑定配置,认证仍是延期工作。决策记录:[api 浏览器信任边界 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md)。 ## 无密钥 fixture diff --git a/packages/client/connection/src/api-request-trust.ts b/packages/client/connection/src/api-request-trust.ts index 11dc6d7621..2a8b8d7273 100644 --- a/packages/client/connection/src/api-request-trust.ts +++ b/packages/client/connection/src/api-request-trust.ts @@ -40,6 +40,21 @@ function parseAuthority(authority: string): URL | undefined { } } +/** + * Assert one configured `trustedHosts` entry is a bare authority (`host` or + * `host:port`) and nothing else. WHATWG parsing would quietly read a hostname + * out of `harness.internal/path` or `user@harness.internal` — a typo must fail + * the load loudly instead of authorizing its hostname or being ignored until + * requests 403. The delimiter test refuses every URL part beyond the authority + * (path, backslash path, query, fragment, userinfo); IPv6 brackets use none of + * them. + * @param entry - the configured value, verbatim. + */ +export function assertTrustedAuthority(entry: string): void { + if (parseAuthority(entry) !== undefined && !/[/\\?#@]/.test(entry)) return + throw new Error(`client-connection: trustedHosts entry ${JSON.stringify(entry)} is not a bare host[:port] authority`) +} + /** * Whether the request authority matches a `trustedHosts` entry. An entry with * an explicit port matches that exact authority; a port-less entry matches the diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index 1bc39ed3ba..f37a64fb21 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -6,7 +6,7 @@ import type { WebRoute } from '@deepseek-ai/dsh-host-webserver' import { toFetchHandler } from '@deepseek-ai/dsh-host-apiproxy' import { API_PATH } from './api-path.ts' import { bridge } from './http-bridge.ts' -import { isTrustedApiRequest } from './api-request-trust.ts' +import { assertTrustedAuthority, isTrustedApiRequest } from './api-request-trust.ts' export { API_PATH } from './api-path.ts' @@ -23,7 +23,8 @@ export interface ConnectionConfig { * port-less `host` matching any port. The /api trust fence refuses any * browser request whose Host is neither loopback nor listed here, so a * non-loopback (`0.0.0.0`) deployment must declare the names it is reached - * by (the dsh CLI derives the machine's LAN IP literals itself). + * by (the dsh CLI derives the machine's LAN IP literals itself). An entry + * that is not a bare authority fails the plugin load. */ trustedHosts?: string[] } @@ -42,6 +43,9 @@ export const Config: z = z.object({ export function apply(ctx: Context, config?: ConnectionConfig): void { // The Loader resolves schema defaults; hand-built test contexts may pass none. const trustedHosts = config?.trustedHosts ?? [] + // Config boundary: a malformed entry fails the load loudly here rather than + // silently authorizing its hostname prefix at request time. + for (const entry of trustedHosts) assertTrustedAuthority(entry) const apiHandler = toFetchHandler(ctx.apiProxy) const route: WebRoute = { kind: 'prefix', diff --git a/packages/client/connection/tests/api-request-trust.spec.ts b/packages/client/connection/tests/api-request-trust.spec.ts index 5dc2d14b1b..99df0d86eb 100644 --- a/packages/client/connection/tests/api-request-trust.spec.ts +++ b/packages/client/connection/tests/api-request-trust.spec.ts @@ -1,7 +1,7 @@ /** Behavior of the /api browser-trust fence (rebinding + cross-site defense). */ import { describe, expect, it } from 'vitest' -import { isTrustedApiRequest } from '../src/api-request-trust.ts' +import { assertTrustedAuthority, isTrustedApiRequest } from '../src/api-request-trust.ts' function request(headers: Record): { headers: Record } { return { headers } @@ -66,6 +66,17 @@ describe('isTrustedApiRequest', () => { expect(isTrustedApiRequest(request({ host: 'localhost:3080', 'sec-fetch-site': 'same-origin' }), [])).toBe(true) }) + it('assertTrustedAuthority accepts bare authorities and throws on anything more', () => { + for (const entry of ['harness.internal', 'harness.internal:3080', 'HARNESS.internal:80', '10.0.0.9', '[::1]:3080']) { + expect(() => { assertTrustedAuthority(entry) }).not.toThrow() + } + // WHATWG parsing would quietly read a hostname out of each of these; the + // config boundary must refuse them instead of authorizing the prefix. + for (const entry of ['harness.internal/path', 'harness.internal/', 'user@harness.internal', 'harness.internal?x', 'harness.internal#f', 'harness.internal\\path', 'bad entry', '']) { + expect(() => { assertTrustedAuthority(entry) }).toThrow(/not a bare host\[:port\] authority/) + } + }) + it('refuses malformed or untrusted authorities on browser requests', () => { const markers = { 'sec-fetch-site': 'same-origin' } expect(isTrustedApiRequest(request({ ...markers }), [])).toBe(false) diff --git a/packages/client/connection/tests/node-half.spec.ts b/packages/client/connection/tests/node-half.spec.ts index 59c8c34ce2..5404f1c798 100644 --- a/packages/client/connection/tests/node-half.spec.ts +++ b/packages/client/connection/tests/node-half.spec.ts @@ -54,6 +54,30 @@ async function mounted(config?: { trustedHosts?: string[] }): Promise<{ routes: } describe('connection node half', () => { + it('fails the load on a trustedHosts entry that is not a bare authority', async () => { + const routes: WebRoute[] = [] + const ctx = new Context() + ctx.provide('httpServer', fakeHttpServer(routes) as HttpServerService) + ctx.provide('apiProxy', {} as unknown as ApiProxy) + // The apply throw also escapes cordis as a late rejection — the shape the + // boot's installFailLoud is contracted to catch. Capture it so the run + // stays clean, same pattern as the webserver bind-failure test. + const rejections: unknown[] = [] + const onUnhandled = (err: unknown): void => { rejections.push(err) } + process.on('unhandledRejection', onUnhandled) + try { + const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.internal/path'] }) + await expect(fiber.await()).rejects.toThrow(/not a bare host\[:port\] authority/) + expect(routes).toHaveLength(0) + for (let i = 0; i < 100 && rejections.length === 0; i++) { + await new Promise(resolve => setTimeout(resolve, 10)) + } + expect(rejections.map(String).join('\n')).toContain('not a bare host[:port] authority') + } finally { + process.off('unhandledRejection', onUnhandled) + } + }) + it('registers the /api prefix route and removes it with the fiber', async () => { const { routes, dispose } = await mounted() expect(routes).toHaveLength(1) From 34518cb012d3d9a16ec851b4a215db7100f4457a Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 16:19:31 +0800 Subject: [PATCH 08/93] fix(connection): judge an entry's explicit port from the parsed URL, not the raw string MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit WHATWG trimming strips stray whitespace before parsing, so 'host:port ' passed the load assert while the raw-string port regex read it as port-less — broadening an exact-port grant to every port on that hostname. The explicit- port judgment now reads URL parses under both special schemes (:80/:443 stay explicit), and the load assert refuses whitespace outright. --- .../connection/src/api-request-trust.ts | 21 +++++++++++++++---- .../tests/api-request-trust.spec.ts | 12 +++++++++++ 2 files changed, 29 insertions(+), 4 deletions(-) diff --git a/packages/client/connection/src/api-request-trust.ts b/packages/client/connection/src/api-request-trust.ts index 2a8b8d7273..ad2519d90b 100644 --- a/packages/client/connection/src/api-request-trust.ts +++ b/packages/client/connection/src/api-request-trust.ts @@ -45,16 +45,29 @@ function parseAuthority(authority: string): URL | undefined { * `host:port`) and nothing else. WHATWG parsing would quietly read a hostname * out of `harness.internal/path` or `user@harness.internal` — a typo must fail * the load loudly instead of authorizing its hostname or being ignored until - * requests 403. The delimiter test refuses every URL part beyond the authority - * (path, backslash path, query, fragment, userinfo); IPv6 brackets use none of + * requests 403. The character test refuses every URL part beyond the authority + * (path, backslash path, query, fragment, userinfo) and all whitespace, which + * WHATWG trimming would otherwise strip silently; IPv6 brackets use none of * them. * @param entry - the configured value, verbatim. */ export function assertTrustedAuthority(entry: string): void { - if (parseAuthority(entry) !== undefined && !/[/\\?#@]/.test(entry)) return + if (parseAuthority(entry) !== undefined && !/[/\\?#@\s]/.test(entry)) return throw new Error(`client-connection: trustedHosts entry ${JSON.stringify(entry)} is not a bare host[:port] authority`) } +/** + * Whether the parsed authority carries an explicit port: judged from URL + * parses under both special schemes (their default ports differ, so `:80` and + * `:443` still count as explicit), never from the raw string, where WHATWG + * trimming of stray whitespace would misread `host:port ` as port-less and + * broaden an exact-port grant to every port. + */ +function hasExplicitPort(entry: string, entryUrl: URL): boolean { + // An authority that parsed under http cannot fail under https. + return entryUrl.port !== '' || new URL(`https://${entry}`).port !== '' +} + /** * Whether the request authority matches a `trustedHosts` entry. An entry with * an explicit port matches that exact authority; a port-less entry matches the @@ -66,7 +79,7 @@ function isTrustedAuthority(hostUrl: URL, trustedHosts: readonly string[]): bool return trustedHosts.some((entry) => { const entryUrl = parseAuthority(entry) if (entryUrl === undefined) return false - return /:\d+$/.test(entry) + return hasExplicitPort(entry, entryUrl) ? entryUrl.host === hostUrl.host : entryUrl.hostname === hostUrl.hostname }) diff --git a/packages/client/connection/tests/api-request-trust.spec.ts b/packages/client/connection/tests/api-request-trust.spec.ts index 99df0d86eb..e3f1c91caf 100644 --- a/packages/client/connection/tests/api-request-trust.spec.ts +++ b/packages/client/connection/tests/api-request-trust.spec.ts @@ -75,6 +75,18 @@ describe('isTrustedApiRequest', () => { for (const entry of ['harness.internal/path', 'harness.internal/', 'user@harness.internal', 'harness.internal?x', 'harness.internal#f', 'harness.internal\\path', 'bad entry', '']) { expect(() => { assertTrustedAuthority(entry) }).toThrow(/not a bare host\[:port\] authority/) } + // WHATWG trimming would silently strip these; the entry must fail instead. + for (const entry of ['harness.internal:3080 ', ' harness.internal', 'harness.internal:30\t80']) { + expect(() => { assertTrustedAuthority(entry) }).toThrow(/not a bare host\[:port\] authority/) + } + }) + + it('never lets stray whitespace broaden an exact-port entry to every port', () => { + // Defense in depth below the load-time assert: the explicit-port judgment + // reads the parsed URL, so a trimmed `host:port ` entry stays exact. + const trusted = ['harness.internal:3080 '] + expect(isTrustedApiRequest(request({ host: 'harness.internal:9999', origin: 'http://harness.internal:9999' }), trusted)).toBe(false) + expect(isTrustedApiRequest(request({ host: 'harness.internal:3080', origin: 'http://harness.internal:3080' }), trusted)).toBe(true) }) it('refuses malformed or untrusted authorities on browser requests', () => { From 716d3ca6361a24df610d2a6840fecc8aea8f2cf4 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 16:44:22 +0800 Subject: [PATCH 09/93] test(apiproxy): drive the browse RPCs through the fetch carrier The full-suite coverage gate found the new listDirectory/createDirectory client methods and handler routes unexecuted: the implementation and schema layers were tested directly, but nothing crossed the wire form. One round trip through InProcessApiClient covers both arrows on each side. --- packages/host/apiproxy/tests/fetch-carrier.spec.ts | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/packages/host/apiproxy/tests/fetch-carrier.spec.ts b/packages/host/apiproxy/tests/fetch-carrier.spec.ts index a0645f4750..6340e4e2e7 100644 --- a/packages/host/apiproxy/tests/fetch-carrier.spec.ts +++ b/packages/host/apiproxy/tests/fetch-carrier.spec.ts @@ -211,6 +211,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: [] }, + }) + 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 command.list / command.execute / skill.list through the wire form', async () => { const c = client() const list = await c.commands.list({ sessionId: 's' as never }) From 7ff8da56dfb8e6ad0130e9dcbdb55f034c3ff530 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 16:49:52 +0800 Subject: [PATCH 10/93] fix(connection): require trustedHosts entries in canonical authority form A dangling colon (harness.internal:) or zero-padded port parses cleanly while WHATWG silently rewrites it, turning an intended exact-port grant into an any-port grant. Replace the character blacklist with a round-trip check: an entry must read back from parsing exactly as written (case aside), refusing the whole rewrite class at load. --- docs/config-catalog.md | 2 +- packages/client/connection/README.i18n.yaml | 4 +- packages/client/connection/README.md | 2 +- packages/client/connection/README.zh.md | 2 +- .../connection/src/api-request-trust.ts | 41 +++++++++++-------- packages/client/connection/src/index.ts | 2 +- .../tests/api-request-trust.spec.ts | 6 +++ 7 files changed, 35 insertions(+), 24 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 5a7f63c85f..878de38a19 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -283,7 +283,7 @@ export interface ConnectionConfig { * browser request whose Host is neither loopback nor listed here, so a * non-loopback (`0.0.0.0`) deployment must declare the names it is reached * by (the dsh CLI derives the machine's LAN IP literals itself). An entry - * that is not a bare authority fails the plugin load. + * that is not a bare, canonical authority fails the plugin load. */ trustedHosts?: string[] } diff --git a/packages/client/connection/README.i18n.yaml b/packages/client/connection/README.i18n.yaml index f0775848d3..c390223071 100644 --- a/packages/client/connection/README.i18n.yaml +++ b/packages/client/connection/README.i18n.yaml @@ -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/client/connection/README.md -README.md: 591e8361c1d28fab909bfe4a4f176fa1887edd93 -README.zh.md: bd772b2ab0f36abc8dbce35d30f55b40e53d0756 +README.md: 7e437e8fd81d1d57ead5ead64d2049111ad163dc +README.zh.md: 3615d5ea1be44e6da8e41fa17f645eb414d1ef3e diff --git a/packages/client/connection/README.md b/packages/client/connection/README.md index 591e8361c1..7e437e8fd8 100644 --- a/packages/client/connection/README.md +++ b/packages/client/connection/README.md @@ -6,7 +6,7 @@ Wire consumer layer: the client plugin's apply mounts `ctx.connection` (shared a ## /api browser-trust fence -The node half guards every request under `/api` before bridging (`src/api-request-trust.ts`). Requests without browser markers (no `Origin`, no `sec-fetch-site` — curl, tests, native clients) pass on any Host: without a browser there is no confused deputy, and such a sender forges every header anyway. For browser requests, the `Host` header must be a loopback authority or match a `trustedHosts` entry — exact on `host:port` entries, any port on port-less entries, both sides compared through WHATWG normalization (DNS-rebinding defense); an attached `Origin` must equal that authority, and an explicit `sec-fetch-site: cross-site` marker is refused. A `trustedHosts` entry that is not a bare `host[:port]` authority fails the plugin load loudly — WHATWG parsing would otherwise quietly authorize the hostname inside a typo like `harness.internal/path`. Failures answer plain 403 before any RPC dispatch. A non-loopback (`--host 0.0.0.0`) deployment therefore needs its serving authorities trusted: the dsh CLI derives the machine's LAN IP literals itself and its `--trusted-host` flag declares named ones, so `trustedHosts` in cordis.yml is for compositions the CLI does not boot. The fence is deliberately not an authentication layer — reachability policy stays with the webserver binding, and auth remains deferred work. Decision record: [the api browser-trust boundary Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md). +The node half guards every request under `/api` before bridging (`src/api-request-trust.ts`). Requests without browser markers (no `Origin`, no `sec-fetch-site` — curl, tests, native clients) pass on any Host: without a browser there is no confused deputy, and such a sender forges every header anyway. For browser requests, the `Host` header must be a loopback authority or match a `trustedHosts` entry — exact on `host:port` entries, any port on port-less entries, both sides compared through WHATWG normalization (DNS-rebinding defense); an attached `Origin` must equal that authority, and an explicit `sec-fetch-site: cross-site` marker is refused. A `trustedHosts` entry that is not a bare, canonical `host[:port]` authority — one WHATWG parsing reads back exactly as written — fails the plugin load loudly: parsing would otherwise quietly authorize the hostname inside `harness.internal/path`, or broaden a dangling-colon or zero-padded port to an any-port grant. Failures answer plain 403 before any RPC dispatch. A non-loopback (`--host 0.0.0.0`) deployment therefore needs its serving authorities trusted: the dsh CLI derives the machine's LAN IP literals itself and its `--trusted-host` flag declares named ones, so `trustedHosts` in cordis.yml is for compositions the CLI does not boot. The fence is deliberately not an authentication layer — reachability policy stays with the webserver binding, and auth remains deferred work. Decision record: [the api browser-trust boundary Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md). ## Keyless fixture diff --git a/packages/client/connection/README.zh.md b/packages/client/connection/README.zh.md index bd772b2ab0..3615d5ea1b 100644 --- a/packages/client/connection/README.zh.md +++ b/packages/client/connection/README.zh.md @@ -6,7 +6,7 @@ ## /api 浏览器信任栅栏 -node 半侧在桥接前守卫 `/api` 下的每个请求(`src/api-request-trust.ts`)。不带浏览器标记的请求(无 `Origin`、无 `sec-fetch-site`——curl、测试、原生客户端)在任何 Host 上都放行:没有浏览器就不存在"混淆代理人",且这类发送方本就可以伪造任何请求头。对浏览器请求,`Host` 头必须是回环地址权威,或与某个 `trustedHosts` 条目匹配——带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,两侧均经 WHATWG 归一化后比较(DNS rebinding 防御);若带有 `Origin` 则必须与该权威完全一致;显式的 `sec-fetch-site: cross-site` 标记一律拒绝。不是纯 `host[:port]` 权威的 `trustedHosts` 条目会让插件加载大声失败——否则 WHATWG 解析会悄悄授权 `harness.internal/path` 这类笔误里的 hostname。失败在任何 RPC 分发之前以纯 403 应答。因此非回环(`--host 0.0.0.0`)部署需要让自己的服务权威被信任:dsh CLI 会自行推导本机的 LAN IP 字面量,其 `--trusted-host` flag 用于声明具名权威,所以 cordis.yml 中的 `trustedHosts` 面向 CLI 不参与引导的组合。这道栅栏刻意不承担认证职责——可达性策略归 webserver 绑定配置,认证仍是延期工作。决策记录:[api 浏览器信任边界 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md)。 +node 半侧在桥接前守卫 `/api` 下的每个请求(`src/api-request-trust.ts`)。不带浏览器标记的请求(无 `Origin`、无 `sec-fetch-site`——curl、测试、原生客户端)在任何 Host 上都放行:没有浏览器就不存在"混淆代理人",且这类发送方本就可以伪造任何请求头。对浏览器请求,`Host` 头必须是回环地址权威,或与某个 `trustedHosts` 条目匹配——带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,两侧均经 WHATWG 归一化后比较(DNS rebinding 防御);若带有 `Origin` 则必须与该权威完全一致;显式的 `sec-fetch-site: cross-site` 标记一律拒绝。不是纯的、规范形 `host[:port]` 权威的 `trustedHosts` 条目——即 WHATWG 解析读回后与原文不完全一致的——会让插件加载大声失败:否则解析会悄悄授权 `harness.internal/path` 这类笔误里的 hostname,或把悬空冒号、补零端口放大成任意端口授权。失败在任何 RPC 分发之前以纯 403 应答。因此非回环(`--host 0.0.0.0`)部署需要让自己的服务权威被信任:dsh CLI 会自行推导本机的 LAN IP 字面量,其 `--trusted-host` flag 用于声明具名权威,所以 cordis.yml 中的 `trustedHosts` 面向 CLI 不参与引导的组合。这道栅栏刻意不承担认证职责——可达性策略归 webserver 绑定配置,认证仍是延期工作。决策记录:[api 浏览器信任边界 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md)。 ## 无密钥 fixture diff --git a/packages/client/connection/src/api-request-trust.ts b/packages/client/connection/src/api-request-trust.ts index ad2519d90b..57a8cb179c 100644 --- a/packages/client/connection/src/api-request-trust.ts +++ b/packages/client/connection/src/api-request-trust.ts @@ -42,30 +42,35 @@ function parseAuthority(authority: string): URL | undefined { /** * Assert one configured `trustedHosts` entry is a bare authority (`host` or - * `host:port`) and nothing else. WHATWG parsing would quietly read a hostname - * out of `harness.internal/path` or `user@harness.internal` — a typo must fail - * the load loudly instead of authorizing its hostname or being ignored until - * requests 403. The character test refuses every URL part beyond the authority - * (path, backslash path, query, fragment, userinfo) and all whitespace, which - * WHATWG trimming would otherwise strip silently; IPv6 brackets use none of - * them. + * `host:port`) in canonical form: it must survive WHATWG parsing unchanged + * (case aside). Anything parsing would silently rewrite is refused as a typo + * that must fail the load loudly instead of being ignored until requests 403 + * or quietly changing the grant: URL parts beyond the authority + * (`harness.internal/path`, `user@harness.internal` — which would authorize + * the embedded hostname), stripped whitespace, a dangling colon or + * zero-padded port (which would broaden an intended exact-port grant to every + * port), and non-canonical host spellings (`0x7f.0.0.1`, percent-encoding, + * unbracketed IPv6; IDN hosts are declared in punycode, the form the wire + * carries). * @param entry - the configured value, verbatim. */ export function assertTrustedAuthority(entry: string): void { - if (parseAuthority(entry) !== undefined && !/[/\\?#@\s]/.test(entry)) return + const entryUrl = parseAuthority(entry) + if (entryUrl !== undefined && canonicalAuthority(entry, entryUrl) === entry.toLowerCase()) return throw new Error(`client-connection: trustedHosts entry ${JSON.stringify(entry)} is not a bare host[:port] authority`) } /** - * Whether the parsed authority carries an explicit port: judged from URL - * parses under both special schemes (their default ports differ, so `:80` and - * `:443` still count as explicit), never from the raw string, where WHATWG - * trimming of stray whitespace would misread `host:port ` as port-less and - * broaden an exact-port grant to every port. + * Canonical form of a parsed authority: `hostname` when no port was written, + * else `hostname:port`. The port is judged from URL parses under both special + * schemes (their default ports differ, so `:80` and `:443` still count as + * explicit), never from the raw string, where WHATWG trimming would misread + * shapes like `host:port ` as port-less. */ -function hasExplicitPort(entry: string, entryUrl: URL): boolean { +function canonicalAuthority(entry: string, entryUrl: URL): string { // An authority that parsed under http cannot fail under https. - return entryUrl.port !== '' || new URL(`https://${entry}`).port !== '' + const port = entryUrl.port !== '' ? entryUrl.port : new URL(`https://${entry}`).port + return port === '' ? entryUrl.hostname : `${entryUrl.hostname}:${port}` } /** @@ -79,9 +84,9 @@ function isTrustedAuthority(hostUrl: URL, trustedHosts: readonly string[]): bool return trustedHosts.some((entry) => { const entryUrl = parseAuthority(entry) if (entryUrl === undefined) return false - return hasExplicitPort(entry, entryUrl) - ? entryUrl.host === hostUrl.host - : entryUrl.hostname === hostUrl.hostname + return canonicalAuthority(entry, entryUrl) === entryUrl.hostname + ? entryUrl.hostname === hostUrl.hostname + : entryUrl.host === hostUrl.host }) } diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index f37a64fb21..a649afda1a 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -24,7 +24,7 @@ export interface ConnectionConfig { * browser request whose Host is neither loopback nor listed here, so a * non-loopback (`0.0.0.0`) deployment must declare the names it is reached * by (the dsh CLI derives the machine's LAN IP literals itself). An entry - * that is not a bare authority fails the plugin load. + * that is not a bare, canonical authority fails the plugin load. */ trustedHosts?: string[] } diff --git a/packages/client/connection/tests/api-request-trust.spec.ts b/packages/client/connection/tests/api-request-trust.spec.ts index e3f1c91caf..2c608cc988 100644 --- a/packages/client/connection/tests/api-request-trust.spec.ts +++ b/packages/client/connection/tests/api-request-trust.spec.ts @@ -79,6 +79,12 @@ describe('isTrustedApiRequest', () => { for (const entry of ['harness.internal:3080 ', ' harness.internal', 'harness.internal:30\t80']) { expect(() => { assertTrustedAuthority(entry) }).toThrow(/not a bare host\[:port\] authority/) } + // WHATWG parsing would silently rewrite these — a dangling colon or + // zero-padded port would broaden an intended exact-port grant to every + // port, and non-canonical host spellings would not read back as written. + for (const entry of ['harness.internal:', '[::1]:', 'harness.internal:0080', '0x7f.0.0.1', '[0:0:0:0:0:0:0:1]']) { + expect(() => { assertTrustedAuthority(entry) }).toThrow(/not a bare host\[:port\] authority/) + } }) it('never lets stray whitespace broaden an exact-port entry to every port', () => { From 772653464d546121c90c5d4fc77337d9716a513f Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 17:02:39 +0800 Subject: [PATCH 11/93] =?UTF-8?q?fix(connection):=20hold=20markerless=20re?= =?UTF-8?q?quests=20to=20the=20Host=20fence=20=E2=80=94=20plain-HTTP=20bro?= =?UTF-8?q?wser=20reads=20carry=20no=20markers?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fetch-Metadata and Origin are only attached to trustworthy destinations, so over plain HTTP a rebound page's same-origin GET (EventSource, images, navigations) arrives with no browser markers and a readable response. Remove the marker shortcut; non-browser clients pass the same fence via loopback, the CLI-derived LAN IP literals, or a declared authority. --- ...07-28-api-browser-trust-boundary.i18n.yaml | 4 +- .../2026-07-28-api-browser-trust-boundary.md | 4 +- ...026-07-28-api-browser-trust-boundary.zh.md | 4 +- docs/config-catalog.md | 2 +- packages/client/connection/README.i18n.yaml | 4 +- packages/client/connection/README.md | 2 +- packages/client/connection/README.zh.md | 2 +- .../connection/src/api-request-trust.ts | 40 ++++++++++--------- packages/client/connection/src/index.ts | 2 +- .../tests/api-request-trust.spec.ts | 16 ++++---- .../client/connection/tests/node-half.spec.ts | 6 +-- 11 files changed, 45 insertions(+), 41 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml index 1e10e92f49..c15af141bd 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.i18n.yaml @@ -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 .agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md -2026-07-28-api-browser-trust-boundary.md: 4dd913bb73da3b24073c020ff80fdfa83b44a812 -2026-07-28-api-browser-trust-boundary.zh.md: 0be817aca9dde68588959d2cd622639d90d9f993 +2026-07-28-api-browser-trust-boundary.md: e56d0fc2a7bd551899605491f3a0522b62b961b0 +2026-07-28-api-browser-trust-boundary.zh.md: 2958f7e49bfd4a258c63fc96c2e8aee0f98183ee diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md index 4dd913bb73..e56d0fc2a7 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md @@ -13,7 +13,7 @@ The web GUI host serves `/api` over plain HTTP (default `127.0.0.1:3080`, `--hos Enforce browser trust once, at the carrier, for the entire `/api` prefix — two halves in two stacked PRs: - **Media-type fence (dsh-host-apiproxy)**: every `/api` POST must declare `application/json`, else 415 before parsing. Cross-site "simple" requests thereby stop existing: any cross-site attempt is forced into a CORS preflight this server never answers. -- **Authority fence (dsh-client-connection, `src/api-request-trust.ts`)**: requests without browser markers (no `Origin`, no `sec-fetch-site`) pass on any Host — a non-browser client is the principal itself, not a deputy, and forges every header anyway, so fencing it buys nothing and breaks non-browser LAN automation. For browser requests, `Host` must be loopback or match a `trustedHosts` entry (exact on `host:port`, any port on port-less entries, WHATWG-normalized; rebinding defense); an attached `Origin` must equal that authority; `sec-fetch-site: cross-site` is refused outright. A `trustedHosts` entry that is not a bare authority fails the plugin load — WHATWG parsing would otherwise quietly authorize the hostname inside a typo. `host.pickDirectory` loses its bespoke guard and rides the same fence. +- **Authority fence (dsh-client-connection, `src/api-request-trust.ts`)**: every request must present a `Host` that is loopback or matches a `trustedHosts` entry (exact on `host:port`, any port on port-less entries, WHATWG-normalized; rebinding defense). Deliberately no shortcut for unmarked requests: over plain HTTP a browser attaches neither `Origin` nor Fetch-Metadata to reads (EventSource, images, navigations — those headers go only to trustworthy destinations), so an unmarked request may be a rebound browser read whose response the page can read, and Host is the one header rebinding cannot forge; non-browser clients pass via loopback, the derived LAN IP literals, or a declared authority. An attached `Origin` must equal the Host authority; `sec-fetch-site: cross-site` is refused outright. A `trustedHosts` entry that is not a bare, canonical authority fails the plugin load — WHATWG parsing would otherwise quietly authorize the hostname inside a typo or broaden an exact-port grant. `host.pickDirectory` loses its bespoke guard and rides the same fence. Two boundaries stay deliberately out of scope: reachability is the webserver binding's policy (`host: 127.0.0.1 | 0.0.0.0`), and authentication for genuinely remote deployments is deferred work recorded in the connection README — the fence is a confused-deputy defense, not an auth layer. The old guard's loopback-socket check was dropped rather than generalized: with binding expressing reachability and `trustedHosts` naming remote authorities, the socket address adds nothing a header fence does not already cover. @@ -26,6 +26,6 @@ Two boundaries stay deliberately out of scope: reachability is the webserver bin ## Consequences - Any future `/api` method is covered by construction; there is no per-route trust decision left to forget. -- Non-loopback deployments must have their serving authorities trusted or browsers are refused. The dsh CLI keeps its advertised `--host 0.0.0.0` LAN URL working by deriving the machine's LAN IP literals into the connection row (port-less entries — an IP-literal Host cannot be a rebound name, and the bound port may be OS-assigned) and offers `dsh web --trusted-host` for named authorities; compositions the CLI does not boot declare `trustedHosts` themselves. Plain curl-shape automation is unaffected everywhere. +- Non-loopback deployments must have their serving authorities trusted or requests are refused. The dsh CLI keeps its advertised `--host 0.0.0.0` LAN URL working by deriving the machine's LAN IP literals into the connection row (port-less entries — an IP-literal Host cannot be a rebound name, and the bound port may be OS-assigned) and offers `dsh web --trusted-host` for named authorities; compositions the CLI does not boot declare `trustedHosts` themselves. Non-browser automation rides the same fence: loopback, a derived LAN IP, or a declared authority passes; an undeclared DNS alias is refused. - Clients must label POST bodies `application/json` (ours always did; raw-fetch tests gained the header). - The trusted-network assumption of an unauthenticated `0.0.0.0` deployment is now documented instead of implicit. diff --git a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md index 0be817aca9..2958f7e49b 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.zh.md @@ -13,7 +13,7 @@ Web GUI 宿主以纯 HTTP 提供 `/api`(默认 `127.0.0.1:3080`,支持 `--ho 在载体层对整个 `/api` 前缀一次性执行浏览器信任检查——两半各占一个栈式 PR: - **媒体类型栅栏(dsh-host-apiproxy)**:每个 `/api` POST 必须声明 `application/json`,否则在解析前以 415 拒绝。跨站"简单请求"由此不复存在:任何跨站尝试都被逼进一次本服务器从不应答的 CORS 预检。 -- **权威栅栏(dsh-client-connection,`src/api-request-trust.ts`)**:不带浏览器标记的请求(无 `Origin`、无 `sec-fetch-site`)在任何 Host 上都放行——非浏览器客户端是委托人本人,不是代理人,且本就可以伪造任何请求头,对它设栅一无所获,反而会打断非浏览器的 LAN 自动化。对浏览器请求,`Host` 必须是回环地址,或与某个 `trustedHosts` 条目匹配(带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,均经 WHATWG 归一化;rebinding 防御);若带 `Origin` 则必须与该权威完全一致;`sec-fetch-site: cross-site` 一律拒绝。不是纯权威的 `trustedHosts` 条目会让插件加载失败——否则 WHATWG 解析会悄悄授权笔误里的 hostname。`host.pickDirectory` 失去专属守卫,与其他请求同栅而行。 +- **权威栅栏(dsh-client-connection,`src/api-request-trust.ts`)**:每个请求的 `Host` 都必须是回环地址,或与某个 `trustedHosts` 条目匹配(带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,均经 WHATWG 归一化;rebinding 防御)。刻意不为无标记请求开捷径:明文 HTTP 下浏览器的读取(EventSource、图片、导航——这些头只发给可信目标)既不带 `Origin` 也不带 Fetch-Metadata,因此无标记请求可能是被重绑页面发起且响应可被读走的读取,而 Host 是重绑唯一伪造不了的请求头;非浏览器客户端经由回环地址、推导的 LAN IP 字面量或已声明的权威通过。若带 `Origin` 则必须与 Host 权威完全一致;`sec-fetch-site: cross-site` 一律拒绝。不是纯的、规范形权威的 `trustedHosts` 条目会让插件加载失败——否则 WHATWG 解析会悄悄授权笔误里的 hostname,或放大精确端口授权。`host.pickDirectory` 失去专属守卫,与其他请求同栅而行。 两条边界刻意留在范围之外:可达性归 webserver 绑定配置(`host: 127.0.0.1 | 0.0.0.0`)管辖;真正远程部署的认证是延期工作,记录在 connection README——这道栅栏是混淆代理人防御,不是认证层。旧守卫的回环 socket 检查被放弃而非泛化:绑定表达可达性、`trustedHosts` 点名远程权威之后,socket 地址提供不了头部栅栏覆盖不到的任何东西。 @@ -26,6 +26,6 @@ Web GUI 宿主以纯 HTTP 提供 `/api`(默认 `127.0.0.1:3080`,支持 `--ho ## 后果 - 未来任何 `/api` 方法天然在覆盖范围内;不存在会被遗忘的按路由信任决定。 -- 非回环部署的服务权威必须获得信任,否则浏览器会被拒绝。dsh CLI 通过把本机 LAN IP 字面量推导进 connection 行(不带端口的条目——IP 字面量 Host 不可能是被重绑的域名,且绑定端口可能由操作系统分配)来保住它广告出的 `--host 0.0.0.0` LAN URL,并提供 `dsh web --trusted-host` 声明具名权威;CLI 不参与引导的组合自行声明 `trustedHosts`。curl 形态的自动化在任何地方都不受影响。 +- 非回环部署的服务权威必须获得信任,否则请求会被拒绝。dsh CLI 通过把本机 LAN IP 字面量推导进 connection 行(不带端口的条目——IP 字面量 Host 不可能是被重绑的域名,且绑定端口可能由操作系统分配)来保住它广告出的 `--host 0.0.0.0` LAN URL,并提供 `dsh web --trusted-host` 声明具名权威;CLI 不参与引导的组合自行声明 `trustedHosts`。非浏览器自动化走同一道栅栏:回环地址、推导的 LAN IP 或已声明的权威可通过;未声明的 DNS 别名会被拒绝。 - 客户端必须给 POST 体标注 `application/json`(我们自己的客户端一向如此;裸 fetch 测试补上了该头)。 - 无认证 `0.0.0.0` 部署的"信任网络"假设从隐含变为成文。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 878de38a19..43c9b5c8bf 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -280,7 +280,7 @@ export interface ConnectionConfig { /** * Authorities this deployment serves beyond loopback: exact `host:port`, or * port-less `host` matching any port. The /api trust fence refuses any - * browser request whose Host is neither loopback nor listed here, so a + * request whose Host is neither loopback nor listed here, so a * non-loopback (`0.0.0.0`) deployment must declare the names it is reached * by (the dsh CLI derives the machine's LAN IP literals itself). An entry * that is not a bare, canonical authority fails the plugin load. diff --git a/packages/client/connection/README.i18n.yaml b/packages/client/connection/README.i18n.yaml index c390223071..6b8558f9be 100644 --- a/packages/client/connection/README.i18n.yaml +++ b/packages/client/connection/README.i18n.yaml @@ -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/client/connection/README.md -README.md: 7e437e8fd81d1d57ead5ead64d2049111ad163dc -README.zh.md: 3615d5ea1be44e6da8e41fa17f645eb414d1ef3e +README.md: 173a9b9998e17d201b2d31d73ea74a94b319dae6 +README.zh.md: ca5da643db443956c25399f07c8b460900942ad4 diff --git a/packages/client/connection/README.md b/packages/client/connection/README.md index 7e437e8fd8..173a9b9998 100644 --- a/packages/client/connection/README.md +++ b/packages/client/connection/README.md @@ -6,7 +6,7 @@ Wire consumer layer: the client plugin's apply mounts `ctx.connection` (shared a ## /api browser-trust fence -The node half guards every request under `/api` before bridging (`src/api-request-trust.ts`). Requests without browser markers (no `Origin`, no `sec-fetch-site` — curl, tests, native clients) pass on any Host: without a browser there is no confused deputy, and such a sender forges every header anyway. For browser requests, the `Host` header must be a loopback authority or match a `trustedHosts` entry — exact on `host:port` entries, any port on port-less entries, both sides compared through WHATWG normalization (DNS-rebinding defense); an attached `Origin` must equal that authority, and an explicit `sec-fetch-site: cross-site` marker is refused. A `trustedHosts` entry that is not a bare, canonical `host[:port]` authority — one WHATWG parsing reads back exactly as written — fails the plugin load loudly: parsing would otherwise quietly authorize the hostname inside `harness.internal/path`, or broaden a dangling-colon or zero-padded port to an any-port grant. Failures answer plain 403 before any RPC dispatch. A non-loopback (`--host 0.0.0.0`) deployment therefore needs its serving authorities trusted: the dsh CLI derives the machine's LAN IP literals itself and its `--trusted-host` flag declares named ones, so `trustedHosts` in cordis.yml is for compositions the CLI does not boot. The fence is deliberately not an authentication layer — reachability policy stays with the webserver binding, and auth remains deferred work. Decision record: [the api browser-trust boundary Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md). +The node half guards every request under `/api` before bridging (`src/api-request-trust.ts`). Every request — browser-marked or not — must present a `Host` that is a loopback authority or matches a `trustedHosts` entry: exact on `host:port` entries, any port on port-less entries, both sides compared through WHATWG normalization (DNS-rebinding defense). There is deliberately no shortcut for requests without browser markers: over plain HTTP a browser attaches neither `Origin` nor Fetch-Metadata to reads (EventSource, images, navigations — those headers go only to trustworthy destinations), so an unmarked request may still be a rebound browser read with a readable response, and Host is the one header rebinding cannot forge; non-browser clients pass the same fence via loopback, the CLI-derived LAN IP literals, or a declared authority. When markers are present, an attached `Origin` must equal the Host authority, and an explicit `sec-fetch-site: cross-site` marker is refused. A `trustedHosts` entry that is not a bare, canonical `host[:port]` authority — one WHATWG parsing reads back exactly as written — fails the plugin load loudly: parsing would otherwise quietly authorize the hostname inside `harness.internal/path`, or broaden a dangling-colon or zero-padded port to an any-port grant. Failures answer plain 403 before any RPC dispatch. A non-loopback (`--host 0.0.0.0`) deployment therefore needs its serving authorities trusted: the dsh CLI derives the machine's LAN IP literals itself and its `--trusted-host` flag declares named ones, so `trustedHosts` in cordis.yml is for compositions the CLI does not boot. The fence is deliberately not an authentication layer — reachability policy stays with the webserver binding, and auth remains deferred work. Decision record: [the api browser-trust boundary Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md). ## Keyless fixture diff --git a/packages/client/connection/README.zh.md b/packages/client/connection/README.zh.md index 3615d5ea1b..ca5da643db 100644 --- a/packages/client/connection/README.zh.md +++ b/packages/client/connection/README.zh.md @@ -6,7 +6,7 @@ ## /api 浏览器信任栅栏 -node 半侧在桥接前守卫 `/api` 下的每个请求(`src/api-request-trust.ts`)。不带浏览器标记的请求(无 `Origin`、无 `sec-fetch-site`——curl、测试、原生客户端)在任何 Host 上都放行:没有浏览器就不存在"混淆代理人",且这类发送方本就可以伪造任何请求头。对浏览器请求,`Host` 头必须是回环地址权威,或与某个 `trustedHosts` 条目匹配——带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,两侧均经 WHATWG 归一化后比较(DNS rebinding 防御);若带有 `Origin` 则必须与该权威完全一致;显式的 `sec-fetch-site: cross-site` 标记一律拒绝。不是纯的、规范形 `host[:port]` 权威的 `trustedHosts` 条目——即 WHATWG 解析读回后与原文不完全一致的——会让插件加载大声失败:否则解析会悄悄授权 `harness.internal/path` 这类笔误里的 hostname,或把悬空冒号、补零端口放大成任意端口授权。失败在任何 RPC 分发之前以纯 403 应答。因此非回环(`--host 0.0.0.0`)部署需要让自己的服务权威被信任:dsh CLI 会自行推导本机的 LAN IP 字面量,其 `--trusted-host` flag 用于声明具名权威,所以 cordis.yml 中的 `trustedHosts` 面向 CLI 不参与引导的组合。这道栅栏刻意不承担认证职责——可达性策略归 webserver 绑定配置,认证仍是延期工作。决策记录:[api 浏览器信任边界 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md)。 +node 半侧在桥接前守卫 `/api` 下的每个请求(`src/api-request-trust.ts`)。每个请求——无论是否带浏览器标记——`Host` 都必须是回环地址权威,或与某个 `trustedHosts` 条目匹配:带端口的 `host:port` 条目精确匹配,不带端口的条目匹配任意端口,两侧均经 WHATWG 归一化后比较(DNS rebinding 防御)。刻意不为无浏览器标记的请求开捷径:明文 HTTP 下浏览器的读取(EventSource、图片、导航——这些头只发给可信目标)既不带 `Origin` 也不带 Fetch-Metadata,因此无标记请求仍可能是被重绑页面发起的、响应可被读走的读取,而 Host 是重绑唯一伪造不了的请求头;非浏览器客户端经由回环地址、CLI 推导的 LAN IP 字面量或已声明的权威通过同一道栅栏。当标记存在时,`Origin` 必须与 Host 权威完全一致;显式的 `sec-fetch-site: cross-site` 标记一律拒绝。不是纯的、规范形 `host[:port]` 权威的 `trustedHosts` 条目——即 WHATWG 解析读回后与原文不完全一致的——会让插件加载大声失败:否则解析会悄悄授权 `harness.internal/path` 这类笔误里的 hostname,或把悬空冒号、补零端口放大成任意端口授权。失败在任何 RPC 分发之前以纯 403 应答。因此非回环(`--host 0.0.0.0`)部署需要让自己的服务权威被信任:dsh CLI 会自行推导本机的 LAN IP 字面量,其 `--trusted-host` flag 用于声明具名权威,所以 cordis.yml 中的 `trustedHosts` 面向 CLI 不参与引导的组合。这道栅栏刻意不承担认证职责——可达性策略归 webserver 绑定配置,认证仍是延期工作。决策记录:[api 浏览器信任边界 Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-api-browser-trust-boundary.md)。 ## 无密钥 fixture diff --git a/packages/client/connection/src/api-request-trust.ts b/packages/client/connection/src/api-request-trust.ts index 57a8cb179c..8c1bddd631 100644 --- a/packages/client/connection/src/api-request-trust.ts +++ b/packages/client/connection/src/api-request-trust.ts @@ -2,12 +2,15 @@ * Browser-trust fence for every /api request. Defends the two confused-deputy * paths a browser opens against a local HTTP API — DNS rebinding (Host names * the attacker's domain while the socket reaches this server) and cross-site - * requests fired from a malicious page — without blocking non-browser clients - * (no browser markers → no deputy to confuse, and a native client forges Host - * freely anyway) or legitimately remote browsers (their authority is declared - * via `trustedHosts`, or derived by the composing app for IP-literal LAN - * serving). Network reachability and authentication stay out of scope: binding - * policy belongs to the webserver config, and this fence is not an auth layer. + * requests fired from a malicious page. The Host fence binds every request, + * browser-looking or not: over plain HTTP a browser attaches neither Origin + * nor Fetch-Metadata to reads (EventSource, images, navigations — those + * headers go only to trustworthy destinations), so an unmarked request may + * still be a rebound browser read and Host is the one header rebinding cannot + * forge. Non-browser and remote clients pass the same fence via loopback, the + * CLI-derived LAN IP literals, or a declared `trustedHosts` authority. + * Network reachability and authentication stay out of scope: binding policy + * belongs to the webserver config, and this fence is not an auth layer. */ import type { IncomingHttpHeaders } from 'node:http' @@ -94,19 +97,16 @@ function isTrustedAuthority(hostUrl: URL, trustedHosts: readonly string[]): bool * Decide whether one /api request may reach the RPC bridge. * @param request - node HTTP request facts (headers). * @param trustedHosts - non-loopback authorities this deployment serves: exact `host:port`, or port-less `host` matching any port. - * @returns true for requests without browser markers, and for browser requests whose Host is ours and whose markers are same-origin. + * @returns true when the Host is ours (loopback or trusted) and any attached browser markers are same-origin. */ export function isTrustedApiRequest(request: ApiTrustRequest, trustedHosts: readonly string[]): boolean { - // Marker gate: Origin and sec-fetch-site exist only when a browser is the - // sender's deputy. Absent both, the sender is the principal itself (curl, - // tests, native shells) and could forge every header below — fencing it - // would add nothing and would break non-browser LAN automation. - const origin = header(request.headers, 'origin') - const secFetchSite = header(request.headers, 'sec-fetch-site') - if (origin === undefined && secFetchSite === undefined) return true - // Host fence (DNS-rebinding defense): the browser fills Host from the URL it - // believes it is talking to, so a rebound page carries the attacker's domain - // here even though the socket lands on this server. + // Host fence (DNS-rebinding defense), applied to every request: the browser + // fills Host from the URL it believes it is talking to, so a rebound page + // carries the attacker's domain here even though the socket lands on this + // server. There is no marker shortcut — a browser read over plain HTTP + // (EventSource, images, navigations) arrives with neither Origin nor + // Fetch-Metadata, indistinguishable from curl, and its response is readable + // by the rebound page. const host = header(request.headers, 'host') if (host === undefined) return false const hostUrl = parseAuthority(host) @@ -114,10 +114,12 @@ export function isTrustedApiRequest(request: ApiTrustRequest, trustedHosts: read if (!isLoopbackHostname(hostUrl.hostname) && !isTrustedAuthority(hostUrl, trustedHosts)) return false // Cross-site fence: modern browsers label the initiator relationship on // every fetch; an explicit cross-site marker is refused regardless of Origin. - if (secFetchSite === 'cross-site') return false + if (header(request.headers, 'sec-fetch-site') === 'cross-site') return false // Origin fence: when a browser attaches an Origin it must be exactly this - // authority (compared through the same normalization as the Host). The + // authority (compared through the same normalization as the Host). Absent + // Origin is fine — the Host fence above already bound the request. The // literal "null" (sandboxed iframes, file: pages) is an opaque origin, refused. + const origin = header(request.headers, 'origin') if (origin === undefined) return true try { return new URL(origin).host === hostUrl.host diff --git a/packages/client/connection/src/index.ts b/packages/client/connection/src/index.ts index a649afda1a..ce55089bdb 100644 --- a/packages/client/connection/src/index.ts +++ b/packages/client/connection/src/index.ts @@ -21,7 +21,7 @@ export interface ConnectionConfig { /** * Authorities this deployment serves beyond loopback: exact `host:port`, or * port-less `host` matching any port. The /api trust fence refuses any - * browser request whose Host is neither loopback nor listed here, so a + * request whose Host is neither loopback nor listed here, so a * non-loopback (`0.0.0.0`) deployment must declare the names it is reached * by (the dsh CLI derives the machine's LAN IP literals itself). An entry * that is not a bare, canonical authority fails the plugin load. diff --git a/packages/client/connection/tests/api-request-trust.spec.ts b/packages/client/connection/tests/api-request-trust.spec.ts index 2c608cc988..f145230a8b 100644 --- a/packages/client/connection/tests/api-request-trust.spec.ts +++ b/packages/client/connection/tests/api-request-trust.spec.ts @@ -8,13 +8,15 @@ function request(headers: Record): { headers: Record } describe('isTrustedApiRequest', () => { - it('accepts every request without browser markers — curl, tests, native clients, on any Host', () => { - // No Origin and no sec-fetch-site → the sender is the principal itself - // (it forges Host freely anyway); this is the LAN-serving shape a Host - // fence must not break. - for (const host of ['127.0.0.1:3080', '192.168.1.5:3080', 'harness.example', undefined]) { - expect(isTrustedApiRequest(request(host === undefined ? {} : { host }), [])).toBe(true) - } + it('holds markerless requests to the same Host fence — a plain-HTTP browser read carries no markers', () => { + // Over plain HTTP a browser attaches neither Origin nor Fetch-Metadata to + // reads (EventSource, images, navigations), so a rebound-origin GET is + // markerless and its response readable: no marker shortcut may exist. + expect(isTrustedApiRequest(request({ host: '127.0.0.1:3080' }), [])).toBe(true) + expect(isTrustedApiRequest(request({ host: '192.168.1.5:3080' }), ['192.168.1.5'])).toBe(true) + expect(isTrustedApiRequest(request({ host: '192.168.1.5:3080' }), [])).toBe(false) + expect(isTrustedApiRequest(request({ host: 'harness.example' }), [])).toBe(false) + expect(isTrustedApiRequest(request({}), [])).toBe(false) }) it('accepts loopback Hosts in every spelling, with and without ports, for browser requests', () => { diff --git a/packages/client/connection/tests/node-half.spec.ts b/packages/client/connection/tests/node-half.spec.ts index 5404f1c798..2c7fd0b281 100644 --- a/packages/client/connection/tests/node-half.spec.ts +++ b/packages/client/connection/tests/node-half.spec.ts @@ -98,14 +98,14 @@ describe('connection node half', () => { }) it('passes loopback and declared-authority requests through to the bridge', async () => { - const { routes, dispose } = await mounted({ trustedHosts: ['harness.example:3080'] }) + const { routes, dispose } = await mounted({ trustedHosts: ['harness.example:3080', '192.168.1.5'] }) // Loopback, no browser markers (curl shape): the fence passes; the carrier // answers 404 for a GET unary path — proof the bridge ran. const loopback = fakeResponse() await routes[0]!.handler(fakeRequest({ host: '127.0.0.1:3080' }), loopback.response) expect(loopback.state.status).toBe(404) - // Undeclared LAN authority, no browser markers: the `--host 0.0.0.0` curl - // shape must reach the bridge even with an empty-by-default trust list. + // LAN authority declared as a port-less IP literal — the shape the CLI + // derives for `--host 0.0.0.0` — passes markerless curl on any port. const lan = fakeResponse() await routes[0]!.handler(fakeRequest({ host: '192.168.1.5:3080' }), lan.response) expect(lan.state.status).toBe(404) From c565022c8af85c5fd3b780c6459a6939aca8c4bf Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 17:09:43 +0800 Subject: [PATCH 12/93] fix(host): derive the picker capability union from a merge-extensible map MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ds-review-bot round 1: the seam documented a merge-extensible union but shipped a closed alias, and the gateway schema rejected any kind beyond dialog/browse — a third backend could neither implement the seam nor be advertised. The union now derives from an augmentable DirectoryPickerCapabilities map, host.describe.directoryPicker preserves unknown wire kinds, and the browse fixture applies listDirectory's root special case so creating under '/' no longer mints a '//name' identity. --- docs/cordis-catalog/services.md | 2 +- packages/client/connection/src/client/fixture.ts | 4 +++- packages/client/connection/tests/fixture.spec.ts | 16 ++++++++++++++++ packages/cordis/tool-cordis/src/api-catalog.ts | 6 +++++- packages/host/apiproxy/src/api/host.schema.ts | 4 +++- packages/host/apiproxy/src/api/host.ts | 5 ++++- packages/host/apiproxy/tests/rpc-schemas.spec.ts | 4 +++- packages/host/directory-picker/README.i18n.yaml | 4 ++-- packages/host/directory-picker/README.md | 2 +- packages/host/directory-picker/README.zh.md | 2 +- packages/host/directory-picker/src/index.ts | 14 ++++++++++++-- 11 files changed, 51 insertions(+), 12 deletions(-) diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index eb212207b3..397e7320d5 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -481,7 +481,7 @@ Abstract directory-picking service. Subclass, implement `capability()`, and load abstract capability(): DirectoryPickerCapability ``` -Source: [`packages/host/directory-picker/src/index.ts:108`](../../packages/host/directory-picker/src/index.ts) +Source: [`packages/host/directory-picker/src/index.ts:118`](../../packages/host/directory-picker/src/index.ts) ## `ctx.fs` — `FileSystem` (abstract seam) diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index a490f0d27d..fdc258beed 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -831,7 +831,9 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { if (children === undefined) { return err(request, { code: 'directory-create-failed', message: `missing parent ${parent}`, details: { path: parent } }) } - const target = `${parent}/${request.payload.name}` + // Same root special case as listDirectory's entry paths: a plain join + // under '/' would mint '//name' and fork the tree's identity. + const target = parent === '/' ? `/${request.payload.name}` : `${parent}/${request.payload.name}` if (children.includes(request.payload.name)) { return err(request, { code: 'directory-exists', message: `${target} already exists`, details: { path: target } }) } diff --git a/packages/client/connection/tests/fixture.spec.ts b/packages/client/connection/tests/fixture.spec.ts index 1b413441df..3f07922f4d 100644 --- a/packages/client/connection/tests/fixture.spec.ts +++ b/packages/client/connection/tests/fixture.spec.ts @@ -312,6 +312,22 @@ describe('createFixtureApi', () => { expect(empty.result).toMatchObject({ ok: true, value: { attachedSessions: 0 } }) }) + it('createDirectory under the root mints /name whose listing and crumbs share the identity', async () => { + const api = createFixtureApi() + const created = await api.host.createDirectory(req({ path: '/', name: 'srv' })) + if (!created.result.ok) throw new Error('create failed') + expect(created.result.value.path).toBe('/srv') + const listed = await api.host.listDirectory(req({ path: '/srv' })) + if (!listed.result.ok) throw new Error('list failed') + expect(listed.result.value.crumbs).toEqual([ + { name: '/', path: '/', hidden: false }, + { name: 'srv', path: '/srv', hidden: false }, + ]) + const root = await api.host.listDirectory(req({ path: '/' })) + if (!root.result.ok) throw new Error('root list failed') + expect(root.result.value.entries).toContainEqual({ name: 'srv', path: '/srv', hidden: false }) + }) + it('workspace.list serves the resident account and create reuses on path collision', async () => { const api = createFixtureApi() const listed = await api.workspace.list(req({})) diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index 04b2e60ef0..698dd32201 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -1603,9 +1603,13 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'DirectoryPickerBrowseCapability', declaration: 'export interface DirectoryPickerBrowseCapability {\n kind: \'browse\';\n list(path?: string): Promise;\n createDirectory(path: string, name: string): Promise;\n}', }, + { + name: 'DirectoryPickerCapabilities', + declaration: 'export interface DirectoryPickerCapabilities {\n dialog: DirectoryPickerDialogCapability;\n browse: DirectoryPickerBrowseCapability;\n}', + }, { name: 'DirectoryPickerCapability', - declaration: 'export type DirectoryPickerCapability = DirectoryPickerDialogCapability | DirectoryPickerBrowseCapability;', + declaration: 'export type DirectoryPickerCapability = DirectoryPickerCapabilities[keyof DirectoryPickerCapabilities];', }, { name: 'DirectoryPickerDialogCapability', diff --git a/packages/host/apiproxy/src/api/host.schema.ts b/packages/host/apiproxy/src/api/host.schema.ts index a73b659970..d4a3a95754 100644 --- a/packages/host/apiproxy/src/api/host.schema.ts +++ b/packages/host/apiproxy/src/api/host.schema.ts @@ -17,7 +17,9 @@ export const hostDescribeValueSchema = z.object({ provider: z.string().optional(), model: z.string().optional(), attachedSessions: z.number().int().nonnegative(), - directoryPicker: z.union([z.literal('dialog'), z.literal('browse')]), + // Open string, not a literal union: unknown kinds must survive the wire so + // a merge-added capability can advertise (the client hides the affordance). + directoryPicker: z.string(), }) satisfies z.ZodType>> /** host.pickDirectory request payload (empty object literal). */ diff --git a/packages/host/apiproxy/src/api/host.ts b/packages/host/apiproxy/src/api/host.ts index abdb3c468b..3de58b7bc7 100644 --- a/packages/host/apiproxy/src/api/host.ts +++ b/packages/host/apiproxy/src/api/host.ts @@ -11,8 +11,11 @@ import type { RpcRequest, RpcResponse } from './rpc.ts' * the host display (`host.pickDirectory`); `browse` = in-app listing/creation * primitives (`host.listDirectory`/`host.createDirectory`). Calling a method * outside the advertised kind fails with `directory-picker-unavailable`. + * The wire preserves kinds beyond the two with methods here (a merge-added + * capability advertises before its RPCs exist); the client's documented + * default for a kind it does not recognize is to hide the picking affordance. */ -export type DirectoryPickerKind = 'dialog' | 'browse' +export type DirectoryPickerKind = 'dialog' | 'browse' | (string & {}) /** One directory row of a listing: a child entry or a breadcrumb ancestor. */ export interface DirectoryEntry { diff --git a/packages/host/apiproxy/tests/rpc-schemas.spec.ts b/packages/host/apiproxy/tests/rpc-schemas.spec.ts index f64883c85b..939de7677e 100644 --- a/packages/host/apiproxy/tests/rpc-schemas.spec.ts +++ b/packages/host/apiproxy/tests/rpc-schemas.spec.ts @@ -211,7 +211,9 @@ describe('host domain schemas', () => { const value = hostDescribeValueSchema.parse({ version: '1', cwd: '/x', provider: 'p', model: 'm', attachedSessions: 2, directoryPicker: 'dialog' }) expect(value.attachedSessions).toBe(2) expect(hostDescribeValueSchema.parse({ version: '1', cwd: '/x', attachedSessions: 0, directoryPicker: 'browse' }).provider).toBeUndefined() - expect(() => hostDescribeValueSchema.parse({ version: '1', cwd: '/x', attachedSessions: 0, directoryPicker: 'other' })).toThrow() + // A kind beyond the two with methods survives the wire (merge-added + // capabilities advertise; the client hides the affordance). + expect(hostDescribeValueSchema.parse({ version: '1', cwd: '/x', attachedSessions: 0, directoryPicker: 'other' }).directoryPicker).toBe('other') }) it('validates the browse listing/creation payloads', () => { diff --git a/packages/host/directory-picker/README.i18n.yaml b/packages/host/directory-picker/README.i18n.yaml index 0d5c753e92..a331a2caeb 100644 --- a/packages/host/directory-picker/README.i18n.yaml +++ b/packages/host/directory-picker/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/directory-picker/README.md -README.md: c1a801cf72f128e6e5ef668c5e28e03ad2284868 -README.zh.md: c352b35b70dfa835aecfcb5ffec2a9ac46f25c42 +README.md: 0332f7df067bfa79c7505be948554e814a690c6c +README.zh.md: a9a782019d0badfba33a7d108113ff5323fde77a diff --git a/packages/host/directory-picker/README.md b/packages/host/directory-picker/README.md index c1a801cf72..0332f7df06 100644 --- a/packages/host/directory-picker/README.md +++ b/packages/host/directory-picker/README.md @@ -2,7 +2,7 @@ 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: 'dialog', pick(signal) }` opens one native OS chooser on the host display ([`-dialog`](../directory-picker-dialog/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 dialog can reach ([`-browse`](../directory-picker-browse/README.md)). 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. The capability object must be stable for the service lifetime. +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: 'dialog', pick(signal) }` opens one native OS chooser on the host display ([`-dialog`](../directory-picker-dialog/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 dialog 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. 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). diff --git a/packages/host/directory-picker/README.zh.md b/packages/host/directory-picker/README.zh.md index c352b35b70..a9a782019d 100644 --- a/packages/host/directory-picker/README.zh.md +++ b/packages/host/directory-picker/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -web GUI 宿主的**工作区目录选择 seam**:抽象服务 `DirectoryPicker`(`ctx.directoryPicker`),唯一契约方法 `capability()` 返回一个可辨识能力对象,描述操作者以何种方式选择目录。后端之间的差异在交互形态而不只是机制,因此 seam 显式建模形态而非统一方法集:`{ kind: 'dialog', pick(signal) }` 在宿主屏幕上打开一个原生 OS 选择器([`-dialog`](../directory-picker-dialog/README.md));`{ kind: 'browse', list(path?), createDirectory(path, name) }` 提供应用内浏览器驱动的列举/创建原语,可服务任何 OS 对话框都触及不到的远程客户端([`-browse`](../directory-picker-browse/README.md))。消费方按 `capability().kind` 分支;联合类型可合并扩展,未知 kind 的文档化默认行为是隐藏选择入口而非失败。能力对象在服务生命周期内必须保持稳定。 +web GUI 宿主的**工作区目录选择 seam**:抽象服务 `DirectoryPicker`(`ctx.directoryPicker`),唯一契约方法 `capability()` 返回一个可辨识能力对象,描述操作者以何种方式选择目录。后端之间的差异在交互形态而不只是机制,因此 seam 显式建模形态而非统一方法集:`{ kind: 'dialog', pick(signal) }` 在宿主屏幕上打开一个原生 OS 选择器([`-dialog`](../directory-picker-dialog/README.md));`{ kind: 'browse', list(path?), createDirectory(path, name) }` 提供应用内浏览器驱动的列举/创建原语,可服务任何 OS 对话框都触及不到的远程客户端([`-browse`](../directory-picker-browse/README.md))。消费方按 `capability().kind` 分支;联合类型由可合并扩展的 `DirectoryPickerCapabilities` 映射派生(新后端在其中声明合并自己的形态),未知 kind 的文档化默认行为是隐藏选择入口而非失败。能力对象在服务生命周期内必须保持稳定。 浏览原语以带类型的 `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)。 diff --git a/packages/host/directory-picker/src/index.ts b/packages/host/directory-picker/src/index.ts index 5e184b36e1..5a6040e51f 100644 --- a/packages/host/directory-picker/src/index.ts +++ b/packages/host/directory-picker/src/index.ts @@ -73,8 +73,18 @@ export interface DirectoryPickerBrowseCapability { createDirectory(path: string, name: string): Promise } -/** Union of interaction shapes a backend can provide (merge-extensible: grows with backends). */ -export type DirectoryPickerCapability = DirectoryPickerDialogCapability | DirectoryPickerBrowseCapability +/** + * 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 { + dialog: DirectoryPickerDialogCapability + 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' From 006a6655ee78db607524e1c1f000273f488ff96b Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 17:15:39 +0800 Subject: [PATCH 13/93] feat(web): in-app workspace-directory browser as the shipped picking default MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Open-local-folder flow now branches on the Host's advertised picker interaction (host.describe.directoryPicker, read per menu open; unknown kinds hide the entry): dialog keeps the native-chooser flow, and browse opens the new in-app directory browser (figma Harness 802-56979) — breadcrumbs rooted at a localized Home crumb, a click-to-edit path zone right of the crumbs, host-flagged hidden entries filtered client-side, an inline New-folder row, and Open adopting the listed directory through the existing workspace-creation error surface. Dialog copy is localized (ctx.locale, namespace 'workspace'); the plugin re-registers its entries on locale/change. apps/cli flips the composed backend from -dialog to -browse, so the picker works for remote deployments out of the box; -dialog stays a composable alternative. The workspace-management e2e drops its native picker monkey-patch and drives the real modal end-to-end via the path-edit affordance. --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 2 +- ...-28-directory-picker-capability-seam.zh.md | 2 +- apps/cli/cordis.yml | 4 +- apps/cli/package.json | 2 +- apps/web/tests/workspace-management.e2e.ts | 53 ++-- packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 5 +- packages/client/ui-workspace/README.zh.md | 5 +- packages/client/ui-workspace/package.json | 3 + .../src/client/DirectoryBrowser.module.css | 185 +++++++++++++ .../src/client/DirectoryBrowser.tsx | 246 ++++++++++++++++++ .../src/client/WorkspaceBrowser.tsx | 8 + .../src/client/WorkspacePicker.tsx | 86 ++++-- .../ui-workspace/src/client/contract/slots.ts | 33 ++- .../client/ui-workspace/src/client/index.ts | 55 +++- .../client/ui-workspace/tests/apply.spec.ts | 18 +- .../tests/directory-browser.spec.tsx | 160 ++++++++++++ .../tests/workspace-browser.spec.tsx | 4 + .../tests/workspace-picker.spec.tsx | 96 ++++++- packages/client/ui-workspace/tsconfig.json | 3 + pnpm-lock.yaml | 7 +- 22 files changed, 913 insertions(+), 72 deletions(-) create mode 100644 packages/client/ui-workspace/src/client/DirectoryBrowser.module.css create mode 100644 packages/client/ui-workspace/src/client/DirectoryBrowser.tsx create mode 100644 packages/client/ui-workspace/tests/directory-browser.spec.tsx diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml index ccef0728d9..6790dafee5 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml @@ -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 .agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md -2026-07-28-directory-picker-capability-seam.md: 8d9d34e7aed4525b243380a4a90801fe59bfc213 -2026-07-28-directory-picker-capability-seam.zh.md: 282f3905c3551912915088f70247260310f442cb +2026-07-28-directory-picker-capability-seam.md: 2bfb80965cec020bac0995173cf5b44ff6f14e37 +2026-07-28-directory-picker-capability-seam.zh.md: ab303e5eca8ae18413e4d2496a6fae3774630e6a diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md index 8d9d34e7ae..2bfb80965c 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md @@ -30,7 +30,7 @@ Placement and policy rulings folded into this decision: ## Consequences -- `cordis.yml` chooses the interaction; `apps/cli` currently mounts `-dialog` (unchanged behavior), and the in-app browser PR flips the default to `-browse` with the GUI branching on `describe`. +- `cordis.yml` chooses the interaction; `apps/cli` mounts `-browse` (the in-app browser is the shipped default), the GUI branches on `describe`, and `-dialog` stays a composable alternative for host-display deployments. - The wire gains `host.listDirectory`/`host.createDirectory`, four error codes, and the `describe.directoryPicker` field; the connection fixture serves a deterministic browse tree for keyless assembled tests. - A future interaction (or an Electron `dialog` provider) is one backend package plus a client branch — no gateway surgery. - `ApiProxyDefaults.pickDirectory` (test-only injection) is gone; tests provide a stub `ctx.directoryPicker` like any other service. diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md index 282f3905c3..ab303e5eca 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md @@ -30,7 +30,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick ## 后果 -- `cordis.yml` 决定交互形态;`apps/cli` 当前挂 `-dialog`(行为不变),应用内浏览器 PR 将把默认翻到 `-browse` 并让 GUI 按 `describe` 分支。 +- `cordis.yml` 决定交互形态;`apps/cli` 挂 `-browse`(应用内浏览器为发布默认),GUI 按 `describe` 分支,`-dialog` 作为面向宿主屏幕部署的可组合备选保留。 - 协议新增 `host.listDirectory`/`host.createDirectory`、四个错误码与 `describe.directoryPicker` 字段;connection fixture 提供确定性浏览树供无密钥组装测试使用。 - 未来的新交互(或 Electron 的 `dialog` 提供方)只是一个后端包加一个客户端分支——无需网关手术。 - `ApiProxyDefaults.pickDirectory`(仅测试注入)删除;测试像提供其他服务一样提供 stub `ctx.directoryPicker`。 diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index 1ca28ecdaa..59ca20a802 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -234,9 +234,9 @@ # shares. provider/model are the host default routing — the profile json's # mapping target (user config overrides these engineering defaults). # Directory-picking backend consumed by the gateway's host.* picker RPCs. -# Swap point: mount '-browse' instead for the in-app browser (remote-capable). +# Swap point: mount '-dialog' instead for the native OS chooser (host-display only). - id: directory-picker - name: '@deepseek-ai/dsh-host-directory-picker-dialog' + name: '@deepseek-ai/dsh-host-directory-picker-browse' - id: api-gateway name: '@deepseek-ai/dsh-host-apiproxy' diff --git a/apps/cli/package.json b/apps/cli/package.json index 90b51e0397..c40903de87 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -48,7 +48,7 @@ "@deepseek-ai/dsh-fs-local": "workspace:^", "@deepseek-ai/dsh-fs-policy": "workspace:^", "@deepseek-ai/dsh-host-apiproxy": "workspace:^", - "@deepseek-ai/dsh-host-directory-picker-dialog": "workspace:^", + "@deepseek-ai/dsh-host-directory-picker-browse": "workspace:^", "@deepseek-ai/dsh-host-webserver": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-llm-deepseek": "workspace:^", diff --git a/apps/web/tests/workspace-management.e2e.ts b/apps/web/tests/workspace-management.e2e.ts index fd18d89087..674969debe 100644 --- a/apps/web/tests/workspace-management.e2e.ts +++ b/apps/web/tests/workspace-management.e2e.ts @@ -30,14 +30,40 @@ describe('web e2e: workspace management (create / rename / flat view / hover car let browser: Browser let page: Page let tripwire: ReturnType - let pickedDirectory: string | null = null + + /** + * Drive the in-app browser to a directory via its path-edit affordance, + * confirm it, and wait for the adoption to settle host-side (workspace + * registered + the flow's New-Session agent up), so later test steps can't + * race the in-flight blank-session attach. + */ + async function openLocalFolder(path: string, options: { waitForAgent?: boolean } = {}): Promise { + const agentsBefore = scaffold.ctx.agents.list().length + await page.getByRole('button', { name: 'Create workspace' }).click() + await page.getByRole('menuitem', { name: 'Open local folder…' }).click() + const dialog = page.getByRole('dialog', { name: '选择工作区目录' }) + await dialog.waitFor({ timeout: 10_000 }) + await dialog.getByRole('button', { name: '编辑路径' }).click() + await dialog.getByLabel('编辑路径').fill(path) + await dialog.getByLabel('编辑路径').press('Enter') + await dialog.getByRole('button', { name: '打开' }).click() + await dialog.waitFor({ state: 'hidden', timeout: 10_000 }) + await expect.poll( + () => scaffold.ctx.workspace.resolveByPath(path), + { timeout: 10_000 }, + ).not.toBeUndefined() + // First adoption births a blank Session+Agent whose workspace attach must + // settle before a test may delete the registration; the reuse path (same + // canonical cwd already has a blank session) creates no agent, so callers + // opt in only where a fresh attach is possible. + if (options.waitForAgent === true) { + await expect.poll(() => scaffold.ctx.agents.list().length, { timeout: 10_000 }) + .toBeGreaterThan(agentsBefore) + } + } beforeAll(async () => { scaffold = await launchWebScaffold({}) - scaffold.ctx.apiProxy.host.pickDirectory = request => Promise.resolve({ - rpcId: request.rpcId, - result: { ok: true, value: { path: pickedDirectory } }, - }) // Seed one cold session (Ungrouped bucket) for the flat view + hover card. const sessionCwd = join(scaffold.workspaceCwd, 'workspace') await mkdir(sessionCwd, { recursive: true }) @@ -137,14 +163,7 @@ describe('web e2e: workspace management (create / rename / flat view / hover car collect() }) // Register the scaffold's existing project directory through the real UI. - pickedDirectory = scaffold.workspaceCwd - await page.getByRole('button', { name: 'Create workspace' }).click() - await page.getByRole('menuitem', { name: 'Open local folder…' }).click() - - await expect.poll( - () => scaffold.ctx.workspace.resolveByPath(scaffold.workspaceCwd), - { timeout: 10_000 }, - ).not.toBeUndefined() + await openLocalFolder(scaffold.workspaceCwd, { waitForAgent: true }) const workspace = await scaffold.ctx.workspace.resolveByPath(scaffold.workspaceCwd) if (workspace === undefined) throw new Error('GUI did not register the existing project directory') await workspace.attachSession(SessionId(SEED_ID)) @@ -200,9 +219,7 @@ describe('web e2e: workspace management (create / rename / flat view / hover car // Re-registering the exact deleted path immediately, without a reload, is // a supported reversible flow. It creates a fresh Workspace id without // re-adopting the retained Session. - pickedDirectory = scaffold.workspaceCwd - await page.getByRole('button', { name: 'Create workspace' }).click() - await page.getByRole('menuitem', { name: 'Open local folder…' }).click() + await openLocalFolder(scaffold.workspaceCwd) await expect.poll( () => scaffold.ctx.workspace.resolveByPath(scaffold.workspaceCwd), { timeout: 10_000 }, @@ -272,9 +289,7 @@ describe('web e2e: workspace management (create / rename / flat view / hover car collect() }) - pickedDirectory = oldPath - await page.getByRole('button', { name: 'Create workspace' }).click() - await page.getByRole('menuitem', { name: 'Open local folder…' }).click() + await openLocalFolder(oldPath) await expect.poll( () => scaffold.ctx.workspace.resolveByPath(oldPath), { timeout: 10_000 }, diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 0d78a8d648..2b9868cdc4 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -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/client/ui-workspace/README.md -README.md: edd6c2f9373d97832def86bb44658d7c1c68dae9 -README.zh.md: f7b73dde953d4294d4d157f479fe932adf1a29c4 +README.md: e478670facaccadd49999a5dfeaac369801036e3 +README.zh.md: 1348b59ac35aaaa103f8653dad33633bbe7792b1 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index edd6c2f937..e478670fac 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) Shared Workspace picker plugin. `WorkspaceBrowser` is registered into the sidebar's `sidebar.workspaces` slot and `WorkspacePicker` into the page-local Session Intent hero's `conversation.hero.workspace` slot, so both surfaces use the same menu and creation flow. -The picker lists real Host Workspace entities through the global `useWorkspaces` hook. Selecting a Workspace invokes the slot owner's `onPick` callback to retarget the frontend Session object. The flat **Open local folder...** action delegates to the Host's native single-directory picker, adopts a returned path through the object layer, and selects the committed Workspace only after its list projection has refreshed; cancellation is silent, and errors remain retryable. **Create a new workspace** retains the name dialog and disables names already present in that list, while the Host remains authoritative for concurrent or non-UI callers. The runtime Session and Workspace services own materialization. The Workspace row's Delete action opens a confirmation that states the retention boundary, blocks duplicate submission, and keeps failures open; success removes the group while its Sessions remain under Ungrouped. +The picker lists real Host Workspace entities through the global `useWorkspaces` hook. Selecting a Workspace invokes the slot owner's `onPick` callback to retarget the frontend Session object. The flat **Open local folder...** action branches on the Host's advertised picker interaction (`host.describe.directoryPicker`, read per menu open; an unknown kind hides the entry): under `dialog` it delegates to the Host's native single-directory chooser, and under `browse` it opens the in-app directory browser (figma 802-56979) — breadcrumbs rooted at a localized Home crumb, a click-to-edit path zone right of the crumbs (Enter navigates, Escape restores), host-flagged hidden entries filtered client-side, an inline New-folder row, and Open adopting the listed directory. Either way adoption goes through the object layer and selects the committed Workspace only after its list projection has refreshed; cancellation is silent, and errors remain retryable. The browser dialog's copy is localized through `ctx.locale` (namespace `workspace`), and the plugin re-registers its entries on `locale/change`. **Create a new workspace** retains the name dialog and disables names already present in that list, while the Host remains authoritative for concurrent or non-UI callers. The runtime Session and Workspace services own materialization. The Workspace row's Delete action opens a confirmation that states the retention boundary, blocks duplicate submission, and keeps failures open; success removes the group while its Sessions remain under Ungrouped. Both target slots are declared by other plugins, so `apply` registers through declaration-aware deferral and re-registers after a declaring slot is restored. @@ -19,4 +19,5 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work - **No Session deletion control** — the existing Session menu row remains visual-only; Workspace registration deletion does not delete Sessions. -- **Native folder selection depends on the local Host carrier** — fixture-only or remote browser deployments cannot open a local operating-system dialog; platform failures are shown in a retryable modal. +- **Native folder selection depends on the local Host carrier** — under a `dialog` composition, fixture-only or remote browser deployments cannot open a local operating-system dialog; platform failures are shown in a retryable modal. The shipped default composes `browse`, which has no such dependence. +- **No show-hidden toggle yet** — the Host flags hidden entries and the browser filters them unconditionally; the toggle is a deferred client-only change. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index f7b73dde95..1348b59ac3 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -4,7 +4,7 @@ 共享 Workspace 选择器插件。`WorkspaceBrowser` 注册到侧边栏的 `sidebar.workspaces` slot,`WorkspacePicker` 注册到页面局部 Session Intent 主视觉区的 `conversation.hero.workspace` slot,因此两个表层使用同一菜单和创建流程。 -该选择器通过全局 `useWorkspaces` hook 列出真实的 Host Workspace 实体。选择 Workspace 会调用 slot owner 的 `onPick` 回调,重新定位前端 Session 对象。平铺显示的 **打开本地文件夹…** 操作会委托 Host 的原生单目录选择器,通过对象层接纳返回的路径,并等待 Workspace 列表投影刷新后才选中已提交的 Workspace;取消操作不会显示提示,发生错误后仍可重试。**创建新工作区** 操作保留名称对话框,并禁用列表中已有的名称,而 Host 对并发或非 UI 调用方仍具有最终决定权。运行时 Session 与 Workspace 服务负责物化。Workspace 行内的 Delete 操作会打开确认框,说明保留边界、阻止重复提交,并在失败时保持打开;成功后,该分组会被移除,其 Session 则留在 Ungrouped 下。 +该选择器通过全局 `useWorkspaces` hook 列出真实的 Host Workspace 实体。选择 Workspace 会调用 slot owner 的 `onPick` 回调,重新定位前端 Session 对象。平铺显示的 **打开本地文件夹…** 操作按 Host 广播的选择器交互形态分支(`host.describe.directoryPicker`,每次菜单打开时读取;未知 kind 隐藏该入口):在 `dialog` 下委托 Host 的原生单目录选择器,在 `browse` 下打开应用内目录浏览器(figma 802-56979)——面包屑以本地化的"主目录"crumb 为根、面包屑右侧空白区点击进入路径编辑态(Enter 导航、Escape 还原)、宿主打标的隐藏条目在客户端过滤、内联新建文件夹行、"打开"接纳当前列出的目录。两条路径的接纳都经由对象层,并等待 Workspace 列表投影刷新后才选中已提交的 Workspace;取消操作不会显示提示,发生错误后仍可重试。浏览器对话框的文案经 `ctx.locale` 本地化(命名空间 `workspace`),插件在 `locale/change` 时重新注册其条目。**创建新工作区** 操作保留名称对话框,并禁用列表中已有的名称,而 Host 对并发或非 UI 调用方仍具有最终决定权。运行时 Session 与 Workspace 服务负责物化。Workspace 行内的 Delete 操作会打开确认框,说明保留边界、阻止重复提交,并在失败时保持打开;成功后,该分组会被移除,其 Session 则留在 Ungrouped 下。 两个目标 slot 都由其他插件声明,因此 `apply` 通过声明感知的延迟机制完成注册,并在声明该 slot 的插件恢复后重新注册。 @@ -19,4 +19,5 @@ ## 已知限制与暂缓事项 - **没有 Session 删除控件**:现有 Session 菜单行仍仅提供视觉效果;删除 Workspace 注册记录不会删除 Session。 -- **原生文件夹选择依赖本地 Host 载体**:仅使用 fixture(测试前置数据)的部署或远程浏览器部署无法打开本地操作系统对话框;模态框会显示平台故障,并允许重试。 +- **原生文件夹选择依赖本地 Host 载体**:在 `dialog` 组合下,仅使用 fixture(测试前置数据)的部署或远程浏览器部署无法打开本地操作系统对话框;模态框会显示平台故障,并允许重试。已发布的默认组合为 `browse`,没有此依赖。 +- **尚无"显示隐藏目录"开关**:Host 打标隐藏条目、浏览器无条件过滤;该开关是延期的纯客户端改动。 diff --git a/packages/client/ui-workspace/package.json b/packages/client/ui-workspace/package.json index c36486d2fd..29d1ecfa36 100644 --- a/packages/client/ui-workspace/package.json +++ b/packages/client/ui-workspace/package.json @@ -25,6 +25,7 @@ "dshClient": { "inject": [ "@deepseek-ai/dsh-client-runtime", + "@deepseek-ai/dsh-client-locale", "@deepseek-ai/dsh-client-ui-conversation", "@deepseek-ai/dsh-client-ui-sidebar" ], @@ -39,6 +40,7 @@ "clsx": "^2.0.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", @@ -47,6 +49,7 @@ "react": "^18.2.0" }, "devDependencies": { + "@deepseek-ai/dsh-client-locale": "workspace:^", "@deepseek-ai/dsh-client-runtime": "workspace:^", "@deepseek-ai/dsh-client-ui-conversation": "workspace:^", "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", diff --git a/packages/client/ui-workspace/src/client/DirectoryBrowser.module.css b/packages/client/ui-workspace/src/client/DirectoryBrowser.module.css new file mode 100644 index 0000000000..b936148cd8 --- /dev/null +++ b/packages/client/ui-workspace/src/client/DirectoryBrowser.module.css @@ -0,0 +1,185 @@ +/* Directory-browser dialog (figma 802-56979). The shared Modal owns the mask, + * card, and title row; this module widens the card and rebuilds the figma + * header/footer separators with bleed margins inside the 24px content column. */ + +.dialog { + width: min(600px, 100%); +} + +/* Breadcrumb bar sits visually inside the header block: bleed to the card + * edges, close the header's 12px bottom pad, draw the l3 separator. */ +.crumbBar { + display: flex; + align-items: center; + gap: 4px; + min-height: 32px; + margin: -12px -24px 0; + padding: 0 24px 12px; + border-bottom: 1px solid var(--dsw-alias-border-l3); +} + +.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 1 0; + 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: 28px; + 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); +} + +/* One directory level: 28px rows, r6, folder icon + name + enter chevron. */ +.level { + display: flex; + flex-direction: column; + gap: 2px; + margin-top: -4px; + max-height: 320px; + overflow-y: auto; +} + +.row { + 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); +} + +.rowIcon { + flex: none; + color: var(--dsw-alias-label-secondary); +} + +.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); +} + +.folderRow { + cursor: default; +} + +.folderInput { + box-sizing: border-box; + flex: 1 1 0; + min-width: 0; + height: 24px; + padding: 0 6px; + border: 1px solid var(--dsw-alias-border-l2); + border-radius: 6px; + outline: none; + background: transparent; + font-size: 13px; + line-height: 20px; + color: var(--dsw-alias-label-primary); +} + +.folderInput::placeholder { + color: var(--dsw-alias-label-caption); +} + +.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: the l3 separator above the action row, New-folder pinned left + * (bleeds across the card; 12px stays below, matching the figma card pad). */ +.footerBar { + display: flex; + align-items: center; + gap: 8px; + width: calc(100% + 48px); + margin: 0 -24px -12px; + padding: 12px 24px; + border-top: 1px solid var(--dsw-alias-border-l3); +} + +.footerGap { + flex: 1 1 0; +} + +.footerAction { + min-width: 72px; +} diff --git a/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx b/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx new file mode 100644 index 0000000000..0301d9e27f --- /dev/null +++ b/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx @@ -0,0 +1,246 @@ +/** + * The in-app workspace-directory browser (figma Harness 802-56979): breadcrumb + * header with a click-to-edit path zone, one navigable directory level, an + * inline New-folder row, and the Cancel/Open footer. 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, 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). */ + listDirectory: (path?: string) => Promise + /** Create one child directory under the listed level. */ + createDirectory: (path: string, name: string) => Promise + /** The operator confirmed the currently listed directory. */ + onOpen: (path: string) => void + /** Close without picking (mask, Escape, Cancel). */ + onClose: () => void + /** The owner's confirm is in flight: Open disables, the level 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] +} + +/** + * 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) { + const [listing, setListing] = useState(null) + const [loading, setLoading] = useState(false) + const [error, setError] = useState(null) + // Path-edit state: null = breadcrumb mode; a string = the draft being typed. + const [pathDraft, setPathDraft] = useState(null) + // New-folder state: null = no inline row; a string = the name being typed. + const [folderDraft, setFolderDraft] = useState(null) + const [creatingFolder, setCreatingFolder] = useState(false) + const requestSeq = useRef(0) + + const navigate = useCallback((path?: string) => { + const seq = ++requestSeq.current + setLoading(true) + setError(null) + listDirectory(path).then((next) => { + if (seq !== requestSeq.current) return + setListing(next) + setLoading(false) + setPathDraft(null) + setFolderDraft(null) + }, (reason: unknown) => { + if (seq !== requestSeq.current) return + setLoading(false) + setError(failureText(reason)) + }) + }, [listDirectory]) + + // 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(() => { + if (open) { + setListing(null) + navigate() + return + } + requestSeq.current += 1 + setError(null) + setPathDraft(null) + setFolderDraft(null) + }, [open, navigate]) + + const confirmFolder = (): void => { + if (listing === null || folderDraft === null || creatingFolder) return + const name = folderDraft.trim() + if (name === '') return + setCreatingFolder(true) + setError(null) + createDirectory(listing.path, name).then(() => { + setCreatingFolder(false) + setFolderDraft(null) + navigate(listing.path) + }, (reason: unknown) => { + setCreatingFolder(false) + setError(failureText(reason)) + }) + } + + // After the hooks: a closed dialog renders nothing and evaluates no copy. + if (!open) return null + + const crumbs = listing === null ? [] : displayCrumbs(listing, t('browser.home')) + + return ( + + + + + +

+ )} + > +
+ {pathDraft === null + ? ( + <> + {crumbs.map((crumb, index) => ( + + {index > 0 && } + + + ))} + {/* The empty zone right of the crumbs is the path-edit affordance. */} +
+
+ {folderDraft !== null && listing !== null && ( +
+ + { setFolderDraft(event.target.value) }} + onKeyDown={(event) => { + if (event.key === 'Enter') { + event.preventDefault() + confirmFolder() + } + if (event.key === 'Escape') { + event.stopPropagation() + setFolderDraft(null) + } + }} + /> +
+ )} + {listing?.entries.filter(entry => !entry.hidden).map(entry => ( + + ))} + {loading &&
{t('browser.loading')}
} + {error !== null &&
{error}
} +
+ + ) +} diff --git a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx index ea1753a63e..f15c8090fe 100644 --- a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx +++ b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx @@ -253,7 +253,11 @@ export function WorkspaceBrowser({ deleteWorkspace, insertSessionBefore, createWorkspace, + directoryPickerKind, pickDirectory, + listDirectory, + createDirectory, + t, }: WorkspaceBrowserProps) { const workspaces = useWorkspaces(state => state.items) const groupBy = useStore(s => s.groupBy) @@ -371,7 +375,11 @@ export function WorkspaceBrowser({ anchorRef={wsPlusRef} useWorkspaces={useWorkspaces} createWorkspace={createWorkspace} + directoryPickerKind={directoryPickerKind} pickDirectory={pickDirectory} + listDirectory={listDirectory} + createDirectory={createDirectory} + t={t} onPick={(workspaceId) => { setWsPickerOpen(false) startSession(workspaceId) diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx index 4ec84c7d3d..fb7edd815a 100644 --- a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -5,24 +5,25 @@ * slot registration. */ import type { RefObject } from 'react' -import { useCallback, useState } from 'react' +import { useCallback, useEffect, useState } from 'react' import { Button, IconFolderClose16, IconPlusOutline16, Menu, Modal, type MenuEntry, } from '@deepseek-ai/dsh-client-ui-primitives' import { WorkspaceCreateError, - type WorkspaceId, type WorkspaceListState, type WorkspaceView, + type DirectoryPickerKind, type WorkspaceId, type WorkspaceListState, type WorkspaceView, } from '@deepseek-ai/dsh-client-runtime/client' -import type { WorkspacePickerProps } from './contract/slots.ts' +import type { DirectoryPickingInjected, WorkspacePickerProps } from './contract/slots.ts' +import { DirectoryBrowser } from './DirectoryBrowser.tsx' import css from './WorkspacePicker.module.css' const OPEN_LOCAL_FOLDER = '::open-local-folder' const CREATE_NEW = '::create-new' -type ModalKind = 'create' | 'folder-error' | null +type ModalKind = 'create' | 'folder-error' | 'browse' | null /** Core flow props: the owner supplies popover control and pick semantics. */ -export interface WorkspaceCreateFlowProps { +export interface WorkspaceCreateFlowProps extends DirectoryPickingInjected { /** Popover visibility (anchor button toggle state, owner-local). */ open: boolean /** The anchor button element — the popover's placement anchor. */ @@ -31,8 +32,6 @@ export interface WorkspaceCreateFlowProps { useWorkspaces: (selector: (state: WorkspaceListState) => S) => S /** Create or adopt a real Host Workspace. */ createWorkspace: (input: { name: string } | { path: string }) => Promise - /** Open the Host's native single-directory picker. */ - pickDirectory: () => Promise /** A real Workspace was picked or created. */ onPick: (workspaceId: WorkspaceId) => void /** Close the popover (outside click / Escape / post-pick). */ @@ -49,7 +48,11 @@ export function WorkspaceCreateFlow({ anchorRef, useWorkspaces, createWorkspace, + directoryPickerKind, pickDirectory, + listDirectory, + createDirectory, + t, onPick, onClose, }: WorkspaceCreateFlowProps) { @@ -65,6 +68,21 @@ export function WorkspaceCreateFlow({ const [modalError, setModalError] = useState(null) const [pickingFolder, setPickingFolder] = useState(false) const [folderConflict, setFolderConflict] = useState(false) + // The Host's picker interaction: read while the menu is open; 'unknown' + // (fetch failure or an unadvertised kind) hides the local-folder entry — + // the merge-extensible union's documented default. + const [pickerKind, setPickerKind] = useState(null) + useEffect(() => { + if (!open) return + let stale = false + directoryPickerKind().then( + // The wire type is the closed two-kind union today; a fetch failure is + // the reachable 'unknown' arm (an unadvertisable host hides the entry). + (kind) => { if (!stale) setPickerKind(kind) }, + () => { if (!stale) setPickerKind('unknown') }, + ) + return () => { stale = true } + }, [open, directoryPickerKind]) const normalizedWorkspaceName = workspaceName.trim() const duplicateWorkspaceName = !creating && normalizedWorkspaceName !== '' && workspaces.some(workspace => workspace.title === normalizedWorkspaceName) @@ -77,17 +95,40 @@ export function WorkspaceCreateFlow({ disabled: pickingFolder, })), ...(workspaces.length > 0 ? [{ type: 'separator' as const, id: 'sep-create' }] : []), - { id: OPEN_LOCAL_FOLDER, label: 'Open local folder…', icon: , disabled: pickingFolder }, + ...(pickerKind === 'unknown' ? [] : [ + { id: OPEN_LOCAL_FOLDER, label: 'Open local folder…', icon: , disabled: pickingFolder || pickerKind === null }, + ]), { id: CREATE_NEW, label: 'Create a new workspace', icon: , disabled: pickingFolder }, ] const closeModal = (): void => { - if (creating) return + if (creating || pickingFolder) return setModalKind(null) setModalError(null) } + /** Adopt a chosen directory as a Workspace; failures land in the folder-error dialog. */ + const adoptDirectory = (path: string): Promise => + createWorkspace({ path }).then((workspace) => { + setModalKind(null) + onPick(workspace.workspaceId) + }).catch((reason: unknown) => { + setFolderConflict( + reason instanceof WorkspaceCreateError + && reason.rpcError.code === 'workspace-name-conflict', + ) + setModalError(reason instanceof Error ? reason.message : String(reason)) + setModalKind('folder-error') + }) + const openLocalFolder = (): void => { + if (pickerKind === 'browse') { + onClose() + setModalError(null) + setFolderConflict(false) + setModalKind('browse') + return + } onClose() setModalKind(null) setModalError(null) @@ -95,13 +136,8 @@ export function WorkspaceCreateFlow({ setPickingFolder(true) void pickDirectory().then(async (path) => { if (path === null) return - const workspace = await createWorkspace({ path }) - onPick(workspace.workspaceId) + await adoptDirectory(path) }).catch((reason: unknown) => { - setFolderConflict( - reason instanceof WorkspaceCreateError - && reason.rpcError.code === 'workspace-name-conflict', - ) setModalError(reason instanceof Error ? reason.message : String(reason)) setModalKind('folder-error') }).finally(() => { setPickingFolder(false) }) @@ -155,6 +191,18 @@ export function WorkspaceCreateFlow({ getAnchorRect={getAnchorRect} /> {open && workspaceSnapshot.phase === 'pending' &&
Loading workspaces…
} + { + setPickingFolder(true) + void adoptDirectory(path).finally(() => { setPickingFolder(false) }) + }} + /> diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index fcdd0e304e..b604c3ece0 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -13,15 +13,38 @@ import type { PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' // runtime shares below. import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' -import type { SessionId, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' +import type { + DirectoryListing, DirectoryPickerKind, SessionId, WorkspaceId, WorkspaceView, +} from '@deepseek-ai/dsh-client-runtime/client' +import type { Translate } from '@deepseek-ai/dsh-client-locale/client' import type { createWorkspaceViewStore } from '../stores.ts' +/** + * Directory-picking share both registrations consume: the Host's composed + * picker interaction decides which calls the flow drives (`dialog` opens the + * native chooser through `pickDirectory`; `browse` drives the in-app browser + * through `listDirectory`/`createDirectory`; an unknown kind hides the + * local-folder entry — the merge-extensible union's documented default). + */ +export type DirectoryPickingInjected = { + /** The Host's advertised picker interaction, read per flow open. */ + directoryPickerKind: () => Promise + /** Ask the local Host to open its native single-directory picker (`dialog`). */ + pickDirectory: () => Promise + /** List one directory level with breadcrumb ancestry (`browse`). */ + listDirectory: (path?: string) => Promise + /** Create one child directory under an existing parent (`browse`). */ + createDirectory: (path: string, name: string) => Promise + /** Localized picker copy (this package's locale namespace). */ + t: Translate +} + /** * Browser-private injected share (arrives via the register inject factory). * Data reads use the global framework hooks; these are the Host actions the * browsing region drives. */ -export type WorkspaceBrowserInjected = { +export type WorkspaceBrowserInjected = DirectoryPickingInjected & { /** * Start a New Session in a Workspace: reuse-or-create its blank session * and open it; with no workspace, clear the selection into the New Session @@ -42,8 +65,6 @@ export type WorkspaceBrowserInjected = { insertSessionBefore: (workspaceId: WorkspaceId, sessionId: SessionId, beforeSessionId?: SessionId) => Promise /** Explicitly create or adopt a real Workspace before targeting a Session. */ createWorkspace: (input: { name: string } | { path: string }) => Promise - /** Ask the local Host to open its native single-directory picker. */ - pickDirectory: () => Promise } /** Full browser props: shell owner share + viewing store + injected actions. */ @@ -57,11 +78,9 @@ export type WorkspaceBrowserProps = * callback; this callback creates only the real Host Workspace. A type alias * supplies the implicit index signature required by the registry. */ -export type WorkspacePickerInjected = { +export type WorkspacePickerInjected = DirectoryPickingInjected & { /** Explicitly create or adopt a real Workspace before targeting a Session. */ createWorkspace: (input: { name: string } | { path: string }) => Promise - /** Ask the local Host to open its native single-directory picker. */ - pickDirectory: () => Promise } /** diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index f27448f926..4c400109f5 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -7,15 +7,19 @@ * packages/client/AGENTS.md. */ import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' -import type { WorkspaceBrowserInjected, WorkspacePickerInjected } from './contract/slots.ts' +import type { DirectoryPickingInjected, WorkspaceBrowserInjected, WorkspacePickerInjected } from './contract/slots.ts' import { createWorkspaceViewStore } from './stores.ts' import { WorkspaceBrowser } from './WorkspaceBrowser.tsx' import { WorkspacePicker } from './WorkspacePicker.tsx' export type { + DirectoryPickingInjected, WorkspaceBrowserInjected, WorkspaceBrowserProps, WorkspacePickerInjected, WorkspacePickerProps, } from './contract/slots.ts' +/** Locale namespace for the picker surfaces (dictionaries registered in apply). */ +const LOCALE_NS = 'workspace' + /** * Required services (cordis fiber inject). The target slots are declared by * the ui-sidebar / ui-conversation applies, whose activation order relative @@ -24,7 +28,7 @@ export type { * provides a waitable service. apply therefore registers via * declaration-aware deferral instead of assuming order. */ -export const inject = ['slots', 'sessions', 'workspaces'] +export const inject = ['slots', 'sessions', 'workspaces', 'locale'] /** * Register the browser and picker once their slot declarations are on the @@ -33,6 +37,39 @@ export const inject = ['slots', 'sessions', 'workspaces'] * @param ctx - client root context. */ export function apply(ctx: ClientContext): void { + ctx.effect(() => { + const disposers = [ + ctx.locale.register(LOCALE_NS, 'zh', { + 'browser.title': '选择工作区目录', + 'browser.home': '主目录', + 'browser.newFolder': '新建文件夹', + 'browser.folderName': '文件夹名称', + 'browser.cancel': '取消', + 'browser.open': '打开', + 'browser.editPath': '编辑路径', + 'browser.loading': '加载中…', + }), + ctx.locale.register(LOCALE_NS, 'en', { + 'browser.title': 'Select Workspace Directory', + 'browser.home': 'Home', + 'browser.newFolder': 'New folder', + 'browser.folderName': 'Folder name', + 'browser.cancel': 'Cancel', + 'browser.open': 'Open', + 'browser.editPath': 'Edit path', + 'browser.loading': 'Loading…', + }), + ] + return () => { for (const dispose of disposers) dispose() } + }, 'ui-workspace: picker dictionaries') + + const picking = (): DirectoryPickingInjected => ({ + directoryPickerKind: () => ctx.workspaces.directoryPickerKind(), + pickDirectory: () => ctx.workspaces.pickDirectory(), + listDirectory: path => ctx.workspaces.listDirectory(path), + createDirectory: (path, name) => ctx.workspaces.createDirectory(path, name), + t: ctx.locale.bind(LOCALE_NS), + }) const browserInjected = (): WorkspaceBrowserInjected => ({ // Explicit group actions keep their target; unscoped New Session rides // the runtime's shared action (recent-Workspace projection inside). @@ -44,11 +81,11 @@ export function apply(ctx: ClientContext): void { await ctx.workspaces.insertSessionBefore(workspaceId, sessionId, beforeSessionId) }, createWorkspace: input => ctx.workspaces.create(input), - pickDirectory: () => ctx.workspaces.pickDirectory(), + ...picking(), }) const pickerInjected = (): WorkspacePickerInjected => ({ createWorkspace: input => ctx.workspaces.create(input), - pickDirectory: () => ctx.workspaces.pickDirectory(), + ...picking(), }) // Declaration-aware registration: each owner's declaring apply may activate // after this one (entry activation order is unconstrained), and a register @@ -83,7 +120,17 @@ export function apply(ctx: ClientContext): void { const unsubscribers = registrations.map(entry => ctx.slots.subscribe(entry.name, () => { tryRegister(entry) })) for (const entry of registrations) tryRegister(entry) + // Language switch: re-register both entries so open surfaces re-render + // with the other dictionary (the bound t keeps a stable identity). + const offLocale = ctx.on('locale/change', () => { + for (const [name, dispose] of disposers) { + dispose() + disposers.delete(name) + } + for (const entry of registrations) tryRegister(entry) + }) return () => { + offLocale() for (const unsubscribe of unsubscribers) unsubscribe() for (const dispose of disposers.values()) dispose() } diff --git a/packages/client/ui-workspace/tests/apply.spec.ts b/packages/client/ui-workspace/tests/apply.spec.ts index 24434f22aa..9e29117916 100644 --- a/packages/client/ui-workspace/tests/apply.spec.ts +++ b/packages/client/ui-workspace/tests/apply.spec.ts @@ -15,16 +15,28 @@ async function bench() { title: 'new', sessionIds: [], createdAt: '0', updatedAt: '0', })) const pickDirectory = vi.fn(async () => '/tmp/picked') + const directoryPickerKind = vi.fn(async () => 'browse' as const) + const listDirectory = vi.fn(async () => ({ path: '/home/u', home: '/home/u', crumbs: [], entries: [] })) + const createDirectory = vi.fn(async () => '/home/u/new') const startSession = vi.fn() const rename = vi.fn(async () => ({})) const insertSessionBefore = vi.fn(async () => ({})) const open = vi.fn() const clear = vi.fn() ctx.provide('workspaces', { - create, pickDirectory, startSession, rename, insertSessionBefore, + create, pickDirectory, directoryPickerKind, listDirectory, createDirectory, + startSession, rename, insertSessionBefore, } as never) ctx.provide('sessions', { open, clear } as never) - return { ctx, slots: ctx.get('slots') as SlotsService, create, pickDirectory, startSession, rename, insertSessionBefore, open, clear } + // Structural locale fake: register/bind are the only members apply touches. + const localeRegister = vi.fn(() => () => {}) + const boundT = (key: string): string => key + ctx.provide('locale', { register: localeRegister, bind: () => boundT } as never) + return { + ctx, slots: ctx.get('slots') as SlotsService, create, pickDirectory, + directoryPickerKind, listDirectory, createDirectory, localeRegister, boundT, + startSession, rename, insertSessionBefore, open, clear, + } } type HoleName = 'sidebar.workspaces' | 'conversation.hero.workspace' | 'conversation.empty.workspace' @@ -37,7 +49,7 @@ function declare(slots: SlotsService, ...names: HoleName[]): () => void { describe('ui-workspace apply', () => { it('declares the services it drives', () => { - expect(inject).toEqual(['slots', 'sessions', 'workspaces']) + expect(inject).toEqual(['slots', 'sessions', 'workspaces', 'locale']) }) it('registers browser and pickers for declarations arriving before or after apply', async () => { diff --git a/packages/client/ui-workspace/tests/directory-browser.spec.tsx b/packages/client/ui-workspace/tests/directory-browser.spec.tsx new file mode 100644 index 0000000000..5b58f0667e --- /dev/null +++ b/packages/client/ui-workspace/tests/directory-browser.spec.tsx @@ -0,0 +1,160 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { cleanup, fireEvent, render, screen, waitFor } 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' + +/** 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 = { + [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: `${HOME}/Documents`, hidden: false }, + ], + }, + [`${HOME}/Documents`]: { + path: `${HOME}/Documents`, + home: HOME, + crumbs: [ + { name: '/', path: '/', hidden: false }, + { name: 'home', path: '/home', hidden: false }, + { name: 'u', path: HOME, hidden: false }, + { name: 'Documents', path: `${HOME}/Documents`, hidden: false }, + ], + entries: [{ name: 'harness', path: `${HOME}/Documents/harness`, hidden: 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[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) => key, + ...overrides, + } + const view = render() + return { view, props, listDirectory, createDirectory, onOpen, onClose } +} + +describe('DirectoryBrowser', () => { + it('opens at the Host home, 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(screen.getByRole('listitem').textContent).toBe('Documents') + expect(screen.queryByText('.config')).toBeNull() + // Inside the home subtree the chain collapses to a localized Home crumb. + expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() + expect(screen.queryByRole('button', { name: '/' })).toBeNull() + }) + + it('enters a row on click and jumps back through a crumb', async () => { + const b = mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('listitem')) + await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') }) + expect(b.listDirectory).toHaveBeenLastCalledWith(`${HOME}/Documents`) + fireEvent.click(screen.getByRole('button', { name: 'browser.home' })) + await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('Documents') }) + }) + + it('edits the path from the crumb bar: Enter navigates, Escape restores', async () => { + mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + const input = screen.getByLabelText('browser.editPath') + expect(input.value).toBe(HOME) + fireEvent.change(input, { target: { value: `${HOME}/Documents` } }) + fireEvent.keyDown(input, { key: 'Enter' }) + await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') }) + // Escape leaves an opened edit without navigating. + fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) + fireEvent.keyDown(screen.getByLabelText('browser.editPath'), { key: 'Escape' }) + expect(screen.queryByLabelText('browser.editPath', { selector: 'input' })).toBeNull() + expect(screen.getByRole('listitem').textContent).toBe('harness') + }) + + 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('creates a folder inline and refreshes the level; failures land as alerts', async () => { + const b = mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' })) + const input = screen.getByLabelText('browser.newFolder') + fireEvent.change(input, { target: { value: 'fresh' } }) + fireEvent.keyDown(input, { key: 'Enter' }) + await waitFor(() => { expect(b.createDirectory).toHaveBeenCalledWith(HOME, 'fresh') }) + // The level reloads after creation (initial + post-create). + await waitFor(() => { expect(b.listDirectory).toHaveBeenLastCalledWith(HOME) }) + + b.createDirectory.mockRejectedValueOnce( + new DirectoryBrowseError({ code: 'directory-exists', message: 'taken already', details: { path: `${HOME}/x` } })) + fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' })) + const retry = screen.getByLabelText('browser.newFolder') + fireEvent.change(retry, { target: { value: 'x' } }) + fireEvent.keyDown(retry, { key: 'Enter' }) + await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('taken already') }) + }) + + it('confirms the listed directory through Open, closes through Cancel, and freezes while busy', 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(screen.getByRole('button', { name: 'browser.cancel' })) + expect(b.onClose).toHaveBeenCalled() + + const busy = mount({ busy: true }) + await waitFor(() => { expect(busy.listDirectory).toHaveBeenCalled() }) + expect(screen.getAllByRole('button', { name: 'browser.open' }).at(-1)!.disabled).toBe(true) + }) + + it('starts back at home on reopen', async () => { + const b = mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('listitem')) + await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') }) + b.view.rerender() + b.view.rerender() + await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('Documents') }) + expect(b.listDirectory).toHaveBeenLastCalledWith(undefined) + }) +}) diff --git a/packages/client/ui-workspace/tests/workspace-browser.spec.tsx b/packages/client/ui-workspace/tests/workspace-browser.spec.tsx index 7b8462f6db..6919571052 100644 --- a/packages/client/ui-workspace/tests/workspace-browser.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-browser.spec.tsx @@ -59,7 +59,11 @@ function mount(overrides: Partial = {}) { deleteWorkspace: vi.fn(async () => {}), insertSessionBefore: vi.fn(async () => {}), createWorkspace: vi.fn(async () => workspace('created', [])), + directoryPickerKind: vi.fn(async () => 'dialog' as const), pickDirectory: vi.fn(async () => null), + listDirectory: vi.fn(async () => ({ path: '/home/u', home: '/home/u', crumbs: [], entries: [] })), + createDirectory: vi.fn(async () => '/home/u/new'), + t: (key: string) => key, ...overrides, } const view = render() diff --git a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx index 6cad175ff3..d400cf0435 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx @@ -5,6 +5,7 @@ import type { SessionListState, WorkspaceId, WorkspaceListState, WorkspaceView, } from '@deepseek-ai/dsh-client-runtime/client' import { WorkspaceCreateError } from '@deepseek-ai/dsh-client-runtime/client' +import type { DirectoryPickingInjected } from '../src/client/contract/slots.ts' import { WorkspacePicker } from '../src/client/WorkspacePicker.tsx' afterEach(cleanup) @@ -35,14 +36,34 @@ function anchor(): { current: HTMLElement } { return { current: element } } +/** Minimal picking share for direct renders (kind resolves to dialog). */ +function pickingShare(): DirectoryPickingInjected { + return { + directoryPickerKind: vi.fn(async () => 'dialog' as const), + pickDirectory: vi.fn(async () => null), + listDirectory: vi.fn(async () => ({ path: '/home/u', home: '/home/u', crumbs: [], entries: [] })), + createDirectory: vi.fn(async () => '/home/u/new'), + t: (key: string) => key, + } +} + function mount( items: readonly WorkspaceView[] = [workspace('alpha', 'Alpha')], createWorkspace = vi.fn(), pickDirectory = vi.fn(async () => null as string | null), + picking: Partial = {}, ) { const onPick = vi.fn() const onClose = vi.fn() const anchorRef = anchor() + const share: DirectoryPickingInjected = { + directoryPickerKind: vi.fn(async () => 'dialog' as const), + pickDirectory, + listDirectory: vi.fn(async () => ({ path: '/home/u', home: '/home/u', crumbs: [], entries: [] })), + createDirectory: vi.fn(async () => '/home/u/new'), + t: key => key, + ...picking, + } const renderPicker = (nextItems: readonly WorkspaceView[]) => ( ) const view = render( renderPicker(items), ) return { - view, onPick, onClose, createWorkspace, pickDirectory, + view, onPick, onClose, createWorkspace, pickDirectory, share, rerenderItems: (nextItems: readonly WorkspaceView[]) => { view.rerender(renderPicker(nextItems)) }, } } @@ -68,6 +89,16 @@ function chooseItem(name: 'Open local folder…' | 'Create a new workspace'): vo fireEvent.click(screen.getByRole('menuitem', { name })) } +/** The local-folder entry disables until the Host's picker kind resolves. */ +async function chooseLocalFolder(): Promise { + await waitFor(() => { + const item = screen.getByRole('menuitem', { name: 'Open local folder…' }) + expect(item).not.toHaveProperty('ariaDisabled', 'true') + expect(item.getAttribute('aria-disabled')).not.toBe('true') + }) + chooseItem('Open local folder…') +} + describe('WorkspacePicker', () => { it('lists real Workspaces from useWorkspaces and forwards a selected id', () => { const b = mount() @@ -92,7 +123,7 @@ describe('WorkspacePicker', () => { const createWorkspace = vi.fn(async () => created) const pickDirectory = vi.fn(async () => '/tmp/project') const b = mount([], createWorkspace, pickDirectory) - chooseItem('Open local folder…') + await chooseLocalFolder() expect(pickDirectory).toHaveBeenCalledOnce() await waitFor(() => { expect(createWorkspace).toHaveBeenCalledWith({ path: '/tmp/project' }) }) expect(createWorkspace).toHaveBeenCalledWith({ path: '/tmp/project' }) @@ -101,7 +132,7 @@ describe('WorkspacePicker', () => { it('treats native picker cancellation as a silent no-op', async () => { const b = mount([], vi.fn(), vi.fn(async () => null)) - chooseItem('Open local folder…') + await chooseLocalFolder() await waitFor(() => { expect(b.pickDirectory).toHaveBeenCalledOnce() }) expect(b.createWorkspace).not.toHaveBeenCalled() expect(b.onPick).not.toHaveBeenCalled() @@ -118,7 +149,7 @@ describe('WorkspacePicker', () => { }) }) const b = mount([], createWorkspace, pickDirectory) - chooseItem('Open local folder…') + await chooseLocalFolder() await waitFor(() => { expect(screen.getByRole('dialog', { name: 'A workspace with this name already exists' })).toBeTruthy() }) @@ -132,7 +163,7 @@ describe('WorkspacePicker', () => { let resolve!: (path: string | null) => void const pending = new Promise((settle) => { resolve = settle }) const b = mount([], vi.fn(), vi.fn(() => pending)) - chooseItem('Open local folder…') + await chooseLocalFolder() expect(screen.getByRole('menuitem', { name: 'Open local folder…' }).disabled).toBe(true) expect(screen.getByRole('menuitem', { name: 'Create a new workspace' }).disabled).toBe(true) fireEvent.click(screen.getByRole('menuitem', { name: 'Open local folder…' })) @@ -142,7 +173,7 @@ describe('WorkspacePicker', () => { it('reports non-Error native picker failures', async () => { const b = mount([], vi.fn(), vi.fn(async () => { throw 'picker unavailable' })) - chooseItem('Open local folder…') + await chooseLocalFolder() await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('picker unavailable') }) @@ -212,11 +243,58 @@ describe('WorkspacePicker', () => { expect(b.onPick).not.toHaveBeenCalled() }) + it('opens the in-app browser under the browse capability and adopts the confirmed directory', async () => { + const created = { ...workspace('adopted'), path: '/home/u', title: 'u' } + const createWorkspace = vi.fn(async () => created) + const b = mount([], createWorkspace, vi.fn(), { + directoryPickerKind: vi.fn(async () => 'browse' as const), + }) + await chooseLocalFolder() + await waitFor(() => { expect(screen.getByRole('dialog', { name: 'browser.title' })).toBeTruthy() }) + // The dialog listed home; Open adopts the listed directory. + await waitFor(() => { expect(b.share.listDirectory).toHaveBeenCalled() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.open' })) + await waitFor(() => { expect(createWorkspace).toHaveBeenCalledWith({ path: '/home/u' }) }) + await waitFor(() => { expect(b.onPick).toHaveBeenCalledWith(created.workspaceId) }) + expect(b.pickDirectory).not.toHaveBeenCalled() + expect(screen.queryByRole('dialog')).toBeNull() + }) + + it('routes an adoption conflict from the browser into the folder-error dialog, and Choose again reopens the browser', async () => { + const createWorkspace = vi.fn(async () => { + throw new WorkspaceCreateError({ + code: 'workspace-name-conflict', message: 'u already exists', details: { name: 'u' }, + }) + }) + const b = mount([], createWorkspace, vi.fn(), { + directoryPickerKind: vi.fn(async () => 'browse' as const), + }) + await chooseLocalFolder() + await waitFor(() => { expect(screen.getByRole('dialog', { name: 'browser.title' })).toBeTruthy() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.open' })) + await waitFor(() => { + expect(screen.getByRole('dialog', { name: 'A workspace with this name already exists' })).toBeTruthy() + }) + fireEvent.click(screen.getByRole('button', { name: 'Choose again' })) + await waitFor(() => { expect(screen.getByRole('dialog', { name: 'browser.title' })).toBeTruthy() }) + expect(b.onPick).not.toHaveBeenCalled() + }) + + it('hides the local-folder entry when the picker kind is unknown', async () => { + mount([], vi.fn(), vi.fn(), { + directoryPickerKind: vi.fn(async () => { throw new Error('unreachable host') }), + }) + await waitFor(() => { + expect(screen.queryByRole('menuitem', { name: 'Open local folder…' })).toBeNull() + }) + expect(screen.getByRole('menuitem', { name: 'Create a new workspace' })).toBeTruthy() + }) + it('waits to show its menu until an optional anchor is available', () => { render( , ) expect(screen.queryByRole('menu')).toBeNull() @@ -229,7 +307,7 @@ describe('WorkspacePicker', () => { render( , ) expect(screen.getByRole('status').textContent).toBe('Loading workspaces…') diff --git a/packages/client/ui-workspace/tsconfig.json b/packages/client/ui-workspace/tsconfig.json index a2679cccb4..76babb3fea 100644 --- a/packages/client/ui-workspace/tsconfig.json +++ b/packages/client/ui-workspace/tsconfig.json @@ -8,6 +8,9 @@ "src" ], "references": [ + { + "path": "../locale" + }, { "path": "../../../vendor/cordis" }, diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a47a1ea140..b3a1b5fa9f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -212,9 +212,9 @@ importers: '@deepseek-ai/dsh-host-apiproxy': specifier: workspace:^ version: link:../../packages/host/apiproxy - '@deepseek-ai/dsh-host-directory-picker-dialog': + '@deepseek-ai/dsh-host-directory-picker-browse': specifier: workspace:^ - version: link:../../packages/host/directory-picker-dialog + version: link:../../packages/host/directory-picker-browse '@deepseek-ai/dsh-host-webserver': specifier: workspace:^ version: link:../../packages/host/webserver @@ -1391,6 +1391,9 @@ importers: specifier: ^2.0.0 version: 2.1.1 devDependencies: + '@deepseek-ai/dsh-client-locale': + specifier: workspace:^ + version: link:../locale '@deepseek-ai/dsh-client-runtime': specifier: workspace:^ version: link:../runtime From 2b64341bc0d7553c87dbbf5c39d92a6b3eee9f6d Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 17:33:19 +0800 Subject: [PATCH 14/93] fix(web): align the directory browser with the figma frame and merge the seam tip MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The dialog now owns the figma structure through a new headless Modal mode (mask/card/Escape stay shared): header block with the title and crumbs 8px apart above the l3 separator (no close chrome — the figma frame has none), 16px to the level, and the 12px card bottom. The picker-kind narrowing returns for the merged open describe kind — an unrecognized advertised kind hides the local-folder entry, now covered alongside the stale-navigation failure arm and the unmount races. --- docs/module-graph.md | 11 +- packages/client/ui-primitives/src/Modal.tsx | 38 +++-- .../src/client/DirectoryBrowser.module.css | 52 ++++--- .../src/client/DirectoryBrowser.tsx | 143 +++++++++--------- .../src/client/WorkspacePicker.tsx | 7 +- .../tests/directory-browser.spec.tsx | 82 ++++++++++ .../tests/workspace-picker.spec.tsx | 52 +++++++ 7 files changed, 276 insertions(+), 109 deletions(-) diff --git a/docs/module-graph.md b/docs/module-graph.md index 03f4bee072..31217705ba 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -292,10 +292,6 @@ flowchart TD pkg_client_ui_slash --> pkg_client_runtime pkg_client_ui_slash --> pkg_client_ui_slots pkg_client_ui_slash --> pkg_invariants - pkg_client_ui_workspace --> pkg_client_runtime - pkg_client_ui_workspace --> pkg_client_ui_primitives - pkg_client_ui_workspace --> pkg_client_ui_slots - pkg_client_ui_workspace --> pkg_invariants pkg_helper --> pkg_brand pkg_helper --> pkg_invariants pkg_helper --> pkg_subprocess @@ -350,6 +346,11 @@ flowchart TD pkg_client_ui_theme --> pkg_client_ui_primitives pkg_client_ui_theme --> pkg_client_ui_slots pkg_client_ui_theme --> pkg_invariants + pkg_client_ui_workspace --> pkg_client_locale + pkg_client_ui_workspace --> pkg_client_runtime + pkg_client_ui_workspace --> pkg_client_ui_primitives + pkg_client_ui_workspace --> pkg_client_ui_slots + pkg_client_ui_workspace --> pkg_invariants pkg_lsp --> pkg_brand pkg_lsp --> pkg_invariants pkg_lsp --> pkg_llm @@ -944,7 +945,6 @@ flowchart TD | [`client-ui-settings`](../packages/client/ui-settings) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-sidebar`](../packages/client/ui-sidebar) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-slash`](../packages/client/ui-slash) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | -| [`client-ui-workspace`](../packages/client/ui-workspace) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`helper`](../packages/sdk/helper) | `sdk` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`subprocess`](../packages/subprocess/subprocess) | | [`telemetry`](../packages/sdk/telemetry) | `sdk` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`invariants`](../packages/support/invariants), [`storage`](../packages/storage/storage) | @@ -961,6 +961,7 @@ flowchart TD | [`client-ui-skill`](../packages/client/ui-skill) | `client` | [`client-connection`](../packages/client/connection), [`client-runtime`](../packages/client/runtime), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-subagent`](../packages/client/ui-subagent) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-theme`](../packages/client/ui-theme) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | +| [`client-ui-workspace`](../packages/client/ui-workspace) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm) | | [`sandbox`](../packages/sandbox/sandbox) | `sandbox` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm) | | [`token-meter`](../packages/llm/token-meter) | `llm` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | diff --git a/packages/client/ui-primitives/src/Modal.tsx b/packages/client/ui-primitives/src/Modal.tsx index 820ff3d7a3..ef790c8b6a 100644 --- a/packages/client/ui-primitives/src/Modal.tsx +++ b/packages/client/ui-primitives/src/Modal.tsx @@ -12,13 +12,16 @@ import css from './Modal.module.css' * Render a centered modal over a blurred page mask. * @param props.open - whether the dialog is showing. * @param props.onClose - Escape or mask click. - * @param props.title - dialog heading. + * @param props.title - dialog heading (aria-label in every mode). * @param props.description - optional supporting sentence under the title. * @param props.children - body (inputs, etc.). * @param props.footer - action row (Cancel / Create). + * @param props.headless - render children directly in the card (no default + * header/close/body chrome) for dialogs whose figma frame owns its own + * header structure; mask, card, Escape, and aria-label remain. * @returns null when closed; otherwise the overlay tree. */ -export function Modal({ open, onClose, title, description, children, footer, className }: { +export function Modal({ open, onClose, title, description, children, footer, className, headless = false }: { open: boolean onClose: () => void title: string @@ -26,6 +29,7 @@ export function Modal({ open, onClose, title, description, children, footer, cla children?: ReactNode footer?: ReactNode className?: string + headless?: boolean }) { useEffect(() => { if (!open) return @@ -47,19 +51,25 @@ export function Modal({ open, onClose, title, description, children, footer, cla aria-modal="true" aria-label={title} > -
-
-

{title}

- -
- {description !== undefined && description !== '' && ( -

{description}

+ {headless + ? children + : ( + <> +
+
+

{title}

+ +
+ {description !== undefined && description !== '' && ( +

{description}

+ )} + {children !== undefined &&
{children}
} +
+ {footer !== undefined &&
{footer}
} + )} - {children !== undefined &&
{children}
} -
- {footer !== undefined &&
{footer}
} ) diff --git a/packages/client/ui-workspace/src/client/DirectoryBrowser.module.css b/packages/client/ui-workspace/src/client/DirectoryBrowser.module.css index b936148cd8..14f3e4f2ca 100644 --- a/packages/client/ui-workspace/src/client/DirectoryBrowser.module.css +++ b/packages/client/ui-workspace/src/client/DirectoryBrowser.module.css @@ -1,21 +1,40 @@ -/* Directory-browser dialog (figma 802-56979). The shared Modal owns the mask, - * card, and title row; this module widens the card and rebuilds the figma - * header/footer separators with bleed margins inside the 24px content column. */ +/* Directory-browser dialog (figma 802-56979). The shared Modal renders + * headless here — mask, card, Escape only — and this module owns the figma + * frame exactly: header (title + crumbs, l3 separator), one directory level, + * and the bordered footer. Card: w600 r24, bottom pad 12, no close chrome. */ -.dialog { +/* Doubled class beats Modal's own .dialog regardless of stylesheet order. */ +.dialog.dialog { width: min(600px, 100%); + padding: 0 0 12px; + gap: 16px; +} + +/* Header block: pl24 pr14 pt22 pb12, 8px between title row and crumb row. */ +.header { + display: flex; + flex-direction: column; + gap: 8px; + 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); } -/* Breadcrumb bar sits visually inside the header block: bleed to the card - * edges, close the header's 12px bottom pad, draw the l3 separator. */ .crumbBar { display: flex; align-items: center; gap: 4px; - min-height: 32px; - margin: -12px -24px 0; - padding: 0 24px 12px; - border-bottom: 1px solid var(--dsw-alias-border-l3); + min-height: 20px; } .crumbSeat { @@ -65,7 +84,7 @@ box-sizing: border-box; flex: 1 1 0; min-width: 0; - height: 28px; + height: 24px; padding: 0 8px; border: 1px solid var(--dsw-alias-border-l2); border-radius: 8px; @@ -76,12 +95,12 @@ color: var(--dsw-alias-label-primary); } -/* One directory level: 28px rows, r6, folder icon + name + enter chevron. */ +/* One directory level: content column pt16 px24, 28px rows with 2px gaps. */ .level { display: flex; flex-direction: column; gap: 2px; - margin-top: -4px; + padding: 16px 24px 0; max-height: 320px; overflow-y: auto; } @@ -164,15 +183,12 @@ color: var(--dsw-alias-state-error-primary); } -/* Footer: the l3 separator above the action row, New-folder pinned left - * (bleeds across the card; 12px stays below, matching the figma card pad). */ +/* Footer: l3 separator on top, pt12 px24, New-folder pinned left. */ .footerBar { display: flex; align-items: center; gap: 8px; - width: calc(100% + 48px); - margin: 0 -24px -12px; - padding: 12px 24px; + padding: 12px 24px 0; border-top: 1px solid var(--dsw-alias-border-l3); } diff --git a/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx b/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx index 0301d9e27f..9454693969 100644 --- a/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx +++ b/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx @@ -100,6 +100,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, }, [open, navigate]) const confirmFolder = (): void => { + /* v8 ignore next -- reentry fence: the inline row only renders with a listing and a draft, and the input disables while creating. */ if (listing === null || folderDraft === null || creatingFolder) return const name = folderDraft.trim() if (name === '') return @@ -126,78 +127,61 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, onClose={onClose} title={t('browser.title')} className={clsx(css.dialog)} - footer={( -
- - - - -
- )} + headless > -
- {pathDraft === null - ? ( - <> - {crumbs.map((crumb, index) => ( - - {index > 0 && } - - - ))} - {/* The empty zone right of the crumbs is the path-edit affordance. */} - + + ))} + {/* The empty zone right of the crumbs is the path-edit affordance. */} +
{folderDraft !== null && listing !== null && ( @@ -241,6 +225,27 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, {loading &&
{t('browser.loading')}
} {error !== null &&
{error}
}
+
+ + + + +
) } diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx index fb7edd815a..3cacbe44b7 100644 --- a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -76,9 +76,10 @@ export function WorkspaceCreateFlow({ if (!open) return let stale = false directoryPickerKind().then( - // The wire type is the closed two-kind union today; a fetch failure is - // the reachable 'unknown' arm (an unadvertisable host hides the entry). - (kind) => { if (!stale) setPickerKind(kind) }, + // The wire kind is an open string (a merge-added capability advertises + // before this client knows it): anything but the two known kinds hides + // the entry, as does a fetch failure. + (kind) => { if (!stale) setPickerKind(kind === 'dialog' || kind === 'browse' ? kind : 'unknown') }, () => { if (!stale) setPickerKind('unknown') }, ) return () => { stale = true } diff --git a/packages/client/ui-workspace/tests/directory-browser.spec.tsx b/packages/client/ui-workspace/tests/directory-browser.spec.tsx index 5b58f0667e..a78527d5f1 100644 --- a/packages/client/ui-workspace/tests/directory-browser.spec.tsx +++ b/packages/client/ui-workspace/tests/directory-browser.spec.tsx @@ -147,6 +147,88 @@ describe('DirectoryBrowser', () => { expect(screen.getAllByRole('button', { name: 'browser.open' }).at(-1)!.disabled).toBe(true) }) + it('renders the full ancestry when the listing 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: [], + } + 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('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() + 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('cancels the inline folder row with Escape and ignores a blank name', async () => { + const b = mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' })) + const input = screen.getByLabelText('browser.newFolder') + fireEvent.change(input, { target: { value: ' ' } }) + fireEvent.keyDown(input, { key: 'Enter' }) + expect(b.createDirectory).not.toHaveBeenCalled() + fireEvent.keyDown(input, { key: 'Escape' }) + expect(screen.queryByLabelText('browser.newFolder')).toBeNull() + }) + + it('ignores a blank path draft on Enter', async () => { + const b = 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: ' ' } }) + fireEvent.keyDown(input, { key: 'Enter' }) + // Only the initial home listing ran; the blank draft navigated nowhere. + expect(b.listDirectory).toHaveBeenCalledTimes(1) + }) + + it('drops a stale listing that resolves after a newer navigation', async () => { + const b = mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + // The next navigation (into Documents) hangs; a Home-crumb jump supersedes it. + let resolveSlow!: (value: DirectoryListing) => void + const slow = new Promise((settle) => { resolveSlow = settle }) + b.listDirectory.mockReturnValueOnce(slow) + fireEvent.click(screen.getByRole('listitem')) + fireEvent.click(screen.getByRole('button', { name: 'browser.home' })) + await waitFor(() => { expect(b.listDirectory).toHaveBeenCalledTimes(3) }) + await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('Documents') }) + resolveSlow(listingFor(`${HOME}/Documents`)) + await new Promise(settle => setTimeout(settle, 0)) + // The stale Documents listing did not clobber the newer Home level. + expect(screen.getByRole('listitem').textContent).toBe('Documents') + }) + + 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((_settle, fail) => { rejectSlow = fail }) + b.listDirectory.mockReturnValueOnce(slow) + fireEvent.click(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)) + // The superseded failure surfaces no alert over the newer level. + expect(screen.queryByRole('alert')).toBeNull() + expect(screen.getByRole('listitem').textContent).toBe('Documents') + }) + it('starts back at home on reopen', async () => { const b = mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) diff --git a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx index d400cf0435..0c634fbd60 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx @@ -280,6 +280,58 @@ describe('WorkspacePicker', () => { expect(b.onPick).not.toHaveBeenCalled() }) + it('drops a picker-kind failure that lands after unmount', async () => { + let rejectKind!: (reason: unknown) => void + const pending = new Promise<'dialog'>((_settle, fail) => { rejectKind = fail }) + const b = mount([], vi.fn(), vi.fn(), { directoryPickerKind: vi.fn(() => pending) }) + b.view.unmount() + await act(async () => { + rejectKind(new Error('gone')) + await pending.catch(() => {}) + }) + expect(b.onPick).not.toHaveBeenCalled() + }) + + it('drops a picker-kind resolution that lands after unmount', async () => { + let resolveKind!: (kind: 'dialog') => void + const pending = new Promise<'dialog'>((settle) => { resolveKind = settle }) + const b = mount([], vi.fn(), vi.fn(), { directoryPickerKind: vi.fn(() => pending) }) + b.view.unmount() + await act(async () => { + resolveKind('dialog') + await pending + }) + expect(b.onPick).not.toHaveBeenCalled() + }) + + it('reports a browse adoption failure thrown as a plain string', async () => { + const b = mount([], vi.fn(async () => { throw 'disk detached' }), vi.fn(), { + directoryPickerKind: vi.fn(async () => 'browse' as const), + }) + await chooseLocalFolder() + await waitFor(() => { expect(screen.getByRole('dialog', { name: 'browser.title' })).toBeTruthy() }) + fireEvent.click(screen.getByRole('button', { name: 'browser.open' })) + await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('disk detached') }) + expect(b.onPick).not.toHaveBeenCalled() + }) + + it('reports a native picker Error by its message', async () => { + const b = mount([], vi.fn(), vi.fn(async () => { throw new Error('no chooser installed') })) + await chooseLocalFolder() + await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('no chooser installed') }) + expect(b.createWorkspace).not.toHaveBeenCalled() + }) + + it('hides the local-folder entry for an unrecognized advertised kind', async () => { + mount([], vi.fn(), vi.fn(), { + directoryPickerKind: vi.fn(async () => 'electron-native'), + }) + await waitFor(() => { + expect(screen.queryByRole('menuitem', { name: 'Open local folder…' })).toBeNull() + }) + expect(screen.getByRole('menuitem', { name: 'Create a new workspace' })).toBeTruthy() + }) + it('hides the local-folder entry when the picker kind is unknown', async () => { mount([], vi.fn(), vi.fn(), { directoryPickerKind: vi.fn(async () => { throw new Error('unreachable host') }), From cd7aa3c7d879d1d65df1dafc3ad2a5688f2252f2 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 17:39:15 +0800 Subject: [PATCH 15/93] fix(host,client): gate the picker affordance on the advertised kind; reject non-absolute browse paths MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ds-review-bot round 2. The workspace UI never consulted the advertised directoryPicker kind: under a browse (or merge-added) backend it still rendered 'Open local folder…' and called pickDirectory(), which the host answers with directory-picker-unavailable. The create flow now reads directoryPickerKind() per menu open and renders the dialog affordance only under 'dialog' — browse (until its in-app browser UI lands) and unknown kinds hide the entry, realizing the seam's documented default; a keyless workspace-flow snapshot pins the hidden entry over the browse fixture. The browse backend also resolved wire paths, silently rebasing '' or relative parents under the host process cwd; both primitives now reject non-absolute explicit paths with their business codes, and the seam JSDoc carries the contract. --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 2 +- ...-28-directory-picker-capability-seam.zh.md | 2 +- apps/web/tests/workspace-flow.snapshot.ts | 14 ++++ packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 2 +- packages/client/ui-workspace/README.zh.md | 2 +- .../src/client/WorkspaceBrowser.tsx | 2 + .../src/client/WorkspacePicker.tsx | 29 +++++++- .../ui-workspace/src/client/contract/slots.ts | 6 +- .../client/ui-workspace/src/client/index.ts | 2 + .../client/ui-workspace/tests/apply.spec.ts | 9 ++- .../tests/workspace-browser.spec.tsx | 1 + .../tests/workspace-picker.spec.tsx | 66 ++++++++++++++----- .../directory-picker-browse/README.i18n.yaml | 4 +- .../host/directory-picker-browse/README.md | 2 +- .../host/directory-picker-browse/README.zh.md | 2 +- .../host/directory-picker-browse/src/index.ts | 11 +++- .../tests/service.spec.ts | 13 ++++ packages/host/directory-picker/src/index.ts | 6 +- 20 files changed, 146 insertions(+), 37 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml index ccef0728d9..c13d5e7a1c 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml @@ -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 .agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md -2026-07-28-directory-picker-capability-seam.md: 8d9d34e7aed4525b243380a4a90801fe59bfc213 -2026-07-28-directory-picker-capability-seam.zh.md: 282f3905c3551912915088f70247260310f442cb +2026-07-28-directory-picker-capability-seam.md: a30675f2d84b6ae68b95ab96df9e32106d6fbf5d +2026-07-28-directory-picker-capability-seam.zh.md: 5560aba07424d7307e386e2e8ae6b724486d6068 diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md index 8d9d34e7ae..a30675f2d8 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md @@ -30,7 +30,7 @@ Placement and policy rulings folded into this decision: ## Consequences -- `cordis.yml` chooses the interaction; `apps/cli` currently mounts `-dialog` (unchanged behavior), and the in-app browser PR flips the default to `-browse` with the GUI branching on `describe`. +- `cordis.yml` chooses the interaction; `apps/cli` currently mounts `-dialog` (unchanged behavior). The GUI already gates its dialog affordance on `describe.directoryPicker` (non-`dialog` kinds hide it); the in-app browser PR flips the default to `-browse` and adds the browse UI. - The wire gains `host.listDirectory`/`host.createDirectory`, four error codes, and the `describe.directoryPicker` field; the connection fixture serves a deterministic browse tree for keyless assembled tests. - A future interaction (or an Electron `dialog` provider) is one backend package plus a client branch — no gateway surgery. - `ApiProxyDefaults.pickDirectory` (test-only injection) is gone; tests provide a stub `ctx.directoryPicker` like any other service. diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md index 282f3905c3..5560aba074 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md @@ -30,7 +30,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick ## 后果 -- `cordis.yml` 决定交互形态;`apps/cli` 当前挂 `-dialog`(行为不变),应用内浏览器 PR 将把默认翻到 `-browse` 并让 GUI 按 `describe` 分支。 +- `cordis.yml` 决定交互形态;`apps/cli` 当前挂 `-dialog`(行为不变)。GUI 已按 `describe.directoryPicker` 门控其对话框入口(非 `dialog` kind 一律隐藏);应用内浏览器 PR 将把默认翻到 `-browse` 并补上浏览 UI。 - 协议新增 `host.listDirectory`/`host.createDirectory`、四个错误码与 `describe.directoryPicker` 字段;connection fixture 提供确定性浏览树供无密钥组装测试使用。 - 未来的新交互(或 Electron 的 `dialog` 提供方)只是一个后端包加一个客户端分支——无需网关手术。 - `ApiProxyDefaults.pickDirectory`(仅测试注入)删除;测试像提供其他服务一样提供 stub `ctx.directoryPicker`。 diff --git a/apps/web/tests/workspace-flow.snapshot.ts b/apps/web/tests/workspace-flow.snapshot.ts index e1fe183ef1..715be624e0 100644 --- a/apps/web/tests/workspace-flow.snapshot.ts +++ b/apps/web/tests/workspace-flow.snapshot.ts @@ -174,6 +174,20 @@ it('locks the composer in the New Session view state until a Workspace is chosen `) }) +it('hides the Open-local-folder entry under the fixture host\'s browse picker capability', async () => { + boot('?fixture=empty') + + await findLockedComposer() + fireEvent.click(workspaceChip()) + const menu = await screen.findByRole('menu') + // Flush the advertised-kind read (fixture describe resolves in microtasks): + // the fixture serves `browse`, whose in-app UI is not wired yet, so the + // dialog affordance must not render — only the create action remains. + await act(async () => {}) + expect(within(menu).getAllByRole('menuitem').map(item => visibleText(item))) + .toEqual(['Create a new workspace']) +}) + it('selects the recent Workspace and opens its blank Session on first load', async () => { boot('?fixture') diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 0d78a8d648..35cd3c3702 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -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/client/ui-workspace/README.md -README.md: edd6c2f9373d97832def86bb44658d7c1c68dae9 -README.zh.md: f7b73dde953d4294d4d157f479fe932adf1a29c4 +README.md: 58aaf56e1953f00417492d766d8f4ae4a0081c81 +README.zh.md: 7c7b33e0ea68fefee8f857cb5e67a36ec5a854f5 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index edd6c2f937..58aaf56e19 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) Shared Workspace picker plugin. `WorkspaceBrowser` is registered into the sidebar's `sidebar.workspaces` slot and `WorkspacePicker` into the page-local Session Intent hero's `conversation.hero.workspace` slot, so both surfaces use the same menu and creation flow. -The picker lists real Host Workspace entities through the global `useWorkspaces` hook. Selecting a Workspace invokes the slot owner's `onPick` callback to retarget the frontend Session object. The flat **Open local folder...** action delegates to the Host's native single-directory picker, adopts a returned path through the object layer, and selects the committed Workspace only after its list projection has refreshed; cancellation is silent, and errors remain retryable. **Create a new workspace** retains the name dialog and disables names already present in that list, while the Host remains authoritative for concurrent or non-UI callers. The runtime Session and Workspace services own materialization. The Workspace row's Delete action opens a confirmation that states the retention boundary, blocks duplicate submission, and keeps failures open; success removes the group while its Sessions remain under Ungrouped. +The picker lists real Host Workspace entities through the global `useWorkspaces` hook. Selecting a Workspace invokes the slot owner's `onPick` callback to retarget the frontend Session object. The flat **Open local folder...** action renders only when the Host advertises the `dialog` picker interaction (read per flow open through `host.describe`); `browse` — until its in-app browser UI lands — and unknown kinds hide the entry, the seam's documented default. When shown, it delegates to the Host's native single-directory picker, adopts a returned path through the object layer, and selects the committed Workspace only after its list projection has refreshed; cancellation is silent, and errors remain retryable. **Create a new workspace** retains the name dialog and disables names already present in that list, while the Host remains authoritative for concurrent or non-UI callers. The runtime Session and Workspace services own materialization. The Workspace row's Delete action opens a confirmation that states the retention boundary, blocks duplicate submission, and keeps failures open; success removes the group while its Sessions remain under Ungrouped. Both target slots are declared by other plugins, so `apply` registers through declaration-aware deferral and re-registers after a declaring slot is restored. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index f7b73dde95..7c7b33e0ea 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -4,7 +4,7 @@ 共享 Workspace 选择器插件。`WorkspaceBrowser` 注册到侧边栏的 `sidebar.workspaces` slot,`WorkspacePicker` 注册到页面局部 Session Intent 主视觉区的 `conversation.hero.workspace` slot,因此两个表层使用同一菜单和创建流程。 -该选择器通过全局 `useWorkspaces` hook 列出真实的 Host Workspace 实体。选择 Workspace 会调用 slot owner 的 `onPick` 回调,重新定位前端 Session 对象。平铺显示的 **打开本地文件夹…** 操作会委托 Host 的原生单目录选择器,通过对象层接纳返回的路径,并等待 Workspace 列表投影刷新后才选中已提交的 Workspace;取消操作不会显示提示,发生错误后仍可重试。**创建新工作区** 操作保留名称对话框,并禁用列表中已有的名称,而 Host 对并发或非 UI 调用方仍具有最终决定权。运行时 Session 与 Workspace 服务负责物化。Workspace 行内的 Delete 操作会打开确认框,说明保留边界、阻止重复提交,并在失败时保持打开;成功后,该分组会被移除,其 Session 则留在 Ungrouped 下。 +该选择器通过全局 `useWorkspaces` hook 列出真实的 Host Workspace 实体。选择 Workspace 会调用 slot owner 的 `onPick` 回调,重新定位前端 Session 对象。平铺显示的 **打开本地文件夹…** 操作仅在 Host 广播 `dialog` 选择交互时渲染(每次流程打开时通过 `host.describe` 读取);`browse`(在其应用内浏览器 UI 落地之前)以及未知 kind 都会隐藏该入口,即 seam 文档化的默认行为。显示时它会委托 Host 的原生单目录选择器,通过对象层接纳返回的路径,并等待 Workspace 列表投影刷新后才选中已提交的 Workspace;取消操作不会显示提示,发生错误后仍可重试。**创建新工作区** 操作保留名称对话框,并禁用列表中已有的名称,而 Host 对并发或非 UI 调用方仍具有最终决定权。运行时 Session 与 Workspace 服务负责物化。Workspace 行内的 Delete 操作会打开确认框,说明保留边界、阻止重复提交,并在失败时保持打开;成功后,该分组会被移除,其 Session 则留在 Ungrouped 下。 两个目标 slot 都由其他插件声明,因此 `apply` 通过声明感知的延迟机制完成注册,并在声明该 slot 的插件恢复后重新注册。 diff --git a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx index ea1753a63e..bf3a41522e 100644 --- a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx +++ b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx @@ -254,6 +254,7 @@ export function WorkspaceBrowser({ insertSessionBefore, createWorkspace, pickDirectory, + directoryPickerKind, }: WorkspaceBrowserProps) { const workspaces = useWorkspaces(state => state.items) const groupBy = useStore(s => s.groupBy) @@ -372,6 +373,7 @@ export function WorkspaceBrowser({ useWorkspaces={useWorkspaces} createWorkspace={createWorkspace} pickDirectory={pickDirectory} + directoryPickerKind={directoryPickerKind} onPick={(workspaceId) => { setWsPickerOpen(false) startSession(workspaceId) diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx index 4ec84c7d3d..8cef0af8f9 100644 --- a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -5,13 +5,13 @@ * slot registration. */ import type { RefObject } from 'react' -import { useCallback, useState } from 'react' +import { useCallback, useEffect, useState } from 'react' import { Button, IconFolderClose16, IconPlusOutline16, Menu, Modal, type MenuEntry, } from '@deepseek-ai/dsh-client-ui-primitives' import { WorkspaceCreateError, - type WorkspaceId, type WorkspaceListState, type WorkspaceView, + type DirectoryPickerKind, type WorkspaceId, type WorkspaceListState, type WorkspaceView, } from '@deepseek-ai/dsh-client-runtime/client' import type { WorkspacePickerProps } from './contract/slots.ts' import css from './WorkspacePicker.module.css' @@ -33,6 +33,8 @@ export interface WorkspaceCreateFlowProps { createWorkspace: (input: { name: string } | { path: string }) => Promise /** Open the Host's native single-directory picker. */ pickDirectory: () => Promise + /** The Host's advertised picker interaction (read per flow open); gates which picking affordance renders. */ + directoryPickerKind: () => Promise /** A real Workspace was picked or created. */ onPick: (workspaceId: WorkspaceId) => void /** Close the popover (outside click / Escape / post-pick). */ @@ -50,6 +52,7 @@ export function WorkspaceCreateFlow({ useWorkspaces, createWorkspace, pickDirectory, + directoryPickerKind, onPick, onClose, }: WorkspaceCreateFlowProps) { @@ -69,6 +72,22 @@ export function WorkspaceCreateFlow({ const duplicateWorkspaceName = !creating && normalizedWorkspaceName !== '' && workspaces.some(workspace => workspace.title === normalizedWorkspaceName) + // The advertised interaction gates the picking affordance: 'dialog' is the + // only kind pickDirectory() can serve, so its entry renders under that kind + // alone; 'browse' (until the in-app browser UI lands) and unknown kinds + // hide the entry, the seam's documented unknown-kind default. Re-read per + // flow open — no cache to go stale across reconnects. + const [dialogPicker, setDialogPicker] = useState(false) + useEffect(() => { + if (!open) return + void directoryPickerKind() + .then((kind) => { setDialogPicker(kind === 'dialog') }) + // A failed describe hides the entry too: the same Host that cannot + // answer describe cannot serve pickDirectory. (Post-unmount settlement + // is safe: React 18 no-ops setState on unmounted components.) + .catch(() => { setDialogPicker(false) }) + }, [open, directoryPickerKind]) + const items: MenuEntry[] = [ ...workspaces.map(workspace => ({ id: workspace.workspaceId, @@ -77,7 +96,9 @@ export function WorkspaceCreateFlow({ disabled: pickingFolder, })), ...(workspaces.length > 0 ? [{ type: 'separator' as const, id: 'sep-create' }] : []), - { id: OPEN_LOCAL_FOLDER, label: 'Open local folder…', icon: , disabled: pickingFolder }, + ...(dialogPicker + ? [{ id: OPEN_LOCAL_FOLDER, label: 'Open local folder…', icon: , disabled: pickingFolder }] + : []), { id: CREATE_NEW, label: 'Create a new workspace', icon: , disabled: pickingFolder }, ] @@ -229,6 +250,7 @@ export function WorkspacePicker({ onClose, createWorkspace, pickDirectory, + directoryPickerKind, }: WorkspacePickerProps) { return ( diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index fcdd0e304e..c20955b567 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -13,7 +13,7 @@ import type { PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' // runtime shares below. import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' -import type { SessionId, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' +import type { DirectoryPickerKind, SessionId, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' import type { createWorkspaceViewStore } from '../stores.ts' /** @@ -44,6 +44,8 @@ export type WorkspaceBrowserInjected = { createWorkspace: (input: { name: string } | { path: string }) => Promise /** Ask the local Host to open its native single-directory picker. */ pickDirectory: () => Promise + /** The Host's advertised picker interaction (read per flow open); gates which picking affordance renders. */ + directoryPickerKind: () => Promise } /** Full browser props: shell owner share + viewing store + injected actions. */ @@ -62,6 +64,8 @@ export type WorkspacePickerInjected = { createWorkspace: (input: { name: string } | { path: string }) => Promise /** Ask the local Host to open its native single-directory picker. */ pickDirectory: () => Promise + /** The Host's advertised picker interaction (read per flow open); gates which picking affordance renders. */ + directoryPickerKind: () => Promise } /** diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index f27448f926..6b84680fbc 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -45,10 +45,12 @@ export function apply(ctx: ClientContext): void { }, createWorkspace: input => ctx.workspaces.create(input), pickDirectory: () => ctx.workspaces.pickDirectory(), + directoryPickerKind: () => ctx.workspaces.directoryPickerKind(), }) const pickerInjected = (): WorkspacePickerInjected => ({ createWorkspace: input => ctx.workspaces.create(input), pickDirectory: () => ctx.workspaces.pickDirectory(), + directoryPickerKind: () => ctx.workspaces.directoryPickerKind(), }) // Declaration-aware registration: each owner's declaring apply may activate // after this one (entry activation order is unconstrained), and a register diff --git a/packages/client/ui-workspace/tests/apply.spec.ts b/packages/client/ui-workspace/tests/apply.spec.ts index 24434f22aa..f9a5884206 100644 --- a/packages/client/ui-workspace/tests/apply.spec.ts +++ b/packages/client/ui-workspace/tests/apply.spec.ts @@ -15,16 +15,17 @@ async function bench() { title: 'new', sessionIds: [], createdAt: '0', updatedAt: '0', })) const pickDirectory = vi.fn(async () => '/tmp/picked') + const directoryPickerKind = vi.fn(async () => 'dialog' as const) const startSession = vi.fn() const rename = vi.fn(async () => ({})) const insertSessionBefore = vi.fn(async () => ({})) const open = vi.fn() const clear = vi.fn() ctx.provide('workspaces', { - create, pickDirectory, startSession, rename, insertSessionBefore, + create, pickDirectory, directoryPickerKind, startSession, rename, insertSessionBefore, } as never) ctx.provide('sessions', { open, clear } as never) - return { ctx, slots: ctx.get('slots') as SlotsService, create, pickDirectory, startSession, rename, insertSessionBefore, open, clear } + return { ctx, slots: ctx.get('slots') as SlotsService, create, pickDirectory, directoryPickerKind, startSession, rename, insertSessionBefore, open, clear } } type HoleName = 'sidebar.workspaces' | 'conversation.hero.workspace' | 'conversation.empty.workspace' @@ -75,12 +76,16 @@ describe('ui-workspace apply', () => { expect(b.create).toHaveBeenCalledWith({ name: 'project' }) await browser.pickDirectory() expect(b.pickDirectory).toHaveBeenCalledOnce() + await browser.directoryPickerKind() + expect(b.directoryPickerKind).toHaveBeenCalledOnce() const picker = (b.slots.entries('conversation.hero.workspace')[0]!.inject as () => WorkspacePickerInjected)() await picker.createWorkspace({ path: '/tmp/project' }) expect(b.create).toHaveBeenCalledWith({ path: '/tmp/project' }) await picker.pickDirectory() expect(b.pickDirectory).toHaveBeenCalledTimes(2) + await picker.directoryPickerKind() + expect(b.directoryPickerKind).toHaveBeenCalledTimes(2) }) it('unregisters every entry on teardown', async () => { diff --git a/packages/client/ui-workspace/tests/workspace-browser.spec.tsx b/packages/client/ui-workspace/tests/workspace-browser.spec.tsx index 7b8462f6db..779ad0b37a 100644 --- a/packages/client/ui-workspace/tests/workspace-browser.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-browser.spec.tsx @@ -60,6 +60,7 @@ function mount(overrides: Partial = {}) { insertSessionBefore: vi.fn(async () => {}), createWorkspace: vi.fn(async () => workspace('created', [])), pickDirectory: vi.fn(async () => null), + directoryPickerKind: vi.fn(async () => 'dialog' as const), ...overrides, } const view = render() diff --git a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx index 6cad175ff3..c7f8fd9765 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx @@ -39,6 +39,7 @@ function mount( items: readonly WorkspaceView[] = [workspace('alpha', 'Alpha')], createWorkspace = vi.fn(), pickDirectory = vi.fn(async () => null as string | null), + directoryPickerKind = vi.fn(async () => 'dialog'), ) { const onPick = vi.fn() const onClose = vi.fn() @@ -53,19 +54,22 @@ function mount( onClose={onClose} createWorkspace={createWorkspace} pickDirectory={pickDirectory} + directoryPickerKind={directoryPickerKind} /> ) const view = render( renderPicker(items), ) return { - view, onPick, onClose, createWorkspace, pickDirectory, + view, onPick, onClose, createWorkspace, pickDirectory, directoryPickerKind, rerenderItems: (nextItems: readonly WorkspaceView[]) => { view.rerender(renderPicker(nextItems)) }, } } -function chooseItem(name: 'Open local folder…' | 'Create a new workspace'): void { - fireEvent.click(screen.getByRole('menuitem', { name })) +// findByRole, not getByRole: the folder entry renders only after the advertised +// picker kind resolves, one microtask after the menu opens. +async function chooseItem(name: 'Open local folder…' | 'Create a new workspace'): Promise { + fireEvent.click(await screen.findByRole('menuitem', { name })) } describe('WorkspacePicker', () => { @@ -79,7 +83,7 @@ describe('WorkspacePicker', () => { const created = workspace('new', 'New') const createWorkspace = vi.fn(async () => created) const b = mount([], createWorkspace) - chooseItem('Create a new workspace') + await chooseItem('Create a new workspace') const input = screen.getByLabelText('New workspace name') fireEvent.change(input, { target: { value: 'project-one' } }) fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) @@ -92,7 +96,7 @@ describe('WorkspacePicker', () => { const createWorkspace = vi.fn(async () => created) const pickDirectory = vi.fn(async () => '/tmp/project') const b = mount([], createWorkspace, pickDirectory) - chooseItem('Open local folder…') + await chooseItem('Open local folder…') expect(pickDirectory).toHaveBeenCalledOnce() await waitFor(() => { expect(createWorkspace).toHaveBeenCalledWith({ path: '/tmp/project' }) }) expect(createWorkspace).toHaveBeenCalledWith({ path: '/tmp/project' }) @@ -101,7 +105,7 @@ describe('WorkspacePicker', () => { it('treats native picker cancellation as a silent no-op', async () => { const b = mount([], vi.fn(), vi.fn(async () => null)) - chooseItem('Open local folder…') + await chooseItem('Open local folder…') await waitFor(() => { expect(b.pickDirectory).toHaveBeenCalledOnce() }) expect(b.createWorkspace).not.toHaveBeenCalled() expect(b.onPick).not.toHaveBeenCalled() @@ -118,7 +122,7 @@ describe('WorkspacePicker', () => { }) }) const b = mount([], createWorkspace, pickDirectory) - chooseItem('Open local folder…') + await chooseItem('Open local folder…') await waitFor(() => { expect(screen.getByRole('dialog', { name: 'A workspace with this name already exists' })).toBeTruthy() }) @@ -132,7 +136,7 @@ describe('WorkspacePicker', () => { let resolve!: (path: string | null) => void const pending = new Promise((settle) => { resolve = settle }) const b = mount([], vi.fn(), vi.fn(() => pending)) - chooseItem('Open local folder…') + await chooseItem('Open local folder…') expect(screen.getByRole('menuitem', { name: 'Open local folder…' }).disabled).toBe(true) expect(screen.getByRole('menuitem', { name: 'Create a new workspace' }).disabled).toBe(true) fireEvent.click(screen.getByRole('menuitem', { name: 'Open local folder…' })) @@ -142,23 +146,23 @@ describe('WorkspacePicker', () => { it('reports non-Error native picker failures', async () => { const b = mount([], vi.fn(), vi.fn(async () => { throw 'picker unavailable' })) - chooseItem('Open local folder…') + await chooseItem('Open local folder…') await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('picker unavailable') }) expect(b.createWorkspace).not.toHaveBeenCalled() }) - it('closes a creation modal when the user cancels', () => { + it('closes a creation modal when the user cancels', async () => { mount([]) - chooseItem('Create a new workspace') + await chooseItem('Create a new workspace') fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) expect(screen.queryByRole('dialog')).toBeNull() }) - it('blocks a create-new name already present in the Workspace list', () => { + it('blocks a create-new name already present in the Workspace list', async () => { const b = mount([workspace('alpha', 'Alpha')]) - chooseItem('Create a new workspace') + await chooseItem('Create a new workspace') fireEvent.change(screen.getByLabelText('New workspace name'), { target: { value: ' Alpha ' } }) expect(screen.getByRole('alert').textContent).toBe('A workspace named “Alpha” already exists.') expect(screen.getByRole('button', { name: 'Create workspace' }).disabled).toBe(true) @@ -171,7 +175,7 @@ describe('WorkspacePicker', () => { const pending = new Promise((settle) => { resolve = settle }) const created = workspace('fresh', 'same-name') const b = mount([], vi.fn(() => pending)) - chooseItem('Create a new workspace') + await chooseItem('Create a new workspace') fireEvent.change(screen.getByLabelText('New workspace name'), { target: { value: 'same-name' } }) fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) @@ -187,7 +191,7 @@ describe('WorkspacePicker', () => { const pending = new Promise((_resolve, rejectPromise) => { reject = rejectPromise }) const createWorkspace = vi.fn(() => pending) const b = mount([], createWorkspace) - chooseItem('Create a new workspace') + await chooseItem('Create a new workspace') const input = screen.getByLabelText('New workspace name') fireEvent.keyDown(input, { key: 'ArrowRight' }) fireEvent.change(input, { target: { value: 'broken' } }) @@ -204,7 +208,7 @@ describe('WorkspacePicker', () => { it('reports non-Error creation failures', async () => { const b = mount([], vi.fn(async () => { throw 'permission denied' })) - chooseItem('Create a new workspace') + await chooseItem('Create a new workspace') fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('Workspace creation failed: permission denied') @@ -217,6 +221,7 @@ describe('WorkspacePicker', () => { 'dialog')} />, ) expect(screen.queryByRole('menu')).toBeNull() @@ -230,8 +235,37 @@ describe('WorkspacePicker', () => { 'dialog')} />, ) expect(screen.getByRole('status').textContent).toBe('Loading workspaces…') }) + + it('hides the folder affordance unless the Host advertises the dialog interaction', async () => { + const b = mount([], vi.fn(), vi.fn(async () => null), vi.fn(async () => 'browse')) + await screen.findByRole('menuitem', { name: 'Create a new workspace' }) + await waitFor(() => { expect(b.directoryPickerKind).toHaveBeenCalled() }) + expect(screen.queryByRole('menuitem', { name: 'Open local folder…' })).toBeNull() + }) + + it('hides the folder affordance when the Host cannot answer describe', async () => { + const b = mount([], vi.fn(), vi.fn(async () => null), vi.fn(async () => { + throw new Error('host unreachable') + })) + await screen.findByRole('menuitem', { name: 'Create a new workspace' }) + await waitFor(() => { expect(b.directoryPickerKind).toHaveBeenCalled() }) + expect(screen.queryByRole('menuitem', { name: 'Open local folder…' })).toBeNull() + }) + + it('does not read the picker kind while the flow is closed', () => { + const directoryPickerKind = vi.fn(async () => 'dialog') + render( + , + ) + expect(directoryPickerKind).not.toHaveBeenCalled() + }) }) diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index fea6c71d41..916db3c321 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/directory-picker-browse/README.md -README.md: f86f74acf4922d490b23c033a281436f1a428f13 -README.zh.md: 0d240630a8b21003c5285bc75e93aac9adf36d92 +README.md: 81357269e1d4b075f7e31b5f3ac5d4721811024a +README.zh.md: 06a7f7651b2abc0aa73eba41042f3d1a86661b76 diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index f86f74acf4..81357269e1 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) The **in-app browsing backend** of the [directory-picker seam](../directory-picker/README.md): `BrowseDirectoryPicker` registers `ctx.directoryPicker` with the `browse` capability — one-level directory listing and child-directory creation over Node's stdlib, which already carries the per-OS adaptation. Nothing renders on the host display, so this backend serves remote clients the dialog 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. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). +Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject a non-absolute explicit path (`directory-unreadable`/`directory-create-failed`) instead of letting `resolve` rebase it under the host process cwd. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). ## Model Experience diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index 0d240630a8..06a7f7651b 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -4,7 +4,7 @@ [目录选择 seam](../directory-picker/README.md) 的**应用内浏览后端**:`BrowseDirectoryPicker` 以 `browse` 能力注册 `ctx.directoryPicker`——基于 Node 标准库(跨 OS 适配本就由它承担)提供单层目录列举与子目录创建。宿主屏幕上不渲染任何东西,因此该后端能服务 dialog 后端无法触及的远程客户端。 -行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 +行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非绝对的显式路径(`directory-unreadable`/`directory-create-failed`),而不是任由 `resolve` 把它重定位到宿主进程 cwd 之下。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 ## 模型体验 diff --git a/packages/host/directory-picker-browse/src/index.ts b/packages/host/directory-picker-browse/src/index.ts index 5f2a9429c0..83a3f6762e 100644 --- a/packages/host/directory-picker-browse/src/index.ts +++ b/packages/host/directory-picker-browse/src/index.ts @@ -11,7 +11,7 @@ import { mkdir, readdir, stat } from 'node:fs/promises' import { homedir } from 'node:os' -import { basename, dirname, join, resolve } from 'node:path' +import { basename, dirname, isAbsolute, join, resolve } from 'node:path' import { DirectoryPicker, DirectoryPickerError, } from '@deepseek-ai/dsh-host-directory-picker' @@ -81,6 +81,11 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { private async list(path?: string): Promise { const home = homedir() + // The seam contract takes absolute paths only; resolve() would silently + // rebase a relative or empty wire value under the host process cwd. + if (path !== undefined && !isAbsolute(path)) { + throw new DirectoryPickerError('directory-unreadable', path, `cannot list "${path}": not an absolute path`) + } const target = resolve(path ?? home) let names: { name: string; isDirectory: boolean; isSymbolicLink: boolean }[] try { @@ -100,6 +105,10 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { } private async createDirectory(path: string, name: string): Promise { + // Same absolute-path fence as list: never rebase a parent under the cwd. + if (!isAbsolute(path)) { + throw new DirectoryPickerError('directory-create-failed', path, `cannot create under "${path}": not an absolute 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). diff --git a/packages/host/directory-picker-browse/tests/service.spec.ts b/packages/host/directory-picker-browse/tests/service.spec.ts index 3833395c11..608fe89348 100644 --- a/packages/host/directory-picker-browse/tests/service.spec.ts +++ b/packages/host/directory-picker-browse/tests/service.spec.ts @@ -70,6 +70,19 @@ describe('BrowseDirectoryPicker', () => { expect((failure as DirectoryPickerError).path).toBe(missing) }) + 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')) diff --git a/packages/host/directory-picker/src/index.ts b/packages/host/directory-picker/src/index.ts index 5a6040e51f..322dc4551c 100644 --- a/packages/host/directory-picker/src/index.ts +++ b/packages/host/directory-picker/src/index.ts @@ -60,7 +60,8 @@ export interface DirectoryPickerBrowseCapability { * List one directory level. * @param path - absolute directory to list; absent lists the home directory. * @returns the level's listing with ancestry. - * @throws {DirectoryPickerError} `directory-unreadable` when the target cannot be listed. + * @throws {DirectoryPickerError} `directory-unreadable` when the target is not absolute + * (a wire value must never rebase under the host cwd) or cannot be listed. */ list(path?: string): Promise /** @@ -68,7 +69,8 @@ export interface DirectoryPickerBrowseCapability { * @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` otherwise. + * @throws {DirectoryPickerError} `directory-exists` for an existing child, + * `directory-create-failed` for a non-absolute parent or any other failure. */ createDirectory(path: string, name: string): Promise } From f43cfb24065506b9c74603088c84fc4b667ea728 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 17:47:56 +0800 Subject: [PATCH 16/93] =?UTF-8?q?fix(cli):=20sample=20LAN=20addresses=20on?= =?UTF-8?q?ce=20=E2=80=94=20trust=20and=20the=20printed=20LAN=20URL=20shar?= =?UTF-8?q?e=20the=20snapshot?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit web.ts re-sampled interfaces after boot, so an address change during entry.run() could advertise a LAN URL absent from the trustedHosts snapshot composePatches captured, answering 403 on arrival. resolveLanTrust now returns the single sample and AppCLIEntry exposes it for display. --- apps/cli/src/app-cli-entry.ts | 42 ++++++++++++++++++---------- apps/cli/src/web.ts | 6 ++-- apps/cli/tests/trusted-hosts.spec.ts | 31 ++++++++------------ 3 files changed, 43 insertions(+), 36 deletions(-) diff --git a/apps/cli/src/app-cli-entry.ts b/apps/cli/src/app-cli-entry.ts index 1002b45660..acc4482018 100644 --- a/apps/cli/src/app-cli-entry.ts +++ b/apps/cli/src/app-cli-entry.ts @@ -34,28 +34,31 @@ export const ALL_INTERFACES_HOST = '0.0.0.0' * authorities an all-interfaces bind is reachable by on the LAN. * @returns the addresses in interface order (possibly empty). */ -export function lanIPv4Addresses(): string[] { +function lanIPv4Addresses(): string[] { return Object.values(networkInterfaces()).flat() .filter((iface): iface is NonNullable => iface !== undefined && iface.family === 'IPv4' && !iface.internal) .map(iface => iface.address) } /** - * Authorities the /api browser-trust fence must accept for one invocation: - * the machine's LAN IP literals when the effective bind is all-interfaces - * (advertised by the printed LAN URL, so they must not answer 403), followed - * by the explicit extras. Derived entries are port-less IP literals — DNS - * rebinding needs an attacker-controlled name, so an IP-literal Host is safe - * on any port, and the bound port may be OS-assigned, unknowable pre-boot. + * One LAN-trust resolution for one invocation, sampled exactly once: the + * machine's LAN IP literals when the effective bind is all-interfaces, and + * the `trustedHosts` value built from them plus the explicit extras. The + * single sample is deliberate — display must advertise only addresses the + * fence was configured with, so both read this snapshot. Derived entries are + * port-less IP literals: DNS rebinding needs an attacker-controlled name, so + * an IP-literal Host is safe on any port, and the bound port may be + * OS-assigned, unknowable pre-boot. * @param bindHost - the effective webserver bind host (CLI flag, else the yml default). * @param extra - `--trusted-host` values, in argv order. - * @returns the connection row's `trustedHosts` value (possibly empty). + * @returns the sampled LAN addresses and the connection row's `trustedHosts` value (each possibly empty). */ -export function resolveTrustedHosts(bindHost: string | undefined, extra: readonly string[]): string[] { - return [ - ...bindHost === ALL_INTERFACES_HOST ? lanIPv4Addresses() : [], - ...extra, - ] +export function resolveLanTrust( + bindHost: string | undefined, + extra: readonly string[], +): { lanAddresses: string[]; trustedHosts: string[] } { + const lanAddresses = bindHost === ALL_INTERFACES_HOST ? lanIPv4Addresses() : [] + return { lanAddresses, trustedHosts: [...lanAddresses, ...extra] } } /** One profile-json key mapped onto a yml row's config field. */ @@ -126,6 +129,14 @@ export class AppCLIEntry { /** The root context, set by {@link run}. */ ctx!: Context + /** + * LAN IPv4 addresses sampled once at patch composition — the exact snapshot + * the /api trust fence was configured with. Display reads this instead of + * re-sampling, so the advertised LAN URL can never name an address the + * fence rejects. Empty unless the effective bind is all-interfaces. + */ + lanAddresses: readonly string[] = [] + private patches: PatchOptions[] = [] constructor(private readonly options: AppCLIEntryOptions) {} @@ -188,9 +199,10 @@ export class AppCLIEntry { if (this.options.workspaceRoot !== undefined) put('api-gateway', 'workspaceRoot', this.options.workspaceRoot) // Source 2b: authorities for the /api browser-trust fence (rationale on - // resolveTrustedHosts). + // resolveLanTrust). const ymlHost = (rows.get('webserver')?.config as { host?: string } | undefined)?.host - const trustedHosts = resolveTrustedHosts(this.options.host ?? ymlHost, this.options.trustedHosts ?? []) + const { lanAddresses, trustedHosts } = resolveLanTrust(this.options.host ?? ymlHost, this.options.trustedHosts ?? []) + this.lanAddresses = lanAddresses if (trustedHosts.length > 0) put('connection', 'trustedHosts', trustedHosts) // Source 3: the frontend dist — an assembly fact of this app, never yml diff --git a/apps/cli/src/web.ts b/apps/cli/src/web.ts index 3d7fc29ab4..69e79ab5d9 100644 --- a/apps/cli/src/web.ts +++ b/apps/cli/src/web.ts @@ -7,7 +7,7 @@ */ import { fileURLToPath } from 'node:url' -import { ALL_INTERFACES_HOST, AppCLIEntry, lanIPv4Addresses } from './app-cli-entry.ts' +import { AppCLIEntry } from './app-cli-entry.ts' const CONFIG_PATH = fileURLToPath(new URL('../cordis.yml', import.meta.url)) @@ -48,7 +48,9 @@ export async function runWeb( void Promise.resolve(ctx.fiber.dispose()).finally(() => { process.exit(code) }) } - const lanCandidate = host === ALL_INTERFACES_HOST ? lanIPv4Addresses()[0] : undefined + // The entry's boot-time snapshot, not a fresh sample: the printed LAN URL + // must name an address the /api trust fence was configured with. + const lanCandidate = entry.lanAddresses[0] const localUrl = `http://${LOOPBACK_HOST}:${boundPort}` console.log(`dsh web: ${localUrl}${lanCandidate === undefined ? '' : ` (LAN: http://${lanCandidate}:${boundPort})`}`) diff --git a/apps/cli/tests/trusted-hosts.spec.ts b/apps/cli/tests/trusted-hosts.spec.ts index 1ed0f602b8..571a9f76b7 100644 --- a/apps/cli/tests/trusted-hosts.spec.ts +++ b/apps/cli/tests/trusted-hosts.spec.ts @@ -1,7 +1,7 @@ -/** LAN-authority derivation for the /api browser-trust fence (`resolveTrustedHosts`). */ +/** Single-sample LAN-trust resolution for the /api browser-trust fence (`resolveLanTrust`). */ -import { afterEach, describe, expect, it, vi } from 'vitest' -import { lanIPv4Addresses, resolveTrustedHosts } from '../src/app-cli-entry.ts' +import { describe, expect, it, vi } from 'vitest' +import { resolveLanTrust } from '../src/app-cli-entry.ts' vi.mock('node:os', () => ({ networkInterfaces: () => ({ @@ -19,22 +19,15 @@ vi.mock('node:os', () => ({ }), })) -afterEach(() => { vi.restoreAllMocks() }) +describe('resolveLanTrust', () => { + it('samples non-internal IPv4 addresses once for an all-interfaces bind: trust and display share them', () => { + const { lanAddresses, trustedHosts } = resolveLanTrust('0.0.0.0', ['harness.internal:3080']) + expect(lanAddresses).toEqual(['192.168.1.5', '10.0.0.7']) + expect(trustedHosts).toEqual(['192.168.1.5', '10.0.0.7', 'harness.internal:3080']) + }) -describe('lanIPv4Addresses', () => { - it('returns only non-internal IPv4 addresses, in interface order', () => { - expect(lanIPv4Addresses()).toEqual(['192.168.1.5', '10.0.0.7']) - }) -}) - -describe('resolveTrustedHosts', () => { - it('derives port-less LAN IP literals for an all-interfaces bind, ahead of the extras', () => { - expect(resolveTrustedHosts('0.0.0.0', ['harness.internal:3080'])) - .toEqual(['192.168.1.5', '10.0.0.7', 'harness.internal:3080']) - }) - - it('derives nothing for a loopback or unresolved bind — extras alone stand', () => { - expect(resolveTrustedHosts('127.0.0.1', [])).toEqual([]) - expect(resolveTrustedHosts(undefined, ['lab.internal'])).toEqual(['lab.internal']) + it('derives nothing for a loopback or unresolved bind — extras alone stand, no LAN URL to print', () => { + expect(resolveLanTrust('127.0.0.1', [])).toEqual({ lanAddresses: [], trustedHosts: [] }) + expect(resolveLanTrust(undefined, ['lab.internal'])).toEqual({ lanAddresses: [], trustedHosts: ['lab.internal'] }) }) }) From c4bf919895ebe92a691fe50b3b5d3cc0d619c35f Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 17:56:03 +0800 Subject: [PATCH 17/93] fix(host,client): default-export the picker seam; invalidate stale kind reads ds-review-bot round 3. The seam package broke the service-package export contract (named export only), so the config catalog filed it under Other libraries and default imports failed; it now default-exports DirectoryPicker like every abstract seam, and the regenerated catalog lists it as one. The picker-kind effect also let a settlement from a superseded flow open leak into the current one (close/reopen mid-describe, or a reconnect that swaps the backend): the read now resets the affordance on every open and a cleanup-toggled flag discards obsolete settlements, both directions pinned by jsdom races. --- docs/config-catalog.md | 2 +- docs/cordis-catalog/services.md | 2 +- .../src/client/WorkspacePicker.tsx | 14 ++++-- .../tests/workspace-picker.spec.tsx | 46 +++++++++++++++++++ packages/host/directory-picker/src/index.ts | 2 + 5 files changed, 60 insertions(+), 6 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index f9b4e9f8bf..0697f56dfe 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2211,6 +2211,7 @@ Abstract service classes — a deployment loads a concrete implementation packag - `@deepseek-ai/dsh-code-runtime` — abstract `CodeRuntime` ([`packages/code-runtime/code-runtime/src/index.ts`](../packages/code-runtime/code-runtime/src/index.ts)) - `@deepseek-ai/dsh-compact` — abstract `CompactService` ([`packages/compact/compact/src/index.ts`](../packages/compact/compact/src/index.ts)) - `@deepseek-ai/dsh-fs` — abstract `FileSystem` ([`packages/fs/fs/src/index.ts`](../packages/fs/fs/src/index.ts)) +- `@deepseek-ai/dsh-host-directory-picker` — abstract `DirectoryPicker` ([`packages/host/directory-picker/src/index.ts`](../packages/host/directory-picker/src/index.ts)) - `@deepseek-ai/dsh-sandbox` — abstract `SandboxProvider` ([`packages/sandbox/sandbox/src/index.ts`](../packages/sandbox/sandbox/src/index.ts)) - `@deepseek-ai/dsh-session-persistence` — abstract `SessionPersistence` ([`packages/session-persistence/session-persistence/src/index.ts`](../packages/session-persistence/session-persistence/src/index.ts)) - `@deepseek-ai/dsh-session-query` — abstract `SessionQueryService` ([`packages/session-query/session-query/src/index.ts`](../packages/session-query/session-query/src/index.ts)) @@ -2234,7 +2235,6 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them. - `@deepseek-ai/dsh-client-web-react` ([`packages/client/web-react/src/index.ts`](../packages/client/web-react/src/index.ts)) - `@deepseek-ai/dsh-helper` ([`packages/sdk/helper/src/index.ts`](../packages/sdk/helper/src/index.ts)) - `@deepseek-ai/dsh-hook-protocol` ([`packages/hooks/hook-protocol/src/index.ts`](../packages/hooks/hook-protocol/src/index.ts)) -- `@deepseek-ai/dsh-host-directory-picker` ([`packages/host/directory-picker/src/index.ts`](../packages/host/directory-picker/src/index.ts)) - `@deepseek-ai/dsh-jsonrpc-demo` ([`packages/examples/jsonrpc-demo/src/index.ts`](../packages/examples/jsonrpc-demo/src/index.ts)) - `@deepseek-ai/dsh-llm-mock-server` ([`packages/support/llm-mock-server/src/index.ts`](../packages/support/llm-mock-server/src/index.ts)) - `@deepseek-ai/dsh-loader-smoke` ([`packages/support/loader-smoke/src/index.ts`](../packages/support/loader-smoke/src/index.ts)) diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 397e7320d5..3b47e405f0 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -481,7 +481,7 @@ Abstract directory-picking service. Subclass, implement `capability()`, and load abstract capability(): DirectoryPickerCapability ``` -Source: [`packages/host/directory-picker/src/index.ts:118`](../../packages/host/directory-picker/src/index.ts) +Source: [`packages/host/directory-picker/src/index.ts:120`](../../packages/host/directory-picker/src/index.ts) ## `ctx.fs` — `FileSystem` (abstract seam) diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx index 8cef0af8f9..2e65fc6b72 100644 --- a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -80,12 +80,18 @@ export function WorkspaceCreateFlow({ const [dialogPicker, setDialogPicker] = useState(false) useEffect(() => { if (!open) return + // Reset before each read: a reconnect can change the composed backend, so + // a previous open's answer must not leak into this one; and a settlement + // from a superseded open (flow closed, or a newer read started) is + // discarded via the cleanup-toggled flag. + setDialogPicker(false) + let stale = false void directoryPickerKind() - .then((kind) => { setDialogPicker(kind === 'dialog') }) + .then((kind) => { if (!stale) setDialogPicker(kind === 'dialog') }) // A failed describe hides the entry too: the same Host that cannot - // answer describe cannot serve pickDirectory. (Post-unmount settlement - // is safe: React 18 no-ops setState on unmounted components.) - .catch(() => { setDialogPicker(false) }) + // answer describe cannot serve pickDirectory. + .catch(() => { if (!stale) setDialogPicker(false) }) + return () => { stale = true } }, [open, directoryPickerKind]) const items: MenuEntry[] = [ diff --git a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx index c7f8fd9765..9ca5304fa4 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx @@ -268,4 +268,50 @@ describe('WorkspacePicker', () => { ) expect(directoryPickerKind).not.toHaveBeenCalled() }) + + /** Render the picker with an owner-controlled `open` and a scripted kind read. */ + function togglable(directoryPickerKind: () => Promise) { + const anchorRef = anchor() + const props = (open: boolean) => ( + + ) + const view = render(props(true)) + return { setOpen: (open: boolean) => { view.rerender(props(open)) } } + } + + it('discards a kind settlement from a superseded flow open', async () => { + let resolveFirst!: (kind: string) => void + const first = new Promise((settle) => { resolveFirst = settle }) + const directoryPickerKind = vi.fn<() => Promise>() + .mockImplementationOnce(() => first) + .mockImplementation(async () => 'browse') + const t = togglable(directoryPickerKind) + // Close while the first read is in flight, then let it answer 'dialog': + // the settlement is stale and must not leak into the next open. + t.setOpen(false) + await act(async () => { resolveFirst('dialog') }) + t.setOpen(true) + await screen.findByRole('menuitem', { name: 'Create a new workspace' }) + await waitFor(() => { expect(directoryPickerKind).toHaveBeenCalledTimes(2) }) + expect(screen.queryByRole('menuitem', { name: 'Open local folder…' })).toBeNull() + }) + + it('discards a stale describe failure after a newer open already answered', async () => { + let rejectFirst!: (reason: Error) => void + const first = new Promise((_settle, reject) => { rejectFirst = reject }) + const directoryPickerKind = vi.fn<() => Promise>() + .mockImplementationOnce(() => first) + .mockImplementation(async () => 'dialog') + const t = togglable(directoryPickerKind) + t.setOpen(false) + t.setOpen(true) + await screen.findByRole('menuitem', { name: 'Open local folder…' }) + // The superseded read failing late must not hide the freshly shown entry. + await act(async () => { rejectFirst(new Error('late loss')); await first.catch(() => {}) }) + expect(screen.getByRole('menuitem', { name: 'Open local folder…' })).toBeTruthy() + }) }) diff --git a/packages/host/directory-picker/src/index.ts b/packages/host/directory-picker/src/index.ts index 322dc4551c..1c4f5e32fb 100644 --- a/packages/host/directory-picker/src/index.ts +++ b/packages/host/directory-picker/src/index.ts @@ -128,3 +128,5 @@ export abstract class DirectoryPicker extends Service { */ abstract capability(): DirectoryPickerCapability } + +export default DirectoryPicker From 99643e59a180619fde26f2da90725514cc0f8aca Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 18:04:21 +0800 Subject: [PATCH 18/93] feat(web): miller two-pane directory browser per the full figma flow The single-column dialog missed the design's interaction model (figma 813-23126/813-23278, sibling frames of the linked node): selection is not navigation. The browser now opens as one wide level; selecting a row keeps it marked (pill + open-folder accent) and previews its children in a second 256px column across a hairline divider, a right-column pick advances one level, and the breadcrumb follows the selection. New folder becomes the design's nested create dialog ("New folder in ...", Untitled-folder placeholder, Cancel/Create), creating inside the selection and landing with the new folder selected. Open adopts the selection, falling back to the listed level, so the e2e path-edit flow is unchanged. The card is the design's fixed 600x420 with per-column scrolling. --- .../src/client/DirectoryBrowser.module.css | 136 ++++++-- .../src/client/DirectoryBrowser.tsx | 267 ++++++++++---- .../client/ui-workspace/src/client/index.ts | 6 + .../tests/directory-browser.spec.tsx | 327 +++++++++++++----- .../tests/workspace-picker.spec.tsx | 4 +- 5 files changed, 553 insertions(+), 187 deletions(-) diff --git a/packages/client/ui-workspace/src/client/DirectoryBrowser.module.css b/packages/client/ui-workspace/src/client/DirectoryBrowser.module.css index 14f3e4f2ca..f59a74aa7e 100644 --- a/packages/client/ui-workspace/src/client/DirectoryBrowser.module.css +++ b/packages/client/ui-workspace/src/client/DirectoryBrowser.module.css @@ -1,13 +1,14 @@ -/* Directory-browser dialog (figma 802-56979). The shared Modal renders +/* Directory-browser dialog (figma 813-23126 family). The shared Modal renders * headless here — mask, card, Escape only — and this module owns the figma - * frame exactly: header (title + crumbs, l3 separator), one directory level, - * and the bordered footer. Card: w600 r24, bottom pad 12, no close chrome. */ + * frame exactly: fixed 600×420 card, 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. */ .dialog.dialog { width: min(600px, 100%); - padding: 0 0 12px; - gap: 16px; + height: 420px; + padding: 0; + gap: 0; } /* Header block: pl24 pr14 pt22 pb12, 8px between title row and crumb row. */ @@ -15,6 +16,7 @@ display: flex; flex-direction: column; gap: 8px; + flex: none; padding: 22px 14px 12px 24px; border-bottom: 1px solid var(--dsw-alias-border-l3); } @@ -95,16 +97,37 @@ color: var(--dsw-alias-label-primary); } -/* One directory level: content column pt16 px24, 28px rows with 2px gaps. */ -.level { +/* 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; + align-items: stretch; + flex: 1 1 0; + min-height: 0; + gap: 20px; + padding: 16px 24px 0; +} + +.column { display: flex; flex-direction: column; gap: 2px; - padding: 16px 24px 0; - max-height: 320px; + 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); +} + .row { display: flex; align-items: center; @@ -123,11 +146,22 @@ 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; @@ -145,29 +179,6 @@ color: var(--dsw-alias-label-tertiary); } -.folderRow { - cursor: default; -} - -.folderInput { - box-sizing: border-box; - flex: 1 1 0; - min-width: 0; - height: 24px; - padding: 0 6px; - border: 1px solid var(--dsw-alias-border-l2); - border-radius: 6px; - outline: none; - background: transparent; - font-size: 13px; - line-height: 20px; - color: var(--dsw-alias-label-primary); -} - -.folderInput::placeholder { - color: var(--dsw-alias-label-caption); -} - .status, .error { padding: 4px; @@ -183,12 +194,14 @@ color: var(--dsw-alias-state-error-primary); } -/* Footer: l3 separator on top, pt12 px24, New-folder pinned left. */ +/* 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; gap: 8px; - padding: 12px 24px 0; + flex: none; + padding: 12px 24px 28px; border-top: 1px solid var(--dsw-alias-border-l3); } @@ -199,3 +212,58 @@ .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; +} diff --git a/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx b/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx index 9454693969..28c0281c56 100644 --- a/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx +++ b/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx @@ -1,15 +1,21 @@ /** - * The in-app workspace-directory browser (figma Harness 802-56979): breadcrumb - * header with a click-to-edit path zone, one navigable directory level, an - * inline New-folder row, and the Cancel/Open footer. 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). + * The in-app workspace-directory browser (figma Harness 813-23126 family): a + * fixed 600×420 dialog 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, IconPlusOutline16, Modal, + 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' @@ -22,13 +28,13 @@ export interface DirectoryBrowserProps { open: boolean /** List one directory level (absent path = the Host home directory). */ listDirectory: (path?: string) => Promise - /** Create one child directory under the listed level. */ + /** Create one child directory under an existing parent. */ createDirectory: (path: string, name: string) => Promise - /** The operator confirmed the currently listed directory. */ + /** 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 level freezes. */ + /** The owner's confirm is in flight: Open disables, the view freezes. */ busy: boolean /** Localized copy. */ t: Translate @@ -52,32 +58,73 @@ function displayCrumbs(listing: DirectoryListing, homeLabel: string): DirectoryE 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 ( +
+ {entries.filter(entry => !entry.hidden).map((entry) => { + const selected = entry.path === selectedPath + return ( + + ) + })} +
+ ) +} + /** * 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) { - const [listing, setListing] = useState(null) + // 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(null) + const [selected, setSelected] = useState(null) + const [child, setChild] = useState(null) const [loading, setLoading] = useState(false) const [error, setError] = useState(null) // Path-edit state: null = breadcrumb mode; a string = the draft being typed. const [pathDraft, setPathDraft] = useState(null) - // New-folder state: null = no inline row; a string = the name being typed. + // Create-folder state: null = closed; a string = the nested dialog's draft. const [folderDraft, setFolderDraft] = useState(null) const [creatingFolder, setCreatingFolder] = useState(false) + const [createError, setCreateError] = useState(null) const requestSeq = useRef(0) + /** Replace the whole view with one freshly listed level (no selection). */ const navigate = useCallback((path?: string) => { const seq = ++requestSeq.current setLoading(true) setError(null) listDirectory(path).then((next) => { if (seq !== requestSeq.current) return - setListing(next) + setParent(next) + setSelected(null) + setChild(null) setLoading(false) setPathDraft(null) - setFolderDraft(null) }, (reason: unknown) => { if (seq !== requestSeq.current) return setLoading(false) @@ -85,11 +132,39 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, }) }, [listDirectory]) + /** Select a row of the listed level and preview its children on the right. */ + const select = useCallback((entry: DirectoryEntry) => { + const seq = ++requestSeq.current + setSelected(entry) + setChild(null) + setLoading(true) + setError(null) + listDirectory(entry.path).then((next) => { + if (seq !== requestSeq.current) return + setChild(next) + setLoading(false) + }, (reason: unknown) => { + if (seq !== requestSeq.current) return + setLoading(false) + setError(failureText(reason)) + }) + }, [listDirectory]) + + /** 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(() => { if (open) { - setListing(null) + setParent(null) + setSelected(null) + setChild(null) navigate() return } @@ -97,29 +172,56 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, setError(null) setPathDraft(null) setFolderDraft(null) + setCreateError(null) }, [open, navigate]) - const confirmFolder = (): void => { - /* v8 ignore next -- reentry fence: the inline row only renders with a listing and a draft, and the input disables while creating. */ - if (listing === null || folderDraft === null || creatingFolder) return + /** 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 const name = folderDraft.trim() if (name === '') return setCreatingFolder(true) - setError(null) - createDirectory(listing.path, name).then(() => { + setCreateError(null) + createDirectory(targetPath, name).then((createdPath) => { setCreatingFolder(false) setFolderDraft(null) - navigate(listing.path) + // 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 = ++requestSeq.current + setLoading(true) + listDirectory(targetPath).then((level) => { + // Same seq fence as navigate/select; the nested dialog blocks + // superseding input during this relist. + /* v8 ignore next */ + if (seq !== requestSeq.current) return + setParent(level) + setLoading(false) + select({ name, path: createdPath, hidden: false }) + }, (reason: unknown) => { + // Same seq fence as navigate/select; the nested dialog blocks + // superseding input during this relist. + /* v8 ignore next */ + if (seq !== requestSeq.current) return + setLoading(false) + setError(failureText(reason)) + }) }, (reason: unknown) => { setCreatingFolder(false) - setError(failureText(reason)) + setCreateError(failureText(reason)) }) } // After the hooks: a closed dialog renders nothing and evaluates no copy. if (!open) return null - const crumbs = listing === null ? [] : displayCrumbs(listing, t('browser.home')) + const crumbSource = child ?? parent + const crumbs = crumbSource === null ? [] : displayCrumbs(crumbSource, t('browser.home')) + const twoPane = selected !== null return ( { if (listing !== null) setPathDraft(listing.path) }} + disabled={parent === null || busy} + /* v8 ignore next -- narrowing guard: the zone disables while the level is null. */ + onClick={() => { if (parent !== null) setPathDraft(selected?.path ?? parent.path) }} /> ) @@ -183,45 +285,26 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, )} -
- {folderDraft !== null && listing !== null && ( -
- - { setFolderDraft(event.target.value) }} - onKeyDown={(event) => { - if (event.key === 'Enter') { - event.preventDefault() - confirmFolder() - } - if (event.key === 'Escape') { - event.stopPropagation() - setFolderDraft(null) - } - }} - /> -
+
+ {parent !== null && ( + + )} + {twoPane && } + {twoPane && child !== null && ( + )} - {listing?.entries.filter(entry => !entry.hidden).map(entry => ( - - ))} {loading &&
{t('browser.loading')}
} {error !== null &&
{error}
}
@@ -229,8 +312,11 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, @@ -239,13 +325,56 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen,
+ {/* Nested create dialog (figma 813:23278): names one folder inside the target. */} + { if (!creatingFolder) setFolderDraft(null) }} + title={t('browser.newFolder')} + className={clsx(css.createDialog)} + headless + > +
+

{t('browser.newFolder')}

+

{t('browser.createIn', { name: targetName })}

+ { setFolderDraft(event.target.value) }} + onKeyDown={(event) => { + if (event.key === 'Enter') { + event.preventDefault() + confirmCreate() + } + if (event.key === 'Escape') { + event.stopPropagation() + if (!creatingFolder) setFolderDraft(null) + } + }} + /> + {createError !== null &&
{createError}
} +
+ + +
+
+
) } diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 4c400109f5..91c62b8fa8 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -44,6 +44,9 @@ export function apply(ctx: ClientContext): void { 'browser.home': '主目录', 'browser.newFolder': '新建文件夹', 'browser.folderName': '文件夹名称', + 'browser.createIn': '在"{name}"中新建文件夹', + 'browser.untitledFolder': '未命名文件夹', + 'browser.create': '创建', 'browser.cancel': '取消', 'browser.open': '打开', 'browser.editPath': '编辑路径', @@ -54,6 +57,9 @@ export function apply(ctx: ClientContext): void { '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', diff --git a/packages/client/ui-workspace/tests/directory-browser.spec.tsx b/packages/client/ui-workspace/tests/directory-browser.spec.tsx index a78527d5f1..28c25b367f 100644 --- a/packages/client/ui-workspace/tests/directory-browser.spec.tsx +++ b/packages/client/ui-workspace/tests/directory-browser.spec.tsx @@ -1,6 +1,6 @@ // @vitest-environment jsdom import { afterEach, describe, expect, it, vi } from 'vitest' -import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' +import { 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' @@ -8,6 +8,8 @@ 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 { @@ -23,19 +25,31 @@ function listingFor(path?: string): DirectoryListing { ], entries: [ { name: '.config', path: `${HOME}/.config`, hidden: true }, - { name: 'Documents', path: `${HOME}/Documents`, hidden: false }, + { name: 'Documents', path: DOCS, hidden: false }, ], }, - [`${HOME}/Documents`]: { - path: `${HOME}/Documents`, + [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: `${HOME}/Documents`, hidden: false }, + { name: 'Documents', path: DOCS, hidden: false }, ], - entries: [{ name: 'harness', path: `${HOME}/Documents/harness`, hidden: false }], + entries: [{ name: 'harness', path: HARNESS, hidden: 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: [], }, } const found = tree[target] @@ -57,49 +71,102 @@ function mount(overrides: Partial[0]> = {}) onOpen, onClose, busy: false, - t: (key: string) => key, + t: (key: string, params?: Record) => (params === undefined ? key : `${key}:${String(params.name)}`), ...overrides, } const view = render() return { view, props, listDirectory, createDirectory, onOpen, onClose } } +/** The rendered level columns, left-to-right. */ +function columns(): HTMLElement[] { + return screen.getAllByRole('list') +} + describe('DirectoryBrowser', () => { - it('opens at the Host home, hides hidden entries, and roots the crumbs at Home', async () => { + 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(columns()).toHaveLength(1) expect(screen.getByRole('listitem').textContent).toBe('Documents') expect(screen.queryByText('.config')).toBeNull() - // Inside the home subtree the chain collapses to a localized Home crumb. expect(screen.getByRole('button', { name: 'browser.home' })).toBeTruthy() expect(screen.queryByRole('button', { name: '/' })).toBeNull() }) - it('enters a row on click and jumps back through a crumb', async () => { + 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(screen.getByRole('listitem')) - await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') }) - expect(b.listDirectory).toHaveBeenLastCalledWith(`${HOME}/Documents`) - fireEvent.click(screen.getByRole('button', { name: 'browser.home' })) - await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('Documents') }) + await waitFor(() => { expect(columns()).toHaveLength(2) }) + const [level, preview] = columns() + const selectedRow = within(level!).getByRole('listitem') + expect(selectedRow.textContent).toBe('Documents') + expect(selectedRow.getAttribute('aria-current')).toBe('true') + expect(within(preview!).getByRole('listitem').textContent).toBe('harness') + expect(b.listDirectory).toHaveBeenLastCalledWith(DOCS) + expect(screen.getByRole('button', { name: 'Documents' })).toBeTruthy() }) - it('edits the path from the crumb bar: Enter navigates, Escape restores', async () => { + it('advances one level when a right-column row is picked', async () => { mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('listitem')) + await waitFor(() => { expect(columns()).toHaveLength(2) }) + fireEvent.click(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(selectedRow.getAttribute('aria-current')).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(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(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(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('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('browser.editPath') expect(input.value).toBe(HOME) - fireEvent.change(input, { target: { value: `${HOME}/Documents` } }) + fireEvent.change(input, { target: { value: DOCS } }) fireEvent.keyDown(input, { key: 'Enter' }) await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') }) - // Escape leaves an opened edit without navigating. + expect(columns()).toHaveLength(1) fireEvent.click(screen.getByRole('button', { name: 'browser.editPath' })) - fireEvent.keyDown(screen.getByLabelText('browser.editPath'), { key: 'Escape' }) + const again = screen.getByLabelText('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() - expect(screen.getByRole('listitem').textContent).toBe('harness') }) it('surfaces an unreadable target as an alert and keeps the edit open for correction', async () => { @@ -114,40 +181,16 @@ describe('DirectoryBrowser', () => { expect(screen.getByRole('listitem').textContent).toBe('Documents') }) - it('creates a folder inline and refreshes the level; failures land as alerts', async () => { - const b = mount() - await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) - fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' })) - const input = screen.getByLabelText('browser.newFolder') - fireEvent.change(input, { target: { value: 'fresh' } }) - fireEvent.keyDown(input, { key: 'Enter' }) - await waitFor(() => { expect(b.createDirectory).toHaveBeenCalledWith(HOME, 'fresh') }) - // The level reloads after creation (initial + post-create). - await waitFor(() => { expect(b.listDirectory).toHaveBeenLastCalledWith(HOME) }) - - b.createDirectory.mockRejectedValueOnce( - new DirectoryBrowseError({ code: 'directory-exists', message: 'taken already', details: { path: `${HOME}/x` } })) - fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' })) - const retry = screen.getByLabelText('browser.newFolder') - fireEvent.change(retry, { target: { value: 'x' } }) - fireEvent.keyDown(retry, { key: 'Enter' }) - await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('taken already') }) + 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() + 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('confirms the listed directory through Open, closes through Cancel, and freezes while busy', 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(screen.getByRole('button', { name: 'browser.cancel' })) - expect(b.onClose).toHaveBeenCalled() - - const busy = mount({ busy: true }) - await waitFor(() => { expect(busy.listDirectory).toHaveBeenCalled() }) - expect(screen.getAllByRole('button', { name: 'browser.open' }).at(-1)!.disabled).toBe(true) - }) - - it('renders the full ancestry when the listing sits outside the home subtree', async () => { + it('renders the full ancestry when the level sits outside the home subtree', async () => { const outside: DirectoryListing = { path: '/srv/data', home: HOME, @@ -164,53 +207,110 @@ describe('DirectoryBrowser', () => { expect(screen.queryByRole('button', { name: 'browser.home' })).toBeNull() }) - 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() - 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('cancels the inline folder row with Escape and ignores a blank name', async () => { + 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(screen.getByRole('listitem')) + await waitFor(() => { expect(columns()).toHaveLength(2) }) fireEvent.click(screen.getByRole('button', { name: 'browser.newFolder' })) - const input = screen.getByLabelText('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: [], + } + } + 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(screen.getByRole('button', { name: 'Documents' })).toBeTruthy() + const level = columns()[0]! + const rows = within(level).getAllByRole('listitem') + expect(rows.some(row => row.textContent === 'fresh' && 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.keyDown(input, { key: 'Escape' }) - expect(screen.queryByLabelText('browser.newFolder')).toBeNull() - }) - - it('ignores a blank path draft on Enter', async () => { - const b = 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: ' ' } }) + fireEvent.change(input, { target: { value: 'x' } }) fireEvent.keyDown(input, { key: 'Enter' }) - // Only the initial home listing ran; the blank draft navigated nowhere. - expect(b.listDirectory).toHaveBeenCalledTimes(1) + 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('drops a stale listing that resolves after a newer navigation', async () => { + it('surfaces a selection-preview failure while keeping the selection marked', async () => { + const b = mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + b.listDirectory.mockRejectedValueOnce( + new DirectoryBrowseError({ code: 'directory-unreadable', message: 'denied', details: { path: DOCS } })) + fireEvent.click(screen.getByRole('listitem')) + await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('denied') }) + expect(screen.getByRole('listitem').getAttribute('aria-current')).toBe('true') + // No preview column arrived for the failed selection. + expect(columns()).toHaveLength(1) + }) + + 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() }) - // The next navigation (into Documents) hangs; a Home-crumb jump supersedes it. let resolveSlow!: (value: DirectoryListing) => void const slow = new Promise((settle) => { resolveSlow = settle }) b.listDirectory.mockReturnValueOnce(slow) fireEvent.click(screen.getByRole('listitem')) fireEvent.click(screen.getByRole('button', { name: 'browser.home' })) await waitFor(() => { expect(b.listDirectory).toHaveBeenCalledTimes(3) }) - await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('Documents') }) - resolveSlow(listingFor(`${HOME}/Documents`)) + await waitFor(() => { expect(columns()).toHaveLength(1) }) + resolveSlow(listingFor(DOCS)) await new Promise(settle => setTimeout(settle, 0)) - // The stale Documents listing did not clobber the newer Home level. - expect(screen.getByRole('listitem').textContent).toBe('Documents') + // 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 () => { @@ -224,19 +324,82 @@ describe('DirectoryBrowser', () => { await waitFor(() => { expect(b.listDirectory).toHaveBeenCalledTimes(3) }) rejectSlow(new Error('too late to matter')) await new Promise(settle => setTimeout(settle, 0)) - // The superseded failure surfaces no alert over the newer level. 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(screen.getByRole('listitem')) + await waitFor(() => { expect(columns()).toHaveLength(2) }) + let rejectSlow!: (reason: unknown) => void + const slow = new Promise((_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(screen.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(screen.getByRole('listitem')) + await waitFor(() => { expect(columns()).toHaveLength(2) }) + let resolveSlow!: (value: DirectoryListing) => void + const slow = new Promise((settle) => { resolveSlow = settle }) + b.listDirectory.mockReturnValueOnce(slow) + fireEvent.click(screen.getByRole('button', { name: 'browser.home' })) + fireEvent.click(screen.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: [] } + mount({ listDirectory: vi.fn(async () => bare) }) + await waitFor(() => { expect(screen.getByRole('button', { name: 'browser.newFolder' })).toBeTruthy() }) + await waitFor(() => { + expect(screen.getByRole('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((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('starts back at home on reopen', async () => { const b = mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) fireEvent.click(screen.getByRole('listitem')) - await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('harness') }) + await waitFor(() => { expect(columns()).toHaveLength(2) }) b.view.rerender() b.view.rerender() await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('Documents') }) + expect(columns()).toHaveLength(1) expect(b.listDirectory).toHaveBeenLastCalledWith(undefined) }) }) diff --git a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx index 0c634fbd60..2d7531a710 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx @@ -41,7 +41,7 @@ function pickingShare(): DirectoryPickingInjected { return { directoryPickerKind: vi.fn(async () => 'dialog' as const), pickDirectory: vi.fn(async () => null), - listDirectory: vi.fn(async () => ({ path: '/home/u', home: '/home/u', crumbs: [], entries: [] })), + listDirectory: vi.fn(async () => ({ path: '/home/u', home: '/home/u', crumbs: [{ name: 'u', path: '/home/u', hidden: false }], entries: [] })), createDirectory: vi.fn(async () => '/home/u/new'), t: (key: string) => key, } @@ -59,7 +59,7 @@ function mount( const share: DirectoryPickingInjected = { directoryPickerKind: vi.fn(async () => 'dialog' as const), pickDirectory, - listDirectory: vi.fn(async () => ({ path: '/home/u', home: '/home/u', crumbs: [], entries: [] })), + listDirectory: vi.fn(async () => ({ path: '/home/u', home: '/home/u', crumbs: [{ name: 'u', path: '/home/u', hidden: false }], entries: [] })), createDirectory: vi.fn(async () => '/home/u/new'), t: key => key, ...picking, From 5f3c53d8351bb616b27a0b1ef94b4e1a6df19796 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 18:04:50 +0800 Subject: [PATCH 19/93] style(web): keep the v8 ignore reasons inline per the invariant rule --- .../client/ui-workspace/src/client/DirectoryBrowser.tsx | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx b/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx index 28c0281c56..49cbff9fb3 100644 --- a/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx +++ b/packages/client/ui-workspace/src/client/DirectoryBrowser.tsx @@ -195,17 +195,13 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, const seq = ++requestSeq.current setLoading(true) listDirectory(targetPath).then((level) => { - // Same seq fence as navigate/select; the nested dialog blocks - // superseding input during this relist. - /* v8 ignore next */ + /* 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) => { - // Same seq fence as navigate/select; the nested dialog blocks - // superseding input during this relist. - /* v8 ignore next */ + /* v8 ignore next -- same fence as navigate/select; the modal blocks superseding input */ if (seq !== requestSeq.current) return setLoading(false) setError(failureText(reason)) From b211a80b1fa8d3eccd1d0c5ab0cb2f7b5b1755d6 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 18:13:20 +0800 Subject: [PATCH 20/93] fix(host,client): require fully qualified browse paths; clear the picker kind on close ds-review-bot round 4. On Windows, isAbsolute admits rooted drive-less forms (\foo, /foo) that resolve() then rebases onto the process's current drive; both browse primitives now gate on a fullyQualified check (drive letter or UNC on win32, POSIX-absolute elsewhere) with a platform test seam, per-platform unit cases, and the contract wording updated on the seam, the backend README pair, and the error messages. The picker-kind effect also kept a resolved 'dialog' across close, so a backend swapped while the menu was closed could paint the stale entry for one frame on reopen; the close arm now clears the state, pinned by a reopen-under-pending-read race test. --- docs/cordis-catalog/services.md | 2 +- .../src/client/WorkspacePicker.tsx | 16 ++++++--- .../tests/workspace-picker.spec.tsx | 14 ++++++++ .../directory-picker-browse/README.i18n.yaml | 4 +-- .../host/directory-picker-browse/README.md | 2 +- .../host/directory-picker-browse/README.zh.md | 2 +- .../host/directory-picker-browse/src/index.ts | 34 ++++++++++++++----- .../tests/service.spec.ts | 15 +++++++- packages/host/directory-picker/src/index.ts | 7 ++-- 9 files changed, 74 insertions(+), 22 deletions(-) diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 3b47e405f0..ce24921fe8 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -481,7 +481,7 @@ Abstract directory-picking service. Subclass, implement `capability()`, and load abstract capability(): DirectoryPickerCapability ``` -Source: [`packages/host/directory-picker/src/index.ts:120`](../../packages/host/directory-picker/src/index.ts) +Source: [`packages/host/directory-picker/src/index.ts:121`](../../packages/host/directory-picker/src/index.ts) ## `ctx.fs` — `FileSystem` (abstract seam) diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx index 2e65fc6b72..786c5cf305 100644 --- a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -79,11 +79,17 @@ export function WorkspaceCreateFlow({ // flow open — no cache to go stale across reconnects. const [dialogPicker, setDialogPicker] = useState(false) useEffect(() => { - if (!open) return - // Reset before each read: a reconnect can change the composed backend, so - // a previous open's answer must not leak into this one; and a settlement - // from a superseded open (flow closed, or a newer read started) is - // discarded via the cleanup-toggled flag. + if (!open) { + // Close discards the answer: a reconnect or HMR can swap the composed + // backend while the menu is closed, and the reopened menu must never + // paint the previous host's entry before the fresh read lands. + setDialogPicker(false) + return + } + // Reset before each read: the injected reader can also change identity + // while the flow stays open, and that prior answer must not leak either; + // a settlement from a superseded read is discarded via the + // cleanup-toggled flag. setDialogPicker(false) let stale = false void directoryPickerKind() diff --git a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx index 9ca5304fa4..d8b3ab5a54 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx @@ -300,6 +300,20 @@ describe('WorkspacePicker', () => { expect(screen.queryByRole('menuitem', { name: 'Open local folder…' })).toBeNull() }) + it('clears the advertised kind on close so a reopen cannot paint the previous host entry', async () => { + const directoryPickerKind = vi.fn<() => Promise>() + .mockImplementationOnce(async () => 'dialog') + // The reopened read never settles: the assertion below sees the paint + // that precedes any fresh answer. + .mockImplementation(() => new Promise(() => {})) + const t = togglable(directoryPickerKind) + await screen.findByRole('menuitem', { name: 'Open local folder…' }) + t.setOpen(false) + t.setOpen(true) + await screen.findByRole('menuitem', { name: 'Create a new workspace' }) + expect(screen.queryByRole('menuitem', { name: 'Open local folder…' })).toBeNull() + }) + it('discards a stale describe failure after a newer open already answered', async () => { let rejectFirst!: (reason: Error) => void const first = new Promise((_settle, reject) => { rejectFirst = reject }) diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index 916db3c321..4dfc363903 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/directory-picker-browse/README.md -README.md: 81357269e1d4b075f7e31b5f3ac5d4721811024a -README.zh.md: 06a7f7651b2abc0aa73eba41042f3d1a86661b76 +README.md: 160a12a8594400c9e6c565881d8e9ca0517b4e24 +README.zh.md: 4cfc4a611fb17cb30ac841c8af8498b51a6388b0 diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index 81357269e1..160a12a859 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) The **in-app browsing backend** of the [directory-picker seam](../directory-picker/README.md): `BrowseDirectoryPicker` registers `ctx.directoryPicker` with the `browse` capability — one-level directory listing and child-directory creation over Node's stdlib, which already carries the per-OS adaptation. Nothing renders on the host display, so this backend serves remote clients the dialog 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 a non-absolute explicit path (`directory-unreadable`/`directory-create-failed`) instead of letting `resolve` rebase it under the host process cwd. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). +Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject an explicit path that is not fully qualified — relative forms, and on Windows the rooted drive-less forms (`\foo`, `/foo`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). ## Model Experience diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index 06a7f7651b..4cfc4a611f 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -4,7 +4,7 @@ [目录选择 seam](../directory-picker/README.md) 的**应用内浏览后端**:`BrowseDirectoryPicker` 以 `browse` 能力注册 `ctx.directoryPicker`——基于 Node 标准库(跨 OS 适配本就由它承担)提供单层目录列举与子目录创建。宿主屏幕上不渲染任何东西,因此该后端能服务 dialog 后端无法触及的远程客户端。 -行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非绝对的显式路径(`directory-unreadable`/`directory-create-failed`),而不是任由 `resolve` 把它重定位到宿主进程 cwd 之下。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 +行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo`、`/foo`)——报 `directory-unreadable`/`directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 ## 模型体验 diff --git a/packages/host/directory-picker-browse/src/index.ts b/packages/host/directory-picker-browse/src/index.ts index 83a3f6762e..d3566e9415 100644 --- a/packages/host/directory-picker-browse/src/index.ts +++ b/packages/host/directory-picker-browse/src/index.ts @@ -11,7 +11,7 @@ import { mkdir, readdir, stat } from 'node:fs/promises' import { homedir } from 'node:os' -import { basename, dirname, isAbsolute, join, resolve } from 'node:path' +import { basename, dirname, join, posix, resolve, win32 } from 'node:path' import { DirectoryPicker, DirectoryPickerError, } from '@deepseek-ai/dsh-host-directory-picker' @@ -35,6 +35,22 @@ function ancestryCrumbs(target: string): DirectoryEntry[] { } } +/** + * True when the path names one fixed filesystem location regardless of + * process state: POSIX-absolute on POSIX; on Windows only drive-qualified + * (`C:\…`) or UNC (`\\server\…`) forms — rooted drive-less forms (`\foo`, + * `/foo`) 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) +} + /** 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. */ @@ -81,10 +97,11 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { private async list(path?: string): Promise { const home = homedir() - // The seam contract takes absolute paths only; resolve() would silently - // rebase a relative or empty wire value under the host process cwd. - if (path !== undefined && !isAbsolute(path)) { - throw new DirectoryPickerError('directory-unreadable', path, `cannot list "${path}": not an absolute path`) + // 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) let names: { name: string; isDirectory: boolean; isSymbolicLink: boolean }[] @@ -105,9 +122,10 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { } private async createDirectory(path: string, name: string): Promise { - // Same absolute-path fence as list: never rebase a parent under the cwd. - if (!isAbsolute(path)) { - throw new DirectoryPickerError('directory-create-failed', path, `cannot create under "${path}": not an absolute parent path`) + // 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, diff --git a/packages/host/directory-picker-browse/tests/service.spec.ts b/packages/host/directory-picker-browse/tests/service.spec.ts index 608fe89348..4cf16107f8 100644 --- a/packages/host/directory-picker-browse/tests/service.spec.ts +++ b/packages/host/directory-picker-browse/tests/service.spec.ts @@ -7,7 +7,7 @@ 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 from '../src/index.ts' +import BrowseDirectoryPicker, { fullyQualified } from '../src/index.ts' let root: string let capability: DirectoryPickerBrowseCapability @@ -70,6 +70,19 @@ describe('BrowseDirectoryPicker', () => { 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) + // 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) + }) + 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) diff --git a/packages/host/directory-picker/src/index.ts b/packages/host/directory-picker/src/index.ts index 1c4f5e32fb..77a63bb568 100644 --- a/packages/host/directory-picker/src/index.ts +++ b/packages/host/directory-picker/src/index.ts @@ -60,8 +60,9 @@ export interface DirectoryPickerBrowseCapability { * List one directory level. * @param path - absolute directory to list; absent lists the home directory. * @returns the level's listing with ancestry. - * @throws {DirectoryPickerError} `directory-unreadable` when the target is not absolute - * (a wire value must never rebase under the host cwd) or cannot be listed. + * @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): Promise /** @@ -70,7 +71,7 @@ export interface DirectoryPickerBrowseCapability { * @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 non-absolute parent or any other failure. + * `directory-create-failed` for a parent that is not fully qualified or any other failure. */ createDirectory(path: string, name: string): Promise } From 987ecc2ec2ab51737a57b8f49d9f233dc0d1b69b Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 18:27:26 +0800 Subject: [PATCH 21/93] fix(host): require complete UNC forms in the fully-qualified path check ds-review-bot round 5: '\\' and '\\server' satisfy win32.isAbsolute and the previous two-separator test, yet resolve() collapses them to drive-relative roots. The UNC arm now requires server and share components; incomplete prefixes reject with the business codes, covered per-platform. --- packages/host/directory-picker-browse/README.i18n.yaml | 4 ++-- packages/host/directory-picker-browse/README.md | 2 +- packages/host/directory-picker-browse/README.zh.md | 2 +- packages/host/directory-picker-browse/src/index.ts | 8 ++++---- .../host/directory-picker-browse/tests/service.spec.ts | 5 +++++ 5 files changed, 13 insertions(+), 8 deletions(-) diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index 4dfc363903..e41ef9a0ae 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/directory-picker-browse/README.md -README.md: 160a12a8594400c9e6c565881d8e9ca0517b4e24 -README.zh.md: 4cfc4a611fb17cb30ac841c8af8498b51a6388b0 +README.md: 9655fdb538da1addb4d10dbee6210965400394c8 +README.zh.md: 1c7b0c36cbb73286f3d4e6a48748c4415f9ff0e4 diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index 160a12a859..9655fdb538 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) The **in-app browsing backend** of the [directory-picker seam](../directory-picker/README.md): `BrowseDirectoryPicker` registers `ctx.directoryPicker` with the `browse` capability — one-level directory listing and child-directory creation over Node's stdlib, which already carries the per-OS adaptation. Nothing renders on the host display, so this backend serves remote clients the dialog 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`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). +Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject an explicit path that is not fully qualified — relative forms, and on Windows the rooted drive-less forms (`\foo`, `/foo`) and incomplete UNC prefixes (`\\`, `\\server`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). ## Model Experience diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index 4cfc4a611f..1c7b0c36cb 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -4,7 +4,7 @@ [目录选择 seam](../directory-picker/README.md) 的**应用内浏览后端**:`BrowseDirectoryPicker` 以 `browse` 能力注册 `ctx.directoryPicker`——基于 Node 标准库(跨 OS 适配本就由它承担)提供单层目录列举与子目录创建。宿主屏幕上不渲染任何东西,因此该后端能服务 dialog 后端无法触及的远程客户端。 -行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo`、`/foo`)——报 `directory-unreadable`/`directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 +行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo`、`/foo`)与不完整的 UNC 前缀(`\\`、`\\server`)——报 `directory-unreadable`/`directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 ## 模型体验 diff --git a/packages/host/directory-picker-browse/src/index.ts b/packages/host/directory-picker-browse/src/index.ts index d3566e9415..561e168421 100644 --- a/packages/host/directory-picker-browse/src/index.ts +++ b/packages/host/directory-picker-browse/src/index.ts @@ -38,16 +38,16 @@ function ancestryCrumbs(target: string): DirectoryEntry[] { /** * True when the path names one fixed filesystem location regardless of * process state: POSIX-absolute on POSIX; on Windows only drive-qualified - * (`C:\…`) or UNC (`\\server\…`) forms — rooted drive-less forms (`\foo`, - * `/foo`) pass `isAbsolute` yet still resolve against the process's current - * drive. + * (`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) + ? win32.isAbsolute(path) && /^(?:[A-Za-z]:[\\/]|[\\/]{2}[^\\/]+[\\/]+[^\\/]+)/.test(path) : posix.isAbsolute(path) } diff --git a/packages/host/directory-picker-browse/tests/service.spec.ts b/packages/host/directory-picker-browse/tests/service.spec.ts index 4cf16107f8..3f214760b7 100644 --- a/packages/host/directory-picker-browse/tests/service.spec.ts +++ b/packages/host/directory-picker-browse/tests/service.spec.ts @@ -76,11 +76,16 @@ describe('BrowseDirectoryPicker', () => { 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 () => { From 5579b13503af657bd59c174e9392936ae3b3fa8e Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 21:07:28 +0800 Subject: [PATCH 22/93] refactor(host): rename the directory-picker dialog backend and kind to native The browse interaction also presents a dialog (the in-app modal), so 'dialog' failed to discriminate the two capability kinds; 'native' names where the chooser runs. Package directory-picker-dialog -> directory-picker-native, kind 'dialog' -> 'native', with every seam/gateway/client/doc reference updated and the seam Agent Note's naming rationale rewritten to match. --- ...directory-picker-capability-seam.i18n.yaml | 4 +-- ...-07-28-directory-picker-capability-seam.md | 10 +++---- ...-28-directory-picker-capability-seam.zh.md | 8 +++--- apps/cli/cordis.yml | 2 +- apps/cli/package.json | 2 +- docs/capability-seams.md | 6 ++--- docs/config-catalog.md | 2 +- docs/module-graph.md | 6 ++--- packages/client/connection/tests/fake-api.ts | 2 +- .../runtime/src/client/workspaces/service.ts | 4 +-- packages/client/runtime/tests/fake-api.ts | 2 +- packages/client/ui-workspace/README.i18n.yaml | 4 +-- packages/client/ui-workspace/README.md | 2 +- packages/client/ui-workspace/README.zh.md | 2 +- .../src/client/WorkspacePicker.tsx | 14 +++++----- .../client/ui-workspace/tests/apply.spec.ts | 2 +- .../tests/workspace-browser.spec.tsx | 2 +- .../tests/workspace-picker.spec.tsx | 16 ++++++------ .../cordis/tool-cordis/src/api-catalog.ts | 6 ++--- packages/host/README.i18n.yaml | 4 +-- packages/host/README.md | 4 +-- packages/host/README.zh.md | 4 +-- packages/host/apiproxy/README.i18n.yaml | 4 +-- packages/host/apiproxy/README.md | 4 +-- packages/host/apiproxy/README.zh.md | 4 +-- packages/host/apiproxy/src/api-proxy.ts | 4 +-- packages/host/apiproxy/src/api/host.ts | 6 ++--- .../tests/api-proxy-workspace.spec.ts | 26 +++++++++---------- .../host/apiproxy/tests/fetch-carrier.spec.ts | 2 +- .../host/apiproxy/tests/rpc-schemas.spec.ts | 2 +- .../directory-picker-browse/README.i18n.yaml | 4 +-- .../host/directory-picker-browse/README.md | 2 +- .../host/directory-picker-browse/README.zh.md | 2 +- .../host/directory-picker-dialog/README.md | 17 ------------ .../README.i18n.yaml | 6 ++--- .../host/directory-picker-native/README.md | 17 ++++++++++++ .../README.zh.md | 4 +-- .../package.json | 4 +-- .../src/index.ts | 20 +++++++------- .../src/invariant.ts | 12 ++++----- .../src/native-picker.ts | 0 .../tests/native-picker.spec.ts | 0 .../tests/service.spec.ts | 14 +++++----- .../tsconfig.json | 0 .../host/directory-picker/README.i18n.yaml | 4 +-- packages/host/directory-picker/README.md | 2 +- packages/host/directory-picker/README.zh.md | 2 +- packages/host/directory-picker/src/index.ts | 10 +++---- .../host/directory-picker/tests/seam.spec.ts | 4 +-- pnpm-lock.yaml | 6 ++--- scripts/gen-doc-graphs.ts | 4 +-- .../verify-package-readme-model-experience.ts | 2 +- tsconfig.host.json | 2 +- 53 files changed, 149 insertions(+), 149 deletions(-) delete mode 100644 packages/host/directory-picker-dialog/README.md rename packages/host/{directory-picker-dialog => directory-picker-native}/README.i18n.yaml (68%) create mode 100644 packages/host/directory-picker-native/README.md rename packages/host/{directory-picker-dialog => directory-picker-native}/README.zh.md (90%) rename packages/host/{directory-picker-dialog => directory-picker-native}/package.json (83%) rename packages/host/{directory-picker-dialog => directory-picker-native}/src/index.ts (64%) rename packages/host/{directory-picker-dialog => directory-picker-native}/src/invariant.ts (63%) rename packages/host/{directory-picker-dialog => directory-picker-native}/src/native-picker.ts (100%) rename packages/host/{directory-picker-dialog => directory-picker-native}/tests/native-picker.spec.ts (100%) rename packages/host/{directory-picker-dialog => directory-picker-native}/tests/service.spec.ts (57%) rename packages/host/{directory-picker-dialog => directory-picker-native}/tsconfig.json (100%) diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml index c13d5e7a1c..1c7ea3556f 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml @@ -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 .agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md -2026-07-28-directory-picker-capability-seam.md: a30675f2d84b6ae68b95ab96df9e32106d6fbf5d -2026-07-28-directory-picker-capability-seam.zh.md: 5560aba07424d7307e386e2e8ae6b724486d6068 +2026-07-28-directory-picker-capability-seam.md: 78ae05e0da67bff791c0b4f315451aa02e1fa6f4 +2026-07-28-directory-picker-capability-seam.zh.md: bd527e2a1dba6934300a50877d4777f7f9fa24b1 diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md index a30675f2d8..78ae05e0da 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md @@ -10,7 +10,7 @@ The web GUI's "Open local folder" flow was hardwired to one interaction: `host.p ## Decision -A three-package capability seam in `packages/host/` — `directory-picker` (interface), `directory-picker-dialog`, `directory-picker-browse` (backends) — with one contract method: `capability()` returns a **discriminated union**, `{ kind: 'dialog', pick(signal) }` or `{ kind: 'browse', list(path?), createDirectory(path, name) }`. The gateway (`dsh-host-apiproxy`) injects `directoryPicker`, advertises the kind through `host.describe.directoryPicker`, serves the matching RPCs, and answers `directory-picker-unavailable` for the other kind; the client branches on the advertised kind and hides the affordance for unknown kinds (merge-extensible default). Composition (`cordis.yml`) is the swap point; the union is discriminated because the backends differ in *interaction shape* — flattening them into one method set would force every backend to fake the other's shape. +A three-package capability seam in `packages/host/` — `directory-picker` (interface), `directory-picker-native`, `directory-picker-browse` (backends) — with one contract method: `capability()` returns a **discriminated union**, `{ kind: 'native', pick(signal) }` or `{ kind: 'browse', list(path?), createDirectory(path, name) }`. The gateway (`dsh-host-apiproxy`) injects `directoryPicker`, advertises the kind through `host.describe.directoryPicker`, serves the matching RPCs, and answers `directory-picker-unavailable` for the other kind; the client branches on the advertised kind and hides the affordance for unknown kinds (merge-extensible default). Composition (`cordis.yml`) is the swap point; the union is discriminated because the backends differ in *interaction shape* — flattening them into one method set would force every backend to fake the other's shape. Placement and policy rulings folded into this decision: @@ -19,18 +19,18 @@ Placement and policy rulings folded into this decision: - **Hidden entries: return-and-flag.** The host stamps `hidden` (POSIX dot convention) and returns everything; the client filters. Display policy stays client-side, and the planned show-hidden toggle becomes a client-only change. Windows' `FILE_ATTRIBUTE_HIDDEN` is not exposed by dirents — documented limitation until a native probe pays for itself. - **Symlinks: follow for enterability.** `stat` probes symlinks (broken/cyclic → skipped); crumbs keep the logical path the operator navigated, and `workspace.create` already canonicalizes via realpath at adoption. - **Whole-filesystem scope, no roots config.** `workspace.create` accepts arbitrary paths and the API serves bash-driving methods, so a browse root would be UX scoping, not a boundary; configurability without a consumer fails the evidence bar. Deferred until a deployment needs it. -- **The dialog backend stays.** Plugin-form was the point: multiple providers can serve the seam (an Electron shell would provide `dialog` natively). The backend names changed from mechanism (`native`/`local` — both run locally) to interaction (`-dialog`/`-browse`). +- **The native backend stays.** Plugin-form was the point: multiple providers can serve the seam (an Electron shell would provide the `native` interaction through its own dialog API). Kind naming: `dialog` was the first pick and was dropped — the browse interaction also presents a dialog (the in-app modal), so the word failed to discriminate; `native` names where the chooser runs. ## Alternatives considered - **Extend `ctx.fs` with browse methods.** Rejected: authority-domain coupling above; also a listing-for-display contract (hidden flags, crumbs, home anchor) does not belong on a storage seam. -- **One uniform seam method set (`pick(): path`).** Rejected: an in-app browser cannot be served behind a single host-side call — the browsing loop lives in the client and needs primitives on the wire; the dialog cannot implement primitives. The interaction difference is irreducible, hence the discriminant. +- **One uniform seam method set (`pick(): path`).** Rejected: an in-app browser cannot be served behind a single host-side call — the browsing loop lives in the client and needs primitives on the wire; the native chooser cannot implement primitives. The interaction difference is irreducible, hence the discriminant. - **Direct stdlib calls inside apiproxy (no seam).** Rejected: keeps the gateway the only swap point (source edits), loses fixture/test backends, and contradicts the plugin doctrine that motivated the work. - **Adopting a file-manager/drive-enumeration dependency.** Rejected per the survey above; recorded here as the dependency policy requires. ## Consequences -- `cordis.yml` chooses the interaction; `apps/cli` currently mounts `-dialog` (unchanged behavior). The GUI already gates its dialog affordance on `describe.directoryPicker` (non-`dialog` kinds hide it); the in-app browser PR flips the default to `-browse` and adds the browse UI. +- `cordis.yml` chooses the interaction; `apps/cli` currently mounts `-native` (unchanged behavior). The GUI already gates its picking affordance on `describe.directoryPicker` (non-`native` kinds hide it); the in-app browser PR flips the default to `-browse` and adds the browse UI. - The wire gains `host.listDirectory`/`host.createDirectory`, four error codes, and the `describe.directoryPicker` field; the connection fixture serves a deterministic browse tree for keyless assembled tests. -- A future interaction (or an Electron `dialog` provider) is one backend package plus a client branch — no gateway surgery. +- A future interaction (or an Electron provider of the `native` interaction) is one backend package plus a client branch — no gateway surgery. - `ApiProxyDefaults.pickDirectory` (test-only injection) is gone; tests provide a stub `ctx.directoryPicker` like any other service. diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md index 5560aba074..bd527e2a1d 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md @@ -10,7 +10,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick ## 决策 -在 `packages/host/` 落一个三包能力 seam——`directory-picker`(接口)、`directory-picker-dialog`、`directory-picker-browse`(后端)——唯一契约方法 `capability()` 返回**可辨识联合**:`{ kind: 'dialog', pick(signal) }` 或 `{ kind: 'browse', list(path?), createDirectory(path, name) }`。网关(`dsh-host-apiproxy`)注入 `directoryPicker`,经 `host.describe.directoryPicker` 广播 kind,提供对应的 RPC,另一种 kind 的调用以 `directory-picker-unavailable` 应答;客户端按广播的 kind 分支,未知 kind 隐藏入口(可合并扩展的默认分支)。组合(`cordis.yml`)就是换装点;联合之所以可辨识,是因为后端差异在**交互形态**——压平成统一方法集会逼每个后端伪装另一方的形态。 +在 `packages/host/` 落一个三包能力 seam——`directory-picker`(接口)、`directory-picker-native`、`directory-picker-browse`(后端)——唯一契约方法 `capability()` 返回**可辨识联合**:`{ kind: 'native', pick(signal) }` 或 `{ kind: 'browse', list(path?), createDirectory(path, name) }`。网关(`dsh-host-apiproxy`)注入 `directoryPicker`,经 `host.describe.directoryPicker` 广播 kind,提供对应的 RPC,另一种 kind 的调用以 `directory-picker-unavailable` 应答;客户端按广播的 kind 分支,未知 kind 隐藏入口(可合并扩展的默认分支)。组合(`cordis.yml`)就是换装点;联合之所以可辨识,是因为后端差异在**交互形态**——压平成统一方法集会逼每个后端伪装另一方的形态。 并入本决策的位置与策略裁决: @@ -19,7 +19,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **隐藏条目:返回并打标。** 宿主标注 `hidden`(POSIX 点前缀约定)并返回全部条目;客户端过滤。展示策略留在客户端,计划中的"显示隐藏"开关变成纯客户端改动。Windows 的 `FILE_ATTRIBUTE_HIDDEN` 不被 dirent 暴露——记为限制,直到原生探测值回其成本。 - **符号链接:为可进入性而跟随。** 用 `stat` 探测符号链接(断链/循环→跳过);面包屑保留操作者导航的逻辑路径,`workspace.create` 在接纳时本就做 realpath 规范化。 - **全盘可浏览,不做 roots 配置。** `workspace.create` 接受任意路径且 API 本就提供驱动 bash 的方法,浏览根只会是 UX 范围而非边界;没有消费方的可配置性过不了证据门槛。等到有部署需要再做。 -- **dialog 后端保留。** 插件化正是目的:多方都能提供该 seam(Electron 壳可以原生提供 `dialog`)。后端命名从机制(`native`/`local`——两者都在本机运行)改为交互(`-dialog`/`-browse`)。 +- **native 后端保留。** 插件化正是目的:多方都能提供该 seam(Electron 壳可以经自己的对话框 API 提供 `native` 交互)。kind 命名:最初选了 `dialog` 后被放弃——browse 交互同样以对话框呈现(应用内弹窗),这个词起不到判别作用;`native` 命名的是选择器运行的位置。 ## 曾考虑的替代方案 @@ -30,7 +30,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick ## 后果 -- `cordis.yml` 决定交互形态;`apps/cli` 当前挂 `-dialog`(行为不变)。GUI 已按 `describe.directoryPicker` 门控其对话框入口(非 `dialog` kind 一律隐藏);应用内浏览器 PR 将把默认翻到 `-browse` 并补上浏览 UI。 +- `cordis.yml` 决定交互形态;`apps/cli` 当前挂 `-native`(行为不变)。GUI 已按 `describe.directoryPicker` 门控其选目录入口(非 `native` kind 一律隐藏);应用内浏览器 PR 将把默认翻到 `-browse` 并补上浏览 UI。 - 协议新增 `host.listDirectory`/`host.createDirectory`、四个错误码与 `describe.directoryPicker` 字段;connection fixture 提供确定性浏览树供无密钥组装测试使用。 -- 未来的新交互(或 Electron 的 `dialog` 提供方)只是一个后端包加一个客户端分支——无需网关手术。 +- 未来的新交互(或提供 `native` 交互的 Electron 实现)只是一个后端包加一个客户端分支——无需网关手术。 - `ApiProxyDefaults.pickDirectory`(仅测试注入)删除;测试像提供其他服务一样提供 stub `ctx.directoryPicker`。 diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index 1ca28ecdaa..47ab16da51 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -236,7 +236,7 @@ # Directory-picking backend consumed by the gateway's host.* picker RPCs. # Swap point: mount '-browse' instead for the in-app browser (remote-capable). - id: directory-picker - name: '@deepseek-ai/dsh-host-directory-picker-dialog' + name: '@deepseek-ai/dsh-host-directory-picker-native' - id: api-gateway name: '@deepseek-ai/dsh-host-apiproxy' diff --git a/apps/cli/package.json b/apps/cli/package.json index 90b51e0397..9244cac610 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -48,7 +48,7 @@ "@deepseek-ai/dsh-fs-local": "workspace:^", "@deepseek-ai/dsh-fs-policy": "workspace:^", "@deepseek-ai/dsh-host-apiproxy": "workspace:^", - "@deepseek-ai/dsh-host-directory-picker-dialog": "workspace:^", + "@deepseek-ai/dsh-host-directory-picker-native": "workspace:^", "@deepseek-ai/dsh-host-webserver": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-llm-deepseek": "workspace:^", diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 5cedd97dba..fb523a0c70 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -138,7 +138,7 @@ flowchart LR pkg_spill_policy["spill-policy"] pkg_directory_picker["directory-picker"] svc_directoryPicker["ctx.directoryPicker
Workspace-directory picking seam"] - pkg_directory_picker_dialog["directory-picker-dialog"] + pkg_directory_picker_native["directory-picker-native"] pkg_directory_picker_browse["directory-picker-browse"] pkg_webserver["webserver"] svc_httpServer["ctx.httpServer
HTTP route registration"] @@ -165,7 +165,7 @@ flowchart LR pkg_compact_tool_result_prune --> svc_toolResultPrune pkg_directory_picker --> svc_directoryPicker pkg_directory_picker_browse --> svc_directoryPicker - pkg_directory_picker_dialog --> svc_directoryPicker + pkg_directory_picker_native --> svc_directoryPicker pkg_fs --> svc_fs pkg_fs_local --> svc_fs pkg_fs_sandbox --> svc_fs @@ -356,7 +356,7 @@ flowchart LR | `ctx.tasks` | `seam` | [`tasks`](../packages/tasks/tasks) | [`tasks-local`](../packages/tasks/tasks-local) | [`tool-bash`](../packages/bash/tool-bash), [`tool-pty`](../packages/pty/tool-pty), [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-tasks`](../packages/tasks/tool-tasks) | - | Producers (background bash, PTY sends, and subagent delegations) register running work; tool-tasks is the model-facing control surface that reads, lists, and kills it; tasks-local is the process-local registry. | | `ctx.web` | `seam` | [`web`](../packages/web/web) | [`web-search-exa`](../packages/web/web-search-exa), [`web-search-perplexity`](../packages/web/web-search-perplexity), [`web-search-deepseek`](../packages/web/web-search-deepseek), [`web-fetch-local`](../packages/web/web-fetch-local) | [`tool-web`](../packages/web/tool-web) | - | Search and fetch providers register into one ctx.web seam; tool-web owns the stable model-facing names. | | `ctx.spillStore` | `seam` | [`spill`](../packages/spill/spill) | [`spill-local`](../packages/spill/spill-local) | [`spill-policy`](../packages/spill/spill-policy) | - | The backend saves oversized tool text and returns a model-facing locator plus retrieval hint; spill-policy is the tools/post-execute consumer that decides when to spill. | -| `ctx.directoryPicker` | `seam` | `directory-picker` | `directory-picker-dialog`, `directory-picker-browse` | `apiproxy` | - | Discriminated interaction capability: the dialog backend opens one native OS chooser on the host display, the browse backend serves listing/creation primitives for the in-app browser; the gateway advertises the kind via host.describe. | +| `ctx.directoryPicker` | `seam` | `directory-picker` | `directory-picker-native`, `directory-picker-browse` | `apiproxy` | - | Discriminated interaction capability: the native backend opens one OS chooser on the host display, the browse backend serves listing/creation primitives for the in-app browser; the gateway advertises the kind via host.describe. | | `ctx.httpServer` | `core` | `webserver` | - | `connection`, `modules`, `hmr` | - | Plain node:http carrier: named-route registry, index transform taps, and the static dist fallback; web-transport plugins register their own routes. | | `ctx.clientModuleHost` | `core` | `modules` | - | `hmr` | - | Composes the __DSH_BOOT__ entry graph from an incremental dshClient scan, serves plugin bundles, and notifies rebuilt/graph-changed subscribers. | | `ctx.workflows` | `seam` | [`workflow`](../packages/workflow/workflow) | [`workflow-workerthread`](../packages/workflow/workflow-workerthread) | [`tool-workflow`](../packages/workflow/tool-workflow), [`tool-ralph`](../packages/workflow/tool-ralph) | - | One engine per context (bash shape, no named-provider registry); the general workflow and fixed Ralph consumers start runs whose agent() calls fan out through ctx.subagents. | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 0697f56dfe..3344bb8aac 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2187,7 +2187,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co - `@deepseek-ai/dsh-fs-policy` ([`packages/fs/fs-policy/src/index.ts`](../packages/fs/fs-policy/src/index.ts)) - `@deepseek-ai/dsh-goal-session` — requires `agents` · `goals` · `sessions` ([`packages/goal/goal-session/src/index.ts`](../packages/goal/goal-session/src/index.ts)) - `@deepseek-ai/dsh-host-directory-picker-browse` ([`packages/host/directory-picker-browse/src/index.ts`](../packages/host/directory-picker-browse/src/index.ts)) -- `@deepseek-ai/dsh-host-directory-picker-dialog` ([`packages/host/directory-picker-dialog/src/index.ts`](../packages/host/directory-picker-dialog/src/index.ts)) +- `@deepseek-ai/dsh-host-directory-picker-native` ([`packages/host/directory-picker-native/src/index.ts`](../packages/host/directory-picker-native/src/index.ts)) - `@deepseek-ai/dsh-llm` ([`packages/llm/llm/src/index.ts`](../packages/llm/llm/src/index.ts)) - `@deepseek-ai/dsh-lsp` ([`packages/lsp/lsp/src/index.ts`](../packages/lsp/lsp/src/index.ts)) - `@deepseek-ai/dsh-pty` ([`packages/pty/pty/src/index.ts`](../packages/pty/pty/src/index.ts)) diff --git a/docs/module-graph.md b/docs/module-graph.md index 03f4bee072..40ab39a8a2 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -184,7 +184,7 @@ flowchart TD pkg_host_apiproxy["host-apiproxy"] pkg_host_directory_picker["host-directory-picker"] pkg_host_directory_picker_browse["host-directory-picker-browse"] - pkg_host_directory_picker_dialog["host-directory-picker-dialog"] + pkg_host_directory_picker_native["host-directory-picker-native"] pkg_host_webserver["host-webserver"] end subgraph group_lsp["packages/lsp"] @@ -262,7 +262,7 @@ flowchart TD pkg_host_apiproxy --> pkg_invariants pkg_host_directory_picker --> pkg_invariants pkg_host_directory_picker_browse --> pkg_invariants - pkg_host_directory_picker_dialog --> pkg_invariants + pkg_host_directory_picker_native --> pkg_invariants pkg_host_webserver --> pkg_invariants pkg_storage --> pkg_invariants pkg_subprocess --> pkg_invariants @@ -932,7 +932,7 @@ flowchart TD | [`host-apiproxy`](../packages/host/apiproxy) | `host` | [`invariants`](../packages/support/invariants) | | [`host-directory-picker`](../packages/host/directory-picker) | `host` | [`invariants`](../packages/support/invariants) | | [`host-directory-picker-browse`](../packages/host/directory-picker-browse) | `host` | [`invariants`](../packages/support/invariants) | -| [`host-directory-picker-dialog`](../packages/host/directory-picker-dialog) | `host` | [`invariants`](../packages/support/invariants) | +| [`host-directory-picker-native`](../packages/host/directory-picker-native) | `host` | [`invariants`](../packages/support/invariants) | | [`host-webserver`](../packages/host/webserver) | `host` | [`invariants`](../packages/support/invariants) | | [`storage`](../packages/storage/storage) | `storage` | [`invariants`](../packages/support/invariants) | | [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`invariants`](../packages/support/invariants) | diff --git a/packages/client/connection/tests/fake-api.ts b/packages/client/connection/tests/fake-api.ts index 06e62cf7a4..c268c73a90 100644 --- a/packages/client/connection/tests/fake-api.ts +++ b/packages/client/connection/tests/fake-api.ts @@ -62,7 +62,7 @@ export class FakeApiClient implements IApiClient { payload => Promise.resolve(ok({ selected: { provider: payload.provider, model: payload.model } })) onPrompt: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) onCancel: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) - onDescribe: (payload: unknown) => Promise> = + onDescribe: (payload: unknown) => Promise> = () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0, directoryPicker: 'browse' as const })) onPickDirectory: (payload: unknown) => Promise> = () => Promise.resolve(ok({ path: null })) diff --git a/packages/client/runtime/src/client/workspaces/service.ts b/packages/client/runtime/src/client/workspaces/service.ts index 14ecace381..95a0e1c897 100644 --- a/packages/client/runtime/src/client/workspaces/service.ts +++ b/packages/client/runtime/src/client/workspaces/service.ts @@ -180,7 +180,7 @@ export class WorkspacesService { } /** - * Open the Host's native directory picker (the `dialog` capability). + * Open the Host's native directory picker (the `native` capability). * @returns the selected path, or null when the user cancelled. */ async pickDirectory(): Promise { @@ -193,7 +193,7 @@ export class WorkspacesService { /** * The directory-picking interaction the Host composed — the fact the picker - * UI branches on (`dialog` opens the native chooser; `browse` opens the + * UI branches on (`native` opens the native chooser; `browse` opens the * in-app browser). Read per flow open: one describe round trip, no cache to * go stale across reconnects. * @returns the Host's advertised picker kind. diff --git a/packages/client/runtime/tests/fake-api.ts b/packages/client/runtime/tests/fake-api.ts index 98a222d9ae..760f0f88a1 100644 --- a/packages/client/runtime/tests/fake-api.ts +++ b/packages/client/runtime/tests/fake-api.ts @@ -80,7 +80,7 @@ export class FakeApiClient implements IApiClient { payload => Promise.resolve(ok({ selected: { provider: payload.provider, model: payload.model } })) onPrompt: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) onCancel: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) - onDescribe: (payload: unknown) => Promise> = + onDescribe: (payload: unknown) => Promise> = () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0, directoryPicker: 'browse' as const })) onPickDirectory: (payload: unknown) => Promise> = () => Promise.resolve(ok({ path: null })) diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 35cd3c3702..7e0cd9380e 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -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/client/ui-workspace/README.md -README.md: 58aaf56e1953f00417492d766d8f4ae4a0081c81 -README.zh.md: 7c7b33e0ea68fefee8f857cb5e67a36ec5a854f5 +README.md: deaa25184f5ddbfc5980033ce60cef43577ff33c +README.zh.md: e14e8ca6a2e3d65ce5fc403291e45ebc03598e04 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index 58aaf56e19..deaa25184f 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) Shared Workspace picker plugin. `WorkspaceBrowser` is registered into the sidebar's `sidebar.workspaces` slot and `WorkspacePicker` into the page-local Session Intent hero's `conversation.hero.workspace` slot, so both surfaces use the same menu and creation flow. -The picker lists real Host Workspace entities through the global `useWorkspaces` hook. Selecting a Workspace invokes the slot owner's `onPick` callback to retarget the frontend Session object. The flat **Open local folder...** action renders only when the Host advertises the `dialog` picker interaction (read per flow open through `host.describe`); `browse` — until its in-app browser UI lands — and unknown kinds hide the entry, the seam's documented default. When shown, it delegates to the Host's native single-directory picker, adopts a returned path through the object layer, and selects the committed Workspace only after its list projection has refreshed; cancellation is silent, and errors remain retryable. **Create a new workspace** retains the name dialog and disables names already present in that list, while the Host remains authoritative for concurrent or non-UI callers. The runtime Session and Workspace services own materialization. The Workspace row's Delete action opens a confirmation that states the retention boundary, blocks duplicate submission, and keeps failures open; success removes the group while its Sessions remain under Ungrouped. +The picker lists real Host Workspace entities through the global `useWorkspaces` hook. Selecting a Workspace invokes the slot owner's `onPick` callback to retarget the frontend Session object. The flat **Open local folder...** action renders only when the Host advertises the `native` picker interaction (read per flow open through `host.describe`); `browse` — until its in-app browser UI lands — and unknown kinds hide the entry, the seam's documented default. When shown, it delegates to the Host's native single-directory picker, adopts a returned path through the object layer, and selects the committed Workspace only after its list projection has refreshed; cancellation is silent, and errors remain retryable. **Create a new workspace** retains the name dialog and disables names already present in that list, while the Host remains authoritative for concurrent or non-UI callers. The runtime Session and Workspace services own materialization. The Workspace row's Delete action opens a confirmation that states the retention boundary, blocks duplicate submission, and keeps failures open; success removes the group while its Sessions remain under Ungrouped. Both target slots are declared by other plugins, so `apply` registers through declaration-aware deferral and re-registers after a declaring slot is restored. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index 7c7b33e0ea..e14e8ca6a2 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -4,7 +4,7 @@ 共享 Workspace 选择器插件。`WorkspaceBrowser` 注册到侧边栏的 `sidebar.workspaces` slot,`WorkspacePicker` 注册到页面局部 Session Intent 主视觉区的 `conversation.hero.workspace` slot,因此两个表层使用同一菜单和创建流程。 -该选择器通过全局 `useWorkspaces` hook 列出真实的 Host Workspace 实体。选择 Workspace 会调用 slot owner 的 `onPick` 回调,重新定位前端 Session 对象。平铺显示的 **打开本地文件夹…** 操作仅在 Host 广播 `dialog` 选择交互时渲染(每次流程打开时通过 `host.describe` 读取);`browse`(在其应用内浏览器 UI 落地之前)以及未知 kind 都会隐藏该入口,即 seam 文档化的默认行为。显示时它会委托 Host 的原生单目录选择器,通过对象层接纳返回的路径,并等待 Workspace 列表投影刷新后才选中已提交的 Workspace;取消操作不会显示提示,发生错误后仍可重试。**创建新工作区** 操作保留名称对话框,并禁用列表中已有的名称,而 Host 对并发或非 UI 调用方仍具有最终决定权。运行时 Session 与 Workspace 服务负责物化。Workspace 行内的 Delete 操作会打开确认框,说明保留边界、阻止重复提交,并在失败时保持打开;成功后,该分组会被移除,其 Session 则留在 Ungrouped 下。 +该选择器通过全局 `useWorkspaces` hook 列出真实的 Host Workspace 实体。选择 Workspace 会调用 slot owner 的 `onPick` 回调,重新定位前端 Session 对象。平铺显示的 **打开本地文件夹…** 操作仅在 Host 广播 `native` 选择交互时渲染(每次流程打开时通过 `host.describe` 读取);`browse`(在其应用内浏览器 UI 落地之前)以及未知 kind 都会隐藏该入口,即 seam 文档化的默认行为。显示时它会委托 Host 的原生单目录选择器,通过对象层接纳返回的路径,并等待 Workspace 列表投影刷新后才选中已提交的 Workspace;取消操作不会显示提示,发生错误后仍可重试。**创建新工作区** 操作保留名称对话框,并禁用列表中已有的名称,而 Host 对并发或非 UI 调用方仍具有最终决定权。运行时 Session 与 Workspace 服务负责物化。Workspace 行内的 Delete 操作会打开确认框,说明保留边界、阻止重复提交,并在失败时保持打开;成功后,该分组会被移除,其 Session 则留在 Ungrouped 下。 两个目标 slot 都由其他插件声明,因此 `apply` 通过声明感知的延迟机制完成注册,并在声明该 slot 的插件恢复后重新注册。 diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx index 786c5cf305..7acb958845 100644 --- a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -72,31 +72,31 @@ export function WorkspaceCreateFlow({ const duplicateWorkspaceName = !creating && normalizedWorkspaceName !== '' && workspaces.some(workspace => workspace.title === normalizedWorkspaceName) - // The advertised interaction gates the picking affordance: 'dialog' is the + // The advertised interaction gates the picking affordance: 'native' is the // only kind pickDirectory() can serve, so its entry renders under that kind // alone; 'browse' (until the in-app browser UI lands) and unknown kinds // hide the entry, the seam's documented unknown-kind default. Re-read per // flow open — no cache to go stale across reconnects. - const [dialogPicker, setDialogPicker] = useState(false) + const [nativePicker, setNativePicker] = useState(false) useEffect(() => { if (!open) { // Close discards the answer: a reconnect or HMR can swap the composed // backend while the menu is closed, and the reopened menu must never // paint the previous host's entry before the fresh read lands. - setDialogPicker(false) + setNativePicker(false) return } // Reset before each read: the injected reader can also change identity // while the flow stays open, and that prior answer must not leak either; // a settlement from a superseded read is discarded via the // cleanup-toggled flag. - setDialogPicker(false) + setNativePicker(false) let stale = false void directoryPickerKind() - .then((kind) => { if (!stale) setDialogPicker(kind === 'dialog') }) + .then((kind) => { if (!stale) setNativePicker(kind === 'native') }) // A failed describe hides the entry too: the same Host that cannot // answer describe cannot serve pickDirectory. - .catch(() => { if (!stale) setDialogPicker(false) }) + .catch(() => { if (!stale) setNativePicker(false) }) return () => { stale = true } }, [open, directoryPickerKind]) @@ -108,7 +108,7 @@ export function WorkspaceCreateFlow({ disabled: pickingFolder, })), ...(workspaces.length > 0 ? [{ type: 'separator' as const, id: 'sep-create' }] : []), - ...(dialogPicker + ...(nativePicker ? [{ id: OPEN_LOCAL_FOLDER, label: 'Open local folder…', icon: , disabled: pickingFolder }] : []), { id: CREATE_NEW, label: 'Create a new workspace', icon: , disabled: pickingFolder }, diff --git a/packages/client/ui-workspace/tests/apply.spec.ts b/packages/client/ui-workspace/tests/apply.spec.ts index f9a5884206..e670a05e9b 100644 --- a/packages/client/ui-workspace/tests/apply.spec.ts +++ b/packages/client/ui-workspace/tests/apply.spec.ts @@ -15,7 +15,7 @@ async function bench() { title: 'new', sessionIds: [], createdAt: '0', updatedAt: '0', })) const pickDirectory = vi.fn(async () => '/tmp/picked') - const directoryPickerKind = vi.fn(async () => 'dialog' as const) + const directoryPickerKind = vi.fn(async () => 'native' as const) const startSession = vi.fn() const rename = vi.fn(async () => ({})) const insertSessionBefore = vi.fn(async () => ({})) diff --git a/packages/client/ui-workspace/tests/workspace-browser.spec.tsx b/packages/client/ui-workspace/tests/workspace-browser.spec.tsx index 779ad0b37a..6079416d30 100644 --- a/packages/client/ui-workspace/tests/workspace-browser.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-browser.spec.tsx @@ -60,7 +60,7 @@ function mount(overrides: Partial = {}) { insertSessionBefore: vi.fn(async () => {}), createWorkspace: vi.fn(async () => workspace('created', [])), pickDirectory: vi.fn(async () => null), - directoryPickerKind: vi.fn(async () => 'dialog' as const), + directoryPickerKind: vi.fn(async () => 'native' as const), ...overrides, } const view = render() diff --git a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx index d8b3ab5a54..fadf1cdebf 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx @@ -39,7 +39,7 @@ function mount( items: readonly WorkspaceView[] = [workspace('alpha', 'Alpha')], createWorkspace = vi.fn(), pickDirectory = vi.fn(async () => null as string | null), - directoryPickerKind = vi.fn(async () => 'dialog'), + directoryPickerKind = vi.fn(async () => 'native'), ) { const onPick = vi.fn() const onClose = vi.fn() @@ -221,7 +221,7 @@ describe('WorkspacePicker', () => { 'dialog')} + directoryPickerKind={vi.fn(async () => 'native')} />, ) expect(screen.queryByRole('menu')).toBeNull() @@ -235,7 +235,7 @@ describe('WorkspacePicker', () => { 'dialog')} + directoryPickerKind={vi.fn(async () => 'native')} />, ) expect(screen.getByRole('status').textContent).toBe('Loading workspaces…') @@ -258,7 +258,7 @@ describe('WorkspacePicker', () => { }) it('does not read the picker kind while the flow is closed', () => { - const directoryPickerKind = vi.fn(async () => 'dialog') + const directoryPickerKind = vi.fn(async () => 'native') render( { .mockImplementationOnce(() => first) .mockImplementation(async () => 'browse') const t = togglable(directoryPickerKind) - // Close while the first read is in flight, then let it answer 'dialog': + // Close while the first read is in flight, then let it answer 'native': // the settlement is stale and must not leak into the next open. t.setOpen(false) - await act(async () => { resolveFirst('dialog') }) + await act(async () => { resolveFirst('native') }) t.setOpen(true) await screen.findByRole('menuitem', { name: 'Create a new workspace' }) await waitFor(() => { expect(directoryPickerKind).toHaveBeenCalledTimes(2) }) @@ -302,7 +302,7 @@ describe('WorkspacePicker', () => { it('clears the advertised kind on close so a reopen cannot paint the previous host entry', async () => { const directoryPickerKind = vi.fn<() => Promise>() - .mockImplementationOnce(async () => 'dialog') + .mockImplementationOnce(async () => 'native') // The reopened read never settles: the assertion below sees the paint // that precedes any fresh answer. .mockImplementation(() => new Promise(() => {})) @@ -319,7 +319,7 @@ describe('WorkspacePicker', () => { const first = new Promise((_settle, reject) => { rejectFirst = reject }) const directoryPickerKind = vi.fn<() => Promise>() .mockImplementationOnce(() => first) - .mockImplementation(async () => 'dialog') + .mockImplementation(async () => 'native') const t = togglable(directoryPickerKind) t.setOpen(false) t.setOpen(true) diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index 698dd32201..148727968c 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -1605,15 +1605,15 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'DirectoryPickerCapabilities', - declaration: 'export interface DirectoryPickerCapabilities {\n dialog: DirectoryPickerDialogCapability;\n browse: DirectoryPickerBrowseCapability;\n}', + declaration: 'export interface DirectoryPickerCapabilities {\n native: DirectoryPickerNativeCapability;\n browse: DirectoryPickerBrowseCapability;\n}', }, { name: 'DirectoryPickerCapability', declaration: 'export type DirectoryPickerCapability = DirectoryPickerCapabilities[keyof DirectoryPickerCapabilities];', }, { - name: 'DirectoryPickerDialogCapability', - declaration: 'export interface DirectoryPickerDialogCapability {\n kind: \'dialog\';\n pick(signal: AbortSignal): Promise;\n}', + name: 'DirectoryPickerNativeCapability', + declaration: 'export interface DirectoryPickerNativeCapability {\n kind: \'native\';\n pick(signal: AbortSignal): Promise;\n}', }, { name: 'Domain', diff --git a/packages/host/README.i18n.yaml b/packages/host/README.i18n.yaml index 9421dce1c5..f50948eb6d 100644 --- a/packages/host/README.i18n.yaml +++ b/packages/host/README.i18n.yaml @@ -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/README.md -README.md: 81c483674c0d30847318b8fd9014bd8bb7d341c2 -README.zh.md: 8b5ecd89ff4b1407cfa8c2bad63c77412b5fd16c +README.md: 0810be58fc773a241528656d7f6e826e9c3aabda +README.zh.md: f9133eee8498594d913b2fe0814ac51d712b678d diff --git a/packages/host/README.md b/packages/host/README.md index 81c483674c..0810be58fc 100644 --- a/packages/host/README.md +++ b/packages/host/README.md @@ -8,8 +8,8 @@ The host side of the dsh web GUI: the API gateway every client shape shares, and |---|---|---| | `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 `dialog`/`browse` capability the gateway's picker RPCs delegate to | `ctx.directoryPicker` | -| `directory-picker-dialog/` | Native-OS-chooser backend (osascript / PowerShell / Zenity+KDialog); host-display only | (registers `ctx.directoryPicker`) | +| `directory-picker/` | Workspace-directory picking seam: discriminated `native`/`browse` capability the gateway's picker RPCs delegate to | `ctx.directoryPicker` | +| `directory-picker-native/` | Native-OS-chooser backend (osascript / PowerShell / Zenity+KDialog); host-display only | (registers `ctx.directoryPicker`) | | `directory-picker-browse/` | In-app browsing backend: listing/creation primitives over Node stdlib; remote-capable | (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. diff --git a/packages/host/README.zh.md b/packages/host/README.zh.md index 8b5ecd89ff..f9133eee84 100644 --- a/packages/host/README.zh.md +++ b/packages/host/README.zh.md @@ -8,8 +8,8 @@ dsh web GUI 的宿主侧:所有客户端形态共用的 API 网关,以及承 |---|---|---| | `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 委托的可辨识 `dialog`/`browse` 能力 | `ctx.directoryPicker` | -| `directory-picker-dialog/` | 原生 OS 选择器后端(osascript/PowerShell/Zenity+KDialog);仅宿主屏幕可用 | (注册 `ctx.directoryPicker`) | +| `directory-picker/` | 工作区目录选择 seam:网关的 picker RPC 委托的可辨识 `native`/`browse` 能力 | `ctx.directoryPicker` | +| `directory-picker-native/` | 原生 OS 选择器后端(osascript/PowerShell/Zenity+KDialog);仅宿主屏幕可用 | (注册 `ctx.directoryPicker`) | | `directory-picker-browse/` | 应用内浏览后端:基于 Node 标准库的列举/创建原语;支持远程 | (注册 `ctx.directoryPicker`) | `apiproxy` 在设计上与传输方式无关——它不注册任何路由;载体自行包装 `ctx.apiProxy`。HTTP 载体路由(连同其 `/api` 浏览器信任栅栏)由 [`client/connection`](../client/connection/README.md) 的 node 半侧挂载,这正是该包住在 client 组的原因:它拥有这条线的两端。 diff --git a/packages/host/apiproxy/README.i18n.yaml b/packages/host/apiproxy/README.i18n.yaml index 55fe86c794..7bc4e88049 100644 --- a/packages/host/apiproxy/README.i18n.yaml +++ b/packages/host/apiproxy/README.i18n.yaml @@ -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: 7c53e6dc9ac5758fce91d8b39abbfab6641384d1 -README.zh.md: 5089935fe545bfc6ac3ddb39b9a2a25b50e1ceab +README.md: 8db8a1b77913677d88dbbbfbdbfc28a90c0d0415 +README.zh.md: 1f957223bb98afb65ab8a313c49b58c701e42be0 diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index 7c53e6dc9a..8db8a1b779 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.md @@ -16,7 +16,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()`. -Directory picking delegates to the composed `ctx.directoryPicker` backend ([the directory-picker seam](../directory-picker/README.md)); `host.describe.directoryPicker` advertises the capability kind the client renders for, and a method called outside the advertised kind fails with `directory-picker-unavailable`. Under `dialog`, `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. +Directory picking delegates to the composed `ctx.directoryPicker` backend ([the directory-picker seam](../directory-picker/README.md)); `host.describe.directoryPicker` advertises the capability kind the client renders for, and a method called outside the advertised kind fails with `directory-picker-unavailable`. 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. `session.history` pages on message boundaries, and its tail page (no `beforeSeq`) carries two session-level extras the page window cannot supply: the in-flight partial's chunk events, and `todos` — the latest `todo/write` whole-list projection over the full log. Older pages omit `todos` because the projection is session-level, not per-page; a tail response that omits it means the whole log holds no `todo/write`, so clients read the absent field as the empty plan rather than as unchanged state. @@ -39,4 +39,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** — under the `dialog` capability, `host.pickDirectory` reports an actionable error when neither Zenity nor KDialog is installed; the browse backend is the composition-level fallback (see the [dialog backend README](../directory-picker-dialog/README.md)). +- **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)). diff --git a/packages/host/apiproxy/README.zh.md b/packages/host/apiproxy/README.zh.md index 5089935fe5..1f957223bb 100644 --- a/packages/host/apiproxy/README.zh.md +++ b/packages/host/apiproxy/README.zh.md @@ -16,7 +16,7 @@ mux 流会在每个已附加会话的订阅基线之后,以及对应的实时 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()` 中。 -目录选择委托给组合的 `ctx.directoryPicker` 后端([目录选择 seam](../directory-picker/README.md));`host.describe.directoryPicker` 广播客户端应按其渲染的能力 kind,调用广播之外的方法会以 `directory-picker-unavailable` 失败。在 `dialog` 下,`host.pickDirectory` 打开一个原生选择器并返回选中路径(取消为 `null`);该方法需等待用户完成操作,是唯一不受默认 30 秒超时限制的一元调用,调用方与连接的中止仍会传播至原生进程。在 `browse` 下,`host.listDirectory` 返回一个按名称排序的目录层级,携带面包屑祖先链、`home` 锚点与宿主判定的 `hidden` 标志(不带路径即家目录),`host.createDirectory` 创建一个经校验的子段;后端的类型化失败 1:1 映射为 `directory-unreadable`/`directory-exists`/`directory-create-failed` 错误码。浏览器载体的前缀级信任栅栏(dsh-client-connection)像覆盖其他所有 `/api` 请求一样覆盖上述全部方法。 +目录选择委托给组合的 `ctx.directoryPicker` 后端([目录选择 seam](../directory-picker/README.md));`host.describe.directoryPicker` 广播客户端应按其渲染的能力 kind,调用广播之外的方法会以 `directory-picker-unavailable` 失败。在 `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` 请求一样覆盖上述全部方法。 `session.history` 按消息边界分页,其尾页(不带 `beforeSeq`)额外携带两项页窗口本身无法提供的会话级数据:进行中局部消息的 chunk 事件,以及 `todos`——整份日志上最后一次 `todo/write` 的整表投影。较早的页面不带 `todos`,因为该投影是会话级而非分页级的;尾页响应缺少该字段意味着整份日志中没有任何 `todo/write`,因此客户端要把缺失字段读作空计划,而不是读作「状态未变」。 @@ -39,4 +39,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 原生选择器依赖桌面工具**:在 `dialog` 能力下,Zenity 和 KDialog 均未安装时,`host.pickDirectory` 会给出包含解决建议的错误提示;组合层面的回退是 browse 后端(见 [dialog 后端 README](../directory-picker-dialog/README.md))。 +- **Linux 原生选择器依赖桌面工具**:在 `native` 能力下,Zenity 和 KDialog 均未安装时,`host.pickDirectory` 会给出包含解决建议的错误提示;组合层面的回退是 browse 后端(见 [native 后端 README](../directory-picker-native/README.md))。 diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index 6e302e3e57..29874f10f8 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -1002,10 +1002,10 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro async pickDirectory(request, signal) { const capability = ctx.directoryPicker.capability() - if (capability.kind !== 'dialog') { + if (capability.kind !== 'native') { return err(request, { code: 'directory-picker-unavailable', - message: `host.pickDirectory needs the dialog capability; the composed picker serves "${capability.kind}"`, + message: `host.pickDirectory needs the native capability; the composed picker serves "${capability.kind}"`, details: { capability: capability.kind }, }) } diff --git a/packages/host/apiproxy/src/api/host.ts b/packages/host/apiproxy/src/api/host.ts index 3de58b7bc7..872c3ae3c3 100644 --- a/packages/host/apiproxy/src/api/host.ts +++ b/packages/host/apiproxy/src/api/host.ts @@ -7,7 +7,7 @@ import type { RpcRequest, RpcResponse } from './rpc.ts' /** * The composed directory-picker interaction the host serves (mirror of the - * `ctx.directoryPicker` capability kind): `dialog` = one native OS chooser on + * `ctx.directoryPicker` capability kind): `native` = one OS chooser on * the host display (`host.pickDirectory`); `browse` = in-app listing/creation * primitives (`host.listDirectory`/`host.createDirectory`). Calling a method * outside the advertised kind fails with `directory-picker-unavailable`. @@ -15,7 +15,7 @@ import type { RpcRequest, RpcResponse } from './rpc.ts' * capability advertises before its RPCs exist); the client's documented * default for a kind it does not recognize is to hide the picking affordance. */ -export type DirectoryPickerKind = 'dialog' | 'browse' | (string & {}) +export type DirectoryPickerKind = 'native' | 'browse' | (string & {}) /** One directory row of a listing: a child entry or a breadcrumb ancestor. */ export interface DirectoryEntry { @@ -64,7 +64,7 @@ export interface HostApi { /** * Open the operating system's single-directory picker; cancellation returns - * null. Only served under the `dialog` capability. + * null. Only served under the `native` capability. */ pickDirectory( request: RpcRequest<{}>, diff --git a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts index 9572c76b23..653c0b2398 100644 --- a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts @@ -59,7 +59,7 @@ 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-'))), - picker: DirectoryPickerCapability = { kind: 'dialog', pick: async () => null }, + picker: DirectoryPickerCapability = { kind: 'native', pick: async () => null }, ) { const ctx = new Context() await ctx.plugin(SessionStore) @@ -107,19 +107,19 @@ async function harness( } describe('host.pickDirectory', () => { - it('returns a selected path or explicit cancellation from the dialog capability', async () => { - const selected = await harness(undefined, { kind: 'dialog', pick: 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, { kind: 'dialog', pick: 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 dialog capability as a cancelled RPC error', async () => { + it('propagates abort into the native capability as a cancelled RPC error', async () => { const { api } = await harness(undefined, { - kind: 'dialog', + kind: 'native', pick: signal => new Promise((_resolve, reject) => { signal.addEventListener('abort', () => { reject(new Error('aborted')) }, { once: true }) }), @@ -130,13 +130,13 @@ describe('host.pickDirectory', () => { expect((await pending).result).toMatchObject({ ok: false, error: { code: 'cancelled' } }) }) - it('folds a non-abort dialog failure into an internal error', async () => { - const { api } = await harness(undefined, { kind: 'dialog', pick: async () => { throw new Error('no chooser installed') } }) + 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 dialog RPC under a browse composition', async () => { + 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({ @@ -190,14 +190,14 @@ describe('host.listDirectory / host.createDirectory', () => { }) }) - it('refuses the browse RPCs under a dialog composition and advertises the kind in describe', async () => { + it('refuses the browse RPCs under a native composition and advertises the kind in describe', async () => { const { api } = await harness() - expect((await api.host.describe(request({}))).result).toMatchObject({ ok: true, value: { directoryPicker: 'dialog' } }) + expect((await api.host.describe(request({}))).result).toMatchObject({ ok: true, value: { directoryPicker: 'native' } }) expect((await api.host.listDirectory(request({}))).result).toMatchObject({ - ok: false, error: { code: 'directory-picker-unavailable', details: { capability: 'dialog' } }, + 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: 'dialog' } }, + ok: false, error: { code: 'directory-picker-unavailable', details: { capability: 'native' } }, }) const browse = await harness(undefined, BROWSE_STUB) expect((await browse.api.host.describe(request({}))).result).toMatchObject({ ok: true, value: { directoryPicker: 'browse' } }) diff --git a/packages/host/apiproxy/tests/fetch-carrier.spec.ts b/packages/host/apiproxy/tests/fetch-carrier.spec.ts index 6340e4e2e7..4211c5cb9c 100644 --- a/packages/host/apiproxy/tests/fetch-carrier.spec.ts +++ b/packages/host/apiproxy/tests/fetch-carrier.spec.ts @@ -75,7 +75,7 @@ function fakeApi(overrides: Partial<{ muxFrames: MuxFrame[]; hostFrames: HostFra }, host: { async describe(request) { - return { rpcId: request.rpcId, result: { ok: true, value: { version: 'v', cwd: '/w', attachedSessions: 0, directoryPicker: 'dialog' as const } } } + return { rpcId: request.rpcId, result: { ok: true, value: { version: 'v', cwd: '/w', attachedSessions: 0, directoryPicker: 'native' as const } } } }, async pickDirectory(request) { return { rpcId: request.rpcId, result: { ok: true, value: { path: null } } } diff --git a/packages/host/apiproxy/tests/rpc-schemas.spec.ts b/packages/host/apiproxy/tests/rpc-schemas.spec.ts index 939de7677e..2923b4d739 100644 --- a/packages/host/apiproxy/tests/rpc-schemas.spec.ts +++ b/packages/host/apiproxy/tests/rpc-schemas.spec.ts @@ -208,7 +208,7 @@ describe('sessions domain schemas', () => { describe('host domain schemas', () => { it('validates describe request/value', () => { expect(hostDescribeRequestSchema.parse({})).toEqual({}) - const value = hostDescribeValueSchema.parse({ version: '1', cwd: '/x', provider: 'p', model: 'm', attachedSessions: 2, directoryPicker: 'dialog' }) + const value = hostDescribeValueSchema.parse({ version: '1', cwd: '/x', provider: 'p', model: 'm', attachedSessions: 2, directoryPicker: 'native' }) expect(value.attachedSessions).toBe(2) expect(hostDescribeValueSchema.parse({ version: '1', cwd: '/x', attachedSessions: 0, directoryPicker: 'browse' }).provider).toBeUndefined() // A kind beyond the two with methods survives the wire (merge-added diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index e41ef9a0ae..34c3e35a79 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/directory-picker-browse/README.md -README.md: 9655fdb538da1addb4d10dbee6210965400394c8 -README.zh.md: 1c7b0c36cbb73286f3d4e6a48748c4415f9ff0e4 +README.md: 688a60894cb0ab066a6d501e4df310f8d31bfb5f +README.zh.md: c19bccc2ff9268cb7a6c931da4671bebc9f76b0c diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index 9655fdb538..688a60894c 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -2,7 +2,7 @@ English | [中文](README.zh.md) -The **in-app browsing backend** of the [directory-picker seam](../directory-picker/README.md): `BrowseDirectoryPicker` registers `ctx.directoryPicker` with the `browse` capability — one-level directory listing and child-directory creation over Node's stdlib, which already carries the per-OS adaptation. Nothing renders on the host display, so this backend serves remote clients the dialog backend cannot. +The **in-app browsing backend** of the [directory-picker seam](../directory-picker/README.md): `BrowseDirectoryPicker` registers `ctx.directoryPicker` with the `browse` capability — one-level directory listing and child-directory creation over Node's stdlib, which already carries the per-OS adaptation. Nothing renders on the host display, so this backend serves remote clients the native backend cannot. Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject an explicit path that is not fully qualified — relative forms, and on Windows the rooted drive-less forms (`\foo`, `/foo`) and incomplete UNC prefixes (`\\`, `\\server`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index 1c7b0c36cb..c19bccc2ff 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -[目录选择 seam](../directory-picker/README.md) 的**应用内浏览后端**:`BrowseDirectoryPicker` 以 `browse` 能力注册 `ctx.directoryPicker`——基于 Node 标准库(跨 OS 适配本就由它承担)提供单层目录列举与子目录创建。宿主屏幕上不渲染任何东西,因此该后端能服务 dialog 后端无法触及的远程客户端。 +[目录选择 seam](../directory-picker/README.md) 的**应用内浏览后端**:`BrowseDirectoryPicker` 以 `browse` 能力注册 `ctx.directoryPicker`——基于 Node 标准库(跨 OS 适配本就由它承担)提供单层目录列举与子目录创建。宿主屏幕上不渲染任何东西,因此该后端能服务 native 后端无法触及的远程客户端。 行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo`、`/foo`)与不完整的 UNC 前缀(`\\`、`\\server`)——报 `directory-unreadable`/`directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 diff --git a/packages/host/directory-picker-dialog/README.md b/packages/host/directory-picker-dialog/README.md deleted file mode 100644 index fe07303557..0000000000 --- a/packages/host/directory-picker-dialog/README.md +++ /dev/null @@ -1,17 +0,0 @@ -# @deepseek-ai/dsh-host-directory-picker-dialog - -English | [中文](README.zh.md) - -The **native-OS-dialog backend** of the [directory-picker seam](../directory-picker/README.md): `DialogDirectoryPicker` registers `ctx.directoryPicker` with the `dialog` 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. - -## 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). diff --git a/packages/host/directory-picker-dialog/README.i18n.yaml b/packages/host/directory-picker-native/README.i18n.yaml similarity index 68% rename from packages/host/directory-picker-dialog/README.i18n.yaml rename to packages/host/directory-picker-native/README.i18n.yaml index 3cd3d36702..c67ecdce91 100644 --- a/packages/host/directory-picker-dialog/README.i18n.yaml +++ b/packages/host/directory-picker-native/README.i18n.yaml @@ -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 packages/host/directory-picker-dialog/README.md -README.md: fe07303557da6b27bb89eb761efba5555c4308c0 -README.zh.md: 214259264d5385ddad1ea6425149c53e31de55d0 +# pnpm run verify-translation-pairing --write packages/host/directory-picker-native/README.md +README.md: 8e9d6c7c558a6b33c2a37d504c571fd3eda579bb +README.zh.md: 68f23698ff0c1a5ee4456a1f121dcf244f09c72b diff --git a/packages/host/directory-picker-native/README.md b/packages/host/directory-picker-native/README.md new file mode 100644 index 0000000000..8e9d6c7c55 --- /dev/null +++ b/packages/host/directory-picker-native/README.md @@ -0,0 +1,17 @@ +# @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. + +## 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). diff --git a/packages/host/directory-picker-dialog/README.zh.md b/packages/host/directory-picker-native/README.zh.md similarity index 90% rename from packages/host/directory-picker-dialog/README.zh.md rename to packages/host/directory-picker-native/README.zh.md index 214259264d..68f23698ff 100644 --- a/packages/host/directory-picker-dialog/README.zh.md +++ b/packages/host/directory-picker-native/README.zh.md @@ -1,8 +1,8 @@ -# @deepseek-ai/dsh-host-directory-picker-dialog +# @deepseek-ai/dsh-host-directory-picker-native [English](README.md) | 中文 -[目录选择 seam](../directory-picker/README.md) 的**原生 OS 对话框后端**:`DialogDirectoryPicker` 以 `dialog` 能力注册 `ctx.directoryPicker`,其 `pick(signal)` 每次调用打开一个原生选择器并解析出所选绝对路径(取消时为 `null`)。平台工具不经 shell 调用:macOS 使用 `osascript`,Windows 使用以 STA 模式运行的 PowerShell `FolderBrowserDialog`,Linux 使用 Zenity 并以 KDialog 回退;调用方的中止信号会终止原生进程。只有操作者坐在宿主屏幕前时才可用——远程部署应组合 [`-browse`](../directory-picker-browse/README.md)。命令边界(`DirectoryPickerRunner`)与平台事实可注入,便于确定性测试。 +[目录选择 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`)与平台事实可注入,便于确定性测试。 ## 模型体验 diff --git a/packages/host/directory-picker-dialog/package.json b/packages/host/directory-picker-native/package.json similarity index 83% rename from packages/host/directory-picker-dialog/package.json rename to packages/host/directory-picker-native/package.json index 94b22e6feb..8db5d3a9df 100644 --- a/packages/host/directory-picker-dialog/package.json +++ b/packages/host/directory-picker-native/package.json @@ -1,6 +1,6 @@ { - "name": "@deepseek-ai/dsh-host-directory-picker-dialog", - "description": "Native-OS-dialog backend of the directory-picker seam for the DeepSeek Harness web GUI host", + "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", diff --git a/packages/host/directory-picker-dialog/src/index.ts b/packages/host/directory-picker-native/src/index.ts similarity index 64% rename from packages/host/directory-picker-dialog/src/index.ts rename to packages/host/directory-picker-native/src/index.ts index bc9814a5e7..f131c8bb0c 100644 --- a/packages/host/directory-picker-dialog/src/index.ts +++ b/packages/host/directory-picker-native/src/index.ts @@ -1,11 +1,11 @@ /** - * Dialog backend of the directory-picker seam: registers `ctx.directoryPicker` - * with the `dialog` capability, opening one native OS chooser on the host + * 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-dialog + * @module @deepseek-ai/dsh-host-directory-picker-native */ import { DirectoryPicker } from '@deepseek-ai/dsh-host-directory-picker' @@ -15,19 +15,19 @@ import { pickNativeDirectory } from './native-picker.ts' export type { DirectoryPickerInternals, DirectoryPickerRunner } from './native-picker.ts' export { pickNativeDirectory } from './native-picker.ts' -/** The `ctx.directoryPicker` dialog implementation (stable capability object per service life). */ -export default class DialogDirectoryPicker extends DirectoryPicker { - private readonly dialogCapability: DirectoryPickerCapability = { - kind: 'dialog', +/** 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 dialog interaction capability. - * @returns the stable `dialog` capability object. + * The native interaction capability. + * @returns the stable `native` capability object. */ capability(): DirectoryPickerCapability { - return this.dialogCapability + return this.nativeCapability } } diff --git a/packages/host/directory-picker-dialog/src/invariant.ts b/packages/host/directory-picker-native/src/invariant.ts similarity index 63% rename from packages/host/directory-picker-dialog/src/invariant.ts rename to packages/host/directory-picker-native/src/invariant.ts index cbd3e63517..777acd57dd 100644 --- a/packages/host/directory-picker-dialog/src/invariant.ts +++ b/packages/host/directory-picker-native/src/invariant.ts @@ -1,23 +1,23 @@ /** - * Package-owned invariant companion for the dialog directory-picker backend. - * @module @deepseek-ai/dsh-host-directory-picker-dialog/invariant + * 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-dialog' +const PACKAGE_NAME = '@deepseek-ai/dsh-host-directory-picker-native' /** Cordis companion plugin name. */ -export const name = 'host-directory-picker-dialog-invariant' +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 dialog outcome is only the returned path. */ +/** No runtime invariant: each pick is one stateless subprocess round trip; the chooser outcome is only the returned path. */ const install: InvariantInstaller = () => {} /** - * Register the dialog directory-picker invariant companion. + * Register the native directory-picker invariant companion. * @param ctx - Cordis context carrying the invariant service. * @returns the installed registration's disposer after setup succeeds. */ diff --git a/packages/host/directory-picker-dialog/src/native-picker.ts b/packages/host/directory-picker-native/src/native-picker.ts similarity index 100% rename from packages/host/directory-picker-dialog/src/native-picker.ts rename to packages/host/directory-picker-native/src/native-picker.ts diff --git a/packages/host/directory-picker-dialog/tests/native-picker.spec.ts b/packages/host/directory-picker-native/tests/native-picker.spec.ts similarity index 100% rename from packages/host/directory-picker-dialog/tests/native-picker.spec.ts rename to packages/host/directory-picker-native/tests/native-picker.spec.ts diff --git a/packages/host/directory-picker-dialog/tests/service.spec.ts b/packages/host/directory-picker-native/tests/service.spec.ts similarity index 57% rename from packages/host/directory-picker-dialog/tests/service.spec.ts rename to packages/host/directory-picker-native/tests/service.spec.ts index f56f93ec41..61b5adddaf 100644 --- a/packages/host/directory-picker-dialog/tests/service.spec.ts +++ b/packages/host/directory-picker-native/tests/service.spec.ts @@ -1,18 +1,18 @@ -/** Registration/capability behavior of the dialog backend (the seam's cordis half). */ +/** Registration/capability behavior of the native backend (the seam's cordis half). */ import { describe, expect, it } from 'vitest' import { Context } from 'cordis' -import DialogDirectoryPicker from '../src/index.ts' +import NativeDirectoryPicker from '../src/index.ts' -describe('DialogDirectoryPicker', () => { - it('registers ctx.directoryPicker with a stable dialog capability and leaves with its fiber', async () => { +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(DialogDirectoryPicker) + const fiber = ctx.plugin(NativeDirectoryPicker) await fiber.await() const picker = ctx.get('directoryPicker') - expect(picker).toBeInstanceOf(DialogDirectoryPicker) + expect(picker).toBeInstanceOf(NativeDirectoryPicker) const capability = picker!.capability() - expect(capability.kind).toBe('dialog') + expect(capability.kind).toBe('native') // Stability: consumers may capture the capability object across calls. expect(picker!.capability()).toBe(capability) await fiber.dispose() diff --git a/packages/host/directory-picker-dialog/tsconfig.json b/packages/host/directory-picker-native/tsconfig.json similarity index 100% rename from packages/host/directory-picker-dialog/tsconfig.json rename to packages/host/directory-picker-native/tsconfig.json diff --git a/packages/host/directory-picker/README.i18n.yaml b/packages/host/directory-picker/README.i18n.yaml index a331a2caeb..7ba7c09de0 100644 --- a/packages/host/directory-picker/README.i18n.yaml +++ b/packages/host/directory-picker/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/directory-picker/README.md -README.md: 0332f7df067bfa79c7505be948554e814a690c6c -README.zh.md: a9a782019d0badfba33a7d108113ff5323fde77a +README.md: dcac8903522d53a8dd5fd346f124071f0f24b38e +README.zh.md: 5b7fc15513bf19722bd71bcbb30c6d187d6a71f5 diff --git a/packages/host/directory-picker/README.md b/packages/host/directory-picker/README.md index 0332f7df06..dcac890352 100644 --- a/packages/host/directory-picker/README.md +++ b/packages/host/directory-picker/README.md @@ -2,7 +2,7 @@ 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: 'dialog', pick(signal) }` opens one native OS chooser on the host display ([`-dialog`](../directory-picker-dialog/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 dialog 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 **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. 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). diff --git a/packages/host/directory-picker/README.zh.md b/packages/host/directory-picker/README.zh.md index a9a782019d..5b7fc15513 100644 --- a/packages/host/directory-picker/README.zh.md +++ b/packages/host/directory-picker/README.zh.md @@ -2,7 +2,7 @@ [English](README.md) | 中文 -web GUI 宿主的**工作区目录选择 seam**:抽象服务 `DirectoryPicker`(`ctx.directoryPicker`),唯一契约方法 `capability()` 返回一个可辨识能力对象,描述操作者以何种方式选择目录。后端之间的差异在交互形态而不只是机制,因此 seam 显式建模形态而非统一方法集:`{ kind: 'dialog', pick(signal) }` 在宿主屏幕上打开一个原生 OS 选择器([`-dialog`](../directory-picker-dialog/README.md));`{ kind: 'browse', list(path?), createDirectory(path, name) }` 提供应用内浏览器驱动的列举/创建原语,可服务任何 OS 对话框都触及不到的远程客户端([`-browse`](../directory-picker-browse/README.md))。消费方按 `capability().kind` 分支;联合类型由可合并扩展的 `DirectoryPickerCapabilities` 映射派生(新后端在其中声明合并自己的形态),未知 kind 的文档化默认行为是隐藏选择入口而非失败。能力对象在服务生命周期内必须保持稳定。 +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 的文档化默认行为是隐藏选择入口而非失败。能力对象在服务生命周期内必须保持稳定。 浏览原语以带类型的 `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)。 diff --git a/packages/host/directory-picker/src/index.ts b/packages/host/directory-picker/src/index.ts index 77a63bb568..c96f21d9a6 100644 --- a/packages/host/directory-picker/src/index.ts +++ b/packages/host/directory-picker/src/index.ts @@ -2,7 +2,7 @@ * 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 `dialog` backend opens one native OS chooser on the + * 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 @@ -13,9 +13,9 @@ import { Context, Service } from 'cordis' -/** The dialog interaction: one native OS directory chooser on the host display. */ -export interface DirectoryPickerDialogCapability { - kind: 'dialog' +/** 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. @@ -82,7 +82,7 @@ export interface DirectoryPickerBrowseCapability { * must equal its key) instead of editing this package. */ export interface DirectoryPickerCapabilities { - dialog: DirectoryPickerDialogCapability + native: DirectoryPickerNativeCapability browse: DirectoryPickerBrowseCapability } diff --git a/packages/host/directory-picker/tests/seam.spec.ts b/packages/host/directory-picker/tests/seam.spec.ts index 4e7a799fa4..52722b9b0d 100644 --- a/packages/host/directory-picker/tests/seam.spec.ts +++ b/packages/host/directory-picker/tests/seam.spec.ts @@ -7,7 +7,7 @@ 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: 'dialog', pick: async () => null } + private readonly stub: DirectoryPickerCapability = { kind: 'native', pick: async () => null } capability(): DirectoryPickerCapability { return this.stub } @@ -19,7 +19,7 @@ describe('DirectoryPicker seam', () => { const fiber = ctx.plugin(StubPicker) await fiber.await() expect(ctx.get('directoryPicker')).toBeInstanceOf(StubPicker) - expect(ctx.get('directoryPicker')!.capability().kind).toBe('dialog') + expect(ctx.get('directoryPicker')!.capability().kind).toBe('native') await fiber.dispose() expect(ctx.get('directoryPicker')).toBeUndefined() }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a47a1ea140..317233f440 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -212,9 +212,9 @@ importers: '@deepseek-ai/dsh-host-apiproxy': specifier: workspace:^ version: link:../../packages/host/apiproxy - '@deepseek-ai/dsh-host-directory-picker-dialog': + '@deepseek-ai/dsh-host-directory-picker-native': specifier: workspace:^ - version: link:../../packages/host/directory-picker-dialog + version: link:../../packages/host/directory-picker-native '@deepseek-ai/dsh-host-webserver': specifier: workspace:^ version: link:../../packages/host/webserver @@ -2727,7 +2727,7 @@ importers: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) - packages/host/directory-picker-dialog: + packages/host/directory-picker-native: dependencies: '@deepseek-ai/dsh-host-directory-picker': specifier: workspace:^ diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 1348ba425a..6f96c0c5f8 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -413,9 +413,9 @@ const SERVICE_ROLES: ServiceRole[] = [ pkg: 'directory-picker', title: 'Workspace-directory picking seam', mode: 'seam', - implementations: ['directory-picker-dialog', 'directory-picker-browse'], + implementations: ['directory-picker-native', 'directory-picker-browse'], consumers: ['apiproxy'], - note: 'Discriminated interaction capability: the dialog backend opens one native OS chooser on the host display, the browse backend serves listing/creation primitives for the in-app browser; the gateway advertises the kind via host.describe.', + note: 'Discriminated interaction capability: the native backend opens one OS chooser on the host display, the browse backend serves listing/creation primitives for the in-app browser; the gateway advertises the kind via host.describe.', }, { key: 'httpServer', diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 79100a4c9e..2f621291bc 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -75,7 +75,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/host/apiproxy': { kind: 'none', reason: 'The wire contract and fetch carriers move already-composed messages and register no model surface.' }, 'packages/host/directory-picker': { kind: 'none', reason: 'The GUI-host picking seam registers no model surface.' }, 'packages/host/directory-picker-browse': { kind: 'none', reason: 'The GUI-host picking backend registers no model surface.' }, - 'packages/host/directory-picker-dialog': { kind: 'none', reason: 'The GUI-host picking backend registers no model surface.' }, + 'packages/host/directory-picker-native': { kind: 'none', reason: 'The GUI-host picking backend registers no model surface.' }, 'packages/host/webserver': { kind: 'none', reason: 'The HTTP carrier bridges browser and API handler and registers no model surface.' }, 'packages/llm/llm': { kind: 'none', reason: 'The adapter registry forwards already-assembled requests unchanged.' }, 'packages/llm/token-meter': { kind: 'indirect', reason: 'The measurement service leaves model-visible changes to its consumers.' }, diff --git a/tsconfig.host.json b/tsconfig.host.json index 98a51dda19..eb2609ed4a 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -165,7 +165,7 @@ { "path": "./packages/host/apiproxy" }, { "path": "./packages/host/directory-picker" }, { "path": "./packages/host/directory-picker-browse" }, - { "path": "./packages/host/directory-picker-dialog" }, + { "path": "./packages/host/directory-picker-native" }, { "path": "./packages/host/webserver" }, { "path": "./packages/sdk/sdk-client" }, { "path": "./packages/sdk/helper" }, From 51402ac7af148d25c2ffce7fa807c852622d67c5 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 21:25:19 +0800 Subject: [PATCH 23/93] refactor(util): extract the shared no-shell native-command runner to dsh-native-command master's toolcall-open extracted runNativeCommand inside apiproxy for the openPath opener while the picker seam had moved the native chooser (its other consumer) into directory-picker-native; after the merge the two packages each carried a verbatim copy. The runner now lives in packages/util/native-command (zero-dependency library, per the util-group contract) and both native integrations depend on it. --- docs/module-graph.md | 3 ++ packages/host/apiproxy/package.json | 1 + .../host/apiproxy/src/native-path-opener.ts | 2 +- packages/host/apiproxy/tsconfig.json | 3 ++ .../host/directory-picker-native/package.json | 3 +- .../src/native-command.ts | 38 ---------------- .../src/native-picker.ts | 2 +- .../directory-picker-native/tsconfig.json | 3 ++ packages/util/README.i18n.yaml | 6 +-- packages/util/README.md | 1 + packages/util/README.zh.md | 1 + packages/util/native-command/README.i18n.yaml | 6 +++ packages/util/native-command/README.md | 27 ++++++++++++ packages/util/native-command/README.zh.md | 27 ++++++++++++ packages/util/native-command/package.json | 37 ++++++++++++++++ .../native-command/src/index.ts} | 8 +++- packages/util/native-command/src/invariant.ts | 31 +++++++++++++ .../tests/native-command.spec.ts | 43 +++++++++++++++++++ packages/util/native-command/tsconfig.json | 15 +++++++ pnpm-lock.yaml | 15 +++++++ .../verify-package-readme-model-experience.ts | 1 + tsconfig.host.json | 1 + 22 files changed, 229 insertions(+), 45 deletions(-) delete mode 100644 packages/host/directory-picker-native/src/native-command.ts create mode 100644 packages/util/native-command/README.i18n.yaml create mode 100644 packages/util/native-command/README.md create mode 100644 packages/util/native-command/README.zh.md create mode 100644 packages/util/native-command/package.json rename packages/{host/apiproxy/src/native-command.ts => util/native-command/src/index.ts} (77%) create mode 100644 packages/util/native-command/src/invariant.ts create mode 100644 packages/util/native-command/tests/native-command.spec.ts create mode 100644 packages/util/native-command/tsconfig.json diff --git a/docs/module-graph.md b/docs/module-graph.md index ddc77f1f21..c11ca86378 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -9,6 +9,7 @@ Inter-package dependencies among the `@deepseek-ai/dsh-*` harness packages, deri flowchart TD subgraph group_util["packages/util"] pkg_brand["brand"] + pkg_native_command["native-command"] pkg_paths["paths"] pkg_retention["retention"] pkg_timeout["timeout"] @@ -244,6 +245,7 @@ flowchart TD pkg_workspace["workspace"] end pkg_brand --> pkg_invariants + pkg_native_command --> pkg_invariants pkg_paths --> pkg_invariants pkg_retention --> pkg_invariants pkg_timeout --> pkg_invariants @@ -920,6 +922,7 @@ flowchart TD | --- | --- | --- | | [`invariants`](../packages/support/invariants) | `support` | — | | [`brand`](../packages/util/brand) | `util` | [`invariants`](../packages/support/invariants) | +| [`native-command`](../packages/util/native-command) | `util` | [`invariants`](../packages/support/invariants) | | [`paths`](../packages/util/paths) | `util` | [`invariants`](../packages/support/invariants) | | [`retention`](../packages/util/retention) | `util` | [`invariants`](../packages/support/invariants) | | [`timeout`](../packages/util/timeout) | `util` | [`invariants`](../packages/support/invariants) | diff --git a/packages/host/apiproxy/package.json b/packages/host/apiproxy/package.json index d90c52816d..cc9ed2b493 100644 --- a/packages/host/apiproxy/package.json +++ b/packages/host/apiproxy/package.json @@ -45,6 +45,7 @@ "@deepseek-ai/dsh-commands": "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:^", diff --git a/packages/host/apiproxy/src/native-path-opener.ts b/packages/host/apiproxy/src/native-path-opener.ts index 15a6d7a73b..a4fbbaa72e 100644 --- a/packages/host/apiproxy/src/native-path-opener.ts +++ b/packages/host/apiproxy/src/native-path-opener.ts @@ -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 diff --git a/packages/host/apiproxy/tsconfig.json b/packages/host/apiproxy/tsconfig.json index d3ba26038a..f5f5931602 100644 --- a/packages/host/apiproxy/tsconfig.json +++ b/packages/host/apiproxy/tsconfig.json @@ -55,6 +55,9 @@ }, { "path": "../../support/invariants" + }, + { + "path": "../../util/native-command" } ] } diff --git a/packages/host/directory-picker-native/package.json b/packages/host/directory-picker-native/package.json index 8db5d3a9df..72cb8a3e8a 100644 --- a/packages/host/directory-picker-native/package.json +++ b/packages/host/directory-picker-native/package.json @@ -27,7 +27,8 @@ ], "license": "BSD-3-Clause", "dependencies": { - "@deepseek-ai/dsh-host-directory-picker": "workspace:^" + "@deepseek-ai/dsh-host-directory-picker": "workspace:^", + "@deepseek-ai/dsh-native-command": "workspace:^" }, "peerDependencies": { "@deepseek-ai/dsh-invariants": "^0.0.1", diff --git a/packages/host/directory-picker-native/src/native-command.ts b/packages/host/directory-picker-native/src/native-command.ts deleted file mode 100644 index 0efe9679d8..0000000000 --- a/packages/host/directory-picker-native/src/native-command.ts +++ /dev/null @@ -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 }) - }, - ) - }) diff --git a/packages/host/directory-picker-native/src/native-picker.ts b/packages/host/directory-picker-native/src/native-picker.ts index 0ae95dfe74..ee3d3075e5 100644 --- a/packages/host/directory-picker-native/src/native-picker.ts +++ b/packages/host/directory-picker-native/src/native-picker.ts @@ -1,6 +1,6 @@ /** Cross-platform native single-directory chooser behind the dialog 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 diff --git a/packages/host/directory-picker-native/tsconfig.json b/packages/host/directory-picker-native/tsconfig.json index 99ca673189..64a32c3441 100644 --- a/packages/host/directory-picker-native/tsconfig.json +++ b/packages/host/directory-picker-native/tsconfig.json @@ -19,6 +19,9 @@ }, { "path": "../../support/invariants" + }, + { + "path": "../../util/native-command" } ] } diff --git a/packages/util/README.i18n.yaml b/packages/util/README.i18n.yaml index 1fc811bc8b..8bd1ff35b2 100644 --- a/packages/util/README.i18n.yaml +++ b/packages/util/README.i18n.yaml @@ -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: 140df90571d84320fb4eb888508c67e60aa29a22 -README.zh.md: 4c16df2a56476c0a7c965a037389fa5ba231e273 +# pnpm run verify-translation-pairing --write packages/util/README.md +README.md: 605c3dd0beebc16109e8e6bc944ea722a60975c0 +README.zh.md: 5c66ded33a36079f80965cf466449843e07511f0 diff --git a/packages/util/README.md b/packages/util/README.md index 140df90571..605c3dd0be 100644 --- a/packages/util/README.md +++ b/packages/util/README.md @@ -10,6 +10,7 @@ Zero-dependency primitives shared across the other groups. A package lands here | `paths/` | Canonical single-root `DSH_HOME` resolution plus shared filesystem path constants and helpers for harness user data (no harness deps) | | `timeout/` | The timing/classification half of a timeout — `clampTimeout`/`deadline`/`timeoutOf`/`TimeoutReason` (pure functions, no harness deps); termination stays in each capability | | `retention/` | Bounded model-facing output — `ItemRetainer`/`TextRetainer` + neutral notice helpers (pure, no harness deps); business semantics stay in each tool | +| `native-command/` | No-shell `execFile` runner for host-native OS integrations — utf8 capture, abort propagation, Windows hide (no harness deps); command choice stays in each caller | `dsh-brand` is the canonical case: it owns ONLY the `Branded` helper, so a capability package can brand the ids it owns (`dsh-tasks`'s `TaskId`, `dsh-session`'s `SessionId`, …) by depending on `dsh-brand` alone, without pulling in an unrelated package just to reach `Branded`. diff --git a/packages/util/README.zh.md b/packages/util/README.zh.md index 4c16df2a56..5c66ded33a 100644 --- a/packages/util/README.zh.md +++ b/packages/util/README.zh.md @@ -10,6 +10,7 @@ | `paths/` | 规范的单根 `DSH_HOME` 解析,以及 harness 用户数据的共享文件系统路径常量和辅助工具(无 harness 依赖) | | `timeout/` | 超时的时序/分类部分:`clampTimeout`/`deadline`/`timeoutOf`/`TimeoutReason`(纯函数,无 harness 依赖);终止机制保留在各个功能中 | | `retention/` | 有界的面向模型输出:`ItemRetainer`/`TextRetainer` 加上中性通知辅助工具(纯工具,无 harness 依赖);业务语义保留在各个工具中 | +| `native-command/` | 宿主原生 OS 集成的免 shell `execFile` 运行器——utf8 捕获、abort 传播、Windows 窗口隐藏(无 harness 依赖);命令选择保留在各调用方 | `dsh-brand` 是规范示例:它只负责 `Branded` 辅助工具,因此功能包可以为自己拥有的 id 添加品牌(`dsh-tasks` 的 `TaskId`、`dsh-session` 的 `SessionId` 等),而只需依赖 `dsh-brand`,无需仅为使用 `Branded` 而引入不相关的包。 diff --git a/packages/util/native-command/README.i18n.yaml b/packages/util/native-command/README.i18n.yaml new file mode 100644 index 0000000000..7d711e9e28 --- /dev/null +++ b/packages/util/native-command/README.i18n.yaml @@ -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/util/native-command/README.md +README.md: 7fc8b1f4640ef87ada62b6656854feb37080e4e6 +README.zh.md: 7c1cacb06d1d58601cc9e63c2ebd9c5f0ccb8159 diff --git a/packages/util/native-command/README.md b/packages/util/native-command/README.md new file mode 100644 index 0000000000..7fc8b1f464 --- /dev/null +++ b/packages/util/native-command/README.md @@ -0,0 +1,27 @@ +# dsh-native-command + +English | [中文](README.zh.md) + +A **zero-dependency no-shell `execFile` runner** shared by host-native OS integrations: one `runNativeCommand(command, args, signal)` call spawns the executable directly (never a shell string), captures utf8 stdout/stderr, propagates the caller's abort into child termination, and hides the transient console window on Windows. Failures reject with the exit `code` and both captured streams attached, so callers classify (missing tool, cancelled, real failure) without re-running anything. + +Its two consumers are the host-side native integrations: the [`directory-picker-native`](../../host/directory-picker-native/README.md) backend's OS chooser commands and the gateway's open-with-default-application hand-off ([`dsh-host-apiproxy`](../../host/apiproxy/README.md) `host.openPath`). The `NativeCommandRunner` type is the injectable command boundary those callers expose for deterministic tests. + +It is a **library, not a service or plugin**: no `ctx`, registers nothing, holds no state, emits no events. + +## Surface + +```ts +import { runNativeCommand, type NativeCommandRunner } from '@deepseek-ai/dsh-native-command' +``` + +## Model Experience + +None, as this is host-side subprocess plumbing; 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 output bounding** — both streams buffer unbounded in memory; every current caller invokes small native tools whose output is a path or an error line. Adopt `dsh-retention` bounding before pointing this at commands with meaningful output volume. diff --git a/packages/util/native-command/README.zh.md b/packages/util/native-command/README.zh.md new file mode 100644 index 0000000000..7c1cacb06d --- /dev/null +++ b/packages/util/native-command/README.zh.md @@ -0,0 +1,27 @@ +# dsh-native-command + +[English](README.md) | 中文 + +宿主原生 OS 集成共享的**零依赖免 shell `execFile` 运行器**:一次 `runNativeCommand(command, args, signal)` 调用直接派生可执行文件(绝不拼 shell 字符串),以 utf8 捕获 stdout/stderr,把调用方的 abort 传播为子进程终止,并在 Windows 上隐藏瞬时控制台窗口。失败时以附带退出 `code` 与两路已捕获输出的错误拒绝,调用方无需重跑即可分类(工具缺失、已取消、真实失败)。 + +它的两个消费者都是宿主侧原生集成:[`directory-picker-native`](../../host/directory-picker-native/README.zh.md) 后端的 OS 选择器命令,以及网关的按默认应用打开转交([`dsh-host-apiproxy`](../../host/apiproxy/README.zh.md) 的 `host.openPath`)。`NativeCommandRunner` 类型是这些调用方为确定性测试暴露的可注入命令边界。 + +它是**库,不是服务或插件**:没有 `ctx`、不注册任何东西、不持有状态、不发事件。 + +## Surface + +```ts +import { runNativeCommand, type NativeCommandRunner } from '@deepseek-ai/dsh-native-command' +``` + +## Model Experience + +无;这是宿主侧子进程管道,这里没有任何东西进入模型请求。 + +#### KV Cache effect + +无;该包既不组装也不发送 provider 请求。 + +## Known Limitations and Deferred Work + +- **不做输出限量**——两路流在内存中无界缓冲;当前每个调用方只运行输出为一个路径或一行错误的小型原生工具。把它指向输出量可观的命令之前,先接入 `dsh-retention` 限量。 diff --git a/packages/util/native-command/package.json b/packages/util/native-command/package.json new file mode 100644 index 0000000000..a20e61c33d --- /dev/null +++ b/packages/util/native-command/package.json @@ -0,0 +1,37 @@ +{ + "name": "@deepseek-ai/dsh-native-command", + "description": "Zero-dependency no-shell execFile runner for host-native OS integrations: utf8 stdio capture, abort propagation, Windows hide", + "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" + } +} diff --git a/packages/host/apiproxy/src/native-command.ts b/packages/util/native-command/src/index.ts similarity index 77% rename from packages/host/apiproxy/src/native-command.ts rename to packages/util/native-command/src/index.ts index 0efe9679d8..8ad8b81749 100644 --- a/packages/host/apiproxy/src/native-command.ts +++ b/packages/util/native-command/src/index.ts @@ -1,4 +1,10 @@ -/** Shared no-shell `execFile` runner for native host dialogs and openers. */ +/** + * Shared no-shell `execFile` runner for host-native OS integrations (the + * native directory chooser, the open-with-default-application hand-off): + * utf8 stdio capture, abort propagation, Windows console hide. A library, + * not a plugin — no ctx, no state, no events. + * @module @deepseek-ai/dsh-native-command + */ import { execFile } from 'node:child_process' diff --git a/packages/util/native-command/src/invariant.ts b/packages/util/native-command/src/invariant.ts new file mode 100644 index 0000000000..bec1d4b774 --- /dev/null +++ b/packages/util/native-command/src/invariant.ts @@ -0,0 +1,31 @@ +/** + * Package-owned invariant companion for `@deepseek-ai/dsh-native-command`. + * @module @deepseek-ai/dsh-native-command/invariant + */ + +/* jscpd:ignore-start */ +import type { Context } from 'cordis' +import type { InvariantInstaller } from '@deepseek-ai/dsh-invariants' + +const PACKAGE_NAME = '@deepseek-ai/dsh-native-command' + +/** Cordis companion plugin name. */ +export const name = 'native-command-invariant' +/** Service required before the companion can reserve package ownership. */ +export const inject = ['invariants'] + +/** + * No runtime invariant: each run is one stateless child-process round trip + * with no owned event stream or mutable runtime data; behavior is enforced by + * unit tests. + */ +const install: InvariantInstaller = () => {} + +/** + * Register this package's 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)) +/* jscpd:ignore-end */ diff --git a/packages/util/native-command/tests/native-command.spec.ts b/packages/util/native-command/tests/native-command.spec.ts new file mode 100644 index 0000000000..4c0adc40f4 --- /dev/null +++ b/packages/util/native-command/tests/native-command.spec.ts @@ -0,0 +1,43 @@ +import { describe, expect, it } from 'vitest' +import { runNativeCommand } from '@deepseek-ai/dsh-native-command' + +const node = process.execPath + +describe('runNativeCommand', () => { + it('captures utf8 stdout and stderr on exit 0', async () => { + const result = await runNativeCommand( + node, + ['-e', 'process.stdout.write("out✓"); process.stderr.write("err")'], + new AbortController().signal, + ) + expect(result).toEqual({ stdout: 'out✓', stderr: 'err' }) + }) + + it('rejects a non-zero exit with code, stdout, and stderr attached', async () => { + const failure = await runNativeCommand( + node, + ['-e', 'process.stdout.write("partial"); process.stderr.write("boom"); process.exit(3)'], + new AbortController().signal, + ).then(() => { throw new Error('unexpected resolve') }, (error: unknown) => error) + expect(failure).toMatchObject({ code: 3, stdout: 'partial', stderr: 'boom' }) + expect((failure as Error).cause).toBeInstanceOf(Error) + }) + + it('rejects a missing executable with the spawn ENOENT code', async () => { + const failure = await runNativeCommand( + 'dsh-definitely-missing-command', + [], + new AbortController().signal, + ).then(() => { throw new Error('unexpected resolve') }, (error: unknown) => error) + expect(failure).toMatchObject({ code: 'ENOENT' }) + }) + + it('terminates the child when the signal aborts', async () => { + const abort = new AbortController() + const pending = runNativeCommand(node, ['-e', 'setTimeout(() => {}, 60_000)'], abort.signal) + abort.abort() + const failure = await pending.then(() => { throw new Error('unexpected resolve') }, (error: unknown) => error) + expect(failure).toBeInstanceOf(Error) + expect((failure as { code?: unknown }).code).toBe('ABORT_ERR') + }) +}) diff --git a/packages/util/native-command/tsconfig.json b/packages/util/native-command/tsconfig.json new file mode 100644 index 0000000000..d970a00263 --- /dev/null +++ b/packages/util/native-command/tsconfig.json @@ -0,0 +1,15 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../support/invariants" + } + ] +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 1059d6b02b..9b06cc5b19 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2682,6 +2682,9 @@ importers: '@deepseek-ai/dsh-llm': specifier: workspace:^ version: link:../../llm/llm + '@deepseek-ai/dsh-native-command': + specifier: workspace:^ + version: link:../../util/native-command '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session @@ -2753,6 +2756,9 @@ importers: '@deepseek-ai/dsh-host-directory-picker': specifier: workspace:^ version: link:../directory-picker + '@deepseek-ai/dsh-native-command': + specifier: workspace:^ + version: link:../../util/native-command devDependencies: '@deepseek-ai/dsh-invariants': specifier: workspace:^ @@ -4797,6 +4803,15 @@ importers: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + packages/util/native-command: + devDependencies: + '@deepseek-ai/dsh-invariants': + specifier: workspace:^ + version: link:../../support/invariants + cordis: + specifier: ^4.0.0-rc.7 + version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + packages/util/paths: devDependencies: '@deepseek-ai/dsh-invariants': diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 930b99ce7f..2184f90d89 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -116,6 +116,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/ui/user-interaction': { kind: 'indirect', reason: 'Model-facing consumers render provider answers and seam errors.' }, 'packages/util/timeout': { kind: 'indirect', reason: 'Only timeout consumers render timeout outcomes.' }, 'packages/util/retention': { kind: 'indirect', reason: 'Only retention consumers render retained content and omission metadata.' }, + 'packages/util/native-command': { kind: 'none', reason: 'The host-side subprocess runner registers no model surface.' }, 'packages/web/web': { kind: 'indirect', reason: 'The provider registry delegates model rendering to dsh-tool-web.' }, 'packages/web/web-fetch-local': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-web.' }, 'packages/web/web-search-exa': { kind: 'indirect', reason: 'The provider backend delegates model rendering to dsh-tool-web.' }, diff --git a/tsconfig.host.json b/tsconfig.host.json index 6867ce6492..effb110c07 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -46,6 +46,7 @@ { "path": "./vendor/hmr" }, { "path": "./vendor/logger-console" }, { "path": "./packages/util/brand" }, + { "path": "./packages/util/native-command" }, { "path": "./packages/util/paths" }, { "path": "./packages/util/timeout" }, { "path": "./packages/util/retention" }, From c6b552e81717e818d27386534858490b18e745b0 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Tue, 28 Jul 2026 21:35:26 +0800 Subject: [PATCH 24/93] refactor(web): drop the permission RPC pair and turn-anchoring machinery The session.permissions/setPermission unary pair, the PermissionOption wire DTO, the client Session wrappers, and the fixture/fake mirrors all leave the wire: the read side moves to the 'permissions' session projection and the write side moves to the /permission command in follow-up commits, so the web protocol gains no permission methods at all. The pendingSwitches + prompt-submit flush + hasOpenTurn move also goes. Knob events no longer need turn enclosure: the persistence scanner keeps standalone events after the last turn/end as part of the preserved prefix (remove-synthetic-log-only-turns), none of the three knob invariants demand an open turn, and the setters append bare events. An idle switch commits immediately; hasOpenTurn stays a user-approval private fold (its audit pair is the one contract that still requires enclosure). The old PermissionSelect chip and its mount-time fetch die with the RPCs (the resident composer broke the mount-once assumption); the projection-fed replacement lands with the Access seat swap. --- packages/client/connection/src/client/api.ts | 2 +- .../client/connection/src/client/fixture.ts | 26 --- .../client/connection/src/client/index.ts | 2 +- packages/client/connection/tests/fake-api.ts | 8 - .../client/connection/tests/fixture.spec.ts | 19 --- packages/client/runtime/src/client/index.ts | 10 +- .../runtime/src/client/sessions/session.ts | 25 --- packages/client/runtime/tests/fake-api.ts | 8 - packages/client/runtime/tests/manager.spec.ts | 6 +- packages/client/runtime/tests/session.spec.ts | 24 --- .../skeleton/PermissionSelect.module.css | 49 ------ .../src/client/skeleton/PermissionSelect.tsx | 88 ---------- .../tests/apply-inject.spec.tsx | 2 +- .../ui-conversation/tests/chat-apply.spec.tsx | 4 +- .../tests/chat-code-subcalls.spec.tsx | 2 +- .../tests/chat-toolview-slot.spec.tsx | 2 +- .../tests/coverage-tails.spec.tsx | 2 +- .../ui-conversation/tests/skeleton.spec.tsx | 4 +- packages/client/ui-sidebar/README.md | 2 +- .../ui-sidebar/tests/sidebar-root.spec.tsx | 13 -- .../client/ui-trajectory/tests/views.spec.tsx | 2 - .../client/ui-workspace/tests/tree.spec.ts | 2 +- .../tests/workspace-browser.spec.tsx | 2 +- packages/core/session/src/index.ts | 19 --- packages/core/session/tests/session.spec.ts | 12 -- packages/host/apiproxy/src/api/index.ts | 2 +- packages/host/apiproxy/src/api/rpc-map.ts | 2 - .../host/apiproxy/src/api/sessions.schema.ts | 30 +--- packages/host/apiproxy/src/api/sessions.ts | 34 ---- packages/host/apiproxy/src/fetch/client.ts | 8 - packages/host/apiproxy/src/fetch/handler.ts | 4 - .../apiproxy/tests/api-proxy-approval.spec.ts | 2 +- .../tests/api-proxy-permission.spec.ts | 152 ------------------ .../apiproxy/tests/client-handler.spec.ts | 2 - .../host/apiproxy/tests/fetch-carrier.spec.ts | 10 +- packages/ui/user-approval/src/index.ts | 17 +- 36 files changed, 37 insertions(+), 561 deletions(-) delete mode 100644 packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css delete mode 100644 packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx delete mode 100644 packages/host/apiproxy/tests/api-proxy-permission.spec.ts diff --git a/packages/client/connection/src/client/api.ts b/packages/client/connection/src/client/api.ts index 54468bce11..77f5445f6d 100644 --- a/packages/client/connection/src/client/api.ts +++ b/packages/client/connection/src/client/api.ts @@ -7,7 +7,7 @@ export type { ApiProxy, SessionsApi, SessionSummary, HostApi, EventsApi, MuxFrame, HostFrame, - ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, PermissionOption, ToolEventView, + ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, ToolEventView, WorkspaceApi, WorkspaceId, WorkspaceView, CommandsApi, CommandDescriptor, SkillsApi, SkillEntry, ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning, diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 8d81b07d76..56d8b90d34 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -483,12 +483,6 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { let approvalPending = true const pendingQuestionRpcId = mint() let questionPending = true - /** Per-session permission preset (fixture mirror of the host permission select). */ - const permissionValues = new Map() - const PERMISSION_OPTIONS = [ - { value: 'workspace-write', name: 'workspace-write', description: 'Write inside the workspace and permitted temporary directories; wider retries require approval.' }, - { value: 'danger-full-access', name: 'danger-full-access', description: 'Full file access without approval prompts.' }, - ] const fixtureQuestions: Extract['questions'] = [ { id: 'harness-profile', @@ -839,24 +833,6 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { } return ok(request, { accepted: true as const }) }, - permissions: (request) => { - const { sessionId: id } = request.payload - if (summaryOf(id) === undefined) { - return err(request, { code: 'session-not-found', message: `no session ${id}`, details: { sessionId: id } }) - } - return ok(request, { options: PERMISSION_OPTIONS, currentValue: permissionValues.get(id) ?? 'workspace-write' }) - }, - setPermission: (request) => { - const { sessionId: id, value } = request.payload - if (summaryOf(id) === undefined) { - return err(request, { code: 'session-not-found', message: `no session ${id}`, details: { sessionId: id } }) - } - if (!PERMISSION_OPTIONS.some(option => option.value === value)) { - return err(request, { code: 'bad-request', message: `unknown permission value ${JSON.stringify(value)}`, details: { issues: [] } }) - } - permissionValues.set(id, value) - return ok(request, { currentValue: value }) - }, }, host: { describe: request => ok(request, { version: '0.0.0-fixture', cwd: '/tmp/fixture', attachedSessions }), @@ -1134,8 +1110,6 @@ export class FixtureApiClient extends AbstractApiClient { case 'session.selectModel': return this.api.sessions.selectModel(request) case 'session.prompt': return this.api.sessions.prompt(request) case 'session.cancel': return this.api.sessions.cancel(request) - case 'session.permissions': return this.api.sessions.permissions(request) - case 'session.setPermission': return this.api.sessions.setPermission(request) case 'host.describe': return this.api.host.describe(request) case 'host.pickDirectory': return this.api.host.pickDirectory(request, new AbortController().signal) case 'host.openPath': return this.api.host.openPath(request, new AbortController().signal) diff --git a/packages/client/connection/src/client/index.ts b/packages/client/connection/src/client/index.ts index af16fb540b..1ce30dbdc4 100644 --- a/packages/client/connection/src/client/index.ts +++ b/packages/client/connection/src/client/index.ts @@ -12,7 +12,7 @@ import { WebApiClient } from './web-api-client.ts' // ---- Contract re-exports (browser-safe apiproxy channels + core types) ---- export type { ApiProxy, SessionsApi, SessionSummary, HostApi, EventsApi, MuxFrame, HostFrame, - ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, PermissionOption, ToolEventView, + ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, ToolEventView, ToolCallView, ToolResultView, WorkspaceApi, WorkspaceId, WorkspaceView, CommandsApi, CommandDescriptor, SkillsApi, SkillEntry, ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning, diff --git a/packages/client/connection/tests/fake-api.ts b/packages/client/connection/tests/fake-api.ts index f1e90bd77f..1dac997ae2 100644 --- a/packages/client/connection/tests/fake-api.ts +++ b/packages/client/connection/tests/fake-api.ts @@ -63,12 +63,6 @@ export class FakeApiClient implements IApiClient { payload => Promise.resolve(ok({ selected: { provider: payload.provider, model: payload.model } })) onPrompt: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) onCancel: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) - onPermissions: (payload: unknown) => - Promise> = - () => Promise.resolve(ok({ options: [], currentValue: 'custom' })) - - onSetPermission: (payload: { sessionId: SessionId; value: string }) => Promise> = - payload => Promise.resolve(ok({ currentValue: payload.value })) onDescribe: (payload: unknown) => Promise> = () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 })) onPickDirectory: (payload: unknown) => Promise> = @@ -92,8 +86,6 @@ export class FakeApiClient implements IApiClient { this.record('session.selectModel', payload, this.onSelectModel(payload)), prompt: (payload: unknown) => this.record('session.prompt', payload, this.onPrompt(payload)), cancel: (payload: unknown) => this.record('session.cancel', payload, this.onCancel(payload)), - permissions: (payload: unknown) => this.record('session.permissions', payload, this.onPermissions(payload)), - setPermission: (payload: { sessionId: SessionId; value: string }) => this.record('session.setPermission', payload, this.onSetPermission(payload)), } readonly host: IApiClient['host'] = { diff --git a/packages/client/connection/tests/fixture.spec.ts b/packages/client/connection/tests/fixture.spec.ts index 7ffd1f5095..7ba49dd5f5 100644 --- a/packages/client/connection/tests/fixture.spec.ts +++ b/packages/client/connection/tests/fixture.spec.ts @@ -345,23 +345,6 @@ describe('createFixtureApi', () => { expect(replayed.some(f => f.type === 'approval/requested')).toBe(false) }) - it('permissions/setPermission mirror the host select: read, switch, validation', async () => { - const api = createFixtureApi() - const read = await api.sessions.permissions(req({ sessionId: sid('fx-alpha') })) - expect(read.result).toMatchObject({ ok: true, value: { currentValue: 'workspace-write' } }) - const switched = await api.sessions.setPermission(req({ sessionId: sid('fx-alpha'), value: 'danger-full-access' })) - expect(switched.result).toMatchObject({ ok: true, value: { currentValue: 'danger-full-access' } }) - const reread = await api.sessions.permissions(req({ sessionId: sid('fx-alpha') })) - expect(reread.result).toMatchObject({ ok: true, value: { currentValue: 'danger-full-access' } }) - // Validation: ghost session and unknown value. - const ghostRead = await api.sessions.permissions(req({ sessionId: sid('fx-ghost') })) - expect(ghostRead.result.ok).toBe(false) - const ghostSwitch = await api.sessions.setPermission(req({ sessionId: sid('fx-ghost'), value: 'workspace-write' })) - expect(ghostSwitch.result.ok).toBe(false) - const unknown = await api.sessions.setPermission(req({ sessionId: sid('fx-alpha'), value: 'nope' })) - expect(unknown.result.ok).toBe(false) - }) - it('describe answers the fixture identity', async () => { const api = createFixtureApi() const response = await api.host.describe(req({})) @@ -739,8 +722,6 @@ describe('FixtureApiClient (protocol-level fake carrier)', () => { expect((await client.sessions.history({ sessionId: id })).result.ok).toBe(true) expect((await client.sessions.prompt({ sessionId: id, mode: 'queue', content: [{ type: 'text', text: '嗨' }] })).result.ok).toBe(true) expect((await client.sessions.cancel({ sessionId: id })).result.ok).toBe(true) - expect((await client.sessions.permissions({ sessionId: id })).result.ok).toBe(true) - expect((await client.sessions.setPermission({ sessionId: id, value: 'danger-full-access' })).result.ok).toBe(true) expect((await client.host.describe({})).result.ok).toBe(true) expect((await client.workspace.list({})).result.ok).toBe(true) const workspace = await client.workspace.create({ name: 'via-client' }) diff --git a/packages/client/runtime/src/client/index.ts b/packages/client/runtime/src/client/index.ts index 63ffae4175..a7e9104b6c 100644 --- a/packages/client/runtime/src/client/index.ts +++ b/packages/client/runtime/src/client/index.ts @@ -40,15 +40,7 @@ export type { PendingInteraction, PendingKind, PendingPayloads } from './session export type { ProjectionsBaseline, ProjectionValueStore, SessionProjectionMap, UseProjection, } from './sessions/projection-store.ts' -export type { PermissionOption, SessionId } from '@deepseek-ai/dsh-client-connection/client' - -/** The permission select material as the object layer serves it to UI plugins. */ -export interface PermissionSelect { - /** Switchable presets plus (when derived) the current-only `custom`. */ - options: { value: string; name: string; description?: string }[] - /** The effective current value (`custom` when knobs match no preset). */ - currentValue: string -} +export type { SessionId } from '@deepseek-ai/dsh-client-connection/client' /** Client-side Cordis context after declaration merging. */ export type ClientContext = Context diff --git a/packages/client/runtime/src/client/sessions/session.ts b/packages/client/runtime/src/client/sessions/session.ts index f354dd5305..00398d53af 100644 --- a/packages/client/runtime/src/client/sessions/session.ts +++ b/packages/client/runtime/src/client/sessions/session.ts @@ -248,31 +248,6 @@ export class Session implements ObservableSnapshot { return result } - /** - * Read the permission select (options + effective current value). - * @returns the select material, or the error branch on failure. - */ - async permissions(): Promise> { - try { - return (await this.api.sessions.permissions({ sessionId: this.sessionId })).result - } catch (error) { - return transportError(error) - } - } - - /** - * Switch the permission preset. - * @param value - a preset value advertised by {@link Session.permissions} (never `custom`). - * @returns the confirmed current value, or the error branch on failure. - */ - async setPermission(value: string): Promise> { - try { - return (await this.api.sessions.setPermission({ sessionId: this.sessionId, value })).result - } catch (error) { - return transportError(error) - } - } - /** First open: pull the tail page (idempotent — in-flight/already-open returns the existing promise). */ open(): Promise { if (this.openState === 'open') return Promise.resolve() diff --git a/packages/client/runtime/tests/fake-api.ts b/packages/client/runtime/tests/fake-api.ts index 930a9f89da..6d37f6705f 100644 --- a/packages/client/runtime/tests/fake-api.ts +++ b/packages/client/runtime/tests/fake-api.ts @@ -81,12 +81,6 @@ export class FakeApiClient implements IApiClient { payload => Promise.resolve(ok({ selected: { provider: payload.provider, model: payload.model } })) onPrompt: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) onCancel: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) - onPermissions: (payload: unknown) => - Promise> = - () => Promise.resolve(ok({ options: [], currentValue: 'custom' })) - - onSetPermission: (payload: { sessionId: SessionId; value: string }) => Promise> = - payload => Promise.resolve(ok({ currentValue: payload.value })) onDescribe: (payload: unknown) => Promise> = () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 })) @@ -111,8 +105,6 @@ export class FakeApiClient implements IApiClient { this.record('session.selectModel', payload, this.onSelectModel(payload)), prompt: (payload: unknown) => this.record('session.prompt', payload, this.onPrompt(payload)), cancel: (payload: unknown) => this.record('session.cancel', payload, this.onCancel(payload)), - permissions: (payload: unknown) => this.record('session.permissions', payload, this.onPermissions(payload)), - setPermission: (payload: { sessionId: SessionId; value: string }) => this.record('session.setPermission', payload, this.onSetPermission(payload)), } readonly host: IApiClient['host'] = { diff --git a/packages/client/runtime/tests/manager.spec.ts b/packages/client/runtime/tests/manager.spec.ts index 3aa0834f99..f2d136bef8 100644 --- a/packages/client/runtime/tests/manager.spec.ts +++ b/packages/client/runtime/tests/manager.spec.ts @@ -358,7 +358,7 @@ describe('connected generation', () => { describe('waiting-approval list bit', () => { it('lights on requested, survives replay duplicates, and clears on resolved — without instantiation', () => { const manager = new SessionManager(new FakeApiClient()) - manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1 } }) + manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1, blank: false } }) expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(false) manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } }) expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(true) @@ -371,7 +371,7 @@ describe('waiting-approval list bit', () => { it('clears only when the last outstanding question resolves; session-removed drops the bit', () => { const manager = new SessionManager(new FakeApiClient()) - manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1 } }) + manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1, blank: false } }) manager.handleMuxEnvelope({ rpcId: 'r1' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'a1' as never, toolName: 'rm' } }) manager.handleMuxEnvelope({ rpcId: 'r2' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'a2' as never, toolName: 'rm' } }) manager.handleMuxEnvelope({ rpcId: 'rx' as never, payload: { type: 'approval/resolved', sessionId: S1, approvalId: 'a1' as never, outcome: 'rejected' as never } }) @@ -386,7 +386,7 @@ describe('waiting-approval list bit', () => { it('drops stale bits on reconnect — the reopen replay re-adds still-pending questions', () => { const manager = new SessionManager(new FakeApiClient()) - manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1 } }) + manager.handleHostEnvelope({ rpcId: 'h1' as never, payload: { type: 'host/session-added', sessionId: S1, blank: false } }) manager.handleMuxEnvelope({ rpcId: 'ra' as never, payload: { type: 'approval/requested', sessionId: S1, approvalId: 'ap1' as never, toolName: 'rm' } }) expect(manager.getListSnapshot().items[0]?.waitingApproval).toBe(true) manager.handleConnected() // resolved-while-disconnected questions send no frame diff --git a/packages/client/runtime/tests/session.spec.ts b/packages/client/runtime/tests/session.spec.ts index 76c7b51e99..ca9193eda1 100644 --- a/packages/client/runtime/tests/session.spec.ts +++ b/packages/client/runtime/tests/session.spec.ts @@ -816,27 +816,3 @@ describe('reference stability (the memo contract)', () => { expect(resolved.pending).toBe(after.pending) }) }) - -describe('permissions / setPermission', () => { - it('passes the select read and switch through with the session id', async () => { - const { api, session } = makeSession() - api.onPermissions = () => Promise.resolve(ok({ options: [{ value: 'workspace-write', name: 'workspace-write' }], currentValue: 'workspace-write' })) - const read = await session.permissions() - expect(read.ok).toBe(true) - if (read.ok) expect(read.value.currentValue).toBe('workspace-write') - expect(api.callsOf('session.permissions')).toMatchObject([{ sessionId: SID }]) - - const switched = await session.setPermission('danger-full-access') - expect(switched.ok).toBe(true) - if (switched.ok) expect(switched.value.currentValue).toBe('danger-full-access') - expect(api.callsOf('session.setPermission')).toMatchObject([{ sessionId: SID, value: 'danger-full-access' }]) - }) - - it('folds transport failures into the error branch', async () => { - const { api, session } = makeSession() - api.onPermissions = () => Promise.reject(new Error('down')) - api.onSetPermission = () => Promise.reject(new Error('down')) - expect((await session.permissions()).ok).toBe(false) - expect((await session.setPermission('x')).ok).toBe(false) - }) -}) diff --git a/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css deleted file mode 100644 index dd5986992c..0000000000 --- a/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css +++ /dev/null @@ -1,49 +0,0 @@ -/* Composer bottom-row permission chip (draft start.jpeg `Read-only ∨`): a - quiet text chip with a chevron; hover paints the standard interactive pill. - The native select is stretched invisibly over the chip so the platform - dropdown does the menu work — keyboard/AT semantics come free. */ - -.root { - position: relative; - display: inline-flex; - align-items: center; -} - -.chip { - display: inline-flex; - align-items: center; - gap: 4px; - padding: 6px 8px; - border-radius: 8px; - color: var(--dsw-alias-label-secondary); - font-size: 14px; - line-height: 20px; - pointer-events: none; /* the overlaid select owns the interaction */ -} - -.root:hover .chip { - background: var(--dsw-alias-interactive-bg-hover); -} - -.chevron { - color: var(--dsw-alias-label-caption); -} - -/* Invisible native select stretched over the chip: real menu, zero drawing. */ -.select { - position: absolute; - inset: 0; - width: 100%; - height: 100%; - opacity: 0; - border: none; - cursor: pointer; -} - -.select:disabled { - cursor: default; -} - -.root:has(.select:disabled) .chip { - opacity: 0.5; -} diff --git a/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx deleted file mode 100644 index a32e2af037..0000000000 --- a/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx +++ /dev/null @@ -1,88 +0,0 @@ -// PermissionSelect: the composer bottom-row permission chip (draft -// start.jpeg's `Read-only ∨` control). Options and the current value load on -// mount from the injected permissions() callback; empty options -// (permission-less host composition) render nothing. The visible chip is -// presentation only — an invisible native select stretched over it owns the -// menu and interaction. A switch disables the control until the host -// confirms, then adopts the confirmed value (`custom` is shown as the current -// value but never offered as a target — the host already omits it from -// switchable options; a stale-select failure restores the previous value). - -import { useEffect, useRef, useState } from 'react' -import type { PermissionSelect as PermissionSelectData } from '@deepseek-ai/dsh-client-runtime/client' -import css from './PermissionSelect.module.css' - -/** - * Display transform: kebab-case machine names render as title-case labels - * (`workspace-write` → `Workspace Write`). Presentation-only — the wire - * vocabulary and the host's advertised names are untouched; a host-configured - * name that is not kebab-case (contains spaces or uppercase) passes through. - */ -function displayName(name: string): string { - if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(name)) return name - return name.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ') -} - -export interface PermissionSelectProps { - /** Read the select material; null hides the control. */ - permissions: () => Promise - /** Switch the preset; resolves the confirmed value, or null on failure. */ - setPermission: (value: string) => Promise -} - -export function PermissionSelect({ permissions, setPermission }: PermissionSelectProps) { - const [data, setData] = useState(null) - const [switching, setSwitching] = useState(false) - // Unmount guard: the load/switch promises outlive a session switch's remount. - const aliveRef = useRef(true) - useEffect(() => { - aliveRef.current = true - void permissions().then((loaded) => { - if (aliveRef.current) setData(loaded) - }) - return () => { - aliveRef.current = false - } - }, [permissions]) - - if (data === null) return null - - const onChange = (value: string): void => { - if (value === data.currentValue) return - setSwitching(true) - const previous = data - setData({ ...data, currentValue: value }) - void setPermission(value).then((confirmed) => { - if (!aliveRef.current) return - setSwitching(false) - if (confirmed === null) setData(previous) - else setData({ ...previous, currentValue: confirmed }) - }) - } - - const current = data.options.find(option => option.value === data.currentValue) - - return ( - - ) -} diff --git a/packages/client/ui-conversation/tests/apply-inject.spec.tsx b/packages/client/ui-conversation/tests/apply-inject.spec.tsx index 6803e3e378..b93c225680 100644 --- a/packages/client/ui-conversation/tests/apply-inject.spec.tsx +++ b/packages/client/ui-conversation/tests/apply-inject.spec.tsx @@ -55,7 +55,7 @@ async function bench() { const listStore = createSnapshotStore({ ids: [ROOT], - byId: { [ROOT]: { id: ROOT, title: 'R', displayTitle: 'R', cwd: '/proj', running: false, blank: false, updatedAt: 1 } }, + byId: { [ROOT]: { id: ROOT, title: 'R', displayTitle: 'R', cwd: '/proj', running: false, waitingApproval: false, blank: false, updatedAt: 1 } }, current: ROOT, phase: 'ready', }) diff --git a/packages/client/ui-conversation/tests/chat-apply.spec.tsx b/packages/client/ui-conversation/tests/chat-apply.spec.tsx index afafafa3dc..34237bfebf 100644 --- a/packages/client/ui-conversation/tests/chat-apply.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-apply.spec.tsx @@ -26,8 +26,8 @@ async function bench() { const listStore = createSnapshotStore({ ids: [ROOT, CHILD], byId: { - [ROOT]: { id: ROOT, title: 'R', displayTitle: 'R', running: false, blank: false, updatedAt: 1 }, - [CHILD]: { id: CHILD, title: 'C', displayTitle: 'C', parentId: ROOT, running: false, blank: false, updatedAt: 2 }, + [ROOT]: { id: ROOT, title: 'R', displayTitle: 'R', running: false, waitingApproval: false, blank: false, updatedAt: 1 }, + [CHILD]: { id: CHILD, title: 'C', displayTitle: 'C', parentId: ROOT, running: false, waitingApproval: false, blank: false, updatedAt: 2 }, }, current: undefined, phase: 'ready', diff --git a/packages/client/ui-conversation/tests/chat-code-subcalls.spec.tsx b/packages/client/ui-conversation/tests/chat-code-subcalls.spec.tsx index 39d2b8283a..1b4d1ee158 100644 --- a/packages/client/ui-conversation/tests/chat-code-subcalls.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-code-subcalls.spec.tsx @@ -78,7 +78,7 @@ async function bench(snapshot: ConversationSnapshot) { const session = createSnapshotStore(snapshot) const list = createSnapshotStore({ ids: [SID], - byId: { [SID]: { id: SID, title: 'S', displayTitle: 'S', running: false, blank: false, updatedAt: 1 } }, + byId: { [SID]: { id: SID, title: 'S', displayTitle: 'S', running: false, waitingApproval: false, blank: false, updatedAt: 1 } }, current: SID, phase: 'ready', }) diff --git a/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx b/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx index 784c04c571..44cf87cc46 100644 --- a/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-toolview-slot.spec.tsx @@ -68,7 +68,7 @@ async function bench(nodes: ToolResultNode[]) { const session = createSnapshotStore(snapshotWith(nodes)) const list = createSnapshotStore({ ids: [SID], - byId: { [SID]: { id: SID, title: 'S', displayTitle: 'S', running: false, blank: false, updatedAt: 1 } }, + byId: { [SID]: { id: SID, title: 'S', displayTitle: 'S', running: false, waitingApproval: false, blank: false, updatedAt: 1 } }, current: SID, phase: 'ready', }) diff --git a/packages/client/ui-conversation/tests/coverage-tails.spec.tsx b/packages/client/ui-conversation/tests/coverage-tails.spec.tsx index 90628f64ee..7a9dfe957d 100644 --- a/packages/client/ui-conversation/tests/coverage-tails.spec.tsx +++ b/packages/client/ui-conversation/tests/coverage-tails.spec.tsx @@ -94,7 +94,7 @@ describe('tails', () => { const sid = 'root-1' as SessionId const list = createSnapshotStore({ ids: [sid], - byId: { [sid]: { id: sid, title: 'r', displayTitle: 'r', running: false, blank: false, updatedAt: 0 } }, + byId: { [sid]: { id: sid, title: 'r', displayTitle: 'r', running: false, waitingApproval: false, blank: false, updatedAt: 0 } }, current: undefined, phase: 'ready', }) diff --git a/packages/client/ui-conversation/tests/skeleton.spec.tsx b/packages/client/ui-conversation/tests/skeleton.spec.tsx index 9d34608156..b6263929cf 100644 --- a/packages/client/ui-conversation/tests/skeleton.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.spec.tsx @@ -64,8 +64,8 @@ function mount( const sessions = createSnapshotStore({ ids: [root, SID], byId: { - [root]: { id: root, displayTitle: 'Root', running: false, blank: false, updatedAt: 1 }, - [SID]: { id: SID, displayTitle: 'Child', parentId: root, cwd: '/projects/one', running: false, blank: false, updatedAt: 2 }, + [root]: { id: root, displayTitle: 'Root', running: false, waitingApproval: false, blank: false, updatedAt: 1 }, + [SID]: { id: SID, displayTitle: 'Child', parentId: root, cwd: '/projects/one', running: false, waitingApproval: false, blank: false, updatedAt: 2 }, }, current: SID, phase: 'ready', diff --git a/packages/client/ui-sidebar/README.md b/packages/client/ui-sidebar/README.md index ca125d6398..93a1f15a58 100644 --- a/packages/client/ui-sidebar/README.md +++ b/packages/client/ui-sidebar/README.md @@ -22,6 +22,6 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work -- **State dots have three live data states (running/amber approval-waiting/none)** — the done/error sources arrive with notifications; the four-color primitive is already wired. +- **State dots have two live data states (running/none)** — the done/error/amber sources arrive with P-II approvals and notifications; the four-color primitive is already wired. - **Group-by menu ships by-workspace only** — Update/Status grouping strategies are drawn without specs and deferred. - **"New task completed" unread marking is local viewing state** — completion-time > last-seen never reaches the host. diff --git a/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx b/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx index fcffc975b1..3c8086e4ce 100644 --- a/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx +++ b/packages/client/ui-sidebar/tests/sidebar-root.spec.tsx @@ -94,17 +94,4 @@ describe('SidebarRoot shell', () => { expect(b.regionOwner().wide).toBe(false) expect(screen.getByRole('button', { name: 'Open sidebar' })).toBeTruthy() }) - - it('waiting-approval shows the amber warning dot and outranks the running ring', () => { - mount( - summary({ id: 'blocked', title: 'blocked one', cwd: '/p', running: true, waitingApproval: true, updatedAt: 2 }), - summary({ id: 'busy', title: 'busy one', cwd: '/p', running: true, updatedAt: 1 }), - ) - act(() => { fireEvent.click(screen.getByText('p')) }) - const blockedRow = screen.getByText('blocked one').closest('[role="treeitem"]')! - const busyRow = screen.getByText('busy one').closest('[role="treeitem"]')! - expect(blockedRow.querySelector('[data-state="warning"]')).toBeTruthy() - expect(blockedRow.querySelector('[data-state="ongoing"]')).toBeNull() - expect(busyRow.querySelector('[data-state="ongoing"]')).toBeTruthy() - }) }) diff --git a/packages/client/ui-trajectory/tests/views.spec.tsx b/packages/client/ui-trajectory/tests/views.spec.tsx index 6e1da8afaa..917beaccc6 100644 --- a/packages/client/ui-trajectory/tests/views.spec.tsx +++ b/packages/client/ui-trajectory/tests/views.spec.tsx @@ -149,8 +149,6 @@ function mount(slots: SlotsService, nodes: ConversationSnapshot['nodes'] = NODES inputActions={{ setDraft: vi.fn(), submit: vi.fn() }} bindDraftMirror={() => () => {}} open={vi.fn()} - permissions={() => Promise.resolve(null)} - setPermission={() => Promise.resolve(null)} />, ) } diff --git a/packages/client/ui-workspace/tests/tree.spec.ts b/packages/client/ui-workspace/tests/tree.spec.ts index 4af5d5f70c..eb34f633d8 100644 --- a/packages/client/ui-workspace/tests/tree.spec.ts +++ b/packages/client/ui-workspace/tests/tree.spec.ts @@ -8,7 +8,7 @@ import { createWorkspaceViewStore } from '../src/client/stores.ts' const sid = (id: string) => id as SessionId const wid = (id: string) => id as WorkspaceId const summary = (id: string, updatedAt: number, cwd?: string): SessionSummary => ({ - id: sid(id), displayTitle: id, running: false, blank: false, updatedAt, ...(cwd === undefined ? {} : { cwd }), + id: sid(id), displayTitle: id, running: false, waitingApproval: false, blank: false, updatedAt, ...(cwd === undefined ? {} : { cwd }), }) const list = (...items: SessionSummary[]): SessionListState => ({ ids: items.map(item => item.id), diff --git a/packages/client/ui-workspace/tests/workspace-browser.spec.tsx b/packages/client/ui-workspace/tests/workspace-browser.spec.tsx index e8405c6bcd..7513342376 100644 --- a/packages/client/ui-workspace/tests/workspace-browser.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-browser.spec.tsx @@ -15,7 +15,7 @@ beforeEach(() => { localStorage.clear() }) const sid = (id: string) => id as SessionId const wid = (id: string) => id as WorkspaceId const summary = (id: string, updatedAt: number, overrides: Partial = {}): SessionSummary => ({ - id: sid(id), displayTitle: id, running: false, blank: false, updatedAt, ...overrides, + id: sid(id), displayTitle: id, running: false, waitingApproval: false, blank: false, updatedAt, ...overrides, }) const sessionState = (items: readonly SessionSummary[], overrides: Partial = {}): SessionListState => ({ ids: items.map(item => item.id), diff --git a/packages/core/session/src/index.ts b/packages/core/session/src/index.ts index b6ade3da7a..e42414503b 100644 --- a/packages/core/session/src/index.ts +++ b/packages/core/session/src/index.ts @@ -51,25 +51,6 @@ export function findLastMessageTurnEnd( return latest } -/** - * Whether the log currently sits inside an open turn (a `turn/start` not yet - * closed by a `turn/end`). The turn is the durable log's commit/replay - * boundary: a bare event appended between turns is indistinguishable from a - * crash tail and silently dropped on reload, so writers of turn-enclosed - * events (approval audit pairs, permission/sandbox knob switches) gate on - * this fold and hold idle writes until the next turn opens. - * @param events - session events, or an owned suffix, to inspect. - * @returns true when the last turn boundary event is a `turn/start`. - */ -export function hasOpenTurn(events: readonly SessionEvent[]): boolean { - for (let index = events.length - 1; index >= 0; index -= 1) { - const type = (events[index] as SessionEvent).type - if (type === 'turn/start') return true - if (type === 'turn/end') return false - } - return false -} - declare module 'cordis' { interface Context { sessions: SessionStore diff --git a/packages/core/session/tests/session.spec.ts b/packages/core/session/tests/session.spec.ts index 2edb119668..7152dd5d41 100644 --- a/packages/core/session/tests/session.spec.ts +++ b/packages/core/session/tests/session.spec.ts @@ -3,7 +3,6 @@ import { Context } from 'cordis' import { createUserMessage, CallId, createMessage, createToolResultMessage, MessageId, ReasoningEffortId } from '@deepseek-ai/dsh-llm' import SessionStore, { findLastMessageTurnEnd, - hasOpenTurn, SESSION_FORMAT_VERSION, Session, SessionEvent, @@ -108,17 +107,6 @@ describe('Session', () => { expect(findLastMessageTurnEnd(session.events)).toBe(messageEnd) }) - it('reports an open turn only between turn/start and its turn/end', () => { - const session = new Session(SessionId('open-turn')) - expect(hasOpenTurn(session.events)).toBe(false) - session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) - expect(hasOpenTurn(session.events)).toBe(true) - session.append('user/message', { content: [{ type: 'text', text: 'x' }], source: { kind: 'user' } }, { surfaceOp: 'append' }) - expect(hasOpenTurn(session.events)).toBe(true) - session.append('turn/end', { turn: 1, reason: { kind: 'completed' } }) - expect(hasOpenTurn(session.events)).toBe(false) - }) - it('round-trips the coarse aborted turn outcome', () => { const session = new Session(SessionId('aborted')) session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) diff --git a/packages/host/apiproxy/src/api/index.ts b/packages/host/apiproxy/src/api/index.ts index 8fc418baa5..5f27f121c4 100644 --- a/packages/host/apiproxy/src/api/index.ts +++ b/packages/host/apiproxy/src/api/index.ts @@ -27,7 +27,7 @@ export interface ApiProxy { // ---- Domain interfaces and payload entities ---- export type { HistoryEntry, ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning, - ModelReasoningEffort, ModelTarget, PermissionOption, SessionModels, SessionProjectionsBlock, SessionsApi, SessionSummary, + ModelReasoningEffort, ModelTarget, SessionModels, SessionProjectionsBlock, SessionsApi, SessionSummary, } from './sessions.ts' export type { HostApi } from './host.ts' export type { WorkspaceApi, WorkspaceId, WorkspaceView } from './workspace.ts' diff --git a/packages/host/apiproxy/src/api/rpc-map.ts b/packages/host/apiproxy/src/api/rpc-map.ts index bf41810dff..7beabd2696 100644 --- a/packages/host/apiproxy/src/api/rpc-map.ts +++ b/packages/host/apiproxy/src/api/rpc-map.ts @@ -24,8 +24,6 @@ export interface RpcMethodMap { 'session.selectModel': SessionsApi['selectModel'] 'session.prompt': SessionsApi['prompt'] 'session.cancel': SessionsApi['cancel'] - 'session.permissions': SessionsApi['permissions'] - 'session.setPermission': SessionsApi['setPermission'] 'host.describe': HostApi['describe'] 'host.pickDirectory': HostApi['pickDirectory'] 'host.openPath': HostApi['openPath'] diff --git a/packages/host/apiproxy/src/api/sessions.schema.ts b/packages/host/apiproxy/src/api/sessions.schema.ts index b7448021ac..8e4cdb5c5b 100644 --- a/packages/host/apiproxy/src/api/sessions.schema.ts +++ b/packages/host/apiproxy/src/api/sessions.schema.ts @@ -11,7 +11,7 @@ import type { RequestPayload, ResponseValue } from './rpc-map.ts' import type { Wire } from './rpc.schema.ts' import type { HistoryEntry, ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning, - ModelReasoningEffort, ModelTarget, PermissionOption, SessionProjectionsBlock, SessionSummary, + ModelReasoningEffort, ModelTarget, SessionProjectionsBlock, SessionSummary, } from './sessions.ts' import type { ToolEventView } from './events.ts' import type { WorkspaceId } from './workspace.ts' @@ -207,31 +207,3 @@ export const sessionCancelValueSchema = z.object({ accepted: z.literal(true), }) satisfies z.ZodType>> -/** One permission select option (a preset table key, or the derived `custom`). */ -export const permissionOptionSchema = z.object({ - value: z.string(), - name: z.string(), - description: z.string().optional(), -}) satisfies z.ZodType> - -/** session.permissions request payload. */ -export const sessionPermissionsRequestSchema = z.object({ - sessionId: sessionIdSchema, -}) satisfies z.ZodType>> - -/** session.permissions response value. */ -export const sessionPermissionsValueSchema = z.object({ - options: z.array(permissionOptionSchema), - currentValue: z.string(), -}) satisfies z.ZodType>> - -/** session.setPermission request payload. */ -export const sessionSetPermissionRequestSchema = z.object({ - sessionId: sessionIdSchema, - value: z.string(), -}) satisfies z.ZodType>> - -/** session.setPermission response value. */ -export const sessionSetPermissionValueSchema = z.object({ - currentValue: z.string(), -}) satisfies z.ZodType>> diff --git a/packages/host/apiproxy/src/api/sessions.ts b/packages/host/apiproxy/src/api/sessions.ts index a0560308dc..1a41a17f00 100644 --- a/packages/host/apiproxy/src/api/sessions.ts +++ b/packages/host/apiproxy/src/api/sessions.ts @@ -145,21 +145,6 @@ export interface SessionSummary { cwd?: string } -/** - * One selectable permission preset (or the derived `custom` state) as the - * client renders it. Protocol-owned DTO (the ACP bridge precedent: each - * protocol owns its presentation shape); the host projects it from - * `ctx.permission` without exposing that service's types on the wire. - */ -export interface PermissionOption { - /** The machine value (`session.setPermission` vocabulary): a preset table key, or `custom`. */ - value: string - /** The display label. */ - name: string - /** One user-facing sentence on what the value means. */ - description?: string -} - /** Session-domain unary methods (the map keys session.* of RpcMethodMap). */ export interface SessionsApi { /** Lists persisted sessions (updatedAt descending). v1 returns everything; cursor is a reserved seat, unimplemented. */ @@ -216,23 +201,4 @@ export interface SessionsApi { /** Stops: clears both FIFOs + aborts the current step (1:1 with agent.cancel). */ cancel(request: RpcRequest<{ sessionId: SessionId }>): Promise> - /** - * Reads the session's permission select: every switchable preset plus the - * effective current value (`custom` when the knobs match no preset — shown, - * never a switch target). A host composed without the permission service - * returns empty options and `custom`; clients hide the control. - */ - permissions(request: RpcRequest<{ sessionId: SessionId }>): - Promise> - - /** - * Switches the session's permission preset. Mirrors the ACP bridge's - * turn-anchoring: inside an open turn the knob events append immediately; - * idle switches are held last-write-wins and flushed into the next prompted - * turn (approval-policy and sandbox-mode events must stay turn-enclosed for - * durable replay). A current-value echo is acknowledged without recording. - * Unknown values and a permission-less composition are bad-request. - */ - setPermission(request: RpcRequest<{ sessionId: SessionId; value: string }>): - Promise> } diff --git a/packages/host/apiproxy/src/fetch/client.ts b/packages/host/apiproxy/src/fetch/client.ts index 25888d19d6..ceca9fee7e 100644 --- a/packages/host/apiproxy/src/fetch/client.ts +++ b/packages/host/apiproxy/src/fetch/client.ts @@ -22,10 +22,8 @@ import { sessionHistoryValueSchema, sessionListValueSchema, sessionModelsValueSchema, - sessionPermissionsValueSchema, sessionPromptValueSchema, sessionSelectModelValueSchema, - sessionSetPermissionValueSchema, } from '../api/sessions.schema.ts' import { workspaceCreateValueSchema, @@ -61,8 +59,6 @@ export interface IApiClient { selectModel(payload: RequestPayload<'session.selectModel'>, signal?: AbortSignal): Promise>> prompt(payload: RequestPayload<'session.prompt'>, signal?: AbortSignal): Promise>> cancel(payload: RequestPayload<'session.cancel'>, signal?: AbortSignal): Promise>> - permissions(payload: RequestPayload<'session.permissions'>, signal?: AbortSignal): Promise>> - setPermission(payload: RequestPayload<'session.setPermission'>, signal?: AbortSignal): Promise>> } host: { describe(payload: RequestPayload<'host.describe'>, signal?: AbortSignal): Promise>> @@ -103,8 +99,6 @@ const UNARY_VALUE_SCHEMAS: { [K in keyof RpcMethodMap]: z.ZodType this.callUnary('session.selectModel', payload, signal), prompt: (payload, signal) => this.callUnary('session.prompt', payload, signal), cancel: (payload, signal) => this.callUnary('session.cancel', payload, signal), - permissions: (payload, signal) => this.callUnary('session.permissions', payload, signal), - setPermission: (payload, signal) => this.callUnary('session.setPermission', payload, signal), } readonly host: IApiClient['host'] = { diff --git a/packages/host/apiproxy/src/fetch/handler.ts b/packages/host/apiproxy/src/fetch/handler.ts index c7de7854eb..505239c084 100644 --- a/packages/host/apiproxy/src/fetch/handler.ts +++ b/packages/host/apiproxy/src/fetch/handler.ts @@ -20,10 +20,8 @@ import { sessionHistoryRequestSchema, sessionListRequestSchema, sessionModelsRequestSchema, - sessionPermissionsRequestSchema, sessionPromptRequestSchema, sessionSelectModelRequestSchema, - sessionSetPermissionRequestSchema, } from '../api/sessions.schema.ts' import { hostDescribeRequestSchema, hostOpenPathRequestSchema, hostPickDirectoryRequestSchema, @@ -62,8 +60,6 @@ const UNARY_ROUTES: UnaryRoutes = { 'session.selectModel': { schema: sessionSelectModelRequestSchema, invoke: (api, r) => api.sessions.selectModel(r) }, 'session.prompt': { schema: sessionPromptRequestSchema, invoke: (api, r) => api.sessions.prompt(r) }, 'session.cancel': { schema: sessionCancelRequestSchema, invoke: (api, r) => api.sessions.cancel(r) }, - 'session.permissions': { schema: sessionPermissionsRequestSchema, invoke: (api, r) => api.sessions.permissions(r) }, - 'session.setPermission': { schema: sessionSetPermissionRequestSchema, invoke: (api, r) => api.sessions.setPermission(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.openPath': { schema: hostOpenPathRequestSchema, invoke: (api, r, signal) => api.host.openPath(r, signal) }, diff --git a/packages/host/apiproxy/tests/api-proxy-approval.spec.ts b/packages/host/apiproxy/tests/api-proxy-approval.spec.ts index e0cb0c71e5..a744224814 100644 --- a/packages/host/apiproxy/tests/api-proxy-approval.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-approval.spec.ts @@ -27,7 +27,7 @@ async function harness(): Promise<{ ctx: Context; api: ApiProxy }> { await ctx.plugin(UserInteractionService) await ctx.plugin(AgentRegistry) await ctx.plugin(ApprovalService) - const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp' }) + const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp', workspaceRoot: '/tmp' }) return { ctx, api } } diff --git a/packages/host/apiproxy/tests/api-proxy-permission.spec.ts b/packages/host/apiproxy/tests/api-proxy-permission.spec.ts deleted file mode 100644 index 472a49a52b..0000000000 --- a/packages/host/apiproxy/tests/api-proxy-permission.spec.ts +++ /dev/null @@ -1,152 +0,0 @@ -/** - * Permission select over the proxy: permissions() projects the preset table - * plus the derived current value (custom shown only when derived), - * setPermission() validates against the table and anchors idle switches to - * the next prompted turn (the ACP bridge's pendingSwitches pattern), and a - * permission-less composition serves an empty select instead of an error. - */ - -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 PermissionService from '@deepseek-ai/dsh-permission' -import type { ApiProxy, RpcRequest } from '@deepseek-ai/dsh-host-apiproxy/api' -import { RpcId } from '@deepseek-ai/dsh-host-apiproxy/api/rpc' -import type { SessionId } from '@deepseek-ai/dsh-session' -import { createApiProxy } from '../src/api-proxy.ts' - -let nextRpc = 1 -function request

(payload: P): RpcRequest

{ - return { rpcId: RpcId(`req-${String(nextRpc++)}`), payload } -} - -async function harness(options: { permission?: boolean } = {}): Promise<{ ctx: Context; api: ApiProxy; sessionId: SessionId }> { - const ctx = new Context() - await ctx.plugin(SessionStore) - await ctx.plugin(SystemPrompt, { persona: '' }) - await ctx.plugin(UserInteractionService) - await ctx.plugin(AgentRegistry) - if (options.permission !== false) { - // The permission service requires a confining executor fact + approval. - ctx.provide('bash', { - sandboxMode: 'workspace-write', - resolve() { throw new Error('permission proxy tests do not execute bash') }, - run() { throw new Error('permission proxy tests do not execute bash') }, - start() { throw new Error('permission proxy tests do not execute bash') }, - }) - await ctx.plugin(ApprovalService) - await ctx.plugin(PermissionService, {}) - } - const api = createApiProxy(ctx, { provider: 'p', model: 'm', cwd: '/tmp' }) - // No agent-loop in this harness: register a bare live agent directly (the - // proxy only reaches `.session`); api-proxy-view.spec.ts precedent. - const session = ctx.sessions.create() - ctx.agents.register({ id: session.id, session, status: 'idle', ctx } as Agent) - return { ctx, api, sessionId: session.id } -} - -function expectOk(response: { result: { ok: true; value: T } | { ok: false } }): T { - expect(response.result.ok).toBe(true) - if (!response.result.ok) throw new Error('unreachable') - return response.result.value -} - -describe('session.permissions', () => { - it('projects the preset table with the effective current value; custom is absent when a preset matches', async () => { - const { api, sessionId } = await harness() - const value = expectOk<{ options: { value: string }[]; currentValue: string }>( - await api.sessions.permissions(request({ sessionId }))) - expect(value.currentValue).toBe('workspace-write') - expect(value.options.map(o => o.value)).toEqual(['workspace-write', 'danger-full-access']) - }) - - it('serves an empty select (custom) on a permission-less composition', async () => { - const { api, sessionId } = await harness({ permission: false }) - const value = expectOk<{ options: unknown[]; currentValue: string }>( - await api.sessions.permissions(request({ sessionId }))) - expect(value).toEqual({ options: [], currentValue: 'custom' }) - }) - - it('appends the derived custom option when the knobs match no preset', async () => { - const { ctx, api, sessionId } = await harness() - const agent = ctx.agents.get(sessionId) - agent?.session.append('sandbox/mode', { mode: 'read-only' }) - const value = expectOk<{ options: { value: string }[]; currentValue: string }>( - await api.sessions.permissions(request({ sessionId }))) - expect(value.currentValue).toBe('custom') - expect(value.options.map(o => o.value)).toEqual(['workspace-write', 'danger-full-access', 'custom']) - }) - - it('propagates the agentFor error for a ghost session (persistence-less harness: internal)', async () => { - // The not-found/internal split is agentFor's documented gate and already - // covered by the history specs; here only the pass-through matters. - const { api } = await harness() - const response = await api.sessions.permissions(request({ sessionId: 'session-void' as SessionId })) - expect(response.result.ok).toBe(false) - }) -}) - -describe('session.setPermission', () => { - it('holds an idle switch pending (visible in permissions()) and flushes it into the next prompted turn', async () => { - const { ctx, api, sessionId } = await harness() - const agent = ctx.agents.get(sessionId) - expect(agent).toBeDefined() - const switched = expectOk<{ currentValue: string }>( - await api.sessions.setPermission(request({ sessionId, value: 'danger-full-access' }))) - expect(switched.currentValue).toBe('danger-full-access') - // No turn open: nothing appended yet; the pending value masks the fold. - expect(agent?.session.events.some(e => e.type === 'permission/preset')).toBe(false) - const echoed = expectOk<{ currentValue: string }>( - await api.sessions.permissions(request({ sessionId }))) - expect(echoed.currentValue).toBe('danger-full-access') - - // The waterfall flush path: prompt-submit inside the new turn writes through. - agent?.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) - await ctx.waterfall('agent/prompt-submit', agent as never, [], { kind: 'user' } as never, new AbortController().signal, () => Promise.resolve({ kind: 'allow' as const })) - expect(agent?.session.events.map(e => e.type)).toContain('permission/preset') - expect(agent?.session.events.map(e => e.type)).toContain('sandbox/mode') - expect(agent?.session.events.map(e => e.type)).toContain('approval/policy') - }) - - it('writes through immediately inside an open turn', async () => { - const { ctx, api, sessionId } = await harness() - const agent = ctx.agents.get(sessionId) - agent?.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) - expectOk(await api.sessions.setPermission(request({ sessionId, value: 'danger-full-access' }))) - expect(agent?.session.events.map(e => e.type)).toContain('permission/preset') - }) - - it('acknowledges a current-value echo without recording a switch', async () => { - const { ctx, api, sessionId } = await harness() - const agent = ctx.agents.get(sessionId) - agent?.session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) - const echoed = expectOk<{ currentValue: string }>( - await api.sessions.setPermission(request({ sessionId, value: 'workspace-write' }))) - expect(echoed.currentValue).toBe('workspace-write') - expect(agent?.session.events.some(e => e.type === 'permission/preset')).toBe(false) - }) - - it('propagates the agentFor error for a ghost session', async () => { - const { api } = await harness() - const response = await api.sessions.setPermission(request({ sessionId: 'session-void' as SessionId, value: 'workspace-write' })) - expect(response.result.ok).toBe(false) - }) - - it('rejects unknown values (custom included) and a permission-less composition as bad-request', async () => { - const { api, sessionId } = await harness() - for (const value of ['custom', 'nope']) { - const response = await api.sessions.setPermission(request({ sessionId, value })) - expect(response.result.ok).toBe(false) - if (!response.result.ok) expect(response.result.error.code).toBe('bad-request') - } - const bare = await harness({ permission: false }) - const response = await bare.api.sessions.setPermission(request({ sessionId: bare.sessionId, value: 'workspace-write' })) - expect(response.result.ok).toBe(false) - if (!response.result.ok) expect(response.result.error.code).toBe('bad-request') - }) -}) diff --git a/packages/host/apiproxy/tests/client-handler.spec.ts b/packages/host/apiproxy/tests/client-handler.spec.ts index c963b55950..2794aa13d2 100644 --- a/packages/host/apiproxy/tests/client-handler.spec.ts +++ b/packages/host/apiproxy/tests/client-handler.spec.ts @@ -45,8 +45,6 @@ function scriptedApi(overrides: { }), prompt: r => ok(r, { accepted: true as const }), cancel: r => ok(r, { accepted: true as const }), - permissions: r => ok(r, { options: [], currentValue: 'custom' }), - setPermission: r => ok(r, { currentValue: r.payload.value }), ...overrides.sessions, }, host: { diff --git a/packages/host/apiproxy/tests/fetch-carrier.spec.ts b/packages/host/apiproxy/tests/fetch-carrier.spec.ts index d631fbc125..6c62501c60 100644 --- a/packages/host/apiproxy/tests/fetch-carrier.spec.ts +++ b/packages/host/apiproxy/tests/fetch-carrier.spec.ts @@ -73,12 +73,6 @@ function fakeApi(overrides: Partial<{ muxFrames: MuxFrame[]; hostFrames: HostFra async cancel(request) { return { rpcId: request.rpcId, result: { ok: true, value: { accepted: true as const } } } }, - async permissions(request) { - return { rpcId: request.rpcId, result: { ok: true, value: { options: [], currentValue: 'custom' } } } - }, - async setPermission(request) { - return { rpcId: request.rpcId, result: { ok: true, value: { currentValue: request.payload.value } } } - }, }, host: { async describe(request) { @@ -184,7 +178,7 @@ describe('unary round trip (handler ⇄ client, no network)', () => { if (!response.result.ok) expect(response.result.error.code).toBe('session-not-found') }) - it('covers create/prompt/cancel/permissions/setPermission/describe passthrough', async () => { + it('covers create/prompt/cancel/describe passthrough', async () => { const c = client() expect((await c.sessions.create({})).result.ok).toBe(true) expect((await c.sessions.models({ sessionId: 's' as never })).result.ok).toBe(true) @@ -206,8 +200,6 @@ describe('unary round trip (handler ⇄ client, no network)', () => { }) expect((await c.sessions.prompt({ sessionId: 's' as never, mode: 'queue', content: [{ type: 'text', text: 'x' }] })).result.ok).toBe(true) expect((await c.sessions.cancel({ sessionId: 's' as never })).result.ok).toBe(true) - expect((await c.sessions.permissions({ sessionId: 's' as never })).result.ok).toBe(true) - expect((await c.sessions.setPermission({ sessionId: 's' as never, value: 'workspace-write' })).result.ok).toBe(true) expect((await c.host.describe({})).result.ok).toBe(true) }) diff --git a/packages/ui/user-approval/src/index.ts b/packages/ui/user-approval/src/index.ts index 021eab7b31..da2eafcbc7 100644 --- a/packages/ui/user-approval/src/index.ts +++ b/packages/ui/user-approval/src/index.ts @@ -11,7 +11,6 @@ import type { Agent } from '@deepseek-ai/dsh-agent' import { createUserMessage, type CallId } from '@deepseek-ai/dsh-llm' import { scopeTarget } from '@deepseek-ai/dsh-scope' import type { Scoped } from '@deepseek-ai/dsh-scope' -import { hasOpenTurn } from '@deepseek-ai/dsh-session' import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' import type {} from '@deepseek-ai/dsh-system-prompt' @@ -139,6 +138,22 @@ export function effectiveApprovalPolicy(events: readonly SessionEvent[]): Approv return undefined } +/** + * Whether the log currently sits inside an open turn (a `turn/start` not yet + * closed by a `turn/end`) — the {@link ApprovalService.request} precondition. + * The audit pair must be turn-enclosed: the turn is the durable log's + * commit/replay boundary, so a bare event appended between turns is + * indistinguishable from a crash tail and silently dropped on reload. + */ +function hasOpenTurn(events: readonly SessionEvent[]): boolean { + for (let index = events.length - 1; index >= 0; index -= 1) { + const type = (events[index] as SessionEvent).type + if (type === 'turn/start') return true + if (type === 'turn/end') return false + } + return false +} + /** * Append the sole durable representation of a session policy override. Invalid * values throw before the log changes; consumers fold the new value on each read. From 1c762864722784d01d3b73d9e3cdbe4d49827b36 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Tue, 28 Jul 2026 21:38:40 +0800 Subject: [PATCH 25/93] feat(host): approval pending registry on the api gateway The approval/request waterfall answerer fills the slot the gateway reserved ('registry absent in this minimal version'): an ask through ctx.approval becomes an answerable approval/requested mux frame with a stable rpcId, mux open replays still-pending frames (refresh recovery), respond routes approvals first by the echoed rpcId and cross-checks the payload's audit correlation, the ask's abort signal withdraws with a broadcast cancelled, and approval/resolved settles every subscriber. The answerer pairs each ask with its approval/asked audit event by scanning for the newest undecided, unclaimed id (callId-matched when the ask names a call); asks that bypassed the audit path delegate to the fail-closed default. The child activates only when ctx.approval is composed; the 275-line spec carries over verbatim at the gateway's new home. --- packages/host/apiproxy/src/api-proxy.ts | 127 +++++++++++++++++++++++- 1 file changed, 124 insertions(+), 3 deletions(-) diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index 56f488857f..310243f17f 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -33,6 +33,12 @@ import type {} from '@deepseek-ai/dsh-session-projection' // 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' @@ -123,9 +129,9 @@ class FrameQueue { } /** - * 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(payload: F): RpcRequest { return { rpcId: RpcId(randomUUID()), payload } @@ -194,6 +200,36 @@ export interface ApiProxyDefaults { /** 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 { + 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 @@ -371,6 +407,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() + const pendingApprovals = new Map() const muxQueues = new Set>>() /** @@ -519,6 +556,73 @@ 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) { + ctx.on('approval/request', (req, next) => { + // 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() + for (const entry of pendingApprovals.values()) claimed.add(entry.approvalId) + const decided = new Set() + 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 + if (req.callId !== undefined && event.data.callId !== req.callId) 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((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 @@ -1150,6 +1254,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. @@ -1267,6 +1374,20 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro }, respond(message: ClientResponse): Promise { + // 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) { From 85ca8be104fe7c623f5af817083dffb15798afe2 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 21:51:01 +0800 Subject: [PATCH 26/93] =?UTF-8?q?feat(host,client):=20compose=20directory?= =?UTF-8?q?=20picking=20through=20slots=20=E2=80=94=20dual-face=20-native,?= =?UTF-8?q?=20no=20wire=20advertisement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ui-workspace's two trigger surfaces each declare a single-kind directory-flow hole (conversation.hero.workspace.directoryFlow / sidebar.workspaces.directoryFlow, same owner contract) and keep only the trigger and the adoption: the Open-local- folder entry renders while the surface's hole is occupied, and the occupant reports one picked path per open through the hole's owner conversation (open/busy/onPicked/onCancel/onError). directory-picker-native becomes dual-face: its browser half fills both holes with a renderless occupant driving host.pickDirectory, so the cordis.yml row that mounts the backend also composes the client interaction — a mismatch is impossible and a second flow package fails at client load. With composition wiring both sides, the host.describe.directoryPicker advertisement and the client's kind branching lose their last consumer: the field, WorkspacesService.directoryPickerKind(), the DirectoryPickerKind wire type, and the picker's per-open describe read are deleted. The connection fixture now serves a deterministic pickDirectory path so the keyless snapshot drives the full pick-then-adopt flow. ui-workspace's hand-rolled declaration deferral is replaced by the deferRegistration helper it duplicated. --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 10 +- ...-28-directory-picker-capability-seam.zh.md | 10 +- apps/cli/cordis.yml | 6 +- apps/web/tests/workspace-flow.snapshot.ts | 27 ++- docs/capability-seams.md | 2 +- docs/config-catalog.md | 1 + docs/module-graph.md | 7 +- packages/client/connection/src/client/api.ts | 2 +- .../client/connection/src/client/fixture.ts | 11 +- .../client/connection/src/client/index.ts | 2 +- .../connection/tests/connection.spec.ts | 4 +- packages/client/connection/tests/fake-api.ts | 4 +- packages/client/runtime/src/client/index.ts | 2 +- .../runtime/src/client/workspaces/service.ts | 17 +- packages/client/runtime/tests/fake-api.ts | 4 +- .../runtime/tests/workspaces-service.spec.ts | 9 - packages/client/ui-workspace/README.i18n.yaml | 4 +- packages/client/ui-workspace/README.md | 4 +- packages/client/ui-workspace/README.zh.md | 4 +- .../src/client/WorkspaceBrowser.tsx | 8 +- .../src/client/WorkspacePicker.tsx | 108 ++++----- .../ui-workspace/src/client/contract/slots.ts | 74 ++++-- .../client/ui-workspace/src/client/index.ts | 70 +++--- .../client/ui-workspace/tests/apply.spec.ts | 34 ++- .../tests/workspace-browser.spec.tsx | 8 +- .../tests/workspace-picker.spec.tsx | 216 +++++++----------- packages/host/README.i18n.yaml | 4 +- packages/host/README.md | 2 +- packages/host/README.zh.md | 2 +- packages/host/apiproxy/README.i18n.yaml | 4 +- packages/host/apiproxy/README.md | 2 +- packages/host/apiproxy/README.zh.md | 2 +- packages/host/apiproxy/src/api-proxy.ts | 1 - packages/host/apiproxy/src/api/host.schema.ts | 1 - packages/host/apiproxy/src/api/host.ts | 14 -- packages/host/apiproxy/src/api/index.ts | 2 +- .../tests/api-proxy-workspace.spec.ts | 5 +- .../apiproxy/tests/client-handler.spec.ts | 2 +- .../host/apiproxy/tests/fetch-carrier.spec.ts | 2 +- .../host/apiproxy/tests/rpc-schemas.spec.ts | 7 +- .../directory-picker-native/README.i18n.yaml | 4 +- .../host/directory-picker-native/README.md | 4 +- .../host/directory-picker-native/README.zh.md | 4 +- .../host/directory-picker-native/package.json | 25 +- .../src/client/index.ts | 73 ++++++ .../src/native-picker.ts | 2 +- .../tests/client-flow.spec.tsx | 123 ++++++++++ .../directory-picker-native/tsconfig.json | 22 +- .../directory-picker-native/tsdown.config.ts | 3 + .../host/directory-picker/README.i18n.yaml | 4 +- packages/host/directory-picker/README.md | 2 +- packages/host/directory-picker/README.zh.md | 2 +- packages/util/native-command/README.i18n.yaml | 2 +- packages/util/native-command/README.zh.md | 2 +- pnpm-lock.yaml | 15 ++ scripts/gen-doc-graphs.ts | 2 +- tsconfig.client.json | 6 + tsconfig.host.json | 2 +- 59 files changed, 614 insertions(+), 385 deletions(-) create mode 100644 packages/host/directory-picker-native/src/client/index.ts create mode 100644 packages/host/directory-picker-native/tests/client-flow.spec.tsx create mode 100644 packages/host/directory-picker-native/tsdown.config.ts diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml index 1c7ea3556f..b49544ddfb 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml @@ -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 .agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md -2026-07-28-directory-picker-capability-seam.md: 78ae05e0da67bff791c0b4f315451aa02e1fa6f4 -2026-07-28-directory-picker-capability-seam.zh.md: bd527e2a1dba6934300a50877d4777f7f9fa24b1 +2026-07-28-directory-picker-capability-seam.md: ce5a2695345e29db5739df206965720559783ce3 +2026-07-28-directory-picker-capability-seam.zh.md: 5b73c3c48493d4f178a523db19bc124eda9c7cca diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md index 78ae05e0da..ce5a269534 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md @@ -10,7 +10,9 @@ The web GUI's "Open local folder" flow was hardwired to one interaction: `host.p ## Decision -A three-package capability seam in `packages/host/` — `directory-picker` (interface), `directory-picker-native`, `directory-picker-browse` (backends) — with one contract method: `capability()` returns a **discriminated union**, `{ kind: 'native', pick(signal) }` or `{ kind: 'browse', list(path?), createDirectory(path, name) }`. The gateway (`dsh-host-apiproxy`) injects `directoryPicker`, advertises the kind through `host.describe.directoryPicker`, serves the matching RPCs, and answers `directory-picker-unavailable` for the other kind; the client branches on the advertised kind and hides the affordance for unknown kinds (merge-extensible default). Composition (`cordis.yml`) is the swap point; the union is discriminated because the backends differ in *interaction shape* — flattening them into one method set would force every backend to fake the other's shape. +A three-package capability seam in `packages/host/` — `directory-picker` (interface), `directory-picker-native`, `directory-picker-browse` (backends) — with one contract method: `capability()` returns a **discriminated union**, `{ kind: 'native', pick(signal) }` or `{ kind: 'browse', list(path?), createDirectory(path, name) }`. The gateway (`dsh-host-apiproxy`) injects `directoryPicker`, serves the matching RPCs, and answers `directory-picker-unavailable` for the other kind. The union is discriminated because the backends differ in *interaction shape* — flattening them into one method set would force every backend to fake the other's shape. + +**The client side is slot-composed, not advertisement-branched.** ui-workspace's two trigger surfaces each declare a `single` directory-flow hole (`conversation.hero.workspace.directoryFlow` / `sidebar.workspaces.directoryFlow`; two keys because a hole has exactly one declaring slot entry — same owner contract, same occupant). Each backend package is **dual-face**: its browser half registers the matching interaction into both holes — `-native` a renderless occupant driving `host.pickDirectory`, `-browse` the in-app browsing dialog. The hole's owner conversation (`open`/`busy`/`onPicked`/`onCancel`/`onError`) carries the whole exchange: ui-workspace keeps the trigger (menu entry rendered only while the hole is occupied) and the adoption (`createWorkspace({path})`, conflict/error dialog, Choose again), the occupant owns everything between `open` and the picked path. One `cordis.yml` row therefore swaps the host capability and the client flow together; a mismatch is impossible by construction, and mounting two flow packages fails at client load (`single` hole). The earlier `host.describe.directoryPicker` advertisement and the client's kind branching are deleted — with composition wiring both sides, a wire fact for the client to branch on had no remaining consumer. The hole registry (`ctx.slots.entries`) replaces it as the per-menu-open occupancy read. Placement and policy rulings folded into this decision: @@ -30,7 +32,7 @@ Placement and policy rulings folded into this decision: ## Consequences -- `cordis.yml` chooses the interaction; `apps/cli` currently mounts `-native` (unchanged behavior). The GUI already gates its picking affordance on `describe.directoryPicker` (non-`native` kinds hide it); the in-app browser PR flips the default to `-browse` and adds the browse UI. -- The wire gains `host.listDirectory`/`host.createDirectory`, four error codes, and the `describe.directoryPicker` field; the connection fixture serves a deterministic browse tree for keyless assembled tests. -- A future interaction (or an Electron provider of the `native` interaction) is one backend package plus a client branch — no gateway surgery. +- `cordis.yml` chooses the interaction; `apps/cli` currently mounts `-native` (unchanged behavior). The in-app browser PR flips that one row to `-browse`, swapping backend and UI together. +- The wire gains `host.listDirectory`/`host.createDirectory` and four error codes; the connection fixture serves a deterministic browse tree and a deterministic `pickDirectory` path for keyless assembled tests. +- A future interaction (or an Electron provider of the `native` interaction) is one dual-face backend package — no gateway surgery, no ui-workspace edits. - `ApiProxyDefaults.pickDirectory` (test-only injection) is gone; tests provide a stub `ctx.directoryPicker` like any other service. diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md index bd527e2a1d..5b73c3c484 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md @@ -10,7 +10,9 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick ## 决策 -在 `packages/host/` 落一个三包能力 seam——`directory-picker`(接口)、`directory-picker-native`、`directory-picker-browse`(后端)——唯一契约方法 `capability()` 返回**可辨识联合**:`{ kind: 'native', pick(signal) }` 或 `{ kind: 'browse', list(path?), createDirectory(path, name) }`。网关(`dsh-host-apiproxy`)注入 `directoryPicker`,经 `host.describe.directoryPicker` 广播 kind,提供对应的 RPC,另一种 kind 的调用以 `directory-picker-unavailable` 应答;客户端按广播的 kind 分支,未知 kind 隐藏入口(可合并扩展的默认分支)。组合(`cordis.yml`)就是换装点;联合之所以可辨识,是因为后端差异在**交互形态**——压平成统一方法集会逼每个后端伪装另一方的形态。 +在 `packages/host/` 落一个三包能力 seam——`directory-picker`(接口)、`directory-picker-native`、`directory-picker-browse`(后端)——唯一契约方法 `capability()` 返回**可辨识联合**:`{ kind: 'native', pick(signal) }` 或 `{ kind: 'browse', list(path?), createDirectory(path, name) }`。网关(`dsh-host-apiproxy`)注入 `directoryPicker`,提供对应的 RPC,另一种 kind 的调用以 `directory-picker-unavailable` 应答。联合之所以可辨识,是因为后端差异在**交互形态**——压平成统一方法集会逼每个后端伪装另一方的形态。 + +**client 侧靠 slot 组合,而非按广播分支。** ui-workspace 的两个触发表层各自声明一个 `single` 目录流洞(`conversation.hero.workspace.directoryFlow`/`sidebar.workspaces.directoryFlow`;之所以是两个 key,是因为一个洞只有一个声明它的 slot entry——owner 契约相同、占用者相同)。每个后端包都是**双面包**:其 browser half 把匹配的交互注册进两个洞——`-native` 是驱动 `host.pickDirectory` 的无渲染占用者,`-browse` 是应用内浏览对话框。洞的 owner 会话(`open`/`busy`/`onPicked`/`onCancel`/`onError`)承载整个交换:ui-workspace 保留触发(菜单入口仅在洞被占用时渲染)与接纳(`createWorkspace({path})`、冲突/错误对话框、重新选择),占用者持有从 `open` 到所选路径之间的一切。因此一行 `cordis.yml` 同时切换宿主能力与 client 流程;错配在构造上不可能,同时挂两个流程包会在 client 加载期失败(`single` 洞)。早先的 `host.describe.directoryPicker` 广播与客户端 kind 分支被删除——组合已经接好两侧后,供客户端分支用的 wire 事实不再有任何消费者。洞注册表(`ctx.slots.entries`)取而代之,成为每次打开菜单的占用读取。 并入本决策的位置与策略裁决: @@ -30,7 +32,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick ## 后果 -- `cordis.yml` 决定交互形态;`apps/cli` 当前挂 `-native`(行为不变)。GUI 已按 `describe.directoryPicker` 门控其选目录入口(非 `native` kind 一律隐藏);应用内浏览器 PR 将把默认翻到 `-browse` 并补上浏览 UI。 -- 协议新增 `host.listDirectory`/`host.createDirectory`、四个错误码与 `describe.directoryPicker` 字段;connection fixture 提供确定性浏览树供无密钥组装测试使用。 -- 未来的新交互(或提供 `native` 交互的 Electron 实现)只是一个后端包加一个客户端分支——无需网关手术。 +- `cordis.yml` 决定交互形态;`apps/cli` 当前挂 `-native`(行为不变)。应用内浏览器 PR 只翻这一行到 `-browse`,后端与 UI 同时切换。 +- 协议新增 `host.listDirectory`/`host.createDirectory` 与四个错误码;connection fixture 提供确定性浏览树与确定性 `pickDirectory` 路径供无密钥组装测试使用。 +- 未来的新交互(或提供 `native` 交互的 Electron 实现)只是一个双面后端包——无需网关手术,也不动 ui-workspace。 - `ApiProxyDefaults.pickDirectory`(仅测试注入)删除;测试像提供其他服务一样提供 stub `ctx.directoryPicker`。 diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index de0af79b59..c6058890d8 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -240,8 +240,10 @@ # The API gateway: the transport-agnostic dispatch face every client shape # shares. provider/model are the host default routing — the profile json's # mapping target (user config overrides these engineering defaults). -# Directory-picking backend consumed by the gateway's host.* picker RPCs. -# Swap point: mount '-browse' instead for the in-app browser (remote-capable). +# Directory-picking package, dual-face: the node half serves the gateway's +# host.* picker RPCs, the browser half fills ui-workspace's directory-flow +# slots — one row composes the whole interaction. Swap point: mount +# '-browse' instead for the in-app browser (remote-capable). - id: directory-picker name: '@deepseek-ai/dsh-host-directory-picker-native' diff --git a/apps/web/tests/workspace-flow.snapshot.ts b/apps/web/tests/workspace-flow.snapshot.ts index 37ba56055e..ca98e7b176 100644 --- a/apps/web/tests/workspace-flow.snapshot.ts +++ b/apps/web/tests/workspace-flow.snapshot.ts @@ -37,6 +37,15 @@ const PLUGINS: readonly (WebBootEntry & { dir: string })[] = [ ], }, { id: '@deepseek-ai/dsh-client-ui-trajectory', dir: 'ui-trajectory', url: '/plugins/ui-trajectory.js', rev: 'fx', inject: ['@deepseek-ai/dsh-client-ui-conversation'] }, + // Dual-face host package: its browser half fills the directory-flow holes + // (the same composition row apps/cli mounts for the node-side backend). + { + id: '@deepseek-ai/dsh-host-directory-picker-native', + dir: '../host/directory-picker-native', + url: '/plugins/directory-picker-native.js', + rev: 'fx', + inject: ['@deepseek-ai/dsh-client-runtime', '@deepseek-ai/dsh-client-ui-workspace'], + }, ] const bundles = new Map(PLUGINS.map(plugin => [ @@ -174,18 +183,24 @@ it('locks the composer in the New Session view state until a Workspace is chosen `) }) -it('hides the Open-local-folder entry under the fixture host\'s browse picker capability', async () => { +it('adopts a directory through the composed native flow and lands in its blank session', async () => { boot('?fixture=empty') await findLockedComposer() fireEvent.click(workspaceChip()) const menu = await screen.findByRole('menu') - // Flush the advertised-kind read (fixture describe resolves in microtasks): - // the fixture serves `browse`, whose in-app UI is not wired yet, so the - // dialog affordance must not render — only the create action remains. - await act(async () => {}) + // The composed flow package occupies the directory-flow hole, so the + // picking affordance is present (no advertised-kind read exists anymore). expect(within(menu).getAllByRole('menuitem').map(item => visibleText(item))) - .toEqual(['Create a new workspace']) + .toEqual(['Open local folder…', 'Create a new workspace']) + fireEvent.click(within(menu).getByRole('menuitem', { name: 'Open local folder…' })) + // The renderless native flow drives the fixture's deterministic pick and + // the owner adopts the returned path into a real Workspace. + await act(async () => {}) + await findHeroComposer() + await waitFor(() => { + expect(visibleText(screen.getByRole('tree', { name: 'Sessions' }))).toContain('project') + }) }) it('selects the recent Workspace and opens its blank Session on first load', async () => { diff --git a/docs/capability-seams.md b/docs/capability-seams.md index b5c0dd6bec..6f934f96e3 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -364,7 +364,7 @@ flowchart LR | `ctx.tasks` | `seam` | [`tasks`](../packages/tasks/tasks) | [`tasks-local`](../packages/tasks/tasks-local) | [`tool-bash`](../packages/bash/tool-bash), [`tool-pty`](../packages/pty/tool-pty), [`tool-subagent`](../packages/subagent/tool-subagent), [`tool-tasks`](../packages/tasks/tool-tasks) | - | Producers (background bash, PTY sends, and subagent delegations) register running work; tool-tasks is the model-facing control surface that reads, lists, and kills it; tasks-local is the process-local registry. | | `ctx.web` | `seam` | [`web`](../packages/web/web) | [`web-search-exa`](../packages/web/web-search-exa), [`web-search-perplexity`](../packages/web/web-search-perplexity), [`web-search-deepseek`](../packages/web/web-search-deepseek), [`web-fetch-local`](../packages/web/web-fetch-local) | [`tool-web`](../packages/web/tool-web) | - | Search and fetch providers register into one ctx.web seam; tool-web owns the stable model-facing names. | | `ctx.spillStore` | `seam` | [`spill`](../packages/spill/spill) | [`spill-local`](../packages/spill/spill-local) | [`spill-policy`](../packages/spill/spill-policy) | - | The backend saves oversized tool text and returns a model-facing locator plus retrieval hint; spill-policy is the tools/post-execute consumer that decides when to spill. | -| `ctx.directoryPicker` | `seam` | `directory-picker` | `directory-picker-native`, `directory-picker-browse` | `apiproxy` | - | Discriminated interaction capability: the native backend opens one OS chooser on the host display, the browse backend serves listing/creation primitives for the in-app browser; the gateway advertises the kind via host.describe. | +| `ctx.directoryPicker` | `seam` | `directory-picker` | `directory-picker-native`, `directory-picker-browse` | `apiproxy` | - | Discriminated interaction capability: the native backend opens one OS chooser on the host display, the browse backend serves listing/creation primitives for the in-app browser; each backend is dual-face, its browser half filling ui-workspace directory-flow slots (no wire advertisement). | | `ctx.httpServer` | `core` | `webserver` | - | `connection`, `modules`, `hmr` | - | Plain node:http carrier: named-route registry, index transform taps, and the static dist fallback; web-transport plugins register their own routes. | | `ctx.clientModuleHost` | `core` | `modules` | - | `hmr` | - | Composes the __DSH_BOOT__ entry graph from an incremental dshClient scan, serves plugin bundles, and notifies rebuilt/graph-changed subscribers. | | `ctx.workflows` | `seam` | [`workflow`](../packages/workflow/workflow) | [`workflow-workerthread`](../packages/workflow/workflow-workerthread) | [`tool-workflow`](../packages/workflow/tool-workflow), [`tool-ralph`](../packages/workflow/tool-ralph) | - | One engine per context (bash shape, no named-provider registry); the general workflow and fixed Ralph consumers start runs whose agent() calls fan out through ctx.subagents. | diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 15339efefd..2018c38f5b 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -2241,6 +2241,7 @@ Imported as libraries by other packages; a `cordis.yml` cannot load them. - `@deepseek-ai/dsh-jsonrpc-demo` ([`packages/examples/jsonrpc-demo/src/index.ts`](../packages/examples/jsonrpc-demo/src/index.ts)) - `@deepseek-ai/dsh-llm-mock-server` ([`packages/support/llm-mock-server/src/index.ts`](../packages/support/llm-mock-server/src/index.ts)) - `@deepseek-ai/dsh-loader-smoke` ([`packages/support/loader-smoke/src/index.ts`](../packages/support/loader-smoke/src/index.ts)) +- `@deepseek-ai/dsh-native-command` ([`packages/util/native-command/src/index.ts`](../packages/util/native-command/src/index.ts)) - `@deepseek-ai/dsh-paths` ([`packages/util/paths/src/index.ts`](../packages/util/paths/src/index.ts)) - `@deepseek-ai/dsh-retention` ([`packages/util/retention/src/index.ts`](../packages/util/retention/src/index.ts)) - `@deepseek-ai/dsh-scope` ([`packages/core/scope/src/index.ts`](../packages/core/scope/src/index.ts)) diff --git a/docs/module-graph.md b/docs/module-graph.md index c11ca86378..320c6c85e4 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -267,7 +267,6 @@ flowchart TD pkg_host_apiproxy --> pkg_invariants pkg_host_directory_picker --> pkg_invariants pkg_host_directory_picker_browse --> pkg_invariants - pkg_host_directory_picker_native --> pkg_invariants pkg_host_webserver --> pkg_invariants pkg_storage --> pkg_invariants pkg_subprocess --> pkg_invariants @@ -355,6 +354,10 @@ flowchart TD pkg_client_ui_theme --> pkg_client_ui_primitives pkg_client_ui_theme --> pkg_client_ui_slots pkg_client_ui_theme --> pkg_invariants + pkg_host_directory_picker_native --> pkg_client_runtime + pkg_host_directory_picker_native --> pkg_client_ui_slots + pkg_host_directory_picker_native --> pkg_client_ui_workspace + pkg_host_directory_picker_native --> pkg_invariants pkg_lsp --> pkg_brand pkg_lsp --> pkg_invariants pkg_lsp --> pkg_llm @@ -944,7 +947,6 @@ flowchart TD | [`host-apiproxy`](../packages/host/apiproxy) | `host` | [`invariants`](../packages/support/invariants) | | [`host-directory-picker`](../packages/host/directory-picker) | `host` | [`invariants`](../packages/support/invariants) | | [`host-directory-picker-browse`](../packages/host/directory-picker-browse) | `host` | [`invariants`](../packages/support/invariants) | -| [`host-directory-picker-native`](../packages/host/directory-picker-native) | `host` | [`invariants`](../packages/support/invariants) | | [`host-webserver`](../packages/host/webserver) | `host` | [`invariants`](../packages/support/invariants) | | [`storage`](../packages/storage/storage) | `storage` | [`invariants`](../packages/support/invariants) | | [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`invariants`](../packages/support/invariants) | @@ -973,6 +975,7 @@ flowchart TD | [`client-ui-skill`](../packages/client/ui-skill) | `client` | [`client-connection`](../packages/client/connection), [`client-runtime`](../packages/client/runtime), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-subagent`](../packages/client/ui-subagent) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-theme`](../packages/client/ui-theme) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | +| [`host-directory-picker-native`](../packages/host/directory-picker-native) | `host` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-workspace`](../packages/client/ui-workspace), [`invariants`](../packages/support/invariants) | | [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm) | | [`sandbox`](../packages/sandbox/sandbox) | `sandbox` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm) | | [`token-meter`](../packages/llm/token-meter) | `llm` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | diff --git a/packages/client/connection/src/client/api.ts b/packages/client/connection/src/client/api.ts index 8214acf0b9..274612402f 100644 --- a/packages/client/connection/src/client/api.ts +++ b/packages/client/connection/src/client/api.ts @@ -8,7 +8,7 @@ export type { ApiProxy, SessionsApi, SessionSummary, HostApi, EventsApi, MuxFrame, HostFrame, ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, ToolEventView, - DirectoryEntry, DirectoryListing, DirectoryPickerKind, + DirectoryEntry, DirectoryListing, WorkspaceApi, WorkspaceId, WorkspaceView, CommandsApi, CommandDescriptor, SkillsApi, SkillEntry, ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning, diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 94d2e9adb5..82ecbb1cf3 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -863,12 +863,11 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { }, }, host: { - describe: request => ok(request, { version: '0.0.0-fixture', cwd: '/tmp/fixture', attachedSessions, directoryPicker: 'browse' as const }), - pickDirectory: request => err(request, { - code: 'directory-picker-unavailable', - message: 'the fixture host serves the browse capability', - details: { capability: 'browse' }, - }), + describe: request => ok(request, { version: '0.0.0-fixture', cwd: '/tmp/fixture', attachedSessions }), + // Deterministic native pick: the keyless lanes drive the full + // pick-then-adopt path without an OS chooser (design-mock content, + // same tree the browse primitives serve). + pickDirectory: request => ok(request, { path: `${FIXTURE_HOME}/Documents/project` }), listDirectory: (request) => { const target = request.payload.path ?? FIXTURE_HOME const children = childrenOf(target) diff --git a/packages/client/connection/src/client/index.ts b/packages/client/connection/src/client/index.ts index ceeaffb66e..0c98f0c1e9 100644 --- a/packages/client/connection/src/client/index.ts +++ b/packages/client/connection/src/client/index.ts @@ -13,7 +13,7 @@ import { WebApiClient } from './web-api-client.ts' export type { ApiProxy, SessionsApi, SessionSummary, HostApi, EventsApi, MuxFrame, HostFrame, ApprovalResponsePayload, QuestionResponsePayload, HistoryEntry, ToolEventView, - DirectoryEntry, DirectoryListing, DirectoryPickerKind, + DirectoryEntry, DirectoryListing, ToolCallView, ToolResultView, WorkspaceApi, WorkspaceId, WorkspaceView, CommandsApi, CommandDescriptor, SkillsApi, SkillEntry, ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning, diff --git a/packages/client/connection/tests/connection.spec.ts b/packages/client/connection/tests/connection.spec.ts index bce6fce2ce..4de4a31f25 100644 --- a/packages/client/connection/tests/connection.spec.ts +++ b/packages/client/connection/tests/connection.spec.ts @@ -75,7 +75,7 @@ describe('connection lifecycle', () => { try { await vi.waitFor(() => { expect(describeCalls).toBe(2) }) // retried after backoff expect(connected).toBe(0) // never announced during the failed generation - gate.resolve(ok({ version: '0', cwd: '/f', attachedSessions: 0, directoryPicker: 'browse' as const })) + gate.resolve(ok({ version: '0', cwd: '/f', attachedSessions: 0 })) await vi.waitFor(() => { expect(connected).toBe(1) }) } finally { controller.stop() @@ -199,7 +199,7 @@ describe('connection lifecycle', () => { controller.start() try { await vi.waitFor(() => { expect(describeCalls).toBe(3) }) - gate.resolve(ok({ version: '0', cwd: '/f', attachedSessions: 0, directoryPicker: 'browse' as const })) + gate.resolve(ok({ version: '0', cwd: '/f', attachedSessions: 0 })) await vi.waitFor(() => { expect(connected).toBe(1) }) expect(states).toEqual(['reconnecting', 'connected']) // two failures, one reconnecting emission } finally { diff --git a/packages/client/connection/tests/fake-api.ts b/packages/client/connection/tests/fake-api.ts index f6ca264bf8..13ca7f4922 100644 --- a/packages/client/connection/tests/fake-api.ts +++ b/packages/client/connection/tests/fake-api.ts @@ -63,8 +63,8 @@ export class FakeApiClient implements IApiClient { payload => Promise.resolve(ok({ selected: { provider: payload.provider, model: payload.model } })) onPrompt: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) onCancel: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) - onDescribe: (payload: unknown) => Promise> = - () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0, directoryPicker: 'browse' as const })) + onDescribe: (payload: unknown) => Promise> = + () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 })) onPickDirectory: (payload: unknown) => Promise> = () => Promise.resolve(ok({ path: null })) onOpenPath: (payload: unknown) => Promise> = diff --git a/packages/client/runtime/src/client/index.ts b/packages/client/runtime/src/client/index.ts index 2d1b42c249..99e2e73433 100644 --- a/packages/client/runtime/src/client/index.ts +++ b/packages/client/runtime/src/client/index.ts @@ -23,7 +23,7 @@ export type { SessionListPhase } from './sessions/manager.ts' export type { WorkspaceListPhase } from './workspaces/manager.ts' export type { WorkspaceListState } from './workspaces/service.ts' export type { - DirectoryEntry, DirectoryListing, DirectoryPickerKind, WorkspaceId, WorkspaceView, + DirectoryEntry, DirectoryListing, WorkspaceId, WorkspaceView, } from '@deepseek-ai/dsh-client-connection/client' // Runtime owns the snapshot store; web-react only binds it to React. export { createSnapshotStore, defineStore, shallowEqual } from './contract/store.ts' diff --git a/packages/client/runtime/src/client/workspaces/service.ts b/packages/client/runtime/src/client/workspaces/service.ts index 88e5bd988c..ca88eb001b 100644 --- a/packages/client/runtime/src/client/workspaces/service.ts +++ b/packages/client/runtime/src/client/workspaces/service.ts @@ -2,7 +2,7 @@ import type { Context } from 'cordis' import type { - DirectoryListing, DirectoryPickerKind, IApiClient, RpcError, + DirectoryListing, IApiClient, RpcError, SessionId, WorkspaceId, WorkspaceView, } from '@deepseek-ai/dsh-client-connection/client' import type { SnapshotStore } from '../contract/store.ts' @@ -191,21 +191,6 @@ export class WorkspacesService { return response.result.value.path } - /** - * The directory-picking interaction the Host composed — the fact the picker - * UI branches on (`native` opens the native chooser; `browse` opens the - * in-app browser). Read per flow open: one describe round trip, no cache to - * go stale across reconnects. - * @returns the Host's advertised picker kind. - */ - async directoryPickerKind(): Promise { - const response = await this.api.host.describe({}) - if (!response.result.ok) { - throw new Error(`host describe failed: ${response.result.error.message}`) - } - return response.result.value.directoryPicker - } - /** * List one directory level through the Host's `browse` capability. * @param path - absolute directory to list; absent lists the Host home directory. diff --git a/packages/client/runtime/tests/fake-api.ts b/packages/client/runtime/tests/fake-api.ts index e2eac0a364..b0f5f13db5 100644 --- a/packages/client/runtime/tests/fake-api.ts +++ b/packages/client/runtime/tests/fake-api.ts @@ -81,8 +81,8 @@ export class FakeApiClient implements IApiClient { payload => Promise.resolve(ok({ selected: { provider: payload.provider, model: payload.model } })) onPrompt: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) onCancel: (payload: unknown) => Promise> = () => Promise.resolve(ok({ accepted: true as const })) - onDescribe: (payload: unknown) => Promise> = - () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0, directoryPicker: 'browse' as const })) + onDescribe: (payload: unknown) => Promise> = + () => Promise.resolve(ok({ version: '0-fake', cwd: '/f', attachedSessions: 0 })) onPickDirectory: (payload: unknown) => Promise> = () => Promise.resolve(ok({ path: null })) onOpenPath: (payload: unknown) => Promise> = diff --git a/packages/client/runtime/tests/workspaces-service.spec.ts b/packages/client/runtime/tests/workspaces-service.spec.ts index 0b2788a693..6f0d35f2fa 100644 --- a/packages/client/runtime/tests/workspaces-service.spec.ts +++ b/packages/client/runtime/tests/workspaces-service.spec.ts @@ -238,15 +238,6 @@ describe('WorkspacesService', () => { await expect(workspaces.pickDirectory()).rejects.toThrow(/no chooser/) }) - it('reads the picker kind from describe per call, failing loud on an unreachable host', async () => { - const ctx = new Context() - const api = new FakeApiClient() - const workspaces = new WorkspacesService(ctx, api, new SessionsService(ctx, api)) - await expect(workspaces.directoryPickerKind()).resolves.toBe('browse') - api.onDescribe = () => Promise.resolve(err({ code: 'internal', message: 'down', details: {} })) - await expect(workspaces.directoryPickerKind()).rejects.toThrow(/host describe failed/) - }) - it('passes listings and creation through the browse wire, wrapping business failures', async () => { const ctx = new Context() const api = new FakeApiClient() diff --git a/packages/client/ui-workspace/README.i18n.yaml b/packages/client/ui-workspace/README.i18n.yaml index 7e0cd9380e..00b639f625 100644 --- a/packages/client/ui-workspace/README.i18n.yaml +++ b/packages/client/ui-workspace/README.i18n.yaml @@ -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/client/ui-workspace/README.md -README.md: deaa25184f5ddbfc5980033ce60cef43577ff33c -README.zh.md: e14e8ca6a2e3d65ce5fc403291e45ebc03598e04 +README.md: 8acf819121b46512d38b39ff858bb2bf797cfe96 +README.zh.md: e97d93f7e38d00af91b43f0df9fb0e3b17ae8ed5 diff --git a/packages/client/ui-workspace/README.md b/packages/client/ui-workspace/README.md index deaa25184f..8acf819121 100644 --- a/packages/client/ui-workspace/README.md +++ b/packages/client/ui-workspace/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) Shared Workspace picker plugin. `WorkspaceBrowser` is registered into the sidebar's `sidebar.workspaces` slot and `WorkspacePicker` into the page-local Session Intent hero's `conversation.hero.workspace` slot, so both surfaces use the same menu and creation flow. -The picker lists real Host Workspace entities through the global `useWorkspaces` hook. Selecting a Workspace invokes the slot owner's `onPick` callback to retarget the frontend Session object. The flat **Open local folder...** action renders only when the Host advertises the `native` picker interaction (read per flow open through `host.describe`); `browse` — until its in-app browser UI lands — and unknown kinds hide the entry, the seam's documented default. When shown, it delegates to the Host's native single-directory picker, adopts a returned path through the object layer, and selects the committed Workspace only after its list projection has refreshed; cancellation is silent, and errors remain retryable. **Create a new workspace** retains the name dialog and disables names already present in that list, while the Host remains authoritative for concurrent or non-UI callers. The runtime Session and Workspace services own materialization. The Workspace row's Delete action opens a confirmation that states the retention boundary, blocks duplicate submission, and keeps failures open; success removes the group while its Sessions remain under Ungrouped. +The picker lists real Host Workspace entities through the global `useWorkspaces` hook. Selecting a Workspace invokes the slot owner's `onPick` callback to retarget the frontend Session object. Each registration declares a **directory-flow child hole** (`single` kind: `conversation.hero.workspace.directoryFlow` / `sidebar.workspaces.directoryFlow`) that the composed picker package's client half fills with its picking interaction — the [`-native`](../../host/directory-picker-native/README.md) backend's renderless OS-chooser driver today, an in-app browsing dialog under a `-browse` composition. The flat **Open local folder...** action renders only while the surface's hole is occupied (occupancy read per menu render; an empty hole means the composition has no picking affordance — the seam's documented no-flow default). This package owns the trigger and the adoption: the occupant reports one picked path per open through the hole's owner conversation (`open`/`busy`/`onPicked`/`onCancel`/`onError`), and the owner adopts it through the object layer, selecting the committed Workspace only after its list projection has refreshed; cancellation is silent, and errors land in the retryable folder dialog whose **Choose again** reopens the flow. **Create a new workspace** retains the name dialog and disables names already present in that list, while the Host remains authoritative for concurrent or non-UI callers. The runtime Session and Workspace services own materialization. The Workspace row's Delete action opens a confirmation that states the retention boundary, blocks duplicate submission, and keeps failures open; success removes the group while its Sessions remain under Ungrouped. Both target slots are declared by other plugins, so `apply` registers through declaration-aware deferral and re-registers after a declaring slot is restored. @@ -19,4 +19,4 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work - **No Session deletion control** — the existing Session menu row remains visual-only; Workspace registration deletion does not delete Sessions. -- **Native folder selection depends on the local Host carrier** — fixture-only or remote browser deployments cannot open a local operating-system dialog; platform failures are shown in a retryable modal. +- **Native folder selection depends on the local Host carrier** — under the `-native` composition, fixture-only or remote browser deployments cannot open a local operating-system dialog; platform failures are shown in a retryable modal. Remote-capable picking is the `-browse` composition's in-app flow. diff --git a/packages/client/ui-workspace/README.zh.md b/packages/client/ui-workspace/README.zh.md index e14e8ca6a2..e97d93f7e3 100644 --- a/packages/client/ui-workspace/README.zh.md +++ b/packages/client/ui-workspace/README.zh.md @@ -4,7 +4,7 @@ 共享 Workspace 选择器插件。`WorkspaceBrowser` 注册到侧边栏的 `sidebar.workspaces` slot,`WorkspacePicker` 注册到页面局部 Session Intent 主视觉区的 `conversation.hero.workspace` slot,因此两个表层使用同一菜单和创建流程。 -该选择器通过全局 `useWorkspaces` hook 列出真实的 Host Workspace 实体。选择 Workspace 会调用 slot owner 的 `onPick` 回调,重新定位前端 Session 对象。平铺显示的 **打开本地文件夹…** 操作仅在 Host 广播 `native` 选择交互时渲染(每次流程打开时通过 `host.describe` 读取);`browse`(在其应用内浏览器 UI 落地之前)以及未知 kind 都会隐藏该入口,即 seam 文档化的默认行为。显示时它会委托 Host 的原生单目录选择器,通过对象层接纳返回的路径,并等待 Workspace 列表投影刷新后才选中已提交的 Workspace;取消操作不会显示提示,发生错误后仍可重试。**创建新工作区** 操作保留名称对话框,并禁用列表中已有的名称,而 Host 对并发或非 UI 调用方仍具有最终决定权。运行时 Session 与 Workspace 服务负责物化。Workspace 行内的 Delete 操作会打开确认框,说明保留边界、阻止重复提交,并在失败时保持打开;成功后,该分组会被移除,其 Session 则留在 Ungrouped 下。 +该选择器通过全局 `useWorkspaces` hook 列出真实的 Host Workspace 实体。选择 Workspace 会调用 slot owner 的 `onPick` 回调,重新定位前端 Session 对象。每个注册各自声明一个**目录流子洞**(`single` kind:`conversation.hero.workspace.directoryFlow`/`sidebar.workspaces.directoryFlow`),由组合的选择器包 client half 填入其选取交互——今天是 [`-native`](../../host/directory-picker-native/README.md) 后端的无渲染 OS 选择器驱动,`-browse` 组合下则是应用内浏览对话框。平铺显示的 **打开本地文件夹…** 操作仅在本表层的洞被占用时渲染(每次菜单渲染读取占用状态;洞为空意味着该组合没有选目录能力——seam 文档化的无流程默认行为)。本包持有触发与接纳:占用者经洞的 owner 会话(`open`/`busy`/`onPicked`/`onCancel`/`onError`)每次打开上报一个所选路径,owner 通过对象层接纳它,并等待 Workspace 列表投影刷新后才选中已提交的 Workspace;取消操作不会显示提示,错误落入可重试的文件夹对话框,其 **重新选择** 会重新打开流程。**创建新工作区** 操作保留名称对话框,并禁用列表中已有的名称,而 Host 对并发或非 UI 调用方仍具有最终决定权。运行时 Session 与 Workspace 服务负责物化。Workspace 行内的 Delete 操作会打开确认框,说明保留边界、阻止重复提交,并在失败时保持打开;成功后,该分组会被移除,其 Session 则留在 Ungrouped 下。 两个目标 slot 都由其他插件声明,因此 `apply` 通过声明感知的延迟机制完成注册,并在声明该 slot 的插件恢复后重新注册。 @@ -19,4 +19,4 @@ ## 已知限制与暂缓事项 - **没有 Session 删除控件**:现有 Session 菜单行仍仅提供视觉效果;删除 Workspace 注册记录不会删除 Session。 -- **原生文件夹选择依赖本地 Host 载体**:仅使用 fixture(测试前置数据)的部署或远程浏览器部署无法打开本地操作系统对话框;模态框会显示平台故障,并允许重试。 +- **原生文件夹选择依赖本地 Host 载体**:在 `-native` 组合下,仅使用 fixture(测试前置数据)的部署或远程浏览器部署无法打开本地操作系统对话框;模态框会显示平台故障,并允许重试。可远程的选取是 `-browse` 组合的应用内流程。 diff --git a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx index 67d5f0d9e5..61da0cc1ea 100644 --- a/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx +++ b/packages/client/ui-workspace/src/client/WorkspaceBrowser.tsx @@ -253,8 +253,8 @@ export function WorkspaceBrowser({ deleteWorkspace, insertSessionBefore, createWorkspace, - pickDirectory, - directoryPickerKind, + hasDirectoryFlow, + renderSlot, }: WorkspaceBrowserProps) { const workspaces = useWorkspaces(state => state.items) const groupBy = useStore(s => s.groupBy) @@ -372,8 +372,8 @@ export function WorkspaceBrowser({ anchorRef={wsPlusRef} useWorkspaces={useWorkspaces} createWorkspace={createWorkspace} - pickDirectory={pickDirectory} - directoryPickerKind={directoryPickerKind} + hasDirectoryFlow={hasDirectoryFlow} + renderDirectoryFlow={owner => renderSlot('sidebar.workspaces.directoryFlow', owner)} createOnly side="right" onPick={(workspaceId) => { diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx index cd68faf551..e98d6d4e26 100644 --- a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -2,18 +2,20 @@ * Workspace pick/create flow. WorkspaceCreateFlow is the reusable core * (menu + path/create dialogs) consumed directly by WorkspaceBrowser (same * package) and wrapped by WorkspacePicker for the conversation empty-state - * slot registration. + * slot registration. Directory picking itself lives in the composed flow + * package's slot occupant (see the contract module doc): this core only + * opens the flow, adopts the picked path, and owns the error surface. */ -import type { RefObject } from 'react' -import { useCallback, useEffect, useRef, useState } from 'react' +import type { ReactNode, RefObject } from 'react' +import { useCallback, useRef, useState } from 'react' import { Button, IconFolderClose16, IconPlusOutline16, Menu, Modal, type MenuEntry, } from '@deepseek-ai/dsh-client-ui-primitives' import { WorkspaceCreateError, - type DirectoryPickerKind, type WorkspaceId, type WorkspaceListState, type WorkspaceView, + type WorkspaceId, type WorkspaceListState, type WorkspaceView, } from '@deepseek-ai/dsh-client-runtime/client' -import type { WorkspacePickerProps } from './contract/slots.ts' +import type { DirectoryFlowOwnerProps, WorkspacePickerProps } from './contract/slots.ts' import css from './WorkspacePicker.module.css' const OPEN_LOCAL_FOLDER = '::open-local-folder' @@ -31,10 +33,10 @@ export interface WorkspaceCreateFlowProps { useWorkspaces: (selector: (state: WorkspaceListState) => S) => S /** Create or adopt a real Host Workspace. */ createWorkspace: (input: { name: string } | { path: string }) => Promise - /** Open the Host's native single-directory picker. */ - pickDirectory: () => Promise - /** The Host's advertised picker interaction (read per flow open); gates which picking affordance renders. */ - directoryPickerKind: () => Promise + /** Whether this surface's directory-flow hole is occupied (read per menu render; empty hides the local-folder entry). */ + hasDirectoryFlow: () => boolean + /** Render this surface's directory-flow hole with the owner conversation (the entry's narrowed renderSlot). */ + renderDirectoryFlow: (owner: DirectoryFlowOwnerProps) => ReactNode /** A real Workspace was picked or created. */ onPick: (workspaceId: WorkspaceId) => void /** Close the popover (outside click / Escape / post-pick). */ @@ -57,8 +59,8 @@ export function WorkspaceCreateFlow({ anchorRef, useWorkspaces, createWorkspace, - pickDirectory, - directoryPickerKind, + hasDirectoryFlow, + renderDirectoryFlow, onPick, onClose, createOnly = false, @@ -75,6 +77,7 @@ export function WorkspaceCreateFlow({ const [workspaceName, setWorkspaceName] = useState('') const [creating, setCreating] = useState(false) const [modalError, setModalError] = useState(null) + const [flowOpen, setFlowOpen] = useState(false) const [pickingFolder, setPickingFolder] = useState(false) const [folderConflict, setFolderConflict] = useState(false) const composingRef = useRef(false) @@ -82,36 +85,12 @@ export function WorkspaceCreateFlow({ const duplicateWorkspaceName = !creating && normalizedWorkspaceName !== '' && workspaces.some(workspace => workspace.title === normalizedWorkspaceName) - // The advertised interaction gates the picking affordance: 'native' is the - // only kind pickDirectory() can serve, so its entry renders under that kind - // alone; 'browse' (until the in-app browser UI lands) and unknown kinds - // hide the entry, the seam's documented unknown-kind default. Re-read per - // flow open — no cache to go stale across reconnects. - const [nativePicker, setNativePicker] = useState(false) - useEffect(() => { - if (!open) { - // Close discards the answer: a reconnect or HMR can swap the composed - // backend while the menu is closed, and the reopened menu must never - // paint the previous host's entry before the fresh read lands. - setNativePicker(false) - return - } - // Reset before each read: the injected reader can also change identity - // while the flow stays open, and that prior answer must not leak either; - // a settlement from a superseded read is discarded via the - // cleanup-toggled flag. - setNativePicker(false) - let stale = false - void directoryPickerKind() - .then((kind) => { if (!stale) setNativePicker(kind === 'native') }) - // A failed describe hides the entry too: the same Host that cannot - // answer describe cannot serve pickDirectory. - .catch(() => { if (!stale) setNativePicker(false) }) - return () => { stale = true } - }, [open, directoryPickerKind]) - + // The occupied hole gates the picking affordance: with no composed flow the + // entry simply is not there (the seam's documented no-flow default). Read + // per render while the menu is open — registrations land through plugin + // activation, and the menu re-renders on every toggle. const createEntries: MenuEntry[] = [ - ...(nativePicker + ...(hasDirectoryFlow() ? [{ id: OPEN_LOCAL_FOLDER, label: 'Open local folder…', icon: , disabled: pickingFolder }] : []), { id: CREATE_NEW, label: 'Create a new workspace', icon: , disabled: pickingFolder }, @@ -134,15 +113,10 @@ export function WorkspaceCreateFlow({ setModalError(null) } - const openLocalFolder = (): void => { - onClose() - setModalKind(null) - setModalError(null) - setFolderConflict(false) - setPickingFolder(true) - void pickDirectory().then(async (path) => { - if (path === null) return - const workspace = await createWorkspace({ path }) + /** Adopt a picked directory; failures land in the folder-error dialog (Choose again reopens the flow). */ + const adoptDirectory = (path: string): Promise => + createWorkspace({ path }).then((workspace) => { + setFlowOpen(false) onPick(workspace.workspaceId) }).catch((reason: unknown) => { setFolderConflict( @@ -150,8 +124,33 @@ export function WorkspaceCreateFlow({ && reason.rpcError.code === 'workspace-name-conflict', ) setModalError(reason instanceof Error ? reason.message : String(reason)) + setFlowOpen(false) setModalKind('folder-error') - }).finally(() => { setPickingFolder(false) }) + }) + + const openLocalFolder = (): void => { + onClose() + setModalKind(null) + setModalError(null) + setFolderConflict(false) + setFlowOpen(true) + } + + /** Owner side of the flow conversation: adopt keeps the flow open (busy) until the Host answers. */ + const flowOwner: DirectoryFlowOwnerProps = { + open: flowOpen, + busy: pickingFolder, + onPicked: (path) => { + setPickingFolder(true) + void adoptDirectory(path).finally(() => { setPickingFolder(false) }) + }, + onCancel: () => { setFlowOpen(false) }, + onError: (message) => { + setFlowOpen(false) + setFolderConflict(false) + setModalError(message) + setModalKind('folder-error') + }, } const handleSelect = (id: string): void => { @@ -205,6 +204,7 @@ export function WorkspaceCreateFlow({ getAnchorRect={getAnchorRect} /> {open && workspaceSnapshot.phase === 'pending' &&

Loading workspaces…
} + {renderDirectoryFlow(flowOwner)} renderSlot('conversation.hero.workspace.directoryFlow', owner)} selectedId={selectedId} onPick={onPick} onClose={onClose} diff --git a/packages/client/ui-workspace/src/client/contract/slots.ts b/packages/client/ui-workspace/src/client/contract/slots.ts index c20955b567..fce3bd9b46 100644 --- a/packages/client/ui-workspace/src/client/contract/slots.ts +++ b/packages/client/ui-workspace/src/client/contract/slots.ts @@ -7,21 +7,74 @@ * consumes the shell's two-fact owner share (wide / expandSidebar). * - WorkspacePicker fills the conversation empty-state hole (menu + * create dialogs shared with the browser). + * + * Each registration also declares one **directory-flow hole** (`single` + * kind): the slot a composed picker package's client half fills with its + * picking interaction — a renderless native-chooser driver or an in-app + * browsing dialog. ui-workspace owns the trigger (the "Open local folder…" + * menu entry, shown only while the hole is occupied) and the adoption + * semantics (`createWorkspace({ path })`, the conflict/error dialog, Choose + * again); the occupant owns everything between `open` and the picked path. + * Two holes exist because the two menu surfaces are independent slot entries + * and a hole has exactly one declaring entry — they carry the same owner + * contract and the same occupant. */ -import type { PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' +import type { PropsRenderSlots, PropsRuntime, PropsStore } from '@deepseek-ai/dsh-client-ui-slots' // Type-only: pull the owner SlotMap merges into programs that resolve the // runtime shares below. import type {} from '@deepseek-ai/dsh-client-ui-sidebar/client' import type {} from '@deepseek-ai/dsh-client-ui-conversation/client' -import type { DirectoryPickerKind, SessionId, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' +import type { SessionId, WorkspaceId, WorkspaceView } from '@deepseek-ai/dsh-client-runtime/client' import type { createWorkspaceViewStore } from '../stores.ts' +/** + * Owner share of the directory-flow holes: the complete conversation between + * the trigger surface and the picking interaction. The occupant reads `open` + * to run/render its interaction and reports exactly one outcome per open. + */ +export interface DirectoryFlowOwnerProps { + /** True while a picking interaction is requested; flipping back to false withdraws the request. */ + open: boolean + /** True while the owner adopts a picked path (`createWorkspace` in flight); occupants disable their commit affordances. */ + busy: boolean + /** The operator picked a directory (absolute host path); the owner adopts it. */ + onPicked: (path: string) => void + /** The operator dismissed the interaction; the owner just closes the flow. */ + onCancel: () => void + /** The interaction itself failed (chooser missing, listing denied); the owner shows its error surface. */ + onError: (message: string) => void +} + +declare module '@deepseek-ai/dsh-client-ui-slots' { + interface SlotMap { + /** Directory-flow hole under the conversation empty-state picker (declared by the WorkspacePicker entry). */ + 'conversation.hero.workspace.directoryFlow': { kind: 'single'; scope: 'root'; owner: DirectoryFlowOwnerProps } + /** Directory-flow hole under the sidebar browsing region (declared by the WorkspaceBrowser entry). */ + 'sidebar.workspaces.directoryFlow': { kind: 'single'; scope: 'root'; owner: DirectoryFlowOwnerProps } + } +} + +/** The two directory-flow holes; a flow package's client half registers its one component into both. */ +export type DirectoryFlowSlotName = + | 'conversation.hero.workspace.directoryFlow' + | 'sidebar.workspaces.directoryFlow' + +/** Directory-picking share both trigger surfaces consume. */ +export type DirectoryPickingInjected = { + /** + * Whether this surface's directory-flow hole is occupied — read when the + * menu opens; an empty hole hides the "Open local folder…" entry (the + * no-flow composition simply has no picking affordance). + */ + hasDirectoryFlow: () => boolean +} + /** * Browser-private injected share (arrives via the register inject factory). * Data reads use the global framework hooks; these are the Host actions the * browsing region drives. */ -export type WorkspaceBrowserInjected = { +export type WorkspaceBrowserInjected = DirectoryPickingInjected & { /** * Start a New Session in a Workspace: reuse-or-create its blank session * and open it; with no workspace, clear the selection into the New Session @@ -42,15 +95,12 @@ export type WorkspaceBrowserInjected = { insertSessionBefore: (workspaceId: WorkspaceId, sessionId: SessionId, beforeSessionId?: SessionId) => Promise /** Explicitly create or adopt a real Workspace before targeting a Session. */ createWorkspace: (input: { name: string } | { path: string }) => Promise - /** Ask the local Host to open its native single-directory picker. */ - pickDirectory: () => Promise - /** The Host's advertised picker interaction (read per flow open); gates which picking affordance renders. */ - directoryPickerKind: () => Promise } /** Full browser props: shell owner share + viewing store + injected actions. */ export type WorkspaceBrowserProps = PropsRuntime<'sidebar.workspaces'> + & PropsRenderSlots<'sidebar.workspaces.directoryFlow'> & PropsStore> & WorkspaceBrowserInjected @@ -59,13 +109,9 @@ export type WorkspaceBrowserProps = * callback; this callback creates only the real Host Workspace. A type alias * supplies the implicit index signature required by the registry. */ -export type WorkspacePickerInjected = { +export type WorkspacePickerInjected = DirectoryPickingInjected & { /** Explicitly create or adopt a real Workspace before targeting a Session. */ createWorkspace: (input: { name: string } | { path: string }) => Promise - /** Ask the local Host to open its native single-directory picker. */ - pickDirectory: () => Promise - /** The Host's advertised picker interaction (read per flow open); gates which picking affordance renders. */ - directoryPickerKind: () => Promise } /** @@ -74,4 +120,6 @@ export type WorkspacePickerInjected = { * currency, so one composed type serves both registrations. */ export type WorkspacePickerProps = - PropsRuntime<'conversation.hero.workspace'> & WorkspacePickerInjected + PropsRuntime<'conversation.hero.workspace'> + & PropsRenderSlots<'conversation.hero.workspace.directoryFlow'> + & WorkspacePickerInjected diff --git a/packages/client/ui-workspace/src/client/index.ts b/packages/client/ui-workspace/src/client/index.ts index 6b84680fbc..4fd9edb38c 100644 --- a/packages/client/ui-workspace/src/client/index.ts +++ b/packages/client/ui-workspace/src/client/index.ts @@ -3,9 +3,12 @@ * the sidebar shell's `sidebar.workspaces` hole (the whole browsing region), * and WorkspacePicker fills the conversation hero's picker hole * (`conversation.hero.workspace` — both hero forms). Both read real Host - * Workspaces through the global useWorkspaces hook. Export discipline: + * Workspaces through the global useWorkspaces hook, and each declares its + * own `single` directory-flow child hole for the composed picker package's + * client half (see the contract module doc). Export discipline: * packages/client/AGENTS.md. */ +import { deferRegistration } from '@deepseek-ai/dsh-client-ui-slots' import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' import type { WorkspaceBrowserInjected, WorkspacePickerInjected } from './contract/slots.ts' import { createWorkspaceViewStore } from './stores.ts' @@ -13,6 +16,7 @@ import { WorkspaceBrowser } from './WorkspaceBrowser.tsx' import { WorkspacePicker } from './WorkspacePicker.tsx' export type { + DirectoryFlowOwnerProps, DirectoryFlowSlotName, DirectoryPickingInjected, WorkspaceBrowserInjected, WorkspaceBrowserProps, WorkspacePickerInjected, WorkspacePickerProps, } from './contract/slots.ts' @@ -44,50 +48,40 @@ export function apply(ctx: ClientContext): void { await ctx.workspaces.insertSessionBefore(workspaceId, sessionId, beforeSessionId) }, createWorkspace: input => ctx.workspaces.create(input), - pickDirectory: () => ctx.workspaces.pickDirectory(), - directoryPickerKind: () => ctx.workspaces.directoryPickerKind(), + hasDirectoryFlow: () => ctx.slots.entries('sidebar.workspaces.directoryFlow').length > 0, }) const pickerInjected = (): WorkspacePickerInjected => ({ createWorkspace: input => ctx.workspaces.create(input), - pickDirectory: () => ctx.workspaces.pickDirectory(), - directoryPickerKind: () => ctx.workspaces.directoryPickerKind(), + hasDirectoryFlow: () => ctx.slots.entries('conversation.hero.workspace.directoryFlow').length > 0, }) - // Declaration-aware registration: each owner's declaring apply may activate - // after this one (entry activation order is unconstrained), and a register - // into an undeclared slot throws. Register once the declaration is on the - // ledger; the subscription also re-registers after an HMR collapse - // re-declares the slot (the cascade disposed our entry with it). + // Declaration-aware registration (deferRegistration): each owner's + // declaring apply may activate after this one, and a register into an + // undeclared slot throws; the deferral also re-registers after an HMR + // collapse re-declares the slot. Each registration declares its own + // directory-flow child hole in the same call (declaration = render + // authorization, one table). ctx.effect(() => { - const registrations = [ - { - name: 'sidebar.workspaces' as const, - component: WorkspaceBrowser, - register: () => ctx.slots.register( - { name: 'sidebar.workspaces', store: createWorkspaceViewStore(), inject: browserInjected }, + const deferred = [ + deferRegistration(ctx.slots, 'sidebar.workspaces', WorkspaceBrowser, () => + ctx.slots.register( + { + name: 'sidebar.workspaces', + children: { 'sidebar.workspaces.directoryFlow': { kind: 'single', scope: 'root' } }, + store: createWorkspaceViewStore(), + inject: browserInjected, + }, WorkspaceBrowser, - ), - }, - { - name: 'conversation.hero.workspace' as const, - component: WorkspacePicker, - register: () => ctx.slots.register( - { name: 'conversation.hero.workspace', inject: pickerInjected }, + )), + deferRegistration(ctx.slots, 'conversation.hero.workspace', WorkspacePicker, () => + ctx.slots.register( + { + name: 'conversation.hero.workspace', + children: { 'conversation.hero.workspace.directoryFlow': { kind: 'single', scope: 'root' } }, + inject: pickerInjected, + }, WorkspacePicker, - ), - }, + )), ] - const disposers = new Map void>() - const tryRegister = (entry: (typeof registrations)[number]): void => { - if (ctx.slots.spec(entry.name) === undefined) return - if (ctx.slots.entries(entry.name).some(e => e.component === entry.component)) return - disposers.set(entry.name, entry.register()) - } - const unsubscribers = registrations.map(entry => - ctx.slots.subscribe(entry.name, () => { tryRegister(entry) })) - for (const entry of registrations) tryRegister(entry) - return () => { - for (const unsubscribe of unsubscribers) unsubscribe() - for (const dispose of disposers.values()) dispose() - } + return () => { for (const entry of deferred) entry.dispose() } }, 'ui-workspace: browser + picker registrations') } diff --git a/packages/client/ui-workspace/tests/apply.spec.ts b/packages/client/ui-workspace/tests/apply.spec.ts index e670a05e9b..4ef3738d01 100644 --- a/packages/client/ui-workspace/tests/apply.spec.ts +++ b/packages/client/ui-workspace/tests/apply.spec.ts @@ -14,18 +14,16 @@ async function bench() { path: 'name' in input ? `/projects/${input.name}` : input.path, title: 'new', sessionIds: [], createdAt: '0', updatedAt: '0', })) - const pickDirectory = vi.fn(async () => '/tmp/picked') - const directoryPickerKind = vi.fn(async () => 'native' as const) const startSession = vi.fn() const rename = vi.fn(async () => ({})) const insertSessionBefore = vi.fn(async () => ({})) const open = vi.fn() const clear = vi.fn() ctx.provide('workspaces', { - create, pickDirectory, directoryPickerKind, startSession, rename, insertSessionBefore, + create, startSession, rename, insertSessionBefore, } as never) ctx.provide('sessions', { open, clear } as never) - return { ctx, slots: ctx.get('slots') as SlotsService, create, pickDirectory, directoryPickerKind, startSession, rename, insertSessionBefore, open, clear } + return { ctx, slots: ctx.get('slots') as SlotsService, create, startSession, rename, insertSessionBefore, open, clear } } type HoleName = 'sidebar.workspaces' | 'conversation.hero.workspace' | 'conversation.empty.workspace' @@ -74,18 +72,30 @@ describe('ui-workspace apply', () => { expect(b.insertSessionBefore).toHaveBeenCalledWith('ws', 's1', 's2') await browser.createWorkspace({ name: 'project' }) expect(b.create).toHaveBeenCalledWith({ name: 'project' }) - await browser.pickDirectory() - expect(b.pickDirectory).toHaveBeenCalledOnce() - await browser.directoryPickerKind() - expect(b.directoryPickerKind).toHaveBeenCalledOnce() const picker = (b.slots.entries('conversation.hero.workspace')[0]!.inject as () => WorkspacePickerInjected)() await picker.createWorkspace({ path: '/tmp/project' }) expect(b.create).toHaveBeenCalledWith({ path: '/tmp/project' }) - await picker.pickDirectory() - expect(b.pickDirectory).toHaveBeenCalledTimes(2) - await picker.directoryPickerKind() - expect(b.directoryPickerKind).toHaveBeenCalledTimes(2) + }) + + it('declares the two directory-flow holes and reports their occupancy per surface', async () => { + const b = await bench() + declare(b.slots, 'sidebar.workspaces', 'conversation.hero.workspace') + await b.ctx.plugin({ inject: [...inject], apply }).await() + // Registration declared the child holes (declaration = render authorization). + expect(b.slots.spec('sidebar.workspaces.directoryFlow')).toMatchObject({ kind: 'single' }) + expect(b.slots.spec('conversation.hero.workspace.directoryFlow')).toMatchObject({ kind: 'single' }) + + const browser = (b.slots.entries('sidebar.workspaces')[0]!.inject as () => WorkspaceBrowserInjected)() + const picker = (b.slots.entries('conversation.hero.workspace')[0]!.inject as () => WorkspacePickerInjected)() + expect(browser.hasDirectoryFlow()).toBe(false) + expect(picker.hasDirectoryFlow()).toBe(false) + // A flow occupant flips exactly its own surface. + const dispose = b.slots.register({ name: 'sidebar.workspaces.directoryFlow' } as never, () => null) + expect(browser.hasDirectoryFlow()).toBe(true) + expect(picker.hasDirectoryFlow()).toBe(false) + dispose() + expect(browser.hasDirectoryFlow()).toBe(false) }) it('unregisters every entry on teardown', async () => { diff --git a/packages/client/ui-workspace/tests/workspace-browser.spec.tsx b/packages/client/ui-workspace/tests/workspace-browser.spec.tsx index 5561394348..e4b038b0f3 100644 --- a/packages/client/ui-workspace/tests/workspace-browser.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-browser.spec.tsx @@ -59,8 +59,8 @@ function mount(overrides: Partial = {}) { deleteWorkspace: vi.fn(async () => {}), insertSessionBefore: vi.fn(async () => {}), createWorkspace: vi.fn(async () => workspace('created', [])), - pickDirectory: vi.fn(async () => null), - directoryPickerKind: vi.fn(async () => 'native' as const), + hasDirectoryFlow: () => true, + renderSlot: ((_name: string, owner: { open: boolean }) => (owner.open ?
: null)) as never, ...overrides, } const view = render() @@ -264,13 +264,11 @@ describe('WorkspaceBrowser', () => { } }) - it('rail create-workspace toggles the create-only picker in place, without expanding', async () => { + it('rail create-workspace toggles the create-only picker in place, without expanding', () => { const expandSidebar = vi.fn() mount({ wide: false, expandSidebar, useWorkspaces: hook(workspaceState([workspace('alpha', [])])) }) fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) expect(expandSidebar).not.toHaveBeenCalled() - // Flush the advertised-kind read that gates the local-folder entry. - await act(async () => {}) // createOnly: existing workspaces are not listed, only the create actions. expect(screen.queryByRole('menuitem', { name: 'alpha' })).toBeNull() expect(screen.getByRole('menuitem', { name: 'Open local folder…' })).toBeTruthy() diff --git a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx index 7c661cc7c2..dbbb444de2 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx @@ -5,6 +5,7 @@ import type { SessionListState, WorkspaceId, WorkspaceListState, WorkspaceView, } from '@deepseek-ai/dsh-client-runtime/client' import { WorkspaceCreateError } from '@deepseek-ai/dsh-client-runtime/client' +import type { DirectoryFlowOwnerProps } from '../src/client/contract/slots.ts' import { WorkspacePicker } from '../src/client/WorkspacePicker.tsx' afterEach(cleanup) @@ -35,15 +36,29 @@ function anchor(): { current: HTMLElement } { return { current: element } } +/** + * Probe occupant of the directory-flow hole: records the latest owner + * conversation so tests drive onPicked/onCancel/onError like a composed flow + * package would, and renders a marker element while the flow is open. + */ +function flowProbe() { + const probe: { owner: DirectoryFlowOwnerProps | undefined } = { owner: undefined } + const renderSlot = ((_name: string, owner: DirectoryFlowOwnerProps) => { + probe.owner = owner + return owner.open ?
: null + }) as never + return { probe, renderSlot } +} + function mount( items: readonly WorkspaceView[] = [workspace('alpha', 'Alpha')], createWorkspace = vi.fn(), - pickDirectory = vi.fn(async () => null as string | null), - directoryPickerKind = vi.fn(async () => 'native'), + hasDirectoryFlow: () => boolean = () => true, ) { const onPick = vi.fn() const onClose = vi.fn() const anchorRef = anchor() + const { probe, renderSlot } = flowProbe() const renderPicker = (nextItems: readonly WorkspaceView[]) => ( ) const view = render( renderPicker(items), ) return { - view, onPick, onClose, createWorkspace, pickDirectory, directoryPickerKind, + view, onPick, onClose, createWorkspace, probe, rerenderItems: (nextItems: readonly WorkspaceView[]) => { view.rerender(renderPicker(nextItems)) }, } } -// findByRole, not getByRole: the folder entry renders only after the advertised -// picker kind resolves, one microtask after the menu opens. -async function chooseItem(name: 'Open local folder…' | 'Create a new workspace'): Promise { - fireEvent.click(await screen.findByRole('menuitem', { name })) +function chooseItem(name: 'Open local folder…' | 'Create a new workspace'): void { + fireEvent.click(screen.getByRole('menuitem', { name })) } describe('WorkspacePicker', () => { @@ -83,7 +96,7 @@ describe('WorkspacePicker', () => { const created = workspace('new', 'New') const createWorkspace = vi.fn(async () => created) const b = mount([], createWorkspace) - await chooseItem('Create a new workspace') + chooseItem('Create a new workspace') const input = screen.getByLabelText('New workspace name') fireEvent.change(input, { target: { value: 'project-one' } }) fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) @@ -91,78 +104,84 @@ describe('WorkspacePicker', () => { await waitFor(() => { expect(b.onPick).toHaveBeenCalledWith(created.workspaceId) }) }) - it('opens a native directory picker, adopts its path, and selects the returned Workspace', async () => { + it('opens the composed directory flow, adopts its picked path, and selects the returned Workspace', async () => { const created = { ...workspace('adopted'), path: '/tmp/project', title: 'project' } const createWorkspace = vi.fn(async () => created) - const pickDirectory = vi.fn(async () => '/tmp/project') - const b = mount([], createWorkspace, pickDirectory) - await chooseItem('Open local folder…') - expect(pickDirectory).toHaveBeenCalledOnce() - await waitFor(() => { expect(createWorkspace).toHaveBeenCalledWith({ path: '/tmp/project' }) }) + const b = mount([], createWorkspace) + expect(screen.queryByTestId('directory-flow')).toBeNull() + chooseItem('Open local folder…') + expect(b.onClose).toHaveBeenCalled() + expect(screen.getByTestId('directory-flow')).toBeTruthy() + await act(async () => { b.probe.owner!.onPicked('/tmp/project') }) expect(createWorkspace).toHaveBeenCalledWith({ path: '/tmp/project' }) await waitFor(() => { expect(b.onPick).toHaveBeenCalledWith(created.workspaceId) }) + // Successful adoption withdraws the flow request. + expect(screen.queryByTestId('directory-flow')).toBeNull() }) - it('treats native picker cancellation as a silent no-op', async () => { - const b = mount([], vi.fn(), vi.fn(async () => null)) - await chooseItem('Open local folder…') - await waitFor(() => { expect(b.pickDirectory).toHaveBeenCalledOnce() }) + it('treats flow cancellation as a silent no-op', () => { + const b = mount([]) + chooseItem('Open local folder…') + act(() => { b.probe.owner!.onCancel() }) + expect(screen.queryByTestId('directory-flow')).toBeNull() expect(b.createWorkspace).not.toHaveBeenCalled() expect(b.onPick).not.toHaveBeenCalled() expect(screen.queryByRole('dialog')).toBeNull() }) - it('shows a name conflict and retries through the native picker', async () => { - const pickDirectory = vi.fn() - .mockResolvedValueOnce('/one/project') - .mockResolvedValueOnce(null) + it('shows a name conflict and retries by reopening the flow', async () => { const createWorkspace = vi.fn(async () => { throw new WorkspaceCreateError({ code: 'workspace-name-conflict', message: 'project already exists', details: { name: 'project' }, }) }) - const b = mount([], createWorkspace, pickDirectory) - await chooseItem('Open local folder…') + const b = mount([], createWorkspace) + chooseItem('Open local folder…') + await act(async () => { b.probe.owner!.onPicked('/one/project') }) await waitFor(() => { expect(screen.getByRole('dialog', { name: 'A workspace with this name already exists' })).toBeTruthy() }) expect(screen.getByRole('alert').textContent).toBe('Choose a folder with a different name.') + // The failed adoption withdrew the flow; Choose again reopens it. + expect(b.probe.owner!.open).toBe(false) fireEvent.click(screen.getByRole('button', { name: 'Choose again' })) - await waitFor(() => { expect(pickDirectory).toHaveBeenCalledTimes(2) }) + expect(b.probe.owner!.open).toBe(true) expect(b.onPick).not.toHaveBeenCalled() }) - it('disables the folder action while the native picker is already open', async () => { - let resolve!: (path: string | null) => void - const pending = new Promise((settle) => { resolve = settle }) - const b = mount([], vi.fn(), vi.fn(() => pending)) - await chooseItem('Open local folder…') + it('disables the create actions and reports busy to the flow while adopting', async () => { + let resolve!: (workspace: WorkspaceView) => void + const pending = new Promise((settle) => { resolve = settle }) + const created = workspace('adopted') + const b = mount([], vi.fn(() => pending)) + chooseItem('Open local folder…') + act(() => { b.probe.owner!.onPicked('/tmp/project') }) + expect(b.probe.owner!.busy).toBe(true) expect(screen.getByRole('menuitem', { name: 'Open local folder…' }).disabled).toBe(true) expect(screen.getByRole('menuitem', { name: 'Create a new workspace' }).disabled).toBe(true) - fireEvent.click(screen.getByRole('menuitem', { name: 'Open local folder…' })) - expect(b.pickDirectory).toHaveBeenCalledTimes(1) - await act(async () => { resolve(null); await pending }) + await act(async () => { resolve(created); await pending }) + expect(b.probe.owner!.busy).toBe(false) }) - it('reports non-Error native picker failures', async () => { - const b = mount([], vi.fn(), vi.fn(async () => { throw 'picker unavailable' })) - await chooseItem('Open local folder…') - await waitFor(() => { - expect(screen.getByRole('alert').textContent).toBe('picker unavailable') - }) + it('shows the flow-reported failure in the folder-error surface', () => { + const b = mount([]) + chooseItem('Open local folder…') + act(() => { b.probe.owner!.onError('no chooser installed') }) + expect(screen.getByRole('alert').textContent).toBe('no chooser installed') + expect(screen.queryByTestId('directory-flow')).toBeNull() expect(b.createWorkspace).not.toHaveBeenCalled() }) - it('closes a creation modal when the user cancels', async () => { + it('closes a creation modal when the user cancels', () => { mount([]) - await chooseItem('Create a new workspace') + chooseItem('Create a new workspace') fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) expect(screen.queryByRole('dialog')).toBeNull() }) - it('blocks a create-new name already present in the Workspace list', async () => { + it('blocks a create-new name already present in the Workspace list', () => { const b = mount([workspace('alpha', 'Alpha')]) - await chooseItem('Create a new workspace') + chooseItem('Create a new workspace') fireEvent.change(screen.getByLabelText('New workspace name'), { target: { value: ' Alpha ' } }) expect(screen.getByRole('alert').textContent).toBe('A workspace named “Alpha” already exists.') expect(screen.getByRole('button', { name: 'Create workspace' }).disabled).toBe(true) @@ -175,7 +194,7 @@ describe('WorkspacePicker', () => { const pending = new Promise((settle) => { resolve = settle }) const created = workspace('fresh', 'same-name') const b = mount([], vi.fn(() => pending)) - await chooseItem('Create a new workspace') + chooseItem('Create a new workspace') fireEvent.change(screen.getByLabelText('New workspace name'), { target: { value: 'same-name' } }) fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) @@ -191,7 +210,7 @@ describe('WorkspacePicker', () => { const pending = new Promise((_resolve, rejectPromise) => { reject = rejectPromise }) const createWorkspace = vi.fn(() => pending) const b = mount([], createWorkspace) - await chooseItem('Create a new workspace') + chooseItem('Create a new workspace') const input = screen.getByLabelText('New workspace name') fireEvent.keyDown(input, { key: 'ArrowRight' }) fireEvent.change(input, { target: { value: 'broken' } }) @@ -208,7 +227,7 @@ describe('WorkspacePicker', () => { it('reports non-Error creation failures', async () => { const b = mount([], vi.fn(async () => { throw 'permission denied' })) - await chooseItem('Create a new workspace') + chooseItem('Create a new workspace') // The name field starts empty (no prefill); a name is required to submit. fireEvent.change(screen.getByLabelText('New workspace name'), { target: { value: 'broken' } }) fireEvent.click(screen.getByRole('button', { name: 'Create workspace' })) @@ -219,11 +238,12 @@ describe('WorkspacePicker', () => { }) it('waits to show its menu until an optional anchor is available', () => { + const { renderSlot } = flowProbe() render( 'native')} + onPick={vi.fn()} onClose={vi.fn()} createWorkspace={vi.fn()} + hasDirectoryFlow={() => true} renderSlot={renderSlot} />, ) expect(screen.queryByRole('menu')).toBeNull() @@ -233,101 +253,31 @@ describe('WorkspacePicker', () => { const state: WorkspaceListState = { ...workspaceState([]), phase: 'pending', state: 'loading', baselinesReady: false, } + const { renderSlot } = flowProbe() render( 'native')} + onPick={vi.fn()} onClose={vi.fn()} createWorkspace={vi.fn()} + hasDirectoryFlow={() => true} renderSlot={renderSlot} />, ) expect(screen.getByRole('status').textContent).toBe('Loading workspaces…') }) - it('hides the folder affordance unless the Host advertises the dialog interaction', async () => { - const b = mount([], vi.fn(), vi.fn(async () => null), vi.fn(async () => 'browse')) - await screen.findByRole('menuitem', { name: 'Create a new workspace' }) - await waitFor(() => { expect(b.directoryPickerKind).toHaveBeenCalled() }) + it('hides the folder entry while the directory-flow hole is empty', () => { + mount([], vi.fn(), () => false) + expect(screen.getByRole('menuitem', { name: 'Create a new workspace' })).toBeTruthy() expect(screen.queryByRole('menuitem', { name: 'Open local folder…' })).toBeNull() }) - it('hides the folder affordance when the Host cannot answer describe', async () => { - const b = mount([], vi.fn(), vi.fn(async () => null), vi.fn(async () => { - throw new Error('host unreachable') - })) - await screen.findByRole('menuitem', { name: 'Create a new workspace' }) - await waitFor(() => { expect(b.directoryPickerKind).toHaveBeenCalled() }) + it('shows the folder entry once the hole reports an occupant on a later render', () => { + let occupied = false + const b = mount([], vi.fn(), () => occupied) expect(screen.queryByRole('menuitem', { name: 'Open local folder…' })).toBeNull() - }) - - it('does not read the picker kind while the flow is closed', () => { - const directoryPickerKind = vi.fn(async () => 'native') - render( - , - ) - expect(directoryPickerKind).not.toHaveBeenCalled() - }) - - /** Render the picker with an owner-controlled `open` and a scripted kind read. */ - function togglable(directoryPickerKind: () => Promise) { - const anchorRef = anchor() - const props = (open: boolean) => ( - - ) - const view = render(props(true)) - return { setOpen: (open: boolean) => { view.rerender(props(open)) } } - } - - it('discards a kind settlement from a superseded flow open', async () => { - let resolveFirst!: (kind: string) => void - const first = new Promise((settle) => { resolveFirst = settle }) - const directoryPickerKind = vi.fn<() => Promise>() - .mockImplementationOnce(() => first) - .mockImplementation(async () => 'browse') - const t = togglable(directoryPickerKind) - // Close while the first read is in flight, then let it answer 'native': - // the settlement is stale and must not leak into the next open. - t.setOpen(false) - await act(async () => { resolveFirst('native') }) - t.setOpen(true) - await screen.findByRole('menuitem', { name: 'Create a new workspace' }) - await waitFor(() => { expect(directoryPickerKind).toHaveBeenCalledTimes(2) }) - expect(screen.queryByRole('menuitem', { name: 'Open local folder…' })).toBeNull() - }) - - it('clears the advertised kind on close so a reopen cannot paint the previous host entry', async () => { - const directoryPickerKind = vi.fn<() => Promise>() - .mockImplementationOnce(async () => 'native') - // The reopened read never settles: the assertion below sees the paint - // that precedes any fresh answer. - .mockImplementation(() => new Promise(() => {})) - const t = togglable(directoryPickerKind) - await screen.findByRole('menuitem', { name: 'Open local folder…' }) - t.setOpen(false) - t.setOpen(true) - await screen.findByRole('menuitem', { name: 'Create a new workspace' }) - expect(screen.queryByRole('menuitem', { name: 'Open local folder…' })).toBeNull() - }) - - it('discards a stale describe failure after a newer open already answered', async () => { - let rejectFirst!: (reason: Error) => void - const first = new Promise((_settle, reject) => { rejectFirst = reject }) - const directoryPickerKind = vi.fn<() => Promise>() - .mockImplementationOnce(() => first) - .mockImplementation(async () => 'native') - const t = togglable(directoryPickerKind) - t.setOpen(false) - t.setOpen(true) - await screen.findByRole('menuitem', { name: 'Open local folder…' }) - // The superseded read failing late must not hide the freshly shown entry. - await act(async () => { rejectFirst(new Error('late loss')); await first.catch(() => {}) }) + // A flow package activating after the first paint is observed on the + // next render — the same cadence as reopening the menu. + occupied = true + b.rerenderItems([]) expect(screen.getByRole('menuitem', { name: 'Open local folder…' })).toBeTruthy() }) }) diff --git a/packages/host/README.i18n.yaml b/packages/host/README.i18n.yaml index f50948eb6d..9a6deda327 100644 --- a/packages/host/README.i18n.yaml +++ b/packages/host/README.i18n.yaml @@ -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/README.md -README.md: 0810be58fc773a241528656d7f6e826e9c3aabda -README.zh.md: f9133eee8498594d913b2fe0814ac51d712b678d +README.md: 7df0ecc4a362be1149188d133233307b1fc48c8a +README.zh.md: 90d5ea2b0947d2cff9ba06e89b6225b39dad7fce diff --git a/packages/host/README.md b/packages/host/README.md index 0810be58fc..7df0ecc4a3 100644 --- a/packages/host/README.md +++ b/packages/host/README.md @@ -9,7 +9,7 @@ The host side of the dsh web GUI: the API gateway every client shape shares, and | `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/` | Native-OS-chooser backend (osascript / PowerShell / Zenity+KDialog); host-display only | (registers `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/` | In-app browsing backend: listing/creation primitives over Node stdlib; remote-capable | (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. diff --git a/packages/host/README.zh.md b/packages/host/README.zh.md index f9133eee84..90d5ea2b09 100644 --- a/packages/host/README.zh.md +++ b/packages/host/README.zh.md @@ -9,7 +9,7 @@ dsh web GUI 的宿主侧:所有客户端形态共用的 API 网关,以及承 | `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);仅宿主屏幕可用 | (注册 `ctx.directoryPicker`) | +| `directory-picker-native/` | 双面原生交互:OS 选择器后端(osascript/PowerShell/Zenity+KDialog,仅宿主屏幕可用)+ 填入 ui-workspace 目录流 slot 的 browser half | (注册 `ctx.directoryPicker`) | | `directory-picker-browse/` | 应用内浏览后端:基于 Node 标准库的列举/创建原语;支持远程 | (注册 `ctx.directoryPicker`) | `apiproxy` 在设计上与传输方式无关——它不注册任何路由;载体自行包装 `ctx.apiProxy`。HTTP 载体路由(连同其 `/api` 浏览器信任栅栏)由 [`client/connection`](../client/connection/README.md) 的 node 半侧挂载,这正是该包住在 client 组的原因:它拥有这条线的两端。 diff --git a/packages/host/apiproxy/README.i18n.yaml b/packages/host/apiproxy/README.i18n.yaml index ee91f44ce8..73b0845370 100644 --- a/packages/host/apiproxy/README.i18n.yaml +++ b/packages/host/apiproxy/README.i18n.yaml @@ -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: 3639722ab25826af8f7a0721f22d244f78b4210b -README.zh.md: 3ac81fb412d4e4caf192953bc7a7c846a1d29965 +README.md: ca4471454f5be5d3fcba38ce665d4fb3fbd85e74 +README.zh.md: 953539e1198a52b2bf7cdd9ca1b0d263cc2ae6f9 diff --git a/packages/host/apiproxy/README.md b/packages/host/apiproxy/README.md index 9beead944f..ca4471454f 100644 --- a/packages/host/apiproxy/README.md +++ b/packages/host/apiproxy/README.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()`. -Directory picking delegates to the composed `ctx.directoryPicker` backend ([the directory-picker seam](../directory-picker/README.md)); `host.describe.directoryPicker` advertises the capability kind the client renders for, and a method called outside the advertised kind fails with `directory-picker-unavailable`. 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. +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`. diff --git a/packages/host/apiproxy/README.zh.md b/packages/host/apiproxy/README.zh.md index a32fbb9074..953539e119 100644 --- a/packages/host/apiproxy/README.zh.md +++ b/packages/host/apiproxy/README.zh.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()` 中。 -目录选择委托给组合的 `ctx.directoryPicker` 后端([目录选择 seam](../directory-picker/README.md));`host.describe.directoryPicker` 广播客户端应按其渲染的能力 kind,调用广播之外的方法会以 `directory-picker-unavailable` 失败。在 `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` 请求一样覆盖上述全部方法。 +目录选择委托给组合的 `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` 相同的回环、同源限制。 diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index 8b68d53e30..9a95ba6fd4 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -1009,7 +1009,6 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro provider: defaults.provider, model: defaults.model, attachedSessions: ctx.agents.list().length, - directoryPicker: ctx.directoryPicker.capability().kind, })) }, diff --git a/packages/host/apiproxy/src/api/host.schema.ts b/packages/host/apiproxy/src/api/host.schema.ts index 97c3979ed8..f5d17421fb 100644 --- a/packages/host/apiproxy/src/api/host.schema.ts +++ b/packages/host/apiproxy/src/api/host.schema.ts @@ -19,7 +19,6 @@ export const hostDescribeValueSchema = z.object({ 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). - directoryPicker: z.string(), }) satisfies z.ZodType>> /** host.pickDirectory request payload (empty object literal). */ diff --git a/packages/host/apiproxy/src/api/host.ts b/packages/host/apiproxy/src/api/host.ts index 2c84998bfc..937fa905af 100644 --- a/packages/host/apiproxy/src/api/host.ts +++ b/packages/host/apiproxy/src/api/host.ts @@ -5,18 +5,6 @@ import type { RpcRequest, RpcResponse } from './rpc.ts' -/** - * The composed directory-picker interaction the host serves (mirror of the - * `ctx.directoryPicker` capability kind): `native` = one OS chooser on - * the host display (`host.pickDirectory`); `browse` = in-app listing/creation - * primitives (`host.listDirectory`/`host.createDirectory`). Calling a method - * outside the advertised kind fails with `directory-picker-unavailable`. - * The wire preserves kinds beyond the two with methods here (a merge-added - * capability advertises before its RPCs exist); the client's documented - * default for a kind it does not recognize is to hide the picking affordance. - */ -export type DirectoryPickerKind = 'native' | 'browse' | (string & {}) - /** 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). */ @@ -51,7 +39,6 @@ export interface HostApi { * 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); - * directoryPicker = the composed picker interaction the client renders for. */ describe(request: RpcRequest<{}>): Promise> /** diff --git a/packages/host/apiproxy/src/api/index.ts b/packages/host/apiproxy/src/api/index.ts index bb6f7d51c3..7944336b36 100644 --- a/packages/host/apiproxy/src/api/index.ts +++ b/packages/host/apiproxy/src/api/index.ts @@ -29,7 +29,7 @@ export type { HistoryEntry, ModelCatalogFailure, ModelCatalogModel, ModelProviderGroup, ModelReasoning, ModelReasoningEffort, ModelTarget, SessionModels, SessionProjectionsBlock, SessionsApi, SessionSummary, } from './sessions.ts' -export type { DirectoryEntry, DirectoryListing, DirectoryPickerKind, 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' diff --git a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts index 5d1989ab5d..e978db9f9b 100644 --- a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts @@ -192,17 +192,14 @@ describe('host.listDirectory / host.createDirectory', () => { }) }) - it('refuses the browse RPCs under a native composition and advertises the kind in describe', async () => { + it('refuses the browse RPCs under a native composition', async () => { const { api } = await harness() - expect((await api.host.describe(request({}))).result).toMatchObject({ ok: true, value: { directoryPicker: 'native' } }) expect((await api.host.listDirectory(request({}))).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' } }, }) - const browse = await harness(undefined, BROWSE_STUB) - expect((await browse.api.host.describe(request({}))).result).toMatchObject({ ok: true, value: { directoryPicker: 'browse' } }) }) }) diff --git a/packages/host/apiproxy/tests/client-handler.spec.ts b/packages/host/apiproxy/tests/client-handler.spec.ts index 8ec798238e..fc1dfd777a 100644 --- a/packages/host/apiproxy/tests/client-handler.spec.ts +++ b/packages/host/apiproxy/tests/client-handler.spec.ts @@ -48,7 +48,7 @@ function scriptedApi(overrides: { ...overrides.sessions, }, host: { - describe: r => ok(r, { version: '0-test', cwd: '/t', attachedSessions: 0, directoryPicker: 'browse' as const }), + 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: [] }), createDirectory: r => ok(r, { path: '/t/new' }), diff --git a/packages/host/apiproxy/tests/fetch-carrier.spec.ts b/packages/host/apiproxy/tests/fetch-carrier.spec.ts index cac34e2ec1..bf0be224f2 100644 --- a/packages/host/apiproxy/tests/fetch-carrier.spec.ts +++ b/packages/host/apiproxy/tests/fetch-carrier.spec.ts @@ -76,7 +76,7 @@ function fakeApi(overrides: Partial<{ muxFrames: MuxFrame[]; hostFrames: HostFra }, host: { async describe(request) { - return { rpcId: request.rpcId, result: { ok: true, value: { version: 'v', cwd: '/w', attachedSessions: 0, directoryPicker: 'native' as const } } } + return { rpcId: request.rpcId, result: { ok: true, value: { version: 'v', cwd: '/w', attachedSessions: 0 } } } }, async pickDirectory(request) { return { rpcId: request.rpcId, result: { ok: true, value: { path: null } } } diff --git a/packages/host/apiproxy/tests/rpc-schemas.spec.ts b/packages/host/apiproxy/tests/rpc-schemas.spec.ts index 5c9ced4249..6c400871ae 100644 --- a/packages/host/apiproxy/tests/rpc-schemas.spec.ts +++ b/packages/host/apiproxy/tests/rpc-schemas.spec.ts @@ -218,12 +218,9 @@ describe('sessions domain schemas', () => { describe('host domain schemas', () => { it('validates describe request/value', () => { expect(hostDescribeRequestSchema.parse({})).toEqual({}) - const value = hostDescribeValueSchema.parse({ version: '1', cwd: '/x', provider: 'p', model: 'm', attachedSessions: 2, directoryPicker: 'native' }) + const value = hostDescribeValueSchema.parse({ version: '1', cwd: '/x', provider: 'p', model: 'm', attachedSessions: 2 }) expect(value.attachedSessions).toBe(2) - expect(hostDescribeValueSchema.parse({ version: '1', cwd: '/x', attachedSessions: 0, directoryPicker: 'browse' }).provider).toBeUndefined() - // A kind beyond the two with methods survives the wire (merge-added - // capabilities advertise; the client hides the affordance). - expect(hostDescribeValueSchema.parse({ version: '1', cwd: '/x', attachedSessions: 0, directoryPicker: 'other' }).directoryPicker).toBe('other') + expect(hostDescribeValueSchema.parse({ version: '1', cwd: '/x', attachedSessions: 0 }).provider).toBeUndefined() }) it('validates the browse listing/creation payloads', () => { diff --git a/packages/host/directory-picker-native/README.i18n.yaml b/packages/host/directory-picker-native/README.i18n.yaml index c67ecdce91..e798bd6471 100644 --- a/packages/host/directory-picker-native/README.i18n.yaml +++ b/packages/host/directory-picker-native/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/directory-picker-native/README.md -README.md: 8e9d6c7c558a6b33c2a37d504c571fd3eda579bb -README.zh.md: 68f23698ff0c1a5ee4456a1f121dcf244f09c72b +README.md: 0b54c651d4f5382021d0f8832ab4f1146b7652c8 +README.zh.md: e5ac2762a691a16a7e6d9d6dd9aefc70a59dcd4f diff --git a/packages/host/directory-picker-native/README.md b/packages/host/directory-picker-native/README.md index 8e9d6c7c55..0b54c651d4 100644 --- a/packages/host/directory-picker-native/README.md +++ b/packages/host/directory-picker-native/README.md @@ -2,7 +2,9 @@ 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 **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 diff --git a/packages/host/directory-picker-native/README.zh.md b/packages/host/directory-picker-native/README.zh.md index 68f23698ff..e5ac2762a6 100644 --- a/packages/host/directory-picker-native/README.zh.md +++ b/packages/host/directory-picker-native/README.zh.md @@ -2,7 +2,9 @@ [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`)与平台事实可注入,便于确定性测试。 +[目录选择 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)。 ## 模型体验 diff --git a/packages/host/directory-picker-native/package.json b/packages/host/directory-picker-native/package.json index 72cb8a3e8a..bafe18e09f 100644 --- a/packages/host/directory-picker-native/package.json +++ b/packages/host/directory-picker-native/package.json @@ -15,12 +15,17 @@ "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" @@ -31,11 +36,27 @@ "@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" + "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:^", - "cordis": "^4.0.0-rc.7" + "@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" } } diff --git a/packages/host/directory-picker-native/src/client/index.ts b/packages/host/directory-picker-native/src/client/index.ts new file mode 100644 index 0000000000..29b7876d2f --- /dev/null +++ b/packages/host/directory-picker-native/src/client/index.ts @@ -0,0 +1,73 @@ +/** + * 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 { useEffect, useRef } from 'react' +import type { ReactElement } from 'react' +import { deferRegistration } from '@deepseek-ai/dsh-client-ui-slots' +import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client' +// Type-only: the SlotMap merge declaring the directory-flow holes and their owner contract. +import type { DirectoryFlowOwnerProps } from '@deepseek-ai/dsh-client-ui-workspace/client' + +/** Injected face: the wire call the flow drives (bound in apply's closure). */ +interface NativeFlowInjected { + /** Ask the local Host to open its native single-directory chooser. */ + pick: () => Promise +} + +/** + * 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 + useEffect(() => { + if (!open) { + armed.current = false + return + } + if (armed.current) return + armed.current = true + pick().then( + (path) => { if (path === null) outcome.current.onCancel(); else outcome.current.onPicked(path) }, + (reason: unknown) => { outcome.current.onError(reason instanceof Error ? reason.message : String(reason)) }, + ) + }, [open, pick]) + return null +} + +/** 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(() => { + const deferred = [ + deferRegistration(ctx.slots, 'conversation.hero.workspace.directoryFlow', NativeDirectoryFlow, () => + ctx.slots.register({ name: 'conversation.hero.workspace.directoryFlow', inject: injected }, NativeDirectoryFlow)), + deferRegistration(ctx.slots, 'sidebar.workspaces.directoryFlow', NativeDirectoryFlow, () => + ctx.slots.register({ name: 'sidebar.workspaces.directoryFlow', inject: injected }, NativeDirectoryFlow)), + ] + return () => { for (const entry of deferred) entry.dispose() } + }, 'directory-picker-native: flow registrations') +} diff --git a/packages/host/directory-picker-native/src/native-picker.ts b/packages/host/directory-picker-native/src/native-picker.ts index ee3d3075e5..2c8e236acc 100644 --- a/packages/host/directory-picker-native/src/native-picker.ts +++ b/packages/host/directory-picker-native/src/native-picker.ts @@ -1,4 +1,4 @@ -/** Cross-platform native single-directory chooser behind the dialog backend's capability. */ +/** Cross-platform native single-directory chooser behind the native backend's capability. */ import { runNativeCommand, type NativeCommandRunner } from '@deepseek-ai/dsh-native-command' diff --git a/packages/host/directory-picker-native/tests/client-flow.spec.tsx b/packages/host/directory-picker-native/tests/client-flow.spec.tsx new file mode 100644 index 0000000000..cf2cb96679 --- /dev/null +++ b/packages/host/directory-picker-native/tests/client-flow.spec.tsx @@ -0,0 +1,123 @@ +// @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, NativeDirectoryFlow } from '../src/client/index.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 => '/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 { + 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('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 })() + 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((settle) => { resolve = settle })) + const first = owner() + const view = render() + expect(pick).toHaveBeenCalledOnce() + // Re-renders while open (busy flips, handler identity changes) must not relaunch the chooser. + const second = owner() + view.rerender() + expect(pick).toHaveBeenCalledOnce() + await act(async () => { resolve('/tmp/project') }) + expect(second.onPicked).toHaveBeenCalledWith('/tmp/project') + expect(first.onPicked).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() + await act(async () => {}) + expect(props.onCancel).toHaveBeenCalledOnce() + expect(props.onPicked).not.toHaveBeenCalled() + // Withdraw and reopen: a fresh request runs a fresh pick. + view.rerender() + view.rerender() + await act(async () => {}) + expect(pick).toHaveBeenCalledTimes(2) + }) + + it('folds pick failures into onError messages', async () => { + const props = owner() + render( { throw new Error('no chooser installed') })} />) + await act(async () => {}) + expect(props.onError).toHaveBeenCalledWith('no chooser installed') + + const nonError = owner() + render( { throw 'denied' })} />) + await act(async () => {}) + expect(nonError.onError).toHaveBeenCalledWith('denied') + }) + + it('renders nothing while closed and while open', () => { + const closed = render( null)} />) + expect(closed.container.innerHTML).toBe('') + const opened = render( null)} />) + expect(opened.container.innerHTML).toBe('') + }) +}) diff --git a/packages/host/directory-picker-native/tsconfig.json b/packages/host/directory-picker-native/tsconfig.json index 64a32c3441..395595e836 100644 --- a/packages/host/directory-picker-native/tsconfig.json +++ b/packages/host/directory-picker-native/tsconfig.json @@ -1,19 +1,16 @@ { - "extends": "../../../tsconfig.base.json", + "extends": "../../../tsconfig.base.client.json", "compilerOptions": { "rootDir": "src", - "outDir": "lib/types" + "outDir": "lib/types", + "types": [ + "node" + ] }, "include": [ "src" ], "references": [ - { - "path": "../../../vendor/cosmokit" - }, - { - "path": "../../../vendor/cordis" - }, { "path": "../directory-picker" }, @@ -22,6 +19,15 @@ }, { "path": "../../util/native-command" + }, + { + "path": "../../client/ui-slots" + }, + { + "path": "../../client/runtime" + }, + { + "path": "../../client/ui-workspace" } ] } diff --git a/packages/host/directory-picker-native/tsdown.config.ts b/packages/host/directory-picker-native/tsdown.config.ts new file mode 100644 index 0000000000..4f280f8112 --- /dev/null +++ b/packages/host/directory-picker-native/tsdown.config.ts @@ -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']) diff --git a/packages/host/directory-picker/README.i18n.yaml b/packages/host/directory-picker/README.i18n.yaml index 7ba7c09de0..3e5bae41b5 100644 --- a/packages/host/directory-picker/README.i18n.yaml +++ b/packages/host/directory-picker/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/directory-picker/README.md -README.md: dcac8903522d53a8dd5fd346f124071f0f24b38e -README.zh.md: 5b7fc15513bf19722bd71bcbb30c6d187d6a71f5 +README.md: 8ef8889c875f5b1d07c015ddef819591041c8d7f +README.zh.md: 8aefffa7b29a47205ea42d0d1df742d1e1b2502d diff --git a/packages/host/directory-picker/README.md b/packages/host/directory-picker/README.md index dcac890352..8ef8889c87 100644 --- a/packages/host/directory-picker/README.md +++ b/packages/host/directory-picker/README.md @@ -2,7 +2,7 @@ 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 **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). diff --git a/packages/host/directory-picker/README.zh.md b/packages/host/directory-picker/README.zh.md index 5b7fc15513..8aefffa7b2 100644 --- a/packages/host/directory-picker/README.zh.md +++ b/packages/host/directory-picker/README.zh.md @@ -2,7 +2,7 @@ [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 的文档化默认行为是隐藏选择入口而非失败。能力对象在服务生命周期内必须保持稳定。 +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)。 diff --git a/packages/util/native-command/README.i18n.yaml b/packages/util/native-command/README.i18n.yaml index 7d711e9e28..b57a63ef98 100644 --- a/packages/util/native-command/README.i18n.yaml +++ b/packages/util/native-command/README.i18n.yaml @@ -3,4 +3,4 @@ # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/util/native-command/README.md README.md: 7fc8b1f4640ef87ada62b6656854feb37080e4e6 -README.zh.md: 7c1cacb06d1d58601cc9e63c2ebd9c5f0ccb8159 +README.zh.md: 4bc66c4047194de03f236fa7591dad88e5c3fb57 diff --git a/packages/util/native-command/README.zh.md b/packages/util/native-command/README.zh.md index 7c1cacb06d..4bc66c4047 100644 --- a/packages/util/native-command/README.zh.md +++ b/packages/util/native-command/README.zh.md @@ -4,7 +4,7 @@ 宿主原生 OS 集成共享的**零依赖免 shell `execFile` 运行器**:一次 `runNativeCommand(command, args, signal)` 调用直接派生可执行文件(绝不拼 shell 字符串),以 utf8 捕获 stdout/stderr,把调用方的 abort 传播为子进程终止,并在 Windows 上隐藏瞬时控制台窗口。失败时以附带退出 `code` 与两路已捕获输出的错误拒绝,调用方无需重跑即可分类(工具缺失、已取消、真实失败)。 -它的两个消费者都是宿主侧原生集成:[`directory-picker-native`](../../host/directory-picker-native/README.zh.md) 后端的 OS 选择器命令,以及网关的按默认应用打开转交([`dsh-host-apiproxy`](../../host/apiproxy/README.zh.md) 的 `host.openPath`)。`NativeCommandRunner` 类型是这些调用方为确定性测试暴露的可注入命令边界。 +它的两个消费者都是宿主侧原生集成:[`directory-picker-native`](../../host/directory-picker-native/README.md) 后端的 OS 选择器命令,以及网关的按默认应用打开转交([`dsh-host-apiproxy`](../../host/apiproxy/README.md) 的 `host.openPath`)。`NativeCommandRunner` 类型是这些调用方为确定性测试暴露的可注入命令边界。 它是**库,不是服务或插件**:没有 `ctx`、不注册任何东西、不持有状态、不发事件。 diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9b06cc5b19..d9fd918267 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2760,12 +2760,27 @@ importers: specifier: workspace:^ version: link:../../util/native-command devDependencies: + '@deepseek-ai/dsh-client-runtime': + specifier: workspace:^ + version: link:../../client/runtime + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:^ + version: link:../../client/ui-slots + '@deepseek-ai/dsh-client-ui-workspace': + specifier: workspace:^ + version: link:../../client/ui-workspace '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants + '@types/react': + specifier: ~18.3.1 + version: 18.3.31 cordis: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + react: + specifier: ^18.2.0 + version: 18.3.1 packages/host/webserver: dependencies: diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 87c2be5cfe..4128e4462b 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -423,7 +423,7 @@ const SERVICE_ROLES: ServiceRole[] = [ mode: 'seam', implementations: ['directory-picker-native', 'directory-picker-browse'], consumers: ['apiproxy'], - note: 'Discriminated interaction capability: the native backend opens one OS chooser on the host display, the browse backend serves listing/creation primitives for the in-app browser; the gateway advertises the kind via host.describe.', + note: 'Discriminated interaction capability: the native backend opens one OS chooser on the host display, the browse backend serves listing/creation primitives for the in-app browser; each backend is dual-face, its browser half filling ui-workspace directory-flow slots (no wire advertisement).', }, { key: 'httpServer', diff --git a/tsconfig.client.json b/tsconfig.client.json index 9f67ab4af7..5eb8ffa5a6 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -19,6 +19,8 @@ "packages/client/*/src/css-modules.d.ts", "packages/client/*/tests/**/*.ts", "packages/client/*/tests/**/*.tsx", + "packages/host/directory-picker-native/tests/**/*.ts", + "packages/host/directory-picker-native/tests/**/*.tsx", "packages/client/tsdown.client.ts", "scripts/client-bundle-purity.spec.ts" ], @@ -27,6 +29,10 @@ // smoke policy). webserver has zero workspace deps and no cordis merge, // so it cannot drag host-side Context augmentation into this program. { "path": "./packages/host/webserver" }, + // Dual-face host leaf: the node half is the native picking backend, the + // browser half registers the picking flow into ui-workspace's slot — + // client-side Context merges keep it out of the host program. + { "path": "./packages/host/directory-picker-native" }, { "path": "./packages/client/ui-slots" }, { "path": "./packages/client/ui-primitives" }, { "path": "./packages/client/web-react" }, diff --git a/tsconfig.host.json b/tsconfig.host.json index effb110c07..4ea1881acb 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -33,6 +33,7 @@ ], "exclude": [ "packages/client/**", + "packages/host/directory-picker-native/**", "scripts/client-bundle-purity.spec.ts" ], "references": [ @@ -168,7 +169,6 @@ { "path": "./packages/host/apiproxy" }, { "path": "./packages/host/directory-picker" }, { "path": "./packages/host/directory-picker-browse" }, - { "path": "./packages/host/directory-picker-native" }, { "path": "./packages/host/webserver" }, { "path": "./packages/sdk/sdk-client" }, { "path": "./packages/sdk/helper" }, From 3c8cd3cb9dbb5ba3441ef116c96798ff8d93ff86 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 21:52:05 +0800 Subject: [PATCH 27/93] doc(packages): keep the groups table inside its word ceiling after the master merge master's session-projection row landed the table at 874 words against the 870 ceiling this PR set; tighten the host/client rows this PR added instead of raising the ceiling. --- packages/README.i18n.yaml | 4 ++-- packages/README.md | 4 ++-- packages/README.zh.md | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/packages/README.i18n.yaml b/packages/README.i18n.yaml index 49dd912706..ba5ab61b06 100644 --- a/packages/README.i18n.yaml +++ b/packages/README.i18n.yaml @@ -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/README.md -README.md: 127ca49000e8b4b47c65aaacec4ecc8c5b76fa7c -README.zh.md: b1037f602eaa4a8385938926b3a3be5a88d7ae12 +README.md: 7a86e0f034264d4059e75775016d8d5d84600d8d +README.zh.md: bfcba626bea2a70f5c2aa508bb2a5b8c09bb61dc diff --git a/packages/README.md b/packages/README.md index 127ca49000..7a86e0f034 100644 --- a/packages/README.md +++ b/packages/README.md @@ -44,8 +44,8 @@ Packages live at `packages///`; groups are containers, while names r | [`sdk/`](sdk/README.md) | Project SDK tooling | Product — stable surface | | [`acp/`](acp/README.md) | Automation-only Agent Client Protocol server | Product — stable surface | | [`ui/`](ui/README.md) | TUI and JSON-RPC integrations, approval/interaction seams, ask-user tool | Product — stable surface | -| [`host/`](host/README.md) | Web-GUI host half: shared API gateway + HTTP route server | Product — stable surface | -| [`client/`](client/README.md) | Web-GUI browser half: shell, wire consumer, object services, slot system, `ui-*` feature plugins | Product — stable surface | +| [`host/`](host/README.md) | Web-GUI host half: API gateway + HTTP route server | Product — stable surface | +| [`client/`](client/README.md) | Web-GUI browser half: shell, wire, object services, slots, `ui-*` plugins | Product — stable surface | | [`examples/`](examples/README.md) | Demo bundles (agent-spine + TUI/CLI/ACP/JSON-RPC bins) leaves load | Support — example infra | | [`support/`](support/README.md) | Support infrastructure (testkits, invariants, replay, Loader smokes) | Support — lower compatibility expectations | | [`util/`](util/README.md) | Low-level zero-dependency utilities shared across groups (`Branded`, Harness home/path helpers, timeout, retention) | Support — small, stable, harness-dep-free | diff --git a/packages/README.zh.md b/packages/README.zh.md index b1037f602e..bfcba626be 100644 --- a/packages/README.zh.md +++ b/packages/README.zh.md @@ -44,8 +44,8 @@ | [`sdk/`](sdk/README.md) | 项目 SDK 工具 | 产品:稳定表面 | | [`acp/`](acp/README.md) | 仅面向自动化的 Agent Client Protocol 服务器 | 产品:稳定表面 | | [`ui/`](ui/README.md) | TUI 与 JSON-RPC 集成、批准/交互 seam、用户问答工具 | 产品:稳定表面 | -| [`host/`](host/README.md) | web GUI 宿主半侧:共享 API 网关 + HTTP 路由服务器 | 产品:稳定表面 | -| [`client/`](client/README.md) | web GUI 浏览器半侧:shell、协议消费层、对象服务、slot 系统、`ui-*` 特性插件 | 产品:稳定表面 | +| [`host/`](host/README.md) | web GUI 宿主半侧:API 网关 + HTTP 路由服务器 | 产品:稳定表面 | +| [`client/`](client/README.md) | web GUI 浏览器半侧:shell、协议层、对象服务、slot、`ui-*` 插件 | 产品:稳定表面 | | [`examples/`](examples/README.md) | 演示组合包(agent-spine + TUI/CLI/ACP/JSON-RPC bin),由叶节点加载 | 支持:示例基础设施 | | [`support/`](support/README.md) | 支持基础设施(testkit、不变式、回放、Loader 冒烟测试) | 支持:兼容性预期较低 | | [`util/`](util/README.md) | 组间共享的低层零依赖工具(`Branded`、Harness home/路径辅助函数、超时、保留策略) | 支持:小型、稳定、无 harness 依赖 | From 012b5eb466e5c21ab0e70923edcbca9b0a0d97ce Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 21:54:02 +0800 Subject: [PATCH 28/93] fix(cli): stop exporting the internal all-interfaces bind literal knip (unused exports) flags ALL_INTERFACES_HOST: both consumers live in apps/cli source, so the constant needs no export surface. --- apps/cli/src/app-cli-entry.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/cli/src/app-cli-entry.ts b/apps/cli/src/app-cli-entry.ts index acc4482018..668d8f7f02 100644 --- a/apps/cli/src/app-cli-entry.ts +++ b/apps/cli/src/app-cli-entry.ts @@ -27,7 +27,7 @@ const PROFILE_DIR = '.dsh-tmp-profile' const PROFILE_FILE = 'config.json' /** The webserver schema's all-interfaces bind literal: gates LAN-authority derivation here and the printed LAN URL in web.ts. */ -export const ALL_INTERFACES_HOST = '0.0.0.0' +const ALL_INTERFACES_HOST = '0.0.0.0' /** * Non-internal IPv4 interface addresses of this machine — the IP-literal From 4822622cb726cb2e08454c5acdfd18c249166481 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 22:22:14 +0800 Subject: [PATCH 29/93] feat(host,client): ship the in-app directory browser as the browse package's client half MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit directory-picker-browse becomes dual-face: its browser half fills ui-workspace's two directory-flow holes with the Select Workspace Directory dialog (figma Harness 813-23126 family — Miller two-column view, breadcrumb with click-to-edit path zone, nested New-folder dialog), driving the node half's host.listDirectory/host.createDirectory and owning its locale namespace (directory-browser, zh default / en). The dialog moves here from ui-workspace wholesale — the trigger surfaces keep only the flow-hole owner conversation. apps/cli flips its one directory-picker row -native -> -browse, swapping the host backend and the client interaction together; picking now works for remote deployments out of the box. The keyless workspace-flow snapshot boots the browse bundle and drives menu -> dialog -> Documents -> project -> Open against the fixture tree. --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 2 +- ...-28-directory-picker-capability-seam.zh.md | 2 +- apps/cli/cordis.yml | 4 +- apps/cli/package.json | 2 +- apps/web/tests/workspace-flow.snapshot.ts | 19 +- docs/module-graph.md | 30 +- packages/client/ui-workspace/package.json | 3 - packages/host/README.i18n.yaml | 4 +- packages/host/README.md | 2 +- packages/host/README.zh.md | 2 +- .../directory-picker-browse/README.i18n.yaml | 4 +- .../host/directory-picker-browse/README.md | 2 + .../host/directory-picker-browse/README.zh.md | 2 + .../host/directory-picker-browse/package.json | 33 +- .../src/client/DirectoryBrowser.module.css | 269 ++++++++++++ .../src/client/DirectoryBrowser.tsx | 376 ++++++++++++++++ .../src/client/index.ts | 109 +++++ .../src/css-modules.d.ts | 6 + .../tests/client-flow.spec.tsx | 127 ++++++ .../tests/directory-browser.spec.tsx | 405 ++++++++++++++++++ .../directory-picker-browse/tsconfig.json | 28 +- .../directory-picker-browse/tsdown.config.ts | 3 + pnpm-lock.yaml | 31 +- tsconfig.client.json | 3 + tsconfig.host.json | 2 +- 26 files changed, 1421 insertions(+), 53 deletions(-) create mode 100644 packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css create mode 100644 packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx create mode 100644 packages/host/directory-picker-browse/src/client/index.ts create mode 100644 packages/host/directory-picker-browse/src/css-modules.d.ts create mode 100644 packages/host/directory-picker-browse/tests/client-flow.spec.tsx create mode 100644 packages/host/directory-picker-browse/tests/directory-browser.spec.tsx create mode 100644 packages/host/directory-picker-browse/tsdown.config.ts diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml index b49544ddfb..8f618cc681 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml @@ -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 .agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md -2026-07-28-directory-picker-capability-seam.md: ce5a2695345e29db5739df206965720559783ce3 -2026-07-28-directory-picker-capability-seam.zh.md: 5b73c3c48493d4f178a523db19bc124eda9c7cca +2026-07-28-directory-picker-capability-seam.md: df31b43e0678815847a48844b69928bdd1bb5175 +2026-07-28-directory-picker-capability-seam.zh.md: 0840c020d4826c74583f100251b6f3352a3b4b4a diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md index ce5a269534..df31b43e06 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md @@ -32,7 +32,7 @@ Placement and policy rulings folded into this decision: ## Consequences -- `cordis.yml` chooses the interaction; `apps/cli` currently mounts `-native` (unchanged behavior). The in-app browser PR flips that one row to `-browse`, swapping backend and UI together. +- `cordis.yml` chooses the interaction; `apps/cli` mounts `-browse` (the shipped default — remote-capable picking out of the box), one row having swapped backend and UI together; `-native` remains the host-display alternative. - The wire gains `host.listDirectory`/`host.createDirectory` and four error codes; the connection fixture serves a deterministic browse tree and a deterministic `pickDirectory` path for keyless assembled tests. - A future interaction (or an Electron provider of the `native` interaction) is one dual-face backend package — no gateway surgery, no ui-workspace edits. - `ApiProxyDefaults.pickDirectory` (test-only injection) is gone; tests provide a stub `ctx.directoryPicker` like any other service. diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md index 5b73c3c484..0840c020d4 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md @@ -32,7 +32,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick ## 后果 -- `cordis.yml` 决定交互形态;`apps/cli` 当前挂 `-native`(行为不变)。应用内浏览器 PR 只翻这一行到 `-browse`,后端与 UI 同时切换。 +- `cordis.yml` 决定交互形态;`apps/cli` 挂 `-browse`(随附默认——开箱即得可远程的选取),一行同时切换了后端与 UI;`-native` 仍是宿主屏幕方案。 - 协议新增 `host.listDirectory`/`host.createDirectory` 与四个错误码;connection fixture 提供确定性浏览树与确定性 `pickDirectory` 路径供无密钥组装测试使用。 - 未来的新交互(或提供 `native` 交互的 Electron 实现)只是一个双面后端包——无需网关手术,也不动 ui-workspace。 - `ApiProxyDefaults.pickDirectory`(仅测试注入)删除;测试像提供其他服务一样提供 stub `ctx.directoryPicker`。 diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index c6058890d8..361619b38b 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -243,9 +243,9 @@ # Directory-picking package, dual-face: the node half serves the gateway's # host.* picker RPCs, the browser half fills ui-workspace's directory-flow # slots — one row composes the whole interaction. Swap point: mount -# '-browse' instead for the in-app browser (remote-capable). +# '-native' instead for the host-display OS chooser. - id: directory-picker - name: '@deepseek-ai/dsh-host-directory-picker-native' + name: '@deepseek-ai/dsh-host-directory-picker-browse' - id: api-gateway name: '@deepseek-ai/dsh-host-apiproxy' diff --git a/apps/cli/package.json b/apps/cli/package.json index cc24c1fd88..e753e5ba3d 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -48,7 +48,7 @@ "@deepseek-ai/dsh-fs-local": "workspace:^", "@deepseek-ai/dsh-fs-policy": "workspace:^", "@deepseek-ai/dsh-host-apiproxy": "workspace:^", - "@deepseek-ai/dsh-host-directory-picker-native": "workspace:^", + "@deepseek-ai/dsh-host-directory-picker-browse": "workspace:^", "@deepseek-ai/dsh-host-webserver": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-llm-deepseek": "workspace:^", diff --git a/apps/web/tests/workspace-flow.snapshot.ts b/apps/web/tests/workspace-flow.snapshot.ts index ca98e7b176..d7cb66e0af 100644 --- a/apps/web/tests/workspace-flow.snapshot.ts +++ b/apps/web/tests/workspace-flow.snapshot.ts @@ -40,11 +40,11 @@ const PLUGINS: readonly (WebBootEntry & { dir: string })[] = [ // Dual-face host package: its browser half fills the directory-flow holes // (the same composition row apps/cli mounts for the node-side backend). { - id: '@deepseek-ai/dsh-host-directory-picker-native', - dir: '../host/directory-picker-native', - url: '/plugins/directory-picker-native.js', + id: '@deepseek-ai/dsh-host-directory-picker-browse', + dir: '../host/directory-picker-browse', + url: '/plugins/directory-picker-browse.js', rev: 'fx', - inject: ['@deepseek-ai/dsh-client-runtime', '@deepseek-ai/dsh-client-ui-workspace'], + inject: ['@deepseek-ai/dsh-client-runtime', '@deepseek-ai/dsh-client-ui-workspace', '@deepseek-ai/dsh-client-locale'], }, ] @@ -183,7 +183,7 @@ it('locks the composer in the New Session view state until a Workspace is chosen `) }) -it('adopts a directory through the composed native flow and lands in its blank session', async () => { +it('adopts a directory through the composed in-app browse flow and lands in its blank session', async () => { boot('?fixture=empty') await findLockedComposer() @@ -194,9 +194,12 @@ it('adopts a directory through the composed native flow and lands in its blank s expect(within(menu).getAllByRole('menuitem').map(item => visibleText(item))) .toEqual(['Open local folder…', 'Create a new workspace']) fireEvent.click(within(menu).getByRole('menuitem', { name: 'Open local folder…' })) - // The renderless native flow drives the fixture's deterministic pick and - // the owner adopts the returned path into a real Workspace. - await act(async () => {}) + // The browse occupant renders the Select Workspace Directory dialog at the + // fixture home; select Documents, advance into project, and adopt it. + const dialog = await screen.findByRole('dialog', { name: '选择工作区目录' }) + fireEvent.click(await within(dialog).findByRole('listitem', { name: /Documents/ })) + fireEvent.click(await within(dialog).findByRole('listitem', { name: /^project/ })) + fireEvent.click(within(dialog).getByRole('button', { name: '打开' })) await findHeroComposer() await waitFor(() => { expect(visibleText(screen.getByRole('tree', { name: 'Sessions' }))).toContain('project') diff --git a/docs/module-graph.md b/docs/module-graph.md index 320c6c85e4..1ff7428fed 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -266,7 +266,6 @@ flowchart TD pkg_jsonrpc_demo --> pkg_invariants pkg_host_apiproxy --> pkg_invariants pkg_host_directory_picker --> pkg_invariants - pkg_host_directory_picker_browse --> pkg_invariants pkg_host_webserver --> pkg_invariants pkg_storage --> pkg_invariants pkg_subprocess --> pkg_invariants @@ -296,10 +295,6 @@ flowchart TD pkg_client_ui_slash --> pkg_client_runtime pkg_client_ui_slash --> pkg_client_ui_slots pkg_client_ui_slash --> pkg_invariants - pkg_client_ui_workspace --> pkg_client_runtime - pkg_client_ui_workspace --> pkg_client_ui_primitives - pkg_client_ui_workspace --> pkg_client_ui_slots - pkg_client_ui_workspace --> pkg_invariants pkg_helper --> pkg_brand pkg_helper --> pkg_invariants pkg_helper --> pkg_subprocess @@ -354,10 +349,11 @@ flowchart TD pkg_client_ui_theme --> pkg_client_ui_primitives pkg_client_ui_theme --> pkg_client_ui_slots pkg_client_ui_theme --> pkg_invariants - pkg_host_directory_picker_native --> pkg_client_runtime - pkg_host_directory_picker_native --> pkg_client_ui_slots - pkg_host_directory_picker_native --> pkg_client_ui_workspace - pkg_host_directory_picker_native --> pkg_invariants + pkg_client_ui_workspace --> pkg_client_locale + pkg_client_ui_workspace --> pkg_client_runtime + pkg_client_ui_workspace --> pkg_client_ui_primitives + pkg_client_ui_workspace --> pkg_client_ui_slots + pkg_client_ui_workspace --> pkg_invariants pkg_lsp --> pkg_brand pkg_lsp --> pkg_invariants pkg_lsp --> pkg_llm @@ -422,6 +418,16 @@ flowchart TD pkg_code_runtime_worker --> pkg_invariants pkg_code_runtime_worker --> pkg_session pkg_code_runtime_worker --> pkg_timeout + pkg_host_directory_picker_browse --> pkg_client_locale + pkg_host_directory_picker_browse --> pkg_client_runtime + pkg_host_directory_picker_browse --> pkg_client_ui_primitives + pkg_host_directory_picker_browse --> pkg_client_ui_slots + pkg_host_directory_picker_browse --> pkg_client_ui_workspace + pkg_host_directory_picker_browse --> pkg_invariants + pkg_host_directory_picker_native --> pkg_client_runtime + pkg_host_directory_picker_native --> pkg_client_ui_slots + pkg_host_directory_picker_native --> pkg_client_ui_workspace + pkg_host_directory_picker_native --> pkg_invariants pkg_lsp_local --> pkg_brand pkg_lsp_local --> pkg_invariants pkg_lsp_local --> pkg_llm @@ -946,7 +952,6 @@ flowchart TD | [`jsonrpc-demo`](../packages/examples/jsonrpc-demo) | `examples` | [`invariants`](../packages/support/invariants) | | [`host-apiproxy`](../packages/host/apiproxy) | `host` | [`invariants`](../packages/support/invariants) | | [`host-directory-picker`](../packages/host/directory-picker) | `host` | [`invariants`](../packages/support/invariants) | -| [`host-directory-picker-browse`](../packages/host/directory-picker-browse) | `host` | [`invariants`](../packages/support/invariants) | | [`host-webserver`](../packages/host/webserver) | `host` | [`invariants`](../packages/support/invariants) | | [`storage`](../packages/storage/storage) | `storage` | [`invariants`](../packages/support/invariants) | | [`subprocess`](../packages/subprocess/subprocess) | `subprocess` | [`invariants`](../packages/support/invariants) | @@ -958,7 +963,6 @@ flowchart TD | [`client-ui-settings`](../packages/client/ui-settings) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-sidebar`](../packages/client/ui-sidebar) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-slash`](../packages/client/ui-slash) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | -| [`client-ui-workspace`](../packages/client/ui-workspace) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`helper`](../packages/sdk/helper) | `sdk` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`subprocess`](../packages/subprocess/subprocess) | | [`telemetry`](../packages/sdk/telemetry) | `sdk` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`invariants`](../packages/support/invariants), [`storage`](../packages/storage/storage) | @@ -975,7 +979,7 @@ flowchart TD | [`client-ui-skill`](../packages/client/ui-skill) | `client` | [`client-connection`](../packages/client/connection), [`client-runtime`](../packages/client/runtime), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-subagent`](../packages/client/ui-subagent) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-theme`](../packages/client/ui-theme) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | -| [`host-directory-picker-native`](../packages/host/directory-picker-native) | `host` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-workspace`](../packages/client/ui-workspace), [`invariants`](../packages/support/invariants) | +| [`client-ui-workspace`](../packages/client/ui-workspace) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm) | | [`sandbox`](../packages/sandbox/sandbox) | `sandbox` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm) | | [`token-meter`](../packages/llm/token-meter) | `llm` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | @@ -995,6 +999,8 @@ flowchart TD | [`client-ui-command`](../packages/client/ui-command) | `client` | [`client-connection`](../packages/client/connection), [`client-runtime`](../packages/client/runtime), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-layout`](../packages/client/ui-layout) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-theme`](../packages/client/ui-theme), [`invariants`](../packages/support/invariants) | | [`code-runtime-worker`](../packages/code-runtime/code-runtime-worker) | `code-runtime` | [`code-runtime`](../packages/code-runtime/code-runtime), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | +| [`host-directory-picker-browse`](../packages/host/directory-picker-browse) | `host` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-workspace`](../packages/client/ui-workspace), [`invariants`](../packages/support/invariants) | +| [`host-directory-picker-native`](../packages/host/directory-picker-native) | `host` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-workspace`](../packages/client/ui-workspace), [`invariants`](../packages/support/invariants) | | [`lsp-local`](../packages/lsp/lsp-local) | `lsp` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`sandbox-policy`](../packages/sandbox/sandbox-policy) | `sandbox` | [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) | diff --git a/packages/client/ui-workspace/package.json b/packages/client/ui-workspace/package.json index 29d1ecfa36..c36486d2fd 100644 --- a/packages/client/ui-workspace/package.json +++ b/packages/client/ui-workspace/package.json @@ -25,7 +25,6 @@ "dshClient": { "inject": [ "@deepseek-ai/dsh-client-runtime", - "@deepseek-ai/dsh-client-locale", "@deepseek-ai/dsh-client-ui-conversation", "@deepseek-ai/dsh-client-ui-sidebar" ], @@ -40,7 +39,6 @@ "clsx": "^2.0.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", @@ -49,7 +47,6 @@ "react": "^18.2.0" }, "devDependencies": { - "@deepseek-ai/dsh-client-locale": "workspace:^", "@deepseek-ai/dsh-client-runtime": "workspace:^", "@deepseek-ai/dsh-client-ui-conversation": "workspace:^", "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", diff --git a/packages/host/README.i18n.yaml b/packages/host/README.i18n.yaml index 9a6deda327..afc0e2a695 100644 --- a/packages/host/README.i18n.yaml +++ b/packages/host/README.i18n.yaml @@ -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/README.md -README.md: 7df0ecc4a362be1149188d133233307b1fc48c8a -README.zh.md: 90d5ea2b0947d2cff9ba06e89b6225b39dad7fce +README.md: d44770f70be16c12f44b78155089e092a3e9bba0 +README.zh.md: 2b6878b08be6489dcd510a0a0e0f0e833c2a8014 diff --git a/packages/host/README.md b/packages/host/README.md index 7df0ecc4a3..d44770f70b 100644 --- a/packages/host/README.md +++ b/packages/host/README.md @@ -10,6 +10,6 @@ The host side of the dsh web GUI: the API gateway every client shape shares, and | `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/` | In-app browsing backend: listing/creation primitives over Node stdlib; remote-capable | (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. diff --git a/packages/host/README.zh.md b/packages/host/README.zh.md index 90d5ea2b09..2b6878b08b 100644 --- a/packages/host/README.zh.md +++ b/packages/host/README.zh.md @@ -10,6 +10,6 @@ dsh web GUI 的宿主侧:所有客户端形态共用的 API 网关,以及承 | `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 标准库的列举/创建原语;支持远程 | (注册 `ctx.directoryPicker`) | +| `directory-picker-browse/` | 双面浏览交互:基于 Node 标准库的列举/创建原语(可远程)+ 渲染应用内选择工作区目录对话框的 browser half | (注册 `ctx.directoryPicker`) | `apiproxy` 在设计上与传输方式无关——它不注册任何路由;载体自行包装 `ctx.apiProxy`。HTTP 载体路由(连同其 `/api` 浏览器信任栅栏)由 [`client/connection`](../client/connection/README.md) 的 node 半侧挂载,这正是该包住在 client 组的原因:它拥有这条线的两端。 diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index 34c3e35a79..c0da9fd2e9 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/directory-picker-browse/README.md -README.md: 688a60894cb0ab066a6d501e4df310f8d31bfb5f -README.zh.md: c19bccc2ff9268cb7a6c931da4671bebc9f76b0c +README.md: 5cec04b68c4c81c4ab1db4b2a5709b5f56139dc0 +README.zh.md: 1a26b496c1b30c5c90c5b7f123292a1c57ddb74a diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index 688a60894c..5cec04b68c 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -6,6 +6,8 @@ The **in-app browsing backend** of the [directory-picker seam](../directory-pick Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject an explicit path that is not fully qualified — relative forms, and on Windows the rooted drive-less forms (`\foo`, `/foo`) and incomplete UNC prefixes (`\\`, `\\server`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). +**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. diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index c19bccc2ff..1a26b496c1 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -6,6 +6,8 @@ 行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo`、`/foo`)与不完整的 UNC 前缀(`\\`、`\\server`)——报 `directory-unreadable`/`directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 +**双面包**: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 宿主的目录选择;这里没有任何内容进入模型请求。 diff --git a/packages/host/directory-picker-browse/package.json b/packages/host/directory-picker-browse/package.json index c1e8626bed..192ce614d2 100644 --- a/packages/host/directory-picker-browse/package.json +++ b/packages/host/directory-picker-browse/package.json @@ -15,26 +15,53 @@ "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-host-directory-picker": "workspace:^", + "clsx": "^2.0.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" + "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:^", - "cordis": "^4.0.0-rc.7" + "@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" } } diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css new file mode 100644 index 0000000000..f59a74aa7e --- /dev/null +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css @@ -0,0 +1,269 @@ +/* Directory-browser dialog (figma 813-23126 family). The shared Modal renders + * headless here — mask, card, Escape only — and this module owns the figma + * frame exactly: fixed 600×420 card, 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. */ +.dialog.dialog { + width: min(600px, 100%); + height: 420px; + 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; +} + +.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 1 0; + 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; + align-items: stretch; + flex: 1 1 0; + min-height: 0; + gap: 20px; + 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); +} + +.row { + 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; + 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; +} diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx new file mode 100644 index 0000000000..49cbff9fb3 --- /dev/null +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -0,0 +1,376 @@ +/** + * The in-app workspace-directory browser (figma Harness 813-23126 family): a + * fixed 600×420 dialog 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). */ + listDirectory: (path?: string) => Promise + /** Create one child directory under an existing parent. */ + createDirectory: (path: string, name: string) => Promise + /** 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 ( +
+ {entries.filter(entry => !entry.hidden).map((entry) => { + const selected = entry.path === selectedPath + return ( + + ) + })} +
+ ) +} + +/** + * 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(null) + const [selected, setSelected] = useState(null) + const [child, setChild] = useState(null) + const [loading, setLoading] = useState(false) + const [error, setError] = useState(null) + // Path-edit state: null = breadcrumb mode; a string = the draft being typed. + const [pathDraft, setPathDraft] = useState(null) + // Create-folder state: null = closed; a string = the nested dialog's draft. + const [folderDraft, setFolderDraft] = useState(null) + const [creatingFolder, setCreatingFolder] = useState(false) + const [createError, setCreateError] = useState(null) + const requestSeq = useRef(0) + + /** Replace the whole view with one freshly listed level (no selection). */ + const navigate = useCallback((path?: string) => { + const seq = ++requestSeq.current + setLoading(true) + setError(null) + listDirectory(path).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)) + }) + }, [listDirectory]) + + /** Select a row of the listed level and preview its children on the right. */ + const select = useCallback((entry: DirectoryEntry) => { + const seq = ++requestSeq.current + setSelected(entry) + setChild(null) + setLoading(true) + setError(null) + listDirectory(entry.path).then((next) => { + if (seq !== requestSeq.current) return + setChild(next) + setLoading(false) + }, (reason: unknown) => { + if (seq !== requestSeq.current) return + setLoading(false) + setError(failureText(reason)) + }) + }, [listDirectory]) + + /** 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(() => { + if (open) { + setParent(null) + setSelected(null) + setChild(null) + navigate() + return + } + requestSeq.current += 1 + setError(null) + setPathDraft(null) + setFolderDraft(null) + setCreateError(null) + }, [open, navigate]) + + /** 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 + const name = folderDraft.trim() + if (name === '') return + setCreatingFolder(true) + setCreateError(null) + createDirectory(targetPath, name).then((createdPath) => { + 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 = ++requestSeq.current + setLoading(true) + listDirectory(targetPath).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) => { + setCreatingFolder(false) + setCreateError(failureText(reason)) + }) + } + + // After the hooks: a closed dialog renders nothing and evaluates no copy. + if (!open) return null + + const crumbSource = child ?? parent + const crumbs = crumbSource === null ? [] : displayCrumbs(crumbSource, t('browser.home')) + const twoPane = selected !== null + + return ( + +
+

{t('browser.title')}

+
+ {pathDraft === null + ? ( + <> + {crumbs.map((crumb, index) => ( + + {index > 0 && } + + + ))} + {/* The empty zone right of the crumbs is the path-edit affordance. */} +
+
+
+ {parent !== null && ( + + )} + {twoPane && } + {twoPane && child !== null && ( + + )} + {loading &&
{t('browser.loading')}
} + {error !== null &&
{error}
} +
+
+ + + + +
+ {/* Nested create dialog (figma 813:23278): names one folder inside the target. */} + { if (!creatingFolder) setFolderDraft(null) }} + title={t('browser.newFolder')} + className={clsx(css.createDialog)} + headless + > +
+

{t('browser.newFolder')}

+

{t('browser.createIn', { name: targetName })}

+ { setFolderDraft(event.target.value) }} + onKeyDown={(event) => { + if (event.key === 'Enter') { + event.preventDefault() + confirmCreate() + } + if (event.key === 'Escape') { + event.stopPropagation() + if (!creatingFolder) setFolderDraft(null) + } + }} + /> + {createError !== null &&
{createError}
} +
+ + +
+
+
+
+ ) +} diff --git a/packages/host/directory-picker-browse/src/client/index.ts b/packages/host/directory-picker-browse/src/client/index.ts new file mode 100644 index 0000000000..804d23a91f --- /dev/null +++ b/packages/host/directory-picker-browse/src/client/index.ts @@ -0,0 +1,109 @@ +/** + * 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 { createElement } from 'react' +import type { ReactElement } from 'react' +import { deferRegistration } from '@deepseek-ai/dsh-client-ui-slots' +import type { ClientContext, DirectoryListing } from '@deepseek-ai/dsh-client-runtime/client' +import type { Translate } from '@deepseek-ai/dsh-client-locale/client' +// Type-only: the SlotMap merge declaring the directory-flow holes and their owner contract. +import type { DirectoryFlowOwnerProps } from '@deepseek-ai/dsh-client-ui-workspace/client' +import { DirectoryBrowser } from './DirectoryBrowser.tsx' + +/** Locale namespace owning the browser dialog's copy. */ +const LOCALE_NS = 'directory-browser' + +/** Injected face: the browse wire calls and copy the dialog drives (bound in apply's closure). */ +interface BrowseFlowInjected { + /** List one directory level (absent path = the Host home directory). */ + listDirectory: (path?: string) => Promise + /** Create one child directory under an existing parent. */ + createDirectory: (path: string, name: string) => Promise + /** 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, + }) +} + +/** 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(() => { + const disposers = [ + ctx.locale.register(LOCALE_NS, 'zh', { + 'browser.title': '选择工作区目录', + 'browser.home': '主目录', + 'browser.newFolder': '新建文件夹', + 'browser.folderName': '文件夹名称', + 'browser.createIn': '在"{name}"中新建文件夹', + 'browser.untitledFolder': '未命名文件夹', + 'browser.create': '创建', + 'browser.cancel': '取消', + 'browser.open': '打开', + 'browser.editPath': '编辑路径', + 'browser.loading': '加载中…', + }), + ctx.locale.register(LOCALE_NS, '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…', + }), + ] + return () => { for (const dispose of disposers) dispose() } + }, 'directory-picker-browse: dialog dictionaries') + + const injected = (): BrowseFlowInjected => ({ + listDirectory: path => ctx.workspaces.listDirectory(path), + createDirectory: (path, name) => ctx.workspaces.createDirectory(path, name), + t: ctx.locale.bind(LOCALE_NS), + }) + ctx.effect(() => { + const deferred = [ + deferRegistration(ctx.slots, 'conversation.hero.workspace.directoryFlow', BrowseDirectoryFlow, () => + ctx.slots.register({ name: 'conversation.hero.workspace.directoryFlow', inject: injected }, BrowseDirectoryFlow)), + deferRegistration(ctx.slots, 'sidebar.workspaces.directoryFlow', BrowseDirectoryFlow, () => + ctx.slots.register({ name: 'sidebar.workspaces.directoryFlow', inject: injected }, BrowseDirectoryFlow)), + ] + return () => { for (const entry of deferred) entry.dispose() } + }, 'directory-picker-browse: flow registrations') +} diff --git a/packages/host/directory-picker-browse/src/css-modules.d.ts b/packages/host/directory-picker-browse/src/css-modules.d.ts new file mode 100644 index 0000000000..bc5e482353 --- /dev/null +++ b/packages/host/directory-picker-browse/src/css-modules.d.ts @@ -0,0 +1,6 @@ +declare module '*.module.css' { + const classes: Record + export default classes +} + +declare module '*.css' diff --git a/packages/host/directory-picker-browse/tests/client-flow.spec.tsx b/packages/host/directory-picker-browse/tests/client-flow.spec.tsx new file mode 100644 index 0000000000..9d0dfc004f --- /dev/null +++ b/packages/host/directory-picker-browse/tests/client-flow.spec.tsx @@ -0,0 +1,127 @@ +// @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, BrowseDirectoryFlow, inject } from '../src/client/index.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 }], +} + +async function bench() { + const ctx = new Context() + await ctx.plugin(SlotsService).await() + ctx.provide('locale', new LocaleService(ctx)) + const listDirectory = vi.fn(async (): Promise => 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 { + 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('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 + createDirectory: (path: string, name: string) => Promise + })() + 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 => homeListing) + const t = (key: string): string => key + render( + '')} + 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( + homeListing)} + createDirectory={vi.fn(async () => '')} + t={key => key} + />, + ) + expect(view.container.innerHTML).toBe('') + }) +}) diff --git a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx new file mode 100644 index 0000000000..28c25b367f --- /dev/null +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -0,0 +1,405 @@ +// @vitest-environment jsdom +import { afterEach, describe, expect, it, vi } from 'vitest' +import { 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 = { + [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 }, + ], + }, + [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 }], + }, + [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: [], + }, + } + 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[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) => (params === undefined ? key : `${key}:${String(params.name)}`), + ...overrides, + } + const view = render() + return { view, props, listDirectory, createDirectory, onOpen, onClose } +} + +/** The rendered level columns, left-to-right. */ +function columns(): HTMLElement[] { + return screen.getAllByRole('list') +} + +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(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(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(selectedRow.getAttribute('aria-current')).toBe('true') + expect(within(preview!).getByRole('listitem').textContent).toBe('harness') + expect(b.listDirectory).toHaveBeenLastCalledWith(DOCS) + expect(screen.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(screen.getByRole('listitem')) + await waitFor(() => { expect(columns()).toHaveLength(2) }) + fireEvent.click(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(selectedRow.getAttribute('aria-current')).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(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(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(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('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('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('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('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() + 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: [], + } + 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('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(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: [], + } + } + 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(screen.getByRole('button', { name: 'Documents' })).toBeTruthy() + const level = columns()[0]! + const rows = within(level).getAllByRole('listitem') + expect(rows.some(row => row.textContent === 'fresh' && 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 selection-preview failure while keeping the selection marked', async () => { + const b = mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + b.listDirectory.mockRejectedValueOnce( + new DirectoryBrowseError({ code: 'directory-unreadable', message: 'denied', details: { path: DOCS } })) + fireEvent.click(screen.getByRole('listitem')) + await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('denied') }) + expect(screen.getByRole('listitem').getAttribute('aria-current')).toBe('true') + // No preview column arrived for the failed selection. + expect(columns()).toHaveLength(1) + }) + + 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((settle) => { resolveSlow = settle }) + b.listDirectory.mockReturnValueOnce(slow) + fireEvent.click(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((_settle, fail) => { rejectSlow = fail }) + b.listDirectory.mockReturnValueOnce(slow) + fireEvent.click(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(screen.getByRole('listitem')) + await waitFor(() => { expect(columns()).toHaveLength(2) }) + let rejectSlow!: (reason: unknown) => void + const slow = new Promise((_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(screen.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(screen.getByRole('listitem')) + await waitFor(() => { expect(columns()).toHaveLength(2) }) + let resolveSlow!: (value: DirectoryListing) => void + const slow = new Promise((settle) => { resolveSlow = settle }) + b.listDirectory.mockReturnValueOnce(slow) + fireEvent.click(screen.getByRole('button', { name: 'browser.home' })) + fireEvent.click(screen.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: [] } + mount({ listDirectory: vi.fn(async () => bare) }) + await waitFor(() => { expect(screen.getByRole('button', { name: 'browser.newFolder' })).toBeTruthy() }) + await waitFor(() => { + expect(screen.getByRole('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((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('starts back at home on reopen', async () => { + const b = mount() + await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) + fireEvent.click(screen.getByRole('listitem')) + await waitFor(() => { expect(columns()).toHaveLength(2) }) + b.view.rerender() + b.view.rerender() + await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('Documents') }) + expect(columns()).toHaveLength(1) + expect(b.listDirectory).toHaveBeenLastCalledWith(undefined) + }) +}) diff --git a/packages/host/directory-picker-browse/tsconfig.json b/packages/host/directory-picker-browse/tsconfig.json index 99ca673189..00dcdf8fde 100644 --- a/packages/host/directory-picker-browse/tsconfig.json +++ b/packages/host/directory-picker-browse/tsconfig.json @@ -1,24 +1,36 @@ { - "extends": "../../../tsconfig.base.json", + "extends": "../../../tsconfig.base.client.json", "compilerOptions": { "rootDir": "src", - "outDir": "lib/types" + "outDir": "lib/types", + "types": [ + "node" + ] }, "include": [ "src" ], "references": [ - { - "path": "../../../vendor/cosmokit" - }, - { - "path": "../../../vendor/cordis" - }, { "path": "../directory-picker" }, { "path": "../../support/invariants" + }, + { + "path": "../../client/ui-slots" + }, + { + "path": "../../client/ui-primitives" + }, + { + "path": "../../client/locale" + }, + { + "path": "../../client/runtime" + }, + { + "path": "../../client/ui-workspace" } ] } diff --git a/packages/host/directory-picker-browse/tsdown.config.ts b/packages/host/directory-picker-browse/tsdown.config.ts new file mode 100644 index 0000000000..4b2be38c3d --- /dev/null +++ b/packages/host/directory-picker-browse/tsdown.config.ts @@ -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']) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 94d5dbb3cd..1c09fd14e7 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -212,9 +212,9 @@ importers: '@deepseek-ai/dsh-host-apiproxy': specifier: workspace:^ version: link:../../packages/host/apiproxy - '@deepseek-ai/dsh-host-directory-picker-native': + '@deepseek-ai/dsh-host-directory-picker-browse': specifier: workspace:^ - version: link:../../packages/host/directory-picker-native + version: link:../../packages/host/directory-picker-browse '@deepseek-ai/dsh-host-webserver': specifier: workspace:^ version: link:../../packages/host/webserver @@ -1412,9 +1412,6 @@ importers: specifier: ^2.0.0 version: 2.1.1 devDependencies: - '@deepseek-ai/dsh-client-locale': - specifier: workspace:^ - version: link:../locale '@deepseek-ai/dsh-client-runtime': specifier: workspace:^ version: link:../runtime @@ -2746,13 +2743,37 @@ importers: '@deepseek-ai/dsh-host-directory-picker': specifier: workspace:^ version: link:../directory-picker + clsx: + specifier: ^2.0.0 + version: 2.1.1 devDependencies: + '@deepseek-ai/dsh-client-locale': + specifier: workspace:^ + version: link:../../client/locale + '@deepseek-ai/dsh-client-runtime': + specifier: workspace:^ + version: link:../../client/runtime + '@deepseek-ai/dsh-client-ui-primitives': + specifier: workspace:^ + version: link:../../client/ui-primitives + '@deepseek-ai/dsh-client-ui-slots': + specifier: workspace:^ + version: link:../../client/ui-slots + '@deepseek-ai/dsh-client-ui-workspace': + specifier: workspace:^ + version: link:../../client/ui-workspace '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants + '@types/react': + specifier: ~18.3.1 + version: 18.3.31 cordis: specifier: ^4.0.0-rc.7 version: 4.0.0-rc.7(@cordisjs/plugin-include@1.0.4)(@cordisjs/plugin-loader@1.0.0-rc.5) + react: + specifier: ^18.2.0 + version: 18.3.1 packages/host/directory-picker-native: dependencies: diff --git a/tsconfig.client.json b/tsconfig.client.json index 5eb8ffa5a6..61f050d32a 100644 --- a/tsconfig.client.json +++ b/tsconfig.client.json @@ -19,6 +19,8 @@ "packages/client/*/src/css-modules.d.ts", "packages/client/*/tests/**/*.ts", "packages/client/*/tests/**/*.tsx", + "packages/host/directory-picker-browse/tests/**/*.ts", + "packages/host/directory-picker-browse/tests/**/*.tsx", "packages/host/directory-picker-native/tests/**/*.ts", "packages/host/directory-picker-native/tests/**/*.tsx", "packages/client/tsdown.client.ts", @@ -33,6 +35,7 @@ // browser half registers the picking flow into ui-workspace's slot — // client-side Context merges keep it out of the host program. { "path": "./packages/host/directory-picker-native" }, + { "path": "./packages/host/directory-picker-browse" }, { "path": "./packages/client/ui-slots" }, { "path": "./packages/client/ui-primitives" }, { "path": "./packages/client/web-react" }, diff --git a/tsconfig.host.json b/tsconfig.host.json index 4ea1881acb..3263effe01 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -33,6 +33,7 @@ ], "exclude": [ "packages/client/**", + "packages/host/directory-picker-browse/**", "packages/host/directory-picker-native/**", "scripts/client-bundle-purity.spec.ts" ], @@ -168,7 +169,6 @@ { "path": "./packages/mcp/mcp-client" }, { "path": "./packages/host/apiproxy" }, { "path": "./packages/host/directory-picker" }, - { "path": "./packages/host/directory-picker-browse" }, { "path": "./packages/host/webserver" }, { "path": "./packages/sdk/sdk-client" }, { "path": "./packages/sdk/helper" }, From 451b7b0446b4220671cf46776983dd0022a20eef Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Tue, 28 Jul 2026 22:23:39 +0800 Subject: [PATCH 30/93] feat(permission): permissions projection unit and /permission command MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The read side becomes the 'permissions' session projection: src/types.ts is the key declaration's one home (PermissionSelect = whole select: table options in declaration order plus a current-only 'custom'), served through ./types and the ./client re-export. The unit folds the three whole-value knob events (permission/preset, sandbox/mode, approval/policy) into a plain KnobState and views the select over the composition defaults the service already owns; current() shares the same derive step, so the fold exists once. The write side becomes the /permission command (the /plan registration shape): bare invocation reports the current preset and the table, a preset argument switches through set() immediately — no turn anchoring (knob events need no enclosure), no dedicated RPC. Both children activate only when their registry is composed. --- packages/ui/permission/README.md | 3 +- packages/ui/permission/package.json | 16 +- packages/ui/permission/src/client.ts | 10 ++ packages/ui/permission/src/index.ts | 151 ++++++++++++++++-- packages/ui/permission/src/types.ts | 44 +++++ .../ui/permission/tests/projection.spec.ts | 116 ++++++++++++++ packages/ui/permission/tsconfig.json | 6 + pnpm-lock.yaml | 9 ++ 8 files changed, 336 insertions(+), 19 deletions(-) create mode 100644 packages/ui/permission/src/client.ts create mode 100644 packages/ui/permission/src/types.ts create mode 100644 packages/ui/permission/tests/projection.spec.ts diff --git a/packages/ui/permission/README.md b/packages/ui/permission/README.md index 6a59ad9425..814085ed6f 100644 --- a/packages/ui/permission/README.md +++ b/packages/ui/permission/README.md @@ -8,6 +8,8 @@ User-facing permission presets through `ctx.permission` ([`PermissionService`](s The service requires a confining `ctx.bash` executor and `ctx.approval`. A table entry named `custom` throws at load; composition defaults outside the table instead make a zero-event session derive `custom`. See the [sandbox switching design](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md). +Two optional children ship the product surfaces over the same service: a `permissions` session-projection unit (`src/types.ts` declares the key; the unit folds the three whole-value knob events and views the select — table options plus a current-only `custom` — over the composition defaults) and the `/permission` command (bare invocation reports the current preset and the table; a preset argument switches through `set`). Each child activates only when its registry (`ctx.sessionProjections` / `ctx.commands`) is composed. + ## Model Experience Indirectly, through `dsh-user-approval` and `dsh-tool-bash`, which render the approval-policy prompt, switch notice, and sandboxed tool outcomes selected by this service's knob events; `permission/preset` itself is log-only. @@ -18,7 +20,6 @@ No direct invalidation; the named consumer owns any request-prefix changes. ## Known Limitations and Deferred Work -- **No shipped composition currently mounts the service** — the ACP bridge was its only selector before [ACP became automation-only](../../../.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.md); the preset table is kept for the interactive front door that next exposes a runtime policy switch. - **Only two mechanism knobs are bundled** — presets select sandbox mode and approval policy; an agent/profile choice is not part of `PresetSpec` yet. - **`custom` is derived-only** — callers can switch away from an unmatched knob combination but cannot target or persist a named custom preset through this service. - **The preset table is process-level** — configuration is fixed for the plugin lifetime; changing available presets requires reloading the plugin. diff --git a/packages/ui/permission/package.json b/packages/ui/permission/package.json index 3ec4cc7685..c5021af37b 100644 --- a/packages/ui/permission/package.json +++ b/packages/ui/permission/package.json @@ -15,12 +15,21 @@ "types": "./lib/types/invariant.d.ts", "default": "./lib/invariant.js" }, + "./types": { + "types": "./lib/types/types.d.ts", + "default": "./lib/types/types.js" + }, + "./client": { + "types": "./lib/types/client.d.ts", + "default": "./lib/types/client.js" + }, "./src/*": "./src/*", "./package.json": "./package.json" }, "files": [ "lib/index.js", "lib/invariant.js", + "lib/types/**/*.js", "lib/types/**/*.d.ts", "lib/types/**/*.d.ts.map", "src" @@ -28,22 +37,27 @@ "license": "BSD-3-Clause", "peerDependencies": { "@deepseek-ai/dsh-bash": "^0.0.1", + "@deepseek-ai/dsh-commands": "^0.0.1", "@deepseek-ai/dsh-invariants": "^0.0.1", "@deepseek-ai/dsh-sandbox": "^0.0.1", "@deepseek-ai/dsh-sandbox-policy": "^0.0.1", "@deepseek-ai/dsh-session": "^0.0.1", + "@deepseek-ai/dsh-session-projection": "^0.0.1", "@deepseek-ai/dsh-user-approval": "^0.0.1", "cordis": "^4.0.0-rc.7" }, "dependencies": { - "schemastery": "^3.18.0" + "schemastery": "^3.18.0", + "zod": "^4.4.3" }, "devDependencies": { "@deepseek-ai/dsh-bash": "workspace:^", + "@deepseek-ai/dsh-commands": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", "@deepseek-ai/dsh-sandbox": "workspace:^", "@deepseek-ai/dsh-sandbox-policy": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", "@deepseek-ai/dsh-user-approval": "workspace:^", "cordis": "^4.0.0-rc.7" } diff --git a/packages/ui/permission/src/client.ts b/packages/ui/permission/src/client.ts new file mode 100644 index 0000000000..d758cf5960 --- /dev/null +++ b/packages/ui/permission/src/client.ts @@ -0,0 +1,10 @@ +/** + * Client-namespace projection of the permission domain: a pure re-export of + * the package's types outlet. Client code imports ONLY the client namespace + * (repo discipline), so `./client` projects the same single-source content + * `./types` serves to host consumers — zero duplication. + * + * @module @deepseek-ai/dsh-permission/client + */ + +export type * from './types.ts' diff --git a/packages/ui/permission/src/index.ts b/packages/ui/permission/src/index.ts index d44dff3df4..597d17199a 100644 --- a/packages/ui/permission/src/index.ts +++ b/packages/ui/permission/src/index.ts @@ -3,13 +3,16 @@ * approval-policy knobs. A switch records the selected preset, then writes * changed knobs through their canonical setters. Execution, prompt narration, * and replay keep reading their knob folds. The preset event preserves user - * intent when two presets share a bundle. + * intent when two presets share a bundle. The read side ships as the + * `permissions` session projection; the write side ships as the + * `/permission` command — both optional children over the same service. * * @module dsh-permission */ import { Context, Service } from 'cordis' import z from 'schemastery' +import { z as zod } from 'zod' import type { Session, SessionEvent } from '@deepseek-ai/dsh-session' import type { SandboxMode } from '@deepseek-ai/dsh-sandbox' import { SANDBOX_MODES, effectiveSandboxMode, setSandboxMode } from '@deepseek-ai/dsh-sandbox-policy' @@ -18,6 +21,16 @@ import { SANDBOX_MODES, effectiveSandboxMode, setSandboxMode } from '@deepseek-a import type {} from '@deepseek-ai/dsh-bash' import type { ApprovalPolicy } from '@deepseek-ai/dsh-user-approval' import { APPROVAL_POLICIES, effectiveApprovalPolicy, setApprovalPolicy } from '@deepseek-ai/dsh-user-approval' +// Type-only: resolves ctx.sessionProjections / ctx.commands for the optional children. +import type {} from '@deepseek-ai/dsh-session-projection' +import type {} from '@deepseek-ai/dsh-commands' +import type { PermissionSelect, PresetOption } from './types.ts' + +// The `permissions` projection-key declaration lives in src/types.ts (its one +// home); this re-export projects the type face onto the package root AND +// keeps the module edge in the emitted index.d.ts, so aggregate programs +// consuming the declarations still receive the SessionProjectionMap merge. +export type * from './types.ts' declare module 'cordis' { interface Context { @@ -49,16 +62,6 @@ export interface PresetSpec { description?: string } -/** The select-option shape a presentation layer advertises for one preset (or for the derived `custom` state). */ -export interface PresetOption { - /** Stable option value: the table key, or `custom`. */ - value: string - /** The display label. */ - name: string - /** One user-facing sentence on what the value means. */ - description?: string -} - /** * Returned when effective knob values match no table entry. Clients may show * it as the current value, but it is never a switch target or event payload. @@ -79,6 +82,50 @@ export function effectivePermissionPreset(events: readonly SessionEvent[]): stri return undefined } +/** + * The projection unit's state: the last seen value of each knob event, null + * before an override (composition defaults apply at view time). Plain JSON + * (persisted-cache precondition). + */ +export interface KnobState { + /** Last `permission/preset` payload, or null. */ + preset: string | null + /** Last `sandbox/mode` payload, or null. */ + sandbox: SandboxMode | null + /** Last `approval/policy` payload, or null. */ + approval: ApprovalPolicy | null +} + +/** State for the empty log: every knob at its composition default. */ +const EMPTY_KNOBS: KnobState = { preset: null, sandbox: null, approval: null } + +/** + * One-event knob transition (the projection unit's `apply`). Uninterested + * events return the same reference — the registry's change gate. + * @param state - the folded knob state before `event`. + * @param event - one committed session event. + * @returns the next state; the same reference when the event is not a knob. + */ +export function applyKnobEvent(state: KnobState, event: SessionEvent): KnobState { + switch (event.type) { + case 'permission/preset': + return { ...state, preset: event.data.preset } + case 'sandbox/mode': + return { ...state, sandbox: event.data.mode } + case 'approval/policy': + return { ...state, approval: event.data.policy } + default: + return state + } +} + +/** Whole-log knob fold (the cold-read parallel of {@link applyKnobEvent}). */ +function foldKnobs(events: readonly SessionEvent[]): KnobState { + let state = EMPTY_KNOBS + for (const event of events) state = applyKnobEvent(state, event) + return state +} + /** The {@link PermissionService} config: the deployment's preset table. */ export interface Config { /** @@ -128,6 +175,55 @@ export class PermissionService extends Service { if (ctx.bash.sandboxMode === undefined) { throw new Error('permission: the mounted bash executor does not confine (no sandboxMode) — presets bundle a sandbox mode, so composing this plugin over an unconfined executor is a misconfiguration') } + + // The permissions projection unit: fold the three whole-value knob + // events; view derives the select over the composition defaults this + // service already owns. The unit child activates only when a projection + // registry is composed (headless assemblies stay unaffected). + // zod `.optional()` types the key `string | undefined` while the domain + // says `description?: string`; on the JSON wire the two serialize + // identically (absent), so the cast records exactly that + // exactOptionalPropertyTypes widening (the Wire precedent). + const selectSchema = zod.object({ + options: zod.array(zod.object({ + value: zod.string().min(1), + name: zod.string().min(1), + description: zod.string().optional(), + })), + currentValue: zod.string().min(1), + }) as unknown as zod.ZodType + ctx.inject(['sessionProjections'], (projectionCtx) => { + projectionCtx.sessionProjections.register<'permissions', KnobState>({ + key: 'permissions', + schema: selectSchema, + init: () => EMPTY_KNOBS, + apply: applyKnobEvent, + view: state => this.selectFor(state), + stateVersion: 1, + }) + }) + + // The /permission command: the one write path a web client uses (the + // popup contribution submits the picked preset as this line). The child + // activates only when a command registry is composed. + ctx.inject(['commands'], (commandCtx) => { + commandCtx.commands.register({ + name: 'permission', + description: 'Switch the permission preset (sandbox mode + approval policy)', + input: { hint: '' }, + handler: ({ agent, rawInput }) => { + const name = rawInput.trim() + if (name === '') { + return { kind: 'success', text: `Current permission preset: ${this.current(agent.session.events)}. Available: ${this.names.join(', ')}.` } + } + if (!this.names.includes(name)) { + return { kind: 'error', text: `unknown permission preset "${name}" (available: ${this.names.join(', ')})` } + } + this.set(agent.session, name) + return { kind: 'success', text: `Permission preset: ${name}.` } + }, + }) + }) } /** @@ -146,13 +242,17 @@ export class PermissionService extends Service { * @returns the effective preset name, or `custom` when nothing matches. */ current(events: readonly SessionEvent[]): string { - const sandbox = effectiveSandboxMode(events) ?? this.ctx.bash.sandboxMode - const approval = effectiveApprovalPolicy(events) ?? this.ctx.approval.config.policy ?? 'ask' + return this.derive(foldKnobs(events)) + } + + /** Resolve the preset for one folded knob state (the shared mathematics of `current` and the projection unit). */ + private derive(state: KnobState): string { + const sandbox = state.sandbox ?? this.ctx.bash.sandboxMode + const approval = state.approval ?? this.ctx.approval.config.policy ?? 'ask' const matches = (spec: PresetSpec): boolean => spec.sandbox === sandbox && spec.approval === approval - const folded = effectivePermissionPreset(events) - if (folded !== undefined) { - const spec = this.presets[folded] - if (spec !== undefined && matches(spec)) return folded + if (state.preset !== null) { + const spec = this.presets[state.preset] + if (spec !== undefined && matches(spec)) return state.preset } for (const [name, spec] of Object.entries(this.presets)) { if (matches(spec)) return name @@ -160,6 +260,23 @@ export class PermissionService extends Service { return CUSTOM_PRESET } + /** + * Build the whole select value for one folded knob state: every table + * option in declaration order, `custom` appended exactly while derived. + * @param state - the folded knob overrides. + * @returns the `permissions` projection payload. + */ + selectFor(state: KnobState): PermissionSelect { + const currentValue = this.derive(state) + return { + options: [ + ...this.names.map(name => this.optionOf(name)), + ...currentValue === CUSTOM_PRESET ? [this.optionOf(CUSTOM_PRESET)] : [], + ], + currentValue, + } + } + /** * Resolve a preset's knob bundle. * @param name - the preset name to resolve. diff --git a/packages/ui/permission/src/types.ts b/packages/ui/permission/src/types.ts new file mode 100644 index 0000000000..607cc96837 --- /dev/null +++ b/packages/ui/permission/src/types.ts @@ -0,0 +1,44 @@ +/** + * Pure types of the permission domain: the ONE home of the `permissions` + * projection-key declaration plus its payload types, free of this package's + * host-side value imports (cordis, schemastery). Two namespace projections + * serve it — the package root re-export for host consumers, `./client` (the + * browser half-entry's re-export) for client aggregates — with zero content + * duplication. + * + * @module @deepseek-ai/dsh-permission/types + */ + +/** The select-option shape a presentation layer advertises for one preset (or for the derived `custom` state). */ +export interface PresetOption { + /** Stable option value: the table key, or `custom`. */ + value: string + /** The display label. */ + name: string + /** One user-facing sentence on what the value means; omitted when not configured. */ + description?: string +} + +/** + * Whole `permissions` projection value: every switchable preset in table + * order (plus the derived current-only `custom` when the knobs match no + * entry) and the effective current value. + */ +export interface PermissionSelect { + /** Switchable presets, plus `custom` appended exactly while it is current. */ + options: PresetOption[] + /** The effective current value: a preset table key, or `custom`. */ + currentValue: string +} + +declare module '@deepseek-ai/dsh-session-projection/types' { + interface SessionProjectionMap { + /** + * The session's permission select, folded from the three whole-value + * knob events (`permission/preset`, `sandbox/mode`, `approval/policy`) + * over the composition defaults. Key absence means no permission service + * is composed — clients hide the control. + */ + permissions: PermissionSelect + } +} diff --git a/packages/ui/permission/tests/projection.spec.ts b/packages/ui/permission/tests/projection.spec.ts new file mode 100644 index 0000000000..2046adb6a1 --- /dev/null +++ b/packages/ui/permission/tests/projection.spec.ts @@ -0,0 +1,116 @@ +/** + * The `permissions` projection unit and the `/permission` command: mounting + * the permission service beside the projection registry serves the whole + * select (table options + effective current value, `custom` appended exactly + * while derived) folded from the three knob events over the composition + * defaults; the command child registers `/permission` whose handler switches + * through `permission.set` (bare invocation reports, unknown names error); + * compositions without either registry are unaffected; unmounting the + * service removes the key (HMR safety). + */ + +import { describe, expect, it } from 'vitest' +import { Context } from 'cordis' +import SessionStore, { SessionId } from '@deepseek-ai/dsh-session' +import type { Session } from '@deepseek-ai/dsh-session' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { createScope } from '@deepseek-ai/dsh-scope' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import CommandService from '@deepseek-ai/dsh-commands' +import PermissionService from '@deepseek-ai/dsh-permission' +import type { Config } from '@deepseek-ai/dsh-permission' + +async function harness(options: { withPermission?: boolean; config?: Config } = {}): Promise<{ ctx: Context; session: Session }> { + const ctx = new Context() + await ctx.plugin(SessionStore) + await ctx.plugin(SessionProjectionRegistry) + await ctx.plugin(CommandService) + ctx.provide('bash', { + sandboxMode: 'workspace-write', + resolve() { throw new Error('permission tests do not execute bash') }, + run() { throw new Error('permission tests do not execute bash') }, + start() { throw new Error('permission tests do not execute bash') }, + }) + ctx.provide('approval', { config: { policy: 'ask' } }) + if (options.withPermission !== false) await ctx.plugin(PermissionService, options.config ?? {}) + return { ctx, session: ctx.sessions.create(SessionId('perm-projected')) } +} + +/** Mint a scoped agent over a live session (the command executor's addressing shape). */ +async function agentFor(ctx: Context, session: Session): Promise { + const agent = { id: session.id, session } as Agent + await ctx.plugin(Object.assign((inner: Context) => { createScope(inner, agent) }, { inject: ['commands'] })) + return agent +} + +describe('permissions projection unit', () => { + it('serves the composition-default select at zero events', async () => { + const { ctx, session } = await harness() + const value = ctx.sessionProjections.snapshot(session).values.permissions + expect(value).toMatchObject({ currentValue: 'workspace-write' }) + expect(value?.options.map(option => option.value)).toEqual(['workspace-write', 'danger-full-access']) + }) + + it('folds the knob events and notifies the change feed per knob append', async () => { + const { ctx, session } = await harness() + const changes: { key: string; value: unknown; seq: number }[] = [] + ctx.sessionProjections.onChanged((_session, key, value, seq) => { + changes.push({ key, value, seq }) + }) + ctx.permission.set(session, 'danger-full-access') + // set() appends preset + sandbox/mode + approval/policy: three knob transitions. + expect(changes).toHaveLength(3) + expect(changes.at(-1)).toMatchObject({ key: 'permissions', value: { currentValue: 'danger-full-access' } }) + // Unrelated event: same-reference apply, no notification. + session.append('turn/start', { turn: 1, trigger: { kind: 'message', source: { kind: 'user' } } }) + expect(changes).toHaveLength(3) + }) + + it('appends custom as a current-only option when the knobs match no preset', async () => { + const { ctx, session } = await harness() + session.append('sandbox/mode', { mode: 'read-only' }) + const value = ctx.sessionProjections.snapshot(session).values.permissions + expect(value?.currentValue).toBe('custom') + expect(value?.options.at(-1)).toMatchObject({ value: 'custom', name: 'Custom' }) + }) + + it('has no permissions key without the service, and drops it on unload (HMR safety)', async () => { + const { ctx, session } = await harness({ withPermission: false }) + expect('permissions' in ctx.sessionProjections.snapshot(session).values).toBe(false) + const fiber = await ctx.plugin(PermissionService, {}) + expect(ctx.sessionProjections.snapshot(session).values.permissions).toMatchObject({ currentValue: 'workspace-write' }) + await fiber.dispose() + expect('permissions' in ctx.sessionProjections.snapshot(session).values).toBe(false) + }) +}) + +describe('/permission command', () => { + it('switches through permission.set and logs the lifecycle pair', async () => { + const { ctx, session } = await harness() + const agent = await agentFor(ctx, session) + const execution = await ctx.commands.execute(agent, '/permission danger-full-access', new AbortController().signal) + expect(execution?.result).toEqual({ kind: 'success', text: 'Permission preset: danger-full-access.' }) + expect(ctx.permission.current(session.events)).toBe('danger-full-access') + const run = session.events.find(event => event.type === 'command/run') + expect(run?.data).toMatchObject({ name: 'permission', args: ' danger-full-access' }) + }) + + it('reports the current preset and the table on bare invocation', async () => { + const { ctx, session } = await harness() + const agent = await agentFor(ctx, session) + const execution = await ctx.commands.execute(agent, '/permission', new AbortController().signal) + expect(execution?.result).toEqual({ + kind: 'success', + text: 'Current permission preset: workspace-write. Available: workspace-write, danger-full-access.', + }) + expect(session.events.filter(event => event.type === 'permission/preset')).toHaveLength(0) + }) + + it('rejects an unknown preset without touching the log', async () => { + const { ctx, session } = await harness() + const agent = await agentFor(ctx, session) + const execution = await ctx.commands.execute(agent, '/permission yolo', new AbortController().signal) + expect(execution?.result).toMatchObject({ kind: 'error' }) + expect(session.events.filter(event => event.type !== 'command/run' && event.type !== 'command/done')).toHaveLength(0) + }) +}) diff --git a/packages/ui/permission/tsconfig.json b/packages/ui/permission/tsconfig.json index 0971399f53..493fbf358e 100644 --- a/packages/ui/permission/tsconfig.json +++ b/packages/ui/permission/tsconfig.json @@ -34,6 +34,12 @@ }, { "path": "../../support/invariants" + }, + { + "path": "../../session-projection/session-projection" + }, + { + "path": "../commands" } ] } diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f5309a6838..3d1760f9e1 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -4569,10 +4569,16 @@ importers: schemastery: specifier: ^3.18.0 version: 3.18.0 + zod: + specifier: ^4.4.3 + version: 4.4.3 devDependencies: '@deepseek-ai/dsh-bash': specifier: workspace:^ version: link:../../bash/bash + '@deepseek-ai/dsh-commands': + specifier: workspace:^ + version: link:../commands '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants @@ -4585,6 +4591,9 @@ importers: '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../core/session + '@deepseek-ai/dsh-session-projection': + specifier: workspace:^ + version: link:../../session-projection/session-projection '@deepseek-ai/dsh-user-approval': specifier: workspace:^ version: link:../user-approval From 95a8e3f94992a9a9c1b02c7d4f2212e81d884334 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 22:29:34 +0800 Subject: [PATCH 31/93] =?UTF-8?q?fix(client,doc):=20address=20review=20?= =?UTF-8?q?=E2=80=94=20flow-open=20busy=20gating,=20seam=20on=20the=20arch?= =?UTF-8?q?itecture=20map,=20browse=20gap=20documented?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - While a picking flow is open (native chooser pending, browse dialog up) or its pick is being adopted, every other menu action disables: a late outcome must not race a concurrent selection or creation (ds-review-bot warning). - ctx.directoryPicker joins the architecture Capability Services map (both languages); neighboring rows condensed to keep the doc inside its ceiling. - directory-picker-browse documents that its client half lands in the next stacked PR: a -browse composition today hides the picking affordance (the documented empty-hole default) rather than misbehaving (ds-review-bot critical; the dialog itself ships in #821). --- docs/architecture.i18n.yaml | 4 ++-- docs/architecture.md | 17 +++++++++-------- docs/architecture.zh.md | 5 +++-- .../ui-workspace/src/client/WorkspacePicker.tsx | 11 ++++++++--- .../tests/workspace-picker.spec.tsx | 8 ++++++-- .../directory-picker-browse/README.i18n.yaml | 4 ++-- packages/host/directory-picker-browse/README.md | 1 + .../host/directory-picker-browse/README.zh.md | 1 + 8 files changed, 32 insertions(+), 19 deletions(-) diff --git a/docs/architecture.i18n.yaml b/docs/architecture.i18n.yaml index e56a3f91bb..c296e10fb1 100644 --- a/docs/architecture.i18n.yaml +++ b/docs/architecture.i18n.yaml @@ -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 docs/architecture.md -architecture.md: 054985ac5ea32a44b9daca3c1abfd58dcdc5d897 -architecture.zh.md: 84876faf2ae27069ba8bd026bcfbc56e32f65574 +architecture.md: 2ae982eba49b6dbd2365496915f9917071167813 +architecture.zh.md: abaef961504ff64dbcd1e8e8ba9bd002406fa7f4 diff --git a/docs/architecture.md b/docs/architecture.md index 054985ac5e..2ae982eba4 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -25,27 +25,28 @@ Harnesses are [Cordis](cordis-primer.md) contexts; packages contribute services, | ctx key | Package family | Role | |---|---|---| -| `ctx.llm` | [`llm/`](../packages/llm/README.md) | adapter registry and streaming model calls | -| `ctx.tokenMeter` | [`llm/token-meter`](../packages/llm/token-meter/README.md) | singleton replay-aware request and surface pressure | +| `ctx.llm` | [`llm/`](../packages/llm/README.md) | adapter registry, streaming model calls | +| `ctx.tokenMeter` | [`llm/token-meter`](../packages/llm/token-meter/README.md) | replay-aware request and surface pressure | | `ctx.bash` | [`bash/`](../packages/bash/README.md) | foreground/background command execution | -| `ctx.subprocess` | [`subprocess/`](../packages/subprocess/README.md) | managed child-process trees for the bash executors, the LSP host, and the ACP subagent backend | +| `ctx.subprocess` | [`subprocess/`](../packages/subprocess/README.md) | managed child-process trees for bash, LSP, and ACP subagent backends | | `ctx.pty` | [`pty/`](../packages/pty/README.md) | owner-scoped persistent terminal sessions | | `ctx.sandbox` | [`sandbox/`](../packages/sandbox/README.md) | same-world process confinement through argv wrapping and per-call policy | | `ctx.sandboxPolicy` | [`sandbox/`](../packages/sandbox/README.md) | shared sandbox policy home | | `ctx.codeRuntime` | [`code-runtime/`](../packages/code-runtime/README.md) | model-written program execution | | `ctx.fs` | [`fs/`](../packages/fs/README.md) | filesystem provider primitives and policy events | | `ctx.lsp` | [`lsp/`](../packages/lsp/README.md) | semantic navigation registry | -| `ctx.skills` | [`skill/`](../packages/skill/README.md) | skill provider registry and progressive disclosure | +| `ctx.skills` | [`skill/`](../packages/skill/README.md) | skill provider registry, progressive disclosure | | `ctx.web` | [`web/`](../packages/web/README.md) | search/fetch provider registries | -| `ctx.compact`, `ctx.toolResultPrune` | [`compact/`](../packages/compact/README.md)/[`compact-tool-result-prune`](../packages/compact/compact-tool-result-prune/README.md) | summary compaction and optional model-free result pruning | +| `ctx.compact`, `ctx.toolResultPrune` | [`compact/`](../packages/compact/README.md)/[`compact-tool-result-prune`](../packages/compact/compact-tool-result-prune/README.md) | summary compaction, optional model-free result pruning | | `ctx.subagents` | [`subagent/`](../packages/subagent/README.md) | named delegation providers | | `ctx.planMode` | [`plan/`](../packages/plan/README.md) | logged plan collaboration state | -| `ctx.tasks` | [`tasks/`](../packages/tasks/README.md) | background task registry and generic `task_*` controls | +| `ctx.tasks` | [`tasks/`](../packages/tasks/README.md) | background task registry, generic `task_*` controls | | `ctx.workflows` | [`workflow/`](../packages/workflow/README.md) | script-driven multi-agent orchestration | | `ctx.goals` | [`goal/`](../packages/goal/README.md) | persisted same-session goals | | `ctx.sessionPersistence` | [`session-persistence/`](../packages/session-persistence/README.md) | durable session-log storage | -| `ctx.sessionQuery` | [`session-query/`](../packages/session-query/README.md) | live-preferred exact/filter/trace interface, SQLite FTS backend, workspace-authorized model tools | -| `ctx.sessionTitle` | [`session-title/`](../packages/session-title/README.md) | log-backed fallbacks and one optional asynchronous provider | +| `ctx.sessionQuery` | [`session-query/`](../packages/session-query/README.md) | live-preferred exact/filter/trace queries over SQLite FTS, workspace-authorized model tools | +| `ctx.sessionTitle` | [`session-title/`](../packages/session-title/README.md) | log-backed fallbacks, one optional asynchronous provider | +| `ctx.directoryPicker` | [`host/directory-picker`](../packages/host/directory-picker/README.md) | GUI-host directory picking (`native`/`browse` interactions) | | `ctx.invariants` | [`support/invariants`](../packages/support/invariants/README.md) | package-name-selected registry of package-owned runtime checks | ## Event diff --git a/docs/architecture.zh.md b/docs/architecture.zh.md index 84876faf2a..abaef96150 100644 --- a/docs/architecture.zh.md +++ b/docs/architecture.zh.md @@ -28,7 +28,7 @@ | `ctx.llm` | [`llm/`](../packages/llm/README.md) | 适配器注册表和模型流式调用 | | `ctx.tokenMeter` | [`llm/token-meter`](../packages/llm/token-meter/README.md) | 感知回放的单实例请求压力与表面压力 | | `ctx.bash` | [`bash/`](../packages/bash/README.md) | 前台和后台命令执行 | -| `ctx.subprocess` | [`subprocess/`](../packages/subprocess/README.md) | 供 bash 执行器、LSP host 与 ACP subagent 后端使用的受管子进程树 | +| `ctx.subprocess` | [`subprocess/`](../packages/subprocess/README.md) | 供 bash、LSP 与 ACP subagent 后端使用的受管子进程树 | | `ctx.pty` | [`pty/`](../packages/pty/README.md) | 按 owner 隔离的持久化终端会话 | | `ctx.sandbox` | [`sandbox/`](../packages/sandbox/README.md) | 通过 argv 包装和逐调用策略限制同一执行环境内的进程 | | `ctx.sandboxPolicy` | [`sandbox/`](../packages/sandbox/README.md) | 共享沙箱策略归属点 | @@ -44,8 +44,9 @@ | `ctx.workflows` | [`workflow/`](../packages/workflow/README.md) | 脚本驱动的多 agent 编排 | | `ctx.goals` | [`goal/`](../packages/goal/README.md) | 持久化的同会话目标 | | `ctx.sessionPersistence` | [`session-persistence/`](../packages/session-persistence/README.md) | 会话日志的持久化存储 | -| `ctx.sessionQuery` | [`session-query/`](../packages/session-query/README.md) | 实时优先的精确检索/过滤/追踪接口、SQLite 全文搜索后端、经工作区授权的模型工具 | +| `ctx.sessionQuery` | [`session-query/`](../packages/session-query/README.md) | 基于 SQLite 全文搜索的实时优先精确检索/过滤/追踪、经工作区授权的模型工具 | | `ctx.sessionTitle` | [`session-title/`](../packages/session-title/README.md) | 基于日志的回退标题和单个可选异步提供方 | +| `ctx.directoryPicker` | [`host/directory-picker`](../packages/host/directory-picker/README.md) | GUI 宿主目录选取(`native`/`browse` 交互) | | `ctx.invariants` | [`support/invariants`](../packages/support/invariants/README.md) | 按包名筛选包自有运行时检查的注册表 | ## 事件 diff --git a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx index e98d6d4e26..83c06b369c 100644 --- a/packages/client/ui-workspace/src/client/WorkspacePicker.tsx +++ b/packages/client/ui-workspace/src/client/WorkspacePicker.tsx @@ -81,6 +81,11 @@ export function WorkspaceCreateFlow({ const [pickingFolder, setPickingFolder] = useState(false) const [folderConflict, setFolderConflict] = useState(false) const composingRef = useRef(false) + // One picking interaction at a time: while the flow is open (native chooser + // pending, browse dialog up) or its pick is being adopted, every other + // menu action stays disabled — a late outcome must not race a concurrent + // selection or creation. + const flowBusy = flowOpen || pickingFolder const normalizedWorkspaceName = workspaceName.trim() const duplicateWorkspaceName = !creating && normalizedWorkspaceName !== '' && workspaces.some(workspace => workspace.title === normalizedWorkspaceName) @@ -91,9 +96,9 @@ export function WorkspaceCreateFlow({ // activation, and the menu re-renders on every toggle. const createEntries: MenuEntry[] = [ ...(hasDirectoryFlow() - ? [{ id: OPEN_LOCAL_FOLDER, label: 'Open local folder…', icon: , disabled: pickingFolder }] + ? [{ id: OPEN_LOCAL_FOLDER, label: 'Open local folder…', icon: , disabled: flowBusy }] : []), - { id: CREATE_NEW, label: 'Create a new workspace', icon: , disabled: pickingFolder }, + { id: CREATE_NEW, label: 'Create a new workspace', icon: , disabled: flowBusy }, ] // With workspaces listed, the create actions pin below the scroll region // (divider + always visible); otherwise they ARE the menu. @@ -103,7 +108,7 @@ export function WorkspaceCreateFlow({ id: workspace.workspaceId, label: workspace.title, icon: , - disabled: pickingFolder, + disabled: flowBusy, })) : createEntries diff --git a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx index dbbb444de2..61d353fe45 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx @@ -149,12 +149,16 @@ describe('WorkspacePicker', () => { expect(b.onPick).not.toHaveBeenCalled() }) - it('disables the create actions and reports busy to the flow while adopting', async () => { + it('disables every menu action from flow open through adoption, and reports busy to the flow', async () => { let resolve!: (workspace: WorkspaceView) => void const pending = new Promise((settle) => { resolve = settle }) const created = workspace('adopted') - const b = mount([], vi.fn(() => pending)) + const b = mount([workspace('alpha', 'Alpha')], vi.fn(() => pending)) chooseItem('Open local folder…') + // The flow is open but nothing is picked yet: a chooser pending on the + // host display must already block concurrent workspace actions. + expect(screen.getByRole('menuitem', { name: 'Alpha' }).disabled).toBe(true) + expect(screen.getByRole('menuitem', { name: 'Create a new workspace' }).disabled).toBe(true) act(() => { b.probe.owner!.onPicked('/tmp/project') }) expect(b.probe.owner!.busy).toBe(true) expect(screen.getByRole('menuitem', { name: 'Open local folder…' }).disabled).toBe(true) diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index 34c3e35a79..150a9c2323 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/directory-picker-browse/README.md -README.md: 688a60894cb0ab066a6d501e4df310f8d31bfb5f -README.zh.md: c19bccc2ff9268cb7a6c931da4671bebc9f76b0c +README.md: 632dfec3dac57cac9ea7a02225959fe6e3acf6a0 +README.zh.md: 81a1eb53eac0d3b5a1ef8f2f98c4359ef6a4c5fd diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index 688a60894c..632dfec3da 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -16,6 +16,7 @@ None; this package neither assembles nor sends a provider request. ## Known Limitations and Deferred Work +- **No client half yet** — the in-app browsing dialog that consumes these primitives lands in the next PR of this stack; until then a `-browse` composition hides the picking affordance entirely (ui-workspace's documented empty-hole default) and the listing/creation RPCs go unconsumed. - **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. diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index c19bccc2ff..81a1eb53ea 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -16,6 +16,7 @@ ## 已知限制与延期工作 +- **尚无 client half**——消费这些原语的应用内浏览对话框在本栈的下一个 PR 落地;在那之前 `-browse` 组合会完全隐藏选目录入口(ui-workspace 文档化的空洞默认行为),列举/创建 RPC 无消费者。 - **不读取 Windows 隐藏属性**——Node 的 dirent 不暴露 `FILE_ATTRIBUTE_HIDDEN`,因此在所有平台上 `hidden` 都意味着点前缀,直到原生探测值回其成本为止。 - **不枚举盘符根**——Windows 上祖先链止于盘符根;跨盘依赖浏览器 UI 的路径输入入口,而不是这里的枚举原语。 - **全盘可浏览**——没有按部署限定的浏览根;`workspace.create` 今天就接受任意路径,这里的根只会是 UX 范围而非边界——等到有部署需要时再做。 From 152f3e959636d51afecfdd5d02e45554b54a5e28 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 28 Jul 2026 22:29:41 +0800 Subject: [PATCH 32/93] feat(apps): register OpenAI and Anthropic providers --- apps/cli/README.i18n.yaml | 6 +++--- apps/cli/README.md | 2 ++ apps/cli/README.zh.md | 2 ++ apps/cli/cordis.yml | 13 +++++++++++++ apps/cli/package.json | 1 + examples/tui-agent/composition.md | 3 +++ examples/tui-agent/cordis.yml | 13 ++++++++++++- pnpm-lock.yaml | 3 +++ 8 files changed, 39 insertions(+), 4 deletions(-) diff --git a/apps/cli/README.i18n.yaml b/apps/cli/README.i18n.yaml index abe51abc2f..a9dd09a858 100644 --- a/apps/cli/README.i18n.yaml +++ b/apps/cli/README.i18n.yaml @@ -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: 42d2a9641cf5d497c9aae45d9f60fce4498addb9 -README.zh.md: 0a62f8bb72e2cf2dbe045d28b81768bf4df800de +# pnpm run verify-translation-pairing --write apps/cli/README.md +README.md: 902db2681571aa291bab88ed05f886d07dbf9543 +README.zh.md: 4105a62058201520f2fc1017fe047966f493b0d3 diff --git a/apps/cli/README.md b/apps/cli/README.md index 42d2a9641c..902db26815 100644 --- a/apps/cli/README.md +++ b/apps/cli/README.md @@ -16,6 +16,8 @@ The TUI surface: The Web and headless surfaces boot one shared composition (`cordis.yml`): both treat the invoking directory as the default project and Workspace root, create named Workspaces beneath that root unless `--workspace-root ` overrides it, load applicable `AGENTS.md`/`CLAUDE.md` instructions into each agent-loop request prefix with a 65,536-byte render budget, and opt into first-message model titles. Headless differs only in listening on an OS-assigned port (parallel `dsh -p` runs never collide; the stderr-printed URL opens the live session in a browser). Both need the frontend dist and client bundles built (`pnpm run build && pnpm run build:web`). +The shipped TUI and Web compositions register the native DeepSeek adapter plus pi-ai OpenAI and Anthropic profiles. Credentials and endpoint overrides come from the provider-standard `DEEPSEEK_API_KEY` / `DEEPSEEK_BASE_URL`, `OPENAI_API_KEY` / `OPENAI_BASE_URL`, and `ANTHROPIC_API_KEY` / `ANTHROPIC_BASE_URL` pairs in the boot's layered environment. + `DSH_TOOLS_MODE` selects the tool presentation mode for the whole Web/headless process: `native` (the schema default when unset), `code` (the `run_code`-only Code Mode wire), or `both`; any other value fails loud at boot through the `dsh-tools` config schema. It is a TEMPORARY seam — process-wide because Loader composition is static — and is removed once the web UI owns per-session tool-mode selection; the TUI surface ignores it (its config tree pins its own mode). ## Install (developer machine) diff --git a/apps/cli/README.zh.md b/apps/cli/README.zh.md index 0a62f8bb72..4105a62058 100644 --- a/apps/cli/README.zh.md +++ b/apps/cli/README.zh.md @@ -16,6 +16,8 @@ TUI 界面: Web 和无头界面启动同一个共享组合(`cordis.yml`):两者都将调用目录视为默认项目和 Workspace 根目录,除非通过 `--workspace-root ` 覆盖,否则会在该根目录下创建具名 Workspace;它们会把适用的 `AGENTS.md`/`CLAUDE.md` 指令加载到每个 agent-loop 请求前缀中,渲染预算为 65,536 字节,并选用首条消息模型标题。无头界面唯一的差异是监听操作系统分配的端口(并行 `dsh -p` 运行绝不冲突;stderr 打印的 URL 会在浏览器中打开实时会话)。两者都需要先构建前端 dist 和客户端 bundle(`pnpm run build && pnpm run build:web`)。 +已交付的 TUI 和 Web 组合会注册原生 DeepSeek 适配器,以及 pi-ai 的 OpenAI 和 Anthropic 提供方配置。凭据和端点覆盖来自启动分层环境中的提供方标准变量对:`DEEPSEEK_API_KEY` / `DEEPSEEK_BASE_URL`、`OPENAI_API_KEY` / `OPENAI_BASE_URL` 和 `ANTHROPIC_API_KEY` / `ANTHROPIC_BASE_URL`。 + `DSH_TOOLS_MODE` 为整个 Web/无头进程选择工具呈现模式:可选值为 `native`(未设置时的 schema 默认值)、`code`(仅含 `run_code` 的 Code Mode 协议接口)或 `both`;任何其他值都会经由 `dsh-tools` 配置 schema 在启动时明确报错。它是一个临时 seam:Loader 组合是静态的,因此该设置作用于整个进程;待 Web UI 负责逐会话工具模式选择后便会移除。TUI 界面会忽略该变量(其配置树固定了自身模式)。 ## 安装(开发机) diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index 0dbd6c839e..55239fc114 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -86,6 +86,19 @@ apiKey: !!js process.env.DEEPSEEK_API_KEY baseURL: !!js process.env.DEEPSEEK_BASE_URL +# Common pi-ai provider routes read credentials and endpoint overrides from the +# boot's layered environment. +- id: llm-pi-ai + name: '@deepseek-ai/dsh-llm-pi-ai' + config: + providers: + - provider: openai + apiKey: !!js process.env.OPENAI_API_KEY + baseURL: !!js process.env.OPENAI_BASE_URL + - provider: anthropic + apiKey: !!js process.env.ANTHROPIC_API_KEY + baseURL: !!js process.env.ANTHROPIC_BASE_URL + # Transient-failure recovery around the loop's model calls (same policy as # the TUI's agent-spine composition; defaults: 2 retries, 500ms→10s backoff). - id: llm-retry diff --git a/apps/cli/package.json b/apps/cli/package.json index 7d984ee1b1..92f49be21c 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -51,6 +51,7 @@ "@deepseek-ai/dsh-host-webserver": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-llm-deepseek": "workspace:^", + "@deepseek-ai/dsh-llm-pi-ai": "workspace:^", "@deepseek-ai/dsh-llm-retry": "workspace:^", "@deepseek-ai/dsh-paths": "workspace:^", "@deepseek-ai/dsh-plan-mode": "workspace:^", diff --git a/examples/tui-agent/composition.md b/examples/tui-agent/composition.md index c6fc223113..86129d3fa4 100644 --- a/examples/tui-agent/composition.md +++ b/examples/tui-agent/composition.md @@ -12,6 +12,8 @@ flowchart LR cfg --> plugin_tui_hmr plugin_tui_llm_deepseek["llm-deepseek
@deepseek-ai/dsh-llm-deepseek"] cfg --> plugin_tui_llm_deepseek + plugin_tui_llm_pi_ai["llm-pi-ai
@deepseek-ai/dsh-llm-pi-ai"] + cfg --> plugin_tui_llm_pi_ai plugin_tui_subprocess["subprocess
@deepseek-ai/dsh-subprocess-local"] cfg --> plugin_tui_subprocess plugin_tui_bash["bash
@deepseek-ai/dsh-bash-local"] @@ -71,6 +73,7 @@ flowchart LR | --- | --- | | `hmr` | `@cordisjs/plugin-hmr` | | `llm-deepseek` | `@deepseek-ai/dsh-llm-deepseek` | +| `llm-pi-ai` | `@deepseek-ai/dsh-llm-pi-ai` | | `subprocess` | `@deepseek-ai/dsh-subprocess-local` | | `bash` | `@deepseek-ai/dsh-bash-local` | | `tui-agent` | `@deepseek-ai/dsh-tui-demo` | diff --git a/examples/tui-agent/cordis.yml b/examples/tui-agent/cordis.yml index 7c8b03db05..2b14271c96 100644 --- a/examples/tui-agent/cordis.yml +++ b/examples/tui-agent/cordis.yml @@ -1,4 +1,4 @@ -# Full-screen TUI coding agent with swappable DeepSeek and local-bash backends. +# Full-screen TUI coding agent with swappable model and local-bash backends. # `dsh-tui-demo` supplies the agent spine, workspace instructions, generic # task controls, JSONL persistence, the pi-tui front door, and `main`. # HMR remains a leaf because it depends on Loader internals. The app bin loads @@ -20,6 +20,17 @@ thinking: enabled reasoningEffort: max +- id: llm-pi-ai + name: '@deepseek-ai/dsh-llm-pi-ai' + config: + providers: + - provider: openai + apiKey: !!js process.env.OPENAI_API_KEY + baseURL: !!js process.env.OPENAI_BASE_URL + - provider: anthropic + apiKey: !!js process.env.ANTHROPIC_API_KEY + baseURL: !!js process.env.ANTHROPIC_BASE_URL + # Local executor for the app bundle's bash tool. # Managed child-process groups for the bash executor (spawn/kill/output plumbing). - id: subprocess diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f5309a6838..059a45f1c4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -221,6 +221,9 @@ importers: '@deepseek-ai/dsh-llm-deepseek': specifier: workspace:^ version: link:../../packages/llm/llm-deepseek + '@deepseek-ai/dsh-llm-pi-ai': + specifier: workspace:^ + version: link:../../packages/llm/llm-pi-ai '@deepseek-ai/dsh-llm-retry': specifier: workspace:^ version: link:../../packages/llm/llm-retry From 7c9d688a825a5b8eb754cb0e9feccedb9d7ac0ed Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 22:37:19 +0800 Subject: [PATCH 33/93] test(host): cover the native flow's re-arm guard A fresh injected face while the same request is open re-fires the effect; the armed guard must not relaunch the chooser (the uncovered branch CI's per-file gate flagged). --- .../host/directory-picker-native/tests/client-flow.spec.tsx | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/packages/host/directory-picker-native/tests/client-flow.spec.tsx b/packages/host/directory-picker-native/tests/client-flow.spec.tsx index cf2cb96679..fe4c30fc5d 100644 --- a/packages/host/directory-picker-native/tests/client-flow.spec.tsx +++ b/packages/host/directory-picker-native/tests/client-flow.spec.tsx @@ -83,6 +83,11 @@ describe('directory-picker-native client half', () => { const second = owner() view.rerender() 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(() => {})) + view.rerender() + expect(replacedPick).not.toHaveBeenCalled() await act(async () => { resolve('/tmp/project') }) expect(second.onPicked).toHaveBeenCalledWith('/tmp/project') expect(first.onPicked).not.toHaveBeenCalled() From 25265b312c2e3cb1788e0c195cc4f8ba7b0ac0e5 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Tue, 28 Jul 2026 22:56:43 +0800 Subject: [PATCH 34/93] feat(web): projection-fed permission chip replaces the Access placeholder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PermissionSelect returns as the Access seat's wired occupant: options and the current value read from the 'permissions' projection through the standard-kit useProjection (no fetch, no mount timing — the resident composer's mount-once fetch bug dies with the fetch), key absence renders nothing (permission-less host, or a Draft with no session), and a pick submits the '/permission ' command line through the new ComposerBarInjected.command callback (Session.command = command.execute admission; the pushed projection frame lands the confirmed value). The READONLY_OPTIONS placeholder and its local state leave InputBar. The connection fixture mirrors the host: a permissions unit fold (three knob events over the fixture preset table), the projections block + baseline/push frames carry the key, and /permission joins the command catalog with the same switch-through-knob-events handler shape. --- .../client/connection/src/client/fixture.ts | 69 ++++++++++++++++ .../connection/tests/fixture-commands.spec.ts | 2 +- .../client/connection/tests/fixture.spec.ts | 25 ++++-- .../runtime/src/client/sessions/session.ts | 15 ++++ packages/client/ui-conversation/package.json | 5 +- .../ui-conversation/src/client/apply.ts | 6 ++ .../src/client/contract/slots.ts | 6 ++ .../src/client/skeleton/InputBar.tsx | 31 +++---- .../skeleton/PermissionSelect.module.css | 49 ++++++++++++ .../src/client/skeleton/PermissionSelect.tsx | 80 +++++++++++++++++++ .../ui-conversation/tests/input-bar.spec.tsx | 36 +++++++-- .../tests/input-matrix.spec.tsx | 1 + .../tests/input-scenarios.spec.tsx | 1 + .../ui-conversation/tests/skeleton.spec.tsx | 1 + packages/client/ui-conversation/tsconfig.json | 3 + pnpm-lock.yaml | 3 + 16 files changed, 295 insertions(+), 38 deletions(-) create mode 100644 packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css create mode 100644 packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 56d8b90d34..3139cd3770 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -303,6 +303,42 @@ function viewFor(event: SessionEvent, log: readonly SessionEvent[]): ToolEventVi } /** Fixture parallel of the host's projection units: whole current values per key over the full log. */ +/** Fixture preset table (the host PermissionService defaults). */ +const PERMISSION_PRESETS: Record = { + 'workspace-write': { sandbox: 'workspace-write', approval: 'ask', description: 'Write inside the workspace and permitted temporary directories; wider retries require approval.' }, + 'danger-full-access': { sandbox: 'danger-full-access', approval: 'never', description: 'Full file access without approval prompts.' }, +} + +/** Host permissions-unit parallel: fold the three knob events, derive the select over the fixture defaults. */ +function permissionSelectOf(log: readonly SessionEvent[]): { options: { value: string; name: string; description?: string }[]; currentValue: string } { + let preset: string | null = null + let sandbox = 'workspace-write' + let approval = 'ask' + for (const event of log) { + const item = event as { type: string; data: Record } + if (item.type === 'permission/preset') preset = item.data['preset'] as string + else if (item.type === 'sandbox/mode') sandbox = item.data['mode'] as string + else if (item.type === 'approval/policy') approval = item.data['policy'] as string + } + const matches = (spec: { sandbox: string; approval: string }): boolean => spec.sandbox === sandbox && spec.approval === approval + let currentValue = 'custom' + const folded = preset === null ? undefined : PERMISSION_PRESETS[preset] + if (preset !== null && folded !== undefined && matches(folded)) { + currentValue = preset + } else { + for (const [name, spec] of Object.entries(PERMISSION_PRESETS)) { + if (matches(spec)) { currentValue = name; break } + } + } + return { + options: [ + ...Object.entries(PERMISSION_PRESETS).map(([value, spec]) => ({ value, name: value, description: spec.description })), + ...currentValue === 'custom' ? [{ value: 'custom', name: 'Custom', description: 'Current sandbox and approval settings do not match a preset.' }] : [], + ], + currentValue, + } +} + function projectionValuesOf(log: readonly SessionEvent[]): Record { const values: Record = {} const titleEvent = log.findLast(item => (item as { type: string }).type === 'session/title') @@ -311,6 +347,8 @@ function projectionValuesOf(log: readonly SessionEvent[]): Record' } }, + { name: 'permission', description: 'Switch the permission preset (sandbox mode + approval policy)', input: { hint: '' } }, ], }) }, @@ -953,6 +1002,26 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy { const match = /^\/(\S+)((?:\s.*)?)$/.exec(request.payload.line.trim()) const name = match?.[1] const args = match?.[2] ?? '' + // /permission mirrors the host handler: switch through the knob + // events (each append pushes a permissions projection frame). + if (name === 'permission') { + const preset = args.trim() + const commandId = `fx-cmd-${logOf(id).length}` as CommandId + append(id, { type: 'command/run', data: { commandId, name, args, source: { kind: 'user' } } }) + const spec = PERMISSION_PRESETS[preset] + if (preset === '') { + const current = permissionSelectOf(logOf(id)).currentValue + append(id, { type: 'command/done', data: { commandId, kind: 'success', text: `Current permission preset: ${current}. Available: ${Object.keys(PERMISSION_PRESETS).join(', ')}.` } }) + } else if (spec === undefined) { + append(id, { type: 'command/done', data: { commandId, kind: 'error', text: `unknown permission preset ${JSON.stringify(preset)} (available: ${Object.keys(PERMISSION_PRESETS).join(', ')})` } }) + } else { + if (permissionSelectOf(logOf(id)).currentValue !== preset) append(id, { type: 'permission/preset', data: { preset } }) + append(id, { type: 'sandbox/mode', data: { mode: spec.sandbox } }) + append(id, { type: 'approval/policy', data: { policy: spec.approval } }) + append(id, { type: 'command/done', data: { commandId, kind: 'success', text: `Permission preset: ${preset}.` } }) + } + return ok(request, { matched: true as const, commandId }) + } const outcomes: Record = { compact: 'fixture:已压缩(假动作)', echo: args.trim(), diff --git a/packages/client/connection/tests/fixture-commands.spec.ts b/packages/client/connection/tests/fixture-commands.spec.ts index bd66d124a4..f4d5a290f7 100644 --- a/packages/client/connection/tests/fixture-commands.spec.ts +++ b/packages/client/connection/tests/fixture-commands.spec.ts @@ -23,7 +23,7 @@ describe('createFixtureApi commands/skills', () => { expect(response.rpcId).toBe(request.rpcId) if (!response.result.ok) throw new Error('list failed') const commands = response.result.value.commands - expect(commands.map(c => c.name)).toEqual(['compact', 'echo', 'goal-fixture']) + expect(commands.map(c => c.name)).toEqual(['compact', 'echo', 'goal-fixture', 'permission']) // input hint rides only the commands declaring it. const echo = commands.find(c => c.name === 'echo') expect(echo?.input?.hint).toBeTruthy() diff --git a/packages/client/connection/tests/fixture.spec.ts b/packages/client/connection/tests/fixture.spec.ts index 7ba49dd5f5..1f2d9f4f4e 100644 --- a/packages/client/connection/tests/fixture.spec.ts +++ b/packages/client/connection/tests/fixture.spec.ts @@ -71,7 +71,17 @@ describe('createFixtureApi', () => { if (!empty.result.ok) throw new Error('empty failed') // Fixture composes the todos unit (host parallel when tool-todo is mounted): null before any write. expect(empty.result.value).toEqual({ - events: [], hasMore: false, projections: { asOfSeq: -1, values: { todos: null } }, + events: [], hasMore: false, projections: { asOfSeq: -1, values: { + todos: null, + // Permission unit composed: the composition-default select. + permissions: { + options: [ + { value: 'workspace-write', name: 'workspace-write', description: 'Write inside the workspace and permitted temporary directories; wider retries require approval.' }, + { value: 'danger-full-access', name: 'danger-full-access', description: 'Full file access without approval prompts.' }, + ], + currentValue: 'workspace-write', + }, + } }, }) }) @@ -206,7 +216,7 @@ describe('createFixtureApi', () => { const envelopes: RpcRequest[] = [] for await (const envelope of api.events.mux(req({}), abort.signal)) { envelopes.push(envelope) - if (envelopes.length >= 4) abort.abort() + if (envelopes.length >= 5) abort.abort() } return envelopes } @@ -214,13 +224,14 @@ describe('createFixtureApi', () => { const second = await openOnce() expect(first[0]?.payload).toMatchObject({ type: 'session/subscribed', sessionId: 'fx-alpha' }) expect((first[0]?.payload as { lastSeq: number }).lastSeq).toBeGreaterThan(0) - // Projection baseline frames follow the subscribed frame (title + todos units). + // Projection baseline frames follow the subscribed frame (title + todos + permissions units). expect(first[1]?.payload).toMatchObject({ type: 'session/projection', sessionId: 'fx-alpha', key: 'title', value: 'Fixture 历史会话' }) expect(first[2]?.payload).toMatchObject({ type: 'session/projection', sessionId: 'fx-alpha', key: 'todos' }) - expect(first[3]?.payload).toMatchObject({ type: 'approval/requested', toolName: 'dangerous_tool' }) - expect(second[3]?.rpcId).toBe(first[3]?.rpcId) // stable rpcId across replays (host replay semantics) - expect(first[4]?.payload).toMatchObject({ type: 'question/requested', sessionId: 'fx-alpha' }) - expect(second[4]?.rpcId).toBe(first[4]?.rpcId) + expect(first[3]?.payload).toMatchObject({ type: 'session/projection', sessionId: 'fx-alpha', key: 'permissions' }) + expect(first[4]?.payload).toMatchObject({ type: 'approval/requested', toolName: 'dangerous_tool' }) + expect(second[4]?.rpcId).toBe(first[4]?.rpcId) // stable rpcId across replays (host replay semantics) + expect(first[5]?.payload).toMatchObject({ type: 'question/requested', sessionId: 'fx-alpha' }) + expect(second[5]?.rpcId).toBe(first[5]?.rpcId) }) it('steer with no replay in flight falls through to a fresh queued turn; non-text blocks stringify empty', async () => { diff --git a/packages/client/runtime/src/client/sessions/session.ts b/packages/client/runtime/src/client/sessions/session.ts index 00398d53af..855d28afd8 100644 --- a/packages/client/runtime/src/client/sessions/session.ts +++ b/packages/client/runtime/src/client/sessions/session.ts @@ -248,6 +248,21 @@ export class Session implements ObservableSnapshot { return result } + /** + * Execute one slash-command line against this session's agent — pure + * admission semantics (the host executor durably logs the lifecycle; + * outcomes render as flow nodes, never as a response echo). + * @param line - the full command line, leading slash included. + * @returns the admission result, or the error branch on transport failure. + */ + async command(line: string): Promise> { + try { + return (await this.api.commands.execute({ sessionId: this.sessionId, line })).result + } catch (error) { + return transportError(error) + } + } + /** First open: pull the tail page (idempotent — in-flight/already-open returns the existing promise). */ open(): Promise { if (this.openState === 'open') return Promise.resolve() diff --git a/packages/client/ui-conversation/package.json b/packages/client/ui-conversation/package.json index 0b184dcbdf..fdf8386b0a 100644 --- a/packages/client/ui-conversation/package.json +++ b/packages/client/ui-conversation/package.json @@ -49,13 +49,14 @@ }, "devDependencies": { "@deepseek-ai/dsh-client-runtime": "workspace:^", - "@deepseek-ai/dsh-session-projection": "workspace:^", - "@deepseek-ai/dsh-tool-todo": "workspace:^", "@deepseek-ai/dsh-client-ui-layout": "workspace:^", "@deepseek-ai/dsh-client-ui-primitives": "workspace:^", "@deepseek-ai/dsh-client-ui-slash": "workspace:^", "@deepseek-ai/dsh-client-ui-slots": "workspace:^", "@deepseek-ai/dsh-invariants": "workspace:^", + "@deepseek-ai/dsh-permission": "workspace:^", + "@deepseek-ai/dsh-session-projection": "workspace:^", + "@deepseek-ai/dsh-tool-todo": "workspace:^", "@types/react": "~18.3.1", "cordis": "^4.0.0-rc.7", "react": "^18.2.0" diff --git a/packages/client/ui-conversation/src/client/apply.ts b/packages/client/ui-conversation/src/client/apply.ts index 75ed09e78e..55416accc3 100644 --- a/packages/client/ui-conversation/src/client/apply.ts +++ b/packages/client/ui-conversation/src/client/apply.ts @@ -150,6 +150,12 @@ export function apply(ctx: Context): void { // Stop failure surfaces via snapshot.promptError; nothing to restore. }) }, + command: async (line) => { + const session = sessions.binding(sessionId)?.session + if (session === undefined) return false + const result = await session.command(line) + return result.ok && result.value.matched + }, hooks: { notices: shell.notices, lexicon: shell.lexicon }, } }, diff --git a/packages/client/ui-conversation/src/client/contract/slots.ts b/packages/client/ui-conversation/src/client/contract/slots.ts index bddfafd6c7..379c33a8c8 100644 --- a/packages/client/ui-conversation/src/client/contract/slots.ts +++ b/packages/client/ui-conversation/src/client/contract/slots.ts @@ -250,6 +250,12 @@ export interface ComposerBarInjected { keyboard: ComposerKeyboard /** Cancel the in-flight turn. */ stop: () => void + /** + * Submit one slash-command line against this session's agent (the chrome + * controls' write path — the permission chip submits `/permission `). + * Resolves admission: false = rejected/unmatched/transport failure. + */ + command: (line: string) => Promise /** Registrant hooks compartment: the renderer binds these to useNotices/useLexicon. */ hooks: { /** Latest surfaced notice (null after none; seq keys re-render of repeats). */ diff --git a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx index 26a65def6a..821e309d89 100644 --- a/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx +++ b/packages/client/ui-conversation/src/client/skeleton/InputBar.tsx @@ -6,12 +6,13 @@ * region-slot content) ride the owner props. Session facts * (running/removed/promptError) are self-selected via useSession. */ -import { useEffect, useRef, useState } from 'react' +import { useEffect, useRef } from 'react' import type { ChangeEvent, KeyboardEvent, MouseEvent, ReactNode } from 'react' import clsx from 'clsx' import { IconPlusOutline16 } from '@deepseek-ai/dsh-client-ui-primitives' import type { ComposerBarProps } from '../contract/slots.ts' import { deriveDecorations } from '../input/decorations.ts' +import { PermissionSelect } from './PermissionSelect.tsx' import css from './InputBar.module.css' /** Prompt failure surface (derived from promptError). */ @@ -22,13 +23,8 @@ export interface InputBarError { export type InputBarProps = ComposerBarProps -const READONLY_OPTIONS: readonly { id: string; label: string }[] = [ - { id: 'readonly', label: 'Read-only' }, - { id: 'readwrite', label: 'Read-write' }, -] - export function InputBar({ - useSession, useInput, inputActions, keyboard, stop, renderSlot, useNotices, useLexicon, + useSession, useInput, inputActions, keyboard, stop, command, renderSlot, useNotices, useLexicon, useProjection, variant, placeholder, accessory, overlay, leftItems, rightItems, onAdd, addLabel = 'Add attachment', }: InputBarProps) { const input = useInput(s => s) @@ -58,9 +54,9 @@ export function InputBar({ }, 10) } - // Placeholder chrome: Access selection stays local until its seam lands - // (plan/model are real seats now — the named single slots below). - const [readonlyId, setReadonlyId] = useState('readonly') + // The Access seat's data: the host-computed permissions projection + // (undefined = capability absent → the chip renders nothing). + const permissions = useProjection('permissions') // Queue cut 1: running input stays free; locked = session disabled only. // The transient machine locks (adjudicating pending / submitting) render @@ -223,19 +219,10 @@ export function InputBar({ if (!empty && !disabled && !machineBusy) inputActions.submit('queue') } - // Access placeholder select (the one remaining local-chrome control). + // The Access seat: the projection-fed permission chip (renders nothing + // while the permissions key is absent — permission-less host or Draft). const accessSelect: ReactNode = ( - + ) // Mirror-layer decorations: a visible backdrop with transparent text. The diff --git a/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css new file mode 100644 index 0000000000..dd5986992c --- /dev/null +++ b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.module.css @@ -0,0 +1,49 @@ +/* Composer bottom-row permission chip (draft start.jpeg `Read-only ∨`): a + quiet text chip with a chevron; hover paints the standard interactive pill. + The native select is stretched invisibly over the chip so the platform + dropdown does the menu work — keyboard/AT semantics come free. */ + +.root { + position: relative; + display: inline-flex; + align-items: center; +} + +.chip { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 6px 8px; + border-radius: 8px; + color: var(--dsw-alias-label-secondary); + font-size: 14px; + line-height: 20px; + pointer-events: none; /* the overlaid select owns the interaction */ +} + +.root:hover .chip { + background: var(--dsw-alias-interactive-bg-hover); +} + +.chevron { + color: var(--dsw-alias-label-caption); +} + +/* Invisible native select stretched over the chip: real menu, zero drawing. */ +.select { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + opacity: 0; + border: none; + cursor: pointer; +} + +.select:disabled { + cursor: default; +} + +.root:has(.select:disabled) .chip { + opacity: 0.5; +} diff --git a/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx new file mode 100644 index 0000000000..0622e64500 --- /dev/null +++ b/packages/client/ui-conversation/src/client/skeleton/PermissionSelect.tsx @@ -0,0 +1,80 @@ +// PermissionSelect: the composer bottom-row permission chip (draft +// start.jpeg's `Read-only ∨` control), the Access seat's wired occupant. +// Options and the current value read from the host-computed `permissions` +// projection (baseline block + push frames — no fetch, no mount timing); +// key absence (a permission-less composition, or a Draft with no host +// session yet) renders nothing. The visible chip is presentation only — an +// invisible native select stretched over it owns the menu and interaction. +// A switch submits the `/permission ` command line (the one write +// path); the control shows the picked value optimistically and disables +// until the admission result, then re-follows the projection — the pushed +// frame confirms the switch, and a failed/unmatched submit falls back to +// the still-authoritative projection value (`custom` is shown as the +// current value but never offered as a target — the host omits it from +// switchable options). + +import { useState } from 'react' +import type { PermissionSelect as PermissionSelectValue } from '@deepseek-ai/dsh-permission/client' +import css from './PermissionSelect.module.css' + +/** + * Display transform: kebab-case machine names render as title-case labels + * (`workspace-write` → `Workspace Write`). Presentation-only — the wire + * vocabulary and the host's advertised names are untouched; a host-configured + * name that is not kebab-case (contains spaces or uppercase) passes through. + */ +function displayName(name: string): string { + if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(name)) return name + return name.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ') +} + +export interface PermissionSelectProps { + /** The host-computed select, or undefined while the capability is absent. */ + value: PermissionSelectValue | undefined + /** Session-removed lock (the bar's chrome disable state). */ + locked: boolean + /** Submit one slash-command line; resolves admission (false = rejected/unmatched). */ + command: (line: string) => Promise +} + +export function PermissionSelect({ value, locked, command }: PermissionSelectProps) { + // Optimistic pick, shown while the admission round-trip runs; null follows + // the projection (the pushed frame lands the confirmed value there). + const [pick, setPick] = useState(null) + if (value === undefined) return null + + const currentValue = pick ?? value.currentValue + const current = value.options.find(option => option.value === currentValue) + + const onChange = (next: string): void => { + if (next === value.currentValue) return + setPick(next) + void command(`/permission ${next}`) + .catch(() => false) + .then(() => { setPick(null) }) + } + + return ( + + ) +} diff --git a/packages/client/ui-conversation/tests/input-bar.spec.tsx b/packages/client/ui-conversation/tests/input-bar.spec.tsx index f8b9fd3d67..0aea847bfe 100644 --- a/packages/client/ui-conversation/tests/input-bar.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.spec.tsx @@ -33,6 +33,7 @@ interface BenchOptions { modelEntry?: React.ReactNode /** Hot text-ref lexicon (injects a minimal slash stub exposing only lexicon()). */ lexicon?: ReadonlyMap<'/' | '@', readonly string[]> + permissions?: { options: { value: string; name: string; description?: string }[]; currentValue: string } draft?: string running?: boolean disabled?: boolean @@ -88,13 +89,14 @@ function bench(over?: BenchOptions) { items: [], state: 'idle', phase: 'ready', error: null, baselinesReady: true, recentWorkspaceId: undefined, })), - useProjection: (() => undefined), + useProjection: ((key: string) => (key === 'permissions' ? over?.permissions : undefined)) as InputBarProps['useProjection'], useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, useNotices: bindSnapshotSelector(shell.notices), useLexicon: bindSnapshotSelector(shell.lexicon), stop, + command: () => Promise.resolve(true), renderSlot, variant: over?.variant ?? 'composer', ...(over?.placeholder !== undefined ? { placeholder: over.placeholder } : {}), @@ -352,16 +354,37 @@ describe('strips and variants', () => { }) describe('placeholder chrome and control seats', () => { - it('renders attach + Access placeholder; plan/model seats render EMPTY without entries (B ruling)', () => { + it('renders attach; the Access chip is absent without the permissions projection; plan/model seats render EMPTY without entries (B ruling)', () => { const { view, slotCalls } = bench() expect(view.getByLabelText('Add attachment')).toBeTruthy() - expect((view.getByLabelText('Access mode') as HTMLSelectElement).value).toBe('readonly') + // Capability absent (no projection value): the chip renders nothing. + expect(view.queryByLabelText('Access mode')).toBeNull() // Both seats dispatched, nothing rendered. expect(slotCalls.map(c => c.key)).toEqual(['conversation.input.plan', 'conversation.input.model']) expect(view.queryByLabelText('Plan mode')).toBeNull() expect(view.queryByLabelText('Model')).toBeNull() }) + it('the Access chip renders the projection value and submits /permission on pick', async () => { + const permissions = { + options: [ + { value: 'workspace-write', name: 'workspace-write' }, + { value: 'danger-full-access', name: 'danger-full-access' }, + ], + currentValue: 'workspace-write', + } + const { view } = bench({ permissions }) + const select = view.getByLabelText('Access mode') as HTMLSelectElement + expect(select.value).toBe('workspace-write') + // Title-case display is presentation only; the option values stay machine names. + expect([...select.options].map(o => o.textContent)).toEqual(['Workspace Write', 'Danger Full Access']) + fireEvent.change(select, { target: { value: 'danger-full-access' } }) + // Optimistic pick + disable until admission resolves (command stub resolves true). + expect(select.disabled).toBe(true) + await act(async () => {}) + expect(select.disabled).toBe(false) + }) + it('a registered entry fills its seat and receives the locked owner prop', () => { const { view, slotCalls } = bench({ disabled: true, @@ -377,12 +400,13 @@ describe('placeholder chrome and control seats', () => { expect(live.slotCalls.every(c => !(c.owner as { locked: boolean }).locked)).toBe(true) }) - it('disabled locks the Access placeholder and attach control (running does not)', () => { - const { view } = bench({ disabled: true }) + it('disabled locks the Access chip and attach control (running does not)', () => { + const permissions = { options: [{ value: 'workspace-write', name: 'workspace-write' }], currentValue: 'workspace-write' } + const { view } = bench({ disabled: true, permissions }) expect((view.getByLabelText('Add attachment') as HTMLButtonElement).disabled).toBe(true) expect((view.getByLabelText('Access mode') as HTMLSelectElement).disabled).toBe(true) cleanup() - const live = bench({ running: true }) + const live = bench({ running: true, permissions }) expect((live.view.getByLabelText('Access mode') as HTMLSelectElement).disabled).toBe(false) }) }) diff --git a/packages/client/ui-conversation/tests/input-matrix.spec.tsx b/packages/client/ui-conversation/tests/input-matrix.spec.tsx index 8a04dde4a5..bcdecc9a02 100644 --- a/packages/client/ui-conversation/tests/input-matrix.spec.tsx +++ b/packages/client/ui-conversation/tests/input-matrix.spec.tsx @@ -47,6 +47,7 @@ function mountBar(shell: SessionInputShell, over?: { running?: boolean; disabled useLexicon: bindSnapshotSelector(shell.lexicon), renderSlot: (() => null) as InputBarProps['renderSlot'], stop: vi.fn(), + command: () => Promise.resolve(true), variant: 'composer', } return render() diff --git a/packages/client/ui-conversation/tests/input-scenarios.spec.tsx b/packages/client/ui-conversation/tests/input-scenarios.spec.tsx index 4464f4876c..9d9ace032c 100644 --- a/packages/client/ui-conversation/tests/input-scenarios.spec.tsx +++ b/packages/client/ui-conversation/tests/input-scenarios.spec.tsx @@ -133,6 +133,7 @@ async function scopedBench(register?: (slash: SlashService) => void) { useLexicon: bindSnapshotSelector(shell.lexicon), renderSlot: (() => null) as InputBarProps['renderSlot'], stop: vi.fn(), + command: () => Promise.resolve(true), variant: 'composer', } const view = render() diff --git a/packages/client/ui-conversation/tests/skeleton.spec.tsx b/packages/client/ui-conversation/tests/skeleton.spec.tsx index b6263929cf..0d32e2edea 100644 --- a/packages/client/ui-conversation/tests/skeleton.spec.tsx +++ b/packages/client/ui-conversation/tests/skeleton.spec.tsx @@ -123,6 +123,7 @@ function mount( useNotices={bindSnapshotSelector(wiring.notices)} useLexicon={bindSnapshotSelector(wiring.lexicon)} stop={stop} + command={() => Promise.resolve(true)} renderSlot={(() => null) as InputBarProps['renderSlot']} {...bar} /> diff --git a/packages/client/ui-conversation/tsconfig.json b/packages/client/ui-conversation/tsconfig.json index 32ba48e8fe..9df35ff30f 100644 --- a/packages/client/ui-conversation/tsconfig.json +++ b/packages/client/ui-conversation/tsconfig.json @@ -40,6 +40,9 @@ }, { "path": "../../support/invariants" + }, + { + "path": "../../ui/permission" } ], "exclude": [ diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 3d1760f9e1..5834d885fe 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -982,6 +982,9 @@ importers: '@deepseek-ai/dsh-invariants': specifier: workspace:^ version: link:../../support/invariants + '@deepseek-ai/dsh-permission': + specifier: workspace:^ + version: link:../../ui/permission '@deepseek-ai/dsh-session-projection': specifier: workspace:^ version: link:../../session-projection/session-projection From a19ea11cfd67dc1775e5dd72a019a080693ed70c Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 22:58:39 +0800 Subject: [PATCH 35/93] doc: regenerate the module graph after ui-workspace dropped its locale edge --- docs/module-graph.md | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/docs/module-graph.md b/docs/module-graph.md index 1ff7428fed..61059e96f3 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -295,6 +295,10 @@ flowchart TD pkg_client_ui_slash --> pkg_client_runtime pkg_client_ui_slash --> pkg_client_ui_slots pkg_client_ui_slash --> pkg_invariants + pkg_client_ui_workspace --> pkg_client_runtime + pkg_client_ui_workspace --> pkg_client_ui_primitives + pkg_client_ui_workspace --> pkg_client_ui_slots + pkg_client_ui_workspace --> pkg_invariants pkg_helper --> pkg_brand pkg_helper --> pkg_invariants pkg_helper --> pkg_subprocess @@ -349,11 +353,16 @@ flowchart TD pkg_client_ui_theme --> pkg_client_ui_primitives pkg_client_ui_theme --> pkg_client_ui_slots pkg_client_ui_theme --> pkg_invariants - pkg_client_ui_workspace --> pkg_client_locale - pkg_client_ui_workspace --> pkg_client_runtime - pkg_client_ui_workspace --> pkg_client_ui_primitives - pkg_client_ui_workspace --> pkg_client_ui_slots - pkg_client_ui_workspace --> pkg_invariants + pkg_host_directory_picker_browse --> pkg_client_locale + pkg_host_directory_picker_browse --> pkg_client_runtime + pkg_host_directory_picker_browse --> pkg_client_ui_primitives + pkg_host_directory_picker_browse --> pkg_client_ui_slots + pkg_host_directory_picker_browse --> pkg_client_ui_workspace + pkg_host_directory_picker_browse --> pkg_invariants + pkg_host_directory_picker_native --> pkg_client_runtime + pkg_host_directory_picker_native --> pkg_client_ui_slots + pkg_host_directory_picker_native --> pkg_client_ui_workspace + pkg_host_directory_picker_native --> pkg_invariants pkg_lsp --> pkg_brand pkg_lsp --> pkg_invariants pkg_lsp --> pkg_llm @@ -418,16 +427,6 @@ flowchart TD pkg_code_runtime_worker --> pkg_invariants pkg_code_runtime_worker --> pkg_session pkg_code_runtime_worker --> pkg_timeout - pkg_host_directory_picker_browse --> pkg_client_locale - pkg_host_directory_picker_browse --> pkg_client_runtime - pkg_host_directory_picker_browse --> pkg_client_ui_primitives - pkg_host_directory_picker_browse --> pkg_client_ui_slots - pkg_host_directory_picker_browse --> pkg_client_ui_workspace - pkg_host_directory_picker_browse --> pkg_invariants - pkg_host_directory_picker_native --> pkg_client_runtime - pkg_host_directory_picker_native --> pkg_client_ui_slots - pkg_host_directory_picker_native --> pkg_client_ui_workspace - pkg_host_directory_picker_native --> pkg_invariants pkg_lsp_local --> pkg_brand pkg_lsp_local --> pkg_invariants pkg_lsp_local --> pkg_llm @@ -963,6 +962,7 @@ flowchart TD | [`client-ui-settings`](../packages/client/ui-settings) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-sidebar`](../packages/client/ui-sidebar) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-slash`](../packages/client/ui-slash) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | +| [`client-ui-workspace`](../packages/client/ui-workspace) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`helper`](../packages/sdk/helper) | `sdk` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`subprocess`](../packages/subprocess/subprocess) | | [`telemetry`](../packages/sdk/telemetry) | `sdk` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`paths`](../packages/util/paths) | | [`storage-domain`](../packages/storage/storage-domain) | `storage` | [`invariants`](../packages/support/invariants), [`storage`](../packages/storage/storage) | @@ -979,7 +979,8 @@ flowchart TD | [`client-ui-skill`](../packages/client/ui-skill) | `client` | [`client-connection`](../packages/client/connection), [`client-runtime`](../packages/client/runtime), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-subagent`](../packages/client/ui-subagent) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-theme`](../packages/client/ui-theme) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | -| [`client-ui-workspace`](../packages/client/ui-workspace) | `client` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | +| [`host-directory-picker-browse`](../packages/host/directory-picker-browse) | `host` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-workspace`](../packages/client/ui-workspace), [`invariants`](../packages/support/invariants) | +| [`host-directory-picker-native`](../packages/host/directory-picker-native) | `host` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-workspace`](../packages/client/ui-workspace), [`invariants`](../packages/support/invariants) | | [`lsp`](../packages/lsp/lsp) | `lsp` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm) | | [`sandbox`](../packages/sandbox/sandbox) | `sandbox` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm) | | [`token-meter`](../packages/llm/token-meter) | `llm` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session) | @@ -999,8 +1000,6 @@ flowchart TD | [`client-ui-command`](../packages/client/ui-command) | `client` | [`client-connection`](../packages/client/connection), [`client-runtime`](../packages/client/runtime), [`client-ui-conversation`](../packages/client/ui-conversation), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slash`](../packages/client/ui-slash), [`client-ui-slots`](../packages/client/ui-slots), [`invariants`](../packages/support/invariants) | | [`client-ui-layout`](../packages/client/ui-layout) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-theme`](../packages/client/ui-theme), [`invariants`](../packages/support/invariants) | | [`code-runtime-worker`](../packages/code-runtime/code-runtime-worker) | `code-runtime` | [`code-runtime`](../packages/code-runtime/code-runtime), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`timeout`](../packages/util/timeout) | -| [`host-directory-picker-browse`](../packages/host/directory-picker-browse) | `host` | [`client-locale`](../packages/client/locale), [`client-runtime`](../packages/client/runtime), [`client-ui-primitives`](../packages/client/ui-primitives), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-workspace`](../packages/client/ui-workspace), [`invariants`](../packages/support/invariants) | -| [`host-directory-picker-native`](../packages/host/directory-picker-native) | `host` | [`client-runtime`](../packages/client/runtime), [`client-ui-slots`](../packages/client/ui-slots), [`client-ui-workspace`](../packages/client/ui-workspace), [`invariants`](../packages/support/invariants) | | [`lsp-local`](../packages/lsp/lsp-local) | `lsp` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`lsp`](../packages/lsp/lsp), [`subprocess`](../packages/subprocess/subprocess), [`timeout`](../packages/util/timeout) | | [`sandbox-local`](../packages/sandbox/sandbox-local) | `sandbox` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`sandbox`](../packages/sandbox/sandbox) | | [`sandbox-policy`](../packages/sandbox/sandbox-policy) | `sandbox` | [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`session`](../packages/core/session) | From c0e7c008cfea8316c2f9b0ec7272f4e849cee5eb Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Tue, 28 Jul 2026 22:59:12 +0800 Subject: [PATCH 36/93] feat(web): sandboxed executor family on the web roster MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit apps/cli/cordis.yml swaps bash-local/fs-local for the acp-agent composition (sandbox-local + sandbox-policy + bash-sandbox + user-approval + permission + fs-sandbox; fs-policy composes on top unchanged). The deployment default stays danger-full-access + never — byte-for-byte the old unconfined behavior, so the replay e2e lane and demos are unaffected — while DSH_PERMISSION_MODE opts a process into a confined default and the /permission command switches per session. The permission preset table ships the three product presets (read-only/ask, workspace-write/ask, danger-full-access/never) explicitly in the deployment config. --- apps/cli/cordis.yml | 49 ++++++++++++++++++++++++++++++++++++++----- apps/cli/package.json | 8 +++++-- pnpm-lock.yaml | 22 ++++++++++++++----- 3 files changed, 67 insertions(+), 12 deletions(-) diff --git a/apps/cli/cordis.yml b/apps/cli/cordis.yml index 0dbd6c839e..5d7e5188ea 100644 --- a/apps/cli/cordis.yml +++ b/apps/cli/cordis.yml @@ -120,8 +120,45 @@ - id: subprocess name: '@deepseek-ai/dsh-subprocess-local' -- id: bash-local - name: '@deepseek-ai/dsh-bash-local' +# The sandboxed product path (the acp-agent composition): per-platform +# runner provider, the shared policy home, the confined bash executor, and +# the approval seam its escalation asks through. The web deployment default +# is danger-full-access + never (same behavior as the former bash-local +# rows); DSH_PERMISSION_MODE opts a process into a confined default, and +# per-session switches ride the /permission command's knob events. +- id: sandbox + name: '@deepseek-ai/dsh-sandbox-local' + +- id: sandbox-policy + name: '@deepseek-ai/dsh-sandbox-policy' + config: + mode: !!js process.env.DSH_PERMISSION_MODE ?? 'danger-full-access' + workspaceRoot: !!js process.cwd() + +- id: bash-sandbox + name: '@deepseek-ai/dsh-bash-sandbox' + +- id: approval + name: '@deepseek-ai/dsh-user-approval' + config: + policy: !!js "(process.env.DSH_PERMISSION_MODE ?? 'danger-full-access') === 'danger-full-access' ? 'never' : 'ask'" + +# Presets over the two knobs (requires the confining executor + approval): +# the web permission chip's table, served through the permissions projection +# and switched through /permission. +- id: permission + name: '@deepseek-ai/dsh-permission' + config: + presets: + read-only: + sandbox: read-only + approval: ask + workspace-write: + sandbox: workspace-write + approval: ask + danger-full-access: + sandbox: danger-full-access + approval: never - id: tool-bash name: '@deepseek-ai/dsh-tool-bash' @@ -133,9 +170,11 @@ name: '@deepseek-ai/dsh-tool-tasks' # fs cwd stays the package default (process.cwd()) — the same value the -# gateway injects into session.cwd, so paths and sessions agree. -- id: fs-local - name: '@deepseek-ai/dsh-fs-local' +# gateway injects into session.cwd, so paths and sessions agree. The +# sandboxed backend rides the SAME policy as bash: write/edit fence by the +# effective mode, so read/write/edit stay available under every mode. +- id: fs-sandbox + name: '@deepseek-ai/dsh-fs-sandbox' - id: fs-policy name: '@deepseek-ai/dsh-fs-policy' diff --git a/apps/cli/package.json b/apps/cli/package.json index 7d984ee1b1..0555262e90 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -20,7 +20,7 @@ "@deepseek-ai/dsh-agent": "workspace:^", "@deepseek-ai/dsh-agent-loop": "workspace:^", "@deepseek-ai/dsh-app-boot": "workspace:^", - "@deepseek-ai/dsh-bash-local": "workspace:^", + "@deepseek-ai/dsh-bash-sandbox": "workspace:^", "@deepseek-ai/dsh-client-connection": "workspace:^", "@deepseek-ai/dsh-client-hmr": "workspace:^", "@deepseek-ai/dsh-client-locale": "workspace:^", @@ -45,15 +45,18 @@ "@deepseek-ai/dsh-commands": "workspace:^", "@deepseek-ai/dsh-compact-basic": "workspace:^", "@deepseek-ai/dsh-frontend": "workspace:^", - "@deepseek-ai/dsh-fs-local": "workspace:^", "@deepseek-ai/dsh-fs-policy": "workspace:^", + "@deepseek-ai/dsh-fs-sandbox": "workspace:^", "@deepseek-ai/dsh-host-apiproxy": "workspace:^", "@deepseek-ai/dsh-host-webserver": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-llm-deepseek": "workspace:^", "@deepseek-ai/dsh-llm-retry": "workspace:^", "@deepseek-ai/dsh-paths": "workspace:^", + "@deepseek-ai/dsh-permission": "workspace:^", "@deepseek-ai/dsh-plan-mode": "workspace:^", + "@deepseek-ai/dsh-sandbox-local": "workspace:^", + "@deepseek-ai/dsh-sandbox-policy": "workspace:^", "@deepseek-ai/dsh-session": "workspace:^", "@deepseek-ai/dsh-session-persistence-jsonl": "workspace:^", "@deepseek-ai/dsh-session-projection": "workspace:^", @@ -84,6 +87,7 @@ "@deepseek-ai/dsh-tool-workflow": "workspace:^", "@deepseek-ai/dsh-tools": "workspace:^", "@deepseek-ai/dsh-tui": "workspace:^", + "@deepseek-ai/dsh-user-approval": "workspace:^", "@deepseek-ai/dsh-user-interaction": "workspace:^", "@deepseek-ai/dsh-workflow-workerthread": "workspace:^", "@deepseek-ai/dsh-workspace": "workspace:^", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 5834d885fe..f95d050030 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -128,9 +128,9 @@ importers: '@deepseek-ai/dsh-app-boot': specifier: workspace:^ version: link:../../packages/ui/app-boot - '@deepseek-ai/dsh-bash-local': + '@deepseek-ai/dsh-bash-sandbox': specifier: workspace:^ - version: link:../../packages/bash/bash-local + version: link:../../packages/bash/bash-sandbox '@deepseek-ai/dsh-client-connection': specifier: workspace:^ version: link:../../packages/client/connection @@ -203,12 +203,12 @@ importers: '@deepseek-ai/dsh-frontend': specifier: workspace:^ version: link:../web - '@deepseek-ai/dsh-fs-local': - specifier: workspace:^ - version: link:../../packages/fs/fs-local '@deepseek-ai/dsh-fs-policy': specifier: workspace:^ version: link:../../packages/fs/fs-policy + '@deepseek-ai/dsh-fs-sandbox': + specifier: workspace:^ + version: link:../../packages/fs/fs-sandbox '@deepseek-ai/dsh-host-apiproxy': specifier: workspace:^ version: link:../../packages/host/apiproxy @@ -227,9 +227,18 @@ importers: '@deepseek-ai/dsh-paths': specifier: workspace:^ version: link:../../packages/util/paths + '@deepseek-ai/dsh-permission': + specifier: workspace:^ + version: link:../../packages/ui/permission '@deepseek-ai/dsh-plan-mode': specifier: workspace:^ version: link:../../packages/plan/plan-mode + '@deepseek-ai/dsh-sandbox-local': + specifier: workspace:^ + version: link:../../packages/sandbox/sandbox-local + '@deepseek-ai/dsh-sandbox-policy': + specifier: workspace:^ + version: link:../../packages/sandbox/sandbox-policy '@deepseek-ai/dsh-session': specifier: workspace:^ version: link:../../packages/core/session @@ -320,6 +329,9 @@ importers: '@deepseek-ai/dsh-tui': specifier: workspace:^ version: link:../../packages/ui/tui + '@deepseek-ai/dsh-user-approval': + specifier: workspace:^ + version: link:../../packages/ui/user-approval '@deepseek-ai/dsh-user-interaction': specifier: workspace:^ version: link:../../packages/ui/user-interaction From 0d9ac53fb04eca7b829aa3c54d04fd86f29d6e36 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 23:04:33 +0800 Subject: [PATCH 37/93] test(web): give the browse-dialog snapshot finds the lane's standard 10s timeout CI's cold jsdom needs more than findByRole's 1s default between opening the dialog and the fixture listing's first paint; the surrounding helpers already wait 10s. --- apps/web/tests/workspace-flow.snapshot.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/apps/web/tests/workspace-flow.snapshot.ts b/apps/web/tests/workspace-flow.snapshot.ts index d7cb66e0af..e6efbd75ea 100644 --- a/apps/web/tests/workspace-flow.snapshot.ts +++ b/apps/web/tests/workspace-flow.snapshot.ts @@ -196,9 +196,9 @@ it('adopts a directory through the composed in-app browse flow and lands in its fireEvent.click(within(menu).getByRole('menuitem', { name: 'Open local folder…' })) // The browse occupant renders the Select Workspace Directory dialog at the // fixture home; select Documents, advance into project, and adopt it. - const dialog = await screen.findByRole('dialog', { name: '选择工作区目录' }) - fireEvent.click(await within(dialog).findByRole('listitem', { name: /Documents/ })) - fireEvent.click(await within(dialog).findByRole('listitem', { name: /^project/ })) + const dialog = await screen.findByRole('dialog', { name: '选择工作区目录' }, { timeout: 10_000 }) + fireEvent.click(await within(dialog).findByRole('listitem', { name: /Documents/ }, { timeout: 10_000 })) + fireEvent.click(await within(dialog).findByRole('listitem', { name: /^project/ }, { timeout: 10_000 })) fireEvent.click(within(dialog).getByRole('button', { name: '打开' })) await findHeroComposer() await waitFor(() => { From 6cd63f741c07e8804dde2f5fc322d6ed55522ec4 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Tue, 28 Jul 2026 23:21:27 +0800 Subject: [PATCH 38/93] =?UTF-8?q?fix(host):=20address=20review=20=E2=80=94?= =?UTF-8?q?=20Escape=20scoping,=20relist=20gating,=20crumb=20overflow,=20a?= =?UTF-8?q?ria=20golden?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Escape (and the mask) now reaches only the topmost dialog: while the nested New-folder dialog is up the browser ignores its own Modal close, and the nested dialog's in-flight fence keeps both open during creation. - New folder disables while any listing loads, so a slow post-create relist/select sequence cannot host a second create against a target the pending listing is about to change. - Deep ancestry scrolls inside a dedicated crumb trail whose tail is pinned into view; the path-edit zone keeps its reserved width instead of being clipped by the card, preserving cross-drive path entry. - The workspace-management e2e records a directory-browser aria golden at a staged tree (host HOME pointed at the scaffold cwd collapses ancestry into the Home crumb, keeping the artifact machine-independent), and the keyless snapshot's row targeting goes through visible label text — listitem accessible-name computation differs across dom-accessibility-api environments (the CI-only miss). --- .../directory-browser.expected.md | 20 +++++++ apps/web/tests/workspace-flow.snapshot.ts | 7 ++- apps/web/tests/workspace-management.e2e.ts | 40 +++++++++++-- .../src/client/DirectoryBrowser.module.css | 14 ++++- .../src/client/DirectoryBrowser.tsx | 47 +++++++++------ .../tests/directory-browser.spec.tsx | 59 ++++++++++++++++++- 6 files changed, 161 insertions(+), 26 deletions(-) create mode 100644 apps/web/tests/snapshots/workspace-management/directory-browser.expected.md diff --git a/apps/web/tests/snapshots/workspace-management/directory-browser.expected.md b/apps/web/tests/snapshots/workspace-management/directory-browser.expected.md new file mode 100644 index 0000000000..e394b2cdb6 --- /dev/null +++ b/apps/web/tests/snapshots/workspace-management/directory-browser.expected.md @@ -0,0 +1,20 @@ +- dialog "选择工作区目录": + - heading "选择工作区目录" [level=2] + - button "主目录" + - img + - button "browse-golden" + - button "编辑路径" + - list: + - listitem: + - img + - text: alpha + - img + - listitem: + - img + - text: beta + - img + - button "新建文件夹": + - img + - text: 新建文件夹 + - button "取消" + - button "打开" diff --git a/apps/web/tests/workspace-flow.snapshot.ts b/apps/web/tests/workspace-flow.snapshot.ts index e6efbd75ea..8d3316ab0a 100644 --- a/apps/web/tests/workspace-flow.snapshot.ts +++ b/apps/web/tests/workspace-flow.snapshot.ts @@ -197,8 +197,11 @@ it('adopts a directory through the composed in-app browse flow and lands in its // The browse occupant renders the Select Workspace Directory dialog at the // fixture home; select Documents, advance into project, and adopt it. const dialog = await screen.findByRole('dialog', { name: '选择工作区目录' }, { timeout: 10_000 }) - fireEvent.click(await within(dialog).findByRole('listitem', { name: /Documents/ }, { timeout: 10_000 })) - fireEvent.click(await within(dialog).findByRole('listitem', { name: /^project/ }, { timeout: 10_000 })) + // Row targeting goes through the visible label text: listitem accessible-name + // computation differs across dom-accessibility-api environments, while the + // row's name span is stable (clicks bubble to the row button). + fireEvent.click(await within(dialog).findByText('Documents', {}, { timeout: 10_000 })) + fireEvent.click(await within(dialog).findByText('project', {}, { timeout: 10_000 })) fireEvent.click(within(dialog).getByRole('button', { name: '打开' })) await findHeroComposer() await waitFor(() => { diff --git a/apps/web/tests/workspace-management.e2e.ts b/apps/web/tests/workspace-management.e2e.ts index 674969debe..a034140bf2 100644 --- a/apps/web/tests/workspace-management.e2e.ts +++ b/apps/web/tests/workspace-management.e2e.ts @@ -13,8 +13,8 @@ import { chromium } from 'playwright' import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest' import { SessionId } from '@deepseek-ai/dsh-session' import { - acknowledgeReloadConnectionLoss, assertFixtureInventory, launchWebScaffold, seedSession, watchConsole, - webSnapshotMode, type WebScaffold, + acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden, + launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold, } from './scaffold.ts' import { saveFailureShot } from './support.ts' @@ -23,6 +23,7 @@ const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/workspace-management', i // spec needs any one cold session row, not new recorded content. const SEED = fileURLToPath(new URL('./snapshots/seeded-history/seed.jsonl', import.meta.url)) const MODE = webSnapshotMode() +const BROWSER_EXPECTED = join(SNAPSHOT_DIR, 'directory-browser.expected.md') const SEED_ID = 'workspace-management-web-e2e' describe('web e2e: workspace management (create / rename / flat view / hover card)', () => { @@ -345,6 +346,35 @@ describe('web e2e: workspace management (create / rename / flat view / hover car expect(tripwire.pageErrors).toEqual([]) }, 90_000) + it('matches the directory-browser dialog aria golden at a staged directory', async () => { + // A staged subtree under the scaffold cwd keeps the listing deterministic + // (normalizeAria scrubs the cwd), and pointing the in-process host's HOME + // at the cwd collapses the breadcrumb ancestry into the Home crumb — no + // machine-specific path segments or real $HOME contents enter the golden. + const staged = join(scaffold.workspaceCwd, 'browse-golden') + await mkdir(join(staged, 'alpha'), { recursive: true }) + await mkdir(join(staged, 'beta'), { recursive: true }) + const realHome = process.env.HOME + process.env.HOME = scaffold.workspaceCwd + try { + await page.getByRole('button', { name: 'Create workspace' }).click() + await page.getByRole('menuitem', { name: 'Open local folder…' }).click() + const dialog = page.getByRole('dialog', { name: '选择工作区目录' }) + await dialog.waitFor({ timeout: 10_000 }) + await dialog.getByRole('button', { name: '编辑路径' }).click() + await dialog.getByLabel('编辑路径').fill(staged) + await dialog.getByLabel('编辑路径').press('Enter') + await expect.poll(() => dialog.getByText('alpha', { exact: true }).count(), { timeout: 10_000 }).toBe(1) + const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd) + await compareOrRefreshGolden(BROWSER_EXPECTED, snapshot, MODE) + await dialog.getByRole('button', { name: '取消' }).click() + await dialog.waitFor({ state: 'hidden', timeout: 10_000 }) + } finally { + process.env.HOME = realHome + } + expect(tripwire.pageErrors).toEqual([]) + }, 60_000) + it('shows the session hover card after a dwell on the row', async () => { onTestFailed(() => saveFailureShot(page, 'web-e2e-ws-hover')) // Expand Ungrouped to reveal the seeded session row, then dwell on it @@ -376,8 +406,8 @@ describe('web e2e: workspace management (create / rename / flat view / hover car it.skipIf(MODE === 'record')('issued zero model calls and stayed clean', async () => { expect(tripwire.warnings).toEqual([]) - // This spec mints no fixture directory contents of its own; the seed it - // reuses is owned (and inventory-guarded) by seeded-history. - await assertFixtureInventory(SNAPSHOT_DIR, ['.gitkeep']) + // The directory-browser aria golden is this spec's one owned artifact; + // the seed it reuses is owned (and inventory-guarded) by seeded-history. + await assertFixtureInventory(SNAPSHOT_DIR, ['.gitkeep', 'directory-browser.expected.md']) }) }) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css index f59a74aa7e..ad2107f54f 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css @@ -39,6 +39,18 @@ 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. */ +.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; @@ -74,7 +86,7 @@ /* The empty remainder of the bar: invisible, but a real click target that * flips the bar into path-edit mode. */ .crumbEditZone { - flex: 1 1 0; + flex: 1 0 34px; min-width: 34px; align-self: stretch; border: none; diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 49cbff9fb3..a3bbc576a7 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -112,6 +112,9 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, const [creatingFolder, setCreatingFolder] = useState(false) const [createError, setCreateError] = useState(null) const requestSeq = 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(null) /** Replace the whole view with one freshly listed level (no selection). */ const navigate = useCallback((path?: string) => { @@ -213,16 +216,24 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, } // After the hooks: a closed dialog renders nothing and evaluates no copy. - if (!open) return null - 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]) + + if (!open) return null const twoPane = selected !== null return ( { if (folderDraft === null) onClose() }} title={t('browser.title')} className={clsx(css.dialog)} headless @@ -233,19 +244,21 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, {pathDraft === null ? ( <> - {crumbs.map((crumb, index) => ( - - {index > 0 && } - - - ))} + + {crumbs.map((crumb, index) => ( + + {index > 0 && } + + + ))} + {/* The empty zone right of the crumbs is the path-edit affordance. */} - + + // The wrapper carries the list semantics; the row keeps its NATIVE + // button role so assistive technology exposes an actionable control. + + + ) })}
@@ -260,7 +262,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, {pathDraft === null ? ( <> - + {crumbs.map((crumb, index) => ( {index > 0 && } @@ -292,7 +294,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, value={pathDraft} aria-label={t('browser.editPath')} autoFocus - disabled={busy} + disabled={parentInert} onChange={(event) => { setPathDraft(event.target.value) }} onKeyDown={(event) => { if (event.key === 'Enter') { diff --git a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx index 5b656496d8..4022d12754 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -83,6 +83,11 @@ 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('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() @@ -98,39 +103,39 @@ describe('DirectoryBrowser', () => { 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(screen.getByRole('listitem')) + 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(selectedRow.getAttribute('aria-current')).toBe('true') + expect(rowButton(selectedRow).getAttribute('aria-current')).toBe('true') expect(within(preview!).getByRole('listitem').textContent).toBe('harness') expect(b.listDirectory).toHaveBeenLastCalledWith(DOCS) - expect(screen.getByRole('button', { name: 'Documents' })).toBeTruthy() + 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(screen.getByRole('listitem')) + fireEvent.click(rowButton(screen.getByRole('listitem'))) await waitFor(() => { expect(columns()).toHaveLength(2) }) - fireEvent.click(within(columns()[1]!).getByRole('listitem')) + 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(selectedRow.getAttribute('aria-current')).toBe('true') + expect(rowButton(selectedRow).getAttribute('aria-current')).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(screen.getByRole('listitem')) + 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(screen.getByRole('listitem').getAttribute('aria-current')).toBeNull() + expect(rowButton(screen.getByRole('listitem')).getAttribute('aria-current')).toBeNull() }) it('opens the selection, else the listed level; Cancel closes; busy freezes Open', async () => { @@ -138,7 +143,7 @@ describe('DirectoryBrowser', () => { await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) fireEvent.click(screen.getByRole('button', { name: 'browser.open' })) expect(b.onOpen).toHaveBeenCalledWith(HOME) - fireEvent.click(screen.getByRole('listitem')) + 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) @@ -282,8 +287,8 @@ describe('DirectoryBrowser', () => { expect(cancels.map(button => button.disabled).sort()).toEqual([false, true]) expect(screen.getByRole('button', { name: 'browser.open' }).disabled).toBe(true) expect(screen.getByRole('button', { name: 'browser.editPath' }).disabled).toBe(true) - for (const row of screen.getAllByRole('listitem')) { - expect(row.disabled).toBe(true) + for (const row of screen.getAllByRole('listitem')) { + expect(rowButton(row).disabled).toBe(true) } }) @@ -326,7 +331,7 @@ describe('DirectoryBrowser', () => { 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(screen.getByRole('listitem')) + 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). @@ -352,10 +357,10 @@ describe('DirectoryBrowser', () => { await waitFor(() => { expect(b.createDirectory).toHaveBeenCalledWith(DOCS, 'fresh') }) // The create target became the level and the new folder its selection. await waitFor(() => { - expect(screen.getByRole('button', { name: 'Documents' })).toBeTruthy() + 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' && row.getAttribute('aria-current') === 'true')).toBe(true) + expect(rows.some(row => row.textContent === 'fresh' && rowButton(row).getAttribute('aria-current') === 'true')).toBe(true) }) }) @@ -394,9 +399,9 @@ describe('DirectoryBrowser', () => { await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) b.listDirectory.mockRejectedValueOnce( new DirectoryBrowseError({ code: 'directory-unreadable', message: 'denied', details: { path: DOCS } })) - fireEvent.click(screen.getByRole('listitem')) + fireEvent.click(rowButton(screen.getByRole('listitem'))) await waitFor(() => { expect(screen.getByRole('alert').textContent).toBe('denied') }) - expect(screen.getByRole('listitem').getAttribute('aria-current')).toBe('true') + expect(rowButton(screen.getByRole('listitem')).getAttribute('aria-current')).toBe('true') // No preview column arrived for the failed selection. expect(columns()).toHaveLength(1) }) @@ -419,7 +424,7 @@ describe('DirectoryBrowser', () => { let resolveSlow!: (value: DirectoryListing) => void const slow = new Promise((settle) => { resolveSlow = settle }) b.listDirectory.mockReturnValueOnce(slow) - fireEvent.click(screen.getByRole('listitem')) + 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) }) @@ -435,7 +440,7 @@ describe('DirectoryBrowser', () => { let rejectSlow!: (reason: unknown) => void const slow = new Promise((_settle, fail) => { rejectSlow = fail }) b.listDirectory.mockReturnValueOnce(slow) - fireEvent.click(screen.getByRole('listitem')) + 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')) @@ -447,14 +452,14 @@ describe('DirectoryBrowser', () => { 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(screen.getByRole('listitem')) + fireEvent.click(rowButton(screen.getByRole('listitem'))) await waitFor(() => { expect(columns()).toHaveLength(2) }) let rejectSlow!: (reason: unknown) => void const slow = new Promise((_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(screen.getByRole('button', { name: 'Documents' })) + 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)) @@ -464,13 +469,13 @@ describe('DirectoryBrowser', () => { 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(screen.getByRole('listitem')) + fireEvent.click(rowButton(screen.getByRole('listitem'))) await waitFor(() => { expect(columns()).toHaveLength(2) }) let resolveSlow!: (value: DirectoryListing) => void const slow = new Promise((settle) => { resolveSlow = settle }) b.listDirectory.mockReturnValueOnce(slow) fireEvent.click(screen.getByRole('button', { name: 'browser.home' })) - fireEvent.click(screen.getByRole('button', { name: 'Documents' })) + 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)) @@ -510,7 +515,7 @@ describe('DirectoryBrowser', () => { it('starts back at home on reopen', async () => { const b = mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) - fireEvent.click(screen.getByRole('listitem')) + fireEvent.click(rowButton(screen.getByRole('listitem'))) await waitFor(() => { expect(columns()).toHaveLength(2) }) b.view.rerender() b.view.rerender() From db0292ffdb0d10e3c144d5f67a70c7661286cb6c Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Tue, 28 Jul 2026 23:55:00 +0800 Subject: [PATCH 42/93] docs: regenerate catalogs and sync bilingual READMEs for the permission surfaces gen-cordis-catalog/api, config/persistence catalogs, module graph, and doc graphs pick up the ui-permission package, the permissions projection key, and the /permission command; KnobState and PermissionSelect join the type-link exemptions (owned by the permission package's own docs), and ui-permission joins the sentence Model Experience allowlist (indirect via the host command). The ui-conversation and dsh-permission READMEs gain their zh halves for the approval/chip and projection/command paragraphs; all three touched pairs re-record. --- docs/config-catalog.md | 5 +++-- docs/cordis-catalog/services.md | 10 +++++++++- docs/event-producer-consumer.md | 6 +++--- docs/module-graph.md | 11 ++++++++++- docs/persistence-catalog.md | 8 ++++---- packages/client/ui-conversation/README.i18n.yaml | 4 ++-- packages/client/ui-conversation/README.md | 2 +- packages/client/ui-conversation/README.zh.md | 4 +++- packages/client/ui-permission/README.i18n.yaml | 4 ++-- packages/cordis/tool-cordis/src/api-catalog.ts | 12 ++++++++++++ packages/ui/permission/README.i18n.yaml | 6 +++--- packages/ui/permission/README.zh.md | 3 ++- scripts/gen-cordis-catalog.ts | 2 ++ scripts/verify-package-readme-model-experience.ts | 1 + 14 files changed, 57 insertions(+), 21 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index a611cd8439..8e3c23b6f1 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -832,7 +832,7 @@ export interface PresetSpec { Depends on: [`ApprovalPolicy`](core-data-structures/approval.md) · [`SandboxMode`](core-data-structures/sandbox.md) -Source: [`packages/ui/permission/src/index.ts:83`](../packages/ui/permission/src/index.ts) +Source: [`packages/ui/permission/src/index.ts:130`](../packages/ui/permission/src/index.ts) ## `@deepseek-ai/dsh-plan-mode` @@ -1971,7 +1971,7 @@ export interface Config { export type ApprovalPolicy = 'ask' | 'never' ``` -Source: [`packages/ui/user-approval/src/index.ts:183`](../packages/ui/user-approval/src/index.ts) +Source: [`packages/ui/user-approval/src/index.ts:198`](../packages/ui/user-approval/src/index.ts) ## `@deepseek-ai/dsh-web` @@ -2154,6 +2154,7 @@ These load from a `cordis.yml` entry with no `config:` block; they declare no co - `@deepseek-ai/dsh-client-ui-layout` ([`packages/client/ui-layout/src/index.ts`](../packages/client/ui-layout/src/index.ts)) - `@deepseek-ai/dsh-client-ui-model` ([`packages/client/ui-model/src/index.ts`](../packages/client/ui-model/src/index.ts)) - `@deepseek-ai/dsh-client-ui-models` ([`packages/client/ui-models/src/index.ts`](../packages/client/ui-models/src/index.ts)) +- `@deepseek-ai/dsh-client-ui-permission` ([`packages/client/ui-permission/src/index.ts`](../packages/client/ui-permission/src/index.ts)) - `@deepseek-ai/dsh-client-ui-question` — requires `tools` · `userInteraction` ([`packages/client/ui-question/src/index.ts`](../packages/client/ui-question/src/index.ts)) - `@deepseek-ai/dsh-client-ui-settings` ([`packages/client/ui-settings/src/index.ts`](../packages/client/ui-settings/src/index.ts)) - `@deepseek-ai/dsh-client-ui-settings-general` ([`packages/client/ui-settings-general/src/index.ts`](../packages/client/ui-settings-general/src/index.ts)) diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index ac556aaf08..2197f2d0ad 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -815,6 +815,14 @@ Owns the deployment's permission presets and their write path. Requires a confin */ current(events: readonly SessionEvent[]): string +/** + * Build the whole select value for one folded knob state: every table + * option in declaration order, `custom` appended exactly while derived. + * @param state - the folded knob overrides. + * @returns the `permissions` projection payload. + */ +selectFor(state: KnobState): PermissionSelect + /** * Resolve a preset's knob bundle. * @param name - the preset name to resolve. @@ -843,7 +851,7 @@ set(session: Session, name: string): void Types: [Session](../core-data-structures/session.md) · [SessionEvent](../core-data-structures/core.md) -Source: [`packages/ui/permission/src/index.ts:97`](../../packages/ui/permission/src/index.ts) +Source: [`packages/ui/permission/src/index.ts:144`](../../packages/ui/permission/src/index.ts) ## `ctx.planMode` — `PlanModeService` diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index dabfeb2517..0124aebea6 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -23,7 +23,7 @@ This matrix shows which packages dispatch each harness-owned event and which pac | `agent/status` | `emit` | [`packages/core/agent/src/types.ts:236`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`emitAgentEvent`) | [`agent`](../packages/core/agent), `apiproxy`, [`goal-session`](../packages/goal/goal-session), [`tui`](../packages/ui/tui) | | `agent/step` | `serial` | [`packages/core/agent/src/types.ts:326`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`compact-basic`](../packages/compact/compact-basic), [`plan-mode`](../packages/plan/plan-mode), [`session-checkpoint-policy`](../packages/session-persistence/session-checkpoint-policy), [`time-context`](../packages/context/time-context), [`tool-skill`](../packages/skill/tool-skill), [`user-approval`](../packages/ui/user-approval), [`workspace-context`](../packages/context/workspace-context) | | `agent/turn-stopping` | `serial` | [`packages/core/agent/src/types.ts:373`](../packages/core/agent/src/types.ts) | [`agent-loop`](../packages/core/agent-loop) (`serial`) | [`hooks-claude`](../packages/hooks/hooks-claude), [`hooks-codex`](../packages/hooks/hooks-codex) | -| `approval/request` | `waterfall` | [`packages/ui/user-approval/src/index.ts:30`](../packages/ui/user-approval/src/index.ts) | [`user-approval`](../packages/ui/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp) | +| `approval/request` | `waterfall` | [`packages/ui/user-approval/src/index.ts:30`](../packages/ui/user-approval/src/index.ts) | [`user-approval`](../packages/ui/user-approval) (`waterfall`) | [`acp`](../packages/acp/acp), `apiproxy` | | `commands/change` | `emit` | [`packages/ui/commands/src/index.ts:154`](../packages/ui/commands/src/index.ts) | [`commands`](../packages/ui/commands) (`events.dispatch`) | `apiproxy`, [`tui`](../packages/ui/tui) | | `domain/changed` | `emit` | [`packages/storage/storage-domain/src/events.ts:46`](../packages/storage/storage-domain/src/events.ts) | [`storage-domain`](../packages/storage/storage-domain) (`emit`) | `apiproxy`, [`storage-domain`](../packages/storage/storage-domain), [`workspace`](../packages/workspace/workspace) | | `fs/edit-intent` | `waterfall` | [`packages/fs/fs/src/index.ts:62`](../packages/fs/fs/src/index.ts) | [`tool-fs`](../packages/fs/tool-fs) (`waterfall`) | [`fs-policy`](../packages/fs/fs-policy) | @@ -63,8 +63,8 @@ This matrix shows which packages dispatch each harness-owned event and which pac | Event string | Dispatchers | Listeners | | --- | --- | --- | -| `commands/changed` | `runtime` (`emit`) | - | -| `connection/reset` | `runtime` (`emit`) | - | +| `commands/changed` | `runtime` (`emit`) | `ui-command` | +| `connection/reset` | `runtime` (`emit`) | `ui-command` | | `internal/dispatch` | - | [`commands`](../packages/ui/commands), [`compact`](../packages/compact/compact), [`fs`](../packages/fs/fs), [`goal`](../packages/goal/goal), [`goal-session`](../packages/goal/goal-session), [`hook-protocol`](../packages/hooks/hook-protocol), [`llm-retry`](../packages/llm/llm-retry), [`permission`](../packages/ui/permission), [`plan-mode`](../packages/plan/plan-mode), [`pty-local`](../packages/pty/pty-local), `runtime`, [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`scope`](../packages/core/scope), [`session`](../packages/core/session), [`subagent`](../packages/subagent/subagent), [`time-context`](../packages/context/time-context), [`tool-todo`](../packages/todo/tool-todo), [`tools`](../packages/core/tools), [`user-approval`](../packages/ui/user-approval), [`workflow`](../packages/workflow/workflow) | | `internal/plugin` | - | `hmr`, `modules`, `webserver` | | `internal/status` | - | [`agent`](../packages/core/agent) | diff --git a/docs/module-graph.md b/docs/module-graph.md index 729745f7ad..95138f6142 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -146,6 +146,7 @@ flowchart TD pkg_client_ui_layout["client-ui-layout"] pkg_client_ui_model["client-ui-model"] pkg_client_ui_models["client-ui-models"] + pkg_client_ui_permission["client-ui-permission"] pkg_client_ui_primitives["client-ui-primitives"] pkg_client_ui_question["client-ui-question"] pkg_client_ui_settings["client-ui-settings"] @@ -562,10 +563,12 @@ flowchart TD pkg_acp --> pkg_session pkg_acp --> pkg_user_approval pkg_permission --> pkg_bash + pkg_permission --> pkg_commands pkg_permission --> pkg_invariants pkg_permission --> pkg_sandbox pkg_permission --> pkg_sandbox_policy pkg_permission --> pkg_session + pkg_permission --> pkg_session_projection pkg_permission --> pkg_user_approval pkg_pty_local --> pkg_agent pkg_pty_local --> pkg_invariants @@ -712,6 +715,11 @@ flowchart TD pkg_tool_ask_user --> pkg_invariants pkg_tool_ask_user --> pkg_tools pkg_tool_ask_user --> pkg_user_interaction + pkg_client_ui_permission --> pkg_client_runtime + pkg_client_ui_permission --> pkg_client_ui_command + pkg_client_ui_permission --> pkg_client_ui_slash + pkg_client_ui_permission --> pkg_invariants + pkg_client_ui_permission --> pkg_permission pkg_session_reference --> pkg_agent pkg_session_reference --> pkg_compact pkg_session_reference --> pkg_invariants @@ -1015,7 +1023,7 @@ flowchart TD | [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session-persistence/session-persistence), [`session-title`](../packages/session-title/session-title) | | [`session-title-llm`](../packages/session-title/session-title-llm) | `session-title` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`timeout`](../packages/util/timeout) | | [`acp`](../packages/acp/acp) | `acp` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`session`](../packages/core/session), [`user-approval`](../packages/ui/user-approval) | -| [`permission`](../packages/ui/permission) | `ui` | [`bash`](../packages/bash/bash), [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`user-approval`](../packages/ui/user-approval) | +| [`permission`](../packages/ui/permission) | `ui` | [`bash`](../packages/bash/bash), [`commands`](../packages/ui/commands), [`invariants`](../packages/support/invariants), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session-projection/session-projection), [`user-approval`](../packages/ui/user-approval) | | [`pty-local`](../packages/pty/pty-local) | `pty` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`pty`](../packages/pty/pty), [`sandbox`](../packages/sandbox/sandbox), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess) | | [`tasks-local`](../packages/tasks/tasks-local) | `tasks` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`tasks`](../packages/tasks/tasks), [`timeout`](../packages/util/timeout) | | [`session-telemetry-otel`](../packages/telemetry/session-telemetry-otel) | `telemetry` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-telemetry`](../packages/telemetry/session-telemetry) | @@ -1040,6 +1048,7 @@ flowchart TD | [`session-title-first-message-llm`](../packages/session-title/session-title-first-message-llm) | `session-title` | [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-title`](../packages/session-title/session-title), [`session-title-llm`](../packages/session-title/session-title-llm) | | [`agent-loop-testkit`](../packages/support/agent-loop-testkit) | `support` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`tool-ask-user`](../packages/ui/tool-ask-user) | `ui` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`tools`](../packages/core/tools), [`user-interaction`](../packages/ui/user-interaction) | +| [`client-ui-permission`](../packages/client/ui-permission) | `client` | [`client-runtime`](../packages/client/runtime), [`client-ui-command`](../packages/client/ui-command), [`client-ui-slash`](../packages/client/ui-slash), [`invariants`](../packages/support/invariants), [`permission`](../packages/ui/permission) | | [`session-reference`](../packages/context/session-reference) | `context` | [`agent`](../packages/core/agent), [`compact`](../packages/compact/compact), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`retention`](../packages/util/retention), [`session`](../packages/core/session), [`session-query`](../packages/session-query/session-query) | | [`workspace-context`](../packages/context/workspace-context) | `context` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`invariants`](../packages/support/invariants), [`llm`](../packages/llm/llm), [`paths`](../packages/util/paths), [`session`](../packages/core/session), [`tools`](../packages/core/tools) | | [`repeat-tool-guard`](../packages/guard/repeat-tool-guard) | `guard` | [`agent`](../packages/core/agent), [`invariants`](../packages/support/invariants), [`tools`](../packages/core/tools) | diff --git a/docs/persistence-catalog.md b/docs/persistence-catalog.md index 4f839e60f9..3c157fae97 100644 --- a/docs/persistence-catalog.md +++ b/docs/persistence-catalog.md @@ -105,7 +105,7 @@ Sources: [`packages/core/session/src/types.ts:256`](../packages/core/session/src Types: [CallId](core-data-structures/core.md) -Source: [`packages/ui/user-approval/src/index.ts:45`](../packages/ui/user-approval/src/index.ts) +Source: [`packages/ui/user-approval/src/index.ts:44`](../packages/ui/user-approval/src/index.ts) #### `approval/decided` — log-only @@ -121,7 +121,7 @@ Source: [`packages/ui/user-approval/src/index.ts:45`](../packages/ui/user-approv } ``` -Source: [`packages/ui/user-approval/src/index.ts:56`](../packages/ui/user-approval/src/index.ts) +Source: [`packages/ui/user-approval/src/index.ts:55`](../packages/ui/user-approval/src/index.ts) #### `approval/policy` — log-only @@ -137,7 +137,7 @@ Source: [`packages/ui/user-approval/src/index.ts:56`](../packages/ui/user-approv 'approval/policy': { policy: ApprovalPolicy } ``` -Source: [`packages/ui/user-approval/src/index.ts:68`](../packages/ui/user-approval/src/index.ts) +Source: [`packages/ui/user-approval/src/index.ts:67`](../packages/ui/user-approval/src/index.ts) ### `assistant/*` @@ -342,7 +342,7 @@ Source: [`packages/llm/llm-retry/src/index.ts:18`](../packages/llm/llm-retry/src 'permission/preset': { preset: string } ``` -Source: [`packages/ui/permission/src/index.ts:36`](../packages/ui/permission/src/index.ts) +Source: [`packages/ui/permission/src/index.ts:49`](../packages/ui/permission/src/index.ts) ### `plan/*` diff --git a/packages/client/ui-conversation/README.i18n.yaml b/packages/client/ui-conversation/README.i18n.yaml index 4d5a458d7d..b5761466eb 100644 --- a/packages/client/ui-conversation/README.i18n.yaml +++ b/packages/client/ui-conversation/README.i18n.yaml @@ -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/client/ui-conversation/README.md -README.md: 51ddecf93240c2196483d3fb2bcfaca4104da31a -README.zh.md: d98cbcc69b875d2f426d9bdd9f2fa81874ec614a +README.md: 9f96883ad34d52e75211b9bea16f7273ded370ae +README.zh.md: ee766a23378a7ff21ceae4015addc19900c7c2b9 diff --git a/packages/client/ui-conversation/README.md b/packages/client/ui-conversation/README.md index 0f86b6241e..9f96883ad3 100644 --- a/packages/client/ui-conversation/README.md +++ b/packages/client/ui-conversation/README.md @@ -8,7 +8,7 @@ The resident conversation shell survives no-session and session transitions. Wit The view ring IS a slot: the conversation registration declares the `'conversation.view'` list slot (session scope) in its `children` table, ConversationRoot renders the active entry through its renderSlot share (`only: `), and view tabs project from the ring ledger's registration options (`id`/`order`/`label`). The chat view is this package's own ring entry; other plugins (ui-trajectory) contribute tabs through plain `ctx.slots.register` — the former package-local view registry (`registerView`/`ViewEntry`/`ConversationViewMap` and the chrome attachment table) is retired, with per-view chrome dissolved into the view components themselves. -Approvals take over the composer through the chain this package declares: `ApprovalPanel` registers as a selector-routed `'conversation.composer'` entry (the ui-question pattern) and occupies the composer in place of the InputBar while an approval wait is pending (amber strip, justification headline, paired command line from the running call's args, one-shot refuse/allow). The `PendingApproval` domain face in `contract/slots.ts` owns the wire encoding — the `ApprovalResponsePayload` value with the audit correlation — over the runtime's `PendingWait` carrier; the broadcast `approval/resolved` frame settles the wait and restores the composer. The sidebar mirrors the blocked state through the manager-tracked `waitingApproval` list bit (lit for uninstantiated sessions too), which outranks the running ring until the question resolves. Question placeholders remain in the message flow as display-only PendingCards while ui-question owns the answering takeover. +Approvals take over the composer through the chain this package declares: `ApprovalPanel` registers as a selector-routed `'conversation.composer'` entry (the ui-question pattern) and occupies the composer in place of the InputBar while an approval wait is pending (amber strip, justification headline, paired command line from the running call's args, one-shot refuse/allow). The `PendingApproval` domain face in `contract/slots.ts` owns the wire encoding — the `ApprovalResponsePayload` value with the audit correlation — over the runtime's `PendingWait` carrier; the broadcast `approval/resolved` frame settles the wait and restores the composer. The sidebar mirrors the blocked state through the manager-tracked `waitingApproval` list bit (lit for uninstantiated sessions too), which outranks the running ring until the question resolves. Question placeholders remain in the message flow as display-only PendingCards while ui-question owns the answering takeover. The composer's bottom-row Access seat mounts `PermissionSelect`, fed by the host-computed `permissions` projection through the standard-kit `useProjection` (key absence hides the chip); a pick submits the `/permission ` command line through the bar's injected `command` callback. Generic tool rows classify the built-in bash, read, search, write, edit, and run_code names into dedicated visual variants. The filesystem variants render the edit icon and a path summary; that path is a hover-underline link that opens the file with the host OS default application (`host.openPath`, relative paths resolve against the session cwd). Tool rows are not whole-row click targets and do not open the details panel. The code variant summarizes with the model-authored `description` and expands to the program itself; its logged sub-dispatches render as always-visible nested rows through the SAME keyed toolview hole (custom registrations and the GenericToolCard fallback apply to sub-rows unchanged). Cordis lifecycle tools reuse those generic variants while presenting `Inspect`, `Mount temporary Plugin`, and `Unmount temporary Plugin` with a shared Cordis accent; mount keeps the code variant's expandable source rendering. diff --git a/packages/client/ui-conversation/README.zh.md b/packages/client/ui-conversation/README.zh.md index d98cbcc69b..ee766a2337 100644 --- a/packages/client/ui-conversation/README.zh.md +++ b/packages/client/ui-conversation/README.zh.md @@ -12,6 +12,8 @@ 工具行同样是 slot:独立工具环(`ToolViewRegistry`/`ctx.toolviews`/outlet)已经退役。聊天配置项声明键控的 `'conversation.chat.toolview'` 空位(Session scope;key 空间在运行时开放);其渲染点逐行通过 `entryKey: toolName` 分发,并以 `GenericToolCard` 作为调用点 `fallback`。owner 载荷是统一的 `ToolRowOwnerProps`(`callId`/`toolName`/`block`/`openFile`),`ToolRowProps` 则预先将其与 Session 标准工具包组合。注册方只是普通插件:`ctx.slots.register({ name: 'conversation.chat.toolview', key: '', inject? }, Row)`,以 `inject: ['slots', 'conversation']` 作为加载顺序 seam(apply 在聊天注册后挂载 ConversationService,因此服务存在即可保证 slot 已声明);Session 区分在组件内部完成(`useSessions` 读取 `parentId`,bash 示例是第三方姿态的范例)。Trajectory/waterfall 工具视图 slot 共享此形状,并随各自的渲染点落地(RendersCheck 会拒绝没有任何渲染方的声明)。 +审批经由本包声明的链接管编辑器:`ApprovalPanel` 注册为按选择器路由的 `'conversation.composer'` 配置项(ui-question 模式),在审批等待未决期间取代 InputBar 占据编辑器(琥珀色条、理由标题、来自运行中调用参数的配对命令行、一次性的拒绝/允许)。`contract/slots.ts` 中的 `PendingApproval` 领域面在运行时 `PendingWait` 载体之上拥有 wire 编码——带审计关联的 `ApprovalResponsePayload` 值;广播的 `approval/resolved` 帧使等待落定并恢复编辑器。侧边栏通过 manager 跟踪的 `waitingApproval` 列表位(未实例化会话同样点亮)镜像该阻塞状态,其优先级高于运行中圆环,直至问题解决。问题占位符仍以只读 PendingCard 形式留在消息流中,应答接管归 ui-question 所有。编辑器底行的 Access 席位挂载 `PermissionSelect`,由 host 计算的 `permissions` 投影经标准工具包 `useProjection` 供数(key 缺席即隐藏 chip);选中会经由输入栏注入的 `command` 回调提交 `/permission ` 命令行。 + todo 两个面就是在该形状上的两个注册项,都是普通注册方插件,`inject: ['slots', 'conversation']`。`TodoRow` 占用 `'conversation.chat.toolview'` 的 `todo_write` key,摘要该次调用「试图写入」的内容(从其 args 解析出 `<已完成>/<总数> 已完成 · <进行中条目>`;模型 JSON 残缺或形状不对时回落到通用摘要;非 ok 执行状态保留通用状态点,使被取消的调用绝不读成一次已完成的更新)。`TodoDock` 以 `order: -1` 占用 `'conversation.input.dock'` 列表 slot(位于队列行之上),是计划条:它经 `useProjection` 读取 host 计算的 `todos` 投影(站立计划:其后没有更晚 `turn/start` 的最近一次 `todo/write`)并渲染 `TodoPanel`,后者接收纯列表,在列表为空时自我隐藏,折叠时收成标题加 `"<已完成>/<总数> tasks · in progress"` 的表头(状态图标为 figma 的勾选/进行中/虚线未开始一组)。选取由 dock 适配器负责,因此面板保持为其 props 的纯函数;站立列表放在此处而非行内,行才能保持单行。输入区 composer 链隐藏的一切(例如 ui-question 对 `conversation.composer` 的接管)也会隐藏整个 dock,包括这条计划条。 逐 Session UI 状态中的选择与活跃视图位于已声明的聊天 store(`stores.ts` `createChatStore`)中;InputHub 拥有输入区状态机,并将草稿镜像到该 store 以便持久化。apply 将同一个 store handle 传给严格限定于会话的子树、聊天视图和详情注册,因此每个会话内共享一个实例,框架拥有其生命周期。组件保持纯粹:框架标准工具包提供 `useSession`/`sessionId`、全局 `useSessions`/`useWorkspaces`,以及输入状态机的 `useInput`/`inputActions`;store 表层与 inject factory 提供其余状态和回调。 @@ -34,5 +36,5 @@ todo 两个面就是在该形状上的两个注册项,都是普通注册方插 - **详情面板是最小形态**:以原始形式显示已选择调用的参数/结果;Input/Output/Metadata 切换、Prev/Next 步进与 See-in-trajectory 深链接暂缓实现。 - **assistant footer 扩展(IconActions 行、逐消息分页)是预留 slot**:设计中已有图稿,尚未实现。 - **others 工具行的闪光图标是手绘近似版本**:无法在本地导出设计字形的矢量几何;等到存在精确导出后再将其提升到 ui-primitives。 -- **审批卡片只是只读占位符**:问题请求通过编辑器链回答(ui-question),Web 侧审批回答属于 P-II 审批项目。 +- **审批面板的「始终允许此类」暂缓**:持久授权需要授权存储设计;今天只能回答允许一次/拒绝。 - **TodoPanel 将过长条目截成单行省略号**:figma 条没有换行或展开入口,完整文本无法在行内读完。 diff --git a/packages/client/ui-permission/README.i18n.yaml b/packages/client/ui-permission/README.i18n.yaml index b817ea593e..0b2d5de3c5 100644 --- a/packages/client/ui-permission/README.i18n.yaml +++ b/packages/client/ui-permission/README.i18n.yaml @@ -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/client/ui-permission/README.md -README.md: '0000000000000000000000000000000000000000' -README.zh.md: '0000000000000000000000000000000000000000' +README.md: 1782f89c0909ea80f8554bb9b271947a39ae7f8f +README.zh.md: 6c750329df5bfb25f738869eeb82ea26fa1b8634 diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index 311f7fc592..a46aef6fb8 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -410,6 +410,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ signature: 'current(events: readonly SessionEvent[]): string', jsDoc: '/**\n * Resolve the preset matching the effective knob values. A still-matching\n * last selection wins shared-bundle ties; otherwise the first table match\n * wins, or {@link CUSTOM_PRESET} when no entry matches.\n * @param events - the session\'s events in log order.\n * @returns the effective preset name, or `custom` when nothing matches.\n */', }, + { + signature: 'selectFor(state: KnobState): PermissionSelect', + jsDoc: '/**\n * Build the whole select value for one folded knob state: every table\n * option in declaration order, `custom` appended exactly while derived.\n * @param state - the folded knob overrides.\n * @returns the `permissions` projection payload.\n */', + }, { signature: 'resolve(name: string): PresetSpec', jsDoc: '/**\n * Resolve a preset\'s knob bundle.\n * @param name - the preset name to resolve.\n * @returns the configured bundle.\n * @throws when `name` is not in the table.\n */', @@ -1767,6 +1771,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'JsonValue', declaration: 'export type JsonValue = null | boolean | number | string | JsonValue[] | {\n [key: string]: JsonValue;\n};', }, + { + name: 'KnobState', + declaration: 'export interface KnobState {\n preset: string | null;\n sandbox: SandboxMode | null;\n approval: ApprovalPolicy | null;\n}', + }, { name: 'KvTable', declaration: 'export interface KvTable {\n get(key: K): V | undefined;\n entries(): IterableIterator<[\n K,\n V\n ]>;\n keys(): IterableIterator;\n readonly size: number;\n put(key: K, value: V): Promise;\n delete(key: K): Promise;\n update(key: K, fn: (current: V) => V): Promise;\n}', @@ -1835,6 +1843,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [ name: 'ObjectJsonSchema', declaration: 'export type ObjectJsonSchema = JsonSchemaNode & {\n type: \'object\';\n};', }, + { + name: 'PermissionSelect', + declaration: 'export interface PermissionSelect {\n options: PresetOption[];\n currentValue: string;\n}', + }, { name: 'PreparedLlmCall', declaration: 'export interface PreparedLlmCall {\n readonly config: LlmCallConfig;\n stream(options: GenerateOptions): AsyncIterable;\n}', diff --git a/packages/ui/permission/README.i18n.yaml b/packages/ui/permission/README.i18n.yaml index c29bf60910..f6f5f49a14 100644 --- a/packages/ui/permission/README.i18n.yaml +++ b/packages/ui/permission/README.i18n.yaml @@ -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: 6a59ad9425bf5bfeb89e9798304a2eb90ee55bfa -README.zh.md: 0e7db1bd41a15ac4be18d33db7b9011a5bc24e7e +# pnpm run verify-translation-pairing --write packages/ui/permission/README.md +README.md: 814085ed6f2c9650854f377e1c97e442fc4211a4 +README.zh.md: 36880d6b8c3f0b39b88db1abb02534f30e3355fa diff --git a/packages/ui/permission/README.zh.md b/packages/ui/permission/README.zh.md index 0e7db1bd41..36880d6b8c 100644 --- a/packages/ui/permission/README.zh.md +++ b/packages/ui/permission/README.zh.md @@ -8,6 +8,8 @@ 该服务要求存在具有约束能力的 `ctx.bash` 执行器和 `ctx.approval`。表中名为 `custom` 的条目会在加载时抛出异常;如果组合在表外指定默认值,则零事件会话会推导出 `custom`。详见[沙箱切换设计](../../../.agents/notes/implemented/feature/2026-07-06-sandbox.md)。 +两个可选子件在同一服务之上交付产品界面:`permissions` 会话投影单元(`src/types.ts` 声明该 key;单元折叠三个全量值旋钮事件,在组合默认值之上视图出 select——表内选项加仅作当前值的 `custom`)与 `/permission` 命令(裸调用报告当前预设与表;预设参数经 `set` 切换)。每个子件仅在其注册表(`ctx.sessionProjections` / `ctx.commands`)被组合时激活。 + ## 模型体验 间接地,通过 `dsh-user-approval` 和 `dsh-tool-bash`:二者会渲染由此服务的调节项事件所选择的审批策略提示词、切换通知和沙箱工具结果;`permission/preset` 本身只写入日志。 @@ -18,7 +20,6 @@ ## 已知限制与延期工作 -- **当前没有已交付的组合挂载此服务**:在 [ACP 变为仅用于自动化](../../../.agents/notes/implemented/simplification/2026-07-23-acp-automation-only-protocol.md)之前,ACP 桥接层是唯一的选择器;preset 表为下一个公开运行时策略切换的交互式入口保留。 - **只组合两个机制调节项**:preset 选择沙箱模式和审批策略;agent(智能体)/profile 选择尚未纳入 `PresetSpec`。 - **`custom` 只能推导得出**:调用方可以从不匹配的调节项组合切换出去,但无法通过此服务选中或持久化一个具名 custom preset。 - **preset 表位于进程级别**:配置在插件生命周期内固定;更改可用 preset 必须重新加载插件。 diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index f35c5b4547..a22a9b1c37 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -249,6 +249,8 @@ const TYPE_LINK_EXEMPTIONS: Readonly> = { InvariantRegistration: 'service-local lifecycle handle is owned by packages/support/invariants/README.md', PresetOption: 'deployment menu metadata is owned by packages/ui/permission/README.md', PresetSpec: 'deployment preset composition is owned by packages/ui/permission/README.md', + KnobState: 'projection unit state shape is owned by packages/ui/permission/README.md', + PermissionSelect: 'permissions projection payload is owned by packages/ui/permission/src/types.ts', PromptAssembly: 'assembly result is owned by packages/core/system-prompt/README.md', ResumeAgentOptions: 'agent resume contract is owned by packages/core/agent/README.md', SessionForkSource: 'service-local fork input is owned by packages/core/session/src/index.ts', diff --git a/scripts/verify-package-readme-model-experience.ts b/scripts/verify-package-readme-model-experience.ts index 55108269a3..8f425312e1 100644 --- a/scripts/verify-package-readme-model-experience.ts +++ b/scripts/verify-package-readme-model-experience.ts @@ -58,6 +58,7 @@ const SENTENCE_MODEL_EXPERIENCE: Readonly> = { 'packages/client/ui-slash': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/ui-command': { kind: 'indirect', reason: 'The dispatch paths trigger the host command.execute RPC; each command handler\'s host package owns any model-visible effect.' }, 'packages/client/ui-model': { kind: 'indirect', reason: 'Selection routes session.selectModel; the host snapshots the target at the next prompt-assembly boundary and owns the model-visible effect.' }, + 'packages/client/ui-permission': { kind: 'indirect', reason: 'The picker submits the host /permission command; the knob events it appends own the model-visible effect through the sandbox/approval consumers.' }, 'packages/client/ui-question': { kind: 'indirect', reason: 'The package mounts dsh-tool-ask-user; that tool owns the model-visible schema and answer rendering.' }, 'packages/client/ui-trajectory': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, 'packages/client/ui-workspace': { kind: 'none', reason: 'Browser-side UI plugin layer; registers no model surface.' }, From 8c0006a8728ab63d6c479dcf25ebbe4b68311de0 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Wed, 29 Jul 2026 00:00:56 +0800 Subject: [PATCH 43/93] style: satisfy lint on the permission-line diff Two overlong lines wrap (fixture permissionSelectOf signature, apply.ts type-import list) and three test-side unnecessary assertions drop (eslint --fix). --- packages/client/connection/src/client/fixture.ts | 4 +++- packages/client/ui-conversation/src/client/apply.ts | 3 ++- .../client/ui-conversation/tests/chat-branch-tails.spec.tsx | 2 +- packages/client/ui-conversation/tests/chat-view.spec.tsx | 2 +- packages/client/ui-conversation/tests/input-bar.spec.tsx | 2 +- 5 files changed, 8 insertions(+), 5 deletions(-) diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 3139cd3770..658c2f9725 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -310,7 +310,9 @@ const PERMISSION_PRESETS: Record { describe('small branch tails', () => { it('PendingCard renders the question count', () => { const view = render( - ['payload'], vi.fn())} />, + , ) expect(view.getByText(/等待回答(1 题)/)).toBeTruthy() }) diff --git a/packages/client/ui-conversation/tests/chat-view.spec.tsx b/packages/client/ui-conversation/tests/chat-view.spec.tsx index 896320d9d2..775fd6a954 100644 --- a/packages/client/ui-conversation/tests/chat-view.spec.tsx +++ b/packages/client/ui-conversation/tests/chat-view.spec.tsx @@ -398,7 +398,7 @@ describe('ChatView', () => { new PendingWait('approval', RpcId('r1'), SID, { approvalId: 'ap1', toolName: 'bash' } as PendingWait<'approval'>['payload'], vi.fn()), new PendingWait('question', RpcId('r2'), SID, - { questions: [{ id: 'q1', question: '选择' }] } as PendingWait<'question'>['payload'], vi.fn()), + { questions: [{ id: 'q1', question: '选择' }] }, vi.fn()), ], }) const view = render() diff --git a/packages/client/ui-conversation/tests/input-bar.spec.tsx b/packages/client/ui-conversation/tests/input-bar.spec.tsx index 0aea847bfe..3e7077ca0b 100644 --- a/packages/client/ui-conversation/tests/input-bar.spec.tsx +++ b/packages/client/ui-conversation/tests/input-bar.spec.tsx @@ -89,7 +89,7 @@ function bench(over?: BenchOptions) { items: [], state: 'idle', phase: 'ready', error: null, baselinesReady: true, recentWorkspaceId: undefined, })), - useProjection: ((key: string) => (key === 'permissions' ? over?.permissions : undefined)) as InputBarProps['useProjection'], + useProjection: ((key: string) => (key === 'permissions' ? over?.permissions : undefined)), useInput: bindSnapshotSelector(shell.state), inputActions: shell.actions, keyboard: shell, From d2b16380d150a94e029a70b5bcadf47c2d2abbdf Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 00:04:06 +0800 Subject: [PATCH 44/93] fix(host): keep path entry available when the home listing fails With no listed level (an unreadable or missing home directory), the path-edit zone previously disabled forever, stranding the operator on the alert with only Cancel; it now opens with an empty draft so an absolute path remains the way forward. Covered by a recovery test. --- .../src/client/DirectoryBrowser.tsx | 8 +++++--- .../tests/directory-browser.spec.tsx | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 19e7a6f799..5318ad0ea0 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -282,9 +282,11 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, type="button" className={css.crumbEditZone} aria-label={t('browser.editPath')} - disabled={parent === null || parentInert} - /* v8 ignore next -- narrowing guard: the zone disables while the level is null. */ - onClick={() => { if (parent !== null) setPathDraft(selected?.path ?? parent.path) }} + // 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={() => { setPathDraft(selected?.path ?? parent?.path ?? '') }} /> ) diff --git a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx index 4022d12754..daf795ddbf 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -269,6 +269,21 @@ describe('DirectoryBrowser', () => { expect(screen.getByRole('button', { name: 'browser.newFolder' }).disabled).toBe(false) }) + it('keeps path entry available when the home listing fails', async () => { + const listDirectory = vi.fn(async (): Promise => { + 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('ignores dismissal while adoption is busy', async () => { const b = mount({ busy: true }) await waitFor(() => { expect(screen.getByRole('dialog')).toBeTruthy() }) From 728d28e7e4787c987dd45e2701e77b109829ea88 Mon Sep 17 00:00:00 2001 From: imccyu <276526105+imccyu@users.noreply.github.com> Date: Wed, 29 Jul 2026 00:06:19 +0800 Subject: [PATCH 45/93] test: close the coverage gaps on the permission line MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two real branches gain assertions (effectivePermissionPreset's backward scan over non-preset events; the popup options() throw when the projection vanished between availability and open — a sync throw, not a rejection). The empty ui-permission node half joins the ui-model entry on the client-lane coverage debt list (same pure-UI plugin shape, same TODO). --- packages/client/ui-permission/tests/browser-plugin.spec.ts | 3 +++ packages/ui/permission/tests/permission.spec.ts | 3 +++ vitest.config.ts | 1 + 3 files changed, 7 insertions(+) diff --git a/packages/client/ui-permission/tests/browser-plugin.spec.ts b/packages/client/ui-permission/tests/browser-plugin.spec.ts index 33fc94b3a0..b0beb2b9b9 100644 --- a/packages/client/ui-permission/tests/browser-plugin.spec.ts +++ b/packages/client/ui-permission/tests/browser-plugin.spec.ts @@ -81,6 +81,9 @@ describe('ui-permission browser plugin', () => { const again = await c.ui.options(proj, new AbortController().signal) expect(again.find(option => option.id === 'workspace-write')?.active).toBe(true) expect(again.find(option => option.id === 'read-only')?.detail).toBe('Reads only.') + // A projection that vanished between availability and open throws. + expect(() => c.ui.options({ sessionId: sid('ghost') }, new AbortController().signal)) + .toThrow(/not available on this host/) }) it('a pick submits the /permission line; rejection and unmatched throw', async () => { diff --git a/packages/ui/permission/tests/permission.spec.ts b/packages/ui/permission/tests/permission.spec.ts index 864f25629d..05a747de8d 100644 --- a/packages/ui/permission/tests/permission.spec.ts +++ b/packages/ui/permission/tests/permission.spec.ts @@ -34,6 +34,9 @@ describe('effectivePermissionPreset', () => { session.append('permission/preset', { preset: 'danger-full-access' }) session.append('permission/preset', { preset: 'workspace-write' }) expect(effectivePermissionPreset(session.events)).toBe('workspace-write') + // The backward scan steps over non-preset events to the latest selection. + session.append('sandbox/mode', { mode: 'read-only' }) + expect(effectivePermissionPreset(session.events)).toBe('workspace-write') }) }) diff --git a/vitest.config.ts b/vitest.config.ts index 16f28449a5..55f172416f 100644 --- a/vitest.config.ts +++ b/vitest.config.ts @@ -138,6 +138,7 @@ export default defineConfig({ 'packages/client/ui-command/src/client/service.ts', 'packages/client/ui-command/src/client/PopupSelectView.tsx', 'packages/client/ui-model/src/index.ts', + 'packages/client/ui-permission/src/index.ts', 'packages/client/ui-model/src/client/ModelSelect.tsx', 'packages/client/ui-model/src/client/directory.ts', 'packages/client/ui-model/src/client/index.ts', From f8cd2bf749561ba6ac317652c2d9611055dca207 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 00:15:30 +0800 Subject: [PATCH 46/93] =?UTF-8?q?fix(host):=20review=20round=205=20?= =?UTF-8?q?=E2=80=94=20draft-pending=20action=20gating,=20in-flow=20errors?= =?UTF-8?q?,=20IME=20guards?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Open and New folder disable while a path draft is uncommitted: targetPath still names the previous selection/listing, and committing against it while a different path shows in the header adopts the wrong directory. - The Miller columns keep their own row so a status/error line renders below them inside the card instead of competing as a third flex item the dialog clips off-screen. - Both text inputs (path editor, folder name) carry the IME composition guard the workspace-name inputs already had: a composing Enter confirms the candidate, never submits. --- .../src/client/DirectoryBrowser.module.css | 13 +++- .../src/client/DirectoryBrowser.tsx | 59 +++++++++++-------- .../tests/directory-browser.spec.tsx | 53 +++++++++++++++++ 3 files changed, 100 insertions(+), 25 deletions(-) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css index d9c72ec55b..47564236fe 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css @@ -41,6 +41,16 @@ /* 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. */ +.millerRow { + display: flex; + align-items: stretch; + flex: 1 1 0; + min-height: 0; + gap: 20px; +} + .crumbTrail { display: flex; align-items: center; @@ -113,10 +123,9 @@ * the hairline divider centered between them; each column scrolls alone. */ .content { display: flex; - align-items: stretch; + flex-direction: column; flex: 1 1 0; min-height: 0; - gap: 20px; padding: 16px 24px 0; } diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 5318ad0ea0..c809ea43b6 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -120,6 +120,9 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // 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(null) + // IME confirmation (Enter selecting a candidate) must not submit either + // text input; the same guard the workspace-name inputs carry. + const composingRef = useRef(false) /** Replace the whole view with one freshly listed level (no selection). */ const navigate = useCallback((path?: string) => { @@ -242,6 +245,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // 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 ( { setPathDraft(event.target.value) }} + onCompositionStart={() => { composingRef.current = true }} + onCompositionEnd={() => { composingRef.current = false }} onKeyDown={(event) => { - if (event.key === 'Enter') { + if (event.key === 'Enter' && !composingRef.current) { event.preventDefault() const target = pathDraft.trim() if (target !== '') navigate(target) @@ -315,25 +324,27 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen,
- {parent !== null && ( - - )} - {twoPane && } - {twoPane && child !== null && ( - - )} +
+ {parent !== null && ( + + )} + {twoPane && } + {twoPane && child !== null && ( + + )} +
{loading &&
{t('browser.loading')}
} {error !== null &&
{error}
}
@@ -341,7 +352,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, - + {/* Retrying needs an occupant to serve the flow; without one the + * button would open a flow nobody can answer or cancel. */} + )} > diff --git a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx index 18ddd8b1fd..490a86d782 100644 --- a/packages/client/ui-workspace/tests/workspace-picker.spec.tsx +++ b/packages/client/ui-workspace/tests/workspace-picker.spec.tsx @@ -303,6 +303,20 @@ describe('WorkspacePicker', () => { expect(screen.getByRole('menuitem', { name: 'Open local folder…' })).toBeTruthy() }) + it('keeps Choose again inert while the flow occupant is gone, and snaps back a flow opened over an empty hole', async () => { + const b = mount([], vi.fn(async () => { throw new Error('adoption failed') })) + chooseItem('Open local folder…') + await act(async () => { b.probe.owner!.onPicked('/one/project') }) + await waitFor(() => { expect(screen.getByRole('dialog', { name: 'Couldn’t open folder' })).toBeTruthy() }) + // The occupant unloads while the error dialog is up: retrying would open + // a flow nobody can serve or cancel, so the button goes inert. + act(() => { b.occupancy.flip(false) }) + expect(screen.getByRole('button', { name: 'Choose again' }).disabled).toBe(true) + // Cancel stays the way out, and the menu actions are usable again. + fireEvent.click(screen.getByRole('button', { name: 'Cancel' })) + expect(screen.getByRole('menuitem', { name: 'Create a new workspace' }).disabled).toBe(false) + }) + it('withdraws an open flow when its occupant unloads, re-enabling the menu actions', () => { const b = mount([]) chooseItem('Open local folder…') diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index 9588943980..4320c46148 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/directory-picker-browse/README.md -README.md: 2f1994100f0fb8fcadae46094267057b3966197e -README.zh.md: a149133a13ca99f176680c68b4931b9673f4aaa8 +README.md: 155b18eecb46d704dc181e29fdf7eb67fac42839 +README.zh.md: 154eeb571171116ae98e46efe77efd45986f67ea diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index 2f1994100f..155b18eecb 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) The **in-app browsing backend** of the [directory-picker seam](../directory-picker/README.md): `BrowseDirectoryPicker` registers `ctx.directoryPicker` with the `browse` capability — one-level directory listing and child-directory creation over Node's stdlib, which already carries the per-OS adaptation. Nothing renders on the host display, so this backend serves remote clients the native backend cannot. -Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject an explicit path that is not fully qualified — relative forms, and on Windows the rooted drive-less forms (`\foo`, `/foo`) and incomplete UNC prefixes (`\\`, `\\server`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. One `list` call materializes at most `maxEntries` rows (config, default 1000 — the bound GitHub's web UI applies to directory listings): a cut level keeps the name-sorted head, counts hidden rows against the bound, stops probing once the bound is hit, and reports `truncated: true` so the client can say the level is incomplete. Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). +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). Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). ## Model Experience diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index a149133a13..154eeb5711 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -4,7 +4,7 @@ [目录选择 seam](../directory-picker/README.md) 的**应用内浏览后端**:`BrowseDirectoryPicker` 以 `browse` 能力注册 `ctx.directoryPicker`——基于 Node 标准库(跨 OS 适配本就由它承担)提供单层目录列举与子目录创建。宿主屏幕上不渲染任何东西,因此该后端能服务 native 后端无法触及的远程客户端。 -行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo`、`/foo`)与不完整的 UNC 前缀(`\\`、`\\server`)——报 `directory-unreadable`/`directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。单次 `list` 至多物化 `maxEntries` 行(配置项,默认 1000——GitHub 网页端对目录列举采用的同一上限):被截断的层级保留按名排序的头部、隐藏行计入上限、达到上限即停止探测,并报告 `truncated: true`,供客户端提示层级不完整。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 +行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo`、`/foo`)与不完整的 UNC 前缀(`\\`、`\\server`)——报 `directory-unreadable`/`directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。单次 `list` 至多返回 `maxEntries` 行(配置项,默认 1000——GitHub 网页端对目录列举采用的同一上限),且层级以流式方式经过一个有界窗口,无论目录有多少子项内存都保持 O(maxEntries):被截断的层级保留按名排序的头部、隐藏行计入上限、只探测窗口内候选,并报告 `truncated: true`,供客户端提示层级不完整(窗口内的断链符号链接不会从窗口外回填——发生过驱逐本身已把层级标记为截断)。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 ## 模型体验 diff --git a/packages/host/directory-picker-browse/package.json b/packages/host/directory-picker-browse/package.json index c1e8626bed..f83b0fcb86 100644 --- a/packages/host/directory-picker-browse/package.json +++ b/packages/host/directory-picker-browse/package.json @@ -27,7 +27,8 @@ ], "license": "BSD-3-Clause", "dependencies": { - "@deepseek-ai/dsh-host-directory-picker": "workspace:^" + "@deepseek-ai/dsh-host-directory-picker": "workspace:^", + "schemastery": "^3.18.0" }, "peerDependencies": { "@deepseek-ai/dsh-invariants": "^0.0.1", diff --git a/packages/host/directory-picker-browse/src/index.ts b/packages/host/directory-picker-browse/src/index.ts index b9699cd612..20ebef1c62 100644 --- a/packages/host/directory-picker-browse/src/index.ts +++ b/packages/host/directory-picker-browse/src/index.ts @@ -9,7 +9,7 @@ * @module @deepseek-ai/dsh-host-directory-picker-browse */ -import { mkdir, readdir, stat } from 'node:fs/promises' +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' @@ -53,6 +53,35 @@ export function fullyQualified(path: string, platform: NodeJS.Platform = process : 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 { + const at = window.findIndex(existing => candidate.name.localeCompare(existing.name) < 0) + if (at === -1) window.push(candidate) + else window.splice(at, 0, candidate) + if (window.length <= keep) return false + window.pop() + return true +} + /** 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. */ @@ -127,25 +156,32 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { throw new DirectoryPickerError('directory-unreadable', path, `cannot list "${path}": not a fully qualified path`) } const target = resolve(path ?? home) - let names: { name: string; isDirectory: boolean; isSymbolicLink: boolean }[] + // 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 { - const dirents = await readdir(target, { withFileTypes: true }) - names = dirents.map(dirent => ({ - name: dirent.name, - isDirectory: dirent.isDirectory(), - isSymbolicLink: dirent.isSymbolicLink(), - })) + const level = await opendir(target) + for await (const dirent of level) { + // 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 + } } catch (error: unknown) { throw new DirectoryPickerError('directory-unreadable', target, `cannot list ${target}: ${messageOf(error)}`) } - // Sort candidates before probing so the bound keeps the name-sorted head - // of the level and probing (symlink stat) stops with the bound instead of - // touching every child of an oversized directory. - names.sort((a, b) => a.name.localeCompare(b.name)) const entries: DirectoryEntry[] = [] - let truncated = false - for (const entry of names) { - const row = await directoryRow(target, entry.name, entry.isDirectory, entry.isSymbolicLink) + let truncated = evicted + for (const candidate of window) { + const row = await directoryRow(target, candidate.name, candidate.isDirectory, candidate.isSymbolicLink) if (row === null) continue if (entries.length === this.config.maxEntries) { truncated = true diff --git a/packages/host/directory-picker-browse/tests/service.spec.ts b/packages/host/directory-picker-browse/tests/service.spec.ts index 8e7a2ba049..2b01d0d29e 100644 --- a/packages/host/directory-picker-browse/tests/service.spec.ts +++ b/packages/host/directory-picker-browse/tests/service.spec.ts @@ -7,7 +7,8 @@ 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, { fullyQualified } from '../src/index.ts' +import BrowseDirectoryPicker, { boundedInsert, fullyQualified } from '../src/index.ts' +import type { ListingCandidate } from '../src/index.ts' let root: string let capability: DirectoryPickerBrowseCapability @@ -21,6 +22,13 @@ beforeAll(async () => { 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) @@ -63,11 +71,31 @@ describe('BrowseDirectoryPicker', () => { 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('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 beyond the window's tail enters last and leaves immediately. + expect(boundedInsert(window, candidate('t'), 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)! diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2a23066eb1..483167a961 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2795,6 +2795,9 @@ importers: '@deepseek-ai/dsh-host-directory-picker': specifier: workspace:^ version: link:../directory-picker + schemastery: + specifier: ^3.18.0 + version: 3.18.0 devDependencies: '@deepseek-ai/dsh-invariants': specifier: workspace:^ From 7503390590d486590f7dd8008ab7d35c884b50a5 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 04:42:13 +0800 Subject: [PATCH 74/93] fix(host): cancellable listing scans and O(log window) insertion capability.list gains an optional AbortSignal threaded from the RPC carrier's request signal (the pickDirectory pattern): a disconnected or timed-out caller stops the opendir loop instead of the scan outliving its caller, and the abort surfaces as its own reason rather than a directory-unreadable dressing. boundedInsert rejects a full window's at-or-beyond-tail candidate on one comparison and binary-inserts retained candidates, so an oversized level no longer pays a window scan per dirent. --- ...directory-picker-capability-seam.i18n.yaml | 4 +-- ...-07-28-directory-picker-capability-seam.md | 2 +- ...-28-directory-picker-capability-seam.zh.md | 2 +- docs/config-catalog.md | 2 +- docs/cordis-catalog/services.md | 2 +- .../client/connection/src/client/fixture.ts | 2 +- .../cordis/tool-cordis/src/api-catalog.ts | 2 +- packages/host/apiproxy/src/api-proxy.ts | 6 ++-- packages/host/apiproxy/src/api/host.ts | 5 +++- packages/host/apiproxy/src/fetch/handler.ts | 2 +- .../tests/api-proxy-workspace.spec.ts | 8 +++--- .../directory-picker-browse/README.i18n.yaml | 4 +-- .../host/directory-picker-browse/README.md | 2 +- .../host/directory-picker-browse/README.zh.md | 2 +- .../host/directory-picker-browse/src/index.ts | 28 +++++++++++++++---- .../tests/service.spec.ts | 17 ++++++++++- packages/host/directory-picker/src/index.ts | 5 +++- 17 files changed, 68 insertions(+), 27 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml index 52bd6fd263..5696f35720 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml @@ -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 .agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md -2026-07-28-directory-picker-capability-seam.md: 7f78f7db0cca36c5aaeeb4efcab51d826945a4a1 -2026-07-28-directory-picker-capability-seam.zh.md: 31537fe1f21c1acbca73763bdd20e6d5f91a8d5e +2026-07-28-directory-picker-capability-seam.md: 9d885abe394cfd30a174f07f6ac9432b774188b6 +2026-07-28-directory-picker-capability-seam.zh.md: 6dd1b66b508f5f06d6a150b6c45f0da7d36bf2ce diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md index 7f78f7db0c..9d885abe39 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md @@ -20,7 +20,7 @@ Placement and policy rulings folded into this decision: - **Dependency survey (hand-roll vs adopt).** Node's stdlib *is* the maintained cross-platform OS layer (`readdir(withFileTypes)`, `homedir`, path semantics); surveyed alternatives fail the dependency bar — file-manager packages (`node-file-manager`, `files-and-folders`, Syncfusion's provider) are whole HTTP apps (fit), drive-letter helpers (`drivelist` native addon, `windows-drive-letters` ~7y stale) fail health/proportionality. The browse backend is a thin adapter over stdlib. - **Hidden entries: return-and-flag.** The host stamps `hidden` (POSIX dot convention) and returns everything; the client filters. Display policy stays client-side, and the planned show-hidden toggle becomes a client-only change. Windows' `FILE_ATTRIBUTE_HIDDEN` is not exposed by dirents — documented limitation until a native probe pays for itself. - **Symlinks: follow for enterability.** `stat` probes symlinks (broken/cyclic → skipped); crumbs keep the logical path the operator navigated, and `workspace.create` already canonicalizes via realpath at adoption. -- **Listing levels are bounded, and streamed.** One `list` call returns at most `maxEntries` rows (config, default 1000 — GitHub's web-UI directory-listing bound). The level streams via `opendir` into a name-sorted window of `maxEntries + 1` candidates, so memory stays O(maxEntries) and enterability probing touches only windowed candidates; the wire `DirectoryListing` carries a required `truncated` flag so the client states incompleteness instead of silently missing tail entries. A windowed broken symlink is not backfilled from beyond the window — the eviction already marks the level truncated. An unbounded level is a memory/responsiveness hole for large or adversarial directories. +- **Listing levels are bounded, and streamed.** One `list` call returns at most `maxEntries` rows (config, default 1000 — GitHub's web-UI directory-listing bound). The level streams via `opendir` into a name-sorted window of `maxEntries + 1` candidates, so memory stays O(maxEntries) and enterability probing touches only windowed candidates; the wire `DirectoryListing` carries a required `truncated` flag so the client states incompleteness instead of silently missing tail entries. 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 (an oversized level must not pay a window scan per dirent), and `list(path, signal)` threads the carrier's request signal so a scan of a stalled network directory cannot outlive a disconnected caller. An unbounded level is a memory/responsiveness hole for large or adversarial directories. - **Whole-filesystem scope, no roots config.** `workspace.create` accepts arbitrary paths and the API serves bash-driving methods, so a browse root would be UX scoping, not a boundary; configurability without a consumer fails the evidence bar. Deferred until a deployment needs it. - **The native backend stays.** Plugin-form was the point: multiple providers can serve the seam (an Electron shell would provide the `native` interaction through its own dialog API). Kind naming: `dialog` was the first pick and was dropped — the browse interaction also presents a dialog (the in-app modal), so the word failed to discriminate; `native` names where the chooser runs. diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md index 31537fe1f2..6dd1b66b50 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md @@ -20,7 +20,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **依赖调研(手写 vs 引入)。** Node 标准库本身就是维护中的跨平台 OS 层(`readdir(withFileTypes)`、`homedir`、路径语义);调研过的替代品都过不了依赖门槛——文件管理器包(`node-file-manager`、`files-and-folders`、Syncfusion 的 provider)是整套 HTTP 应用(契合度不过),盘符工具(原生插件 `drivelist`、约七年未更的 `windows-drive-letters`)健康度/比例失当。browse 后端是标准库上的薄适配。 - **隐藏条目:返回并打标。** 宿主标注 `hidden`(POSIX 点前缀约定)并返回全部条目;客户端过滤。展示策略留在客户端,计划中的"显示隐藏"开关变成纯客户端改动。Windows 的 `FILE_ATTRIBUTE_HIDDEN` 不被 dirent 暴露——记为限制,直到原生探测值回其成本。 - **符号链接:为可进入性而跟随。** 用 `stat` 探测符号链接(断链/循环→跳过);面包屑保留操作者导航的逻辑路径,`workspace.create` 在接纳时本就做 realpath 规范化。 -- **列举层级有上限,且流式处理。** 单次 `list` 至多返回 `maxEntries` 行(配置项,默认 1000——GitHub 网页端目录列举的同一上限)。层级经 `opendir` 流入一个按名排序、容量 `maxEntries + 1` 的候选窗口,内存保持 O(maxEntries),可进入性探测只触及窗口内候选;线上 `DirectoryListing` 携带必填的 `truncated` 标志,让客户端明示不完整而不是静默缺尾。窗口内的断链符号链接不从窗口外回填——发生过驱逐本身已把层级标记为截断。无上限的层级对超大或恶意构造的目录就是内存/响应性漏洞。 +- **列举层级有上限,且流式处理。** 单次 `list` 至多返回 `maxEntries` 行(配置项,默认 1000——GitHub 网页端目录列举的同一上限)。层级经 `opendir` 流入一个按名排序、容量 `maxEntries + 1` 的候选窗口,内存保持 O(maxEntries),可进入性探测只触及窗口内候选;线上 `DirectoryListing` 携带必填的 `truncated` 标志,让客户端明示不完整而不是静默缺尾。窗口内的断链符号链接不从窗口外回填——发生过驱逐本身已把层级标记为截断。窗口插入为二分查找、满窗尾部单次比较即拒绝(超大层级不能为每个 dirent 付出一次全窗扫描),且 `list(path, signal)` 透传载体的请求信号,滞塞网络目录的扫描不会在调用方断连后继续存活。无上限的层级对超大或恶意构造的目录就是内存/响应性漏洞。 - **全盘可浏览,不做 roots 配置。** `workspace.create` 接受任意路径且 API 本就提供驱动 bash 的方法,浏览根只会是 UX 范围而非边界;没有消费方的可配置性过不了证据门槛。等到有部署需要再做。 - **native 后端保留。** 插件化正是目的:多方都能提供该 seam(Electron 壳可以经自己的对话框 API 提供 `native` 交互)。kind 命名:最初选了 `dialog` 后被放弃——browse 交互同样以对话框呈现(应用内弹窗),这个词起不到判别作用;`native` 命名的是选择器运行的位置。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 8db82e5cc7..3e70c22fbc 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -533,7 +533,7 @@ export interface Config { } ``` -Source: [`packages/host/directory-picker-browse/src/index.ts:114`](../packages/host/directory-picker-browse/src/index.ts) +Source: [`packages/host/directory-picker-browse/src/index.ts:127`](../packages/host/directory-picker-browse/src/index.ts) ## `@deepseek-ai/dsh-host-webserver` diff --git a/docs/cordis-catalog/services.md b/docs/cordis-catalog/services.md index 5c422d6586..314c707f4c 100644 --- a/docs/cordis-catalog/services.md +++ b/docs/cordis-catalog/services.md @@ -500,7 +500,7 @@ Abstract directory-picking service. Subclass, implement `capability()`, and load abstract capability(): DirectoryPickerCapability ``` -Source: [`packages/host/directory-picker/src/index.ts:128`](../../packages/host/directory-picker/src/index.ts) +Source: [`packages/host/directory-picker/src/index.ts:131`](../../packages/host/directory-picker/src/index.ts) ## `ctx.fs` — `FileSystem` (abstract seam) diff --git a/packages/client/connection/src/client/fixture.ts b/packages/client/connection/src/client/fixture.ts index 0a029072d0..a11d8c4157 100644 --- a/packages/client/connection/src/client/fixture.ts +++ b/packages/client/connection/src/client/fixture.ts @@ -1160,7 +1160,7 @@ export class FixtureApiClient extends AbstractApiClient { case 'session.cancel': return this.api.sessions.cancel(request) case 'host.describe': return this.api.host.describe(request) case 'host.pickDirectory': return this.api.host.pickDirectory(request, new AbortController().signal) - case 'host.listDirectory': return this.api.host.listDirectory(request) + case 'host.listDirectory': return this.api.host.listDirectory(request, new AbortController().signal) case 'host.createDirectory': return this.api.host.createDirectory(request) case 'host.openPath': return this.api.host.openPath(request, new AbortController().signal) case 'workspace.list': return this.api.workspace.list(request) diff --git a/packages/cordis/tool-cordis/src/api-catalog.ts b/packages/cordis/tool-cordis/src/api-catalog.ts index 9ca1d81ca9..e8761181ad 100644 --- a/packages/cordis/tool-cordis/src/api-catalog.ts +++ b/packages/cordis/tool-cordis/src/api-catalog.ts @@ -1669,7 +1669,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [ }, { name: 'DirectoryPickerBrowseCapability', - declaration: 'export interface DirectoryPickerBrowseCapability {\n kind: \'browse\';\n list(path?: string): Promise;\n createDirectory(path: string, name: string): Promise;\n}', + declaration: 'export interface DirectoryPickerBrowseCapability {\n kind: \'browse\';\n list(path?: string, signal?: AbortSignal): Promise;\n createDirectory(path: string, name: string): Promise;\n}', }, { name: 'DirectoryPickerCapabilities', diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index 7b7beacec8..d4c4268088 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -1076,7 +1076,7 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro } }, - async listDirectory(request) { + async listDirectory(request, signal) { const capability = ctx.directoryPicker.capability() if (capability.kind !== 'browse') { return err(request, { @@ -1086,7 +1086,9 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro }) } try { - return ok(request, await capability.list(request.payload.path)) + // 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) { return err(request, directoryError(error)) } diff --git a/packages/host/apiproxy/src/api/host.ts b/packages/host/apiproxy/src/api/host.ts index 0338494bed..3d0713e523 100644 --- a/packages/host/apiproxy/src/api/host.ts +++ b/packages/host/apiproxy/src/api/host.ts @@ -62,10 +62,13 @@ export interface HostApi { /** * 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`. + * 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> /** diff --git a/packages/host/apiproxy/src/fetch/handler.ts b/packages/host/apiproxy/src/fetch/handler.ts index 1f9bf3fde7..5398ce4848 100644 --- a/packages/host/apiproxy/src/fetch/handler.ts +++ b/packages/host/apiproxy/src/fetch/handler.ts @@ -64,7 +64,7 @@ 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) => api.host.listDirectory(r) }, + '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) }, diff --git a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts index 9c52b62a61..f04850c34d 100644 --- a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts @@ -172,9 +172,9 @@ const BROWSE_STUB: DirectoryPickerCapability = { 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({})) + 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' })) + 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' } }) @@ -182,7 +182,7 @@ describe('host.listDirectory / host.createDirectory', () => { 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' }))).result).toMatchObject({ + 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({ @@ -195,7 +195,7 @@ describe('host.listDirectory / host.createDirectory', () => { it('refuses the browse RPCs under a native composition', async () => { const { api } = await harness() - expect((await api.host.listDirectory(request({}))).result).toMatchObject({ + 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({ diff --git a/packages/host/directory-picker-browse/README.i18n.yaml b/packages/host/directory-picker-browse/README.i18n.yaml index 4320c46148..96151039b3 100644 --- a/packages/host/directory-picker-browse/README.i18n.yaml +++ b/packages/host/directory-picker-browse/README.i18n.yaml @@ -2,5 +2,5 @@ # side as of the last confirmed-consistent state. Both languages carry equal authority; # after editing either side, bring the other along and re-record with: # pnpm run verify-translation-pairing --write packages/host/directory-picker-browse/README.md -README.md: 155b18eecb46d704dc181e29fdf7eb67fac42839 -README.zh.md: 154eeb571171116ae98e46efe77efd45986f67ea +README.md: 9543fc89f1314d05d02df72e9b5d86af21fdad66 +README.zh.md: dd314c5b5a709b2cf2e6840911fd665ead7d7e87 diff --git a/packages/host/directory-picker-browse/README.md b/packages/host/directory-picker-browse/README.md index 155b18eecb..9543fc89f1 100644 --- a/packages/host/directory-picker-browse/README.md +++ b/packages/host/directory-picker-browse/README.md @@ -4,7 +4,7 @@ English | [中文](README.zh.md) The **in-app browsing backend** of the [directory-picker seam](../directory-picker/README.md): `BrowseDirectoryPicker` registers `ctx.directoryPicker` with the `browse` capability — one-level directory listing and child-directory creation over Node's stdlib, which already carries the per-OS adaptation. Nothing renders on the host display, so this backend serves remote clients the native backend cannot. -Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject an explicit path that is not fully qualified — relative forms, and on Windows the rooted drive-less forms (`\foo`, `/foo`) and incomplete UNC prefixes (`\\`, `\\server`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. 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). Failures throw the seam's typed `DirectoryPickerError`. Policy rationale: [the directory-picker capability seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md). +Behavior facts: listings return **directories only**, name-sorted, with symlinks-to-directories followed (broken/cyclic links skipped — the probe `stat` failing means "not enterable") and a host-owned `hidden` flag (POSIX dot convention) left for the client to act on; `crumbs` is the root-to-target ancestor chain, the root crumb labeled by its full path (`/`, `C:\`); an absent `list` path means the host account's home directory. `createDirectory` is non-recursive (a missing parent is a real failure, not a level to invent) and validates the name as a single non-blank segment even when called directly, mirroring the wire schema's fence. Both primitives reject an explicit path that is not fully qualified — relative forms, and on Windows the rooted drive-less forms (`\foo`, `/foo`) and incomplete UNC prefixes (`\\`, `\\server`) that `isAbsolute` accepts — with `directory-unreadable`/`directory-create-failed`, instead of letting `resolve` rebase it under the host process cwd or current drive. One `list` call 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). ## Model Experience diff --git a/packages/host/directory-picker-browse/README.zh.md b/packages/host/directory-picker-browse/README.zh.md index 154eeb5711..dd314c5b5a 100644 --- a/packages/host/directory-picker-browse/README.zh.md +++ b/packages/host/directory-picker-browse/README.zh.md @@ -4,7 +4,7 @@ [目录选择 seam](../directory-picker/README.md) 的**应用内浏览后端**:`BrowseDirectoryPicker` 以 `browse` 能力注册 `ctx.directoryPicker`——基于 Node 标准库(跨 OS 适配本就由它承担)提供单层目录列举与子目录创建。宿主屏幕上不渲染任何东西,因此该后端能服务 native 后端无法触及的远程客户端。 -行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo`、`/foo`)与不完整的 UNC 前缀(`\\`、`\\server`)——报 `directory-unreadable`/`directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。单次 `list` 至多返回 `maxEntries` 行(配置项,默认 1000——GitHub 网页端对目录列举采用的同一上限),且层级以流式方式经过一个有界窗口,无论目录有多少子项内存都保持 O(maxEntries):被截断的层级保留按名排序的头部、隐藏行计入上限、只探测窗口内候选,并报告 `truncated: true`,供客户端提示层级不完整(窗口内的断链符号链接不会从窗口外回填——发生过驱逐本身已把层级标记为截断)。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 +行为事实:列举**只返回目录**、按名称排序,指向目录的符号链接会被跟随(断链/循环链接被跳过——探测 `stat` 失败即"不可进入"),并携带宿主判定的 `hidden` 标志(POSIX 点前缀约定),展示决策留给客户端;`crumbs` 是从根到目标的祖先链,根 crumb 以完整路径标注(`/`、`C:\`);`list` 不带路径即列举宿主账户的家目录。`createDirectory` 不递归(父目录缺失是真实失败,不是要补造的层级),且即便被直接调用也把名称校验为单个非空段,与协议 schema 的栅栏一致。两个原语都拒绝非完全限定的显式路径——相对形态,以及 Windows 上 `isAbsolute` 会放行的无盘符有根形态(`\foo`、`/foo`)与不完整的 UNC 前缀(`\\`、`\\server`)——报 `directory-unreadable`/`directory-create-failed`,而不是任由 `resolve` 把它重定位到宿主进程 cwd 或当前盘符之下。单次 `list` 至多返回 `maxEntries` 行(配置项,默认 1000——GitHub 网页端对目录列举采用的同一上限),且层级以流式方式经过一个有界窗口,无论目录有多少子项内存都保持 O(maxEntries):被截断的层级保留按名排序的头部、隐藏行计入上限、只探测窗口内候选,并报告 `truncated: true`,供客户端提示层级不完整(窗口内的断链符号链接不会从窗口外回填——发生过驱逐本身已把层级标记为截断);窗口插入为二分查找、满窗尾部单次比较即拒绝,且 `list` 透传调用方的 `AbortSignal`,断连或超时会停止扫描而不是让它在调用方离开后继续。失败抛出 seam 的类型化 `DirectoryPickerError`。策略依据:[目录选择能力 seam Agent Note](../../../.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md)。 ## 模型体验 diff --git a/packages/host/directory-picker-browse/src/index.ts b/packages/host/directory-picker-browse/src/index.ts index 20ebef1c62..be27c5a2d4 100644 --- a/packages/host/directory-picker-browse/src/index.ts +++ b/packages/host/directory-picker-browse/src/index.ts @@ -74,9 +74,22 @@ export interface ListingCandidate { * @returns true when an eviction happened (the level has candidates beyond the window). */ export function boundedInsert(window: ListingCandidate[], candidate: ListingCandidate, keep: number): boolean { - const at = window.findIndex(existing => candidate.name.localeCompare(existing.name) < 0) - if (at === -1) window.push(candidate) - else window.splice(at, 0, candidate) + // 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 @@ -131,7 +144,7 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { private readonly browseCapability: DirectoryPickerCapability = { kind: 'browse', - list: path => this.list(path), + list: (path, signal) => this.list(path, signal), createDirectory: (path, name) => this.createDirectory(path, name), } @@ -147,7 +160,7 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { return this.browseCapability } - private async list(path?: string): Promise { + private async list(path?: string, signal?: AbortSignal): Promise { 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 @@ -169,6 +182,9 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { try { const level = await opendir(target) for await (const dirent of level) { + // A disconnected/timed-out caller stops the scan here; throwing out + // of the loop closes the directory handle via the iterator's return. + signal?.throwIfAborted() // 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 @@ -176,6 +192,8 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { if (boundedInsert(window, candidate, keep)) evicted = true } } 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[] = [] diff --git a/packages/host/directory-picker-browse/tests/service.spec.ts b/packages/host/directory-picker-browse/tests/service.spec.ts index 2b01d0d29e..99366e8754 100644 --- a/packages/host/directory-picker-browse/tests/service.spec.ts +++ b/packages/host/directory-picker-browse/tests/service.spec.ts @@ -83,6 +83,19 @@ describe('BrowseDirectoryPicker', () => { } }) + 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. + await expect(capability.list(root, gone.signal)).rejects.toThrow('caller left') + // A live signal changes nothing about ordinary failures. + const live = new AbortController() + 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('boundedInsert keeps the window name-sorted and bounded, reporting evictions', () => { const candidate = (name: string): ListingCandidate => ({ name, isDirectory: true, isSymbolicLink: false }) const window: ListingCandidate[] = [] @@ -91,9 +104,11 @@ describe('BrowseDirectoryPicker', () => { // 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 beyond the window's tail enters last and leaves immediately. + // 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 () => { diff --git a/packages/host/directory-picker/src/index.ts b/packages/host/directory-picker/src/index.ts index 3b4b60562f..4dba9c9c22 100644 --- a/packages/host/directory-picker/src/index.ts +++ b/packages/host/directory-picker/src/index.ts @@ -65,13 +65,16 @@ export interface DirectoryPickerBrowseCapability { /** * 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): Promise + list(path?: string, signal?: AbortSignal): Promise /** * Create one child directory under an existing parent. * @param path - absolute existing parent directory. From 1a9b84b19e7973fc00db89f5da52dea507d15d12 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 04:46:49 +0800 Subject: [PATCH 75/93] fix(host): restart home on early-edit cancel; clamp the dialog to short viewports Escape canceling a path edit opened before any level listed relaunches the home listing instead of stranding a blank picker (the editor had superseded the initial request while parent was still null). The card's height clamps to the viewport (min(420px, 100dvh - 32px)); header and footer are flex-none and the columns scroll, so Open/Cancel stay reachable on landscape phones and short embedded windows. --- .../client/connection/tests/fixture.spec.ts | 4 ++-- .../src/client/DirectoryBrowser.module.css | 7 +++++-- .../src/client/DirectoryBrowser.tsx | 7 ++++++- .../tests/directory-browser.spec.tsx | 21 +++++++++++++++++++ 4 files changed, 34 insertions(+), 5 deletions(-) diff --git a/packages/client/connection/tests/fixture.spec.ts b/packages/client/connection/tests/fixture.spec.ts index 3c8256ac3e..15fecad404 100644 --- a/packages/client/connection/tests/fixture.spec.ts +++ b/packages/client/connection/tests/fixture.spec.ts @@ -320,13 +320,13 @@ describe('createFixtureApi', () => { const created = await api.host.createDirectory(req({ path: '/', name: 'srv' })) if (!created.result.ok) throw new Error('create failed') expect(created.result.value.path).toBe('/srv') - const listed = await api.host.listDirectory(req({ path: '/srv' })) + const listed = await api.host.listDirectory(req({ path: '/srv' }), new AbortController().signal) if (!listed.result.ok) throw new Error('list failed') expect(listed.result.value.crumbs).toEqual([ { name: '/', path: '/', hidden: false }, { name: 'srv', path: '/srv', hidden: false }, ]) - const root = await api.host.listDirectory(req({ path: '/' })) + const root = await api.host.listDirectory(req({ path: '/' }), new AbortController().signal) if (!root.result.ok) throw new Error('root list failed') expect(root.result.value.entries).toContainEqual({ name: 'srv', path: '/srv', hidden: false }) }) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css index 4e9378290b..82be42efbe 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css @@ -1,12 +1,15 @@ /* Directory-browser dialog (figma 813-23126 family). The shared Modal renders * headless here — mask, card, Escape only — and this module owns the figma - * frame exactly: fixed 600×420 card, header (title + crumbs, l3 separator), + * 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: 420px; + height: min(420px, calc(100dvh - 32px)); padding: 0; gap: 0; } diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index fe8b7ff5c7..1c50eb8167 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -1,6 +1,7 @@ /** * The in-app workspace-directory browser (figma Harness 813-23126 family): a - * fixed 600×420 dialog whose header carries the title, the selection-path + * 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 @@ -364,6 +365,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // 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() } }} /> diff --git a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx index a590bd3b17..5221e627f8 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -177,6 +177,27 @@ describe('DirectoryBrowser', () => { 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(() => {}) + 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('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) + }) + it('surfaces an unreadable target as an alert and keeps the edit open for correction', async () => { mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) From baaa53523542c1f3247e3f8277f0ed57f9bdf20b Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 05:05:36 +0800 Subject: [PATCH 76/93] fix(host): race directory reads against the caller's signal; report aborts as cancelled Every filesystem await in the browse scan (opendir and each read) now races the signal through raceAbort, so a stalled network open/read stops with a departed caller and an already-aborted request rejects even for an empty level; the abandoned settlement is swallowed and an abandoned open that still mints a handle is closed, never leaked. apiproxy maps an aborted listing to the cancelled wire code, matching pickDirectory and command.execute, instead of reporting a false internal failure. The fixture spec call sites gain the wire signal argument the previous commit's static lane flagged. --- docs/config-catalog.md | 2 +- .../client/connection/tests/fixture.spec.ts | 4 +- packages/host/apiproxy/src/api-proxy.ts | 5 ++ .../tests/api-proxy-workspace.spec.ts | 14 ++++ .../host/directory-picker-browse/src/index.ts | 82 ++++++++++++++++--- .../tests/service.spec.ts | 39 ++++++++- 6 files changed, 131 insertions(+), 15 deletions(-) diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 3e70c22fbc..42eb9c2325 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -533,7 +533,7 @@ export interface Config { } ``` -Source: [`packages/host/directory-picker-browse/src/index.ts:127`](../packages/host/directory-picker-browse/src/index.ts) +Source: [`packages/host/directory-picker-browse/src/index.ts:170`](../packages/host/directory-picker-browse/src/index.ts) ## `@deepseek-ai/dsh-host-webserver` diff --git a/packages/client/connection/tests/fixture.spec.ts b/packages/client/connection/tests/fixture.spec.ts index 3c8256ac3e..15fecad404 100644 --- a/packages/client/connection/tests/fixture.spec.ts +++ b/packages/client/connection/tests/fixture.spec.ts @@ -320,13 +320,13 @@ describe('createFixtureApi', () => { const created = await api.host.createDirectory(req({ path: '/', name: 'srv' })) if (!created.result.ok) throw new Error('create failed') expect(created.result.value.path).toBe('/srv') - const listed = await api.host.listDirectory(req({ path: '/srv' })) + const listed = await api.host.listDirectory(req({ path: '/srv' }), new AbortController().signal) if (!listed.result.ok) throw new Error('list failed') expect(listed.result.value.crumbs).toEqual([ { name: '/', path: '/', hidden: false }, { name: 'srv', path: '/srv', hidden: false }, ]) - const root = await api.host.listDirectory(req({ path: '/' })) + const root = await api.host.listDirectory(req({ path: '/' }), new AbortController().signal) if (!root.result.ok) throw new Error('root list failed') expect(root.result.value.entries).toContainEqual({ name: 'srv', path: '/srv', hidden: false }) }) diff --git a/packages/host/apiproxy/src/api-proxy.ts b/packages/host/apiproxy/src/api-proxy.ts index d4c4268088..a2b2a887cd 100644 --- a/packages/host/apiproxy/src/api-proxy.ts +++ b/packages/host/apiproxy/src/api-proxy.ts @@ -1090,6 +1090,11 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro // 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)) } }, diff --git a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts index f04850c34d..3968cba5c7 100644 --- a/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts +++ b/packages/host/apiproxy/tests/api-proxy-workspace.spec.ts @@ -193,6 +193,20 @@ describe('host.listDirectory / host.createDirectory', () => { }) }) + 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({ diff --git a/packages/host/directory-picker-browse/src/index.ts b/packages/host/directory-picker-browse/src/index.ts index be27c5a2d4..dbb3a03a5b 100644 --- a/packages/host/directory-picker-browse/src/index.ts +++ b/packages/host/directory-picker-browse/src/index.ts @@ -95,6 +95,49 @@ export function boundedInsert(window: ListingCandidate[], candidate: ListingCand 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(operation: Promise, signal: AbortSignal | undefined): Promise { + if (signal === undefined) return operation + return new Promise((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)) +} + /** 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. */ @@ -180,16 +223,35 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { const window: ListingCandidate[] = [] let evicted = false try { - const level = await opendir(target) - for await (const dirent of level) { - // A disconnected/timed-out caller stops the scan here; throwing out - // of the loop closes the directory handle via the iterator's return. - signal?.throwIfAborted() - // 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 + // 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.) + void opening.then(async (dir) => { await dir.close() }, () => { + // 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 + // one included (its abandoned read settles against the closed handle + // and raceAbort already swallowed that settlement). + await level.close() } } catch (error: unknown) { // An abort is the caller's own reason, not an unreadable directory. diff --git a/packages/host/directory-picker-browse/tests/service.spec.ts b/packages/host/directory-picker-browse/tests/service.spec.ts index 99366e8754..835948d9fe 100644 --- a/packages/host/directory-picker-browse/tests/service.spec.ts +++ b/packages/host/directory-picker-browse/tests/service.spec.ts @@ -7,7 +7,7 @@ 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 } from '../src/index.ts' +import BrowseDirectoryPicker, { boundedInsert, fullyQualified, raceAbort } from '../src/index.ts' import type { ListingCandidate } from '../src/index.ts' let root: string @@ -86,8 +86,15 @@ describe('BrowseDirectoryPicker', () => { 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. + // 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 changes nothing about ordinary failures. const live = new AbortController() const missing = join(root, 'no-such-dir') @@ -96,6 +103,34 @@ describe('BrowseDirectoryPicker', () => { 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((_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[] = [] From e89ae129d76f59092c1cc25905e658d822f866ac Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 05:16:11 +0800 Subject: [PATCH 77/93] fix(host): wrap the dialog footer on narrow viewports The confirm/cancel pair wraps onto its own row when the viewport-clamped card is too narrow for the whole footer, so Open stays visible instead of clipping past the card's hidden overflow. --- .../src/client/DirectoryBrowser.module.css | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css index 82be42efbe..800af854a1 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.module.css @@ -233,6 +233,9 @@ .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; From 7d07ab0c9dc2983c7476d7648b30289dfaee6a38 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 05:32:12 +0800 Subject: [PATCH 78/93] fix(host): abandon close behind a stalled read; race symlink probes; observe cleanup failures MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The aborted exit no longer awaits close (Node queues it behind any in-flight read, chaining the departed caller back onto the very stall the abort escaped) — the abandoned close's failure is swallowed, it has no consumer. Symlink stat probes race the signal too, with a per-candidate abort check between probes, so a stalled probe target cannot keep a departed request alive. The deferred handle cleanup after a lost opendir race now consumes its own close failure instead of leaking it as an unhandled rejection. --- ...directory-picker-capability-seam.i18n.yaml | 4 +- ...-07-28-directory-picker-capability-seam.md | 2 +- ...-28-directory-picker-capability-seam.zh.md | 2 +- docs/config-catalog.md | 2 +- .../host/directory-picker-browse/src/index.ts | 42 +++++++++++++++---- .../tests/service.spec.ts | 7 +++- 6 files changed, 44 insertions(+), 15 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml index 5696f35720..cd1441f46f 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.i18n.yaml @@ -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 .agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md -2026-07-28-directory-picker-capability-seam.md: 9d885abe394cfd30a174f07f6ac9432b774188b6 -2026-07-28-directory-picker-capability-seam.zh.md: 6dd1b66b508f5f06d6a150b6c45f0da7d36bf2ce +2026-07-28-directory-picker-capability-seam.md: 9f2703b7499870bf2d5ff8735e3c8cb2c351a503 +2026-07-28-directory-picker-capability-seam.zh.md: 946156a5d06cea30c833c768147b36b30f258192 diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md index 9d885abe39..9f2703b749 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.md @@ -20,7 +20,7 @@ Placement and policy rulings folded into this decision: - **Dependency survey (hand-roll vs adopt).** Node's stdlib *is* the maintained cross-platform OS layer (`readdir(withFileTypes)`, `homedir`, path semantics); surveyed alternatives fail the dependency bar — file-manager packages (`node-file-manager`, `files-and-folders`, Syncfusion's provider) are whole HTTP apps (fit), drive-letter helpers (`drivelist` native addon, `windows-drive-letters` ~7y stale) fail health/proportionality. The browse backend is a thin adapter over stdlib. - **Hidden entries: return-and-flag.** The host stamps `hidden` (POSIX dot convention) and returns everything; the client filters. Display policy stays client-side, and the planned show-hidden toggle becomes a client-only change. Windows' `FILE_ATTRIBUTE_HIDDEN` is not exposed by dirents — documented limitation until a native probe pays for itself. - **Symlinks: follow for enterability.** `stat` probes symlinks (broken/cyclic → skipped); crumbs keep the logical path the operator navigated, and `workspace.create` already canonicalizes via realpath at adoption. -- **Listing levels are bounded, and streamed.** One `list` call returns at most `maxEntries` rows (config, default 1000 — GitHub's web-UI directory-listing bound). The level streams via `opendir` into a name-sorted window of `maxEntries + 1` candidates, so memory stays O(maxEntries) and enterability probing touches only windowed candidates; the wire `DirectoryListing` carries a required `truncated` flag so the client states incompleteness instead of silently missing tail entries. 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 (an oversized level must not pay a window scan per dirent), and `list(path, signal)` threads the carrier's request signal so a scan of a stalled network directory cannot outlive a disconnected caller. An unbounded level is a memory/responsiveness hole for large or adversarial directories. +- **Listing levels are bounded, and streamed.** One `list` call returns at most `maxEntries` rows (config, default 1000 — GitHub's web-UI directory-listing bound). The level streams via `opendir` into a name-sorted window of `maxEntries + 1` candidates, so memory stays O(maxEntries) and enterability probing touches only windowed candidates; the wire `DirectoryListing` carries a required `truncated` flag so the client states incompleteness instead of silently missing tail entries. 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 (an oversized level must not pay a window scan per dirent), and `list(path, signal)` threads the carrier's request signal so a scan of a stalled network directory cannot outlive a disconnected caller — every await in the scan (open, each read, each symlink probe) races the signal, an aborted exit abandons rather than awaits the close (Node queues close behind in-flight reads), and abandoned settlements are swallowed so cleanup can never surface as an unhandled rejection. An unbounded level is a memory/responsiveness hole for large or adversarial directories. - **Whole-filesystem scope, no roots config.** `workspace.create` accepts arbitrary paths and the API serves bash-driving methods, so a browse root would be UX scoping, not a boundary; configurability without a consumer fails the evidence bar. Deferred until a deployment needs it. - **The native backend stays.** Plugin-form was the point: multiple providers can serve the seam (an Electron shell would provide the `native` interaction through its own dialog API). Kind naming: `dialog` was the first pick and was dropped — the browse interaction also presents a dialog (the in-app modal), so the word failed to discriminate; `native` names where the chooser runs. diff --git a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md index 6dd1b66b50..946156a5d0 100644 --- a/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md +++ b/.agents/notes/implemented/architecture/2026-07-28-directory-picker-capability-seam.zh.md @@ -20,7 +20,7 @@ web GUI 的"打开本地文件夹"流程被焊死在一种交互上:`host.pick - **依赖调研(手写 vs 引入)。** Node 标准库本身就是维护中的跨平台 OS 层(`readdir(withFileTypes)`、`homedir`、路径语义);调研过的替代品都过不了依赖门槛——文件管理器包(`node-file-manager`、`files-and-folders`、Syncfusion 的 provider)是整套 HTTP 应用(契合度不过),盘符工具(原生插件 `drivelist`、约七年未更的 `windows-drive-letters`)健康度/比例失当。browse 后端是标准库上的薄适配。 - **隐藏条目:返回并打标。** 宿主标注 `hidden`(POSIX 点前缀约定)并返回全部条目;客户端过滤。展示策略留在客户端,计划中的"显示隐藏"开关变成纯客户端改动。Windows 的 `FILE_ATTRIBUTE_HIDDEN` 不被 dirent 暴露——记为限制,直到原生探测值回其成本。 - **符号链接:为可进入性而跟随。** 用 `stat` 探测符号链接(断链/循环→跳过);面包屑保留操作者导航的逻辑路径,`workspace.create` 在接纳时本就做 realpath 规范化。 -- **列举层级有上限,且流式处理。** 单次 `list` 至多返回 `maxEntries` 行(配置项,默认 1000——GitHub 网页端目录列举的同一上限)。层级经 `opendir` 流入一个按名排序、容量 `maxEntries + 1` 的候选窗口,内存保持 O(maxEntries),可进入性探测只触及窗口内候选;线上 `DirectoryListing` 携带必填的 `truncated` 标志,让客户端明示不完整而不是静默缺尾。窗口内的断链符号链接不从窗口外回填——发生过驱逐本身已把层级标记为截断。窗口插入为二分查找、满窗尾部单次比较即拒绝(超大层级不能为每个 dirent 付出一次全窗扫描),且 `list(path, signal)` 透传载体的请求信号,滞塞网络目录的扫描不会在调用方断连后继续存活。无上限的层级对超大或恶意构造的目录就是内存/响应性漏洞。 +- **列举层级有上限,且流式处理。** 单次 `list` 至多返回 `maxEntries` 行(配置项,默认 1000——GitHub 网页端目录列举的同一上限)。层级经 `opendir` 流入一个按名排序、容量 `maxEntries + 1` 的候选窗口,内存保持 O(maxEntries),可进入性探测只触及窗口内候选;线上 `DirectoryListing` 携带必填的 `truncated` 标志,让客户端明示不完整而不是静默缺尾。窗口内的断链符号链接不从窗口外回填——发生过驱逐本身已把层级标记为截断。窗口插入为二分查找、满窗尾部单次比较即拒绝(超大层级不能为每个 dirent 付出一次全窗扫描),且 `list(path, signal)` 透传载体的请求信号,滞塞网络目录的扫描不会在调用方断连后继续存活——扫描中的每个 await(打开、每次读取、每次符号链接探测)都与信号赛跑,中止路径放弃而非等待 close(Node 会把 close 排在在飞读取之后),被放弃的 settlement 全部吞掉,清理不会以未处理拒绝的形式冒出。无上限的层级对超大或恶意构造的目录就是内存/响应性漏洞。 - **全盘可浏览,不做 roots 配置。** `workspace.create` 接受任意路径且 API 本就提供驱动 bash 的方法,浏览根只会是 UX 范围而非边界;没有消费方的可配置性过不了证据门槛。等到有部署需要再做。 - **native 后端保留。** 插件化正是目的:多方都能提供该 seam(Electron 壳可以经自己的对话框 API 提供 `native` 交互)。kind 命名:最初选了 `dialog` 后被放弃——browse 交互同样以对话框呈现(应用内弹窗),这个词起不到判别作用;`native` 命名的是选择器运行的位置。 diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 42eb9c2325..075597d502 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -533,7 +533,7 @@ export interface Config { } ``` -Source: [`packages/host/directory-picker-browse/src/index.ts:170`](../packages/host/directory-picker-browse/src/index.ts) +Source: [`packages/host/directory-picker-browse/src/index.ts:181`](../packages/host/directory-picker-browse/src/index.ts) ## `@deepseek-ai/dsh-host-webserver` diff --git a/packages/host/directory-picker-browse/src/index.ts b/packages/host/directory-picker-browse/src/index.ts index dbb3a03a5b..6fa157ea87 100644 --- a/packages/host/directory-picker-browse/src/index.ts +++ b/packages/host/directory-picker-browse/src/index.ts @@ -138,6 +138,11 @@ 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. */ @@ -149,13 +154,19 @@ function messageOf(error: unknown): string { * 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): Promise { +async function directoryRow( + parent: string, name: string, isDirectory: boolean, isSymbolicLink: boolean, signal: AbortSignal | undefined, +): Promise { const path = join(parent, name) let enterable = isDirectory if (!enterable && isSymbolicLink) { try { - enterable = (await stat(path)).isDirectory() + // 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 } @@ -231,8 +242,10 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { 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.) - void opening.then(async (dir) => { await dir.close() }, () => { + // 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 @@ -248,10 +261,18 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { if (boundedInsert(window, candidate, keep)) evicted = true } } finally { - // Manual read() never auto-closes; close on every exit, the aborted - // one included (its abandoned read settles against the closed handle - // and raceAbort already swallowed that settlement). - await level.close() + // 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. @@ -261,7 +282,10 @@ export default class BrowseDirectoryPicker extends DirectoryPicker { const entries: DirectoryEntry[] = [] let truncated = evicted for (const candidate of window) { - const row = await directoryRow(target, candidate.name, candidate.isDirectory, candidate.isSymbolicLink) + // 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 diff --git a/packages/host/directory-picker-browse/tests/service.spec.ts b/packages/host/directory-picker-browse/tests/service.spec.ts index 835948d9fe..002d42e516 100644 --- a/packages/host/directory-picker-browse/tests/service.spec.ts +++ b/packages/host/directory-picker-browse/tests/service.spec.ts @@ -95,8 +95,13 @@ describe('BrowseDirectoryPicker', () => { // 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 changes nothing about ordinary failures. + // 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) From 723bb9057cb840378e099a459796b210cf35996c Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 05:49:18 +0800 Subject: [PATCH 79/93] fix(host): pass the entered path to the Host untrimmed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Trim now only detects a blank draft; the original text navigates — a real directory name may end in whitespace, and trimming would list its sibling or adopt the wrong workspace. --- .../src/client/DirectoryBrowser.tsx | 6 ++++-- .../tests/directory-browser.spec.tsx | 12 ++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 1c50eb8167..db2231f384 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -347,8 +347,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, onKeyDown={(event) => { if (event.key === 'Enter' && !composingRef.current) { event.preventDefault() - const target = pathDraft.trim() - if (target !== '') navigate(target) + // 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() diff --git a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx index 5221e627f8..dd7b7c0ae2 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -198,6 +198,18 @@ describe('DirectoryBrowser', () => { expect(listDirectory).toHaveBeenLastCalledWith(undefined) }) + 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('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} `) }) + }) + it('surfaces an unreadable target as an alert and keeps the edit open for correction', async () => { mount() await waitFor(() => { expect(screen.getByRole('listitem')).toBeTruthy() }) From 463893947bf7174532cefe8658e0cf2e73d6ee33 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 05:59:51 +0800 Subject: [PATCH 80/93] fix(host): create folders with the entered name untrimmed MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Same contract as the path editor: trim only rejects an all-whitespace draft, and the Host receives the original spelling — the backend accepts any non-blank single segment verbatim, so trimming here would create and select a different sibling. --- .../src/client/DirectoryBrowser.tsx | 7 +++++-- .../tests/directory-browser.spec.tsx | 11 +++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index db2231f384..1705a42e2a 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -211,8 +211,11 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, 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 - const name = folderDraft.trim() - if (name === '') 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 diff --git a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx index dd7b7c0ae2..f0c54ad421 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -542,6 +542,17 @@ describe('DirectoryBrowser', () => { 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() }) From 53240f4664575c1a214bd1ec222f36d5073cd461 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 06:19:18 +0800 Subject: [PATCH 81/93] fix(host,client): abort superseded listings on the wire; keep the native swap resolvable Supersession (newer navigation, path editing, closing, unmount) now aborts the in-flight listing's request instead of only discarding its result: the browser mints an AbortController per listing, the signal rides the workspace face (IWorkspaces.listDirectory gains an optional signal) onto the fetch carrier, and the Host scan stops with it (817's cancellation chain). apps/cli keeps both picker packages as dependencies so the documented one-row cordis.yml swap to the native backend resolves at boot. --- apps/cli/package.json | 1 + .../runtime/src/client/contract/workspaces.ts | 3 +- .../runtime/src/client/workspaces/service.ts | 5 +- .../client/test-runtime/src/workspaces.ts | 2 +- .../src/client/DirectoryBrowser.tsx | 50 +++++++++++++------ .../src/client/flow.ts | 4 +- .../src/client/index.ts | 2 +- .../tests/directory-browser.spec.tsx | 35 ++++++++++--- pnpm-lock.yaml | 3 ++ 9 files changed, 77 insertions(+), 28 deletions(-) diff --git a/apps/cli/package.json b/apps/cli/package.json index db4c0c6173..36f1f15424 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -49,6 +49,7 @@ "@deepseek-ai/dsh-fs-policy": "workspace:^", "@deepseek-ai/dsh-host-apiproxy": "workspace:^", "@deepseek-ai/dsh-host-directory-picker-browse": "workspace:^", + "@deepseek-ai/dsh-host-directory-picker-native": "workspace:^", "@deepseek-ai/dsh-host-webserver": "workspace:^", "@deepseek-ai/dsh-llm": "workspace:^", "@deepseek-ai/dsh-llm-deepseek": "workspace:^", diff --git a/packages/client/runtime/src/client/contract/workspaces.ts b/packages/client/runtime/src/client/contract/workspaces.ts index bb50b43277..9238ea5fd0 100644 --- a/packages/client/runtime/src/client/contract/workspaces.ts +++ b/packages/client/runtime/src/client/contract/workspaces.ts @@ -40,9 +40,10 @@ export interface IWorkspaces { /** * List one directory level through the Host's `browse` capability. * @param path - absolute directory to list; absent lists the Host home directory. + * @param signal - aborts the wire request (and the Host's scan) when the caller supersedes it. * @returns the level's listing with breadcrumb ancestry. */ - listDirectory(path?: string): Promise + listDirectory(path?: string, signal?: AbortSignal): Promise /** * Create one child directory through the Host's `browse` capability. * @param path - absolute existing parent directory. diff --git a/packages/client/runtime/src/client/workspaces/service.ts b/packages/client/runtime/src/client/workspaces/service.ts index acc0d079aa..1dd3319e79 100644 --- a/packages/client/runtime/src/client/workspaces/service.ts +++ b/packages/client/runtime/src/client/workspaces/service.ts @@ -195,10 +195,11 @@ export class WorkspacesService implements IWorkspaces { /** * List one directory level through the Host's `browse` capability. * @param path - absolute directory to list; absent lists the Host home directory. + * @param signal - aborts the wire request (and the Host's scan) when the caller supersedes it. * @returns the level's listing with breadcrumb ancestry. */ - async listDirectory(path?: string): Promise { - const response = await this.api.host.listDirectory(path === undefined ? {} : { path }) + async listDirectory(path?: string, signal?: AbortSignal): Promise { + const response = await this.api.host.listDirectory(path === undefined ? {} : { path }, signal) if (!response.result.ok) throw new DirectoryBrowseError(response.result.error) return response.result.value } diff --git a/packages/client/test-runtime/src/workspaces.ts b/packages/client/test-runtime/src/workspaces.ts index b4d91a96b9..3505de0853 100644 --- a/packages/client/test-runtime/src/workspaces.ts +++ b/packages/client/test-runtime/src/workspaces.ts @@ -115,7 +115,7 @@ export class TestWorkspaces implements IWorkspaces { * @param path - absolute directory to list; absent lists the home level. * @returns the level's listing. */ - async listDirectory(path?: string): Promise { + async listDirectory(path?: string, _signal?: AbortSignal): Promise { this.calls.push({ method: 'listDirectory', args: [path] }) const stub = this.stubs.get('listDirectory') if (stub !== undefined) return await (stub(path) as Promise) diff --git a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx index 1705a42e2a..f348f1dd8d 100644 --- a/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx +++ b/packages/host/directory-picker-browse/src/client/DirectoryBrowser.tsx @@ -27,8 +27,8 @@ import css from './DirectoryBrowser.module.css' 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). */ - listDirectory: (path?: string) => Promise + /** 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 /** Create one child directory under an existing parent. */ createDirectory: (path: string, name: string) => Promise /** The operator confirmed a directory (the selection, else the listed level). */ @@ -115,6 +115,10 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, const [creatingFolder, setCreatingFolder] = useState(false) const [createError, setCreateError] = useState(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(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) @@ -130,18 +134,34 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, 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 } => { + 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 = ++requestSeq.current + const { seq, scan } = launchListing(path) setLoading(true) setError(null) - listDirectory(path).then((next) => { + scan.then((next) => { if (seq !== requestSeq.current) return setParent(next) setSelected(null) @@ -153,16 +173,16 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, setLoading(false) setError(failureText(reason)) }) - }, [listDirectory]) + }, [launchListing]) /** Select a row of the listed level and preview its children on the right. */ const select = useCallback((entry: DirectoryEntry) => { - const seq = ++requestSeq.current + const { seq, scan } = launchListing(entry.path) setSelected(entry) setChild(null) setLoading(true) setError(null) - listDirectory(entry.path).then((next) => { + scan.then((next) => { if (seq !== requestSeq.current) return setChild(next) setLoading(false) @@ -174,7 +194,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // breadcrumb still names the level: fall back to the single pane. setSelected(null) }) - }, [listDirectory]) + }, [launchListing]) /** A right-column pick advances the view one level: child becomes the level. */ const advance = useCallback((entry: DirectoryEntry) => { @@ -196,12 +216,12 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, navigate() return } - requestSeq.current += 1 + supersede() setError(null) setPathDraft(null) setFolderDraft(null) setCreateError(null) - }, [open, navigate]) + }, [open, navigate, supersede]) /** The folder a create or Open acts on: the selection, else the listed level. */ const targetPath = selected?.path ?? parent?.path ?? null @@ -227,9 +247,9 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, 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 = ++requestSeq.current + const { seq, scan } = launchListing(targetPath) setLoading(true) - listDirectory(targetPath).then((level) => { + scan.then((level) => { /* v8 ignore next -- same fence as navigate/select; the modal blocks superseding input */ if (seq !== requestSeq.current) return setParent(level) @@ -324,7 +344,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // Opening the editor supersedes any pending listing: a // settlement landing before the first keystroke would // otherwise close the editor via navigate's draft reset. - requestSeq.current += 1 + supersede() setLoading(false) setPathDraft(selected?.path ?? parent?.path ?? '') }} @@ -342,7 +362,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // Editing the draft supersedes any in-flight navigation: // its completion must neither clear the newer text nor // repopulate the view with the older path. - requestSeq.current += 1 + supersede() setLoading(false) setPathDraft(event.target.value) }} @@ -361,7 +381,7 @@ export function DirectoryBrowser({ open, listDirectory, createDirectory, onOpen, // launched: its late success must not jump to the // cancelled path, so the pending request is superseded // and the view leaves the loading state. - requestSeq.current += 1 + supersede() setLoading(false) setPathDraft(null) setError(null) diff --git a/packages/host/directory-picker-browse/src/client/flow.ts b/packages/host/directory-picker-browse/src/client/flow.ts index 662c40de62..84e49b2c98 100644 --- a/packages/host/directory-picker-browse/src/client/flow.ts +++ b/packages/host/directory-picker-browse/src/client/flow.ts @@ -13,8 +13,8 @@ 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). */ - listDirectory: (path?: string) => Promise + /** List one directory level (absent path = the Host home directory); the signal aborts a superseded scan. */ + listDirectory: (path?: string, signal?: AbortSignal) => Promise /** Create one child directory under an existing parent. */ createDirectory: (path: string, name: string) => Promise /** Localized dialog copy (this package's namespace). */ diff --git a/packages/host/directory-picker-browse/src/client/index.ts b/packages/host/directory-picker-browse/src/client/index.ts index 6eb43829db..8ec0ffc5f9 100644 --- a/packages/host/directory-picker-browse/src/client/index.ts +++ b/packages/host/directory-picker-browse/src/client/index.ts @@ -72,7 +72,7 @@ export function apply(ctx: ClientContext): void { }, 'directory-picker-browse: dialog dictionaries') const injected = (): BrowseFlowInjected => ({ - listDirectory: path => ctx.workspaces.listDirectory(path), + listDirectory: (path, signal) => ctx.workspaces.listDirectory(path, signal), createDirectory: (path, name) => ctx.workspaces.createDirectory(path, name), t: ctx.locale.bind(LOCALE_NS), }) diff --git a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx index f0c54ad421..babe7c8bf7 100644 --- a/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx +++ b/packages/host/directory-picker-browse/tests/directory-browser.spec.tsx @@ -95,7 +95,7 @@ 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(b.listDirectory).toHaveBeenCalledWith(undefined, expect.any(AbortSignal)) expect(columns()).toHaveLength(1) expect(screen.getByRole('listitem').textContent).toBe('Documents') expect(screen.queryByText('.config')).toBeNull() @@ -113,7 +113,7 @@ describe('DirectoryBrowser', () => { 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(b.listDirectory).toHaveBeenLastCalledWith(DOCS, expect.any(AbortSignal)) expect(within(screen.getByRole('navigation')).getByRole('button', { name: 'Documents' })).toBeTruthy() }) @@ -130,6 +130,29 @@ describe('DirectoryBrowser', () => { 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((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() + 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() }) @@ -195,7 +218,7 @@ describe('DirectoryBrowser', () => { // rows nor status behind. await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('Documents') }) expect(listDirectory).toHaveBeenCalledTimes(2) - expect(listDirectory).toHaveBeenLastCalledWith(undefined) + expect(listDirectory).toHaveBeenLastCalledWith(undefined, expect.any(AbortSignal)) }) it('passes the entered path to the Host untrimmed (trim only gates blank drafts)', async () => { @@ -207,7 +230,7 @@ describe('DirectoryBrowser', () => { 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} `) }) + 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 () => { @@ -347,7 +370,7 @@ describe('DirectoryBrowser', () => { expect(b.listDirectory.mock.calls.length).toBe(listCalls) fireEvent.compositionEnd(pathInput) fireEvent.keyDown(pathInput, { key: 'Enter' }) - await waitFor(() => { expect(b.listDirectory).toHaveBeenLastCalledWith(DOCS) }) + 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') @@ -764,6 +787,6 @@ describe('DirectoryBrowser', () => { b.view.rerender() await waitFor(() => { expect(screen.getByRole('listitem').textContent).toBe('Documents') }) expect(columns()).toHaveLength(1) - expect(b.listDirectory).toHaveBeenLastCalledWith(undefined) + expect(b.listDirectory).toHaveBeenLastCalledWith(undefined, expect.any(AbortSignal)) }) }) diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f7026700fa..bc013a08a6 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -215,6 +215,9 @@ importers: '@deepseek-ai/dsh-host-directory-picker-browse': specifier: workspace:^ version: link:../../packages/host/directory-picker-browse + '@deepseek-ai/dsh-host-directory-picker-native': + specifier: workspace:^ + version: link:../../packages/host/directory-picker-native '@deepseek-ai/dsh-host-webserver': specifier: workspace:^ version: link:../../packages/host/webserver From d80fca0db888b3837a5983a34292768da51a9674 Mon Sep 17 00:00:00 2001 From: creatixchu Date: Wed, 29 Jul 2026 06:31:18 +0800 Subject: [PATCH 82/93] fix(client): forward the abort signal through the workspaces test double TestWorkspaces.listDirectory now records the signal and passes it to the installed stub, mirroring the production face, so cancellation integration tests can observe or reject on a superseded scan instead of the harness silently dropping it. --- packages/client/test-runtime/src/workspaces.ts | 9 ++++++--- .../client/test-runtime/tests/runtime.spec.tsx | 14 ++++++++++---- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/packages/client/test-runtime/src/workspaces.ts b/packages/client/test-runtime/src/workspaces.ts index 3505de0853..6c1a9d0aad 100644 --- a/packages/client/test-runtime/src/workspaces.ts +++ b/packages/client/test-runtime/src/workspaces.ts @@ -115,10 +115,13 @@ export class TestWorkspaces implements IWorkspaces { * @param path - absolute directory to list; absent lists the home level. * @returns the level's listing. */ - async listDirectory(path?: string, _signal?: AbortSignal): Promise { - this.calls.push({ method: 'listDirectory', args: [path] }) + async listDirectory(path?: string, signal?: AbortSignal): Promise { + // The signal is recorded and forwarded like the production face passes + // it to the wire, so cancellation integration tests can observe or + // reject on a superseded scan. + this.calls.push({ method: 'listDirectory', args: [path, signal] }) const stub = this.stubs.get('listDirectory') - if (stub !== undefined) return await (stub(path) as Promise) + if (stub !== undefined) return await (stub(path, signal) as Promise) // The chain runs root-to-target inclusive, per the DirectoryListing // contract — a bare root crumb would mislabel the level in browsers // driven by this double. diff --git a/packages/client/test-runtime/tests/runtime.spec.tsx b/packages/client/test-runtime/tests/runtime.spec.tsx index a6f22a85fe..b170f69ba2 100644 --- a/packages/client/test-runtime/tests/runtime.spec.tsx +++ b/packages/client/test-runtime/tests/runtime.spec.tsx @@ -329,16 +329,22 @@ describe('workspaces', () => { await expect(runtime.workspaces.listDirectory()).resolves.toMatchObject({ path: '/home/test', entries: [] }) await expect(runtime.workspaces.listDirectory('/home/test')).resolves.toMatchObject({ path: '/home/test' }) await expect(runtime.workspaces.createDirectory('/home/test', 'fresh')).resolves.toBe('/home/test/fresh') + // The recorded signal seat mirrors the production face (undefined here; + // cancellation tests pass and observe a real one). expect(runtime.workspaces.calls).toEqual([ - { method: 'listDirectory', args: [undefined] }, - { method: 'listDirectory', args: ['/home/test'] }, + { method: 'listDirectory', args: [undefined, undefined] }, + { method: 'listDirectory', args: ['/home/test', undefined] }, { method: 'createDirectory', args: ['/home/test', 'fresh'] }, ]) // Stubs replace the defaults like every sibling method. const listing = { path: '/x', home: '/x', crumbs: [], entries: [] } - runtime.workspaces.stub('listDirectory', vi.fn(() => Promise.resolve(listing as never))) + const listStub = vi.fn(() => Promise.resolve(listing as never)) + runtime.workspaces.stub('listDirectory', listStub) runtime.workspaces.stub('createDirectory', vi.fn(() => Promise.resolve('/x/made' as never))) - await expect(runtime.workspaces.listDirectory('/x')).resolves.toBe(listing) + const scan = new AbortController() + await expect(runtime.workspaces.listDirectory('/x', scan.signal)).resolves.toBe(listing) + // The stub receives the signal too, like the production face gives the wire. + expect(listStub).toHaveBeenLastCalledWith('/x', scan.signal) await expect(runtime.workspaces.createDirectory('/x', 'made')).resolves.toBe('/x/made') await runtime.dispose() }) From 31cb340c367abf5f33dfefb3787c6eeb2aaf749b Mon Sep 17 00:00:00 2001 From: Turtle Date: Wed, 29 Jul 2026 10:00:29 +0800 Subject: [PATCH 83/93] feat(tui)!: consolidate terminal UI improvements --- packages/bash/tool-bash/README.i18n.yaml | 6 +- packages/bash/tool-bash/README.md | 4 +- packages/bash/tool-bash/README.zh.md | 4 +- packages/bash/tool-bash/src/index.ts | 4 +- packages/bash/tool-bash/src/render.ts | 31 +- packages/bash/tool-bash/tests/tools.spec.ts | 30 +- packages/ui/tui/AGENTS.md | 5 + packages/ui/tui/README.i18n.yaml | 4 +- packages/ui/tui/README.md | 23 +- packages/ui/tui/README.zh.md | 25 +- packages/ui/tui/src/chat/resume.ts | 82 ++- packages/ui/tui/src/chat/timing.ts | 2 +- packages/ui/tui/src/components/dialogs.ts | 175 +++++-- packages/ui/tui/src/components/theme.ts | 232 +++++++-- packages/ui/tui/src/components/transcript.ts | 211 ++++++-- .../ui/tui/src/components/xml-tool-output.ts | 40 +- packages/ui/tui/src/config.ts | 14 +- packages/ui/tui/src/extension/types.ts | 4 +- packages/ui/tui/src/index.ts | 199 ++++--- packages/ui/tui/src/runtime.ts | 22 +- packages/ui/tui/tests/harness.ts | 3 + .../advanced-cards-collapsed.expected.txt | 25 +- .../advanced-cards-expanded.expected.txt | 37 +- .../snapshots/banner-gradient.expected.txt | 16 +- .../snapshots/code-mode-pending.expected.txt | 18 +- .../conversation-streaming.expected.txt | 25 +- .../cordis-tools-pending.expected.txt | 18 +- .../snapshots/disposed-terminal.expected.txt | 104 ++-- .../dynamic-workflow-pending.expected.txt | 18 +- .../snapshots/errors-and-help.expected.txt | 102 ++-- .../snapshots/file-autocomplete.expected.txt | 20 +- .../model-selector-filtered.expected.txt | 52 ++ .../snapshots/model-selector.expected.txt | 69 +-- .../snapshots/model-switching.expected.txt | 20 +- ...question-dialog-single-option.expected.txt | 22 +- .../question-dialog-validation.expected.txt | 14 +- .../snapshots/question-dialog.expected.txt | 14 +- ...esume-sessions-all-workspaces.expected.txt | 57 ++ .../snapshots/resume-sessions.expected.txt | 17 +- .../snapshots/retry-cancelled.expected.txt | 20 +- .../snapshots/retry-exhausted.expected.txt | 20 +- .../snapshots/retry-recovered.expected.txt | 20 +- .../snapshots/retry-scheduled.expected.txt | 20 +- .../snapshots/session-reference.expected.txt | 16 +- .../session-title-autocomplete.expected.txt | 20 +- .../shell-prompt-multiline.expected.txt | 10 +- .../status-diagnostics-narrow.expected.txt | 48 +- .../snapshots/status-diagnostics.expected.txt | 50 +- .../step-timing-completed.expected.txt | 22 +- ...rface-after-compaction-narrow.expected.txt | 39 +- ...surface-after-compaction-wide.expected.txt | 40 +- .../surface-before-compaction.expected.txt | 25 +- .../snapshots/todo-plan-cleared.expected.txt | 22 +- .../snapshots/untrusted-controls.expected.txt | 35 +- packages/ui/tui/tests/tui.snapshot.ts | 66 ++- packages/ui/tui/tests/tui.spec.ts | 485 +++++++++++++++--- packages/ui/tui/tests/xml-tool-output.spec.ts | 45 +- 57 files changed, 1875 insertions(+), 896 deletions(-) create mode 100644 packages/ui/tui/AGENTS.md create mode 100644 packages/ui/tui/tests/snapshots/model-selector-filtered.expected.txt create mode 100644 packages/ui/tui/tests/snapshots/resume-sessions-all-workspaces.expected.txt diff --git a/packages/bash/tool-bash/README.i18n.yaml b/packages/bash/tool-bash/README.i18n.yaml index a529b56b56..676c935cbd 100644 --- a/packages/bash/tool-bash/README.i18n.yaml +++ b/packages/bash/tool-bash/README.i18n.yaml @@ -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: 965ae25a5e29a4f767adfcb73e4a77f1060e4b46 -README.zh.md: 60be5c5ca5624719f5ca651a78b6ba56f3f3df06 +# pnpm run verify-translation-pairing --write packages/bash/tool-bash/README.md +README.md: deb6b899c81cb8c335b4c1cffdde4797e0a8be92 +README.zh.md: c2514308fb9f234e6d191a6b1a821ac3d195378b diff --git a/packages/bash/tool-bash/README.md b/packages/bash/tool-bash/README.md index 965ae25a5e..deb6b899c8 100644 --- a/packages/bash/tool-bash/README.md +++ b/packages/bash/tool-bash/README.md @@ -57,7 +57,7 @@ When `run_in_background` is true, this plugin preflights `ctx.tasks.start()` bef ## UI presentation -The tool owns its `presentCall`/`presentResult` render intent. A foreground call is a terminal card carrying command, description, cwd, raw output, and parsed exit status. A background start is a generic execute card because it returns only a task id; the generic `task_*` tools own their own cards. These presenters are pure and replay-safe. +The tool owns its `presentCall`/`presentResult` render intent. A foreground call is a terminal card carrying command, description, cwd, output, and parsed exit status. Because the card shows the exit as its own pill, the `[exit code: N]` / `[killed by signal: …]` marker the parse consumes leaves the output; every other marker (truncation, timeout, sandbox) stays in it. A background start is a generic execute card because it returns only a task id; the generic `task_*` tools own their own cards. These presenters are pure and replay-safe. ## The tool builds its request from named args only @@ -153,6 +153,6 @@ Append-only; newly visible content follows the reusable request prefix and does ## Known Limitations and Deferred Work -- **Replay exit pills parse from result text** — output whose final line happens to be exactly `[exit code: N]` / `[killed by signal: …]` shows a wrong pill on session replay; a display-only known residual. +- **Replay exit pills parse from result text** — output whose final line happens to be exactly `[exit code: N]` / `[killed by signal: …]` shows a wrong pill on session replay and loses that line from the card body, because the parse treats it as the marker it consumes; a display-only known residual. - **The `bash` tool opts out of `timeout-policy` budgets** — it keeps the executor-owned `BASH_TIMEOUT` path, per [the tool-call timeout-policy Agent Note](../../../.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.md). - **Background processes have no executor timeout** — callers must use `task_kill`, or rely on owner/service disposal, when work no longer matters. diff --git a/packages/bash/tool-bash/README.zh.md b/packages/bash/tool-bash/README.zh.md index 60be5c5ca5..c2514308fb 100644 --- a/packages/bash/tool-bash/README.zh.md +++ b/packages/bash/tool-bash/README.zh.md @@ -57,7 +57,7 @@ overlay 根据当前 `ToolExecution` 计算,并通过专用的 `BashExecReques ## UI 展示 -工具持有自己的 `presentCall`/`presentResult` 渲染意图。前台调用是终端卡片,包含命令、说明、cwd、原始输出和解析后的退出状态。后台启动只返回 task id,因此使用通用执行卡片;通用 `task_*` 工具持有各自的卡片。这些 presenter 是纯函数,可安全回放。 +工具持有自己的 `presentCall`/`presentResult` 渲染意图。前台调用是终端卡片,包含命令、说明、cwd、输出和解析后的退出状态。由于卡片以独立的 pill 展示退出状态,解析所消耗的 `[exit code: N]` / `[killed by signal: …]` 标记会从输出中移除;其他所有标记(截断、超时、沙箱)都保留在输出中。后台启动只返回 task id,因此使用通用执行卡片;通用 `task_*` 工具持有各自的卡片。这些 presenter 是纯函数,可安全回放。 ## 工具仅使用具名参数构建请求 @@ -153,6 +153,6 @@ renderer 先输出依数据而定的 stdout 尾部,再输出可选的 `[stderr ## 已知限制与延期工作 -- **回放退出状态 pill 从结果文本解析**:如果输出最后一行恰好精确为 `[exit code: N]` / `[killed by signal: …]`,会话回放将显示错误的 pill;这是仅影响展示的已知残留问题。 +- **回放退出状态 pill 从结果文本解析**:如果输出最后一行恰好精确为 `[exit code: N]` / `[killed by signal: …]`,会话回放将显示错误的 pill,并且该行会从卡片正文中丢失,因为解析会把它当作自己消耗的标记;这是仅影响展示的已知残留问题。 - **`bash` 工具不采用 `timeout-policy` 预算**:根据[工具调用 timeout-policy Agent Note](../../../.agents/notes/implemented/architecture/2026-07-07-tool-call-timeout-policy.md),它保留由执行器持有的 `BASH_TIMEOUT` 路径。 - **后台进程没有执行器超时**:工作不再需要时,调用方必须使用 `task_kill`,或依赖持有者/服务的 dispose。 diff --git a/packages/bash/tool-bash/src/index.ts b/packages/bash/tool-bash/src/index.ts index b403c4414e..f8cece2862 100644 --- a/packages/bash/tool-bash/src/index.ts +++ b/packages/bash/tool-bash/src/index.ts @@ -296,7 +296,9 @@ function presentBashResult(args: unknown, result: ToolResult): ToolResultView | if (isBackground || result.isError) { return { card: 'generic', content: [{ type: 'text', text: `\`\`\`console\n${raw.replace(/\n+$/, '')}\n\`\`\`` }] } } - return { card: 'terminal', output: raw, ...parseExitStatus(raw) } + // The exit marker becomes the card's exit pill, so it leaves the output body. + const { body, ...exit } = parseExitStatus(raw) + return { card: 'terminal', output: body, ...exit } } /** diff --git a/packages/bash/tool-bash/src/render.ts b/packages/bash/tool-bash/src/render.ts index 77a88e28f3..eabe681c25 100644 --- a/packages/bash/tool-bash/src/render.ts +++ b/packages/bash/tool-bash/src/render.ts @@ -95,10 +95,23 @@ export function renderProcessRead( } /** - * Recover the structured exit status from a rendered {@link renderResult} - * string — the inverse of the status markers it appends. A killed marker - * yields `signal`; otherwise a non-zero marker yields `exitCode`; absent both - * means a clean exit 0. + * The exit status recovered from a rendered result, with the output body that + * status was split off from. + */ +export type ParsedExitStatus = + & { body: string } + & ({ exitCode: number } | { signal: string }) + +/** + * Split a rendered {@link renderResult} string into its output body and the + * structured exit status — the inverse of the status markers it appends. A + * killed marker yields `signal`; otherwise a non-zero marker yields `exitCode`; + * absent both means a clean exit 0. + * + * The consumed marker is removed from `body` because a terminal presentation + * shows the exit status as its own pill: leaving the marker in the output would + * render the exit twice. Other markers (timeout, sandbox denial) carry facts no + * pill shows, so they stay in the body. * * Replay only retains the rendered content text, not the original * `BashRunResult`, so terminal presentation must recover the exit pill here. @@ -106,12 +119,12 @@ export function renderProcessRead( * that merely ends with marker-like text from matching unless the final line * is indistinguishable from a real marker. * @param text - rendered model-facing bash result. - * @returns the recovered terminal exit code or signal. + * @returns the marker-free body plus the recovered terminal exit code or signal. */ -export function parseExitStatus(text: string): { exitCode: number } | { signal: string } { +export function parseExitStatus(text: string): ParsedExitStatus { const signal = /\n\[killed by signal: ([^\]\n]+)\]$/.exec(text) - if (signal?.[1] !== undefined) return { signal: signal[1] } + if (signal?.[1] !== undefined) return { body: text.slice(0, signal.index), signal: signal[1] } const exit = /\n\[exit code: (\d+)\]$/.exec(text) - if (exit?.[1] !== undefined) return { exitCode: Number(exit[1]) } - return { exitCode: 0 } + if (exit?.[1] !== undefined) return { body: text.slice(0, exit.index), exitCode: Number(exit[1]) } + return { body: text, exitCode: 0 } } diff --git a/packages/bash/tool-bash/tests/tools.spec.ts b/packages/bash/tool-bash/tests/tools.spec.ts index 15222ee647..a52b3f16f1 100644 --- a/packages/bash/tool-bash/tests/tools.spec.ts +++ b/packages/bash/tool-bash/tests/tools.spec.ts @@ -911,22 +911,32 @@ describe('tool-owned UI presentation (presentCall / presentResult)', () => { it('bash presentResult: a terminal result carries RAW output (newlines intact) + parsed exit code', async () => { const ctx = await setup() const present = ctx.tools.get('bash')!.presentResult!( - { command: 'echo hi', description: 'echo' }, - { content: [{ type: 'text', text: 'hi\n[exit code: 0]\n\n' }], isError: false }, + { command: 'printf "hi\\n\\n"', description: 'echo' }, + // A clean run renders no exit marker at all, so the body is the raw bytes. + { content: [{ type: 'text', text: 'hi\n\n' }], isError: false }, ) // A terminal result keeps the RAW bytes (newlines intact) a terminal renderer - // needs; the bridge derives the fenced fallback. exitCode is parsed back from - // the [exit code: N] marker. - expect(present).toEqual({ card: 'terminal', output: 'hi\n[exit code: 0]\n\n', exitCode: 0 }) + // needs; the bridge derives the fenced fallback. + expect(present).toEqual({ card: 'terminal', output: 'hi\n\n', exitCode: 0 }) }) it('bash presentResult: a non-zero exit and a signal kill parse into exitCode / signal', async () => { const ctx = await setup() const args = { command: 'x', description: 'x' } const nonzero = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'oops\n[exit code: 3]' }], isError: false }) - expect(nonzero).toEqual({ card: 'terminal', output: 'oops\n[exit code: 3]', exitCode: 3 }) + expect(nonzero).toEqual({ card: 'terminal', output: 'oops', exitCode: 3 }) const killed = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: 'gone\n[killed by signal: SIGKILL]' }], isError: false }) - expect(killed).toEqual({ card: 'terminal', output: 'gone\n[killed by signal: SIGKILL]', signal: 'SIGKILL' }) + expect(killed).toEqual({ card: 'terminal', output: 'gone', signal: 'SIGKILL' }) + }) + + it('bash presentResult: markers a pill CANNOT show (timeout, sandbox denial) stay in the terminal output', async () => { + const ctx = await setup() + const args = { command: 'x', description: 'x' } + const timedOut = ctx.tools.get('bash')!.presentResult!( + args, + { content: [{ type: 'text', text: 'slow\n[timed out after 100ms]\n[exit code: 143]' }], isError: false }, + ) + expect(timedOut).toEqual({ card: 'terminal', output: 'slow\n[timed out after 100ms]', exitCode: 143 }) }) it('bash presentResult exit parse is the inverse of renderResult markers (round-trip)', async () => { @@ -952,8 +962,11 @@ describe('tool-owned UI presentation (presentCall / presentResult)', () => { const rendered = renderResult(c.result) const out = present.presentResult!({ command: 'x', description: 'x' }, { content: [{ type: 'text', text: rendered }], isError: false }) // Drop card + output; the remaining fields are the parsed exit. - const { card: _c, output: _o, ...exit } = out as { card: string; output?: string; exitCode?: number; signal?: string } + const { card: _c, output, ...exit } = out as { card: string; output?: string; exitCode?: number; signal?: string } expect(exit).toEqual(c.expect) + // Whatever the parse consumed is gone from the body, so a card with an exit + // pill never shows the same status twice. + expect(output).not.toMatch(/\[exit code: \d+\]|\[killed by signal: /) } }) @@ -964,6 +977,7 @@ describe('tool-owned UI presentation (presentCall / presentResult)', () => { // newline; parsing requires the leading newline emitted for real markers, so this stays exit 0. const out = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[exit code: 5]' }], isError: false }) expect(out).toEqual({ card: 'terminal', output: '[exit code: 5]', exitCode: 0 }) + // Unparsed marker-like text is real output, so it is NOT stripped from the body. // Same for a fake signal marker with no leading newline. const sig = ctx.tools.get('bash')!.presentResult!(args, { content: [{ type: 'text', text: '[killed by signal: SIGKILL]' }], isError: false }) expect(sig).toEqual({ card: 'terminal', output: '[killed by signal: SIGKILL]', exitCode: 0 }) diff --git a/packages/ui/tui/AGENTS.md b/packages/ui/tui/AGENTS.md new file mode 100644 index 0000000000..2e73212a58 --- /dev/null +++ b/packages/ui/tui/AGENTS.md @@ -0,0 +1,5 @@ +# AGENTS.md — TUI package + +These rules supplement the package conventions in [packages/AGENTS.md](../../AGENTS.md). + +- **Present TUI designs in tmux, not in the session transcript.** When tmux is available, run the assembled TUI in a pane of the same window the session runs in and point the user at it; print a rendering into the transcript only as a fallback. diff --git a/packages/ui/tui/README.i18n.yaml b/packages/ui/tui/README.i18n.yaml index 4e0757170d..8ab63910fa 100644 --- a/packages/ui/tui/README.i18n.yaml +++ b/packages/ui/tui/README.i18n.yaml @@ -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/ui/tui/README.md -README.md: 5aafd6f5207320bf273c96a04f2d606577ca2da0 -README.zh.md: 1901faeb26c65126bc5475a991fedecd39a88ba5 +README.md: 0b358520b863f0b9ee7a128cf4807f582fc46d8d +README.zh.md: 7e89197bd82d16dfbabeb715e953275e2f6dd68b diff --git a/packages/ui/tui/README.md b/packages/ui/tui/README.md index 5aafd6f520..0b358520b8 100644 --- a/packages/ui/tui/README.md +++ b/packages/ui/tui/README.md @@ -22,9 +22,9 @@ Typing `@` at a token boundary searches files and directories under the session When optional `ctx.sessionReferences` is mounted, the same `@` menu also offers metadata-only session candidates, inserts `@[label](dsh-session:)`, and prepares the selected snapshots before dispatch. Session references remain structured because the model has no filesystem-like tool for retrieving session snapshots later. Preparation disables duplicate submission and restores the editor input on failure. The TUI chooses `agent.steer()` or `agent.followup()` from the status after that asynchronous preparation, so idle follow-ups still dispatch `agent/prompt-submit` while in-turn steering joins at a checkpoint without that hook. -While the agent is running, ordinary editor submissions call `agent.steer()`; otherwise they call `agent.followup()`. A slash at the start of the submitted line enters `ctx.commands` instead: known commands execute directly, unknown commands produce a warning, and neither path automatically reaches the model. A command producer may explicitly schedule agent work; [`dsh-plan-mode`](../../plan/plan-mode/README.md#model-and-human-surfaces) uses that contract for `/plan [message]`. The TUI registers `/help`, `/model`, `/clear`, `/reasoning`, `/tools`, `/redraw`, `/reload`, `/resume`, `/status`, and `/exit` as agent-scoped definitions; every other effective command joins autocomplete and `/help` dynamically, as do `/skill:` completions. A status line above the editor reports the turn phase the TUI derives from session events — waiting for the first token, thinking, responding, or executing tools — with the elapsed time in that phase and the running step total, refreshed each second, and ends with the `Enter sends steering, Esc cancels` hint; while steering messages wait to reach the model it inserts a `N queued ·` badge before the hint that clears as each drains. Ctrl+C or Escape cancels a running turn. Tool cards collapse long bodies into a configurable head/tail preview; Ctrl+O toggles every card between its preview and full output. Ctrl+R toggles reasoning, Ctrl+L redraws, and Ctrl+D exits while idle. +While the agent is running, ordinary editor submissions call `agent.steer()`; otherwise they call `agent.followup()`. A slash at the start of the submitted line enters `ctx.commands` instead: known commands execute directly, unknown commands produce a warning, and neither path automatically reaches the model. A command producer may explicitly schedule agent work; [`dsh-plan-mode`](../../plan/plan-mode/README.md#model-and-human-surfaces) uses that contract for `/plan [message]`. The TUI registers `/help`, `/model`, `/clear`, `/palette`, `/reload`, `/resume`, `/status`, and `/exit` as agent-scoped definitions; every other effective command joins autocomplete and `/help` dynamically, as do `/skill:` completions. A status line above the editor reports the turn phase the TUI derives from session events — waiting for the first token, thinking, responding, or executing tools — with the elapsed time in that phase and the running step total, refreshed each second, and ends with the `Enter sends steering, Esc cancels` hint; while steering messages wait to reach the model it inserts a `N queued ·` badge before the hint that clears as each drains. Ctrl+C or Escape cancels a running turn. Tool and injected-context cards collapse long bodies into a configurable head/tail preview; Ctrl+O cycles tool cards through collapsed preview, full output, and hidden — the hidden phase drops tool cards from the transcript entirely while context cards stay at their preview, since injected instructions are not tool traffic. An injected-context card renders its message as prose with the producer's outer reminder frame stripped, so neither the fold nor the frame stripping depends on the payload's syntax. Ctrl+R toggles reasoning, Ctrl+L redraws, and Ctrl+D exits while idle. -`/model` opens the advisory `ctx.llm` catalog as a keyboard selector: Up/Down moves, Shift+Tab cycles the focused model's adapter-advertised reasoning efforts in display order, Enter selects the model and effort, and Escape closes it. When an adapter does not advertise a default effort, the cycle also includes `provider default`, which clears an explicit selection; models without selectable effort metadata ignore Shift+Tab. The selector renders the exact advertised effort list—including `off` when present—and does not synthesize, clamp, or transfer an effort between models. `/model ` still selects an unambiguous model id directly, while `/model /` selects an exact target and uses its adapter default when one exists. The configured target or latest logged request header initializes the selector, and an unlisted current model remains visible because catalogs are advisory. Selection is local to this TUI session. Prompt assembly snapshots the target for one step, replaces `{{provider}}` and `{{model}}`, and applies the same provider/model/reasoning-effort target through `agent/request`; a switch during assembly therefore starts with a later step. The request header durably records targets that reach the model, while an unused selection remains process-local. +`/model` opens the advisory `ctx.llm` catalog as a keyboard selector: a filter box above the list narrows rows by a case-insensitive substring over each row's `provider/model` label, model name, and description, keeping the highlighted row selected when it survives the filter; Up/Down moves, Shift+Tab cycles the focused model's adapter-advertised reasoning efforts in display order, Enter selects the model and effort, and Escape clears a non-empty filter before a second Escape closes it. When an adapter does not advertise a default effort, the cycle also includes `provider default`, which clears an explicit selection; models without selectable effort metadata ignore Shift+Tab. The selector renders the exact advertised effort list—including `off` when present—and does not synthesize, clamp, or transfer an effort between models. `/model ` still selects an unambiguous model id directly, while `/model /` selects an exact target and uses its adapter default when one exists. The configured target or latest logged request header initializes the selector, and an unlisted current model remains visible because catalogs are advisory. Selection is local to this TUI session. Prompt assembly snapshots the target for one step, replaces `{{provider}}` and `{{model}}`, and applies the same provider/model/reasoning-effort target through `agent/request`; a switch during assembly therefore starts with a later step. The request header durably records targets that reach the model, while an unused selection remains process-local. `/reload` (EXPERIMENTAL, dev-only) re-reads every file-backed loader config tree and applies the diff to the running app — the HMR watcher's config path, invoked manually; it needs the cordis Loader in the context and degrades to a warning without one, runs only while the agent is idle, and refuses re-entry while a reload is in flight. Module-source hot reload remains watcher-owned. When a `skills` service is mounted, `/skill: [instructions]` loads that skill's instructions into the conversation as a user turn; autocomplete lists the model-invocable skills, and any skill (including a model-disabled one) is loadable by its exact name. @@ -32,9 +32,15 @@ The footer sums the session's reported usage as `↑ `/status` adds a point-in-time diagnostics card to the transcript and remains available while the agent runs. It reports the session id, title, working directory, selected provider/model, selected reasoning effort or default behavior, reasoning-block visibility, agent state, event/turn/step/tool-call counts, exact input/output/cache token buckets, KV-cache hit rate, token-meter context use and capacity, creation time, and latest event time. Missing titles, models, cache input, or context capacity are labeled instead of inferred. The card is terminal-only and does not duplicate the compact footer. -`/resume` opens a full-viewport keyboard selector over the current workspace instead of a centered dialog. Its focused search field starts immediately after the search glyph and emits pi-tui's cursor marker, so terminal IME composition remains anchored inside the field. Candidates are sorted by last logged activity and searchable by log-backed title or session id; each row reports current/live/persisted state, last turn outcome, recent provider/model, and durable goal phase when present. Up/Down and Page Up/Page Down navigate, Enter resumes, Escape clears a non-empty search before a second Escape cancels, and Ctrl+C cancels directly. The current session, a session already live in this runtime, an unreadable log, a mismatched cwd, or a session whose logged provider has no current adapter remains visible but disabled. Selection repeats those checks and requires the current agent to be idle before flushing the current session. The TUI then stops the terminal UI and calls the optional host-owned `TuiRuntime.handoffResume`; where `process.execve` is available, the shipped `dsh` host disposes the app and replaces its process. Resume restores the same `SessionId`, transcript, title, todos, and durable goal; goal activation remains disarmed and the TUI asks for human confirmation or `/goal resume`. +`/resume` opens a full-viewport keyboard selector instead of a centered dialog. Two scopes cover the same candidate set: the current workspace, which it opens on, and all workspaces, which Tab toggles to. The scope line under the search field names the active scope and the count the other holds, and each row in the all-workspaces scope also reports its own workspace. Toggling clears the search and selection so the highlighted row always belongs to the visible list. -`resumeCommand` remains the deployment-owned fallback: exiting prints it only after the current session is durable, and a host without in-place handoff shows the selected session's command. `{session}` expands to the session id. TUI code never executes the template or arbitrary shell text. +Its focused search field starts immediately after the search glyph and emits pi-tui's cursor marker, so terminal IME composition remains anchored inside the field. Candidates are sorted by last logged activity and searchable by log-backed title or session id, and by workspace label in the all-workspaces scope; each row reports current/live/persisted state, last turn outcome, recent provider/model, and durable goal phase when present. Up/Down and Page Up/Page Down navigate, Enter resumes, Escape clears a non-empty search before a second Escape cancels, and Ctrl+C cancels directly. The current session, a session already live in this runtime, an unreadable log, a session with no recorded workspace to run in, or a session whose logged provider has no current adapter remains visible but disabled; a workspace other than the current one is a scope rather than a disabled reason, because resume enters that directory. + +Selection repeats those checks and requires the current agent to be idle before flushing the current session. The TUI then stops the terminal UI and calls the optional host-owned `TuiRuntime.handoffResume` with the selected id and the workspace re-read at preflight: process cwd, not the restored session header, is what filesystem and shell tools resolve against, so the host must enter that directory. Where `process.execve` is available, the shipped `dsh` host chdirs into it before disposing the app and replacing its process, and rejects an unreachable directory while the terminal can still be restored. Resume restores the same `SessionId`, transcript, title, todos, and durable goal; goal activation remains disarmed and the TUI asks for human confirmation or `/goal resume`. + +The exit line is launcher-owned, not configurable. A launcher provides `TUI_GOODBYE_MESSAGE_KEY` on the boot context — for the shipped `dsh`, the command that resumes this session — and exiting prints it verbatim after the terminal is released; absent, exiting prints nothing. Only the launcher knows how it was invoked, so only it can name a command that works. The TUI escapes terminal controls before rendering and never executes the text. A launcher that also supplies `MAIN_SESSION_ID_KEY` fixes which session the mounted app binds to, so resume survives any config-level patch. + +A launcher can seed a fresh session's first turn by providing `INITIAL_SKILL_KEY` (the skill name) on the boot context; the TUI auto-invokes it exactly as a typed `/skill:`, once the chat is live. The shipped `dsh migrate`/`dsh upgrade` set it and only for a fresh session, so a resumed session never re-invokes the skill; an unknown name is reported as a notice. ## Config @@ -57,7 +63,6 @@ The footer sums the session's reported usage as `↑ | `showHardwareCursor` | `false` | Show the hardware cursor at pi-tui's IME marker | | `color` | `true` | Apply the built-in ANSI palette (see [Color](#color)) | | `title` | `DeepSeek Harness` | Product suffix for the terminal window title. | -| `resumeCommand` | — | Shell command template for the exit hint and hosts without in-place handoff, with `{session}` expanded to the session id | ```yaml - id: terminal @@ -74,7 +79,11 @@ Startup fails before mounting when either process stream is not a TTY. The compo ## Color -The palette uses the standard 16-color ANSI foregrounds and SGR attributes, which every terminal remaps to its active color scheme, so it stays readable on light and dark backgrounds alike. Body text keeps the terminal's default foreground rather than a fixed shade. Grouped regions (user prompts, assistant replies, tool cards) are separated by a bold, underlined role header in the role color and blank-line spacing rather than a filled block or a per-line prefix, so a mouse drag-select copies the message text without any leading bar or indent; a tool card's status (pending, error, success) shows in its colored, underlined title glyph and title. The question panel emphasizes its active row with bold accent text, while selectors use reverse video. These treatments are foreground-only, so they never collide with the terminal background. Set `color: false` to strip all styling. +Every SGR code the TUI emits lives in one table, `paletteSpec` in `components/theme.ts`, which `createPalette` derives its wrappers from and `/palette` prints; no component writes an escape of its own. The table holds only the standard 16-color ANSI foregrounds and SGR attributes, which every terminal remaps to its active color scheme, so the TUI stays readable on light and dark backgrounds alike — the startup banner's brand gradient is the one deliberate exception. Body text keeps the terminal's default foreground rather than a fixed shade. + +There is one role per visual meaning: `dim` is the single recessed tone and `accent` the single emphasis color, while `success` and `error` double as a diff's added and removed lines. Colors and attributes are separately typed, so `bold(accent(x))` compiles and `accent(error(x))` does not — SGR has no color stack, so nesting one color inside another silently drops the outer color at the inner one's close. Attributes occupy independent SGR groups and compose with any color in either order. Run `/palette` to see every role as your terminal renders it, with its SGR pair. + +Grouped regions (user prompts, assistant replies, tool cards) are separated by a bold, underlined role header in the role color and blank-line spacing rather than a filled block or a per-line prefix, so a mouse drag-select copies the message text without any leading bar or indent; a tool card's status (pending, error, success) shows in its colored, underlined title glyph and title. Inside a tool card, the whole body — presenter title, a terminal `$` command and cwd, and the tool's own output — renders in one dim tone, so only the status-colored header carries color and the body reads as one recessed block instead of a run of competing shades; an injected-context card's prose is the same tone as its header. A diff card's `+`/`-` lines and a `[signal …]` marker stay colored, because there the color is the meaning rather than emphasis. The question panel emphasizes its active row with bold accent text, while selectors use reverse video. These treatments are foreground-only, so they never collide with the terminal background. Set `color: false` to strip all styling. ## Model Experience @@ -156,7 +165,7 @@ Append-only; newly visible content follows the reusable request prefix and does ## Known Limitations and Deferred Work -- **Resume has no cross-process session lock** — the selector rejects sessions known to be live in its own runtime, but another process can resume the same persisted id before or during handoff. Deployments that can run concurrent hosts must coordinate ownership outside the TUI. +- **Resume has no cross-process session lock** — the selector rejects sessions known to be live in its own runtime, but another process can resume the same persisted id before or during handoff. The all-workspaces scope makes this reachable in one step, since a session another host is driving in a different directory is now selectable. Deployments that can run concurrent hosts must coordinate ownership outside the TUI. - **One configured session owns the transcript and editor** — questions from other agents can still use the shared overlay provider, but session rendering and prompt input remain bound to `sessionId`. - **Tool cards are text terminal presentations** — terminal, diff, and generic cards use tool-owned titles/content, but session content currently has no image block for inline image rendering. - **Non-TTY operation is intentionally unsupported** — app bundles that need automation must compose a one-shot or server front door (`dsh-cli-demo`, `dsh-acp`) rather than expecting an internal fallback. diff --git a/packages/ui/tui/README.zh.md b/packages/ui/tui/README.zh.md index 1901faeb26..7e89197bd8 100644 --- a/packages/ui/tui/README.zh.md +++ b/packages/ui/tui/README.zh.md @@ -22,9 +22,9 @@ TUI 从活跃会话表层重建已恢复历史,渲染 Markdown 响应与 reaso 挂载可选的 `ctx.sessionReferences` 后,同一个 `@` 菜单还会提供仅含元数据的会话候选项,插入 `@[label](dsh-session:)`,并在分派前准备所选快照。会话引用保持结构化,因为模型没有类似文件系统的工具可在稍后检索会话快照。准备期间会禁止重复提交,并在失败时恢复编辑器输入。TUI 会在异步准备后根据状态选择 `agent.steer()` 或 `agent.followup()`,因此空闲 followup 仍会分派 `agent/prompt-submit`,而轮次中的 steering 会在检查点加入且不触发该 hook。 -Agent 运行时,普通编辑器提交会调用 `agent.steer()`;其他时候调用 `agent.followup()`。提交行以斜杠开头时会改为进入 `ctx.commands`:已知命令直接执行,未知命令产生警告,两条路径都不会自动到达模型。命令生产方可以显式调度 agent 工作;[`dsh-plan-mode`](../../plan/plan-mode/README.md#model-and-human-surfaces) 使用该契约实现 `/plan [message]`。TUI 将 `/help`、`/model`、`/clear`、`/reasoning`、`/tools`、`/redraw`、`/reload`、`/resume`、`/status` 和 `/exit` 注册为 agent 作用域定义;其他所有有效命令都会动态加入自动补全与 `/help`,`/skill:` 补全也相同。编辑器上方的状态行会报告 TUI 从会话事件派生的轮次阶段,包括等待首个 token、思考、响应或执行工具;它显示该阶段已经过时间和运行中的步骤总数,每秒刷新,并以 `Enter sends steering, Esc cancels` 提示结尾。Steering 消息等待到达模型期间,会在提示前插入 `N queued ·` 徽标,每条消息排空后随即清除。Ctrl+C 或 Escape 会取消运行中的轮次。工具卡片把长主体折叠为可配置的头尾预览;Ctrl+O 在预览与完整输出之间切换所有卡片。Ctrl+R 切换 reasoning,Ctrl+L 重绘,Ctrl+D 在空闲时退出。 +Agent 运行时,普通编辑器提交会调用 `agent.steer()`;其他时候调用 `agent.followup()`。提交行以斜杠开头时会改为进入 `ctx.commands`:已知命令直接执行,未知命令产生警告,两条路径都不会自动到达模型。命令生产方可以显式调度 agent 工作;[`dsh-plan-mode`](../../plan/plan-mode/README.md#model-and-human-surfaces) 使用该契约实现 `/plan [message]`。TUI 将 `/help`、`/model`、`/clear`、`/palette`、`/reload`、`/resume`、`/status` 和 `/exit` 注册为 agent 作用域定义;其他所有有效命令都会动态加入自动补全与 `/help`,`/skill:` 补全也相同。编辑器上方的状态行会报告 TUI 从会话事件派生的轮次阶段,包括等待首个 token、思考、响应或执行工具;它显示该阶段已经过时间和运行中的步骤总数,每秒刷新,并以 `Enter sends steering, Esc cancels` 提示结尾。Steering 消息等待到达模型期间,会在提示前插入 `N queued ·` 徽标,每条消息排空后随即清除。Ctrl+C 或 Escape 会取消运行中的轮次。工具卡片与注入上下文卡片都把长主体折叠为可配置的头尾预览;Ctrl+O 让工具卡片在折叠预览、完整输出、隐藏三种状态间循环——隐藏阶段把工具卡片从 transcript 中完全去掉,而上下文卡片保持预览,因为注入的指令不属于工具流量。注入上下文卡片把消息渲染为文本,并去掉生产方的外层提醒外框,因此折叠与去外框都不依赖载荷的语法。Ctrl+R 切换 reasoning,Ctrl+L 重绘,Ctrl+D 在空闲时退出。 -`/model` 将建议性的 `ctx.llm` catalog 打开为键盘选择器:Up/Down 移动,Shift+Tab 按显示顺序循环切换适配器为焦点模型公布的推理强度,Enter 选择模型和推理强度,Escape 关闭。适配器未公布默认推理强度时,循环还会包含 `provider default`,该项会清除显式选择;没有可选推理强度元数据的模型会忽略 Shift+Tab。选择器会原样呈现公布的推理强度列表(包括存在时的 `off`),不会合成、自动调整或在模型之间转移推理强度。`/model ` 仍可直接选择无歧义的模型 id,`/model /` 则选择精确目标,并在存在时使用其适配器默认值。已配置目标或最新记录的请求 header 会初始化选择器;由于 catalog 仅提供建议,未列出的当前模型仍会显示。选择仅对本 TUI 会话有效。提示词组装会为一个步骤建立目标快照,替换 `{{provider}}` 和 `{{model}}`,并通过 `agent/request` 应用同一个提供方/模型/推理强度目标;因此组装期间的切换会从后续步骤开始生效。请求 header 会持久记录真正到达模型的目标,未使用的选择则只存在于进程本地。 +`/model` 将建议性的 `ctx.llm` catalog 打开为键盘选择器:列表上方设有一个过滤框,按对每行 `provider/model` 标签、模型名称和描述的大小写不敏感子串匹配来缩小行集,并在高亮行仍通过过滤时保持其选中状态;Up/Down 移动,Shift+Tab 按显示顺序循环切换适配器为焦点模型公布的推理强度,Enter 选择模型和推理强度,Escape 会先清除非空过滤内容,再次按下才关闭选择器。适配器未公布默认推理强度时,循环还会包含 `provider default`,该项会清除显式选择;没有可选推理强度元数据的模型会忽略 Shift+Tab。选择器会原样呈现公布的推理强度列表(包括存在时的 `off`),不会合成、自动调整或在模型之间转移推理强度。`/model ` 仍可直接选择无歧义的模型 id,`/model /` 则选择精确目标,并在存在时使用其适配器默认值。已配置目标或最新记录的请求 header 会初始化选择器;由于 catalog 仅提供建议,未列出的当前模型仍会显示。选择仅对本 TUI 会话有效。提示词组装会为一个步骤建立目标快照,替换 `{{provider}}` 和 `{{model}}`,并通过 `agent/request` 应用同一个提供方/模型/推理强度目标;因此组装期间的切换会从后续步骤开始生效。请求 header 会持久记录真正到达模型的目标,未使用的选择则只存在于进程本地。 `/reload`(实验性,仅开发环境)会重新读取所有基于文件的 loader 配置树,并把 diff 应用到运行中 app:它手动调用 HMR(热模块替换)watcher 的配置路径;上下文中必须有 cordis Loader,否则退化为警告。它只在 agent 空闲时运行,并拒绝 reload 进行期间的再次进入。模块源代码热重载仍由 watcher 持有。挂载 `skills` 服务后,`/skill: [instructions]` 会把该 skill 的指令作为一个 user 轮次加载到会话中;自动补全列出模型可调用的 skill,任何 skill(包括模型禁用的 skill)都可通过精确名称加载。 @@ -32,9 +32,15 @@ Footer 将会话报告的用量汇总为 `↑`;任 `/status` 会向 transcript 添加一张时间点诊断卡片,并在 agent 运行时保持可用。它报告会话 id、标题、工作目录、所选提供方/模型、所选推理强度或默认行为、reasoning 块可见性、agent 状态、事件/轮次/步骤/工具调用计数、精确输入/输出/缓存 token bucket、KV-cache 命中率、token-meter 上下文用量与容量、创建时间和最新事件时间。缺失标题、模型、缓存输入或上下文容量时会明确标记,而非推断。该卡片只存在于终端,不会重复紧凑 footer。 -`/resume` 会针对当前工作区打开全 viewport 键盘选择器,而非居中对话框。获得焦点的搜索字段紧跟搜索 glyph 开始,并发出 pi-tui 的 cursor marker,使终端 IME 组合保持锚定在字段内。候选项按最近记录的活动排序,可按日志支持的标题或会话 id 搜索;每行报告 current/live/persisted 状态、上一轮次结果、近期提供方/模型,以及存在时的持久目标阶段。Up/Down 与 Page Up/Page Down 导航,Enter 恢复,Escape 会先清除非空搜索,再次按下才取消,Ctrl+C 则直接取消。当前会话、已在本运行时中活跃的会话、不可读日志、cwd 不匹配或日志所记提供方没有当前适配器的会话仍会显示,但不可选择。选择时会重复这些检查,并要求当前 agent 空闲,随后 flush 当前会话。TUI 接着停止终端 UI,并调用由宿主持有的可选 `TuiRuntime.handoffResume`;存在 `process.execve` 时,发布的 `dsh` 宿主会对 app 执行 dispose(资源释放)并替换自身进程。恢复操作保留相同的 `SessionId`、transcript、标题、todo 和持久目标;目标激活仍保持解除,TUI 会要求用户确认或执行 `/goal resume`。 +`/resume` 会打开全 viewport 键盘选择器,而非居中对话框。两个作用域覆盖同一候选项集合:打开时所处的当前工作区,以及按 Tab 切换到的所有工作区。搜索字段下方的作用域行会给出当前作用域的名称以及另一个作用域包含的数量,且在所有工作区作用域中每行还会报告自身所属的工作区。切换会清除搜索与选择,使高亮行始终属于可见列表。 -`resumeCommand` 仍是部署持有的回退行为:只有当前会话已持久化后,退出才会打印它;不支持原地 handoff 的宿主会显示所选会话的命令。`{session}` 展开为会话 id。TUI 代码绝不会执行模板或任意 shell 文本。 +获得焦点的搜索字段紧跟搜索 glyph 开始,并发出 pi-tui 的 cursor marker,使终端 IME 组合保持锚定在字段内。候选项按最近记录的活动排序,可按日志支持的标题或会话 id 搜索,在所有工作区作用域中还可按工作区标签搜索;每行报告 current/live/persisted 状态、上一轮次结果、近期提供方/模型,以及存在时的持久目标阶段。Up/Down 与 Page Up/Page Down 导航,Enter 恢复,Escape 会先清除非空搜索,再次按下才取消,Ctrl+C 则直接取消。当前会话、已在本运行时中活跃的会话、不可读日志、没有可运行的已记录工作区的会话,或日志所记提供方没有当前适配器的会话仍会显示,但不可选择;不同于当前工作区的工作区属于作用域而非禁用原因,因为恢复会进入该目录。 + +选择时会重复这些检查,并要求当前 agent 空闲,随后 flush 当前会话。TUI 接着停止终端 UI,并以所选 id 和在预检时重新读取的工作区调用由宿主持有的可选 `TuiRuntime.handoffResume`:文件系统与 shell 工具解析所依据的是进程 cwd,而非恢复出的会话头部,因此宿主必须进入该目录。存在 `process.execve` 时,发布的 `dsh` 宿主会先 chdir 进入该目录,再对 app 执行 dispose 并替换自身进程,并在终端仍可恢复时拒绝不可达的目录。恢复操作保留相同的 `SessionId`、transcript、标题、todo 和持久目标;目标激活仍保持解除,TUI 会要求用户确认或执行 `/goal resume`。 + +退出时打印的行由启动器拥有,不可通过配置指定。启动器在启动上下文上提供 `TUI_GOODBYE_MESSAGE_KEY`(对于随附的 `dsh`,即恢复本会话的命令),释放终端后退出会原样打印它;未提供时退出不打印任何内容。只有启动器知道自己是如何被调用的,因此只有它能给出可用的命令。TUI 在渲染前会转义终端控制字符,且绝不执行该文本。若启动器同时提供 `MAIN_SESSION_ID_KEY`,则会固定已挂载应用绑定的会话,因此恢复功能不受配置层修补影响。 + +启动器可通过在启动上下文上提供 `INITIAL_SKILL_KEY`(skill 名称)来播种全新会话的首轮;聊天就绪后,TUI 会像用户手动键入 `/skill:` 一样自动调用它。随附的 `dsh migrate`/`dsh upgrade` 会设置该键,且仅对全新会话设置,因此恢复的会话绝不会重复调用该 skill;未知名称会以通知形式报告。 ## 配置 @@ -57,7 +63,6 @@ Footer 将会话报告的用量汇总为 `↑`;任 | `showHardwareCursor` | `false` | 在 pi-tui 的 IME marker 处显示硬件 cursor | | `color` | `true` | 应用内置 ANSI palette(参见[颜色](#color)) | | `title` | `DeepSeek Harness` | 终端窗口标题的产品后缀。 | -| `resumeCommand` | 未设置 | 供退出提示和不支持原地 handoff 的宿主使用的 shell 命令模板,其中 `{session}` 会展开为会话 id | ```yaml - id: terminal @@ -70,11 +75,15 @@ Footer 将会话报告的用量汇总为 `↑`;任 fileSearchExcludedDirectories: ['.git', 'node_modules', 'dist'] ``` -任一进程流不是 TTY 时,启动会在挂载前失败。组合 app 必须先挂载 TUI,再挂载由配置创建的 agent,使入口能够观察 `agent-loop/config-start-failed`;完全匹配会话的失败会在全屏模式启动前写出并以状态 1 退出,而不是留下空白终端。dispose 会停止接收扩展请求,卸载 `ctx.tui` 提供方及其依赖插件,中止运行中的命令,移除 TUI 定义,停止 loader,拒绝待处理问题,排空终端输入,恢复终端状态,注销事件 listener 和用户交互提供方,并且绝不会在 HMR 期间退出替换进程。 +任一进程流不是 TTY 时,启动会在挂载前失败。组合 app 必须先挂载 TUI,再挂载由配置创建的 agent,使入口能够观察 `agent-loop/config-start-failed`;完全匹配会话的失败会在全屏模式启动前写出并以状态 1 退出,而不是留下空白终端。dispose(资源释放)会停止接收扩展请求,卸载 `ctx.tui` 提供方及其依赖插件,中止运行中的命令,移除 TUI 定义,停止 loader,拒绝待处理问题,排空终端输入,恢复终端状态,注销事件 listener 和用户交互提供方,并且绝不会在 HMR 期间退出替换进程。 ## 颜色 -Palette 使用标准 16 色 ANSI 前景色和 SGR 属性,每个终端都会将其重新映射到当前配色方案,因此浅色与深色背景下都保持可读。正文使用终端默认前景色,而非固定色调。成组区域(用户提示词、assistant 回复、工具卡片)通过以角色色渲染的粗体带下划线角色标题和空行分隔,而非填充背景块或逐行前缀,因此用鼠标框选复制时不会带上任何左侧竖条或缩进;工具卡片的状态(进行中、错误、成功)由其彩色带下划线的标题字形与标题体现。问题面板使用粗体强调色文本突出活跃行,选择器则使用反色。所有效果都只作用于前景色,因此不会与终端背景冲突。设置 `color: false` 可移除所有样式。 +TUI 发出的所有 SGR 代码都集中在一个表中,即 `components/theme.ts` 内的 `paletteSpec`;`createPalette` 从该表派生包装层,`/palette` 则打印该表,任何组件都不会自行写入转义序列。该表仅包含标准 16 色 ANSI 前景色和 SGR 属性;每个终端都会将它们重新映射到当前配色方案,因此 TUI 在浅色与深色背景下都保持可读——启动 banner 的品牌渐变是唯一一个有意保留的例外。正文使用终端默认前景色,而非固定色调。 + +每种视觉语义只对应一个角色:`dim` 是唯一的弱化色调,`accent` 是唯一的强调色,`success` 和 `error` 还分别充当 diff 的新增行与删除行。颜色和属性分属不同类型,因此 `bold(accent(x))` 可以通过编译,`accent(error(x))` 则不行——SGR 没有颜色栈;在一种颜色内嵌套另一种颜色时,内层颜色闭合时会静默丢弃外层颜色。各属性占用彼此独立的 SGR 组,可以按任一顺序与任何颜色组合。运行 `/palette` 可查看每个角色在你的终端上的实际渲染效果及其 SGR 码对。 + +成组区域(用户提示词、assistant 回复、工具卡片)通过以角色色渲染的粗体带下划线角色标题和空行分隔,而非填充背景块或逐行前缀,因此用鼠标框选复制时不会带上任何左侧竖条或缩进;工具卡片的状态(进行中、错误、成功)由其彩色带下划线的标题字形与标题体现。在工具卡片内部,整个正文——presenter 标题、终端 `$` 命令与 cwd,以及工具自身的输出——统一以同一种暗色渲染,因此只有带状态色的表头携带颜色,正文读作一个整体弱化的区块,而不是一串互相竞争的色调;注入上下文卡片的正文与其表头也是同一种色调。diff 卡片的 `+`/`-` 行与 `[signal …]` 标记保留颜色,因为那里的颜色本身就是语义,而非强调。问题面板使用粗体强调色文本突出活跃行,选择器则使用反色。所有效果都只作用于前景色,因此不会与终端背景冲突。设置 `color: false` 可移除所有样式。 ## 模型体验 @@ -156,7 +165,7 @@ Paths prefixed with @ are files explicitly referenced by the user. Use the read ## 已知限制与延期工作 -- **恢复功能没有跨进程会话锁**:选择器会拒绝本运行时中已知处于活跃状态的会话,但另一个进程可以在 handoff 之前或期间恢复同一持久 id。能够运行并发宿主的部署必须在 TUI 外协调所有权。 +- **恢复功能没有跨进程会话锁**:选择器会拒绝本运行时中已知处于活跃状态的会话,但另一个进程可以在 handoff 之前或期间恢复同一持久 id。所有工作区作用域让这一情形一步即可触及,因为另一个宿主正在其他目录驱动的会话现在也可被选中。能够运行并发宿主的部署必须在 TUI 外协调所有权。 - **一个已配置会话持有 transcript 和编辑器**:其他 agent 的问题仍可使用共享 overlay 提供方,但会话渲染与提示词输入仍绑定到 `sessionId`。 - **工具卡片是文本终端展示**:终端、diff 与通用卡片使用工具持有的标题/内容,但会话内容目前没有用于内联图像渲染的图像块。 - **有意不支持非 TTY 运行**:需要自动化的 app bundle 必须组合单次执行或服务器入口(`dsh-cli-demo`、`dsh-acp`),而不能依赖内部回退。 diff --git a/packages/ui/tui/src/chat/resume.ts b/packages/ui/tui/src/chat/resume.ts index 2f0fdd423c..9521bd7368 100644 --- a/packages/ui/tui/src/chat/resume.ts +++ b/packages/ui/tui/src/chat/resume.ts @@ -1,26 +1,23 @@ /** * Session-resume sub-controller for the interactive chat channel: the * `/resume` selector, per-candidate summary reads that tolerate a corrupt - * neighbor, the pre-handoff preflight, the terminal handoff itself, and the - * durable resume-hint command printed on exit. + * neighbor, the pre-handoff preflight, and the terminal handoff itself. * @module @deepseek-ai/dsh-tui/chat/resume */ import type { TUI } from '@earendil-works/pi-tui' import type { Agent, AgentStatus } from '@deepseek-ai/dsh-agent' import { errorChain } from '@deepseek-ai/dsh-llm' -import { SessionId, type SessionHeader } from '@deepseek-ai/dsh-session' +import type { SessionId } from '@deepseek-ai/dsh-session' import type { SessionLogSnapshot, SessionQueryService, SessionRecord, } from '@deepseek-ai/dsh-session-query' -import type { SessionPersistence } from '@deepseek-ai/dsh-session-persistence' import type { HintEditor } from './helpers.ts' import { formatCwd } from './helpers.ts' import type { TuiOverlaySession } from '../extension/types.ts' import type { TuiRuntime } from '../runtime.ts' -import type { Config } from '../config.ts' import { ResumePicker, summarizeResumeCandidate, @@ -31,9 +28,7 @@ import type { ChannelNotice, ChatChannelDeps } from './channel.ts' /** Collaborators the resume controller needs from the chat channel. */ export interface ResumeControllerDeps extends ChatChannelDeps, ChannelNotice { readonly agent: Agent - readonly config: Config readonly runtime: TuiRuntime - readonly persistence: SessionPersistence | undefined readonly sessionQuery: SessionQueryService | undefined readonly ui: TUI readonly editor: HintEditor @@ -43,47 +38,27 @@ export interface ResumeControllerDeps extends ChatChannelDeps, ChannelNotice { /** Session-resume controller for one chat channel. */ export interface ResumeController { - /** Open the current-workspace searchable session selector. */ + /** Open the searchable session selector, scoped to this workspace until the user widens it. */ showResume(): void - /** - * The resume command for the current session — the configured template with - * every `{session}` filled — but only once the session is durably persisted; - * `undefined` otherwise. - */ - currentResumeCommand(): Promise } /** * Build the session-resume controller for one chat channel. * @param deps - channel collaborators, terminal handles, and optional services. - * @returns the controller wired to the `/resume` command and exit hint. + * @returns the controller wired to the `/resume` command. */ export function createResumeController(deps: ResumeControllerDeps): ResumeController { const { - ctx, agent, config, runtime, resolved, palette, overlayManager, - persistence, sessionQuery, ui, editor, + ctx, agent, runtime, resolved, palette, overlayManager, + sessionQuery, ui, editor, } = deps let resumeOverlay: TuiOverlaySession | undefined let resumeInFlight = false let resumeScan = 0 - /** - * Persisted sessions for this workspace, newest first. Empty when no - * persistence backend is mounted or a listing failure would otherwise block - * exit or crash `/resume`; the resume hint is best-effort convenience. - */ - const listWorkspaceSessions = async (): Promise => { - if (persistence === undefined) return [] - let all: readonly SessionHeader[] - try { - all = await persistence.list() - } catch { - // A listing failure must never block terminal exit or crash `/resume`. - return [] - } - return all - .filter(header => header.cwd === agent.session.header.cwd) - } + /** Label any session's own workspace the way the prompt labels the current one. */ + const workspaceLabel = (cwd: string | undefined): string => + runtime.formatCwd?.(cwd) ?? formatCwd(cwd) /** Build one display candidate without letting a corrupt neighbor abort the selector. */ const readResumeCandidate = async ( @@ -109,6 +84,7 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro agent.session.id, agent.session.header.cwd, providers, + workspaceLabel, ) } catch (error: unknown) { return { @@ -116,13 +92,18 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro title: 'Unreadable session', lastActivityAt: record.header.createdAt, lastTurn: 'log unavailable', + currentWorkspace: record.header.cwd === agent.session.header.cwd, + workspaceLabel: workspaceLabel(record.header.cwd), disabledReason: `session cannot be loaded: ${errorChain(error)}`, } } } - /** Re-read every mutable precondition immediately before terminal handoff. */ - const preflightResume = async (sessionId: SessionId): Promise => { + /** + * Re-read every mutable precondition immediately before terminal handoff and + * resolve the exact identity and workspace the host will re-exec into. + */ + const preflightResume = async (sessionId: SessionId): Promise<{ id: SessionId; cwd: string }> => { /* v8 ignore next -- only showResume can call this closure, after proving the optional service exists */ if (sessionQuery === undefined) throw new Error('Resume is unavailable: session query is not mounted.') const initialStatus = deps.agentStatus() @@ -134,9 +115,12 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro new Set(ctx.llm.listProviders().map(provider => provider.id)), ) if (candidate.disabledReason !== undefined) throw new Error(candidate.disabledReason) + const cwd = candidate.record.header.cwd + /* v8 ignore next -- summarizeResumeCandidate disables a cwd-less record, so the check above already rejected it */ + if (cwd === undefined) throw new Error(`Session "${sessionId}" has no recorded workspace to resume in.`) const finalStatus = deps.agentStatus() if (finalStatus !== 'idle') throw new Error(`Resume requires an idle agent (status: ${finalStatus}).`) - return candidate + return { id: candidate.record.header.id, cwd } } const handoffResume = async (candidate: ResumeCandidate, overlay: TuiOverlaySession): Promise => { @@ -147,13 +131,9 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro const checked = await preflightResume(candidate.record.header.id) const hostHandoff = runtime.handoffResume if (hostHandoff === undefined) { - const template = config.resumeCommand - const fallback = template?.replaceAll('{session}', checked.record.header.id) await overlay.close() resumeOverlay = undefined - deps.appendNotice(fallback === undefined - ? 'Session is resumable, but this host cannot hand it off in place.' - : `This host cannot hand off in place. Exit and run: ${fallback}`, 'warning') + deps.appendNotice('Session is resumable, but this host cannot hand it off in place.', 'warning') return } /* v8 ignore next -- shutdown during preflight invalidates an awaited service read or reaches this guard */ @@ -169,7 +149,10 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro if (deps.isDisposed()) return ui.stop() terminalReleased = true - await hostHandoff(checked.record.header.id) + // The host re-execs into the session's own workspace: process cwd, not the + // restored session header, is what the filesystem and shell tools resolve + // against. + await hostHandoff(checked.id, checked.cwd) throw new Error('resume host returned without replacing the process') } catch (error: unknown) { if (!deps.isDisposed()) { @@ -189,12 +172,6 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro } return { - currentResumeCommand: async (): Promise => { - if (config.resumeCommand === undefined) return undefined - const sessions = await listWorkspaceSessions() - if (!sessions.some(header => header.id === agent.session.id)) return undefined - return config.resumeCommand.replaceAll('{session}', agent.session.id) - }, showResume(): void { if (agent.status !== 'idle') { deps.appendNotice('Resume requires the current turn to finish or be cancelled first.', 'warning') @@ -208,9 +185,10 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro void resumeOverlay?.close() void sessionQuery.listSessions().then(async (records) => { if (deps.isDisposed() || scan !== resumeScan) return - const workspace = records.filter(record => record.header.cwd === agent.session.header.cwd) + // Every workspace in the store is summarized; the picker owns the + // current-workspace/all-workspaces scope split over the whole set. const providers = new Set(ctx.llm.listProviders().map(provider => provider.id)) - const candidates = await Promise.all(workspace.map(record => readResumeCandidate(record, providers))) + const candidates = await Promise.all(records.map(record => readResumeCandidate(record, providers))) candidates.sort((a, b) => b.lastActivityAt - a.lastActivityAt || a.record.header.id.localeCompare(b.record.header.id)) if (deps.isDisposed() || scan !== resumeScan) return @@ -218,7 +196,7 @@ export function createResumeController(deps: ResumeControllerDeps): ResumeContro create: host => new ResumePicker( candidates, resolved.maxResumeOptions, - runtime.formatCwd?.(agent.session.header.cwd) ?? formatCwd(agent.session.header.cwd), + workspaceLabel(agent.session.header.cwd), () => host.viewport.rows, palette, (candidate) => { void handoffResume(candidate, session) }, diff --git a/packages/ui/tui/src/chat/timing.ts b/packages/ui/tui/src/chat/timing.ts index 13477adfa0..0aff3bc736 100644 --- a/packages/ui/tui/src/chat/timing.ts +++ b/packages/ui/tui/src/chat/timing.ts @@ -290,7 +290,7 @@ export function fadeGlyph( return `\x1b[38;2;${r};${g};${b}m${glyph}\x1b[39m` } if (!visible) return ' ' - return colorEnabled ? palette.muted(glyph) : glyph + return colorEnabled ? palette.dim(glyph) : glyph } /** diff --git a/packages/ui/tui/src/components/dialogs.ts b/packages/ui/tui/src/components/dialogs.ts index 370be088b1..5e9237574a 100644 --- a/packages/ui/tui/src/components/dialogs.ts +++ b/packages/ui/tui/src/components/dialogs.ts @@ -205,7 +205,7 @@ export class StatusCardComponent implements Component { if (groupIndex > 0) body.push('') for (const [label, value] of group) { const plainLabel = truncateToWidth(`${label}:`, labelWidth, '') - const prefix = ` ${this.palette.muted(plainLabel.padEnd(labelWidth))} ` + const prefix = ` ${this.palette.dim(plainLabel.padEnd(labelWidth))} ` const continuation = ' '.repeat(1 + labelWidth + 2) const valueWidth = Math.max(1, innerWidth - visibleWidth(prefix)) const wrapped = wrapTextWithAnsi(value, valueWidth) @@ -281,9 +281,10 @@ export function renderDialog( return lines } -/** Keyboard model selector rendered as a bordered overlay, with per-model reasoning-effort cycling. */ +/** Keyboard model selector rendered as a bordered overlay, with a filter box and per-model reasoning-effort cycling. */ export class ModelDialog implements Component { - private readonly list: SelectList + private list: SelectList + private readonly filter = new Input() private readonly items: Map private readonly choices: Map private readonly efforts: Map @@ -292,10 +293,10 @@ export class ModelDialog implements Component { constructor( choices: readonly ModelChoice[], current: AgentLlmTarget | undefined, - maxVisible: number, + private readonly maxVisible: number, private readonly palette: Palette, - done: (selection: ModelDialogSelection) => void, - cancel: () => void, + private readonly done: (selection: ModelDialogSelection) => void, + private readonly cancel: () => void, ) { this.items = new Map() this.choices = new Map() @@ -317,18 +318,38 @@ export class ModelDialog implements Component { description: this.describeChoice(choice, isCurrent), }) } - this.list = new SelectList([...this.items.values()], maxVisible, dialogSelectTheme(palette)) - const currentIndex = current === undefined - ? 0 - : choices.findIndex(choice => choice.provider === current.provider && choice.model === current.model) - this.list.setSelectedIndex(currentIndex) - this.list.onSelect = (item) => { - const selected = choices.find(choice => targetLabel(choice) === item.value) - /* v8 ignore next -- SelectList only returns values built from `choices`. */ - if (selected === undefined) return - done({ choice: selected, reasoningEffort: this.efforts.get(item.value) }) - } - this.list.onCancel = cancel + this.list = this.buildList(this.currentValue) + } + + /** Build a SelectList over the currently filtered items, selecting `selectValue` when present. */ + private buildList(selectValue: string | undefined): SelectList { + const items = this.filteredItems() + const list = new SelectList(items, this.maxVisible, dialogSelectTheme(this.palette)) + const index = selectValue === undefined ? 0 : items.findIndex(item => item.value === selectValue) + list.setSelectedIndex(Math.max(0, index)) + list.onSelect = (item) => { this.confirm(item) } + list.onCancel = this.cancel + return list + } + + /** Items matching the filter box, as a case-insensitive substring over the label, model name, and description. */ + private filteredItems(): SelectItem[] { + const query = this.filter.getValue().trim().toLocaleLowerCase() + if (query === '') return [...this.items.values()] + return [...this.items.values()].filter((item) => { + const choice = this.choices.get(item.value) + /* v8 ignore next -- items and choices share the same keys. */ + if (choice === undefined) return false + return [item.value, choice.modelName, choice.description ?? ''] + .some(field => field.toLocaleLowerCase().includes(query)) + }) + } + + private confirm(item: SelectItem): void { + const selected = this.choices.get(item.value) + /* v8 ignore next -- SelectList only returns values built from `choices`. */ + if (selected === undefined) return + this.done({ choice: selected, reasoningEffort: this.efforts.get(item.value) }) } private describeChoice(choice: ModelChoice, isCurrent: boolean): string { @@ -362,24 +383,50 @@ export class ModelDialog implements Component { } invalidate(): void { + this.filter.invalidate() this.list.invalidate() } handleInput(data: string): void { if (matchesKey(data, Key.shift(Key.tab))) { this.cycleReasoningEffort() - } else { + } else if (matchesKey(data, Key.escape)) { + if (this.filter.getValue() === '') this.cancel() + else { + this.filter.setValue('') + this.list = this.buildList(undefined) + } + } else if ( + matchesKey(data, Key.up) + || matchesKey(data, Key.down) + || matchesKey(data, Key.enter) + ) { this.list.handleInput(data) + } else { + const previous = this.filter.getValue() + this.filter.focused = true + this.filter.handleInput(data) + if (this.filter.getValue() !== previous) { + const selected = this.list.getSelectedItem() + this.list = this.buildList(selected?.value) + } } this.invalidate() } render(width: number): string[] { const innerWidth = Math.max(1, width - 4) + this.filter.focused = true + const results = this.filteredItems() + const filterContent = truncateToWidth(this.filter.render(innerWidth).join(''), innerWidth, '') return renderDialog('Select model', [ - ...this.list.render(innerWidth), + filterContent, '', - this.palette.dim('↑/↓ navigate • Shift+Tab reasoning • Enter select • Esc cancel'), + ...results.length === 0 + ? [this.palette.dim(' No models match the filter')] + : this.list.render(innerWidth), + '', + this.palette.dim('type to filter • ↑/↓ move • Shift+Tab reasoning • Enter select • Esc'), ], width, this.palette) } } @@ -396,6 +443,10 @@ export interface ResumeCandidate { title: string lastActivityAt: number lastTurn: string + /** Whether the session's workspace is the one the current session runs in, which selects the picker scope that lists it. */ + currentWorkspace: boolean + /** The session's own workspace as a prompt-style label; the all-workspaces scope shows it per row. */ + workspaceLabel: string route?: ResumeRoute goalPhase?: GoalPhase disabledReason?: string @@ -429,12 +480,15 @@ function resumeRoute(snapshot: SessionLogSnapshot): ResumeRoute | undefined { /** * Build one resume selector row from a record and its log snapshot, deriving the - * title, route, goal phase, and any reason the session cannot be resumed here. + * title, route, goal phase, workspace scope, and any reason the session cannot + * be resumed here. A workspace other than the current one is a scope, not a + * disabled reason: resuming it hands the process off into that directory. * @param record - The session record. * @param snapshot - The session's log snapshot. * @param currentId - The current session id. - * @param cwd - The current workspace directory. + * @param cwd - The CURRENT session's workspace, which decides the picker scope this row falls in. * @param availableProviders - Providers registered in this runtime. + * @param formatWorkspace - Renders THIS record's own cwd as its prompt-style label. * @returns The summarized resume candidate. */ export function summarizeResumeCandidate( @@ -443,6 +497,7 @@ export function summarizeResumeCandidate( currentId: SessionId, cwd: string | undefined, availableProviders: ReadonlySet, + formatWorkspace: (cwd: string | undefined) => string, ): ResumeCandidate { const title = foldSessionTitle(snapshot.events)?.title ?? 'Untitled session' const route = resumeRoute(snapshot) @@ -450,7 +505,7 @@ export function summarizeResumeCandidate( let disabledReason: string | undefined if (record.header.id === currentId) disabledReason = 'current session' else if (record.live) disabledReason = 'session is already live in this runtime' - else if (record.header.cwd !== cwd) disabledReason = 'different workspace' + else if (record.header.cwd === undefined) disabledReason = 'session has no recorded workspace' else if (route !== undefined && !availableProviders.has(route.provider)) { disabledReason = `session is complete, but route is currently unavailable (${route.provider}/${route.model})` } @@ -459,6 +514,8 @@ export function summarizeResumeCandidate( title, lastActivityAt: snapshot.events.at(-1)?.time ?? snapshot.session.createdAt, lastTurn: resumeTurnLabel(snapshot), + currentWorkspace: record.header.cwd === cwd, + workspaceLabel: formatWorkspace(record.header.cwd), ...route === undefined ? {} : { route }, /* v8 ignore next -- goal-bearing resume records are covered by the goal/session integration surface. */ ...foldedGoal === undefined ? {} : { goalPhase: foldedGoal.phase }, @@ -466,12 +523,23 @@ export function summarizeResumeCandidate( } } -/** Full-viewport keyboard selector over detached, preflighted resume summaries. */ +/** Which workspaces the resume picker currently lists. */ +export type ResumeScope = 'workspace' | 'all' + +/** + * Full-viewport keyboard selector over detached, preflighted resume summaries. + * + * Two scopes over one candidate set: `workspace` (the default) lists only the + * current session's workspace, `all` lists every workspace and labels each row + * with its own. Tab toggles between them; the search query and selection reset + * on a scope change so the highlighted row always belongs to the visible list. + */ export class ResumePicker implements Component, Focusable { private readonly search = new Input() private pasteBuffer: string | undefined private selectedIndex = 0 private error = '' + private scope: ResumeScope = 'workspace' focused = false constructor( @@ -488,15 +556,29 @@ export class ResumePicker implements Component, Focusable { this.search.invalidate() } + /** Candidates in the active scope, before the search query narrows them. */ + private scoped(): ResumeCandidate[] { + return this.scope === 'all' + ? [...this.candidates] + : this.candidates.filter(candidate => candidate.currentWorkspace) + } + private filtered(): ResumeCandidate[] { const query = this.search.getValue().trim().toLocaleLowerCase() - if (query === '') return [...this.candidates] - return this.candidates.filter(candidate => candidate.title.toLocaleLowerCase().includes(query) - || candidate.record.header.id.toLocaleLowerCase().includes(query)) + const scoped = this.scoped() + if (query === '') return scoped + // The workspace label only distinguishes rows once it is on screen, so it + // joins the searchable text exactly in the scope that shows it. + return scoped.filter(candidate => candidate.title.toLocaleLowerCase().includes(query) + || candidate.record.header.id.toLocaleLowerCase().includes(query) + || (this.scope === 'all' && candidate.workspaceLabel.toLocaleLowerCase().includes(query))) } private visibleCandidateCount(): number { - const candidateBudget = Math.max(1, Math.floor((Math.max(1, this.viewportRows()) - 13) / 4)) + // The all-workspaces scope adds a per-row workspace line, so a row costs + // one more terminal row there than in the single-workspace scope. + const rowHeight = this.scope === 'all' ? 5 : 4 + const candidateBudget = Math.max(1, Math.floor((Math.max(1, this.viewportRows()) - 13) / rowHeight)) return Math.min(this.maxVisible, candidateBudget) } @@ -553,6 +635,11 @@ export class ResumePicker implements Component, Focusable { Math.max(0, filtered.length - 1), this.selectedIndex + this.visibleCandidateCount(), ) + } else if (matchesKey(data, Key.tab)) { + this.scope = this.scope === 'workspace' ? 'all' : 'workspace' + this.search.setValue('') + this.selectedIndex = 0 + this.error = '' } else if (matchesKey(data, Key.enter)) { const selected = filtered[this.selectedIndex] if (selected === undefined) this.error = 'No session matches this search.' @@ -570,6 +657,21 @@ export class ResumePicker implements Component, Focusable { this.invalidate() } + /** + * The scope line under the search box: the active scope with the current + * workspace it means, and the inactive scope with the count Tab would reveal. + */ + private renderScopeLine(): string { + const inWorkspace = this.candidates.filter(candidate => candidate.currentWorkspace).length + const active = this.scope === 'workspace' + ? `this workspace ${displayText(this.workspaceLabel)}` + : `all workspaces (${this.candidates.length})` + const other = this.scope === 'workspace' + ? `all workspaces (${this.candidates.length})` + : `this workspace (${inWorkspace})` + return `${this.palette.accent(active)}${this.palette.dim(` ⇥ ${other}`)}` + } + render(width: number): string[] { this.search.focused = this.focused const height = Math.max(1, this.viewportRows()) @@ -594,7 +696,7 @@ export class ResumePicker implements Component, Focusable { `${indent}${this.palette.dim('│')} ${clippedSearch}${' '.repeat(Math.max(0, searchInnerWidth - visibleWidth(clippedSearch)))} ${this.palette.dim('│')}`, `${indent}${this.palette.dim(`╰${'─'.repeat(Math.max(0, contentWidth - 2))}╯`)}`, '', - `${indent}${this.palette.muted(displayText(this.workspaceLabel))}`, + `${indent}${this.renderScopeLine()}`, '', ) @@ -620,8 +722,13 @@ export class ResumePicker implements Component, Focusable { const route = candidate.route === undefined ? 'route unavailable' : `${candidate.route.provider}/${candidate.route.model}` /* v8 ignore next -- only goal-bearing resume records add this integration-owned suffix. */ const goal = candidate.goalPhase === undefined ? '' : ` · goal ${candidate.goalPhase}` - push(this.palette.muted(` ${new Date(candidate.lastActivityAt).toISOString()} · ${candidate.lastTurn} · ${route}${goal}`)) + push(this.palette.dim(` ${new Date(candidate.lastActivityAt).toISOString()} · ${candidate.lastTurn} · ${route}${goal}`)) push(this.palette.dim(` ${status} · ${displayText(candidate.record.header.id)}`)) + // Only the all-workspaces scope mixes directories, so the per-row + // workspace is redundant in the scope that already names one. + if (this.scope === 'all') { + push(this.palette.dim(` workspace ${displayText(candidate.workspaceLabel)}`)) + } if (candidate.disabledReason !== undefined) { push(this.palette.warning(` unavailable: ${displayText(candidate.disabledReason)}`)) } @@ -632,7 +739,7 @@ export class ResumePicker implements Component, Focusable { push(this.palette.error(displayText(this.error))) } - const footer = `${indent}${this.palette.dim('Type to search • ↑/↓ navigate • Enter resume • Esc clear/cancel')}` + const footer = `${indent}${this.palette.dim('Type to search • ↑/↓ navigate • Tab scope • Enter resume • Esc clear/cancel')}` while (lines.length < height - 2) lines.push('') lines.push(footer, '') return lines.slice(0, height) @@ -720,7 +827,7 @@ export class QuestionDialog implements Component, Focusable { const innerWidth = Math.max(1, width - 4) const header = `Question ${this.position}/${this.total} (${this.unanswered} unanswered)${this.question.header === undefined ? '' : ` · ${displayText(this.question.header)}`}` const lines = [ - this.palette.muted(header), + this.palette.dim(header), ...wrapTextWithAnsi(this.palette.text(displayText(this.question.question)), innerWidth), ] const push = (line: string): void => { lines.push(line) } @@ -764,7 +871,7 @@ export class QuestionDialog implements Component, Focusable { : left const description = option.description === undefined ? '' - : `${' '.repeat(Math.max(1, descriptionColumn - visibleWidth(left)))}${this.palette.muted(displayText(option.description))}` + : `${' '.repeat(Math.max(1, descriptionColumn - visibleWidth(left)))}${this.palette.dim(displayText(option.description))}` push(`${leftStyled}${description}`) } if (options.length > this.maxVisible) push(this.palette.dim(`${this.selectedIndex + 1}/${options.length}`)) diff --git a/packages/ui/tui/src/components/theme.ts b/packages/ui/tui/src/components/theme.ts index 1ea75b437f..269a7c28e8 100644 --- a/packages/ui/tui/src/components/theme.ts +++ b/packages/ui/tui/src/components/theme.ts @@ -11,67 +11,149 @@ import type { TerminalColorScheme, } from '@earendil-works/pi-tui' -/** Theme-agnostic role colors and SGR attribute wrappers. */ +/** + * Text carrying exactly one palette color. Branded so the compiler rejects + * wrapping it in a second color: SGR has no color stack, so an inner span's + * close reverts to the default foreground rather than the outer color, which + * silently drops the outer color for the remainder of the line. + */ +export type Colored = string & { readonly __coloredBy: unique symbol } + +/** + * Text a color may still be applied to: a bare string, or one already carrying + * SGR attributes. Attributes (bold, italic, underline, strike, reverse) occupy + * independent SGR groups from the foreground color, so they compose in either + * order without either side clobbering the other. + */ +export type Colorable = string & { readonly __coloredBy?: undefined } + +/** Applies one color role; rejects input that already carries a color. */ +export type ColorRole = (text: Colorable) => Colored + +/** Applies one SGR attribute; accepts colored or uncolored text and preserves its color. */ +export type AttributeRole = (text: T) => T + +/** + * Theme-agnostic role colors and SGR attribute wrappers. + * + * One role per visual meaning: `dim` is the single recessed tone, `accent` the + * single emphasis color, and `success`/`error` double as a diff's added/removed + * pair. Roles that resolved to the same escape were merged rather than kept as + * aliases, so a reader cannot pick a name that silently renders as another. + * + * Colors and attributes are separately typed: `bold(accent(x))` and + * `accent(bold(x))` both compile, while `accent(error(x))` does not. + */ export interface Palette { - accent: (text: string) => string - accent2: (text: string) => string - text: (text: string) => string - muted: (text: string) => string - dim: (text: string) => string - success: (text: string) => string - warning: (text: string) => string - error: (text: string) => string - code: (text: string) => string - added: (text: string) => string - removed: (text: string) => string - bold: (text: string) => string - italic: (text: string) => string - underline: (text: string) => string - strike: (text: string) => string + accent: ColorRole + /** The terminal's own default foreground; still a color, so it does not stack. */ + text: ColorRole + /** The one recessed tone, below `text`: tool-card bodies, chrome, reasoning, footers. */ + dim: ColorRole + success: ColorRole + warning: ColorRole + error: ColorRole + code: ColorRole + bold: AttributeRole + italic: AttributeRole + underline: AttributeRole + strike: AttributeRole /** Reverse video for the active selection; swaps the theme's own fg/bg so it reads on any scheme. */ - selected: (text: string) => string + selected: AttributeRole } -function ansi(open: string, close: string, enabled: boolean): (text: string) => string { - return enabled ? text => `\x1b[${open}m${text}\x1b[${close}m` : text => text +/** Names of the palette's color roles, in the order `/palette` prints them. */ +export const COLOR_ROLES = ['text', 'dim', 'accent', 'code', 'success', 'warning', 'error'] as const + +/** Names of the palette's attribute roles, in the order `/palette` prints them. */ +export const ATTRIBUTE_ROLES = ['bold', 'italic', 'underline', 'strike', 'selected'] as const + +/** One role's SGR parameters and the reason it carries them. */ +export interface RoleSpec { + /** SGR parameters that open the span, without the `ESC [` prefix or `m` suffix. */ + readonly open: string + /** SGR parameters that close it; MUST reset every group `open` sets. */ + readonly close: string + /** What the role means, shown by `/palette`. */ + readonly purpose: string } /** - * Theme-agnostic palette built from the standard 16-color ANSI set plus SGR - * attributes, which every terminal remaps to its active color scheme. Body - * `text` stays the terminal's default foreground so it reads on light and dark - * backgrounds alike; grouping uses foreground-only bold, underlined role - * headers and reverse video rather than fixed background fills or per-line - * prefixes, so a transcript drag-select copies message text without stray - * glyphs. + * Every SGR code the TUI is allowed to emit, keyed by role. This table is the + * single source: {@link createPalette} derives the wrappers from it and + * `/palette` prints it, so a role cannot exist in one and not the other, and no + * component hand-writes an escape. + * + * Only the standard 16-color set and SGR attributes appear here. Terminals remap + * those to the user's active theme, so the TUI stays legible on any background; + * a fixed 24-bit color would not. The brand gradient is the one deliberate + * exception ({@link gradientText}). + * + * @param scheme - Active terminal color scheme; only `code` differs between them. + * @returns The SGR spec for every color and attribute role. + */ +export function paletteSpec(scheme: TerminalColorScheme): { + readonly colors: Readonly> + readonly attributes: Readonly> +} { + return { + colors: { + // The terminal's own foreground, emitted as no escape at all: ordinary body + // text must inherit whatever the user's theme uses. + text: { open: '', close: '', purpose: 'Body text, the terminal default foreground' }, + // SGR 2 over an explicit default foreground, closing both groups it sets. + // The attribute fades relative to whatever the terminal's own foreground is, + // which is the only way to land *below* `text` on both schemes: ANSI 90 + // (bright black) is a fixed hue that many light themes render heavier than + // their default foreground, which made every "dim" surface the most + // prominent text on screen. + dim: { open: '2;39', close: '22;39', purpose: 'The one recessed tone: tool bodies, chrome, footers' }, + accent: { open: '95', close: '39', purpose: 'The one emphasis color: role headers, prompt, borders' }, + // ANSI 36 (cyan) is difficult to read on a light background — use ANSI 34 + // (blue) which is legible on both light and dark schemes. + code: scheme === 'light' + ? { open: '34', close: '39', purpose: 'Inline code and code blocks in prose' } + : { open: '36', close: '39', purpose: 'Inline code and code blocks in prose' }, + success: { open: '32', close: '39', purpose: 'Succeeded calls, and a diff\'s added lines' }, + warning: { open: '33', close: '39', purpose: 'Pending calls and warnings' }, + error: { open: '31', close: '39', purpose: 'Failures, signals, and a diff\'s removed lines' }, + }, + attributes: { + bold: { open: '1', close: '22', purpose: 'Emphasis; composes with any color' }, + italic: { open: '3', close: '23', purpose: 'Reasoning text' }, + underline: { open: '4', close: '24', purpose: 'Role-header banding' }, + strike: { open: '9', close: '29', purpose: 'Struck-through Markdown' }, + selected: { open: '7', close: '27', purpose: 'Reverse video for the active selection' }, + }, + } +} + +/** + * Wrap text in an SGR pair, or pass it through when color is disabled. + * An empty `open` emits nothing, so the `text` role costs no escape. + */ +function ansi(spec: RoleSpec, enabled: boolean): (text: string) => string { + if (!enabled || spec.open === '') return text => text + return text => `\x1b[${spec.open}m${text}\x1b[${spec.close}m` +} + +/** + * Theme-agnostic palette derived from {@link paletteSpec}. Body `text` stays the + * terminal's default foreground so it reads on light and dark backgrounds alike; + * grouping uses foreground-only bold, underlined role headers and reverse video + * rather than fixed background fills or per-line prefixes, so a transcript + * drag-select copies message text without stray glyphs. * * @param enabled - Whether ANSI is emitted at all. - * @param scheme - Active terminal color scheme; adjusts dim and code roles. + * @param scheme - Active terminal color scheme; adjusts the code role. * @returns The role palette for the given scheme. */ export function createPalette(enabled: boolean, scheme: TerminalColorScheme = 'dark'): Palette { - return { - accent: ansi('94', '39', enabled), - accent2: ansi('95', '39', enabled), - text: text => text, - muted: ansi('90', '39', enabled), - // SGR 2 (dim) lightens text on a light background — substitute ANSI 90 - // (bright black / gray) which renders as a readable muted tone on any scheme. - dim: scheme === 'light' ? ansi('90', '39', enabled) : ansi('2', '22', enabled), - success: ansi('32', '39', enabled), - warning: ansi('33', '39', enabled), - error: ansi('31', '39', enabled), - // ANSI 36 (cyan) is difficult to read on a light background — use - // ANSI 34 (blue) which is legible on both light and dark schemes. - code: scheme === 'light' ? ansi('34', '39', enabled) : ansi('36', '39', enabled), - added: ansi('32', '39', enabled), - removed: ansi('31', '39', enabled), - bold: ansi('1', '22', enabled), - italic: ansi('3', '23', enabled), - underline: ansi('4', '24', enabled), - strike: ansi('9', '29', enabled), - selected: ansi('7', '27', enabled), - } + const spec = paletteSpec(scheme) + const roles = {} as Record + for (const name of COLOR_ROLES) roles[name] = ansi(spec.colors[name], enabled) + for (const name of ATTRIBUTE_ROLES) roles[name] = ansi(spec.attributes[name], enabled) + return roles as unknown as Palette } /** @@ -145,8 +227,8 @@ export function markdownTheme(palette: Palette): MarkdownTheme { // pi-tui presents both fence rows through this callback. Keep the opening // language label, but hide Markdown syntax and the otherwise-empty close. codeBlockBorder: text => palette.dim(text.slice(3)), - quote: text => palette.muted(text), - quoteBorder: text => palette.accent2(text), + quote: text => palette.dim(text), + quoteBorder: text => palette.accent(text), hr: text => palette.dim(text), listBullet: text => palette.accent(text), bold: text => palette.bold(text), @@ -165,7 +247,7 @@ export function selectTheme(palette: Palette): SelectListTheme { return { selectedPrefix: palette.accent, selectedText: palette.accent, - description: palette.muted, + description: palette.dim, scrollInfo: palette.dim, noMatch: palette.warning, } @@ -182,3 +264,49 @@ export function dialogSelectTheme(palette: Palette): SelectListTheme { selectedText: text => palette.selected(palette.accent(text)), } } + +/** Sample text every `/palette` row renders, long enough to judge a tone against its neighbours. */ +const PALETTE_SAMPLE = 'The quick brown fox 0123' + +/** + * Render every palette role as a labelled sample row, each painted by the role + * it names, so a reader compares the actual tones their terminal produces rather + * than reading SGR numbers. Colors print first and attributes second because the + * two groups compose in that order; every row shows its SGR pair so a mismatch + * between the table and the screen is visible. + * + * @param palette - Active role palette, used to paint each sample. + * @param scheme - Active color scheme, reported in the heading and selecting the spec. + * @param colorEnabled - Whether ANSI is emitted; reported so an unstyled listing is not confusing. + * @returns The rendered rows, without a trailing blank. + */ +export function renderPalette( + palette: Palette, + scheme: TerminalColorScheme, + colorEnabled: boolean, +): string[] { + const spec = paletteSpec(scheme) + const width = Math.max(...[...COLOR_ROLES, ...ATTRIBUTE_ROLES].map(name => name.length)) + // Two rows per role: the painted sample beside its name and SGR pair, then the + // purpose indented under it. Splitting the purpose onto its own row keeps every + // sample on one visual line at the narrow widths a side-by-side pane gives. + const head = (name: string, role: RoleSpec, sample: string): string => { + const pair = role.open === '' ? 'no escape' : `ESC[${role.open}m ESC[${role.close}m` + return ` ${sample} ${palette.dim(`${name.padEnd(width)} ${pair}`)}` + } + const purpose = (role: RoleSpec): string => ` ${palette.dim(` ${role.purpose}`)}` + const rows = [ + palette.bold(palette.accent('Palette')), + palette.dim(`${scheme} scheme · color ${colorEnabled ? 'on' : 'off'}`), + '', + palette.dim('Colors — exactly one per span; they never nest inside each other.'), + ] + for (const name of COLOR_ROLES) { + rows.push(head(name, spec.colors[name], palette[name](PALETTE_SAMPLE)), purpose(spec.colors[name])) + } + rows.push('', palette.dim('Attributes — compose with any color, in either order.')) + for (const name of ATTRIBUTE_ROLES) { + rows.push(head(name, spec.attributes[name], palette[name](PALETTE_SAMPLE)), purpose(spec.attributes[name])) + } + return rows +} diff --git a/packages/ui/tui/src/components/transcript.ts b/packages/ui/tui/src/components/transcript.ts index 1e79d94ce8..58d3d6a178 100644 --- a/packages/ui/tui/src/components/transcript.ts +++ b/packages/ui/tui/src/components/transcript.ts @@ -25,7 +25,7 @@ import type { ToolResultView, } from '@deepseek-ai/dsh-tools' import type { FileDiff } from '@deepseek-ai/dsh-tools' -import { renderUnknownXml } from './xml-tool-output.ts' +import { preview, renderUnknownXml } from './xml-tool-output.ts' import { displayInlineText, displayText } from './text.ts' import { gradientText, type Palette } from './theme.ts' import { contentText, type ParsedArguments } from './content.ts' @@ -58,9 +58,9 @@ function diffLines(diff: FileDiff, palette: Palette): string[] { // each hunk always carries its own path header (no redundancy to suppress). const lines = [palette.bold(displayText(diff.path))] if (diff.oldText !== null) { - for (const line of displayText(diff.oldText).split('\n')) lines.push(palette.removed(`- ${line}`)) + for (const line of displayText(diff.oldText).split('\n')) lines.push(palette.error(`- ${line}`)) } - for (const line of displayText(diff.newText).split('\n')) lines.push(palette.added(`+ ${line}`)) + for (const line of displayText(diff.newText).split('\n')) lines.push(palette.success(`+ ${line}`)) return lines } @@ -109,7 +109,7 @@ export class HeaderComponent implements Component { const subtitle = this.subtitle() const lines = [ title, - ...subtitle === undefined ? [] : [this.palette.muted(displayText(subtitle))], + ...subtitle === undefined ? [] : [this.palette.dim(displayText(subtitle))], this.palette.dim(detail), ] .flatMap(line => wrapTextWithAnsi(line, usable)) @@ -147,12 +147,12 @@ function assistantMessageChildren( const text = displayText(textBlocks(content, 'text').trim()) const children: Component[] = [ new Spacer(1), - new Text(messageHeader('Assistant', palette.accent2, palette), 0, 0), + new Text(messageHeader('Assistant', palette.accent, palette), 0, 0), ] if (reasoning && showReasoning) { children.push( - new Text(palette.italic(palette.muted('Reasoning')), 0, 0), - new Markdown(reasoning, 0, 0, mdTheme, { color: value => palette.muted(value), italic: true }), + new Text(palette.italic(palette.dim('Reasoning')), 0, 0), + new Markdown(reasoning, 0, 0, mdTheme, { color: value => palette.dim(value), italic: true }), ) } if (text) children.push(new Markdown(text, 0, 0, mdTheme, { color: value => palette.text(value) })) @@ -301,10 +301,27 @@ export class StreamingAssistantComponent extends Container { } } +/** + * A tool card's body split at the Markdown boundary. `prelude` rows are already + * styled and render verbatim (a terminal `$` command, its cwd, a diff's hunks); + * `lines` is the tool's own text. A generic card renders both as one Markdown + * document under the dim body tone. + */ +interface CardBody { + readonly prelude: readonly string[] + readonly lines: readonly string[] +} + +/** + * Ctrl+O card-visibility cycle: `hidden` drops tool cards from the transcript, + * `collapsed` previews the first body lines, `expanded` shows everything. + */ +export type ToolCardVisibility = 'hidden' | 'collapsed' | 'expanded' + /** A tool call and its result, rendered as a collapsible status card. */ export class ToolCardComponent implements Component { private result: { content: ContentBlock[]; isError: boolean; meta?: JsonValue } | undefined - private expanded = false + private visibility: ToolCardVisibility = 'collapsed' private callView: ToolCallView private resultView: ToolResultView | undefined @@ -353,16 +370,19 @@ export class ToolCardComponent implements Component { } /** - * Expand or collapse the card's body preview. - * @param expanded - Whether the full body is shown. + * Set the card's visibility state. + * @param visibility - Hidden, collapsed preview, or full body. */ - setExpanded(expanded: boolean): void { - this.expanded = expanded + setVisibility(visibility: ToolCardVisibility): void { + this.visibility = visibility } invalidate(): void {} render(width: number): string[] { + // Hidden renders nothing — not even the leading gap — so the transcript + // keeps only the conversation, the way Codex hides tool calls. + if (this.visibility === 'hidden') return [] const isError = this.result?.isError ?? false // A ring marker: hollow while the call is pending, filled once it settles; // the header color (warning/success/error) tells pending from ok from error. @@ -374,25 +394,23 @@ export class ToolCardComponent implements Component { ? renderUnknownXml( displayText(contentText(genericContent)), this.maxOutputLines, - this.expanded, + this.visibility === 'expanded', displayText, - text => this.palette.muted(text), + text => this.palette.dim(text), + text => this.palette.dim(text), /* v8 ignore next -- renderUnknownXml calls the collapsed summary only when hidden XML children exceed this card's limit. */ count => this.palette.dim(` … +${count} lines (Ctrl+O to expand)`), ) : undefined - const body = unknownXml ?? (genericContent !== undefined && rawBody.length > 0 - ? new Markdown(rawBody.join('\n'), 0, 0, this.mdTheme, { color: value => this.palette.text(value) }).render(width) - : rawBody) - const headLines = Math.ceil(this.maxOutputLines / 2) - const tailLines = this.maxOutputLines - headLines - const visibleBody = unknownXml !== undefined || this.expanded || body.length <= this.maxOutputLines + // A generic card renders title and result as one Markdown document, so the + // document's own block spacing is preserved, then dims every row — the whole + // card body reads as one dim block under the status-colored header. + const body = unknownXml ?? (genericContent !== undefined && rawBody.lines.length > 0 + ? this.dimBody(rawBody, width) + : [...rawBody.prelude, ...rawBody.lines]) + const visibleBody = unknownXml !== undefined || this.visibility === 'expanded' ? body - : [ - ...body.slice(0, headLines), - this.palette.dim(`… +${body.length - this.maxOutputLines} lines (Ctrl+O to expand)`), - ...body.slice(body.length - tailLines), - ] + : preview(body, this.maxOutputLines, count => this.palette.dim(`… +${count} lines (Ctrl+O to expand)`)) // The header is a fixed `Tool / ` frame in the status color (warning // pending / success ok / error), flat — no bold or underline, so one color // reads consistently across the whole row. Every tool-specific detail (a @@ -409,7 +427,9 @@ export class ToolCardComponent implements Component { const desc = this.headerDescription() const headerText = `${glyph} Tool / ${displayText(this.name)}${desc === undefined ? '' : ` / ${displayInlineText(desc)}`}` const header = truncateToWidth(headerText, Math.max(1, width - 2), '') - const lines = [statusColor(header)] + // The blank first row is the card's own paragraph gap (no external Spacer), + // so the hidden state removes the gap together with the card. + const lines: string[] = ['', statusColor(header)] if (visibleBody.length > 0) lines.push(...new Text(visibleBody.join('\n'), 0, 0).render(width)) return lines } @@ -438,10 +458,11 @@ export class ToolCardComponent implements Component { return this.resultView?.title ?? this.callView.title } - private renderBody(): string[] { + private renderBody(): CardBody { const view = this.resultView ?? this.callView if (view.card === 'terminal') { const pending = this.terminalPending() + const prelude: string[] = [] const lines: string[] = [] // The command shows as a $-line here whenever it is not the header: either a // description headlines the row (the command still belongs somewhere) or the row @@ -452,18 +473,18 @@ export class ToolCardComponent implements Component { // rows and collide with the output below. const headlined = pending?.description !== undefined && pending.description !== '' const commandInBody = pending !== undefined && (headlined || this.result === undefined) - if (commandInBody) lines.push(this.palette.code(`$ ${displayInlineText(pending.title)}`)) - if (pending?.cwd) lines.push(this.palette.dim(displayInlineText(pending.cwd))) + if (commandInBody) prelude.push(this.palette.dim(`$ ${displayInlineText(pending.title)}`)) + if (pending?.cwd) prelude.push(this.palette.dim(displayInlineText(pending.cwd))) if (this.resultView?.card === 'terminal') { - if (this.resultView.output) lines.push(...displayText(this.resultView.output).split('\n')) + if (this.resultView.output) lines.push(...this.dimOutput(this.resultView.output)) if (this.resultView.exitCode !== undefined) lines.push(this.palette.dim(`[exit ${this.resultView.exitCode}]`)) if (this.resultView.signal !== undefined) { lines.push(this.palette.error(`[signal ${displayText(this.resultView.signal)}]`)) } } else if (this.result !== undefined) { - lines.push(...displayText(contentText(this.result.content)).split('\n')) + lines.push(...this.dimOutput(contentText(this.result.content))) } - return lines.filter(Boolean) + return { prelude: prelude.filter(Boolean), lines: lines.filter(Boolean) } } if (view.card === 'diff') { // The header no longer names the file, so each diff keeps its own path @@ -477,22 +498,138 @@ export class ToolCardComponent implements Component { }) const files = view.diffs.length const footer = this.palette.dim(`└ +${added} -${removed} · ${files} file${files === 1 ? '' : 's'}`) - return [...hunks, footer] + // A diff's own `+`/`-` colors carry its meaning, so it renders verbatim + // rather than under the dim result-output color. + return { prelude: [...hunks, footer], lines: [] } } const content = view.content ?? this.result?.content + const prelude: string[] = [] const lines: string[] = [] // The presenter title headlines the body now that the header is a fixed // `Tool / ` frame (a terminal card keeps its command $-line instead). // Skip it when it only repeats the tool name (the fallback presenter for a // tool with no presentCall, or an unknown tool), which the header already shows. const bodyTitle = this.bodyTitle() - if (bodyTitle !== displayText(this.name)) lines.push(displayInlineText(bodyTitle)) + if (bodyTitle !== displayText(this.name)) prelude.push(displayInlineText(bodyTitle)) if (content !== undefined) lines.push(...displayText(contentText(content)).split('\n')) const rawInput = this.result === undefined && this.callView.card === 'generic' ? this.callView.rawInput : undefined if (rawInput !== undefined) lines.push(...pretty(rawInput).split('\n')) - return lines.filter((line, index, all) => line.length > 0 || (index > 0 && index < all.length - 1)) + // Blank-line trimming spans the whole body, so the title counts as a row: + // interior blanks (a result's own paragraph break) survive while the body's + // leading and trailing ones are dropped. + const total = prelude.length + lines.length + return { + prelude, + lines: lines.filter((line, index) => { + const row = prelude.length + index + return line.length > 0 || (row > 0 && row < total - 1) + }), + } + } + + /** + * A tool's own output text as dim rows — the card's result-output color, which + * separates what the tool produced from the card's own framing. A blank row + * stays the empty string so the terminal branch's blank-row filter still reads + * it as blank instead of as an ANSI-wrapped value. + */ + private dimOutput(text: string): string[] { + return displayText(text).split('\n').map(line => line === '' ? line : this.palette.dim(line)) + } + + /** + * Render a generic card's prelude and result as one Markdown document under the + * dim body tone. Rendering both together preserves the document's own block + * spacing (Markdown's blank row before a heading); dimming every row keeps the + * card body one uniform tone, so only the status-colored header carries color. + */ + private dimBody(body: CardBody, width: number): string[] { + const rows = new Markdown([...body.prelude, ...body.lines].join('\n'), 0, 0, this.mdTheme, { + color: value => this.palette.text(value), + }).render(width) + // A whitespace-only row carries no output to dim; leaving it unwrapped keeps + // Markdown's padding out of the styled ranges. + return rows.map(row => row.trim() === '' ? row : this.palette.dim(row)) + } +} + +/** + * Matches a lone reminder-frame tag on its own line, capturing the element name. + * Producers emit the frame as whole lines (`workspace-context`, `dsh-tool-skill`), + * so anchoring the whole line keeps a tag mentioned inside prose from matching. + */ +const REMINDER_FRAME_LINE = /^<(\/?)([a-zA-Z][\w:.-]*)>$/u + +/** + * Drop a producer's outer reminder frame, keeping the instruction body verbatim. + * The card header already names the source, so the frame lines carry nothing. + * Only a matched open/close pair on the first and last lines is removed, so a + * body that merely starts with a tag-like line is left intact. + * @param text - Complete model-facing context text. + * @returns The body without its outer frame lines, trimmed of the blank lines they leave. + */ +function stripReminderFrame(text: string): string { + // A frame needs an open line and a distinct close line, so anything shorter than + // two lines is already frameless. + const [first = '', ...rest] = text.split('\n') + const last = rest.at(-1) + if (last === undefined) return text + const open = REMINDER_FRAME_LINE.exec(first.trim()) + const close = REMINDER_FRAME_LINE.exec(last.trim()) + if (open?.[1] !== '' || close?.[1] !== '/' || open[2] !== close[2]) return text + return rest.slice(0, -1).join('\n').replace(/^\n+|\n+$/gu, '') +} + +/** + * Injected context (plugin/goal source, e.g. `workspace-context`), rendered as a + * collapsible dim card that shares the tool-card `Ctrl+O` toggle. The header is + * `Context ·