refactor(web): open produced files through the Host, not over HTTP

Scope decision: previews for a browser that is not on the Host machine are
not supported. With that settled, host.openPath answers the supported case
completely — a file:// document in a real browser has full page capabilities
and no reach into /api — and the HTTP serving this branch had built answered
only the unsupported one.

Removed: the /f route and its listener, the workspace-file URL shape,
ApiProxy.workspaceRootOf, ConnectionHandle.fileUrl, and the port published
into the index page.

Kept, and finished:
- the produced-files row a turn ends with, derived from mutation locations;
- the path link now reads as a link at rest, not only on hover — the reported
  "I can't open what it made" was this, sitting on a working capability;
- the Host opener prefers the default BROWSER for .html/.htm/.xhtml/.svg, so
  a developer who binds .html to an editor still gets a rendered page
  (macOS via the LaunchServices https handler, Linux via $BROWSER, every
  failure falling back to the default application).

The retired designs and their measurements stay in the Agent Note, including
why same-origin serving was unsafe and why the sandbox that fixed it broke
the pages invisibly.
This commit is contained in:
ZiyaZhang
2026-08-01 03:15:54 -07:00
parent 59bfe77fb8
commit 8fb6c2bd69
50 changed files with 317 additions and 1211 deletions

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-07-31-web-workspace-file-links.md
2026-07-31-web-workspace-file-links.md: 8eeb96517aa905e77e50ce36f0efb704353c0821
2026-07-31-web-workspace-file-links.zh.md: 63d746b0a9aabaf78ba5653e16705bd662a54126
2026-07-31-web-workspace-file-links.md: da99426ecb5ca81dcc110bbd4d5c1218390ae4bd
2026-07-31-web-workspace-file-links.zh.md: 91aa94c6fe253c64125eb31fd15973a5aaff1a8f

View File

@@ -4,36 +4,32 @@ Status: implemented
English | [中文](2026-07-31-web-workspace-file-links.zh.md)
> Scope: the `/f` workspace-file route on the web transport, the `IWorkspaces.fileUrl` derivation behind it, the conversation's file-open affordance switching to it, and the produced-files row a finished turn ends with. Not in scope: an artifact registry, versioning, live reload, or any model-facing declaration.
> Scope: the produced-files row a finished turn ends with, the file-path link that reads as one, and the Host opener preferring the default browser for documents a browser renders. Not in scope, by decision: serving workspace files over HTTP, and previews for a client that is not on the Host machine.
## Problem
A web session that produced a file had no way to look at it. The agent wrote `deepseek-homepage.html`, said so, and the user's only recourse was to copy an absolute path like `/private/tmp/dsh-client-hotplug.ygPvsm/workspaces/plugin-hotplug/deepseek-homepage.html` into a terminal.
The parts were nearly all present, pointed at the wrong target. `ToolRow` already renders a mutation or read row's path as a real button, `ui-conversation` already routes its click through `openFile`, and `workspaces.openPath` already carries it to the Host's system opener. But that opener runs on the Host machine, and `host.openPath` is loopback-pinned by the `/api` trust fence, so the affordance answered nothing for a browser reached over the LAN and was invisible even locally (the path styled as plain text, underlined only on hover). Meanwhile `MarkdownText` strips every non-`http(s)` URL, so a path the model wrote into its closing message could never become a link at all, and `ToolCallView.locations` — the follow-along vocabulary the file tools already populate — had no consumer in the client.
Two distinct defects sat behind that. The transcript never said what a turn had produced: `ToolCallView.locations` — the follow-along vocabulary the file tools already populate — had no consumer in the client, so a reader's only account of the output was whatever the closing message happened to spell. And the affordance that did exist was invisible: `ToolRow` already renders a mutation or read row's path as a real button wired to `host.openPath`, but styled exactly like the surrounding prose and underlined only on hover, so nobody found it. The reported "I can't open what it made" was a discoverability failure sitting on top of a working capability.
## Decision
**One prefix route on the transport that already exists, not a new capability.** `client-connection` owns both browser-facing prefixes: `/api` for RPC and `/f/<sessionId>/<segments…>` for workspace-file reads. It was already the package holding `httpServer`, the `trustedHosts` config, and the browser-trust fence; a separate package would have duplicated the fence and the config, and forced `AppCLIEntry` to patch two rows for one `--trusted-host` flag. The webserver's own contract — every feature surface is a route some other plugin registers — makes the route the whole mechanism. Segments ride the path rather than a query parameter so a served document's relative references resolve to its siblings.
**A finished turn ends with the files it produced.** `turnDeliverables` reads them off the mutation tools' own follow-along `locations` — a diff card, or a generic card whose `kind` is `edit` (the shape `str_replace_editor`'s insert presents) — so a turn's output is listed whether or not the closing message named it, and a new mutation tool joins by declaring what it does rather than by being added to a list. Reads, deletes, and failed calls contribute nothing; a path appears once per turn in first-seen order; accumulation resets on the turn boundary, so a turn that mutates and then ends without content text cannot spill into the next turn's row. The row renders under the closing assistant's body and above its IconActions, keyed to the seq `assistantActionsSeqs` already elects.
**The request names a Session; the gateway names the authority.** `ApiProxy.workspaceRootOf` answers where a Session's files live — a live agent's `session.header.cwd` first, then the persistence store, never a resume — as a second, non-envelope face of the `cwd` the session summaries already carry. The route reads that instead of `ctx.agents` directly, because `client-connection` is registered in the client program and importing the core service packages merges their host-side `sessions: SessionStore` declaration over the browser runtime's own `sessions: SessionsService` — the collision `tsconfig.host.json`/`tsconfig.client.json` exist to prevent. Both the cwd and the resolved target go through `realpath` before the prefix comparison, so a workspace-internal symlink pointing outward is refused by its target; traversal spellings are refused at parse time, before any filesystem call. Reads stream through `pipeline`, so a client that goes away destroys the descriptor and no request ever buffers a file.
**The path link reads as a link.** Underlined at rest, not only on hover. This is the smaller half of the diff and the larger half of the fix.
**The URL shape lives in `dsh-host-apiproxy/api`, with the other browser-importable contract surfaces.** Both ends must agree on one encoding, but a client bundle may not value-import another plugin's package: the purity gate in `packages/client/tsdown.client.ts` allows only platform modules and the `INLINE_SAFE` wire layers, of which apiproxy is one. Putting `api/files.ts` there is what lets the browser half build a URL and the serving half parse it from a single source, and it needed no new package edge — both sides already depend on apiproxy.
**Opening stays the Host's job, and prefers the default browser.** `host.openPath` hands the path to the operating system, which yields a `file://` document in a real browser: full page capabilities, and no reachability into `/api`, because a `file://` document is not same-origin with it. Measured on the reported artifact: `localStorage` works, the theme toggle flips, the tabs switch, and `fetch` to the API fails. For documents a browser renders — `.html`, `.htm`, `.xhtml`, `.svg` — the opener resolves the default *browser* rather than the type's default application, because a developer who binds `.html` to an editor would otherwise click a produced page and get source code. Each platform answers "which browser" as completely as it can (macOS from the LaunchServices `https` handler, Linux from `$BROWSER`), and every failure falls back to the default application rather than surfacing.
**Workspace files get their own port, and therefore their own origin.** The isolation question was worked three ways before landing here. A sandbox header came first, on the reasoning that `/api/events.mux` is a readable same-origin `GET` stream. It was then dropped on the premise that these files are agent-authored, so a browser boundary would sit behind one already crossed — a premise review falsified: a read row makes every file in a cloned repository openable, and a same-origin active document was measured driving `/api/settings.describe` to a `200` with full data, reaching the loopback-pinned settings and credential plane from a page nobody in this session wrote. Restoring the sandbox closed that, and measuring what it cost decided the final shape: under `CSP: sandbox` the report's own artifact throws `SecurityError` on load, and because an uncaught exception aborts the rest of its `<script>`, every listener declared after that line — theme toggle, mobile menu, model tabs — never binds. Two of the four artifacts in the reporting user's workspace were dead pages under it, and they still *looked* right. A second port is the boundary without the amputation: cross-origin to `/api` (refused by the fence's Origin check and by CORS), same-origin with itself (so `localStorage`, cookies, and `fetch` all work). It binds the same host as the API so LAN previews keep working, answers `/f` and nothing else, and publishes its port into the index page for the browser half to address.
**The client decides by derivation, not by probing.** `ConnectionHandle.fileUrl(sessionId, cwd, path)` expresses a tool-reported path as segments below the session cwd and returns an absolute URL on the workspace-file origin — the page's own hostname, the published port — or `undefined` when the path leaves the workspace or no port was published. It lives on the connection handle because the transport owns both ends: the listener that serves the bytes and the port that addresses it. `undefined` is exactly the signal to fall back to `openPath`, which is also what makes the keyless fixture lane (served by no host) degrade to the old behavior instead of opening a dead tab.
**Serving workspace files over HTTP is out of scope, and so are non-local clients.** An earlier revision served files from the harness itself — first same-origin with `/api`, then behind `CSP: sandbox`, then from a second listener whose own port gave served documents their own origin. Each step answered a real problem, and the whole line was retired once the product scope was settled: previews for a browser that is not on the Host machine are not supported. With that decided, the Host opener answers the supported case completely and the HTTP machinery answered only the unsupported one.
## Alternatives considered
- **The artifact capability family (RFC #268 / PR #272)** — a seam with ids, versions, snapshot storage, its own HTTP server, SSE live reload, and a browser auto-opener. Its review found seven critical issues, and every one of them came from that machinery: an unlistened opener spawn crashing the harness, the opener inheriting `DEEPSEEK_API_KEY`, in-flight publishes outliving disposal, `readFile` preceding the size cap, a snapshot TOCTOU, and retention leaking with undisposed agents. `dsh web` already runs an HTTP server and the user is already in a browser, so none of that machinery buys anything here. The RFC and its tests stay as the input for the day a real cross-session or versioned-artifact need appears; this route is that seam's natural mount point when it does.
- **A dedicated `dsh-client-workspace-files` package** — the honest seam shape if file serving were an independent capability. It is not: it needs the same fence and the same `trustedHosts` value as `/api`, and splitting would have duplicated both against the repository's own "don't split preemptively" rule.
- **Keeping the URL-shape module in `client-connection` and importing it from the runtime** — the first cut, and the build refused it: a cross-plugin value import into a client bundle either inlines a duplicate runtime instance or names a specifier the frozen module table cannot answer. The gate is the reason the shared module sits in the wire layer rather than in the package that happens to own the route.
- **`/f/<absolute path>`, so `openPath` could stay the single call site** — drops the sessionId from the URL, but then the served authority becomes the union of every workspace the host knows. The tight authority costs exactly one call-site edit, because `openFile` already has both the sessionId and the cwd in scope.
- **`connect-src 'none'` plus a navigation fence, to keep `localStorage` working under a sandbox** — measurably viable against the SSE-read vector (Chrome sends `Sec-Fetch-Dest: document` for `window.open` and `empty` for `EventSource`, loopback included), but it never addressed the larger one: same-origin `fetch` to a POST method is what reaches the configuration plane, and blocking `connect-src` from the served document is exactly what a hostile document would not do to itself.
- **Keeping the sandbox and accepting the limitation** — the honest reading of that trade only became visible once measured: it is not "a preview cannot remember a theme" but "a preview's entire script dies at its first storage access", on pages that still render perfectly. A limitation nobody can see is worse than one that costs a port.
- **Linkifying paths in the assistant's closing message** — the shape a user asks for ("put the link at the end"), but it makes rendering depend on the model spelling a path recognizably. The tool calls already carry `locations` as structured fact, so the produced-files row consumes that instead; linkifying the prose stays unnecessary rather than merely deferred.
- **Serving `/f/<sessionId>/<segments…>` from the harness** — built and working, including confinement by dual `realpath`, the browser-trust fence, streamed reads, and a separate listener whose port gave served documents their own origin. It is the only design that shows a preview to a client on another machine, which is exactly the case ruled out of scope. Retired for that reason, not because it failed; its cost was a second socket with its own lifecycle, a port published into the page, and a URL-shape contract shared across two packages.
- **Same-origin HTTP serving without isolation** — measurably unsafe, and recorded so nobody retries it: a document served beside `/api` drove `settings.describe` to a `200` with full data and `session.list` to 35 KB of every session's transcript, from a page that need not be agent-authored at all (a read row makes every file in a cloned repository openable).
- **`Content-Security-Policy: sandbox` over that same-origin serving** — closes the hole by taking the document's origin away, which measurably breaks the pages this feature exists to show: the reported artifact throws `SecurityError` on load, and because an uncaught exception aborts the rest of its `<script>`, every listener declared after that line — theme toggle, mobile menu, model tabs — never binds. Two of the four artifacts in the reporting user's workspace were dead pages under it, and they still rendered perfectly, so the breakage was invisible.
- **Linkifying paths in the assistant's closing message** — the shape a user asks for ("put the link at the end"), but it makes rendering depend on the model spelling a path recognizably. The tool calls already carry `locations` as structured fact, so the produced-files row consumes that instead.
- **An embedded WebView in the desktop shell** — the strongest isolation available, since the preview then runs in a container the product owns rather than in the user's browser. It belongs to the desktop shell's own design, not to this surface, and is recorded here as the direction a future preview capability should take.
## Consequences
Every existing file affordance changed target at once: write, edit, read, and the generic single-file card all reach `openFile`, so one call-site edit made produced files openable in the browser, LAN clients included. Three tests asserting the old `openPath` destination were rewritten to the new one; the outside-workspace fallback keeps the old assertion. The route is covered against a real HTTP server and a real temporary workspace, because confinement, content typing, and the sandbox header are wire facts, and the assembled web lane (`apps/web/tests/workspace-file-open.e2e.ts`, keyless over a cold-seeded session) proves the product path: clicking a read row's path opens `/f/<sessionId>/a.txt` in a second tab serving that workspace file, while a traversal spelling answers 404. A preview runs with its own origin's full capabilities, so a generated page behaves as its author intended. The residual the port does not close: two Sessions share one workspace-file origin, so a document from one may fetch another's served files. That is strictly narrower than the API surface it replaces, and narrowing it further would mean an origin per Session, which nothing today needs. The produced-files row ships here too: `turnDeliverables` reads a turn's output off the mutation tools' render intent (a diff card, or a generic card whose `kind` is `edit`), resets on the turn boundary so an interrupted turn cannot spill into the next, and renders under the closing assistant. Still deferred: linkification inside assistant Markdown, and any cross-session view of past deliverables.
Every existing file affordance changed at once: write, edit, read, and the generic single-file card all reach `openFile`, so the link fix and the browser preference apply to all of them without a per-row change. The keyless web lane (`apps/web/tests/produced-files.e2e.ts`) cold-seeds a recorded write turn and pins the row in the assembled application; it deliberately does not click, because the click hands a path to the Host's opener and would launch a real application on the machine running the suite. A produced file opens as a `file://` document, which cannot `fetch` its own siblings (a multi-file artifact that loads `./data.json` breaks, while `<script src>`, `<img>`, and CSS `@import` are unaffected) — the one capability HTTP serving had that this does not. A client reached over the network sees nothing when it clicks: `host.openPath` runs on the Host and is loopback-pinned by the `/api` trust fence. That is the scope decision showing through, not a defect, and it is why the row keeps the full path in its `title` for a reader who can only copy it. Markdown opens in whatever the platform hands `.md`, usually an editor rather than a renderer; rendering it inside the product is a separate, deferred surface.

View File

@@ -4,36 +4,32 @@ Status: implemented
[English](2026-07-31-web-workspace-file-links.md) | 中文
> 范围:web 传输层上的 `/f` 工作区文件路由、其背后的 `IWorkspaces.fileUrl` 推导、会话中打开文件的交互改指向它,以及完成的一轮以其产出文件收尾的那一行。不在范围内:产物注册表、版本、实时重载,或任何面向模型的声明
> 范围:完成的一轮以其产出文件收尾的那一行、读得出是链接的文件路径链接,以及 Host 打开器对浏览器可渲染文档优先选用默认浏览器。经决定不在范围内:以 HTTP 提供工作区文件,以及为不在 Host 机器上的客户端提供预览
## 问题
一个产出了文件的 web 会话没有办法看到那个文件。agent 写出了 `deepseek-homepage.html` 并如实告知,而用户唯一的办法是把 `/private/tmp/dsh-client-hotplug.ygPvsm/workspaces/plugin-hotplug/deepseek-homepage.html` 这样的绝对路径复制进终端。
零件几乎都在,只是指错了目标。`ToolRow` 早已把改写行或读取行的路径渲染成一个真正的按钮,`ui-conversation` 早已把它的点击经由 `openFile` 转发,`workspaces.openPath` 也早已把它送到 Host 的系统打开器。但那个打开器运行在 Host 机器上,而 `host.openPath``/api` 信任 fence 钉在回环,所以这个交互对经 LAN 访问的浏览器什么都答不了,即便在本机也是隐形的(路径的样式就是普通文本,只有 hover 时才有下划线)。与此同时 `MarkdownText` 会剥掉每一个非 `http(s)` 的 URL因此模型写进收尾消息里的路径根本不可能成为链接`ToolCallView.locations`——文件工具早已填好的跟随文件词汇——在客户端没有任何消费方
这背后是两个不同的缺陷。转录从不说明一轮产出了什么:`ToolCallView.locations`——文件工具早已填好的跟随文件词汇——在客户端没有任何消费方,因此读者对产出的唯一交代,就是收尾消息恰好拼出来的那点内容。而已经存在的那个交互是隐形的:`ToolRow` 早已把改写行或读取行的路径渲染成一个接到 `host.openPath` 的真按钮,但它的样式与周围正文一模一样、只有悬停才有下划线,于是没人发现。所报告的“做完了打不开”,是一个可发现性失败叠在一项本就可用的能力之上
## 决定
**在已有的传输层上加一条前缀路由,而不是加一项能力。** `client-connection` 持有两条面向浏览器的前缀:`/api` 承载 RPC`/f/<sessionId>/<segments…>` 承载工作区文件读取。它本来就是持有 `httpServer``trustedHosts` 配置和浏览器信任 fence 的那个包;单开一个包会把 fence 和配置各复制一份,并逼着 `AppCLIEntry` 为一个 `--trusted-host` 标志去 patch 两行。webserver 自己的契约——每个特性面都是别的插件注册的一条路由——让这条路由本身就是全部机制。段落走路径而非查询参数,是为了让所服务文档的相对引用能解析到它的同级文件
**完成的一轮以它产出的文件收尾。** `turnDeliverables` 从改写工具自身的跟随文件 `locations` 中读出它们——diff 卡片,或 `kind``edit` 的 generic 卡片(即 `str_replace_editor` 的 insert 所呈现的形状——因此无论收尾消息是否点名这一轮的产出都会被列出新的改写工具靠声明自己做了什么加入而不是靠被加进某张名单。read、删除与失败的调用不贡献任何条目同一路径在一轮内按首见顺序只出现一次累积在 turn 边界重置,因此一轮若先改写文件、随后没有正文内容就结束,不会溢进下一轮的行里。该行渲染在收尾 assistant 正文之下、其 IconActions 之上,键控到 `assistantActionsSeqs` 早已选出的那个 seq
**请求指名 Session由网关指名权限边界。** `ApiProxy.workspaceRootOf` 回答某个 Session 的文件位于何处——先看活跃 agent 的 `session.header.cwd`,再看持久化存储,绝不恢复会话——它是会话摘要早已携带的那个 `cwd` 的第二副面孔,只是不带信封。路由读取它而不是直接够 `ctx.agents`,因为 `client-connection` 注册在 client 程序里,而引入核心服务包会把它们 host 侧的 `sessions: SessionStore` 声明盖到浏览器运行时自己的 `sessions: SessionsService` 之上——这正是 `tsconfig.host.json``tsconfig.client.json` 分立所要防的那种冲突。cwd 与解析出的目标在前缀比较前都要过 `realpath`,因此工作区内指向工作区外的符号链接会因其目标而被拒绝;穿越写法在解析期就被拒,早于任何文件系统调用。读取经 `pipeline` 流出,因此客户端离开即销毁描述符,任何请求都不会把文件缓冲起来
**路径链接读得出是链接。** 静止状态下就带下划线,而不只在悬停时。这是本次改动中更小的那一半,却是修复中更大的那一半
**URL 形状落在 `dsh-host-apiproxy/api`,与其余浏览器可导入的契约面同处一地。** 两端必须就同一套编码达成一致,但客户端 bundle 不允许值导入另一个插件的包:`packages/client/tsdown.client.ts` 里的纯度 gate 只放行平台模块与 `INLINE_SAFE` 协议层,而 apiproxy 正是其中之一。把 `api/files.ts` 放在那里,才使构造 URL 的浏览器半侧与解析它的服务半侧共用单一来源,而且没有新增任何包依赖边——两侧本来就依赖 apiproxy
**打开仍然是 Host 的职责,并且优先选用默认浏览器。** `host.openPath` 把路径交给操作系统,得到的是真实浏览器里的一份 `file://` 文档:页面能力完整,且够不到 `/api`——因为 `file://` 文档与它并不同源。在所报告的那份产物上实测:`localStorage` 可用、主题切换生效、tabs 可切换,而对 API 的 `fetch` 失败。对浏览器能渲染的文档——`.html``.htm``.xhtml``.svg`——打开器解析的是默认**浏览器**而非该类型的默认应用,因为把 `.html` 绑给编辑器的开发者否则点开一个产出的页面得到的会是源码。每个平台在自己能力范围内回答“哪个浏览器”macOS 取 LaunchServices 的 `https` 处理程序Linux 取 `$BROWSER`),任何一步失败都回退到默认应用,而不是把失败抛给用户
**工作区文件获得自己的端口,因而拥有自己的源。** 隔离这件事在落到此处之前走了三步。最初是加 sandbox 头,理由是 `/api/events.mux` 是一条同源可读的 `GET` 流。随后它被拿掉,前提是这些文件由 agent 撰写、浏览器边界只会立在一条早已越过的边界之后——而评审推翻了这个前提:一条 read 行就让 clone 下来的仓库里任何文件变得可打开,而同源的活动文档经实测能把 `/api/settings.describe` 打到 `200` 并拿到完整数据,从一个本次会话中无人撰写的页面触达了被钉在回环的设置与凭据面。加回 sandbox 堵住了它,而“量清楚它的代价”决定了最终形状:在 `CSP: sandbox` 之下,报告中那份产物加载时就抛 `SecurityError`,又因为未捕获异常会中止其 `<script>` 的其余部分,该行之后声明的所有监听器——主题切换、移动端菜单、模型 tabs——统统不会绑定。报告者工作区里四份产物有两份在它之下是死页面而且它们**看上去**仍然正常。第二个端口给出了这条边界而无需截肢:对 `/api` 是跨源(被 fence 的 Origin 校验与 CORS 双重拒绝),对自身是同源(因此 `localStorage`、cookie 与 `fetch` 都可用)。它绑定与 API 相同的 host因此 LAN 预览继续可用;只应答 `/f`,别无其他;并把端口注入首页供浏览器半侧寻址
**客户端靠推导决定,而不是靠探测。** `ConnectionHandle.fileUrl(sessionId, cwd, path)` 把工具报告的路径表达为 session cwd 之下的段落,并返回工作区文件源上的绝对 URL——页面自身的主机名加上已发布的端口——路径离开工作区或没有端口发布时返回 `undefined`。它落在 connection 句柄上,是因为传输层同时持有两端:提供字节的监听器,和寻址它的端口。`undefined` 恰好就是回退到 `openPath` 的信号,这也让无密钥 fixture 通道(不由任何 host 提供)退化为旧行为,而不是打开一个空标签页。
**以 HTTP 提供工作区文件不在范围内,非本机客户端亦然。** 更早的一版由 harness 自己提供文件——先是与 `/api` 同源,随后加上 `CSP: sandbox`,再后来交给一个以自身端口给所服务文档独立源的第二监听器。每一步都在回答一个真实问题,而整条线在产品范围定下之后被整体退役:不为“浏览器不在 Host 机器上”的场景提供预览。这一点定下之后Host 打开器完整回答了受支持的场景,而那套 HTTP 机制回答的只是不受支持的那个
## 考虑过的替代方案
- **产物能力族RFC #268 / PR #272**——一条带 id、版本、快照存储、自有 HTTP 服务器、SSE 实时重载与浏览器自动打开器的 seam。它的评审给出了七个 critical而每一个都来自那套机械结构未监听的打开器 spawn 会让 harness 崩溃、打开器继承 `DEEPSEEK_API_KEY`、进行中的 publish 活过 dispose、`readFile` 先于大小上限、快照的 TOCTOU以及未 dispose 的 agent 导致保留期泄漏。`dsh web` 本来就跑着一个 HTTP 服务器用户本来就在浏览器里那套机械结构在这里买不到任何东西。RFC 与其测试保留下来,作为真正出现跨会话或版本化产物需求那天的输入;届时这条路由就是那条 seam 的天然挂载点
- **单开一个 `dsh-client-workspace-files` 包**——如果文件服务是一项独立能力,这才是诚实的 seam 形状。它不是:它需要与 `/api` 相同的 fence 和相同的 `trustedHosts` 值,拆分会把两者都复制一份,违背仓库自己的“不要预先拆分”
- **把 URL 形状模块留在 `client-connection` 里、由 runtime 去导入**——最初就是这么写的,构建直接拒绝:向客户端 bundle 做跨插件值导入,要么内联出一份重复的运行时实例,要么落到冻结模块表答不出的说明符上。这道 gate 正是共享模块落在协议层、而非落在恰好持有该路由的那个包里的原因
- **`/f/<绝对路径>`,好让 `openPath` 保持为唯一调用点**——这会把 sessionId 从 URL 里去掉,但所服务的权限边界随之变成 host 已知的全部工作区之并集。紧的权限边界只花掉一处调用点的改动,因为 `openFile` 本来就同时持有 sessionId 与 cwd
- **`connect-src 'none'` 加一道导航栅栏,在 sandbox 之下保住 `localStorage`**——针对“读走 SSE 流”这条向量经实测可行Chrome 对 `window.open``Sec-Fetch-Dest: document`、对 `EventSource``empty`,回环也在内),但它从未触及更大的那条:真正够到配置面的是向 POST 方法发起的同源 `fetch`,而“从所服务文档一侧封住 `connect-src`”恰恰是敌意文档不会对自己做的事
- **保留 sandbox 并接受这条限制**——这笔交易的真实读数要量过才看得见:它不是“预览记不住主题”,而是“预览的整段脚本在第一次访问存储时就死了”,而页面照样渲染得完美无缺。一条没人看得见的限制,比一条要花掉一个端口的限制更糟。
- **把路径在助手的收尾消息里链接化**——这是用户开口要的形状(“在结尾附上链接”),但它让渲染取决于模型是否把路径拼写得可识别。工具调用已经把 `locations` 作为结构化事实携带,产出文件行消费的正是它;因此把正文链接化是不必要,而不只是被推迟。
- **由 harness 提供 `/f/<sessionId>/<segments…>`**——已经实现并可用,包含双 `realpath` 收敛、浏览器信任 fence、流式读取以及一个以自身端口给所服务文档独立源的监听器。它是唯一能把预览呈现给另一台机器上客户端的设计而那恰恰是被判出范围的场景。因此退役而不是因为它失败了它的代价是一个带自身生命周期的第二 socket、一个注入页面的端口以及一份跨两个包共享的 URL 形状契约
- **同源 HTTP 提供且不加隔离**——经实测不安全,记录在此以免有人重试:与 `/api` 并排提供的文档把 `settings.describe` 打到 `200` 并拿到完整数据,把 `session.list` 打到 35 KB 的全部会话转录,而这个页面根本不必由 agent 撰写(一条 read 行就让 clone 下来的仓库里任何文件变得可打开)
- **在那套同源提供之上加 `Content-Security-Policy: sandbox`**——它以剥夺文档的源来堵住这个洞,而这经实测会破坏本功能存在的意义所在的那类页面:所报告的产物在加载时抛 `SecurityError`,又因为未捕获异常会中止其 `<script>` 的其余部分,该行之后声明的所有监听器——主题切换、移动端菜单、模型 tabs——统统不会绑定。报告者工作区里四份产物有两份在它之下是死页面而且它们渲染得完美无缺所以这种破坏是看不见的
- **把路径在助手的收尾消息里链接化**——这是用户开口要的形状(“在结尾附上链接”),但它让渲染取决于模型是否把路径拼写得可识别。工具调用已经把 `locations` 作为结构化事实携带,产出文件行消费的正是它
- **桌面端外壳中的内嵌 WebView**——可得到的最强隔离,因为那时预览跑在产品自己拥有的容器里,而不是用户的浏览器里。它属于桌面端外壳自身的设计,而非本交互面,记录在此作为未来预览能力应走的方向
## 影响
现有的每一处文件交互都同时换了目标write、edit、read 与通用单文件卡片都汇到 `openFile`,因此一处调用点的改动就让产出的文件在浏览器里可打开LAN 客户端也在内。三个断言旧 `openPath` 去向的测试被改写为新的去向;工作区外的回退保留了旧断言。这条路由对着真实 HTTP 服务器与真实临时工作区做覆盖,因为收敛、内容定型与 sandbox 头都是协议事实;而组装后的 web 通道(`apps/web/tests/workspace-file-open.e2e.ts`,在冷播种会话上无密钥运行)证明了产品路径:点击读取行的路径会在第二个标签页打开 `/f/<sessionId>/a.txt` 并提供那个工作区文件,而穿越写法应答 404。预览以自身源的完整能力运行因此生成的页面按其作者的意图工作。端口没有堵住的残余两个 Session 共用同一个工作区文件源,因此来自其一的文档可以 fetch 另一个已服务的文件。这比它所替代的 API 面严格更窄,而要再窄一层就意味着每个 Session 一个源,今天没有任何需求指向那里。产出文件行也在本次一并落地:`turnDeliverables` 依据改写工具的渲染意图diff 卡片,或 `kind``edit` 的 generic 卡片)读出一轮的产出,在 turn 边界重置以免中断的一轮溢进下一轮,并渲染在收尾 assistant 之下。仍然暂缓:助手 Markdown 内部的链接化,以及任何跨会话回看既往产物的视图
现有的每一处文件交互都同时改变了write、edit、read 与通用单文件卡片都汇到 `openFile`,因此链接可见性修复与浏览器优先策略无需逐行改动即适用于全部。无密钥 web 通道(`apps/web/tests/produced-files.e2e.ts`冷播种一段录制的 write 轮次,在组装后的应用中钉住该行;它刻意不点击,因为点击会把路径交给 Host 打开器,从而在跑测试的机器上启动一个真实应用。产出的文件以 `file://` 文档打开,它无法 `fetch` 自己的同级文件(一个加载 `./data.json` 的多文件产物会坏,而 `<script src>``<img>` 与 CSS `@import` 不受影响)——这是 HTTP 提供曾有、而此处没有的那一项能力。经网络访问的客户端点击后看不到任何东西:`host.openPath` 在 Host 上运行,且被 `/api` 信任 fence 钉在回环。那是范围决定的显现,不是缺陷,也正因如此该行把完整路径保留在 `title`供只能复制它的读者使用。markdown 会由平台交给 `.md` 的默认处理程序打开,通常是编辑器而非渲染器;在产品内渲染它是另一个被推迟的交互面

View File

@@ -0,0 +1,76 @@
// Web e2e scenario: the produced-files row a finished turn ends with. Cold-seeds
// a recorded write turn (zero model calls). Package tests cover the derivation
// in isolation, but only the assembled application shows that a turn's writes
// reach the transcript as an openable row (docs/testing.md snapshot rule). The
// click itself is not driven here: it hands the path to the Host's opener,
// which would launch a real application on the machine running the suite.
import { readFile, writeFile, mkdir } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Browser, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import {
launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { newEnglishPage, saveFailureShot } from './support.ts'
// Borrowed read-only: this scenario needs any settled turn whose tools WROTE a
// file, not a new recording (the message-actions borrowing pattern).
const SEED = fileURLToPath(new URL('./snapshots/permission-policy-context/session.jsonl', import.meta.url))
const MODE = webSnapshotMode()
const SEED_ID = 'produced-files-web-e2e'
/** The file the borrowed recording's write tool produces. */
const PRODUCED = 'policy-neutral.txt'
describe('web e2e: a finished turn ends with the files it produced', () => {
let scaffold: WebScaffold
let browser: Browser
let page: Page
let tripwire: ReturnType<typeof watchConsole>
beforeAll(async () => {
scaffold = await launchWebScaffold({})
// The seeded Session's cwd is the scaffold workspace; the recording's own
// nested directory is created too, so its paths stay resolvable.
await mkdir(join(scaffold.workspaceCwd, 'workspace'), { recursive: true })
await writeFile(join(scaffold.workspaceCwd, PRODUCED), 'neutral\n')
const raw = await readFile(SEED, 'utf8')
expect(raw, 'borrowed recording must carry the write this scenario reads').toContain(PRODUCED)
await seedSession(scaffold, raw, SEED_ID)
browser = await chromium.launch()
page = await newEnglishPage(browser)
tripwire = watchConsole(page)
await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
}, 120_000)
afterAll(async () => {
await browser?.close()
await scaffold?.close()
})
it.skipIf(MODE === 'record')('lists the written file under the closing message, as an opener', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-produced-files'))
const groupRow = page.locator('[role="treeitem"]').first()
await groupRow.waitFor({ timeout: 15_000 })
await groupRow.click()
const sessionRow = page.locator('[role="treeitem"]').nth(1)
await sessionRow.waitFor({ timeout: 10_000 })
await sessionRow.click()
// The row the turn ends with — derived from the write call's locations,
// not from whatever the closing message happened to say.
const chip = page.getByRole('button', { name: `Open ${PRODUCED}`, exact: true }).first()
await chip.waitFor({ timeout: 15_000 })
expect(await chip.innerText()).toBe(PRODUCED)
// The full path stays reachable for a reader who wants to copy it.
expect(await chip.getAttribute('title')).toContain(PRODUCED)
// A turn's produced files are labelled, not left as bare chips.
expect(await page.getByText('Produced', { exact: true }).count()).toBeGreaterThan(0)
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
}, 90_000)
})

View File

@@ -1,122 +0,0 @@
// Web e2e scenario: a produced file, from the row that lists it to the bytes
// the browser gets. Cold-seeds a recorded write turn (zero model calls).
// Package tests cover the derivation and the route in isolation, but only the
// assembled application shows that the turn's Produced row, the URL it opens,
// and the file on disk are the same thing (docs/testing.md snapshot rule).
import { readFile, writeFile, mkdir } from 'node:fs/promises'
import { join } from 'node:path'
import { fileURLToPath } from 'node:url'
import type { Browser, Page } from 'playwright'
import { chromium } from 'playwright'
import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
import {
launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
} from './scaffold.ts'
import { newEnglishPage, saveFailureShot } from './support.ts'
// Borrowed read-only: this scenario needs any settled turn whose tools WROTE a
// file, not a new recording (the message-actions borrowing pattern).
const SEED = fileURLToPath(new URL('./snapshots/permission-policy-context/session.jsonl', import.meta.url))
const MODE = webSnapshotMode()
const SEED_ID = 'workspace-file-open-web-e2e'
/** The file the borrowed recording's write tool produces. */
const PRODUCED = 'policy-neutral.txt'
/** An active document placed alongside it, for the isolation header the route puts on those. */
const ACTIVE = 'preview.html'
describe('web e2e: opening a produced file from the conversation', () => {
let scaffold: WebScaffold
let browser: Browser
let page: Page
let tripwire: ReturnType<typeof watchConsole>
beforeAll(async () => {
scaffold = await launchWebScaffold({})
// The seeded Session's cwd is the scaffold workspace; the recording's own
// nested directory is created too, so its paths stay resolvable.
await mkdir(join(scaffold.workspaceCwd, 'workspace'), { recursive: true })
await writeFile(join(scaffold.workspaceCwd, PRODUCED), 'neutral\n')
await writeFile(join(scaffold.workspaceCwd, ACTIVE), '<h1>produced</h1>\n')
const raw = await readFile(SEED, 'utf8')
expect(raw, 'borrowed recording must carry the write this scenario reads').toContain(PRODUCED)
await seedSession(scaffold, raw, SEED_ID)
browser = await chromium.launch()
page = await newEnglishPage(browser)
tripwire = watchConsole(page)
await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
}, 120_000)
afterAll(async () => {
await browser?.close()
await scaffold?.close()
})
it.skipIf(MODE === 'record')('ends the turn with its produced file, which opens as the workspace file itself', async () => {
onTestFailed(() => saveFailureShot(page, 'web-e2e-workspace-file-open'))
const groupRow = page.locator('[role="treeitem"]').first()
await groupRow.waitFor({ timeout: 15_000 })
await groupRow.click()
const sessionRow = page.locator('[role="treeitem"]').nth(1)
await sessionRow.waitFor({ timeout: 10_000 })
await sessionRow.click()
// The row the turn ends with — derived from the write call's locations,
// not from whatever the closing message happened to say.
const chip = page.getByRole('button', { name: `Open ${PRODUCED}`, exact: true }).first()
await chip.waitFor({ timeout: 15_000 })
expect(await chip.innerText()).toBe(PRODUCED)
const [opened] = await Promise.all([
page.context().waitForEvent('page', { timeout: 15_000 }),
chip.click(),
])
await opened.waitForLoadState('domcontentloaded')
const url = new URL(opened.url())
expect(url.pathname).toBe(`/f/${SEED_ID}/${PRODUCED}`)
expect(await opened.locator('body').innerText()).toContain('neutral')
// The isolation: previews come from the app's hostname on a DIFFERENT
// port, so a served document is cross-origin to /api while keeping its own
// capabilities. A workspace file is not necessarily agent-authored.
const app = new URL(scaffold.baseUrl)
expect(url.hostname).toBe(app.hostname)
expect(url.port).not.toBe(app.port)
const filesOrigin = url.origin
const served = await page.request.get(opened.url())
expect(served.status()).toBe(200)
expect(served.headers()['x-content-type-options']).toBe('nosniff')
expect(served.headers()['cache-control']).toBe('no-store')
// No document is stripped of its origin: the port is the boundary.
expect(served.headers()['content-security-policy']).toBeUndefined()
// An active document keeps its own storage — the capability a sandbox
// header would have taken, and the reason this route has its own port.
const active = opened
await active.goto(`${filesOrigin}/f/${SEED_ID}/${ACTIVE}`, { waitUntil: 'load' })
expect(await active.evaluate(() => {
try { window.localStorage.setItem('probe', '1'); return 'ok' } catch { return 'blocked' }
})).toBe('ok')
// …and cannot reach the API, which lives on the other origin.
expect(await active.evaluate(async (base) => {
try {
await fetch(`${base}/api/session.list`, {
method: 'POST', headers: { 'content-type': 'application/json' },
body: JSON.stringify({ type: 'client-request', rpcId: 'x', method: 'session.list', payload: {} }),
})
return 'reached'
} catch { return 'blocked' }
}, scaffold.baseUrl)).toBe('blocked')
// The workspace-file origin serves that one prefix and nothing else.
expect((await page.request.get(`${filesOrigin}/`)).status()).toBe(404)
// Nothing outside the Session's workspace is reachable through the route.
expect((await page.request.get(`${filesOrigin}/f/${SEED_ID}/..%2Fetc%2Fhosts`)).status()).toBe(404)
await active.close()
expect(tripwire.pageErrors).toEqual([])
expect(tripwire.warnings).toEqual([])
}, 90_000)
})

View File

@@ -51,7 +51,7 @@
"tests/access-confirmation.e2e.ts",
"tests/shipped-composition.e2e.ts",
"tests/startup-auto-selection.e2e.ts",
"tests/workspace-file-open.e2e.ts"
"tests/produced-files.e2e.ts"
],
"references": [
{

View File

@@ -296,7 +296,7 @@ export interface ConnectionConfig {
}
```
Source: [`packages/client/connection/src/index.ts:25`](../packages/client/connection/src/index.ts)
Source: [`packages/client/connection/src/index.ts:20`](../packages/client/connection/src/index.ts)
## `@deepseek-ai/dsh-client-hmr`

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/connection/README.md
README.md: 5001da2458ea3470659f5983dffc8de832aadeac
README.zh.md: 47e745964e4087c6ccc59aae5bbfba69f96480e4
README.md: c8b7c4787cbcbf6a202fb944459a589fcadd7c8d
README.zh.md: f36cb4c4c6856089751e4492eb6e4b8e22abde56

View File

@@ -2,22 +2,14 @@
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 node half owns both browser-facing prefixes — `/api` for RPC and `/f` for workspace-file reads — behind one trust fence. The `/api` route pins the privileged method set (`host.pickDirectory`, `host.openPath`, and the whole configuration plane — `settings.describe`/`update`/`replace`/`mutate` and `credentials.describe`/`set`/`unset`, reads included, since describing returns the exposed configuration and probing an arbitrary reference reports where a credential comes from) to loopback by passing the trust fence with an empty trust list — a declared `trustedHosts` authority reaches every other method, while these stay loopback-local until a real authentication layer exists. 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.
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 node half's `/api` route pins the privileged method set (`host.pickDirectory`, `host.openPath`, and the whole configuration plane — `settings.describe`/`update`/`replace`/`mutate` and `credentials.describe`/`set`/`unset`, reads included, since describing returns the exposed configuration and probing an arbitrary reference reports where a credential comes from) to loopback by passing the trust fence with an empty trust list — a declared `trustedHosts` authority reaches every other method, while these stay loopback-local until a real authentication layer exists. 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`). 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).
## /f workspace-file reads
The node half also serves one file at a time out of a Session's workspace under `/f/<sessionId>/<segments…>`, so a produced deliverable is reachable from the page that reported it — an `http` page cannot follow a `file://` link, and a browser that is not on the Host machine has no such path anyway. The segments ride the URL rather than a query parameter so a served document's relative references resolve to its siblings. The request names a Session and the gateway names that Session's directory (`ApiProxy.workspaceRootOf`, which answers from a live agent's header or the persistence store and never resumes an agent to serve a file); this package reads the authority rather than the core services, because holding their host-side Context declarations would merge them over the browser runtime's own. The URL shape itself lives with the other browser-importable contract surfaces, in [`@deepseek-ai/dsh-host-apiproxy/api`](../../host/apiproxy/README.md), so the browser half that builds a URL and this half that parses one share a single encoding decision. Both the cwd and the resolved target go through `realpath` before comparison, so a symlink inside the workspace pointing out of it is refused by its target rather than its name; traversal spellings are refused earlier still, at parse time, before any filesystem call. Reads stream (no request buffers a file), answer `GET`/`HEAD` only, and carry `nosniff` with `no-store`. Extensions outside the served content-type table are typed `text/plain` rather than offered as a download, because a workspace read is a request to see a file.
Workspace files are served from their own port, and therefore their own origin. That port is the isolation: a workspace file is not necessarily agent-authored — a read row makes every file in a cloned repository openable — so an active document served beside `/api` would have its script pass the browser-trust fence into every method, the loopback-pinned settings and credential plane included. A different origin closes that without touching the document: a preview keeps `localStorage`, cookies, and its own `fetch`, while a call to the API is cross-origin and refused twice over — by the fence's Origin check and by CORS. The alternative, `Content-Security-Policy: sandbox`, buys the same boundary by taking the document's origin away entirely, which measurably breaks the pages this route exists to show (a page that reads `localStorage` throws on load, and every listener declared after that line in the same script never binds). The listener binds the same host as the API, so a client that can reach the app can reach its previews; it answers the `/f` prefix and nothing else — no index, no SPA fallback, no API — and its port is published into the index page as `window.__DSH_FILES_PORT__`, which the browser half reads to address it. The same trust fence gates it, so a `trustedHosts` deployment serves workspace files exactly where it serves ordinary reads.
## Keyless fixture
A fixture page is served by no host, so no workspace-file port is published into it and `ConnectionHandle.fileUrl` answers `undefined` — a file-path row falls back to the Host opener rather than opening a dead tab.
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. Fixture content search preserves the production-facing `unicode61`-style case, diacritic, and token-phrase behavior and returns a match-centered snippet of at most 120 Unicode code points.
## Model Experience

View File

@@ -2,18 +2,12 @@
[English](README.md) | 中文
协议消费层:客户端插件的 apply 会挂载 `ctx.connection`(共享 API 客户端 + 单消费方流循环启动器);导出表层携带协议契约类型、`AbstractApiClient` seam以及循环的 sink配置类型。node 半侧持有两条面向浏览器的前缀——`/api` 承载 RPC`/f` 承载工作区文件读取——共用同一道信任 fence。`/api` 路由让特权方法集(`host.pickDirectory``host.openPath`,以及整个配置面——`settings.describe`/`update`/`replace`/`mutate``credentials.describe`/`set`/`unset`,读取也在内,因为 describe 会返回已暴露的配置,而探测任意引用会报出某条凭据来自何处)以空信任表过信任 fence从而钉在回环——已声明的 `trustedHosts` 授权可达其余全部方法而这些方法在真正的认证层出现之前仍只限回环本机。平台子类WebApiClient/FixtureApiClient、ConnectionController 循环和 fixture 数据源都属于包内部apply 负责选择并驱动它们,测试则通过 src 访问。契约api-contracts v3 §3。
协议消费层:客户端插件的 apply 会挂载 `ctx.connection`(共享 API 客户端 + 单消费方流循环启动器);导出表层携带协议契约类型、`AbstractApiClient` seam以及循环的 sink配置类型。node 半侧`/api` 路由让特权方法集(`host.pickDirectory``host.openPath`,以及整个配置面——`settings.describe`/`update`/`replace`/`mutate``credentials.describe`/`set`/`unset`,读取也在内,因为 describe 会返回已暴露的配置,而探测任意引用会报出某条凭据来自何处)以空信任表过信任 fence从而钉在回环——已声明的 `trustedHosts` 授权可达其余全部方法而这些方法在真正的认证层出现之前仍只限回环本机。平台子类WebApiClient/FixtureApiClient、ConnectionController 循环和 fixture 数据源都属于包内部apply 负责选择并驱动它们,测试则通过 src 访问。契约api-contracts v3 §3。
## /api 浏览器信任栅栏
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)。
## /f 工作区文件读取
node 半侧还会在 `/f/<sessionId>/<segments…>` 下逐个提供某个 Session 工作区里的文件,让产出的交付物能从报告它的那个页面直接抵达——`http` 页面无法跟随 `file://` 链接,而不在 Host 机器上的浏览器本来也没有那条路径。段落走 URL 而非查询参数,是为了让所服务文档的相对引用能解析到它的同级文件。请求指名一个 Session由网关指名该 Session 的目录(`ApiProxy.workspaceRootOf`,它从活跃 agent 的 header 或持久化存储作答,绝不会为了提供一个文件而恢复 agent本包读取这个权威来源而不去够核心服务因为持有它们的 host 侧 Context 声明会把它们盖到浏览器运行时自己的声明之上。URL 形状本身与其余浏览器可导入的契约面放在一起,位于 [`@deepseek-ai/dsh-host-apiproxy/api`](../../host/apiproxy/README.md),因此构造 URL 的浏览器半侧与解析 URL 的这一半共享同一个编码决定。cwd 与解析出的目标在比较前都要过 `realpath`,因此工作区内指向工作区外的符号链接会因其目标而被拒绝,而不是因其名字;穿越写法拒得更早,在解析期、任何文件系统调用之前。读取是流式的(没有请求会把文件缓冲起来),只应答 `GET``HEAD`,并带上 `nosniff``no-store`。所服务的内容类型表之外的扩展名一律按 `text/plain` 定型而非作为下载给出,因为工作区读取本就是一个“让我看看这个文件”的请求。
工作区文件由它自己的端口提供,因而拥有自己的源。那个端口就是隔离:工作区文件未必由 agent 撰写——一条 read 行就能让 clone 下来的仓库里任何文件变得可打开——因此与 `/api` 并排提供的活动文档,其脚本会带着浏览器信任 fence 通行到每一个方法,包括那些正因会改动设置与凭据而被钉在回环的方法。换一个源即可堵死这条,且不必动文档本身:预览保有 `localStorage`、cookie 与自己的 `fetch`,而对 API 的调用属于跨源会被两道独立的关卡拒绝——fence 的 Origin 校验,以及 CORS。另一种做法 `Content-Security-Policy: sandbox` 用"干脆剥夺文档的源"换来同一条边界,而这经实测会破坏本路由存在的意义所在的那类页面(读 `localStorage` 的页面在加载时抛异常,同一 script 块中该行之后声明的所有监听器都不会绑定)。该监听器绑定与 API 相同的 host因此能访问应用的客户端也能访问它的预览它只应答 `/f` 前缀,别无其他——没有首页、没有 SPA 兜底、没有 API——其端口以 `window.__DSH_FILES_PORT__` 注入首页,由浏览器半侧读取来寻址。它由同一道信任 fence 把守,因此配置了 `trustedHosts` 的部署提供工作区文件的范围,与它提供普通读取的范围完全一致。
## 无密钥 fixture
fixture 页面不由任何 host 提供,因此没有工作区文件端口注入其中,`ConnectionHandle.fileUrl` 应答 `undefined`——文件路径行会回退到 Host 打开器,而不是打开一个空标签页。

View File

@@ -2363,10 +2363,6 @@ export function createFixtureApi(options: FixtureOptions = {}): ApiProxy {
return Promise.resolve({ accepted: true })
},
// The fixture has no filesystem behind its Sessions, so it names no
// directory for any of them; the /f route belongs to the node half, which
// a fixture page never reaches.
workspaceRootOf: () => Promise.resolve(undefined),
}
}

View File

@@ -4,9 +4,6 @@
* controller with its sinks.
*/
import type { Context } from 'cordis'
import { workspaceFileSegments, workspaceFileUrl } from '@deepseek-ai/dsh-host-apiproxy/api'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { FILES_PORT_GLOBAL } from '../files-server.ts'
import type { IApiClient } from './api.ts'
import { ConnectionController, type ConnectionConfig, type ConnectionSinks, type ConnectionState } from './connection.ts'
import { FixtureApiClient } from './fixture.ts'
@@ -59,19 +56,6 @@ export interface ConnectionHandle {
* @returns stop handle for the loop.
*/
start(sinks: ConnectionSinks, config?: ConnectionConfig): { stop(): void }
/**
* Absolute URL serving one file out of a Session's workspace, on the
* transport's own workspace-file origin — the same hostname the page is
* reached by, a different port, so a served document is isolated from this
* API without being stripped of its own capabilities.
* @param sessionId - the Session whose cwd anchors the path.
* @param cwd - that Session's working directory, or `undefined` when unknown.
* @param path - the path a tool reported (absolute, or relative to `cwd`).
* @returns the URL, or `undefined` when the path lies outside the workspace
* (which this transport never serves) or when this page was not served by a
* host that published a workspace-file port (the fixture carrier).
*/
fileUrl(sessionId: SessionId, cwd: string | undefined, path: string): string | undefined
}
/**
@@ -84,15 +68,6 @@ export function apply(ctx: Context): void {
let started = false
const handle: ConnectionHandle = {
api,
fileUrl(sessionId, cwd, path) {
// Published by the node half's index tap; absent means no host is
// serving workspace files to this page (the keyless fixture lane).
const port = (globalThis as unknown as Record<string, unknown>)[FILES_PORT_GLOBAL]
if (typeof port !== 'number') return undefined
const segments = workspaceFileSegments(cwd, path)
if (segments === undefined) return undefined
return `${location.protocol}//${location.hostname}:${String(port)}${workspaceFileUrl(sessionId, segments)}`
},
start(sinks, config) {
if (started) throw new Error('connection: the stream loop is already owned by another consumer')
started = true

View File

@@ -1,127 +0,0 @@
/**
* The workspace-file listener: a second loopback/LAN socket on the same host
* as the API, serving nothing but `/f`.
*
* The port is the isolation. A workspace file is not necessarily
* agent-authored — a read row makes every file in a cloned repository
* openable — so an active document must not be same-origin with `/api`, where
* its script would pass the browser-trust fence into every method, the
* loopback-pinned settings and credential plane included. A different port is
* a different origin, which the browser enforces for free: the document keeps
* `localStorage`, cookies, and its own `fetch`, while a call to the API is
* cross-origin and refused twice over — by the fence's Origin check and by
* CORS. The alternative, `Content-Security-Policy: sandbox`, buys the same
* boundary by taking the document's origin away entirely, which measurably
* breaks the pages this route exists to show.
*/
import { createServer } from 'node:http'
import type { IncomingMessage, Server, ServerResponse } from 'node:http'
import type { AddressInfo } from 'node:net'
import { FILES_PATH } from '@deepseek-ai/dsh-host-apiproxy/api'
import { isTrustedApiRequest } from './api-request-trust.ts'
import { handleWorkspaceFile, type WorkspaceFileDeps } from './workspace-files.ts'
/** A listening workspace-file server: its port, and the teardown that reaches quiescence. */
export interface FilesServer {
/** The bound port (OS-assigned), which the browser half needs to address this origin. */
port: number
/** Close the socket and destroy held connections; resolves once quiet. */
close: () => Promise<void>
}
/**
* Bind the workspace-file listener.
* @param host - the same bind host the API uses, so a client that can reach
* the app can reach its previews (a LAN deployment included).
* @param trustedHosts - the deployment's non-loopback serving authorities,
* applied through the same fence as `/api`.
* @param deps - the session-to-directory lookup reads are confined by.
* @param onSocketError - reports a post-listen socket error; without a
* listener node would raise it as an unhandled 'error' event.
* @returns the bound port and its disposer.
*/
export async function listenForWorkspaceFiles(
host: string,
trustedHosts: readonly string[],
deps: WorkspaceFileDeps,
onSocketError: (error: Error) => void,
): Promise<FilesServer> {
const handle = async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
if (!isTrustedApiRequest(req, trustedHosts)) {
res.writeHead(403)
res.end('forbidden')
return
}
/* v8 ignore next -- `?? '/'` arm: node:http always sets url on server requests. */
const pathname = new URL(req.url ?? '/', 'http://dsh.internal').pathname
// This origin serves one prefix and nothing else: no index, no SPA
// fallback, no API. Anything else is not here — answered before the method
// check, because a 405 would claim the resource exists.
if (pathname !== FILES_PATH && !pathname.startsWith(`${FILES_PATH}/`)) {
res.writeHead(404)
res.end()
return
}
if (req.method !== 'GET' && req.method !== 'HEAD') {
// RFC 9110 §15.5.6: a 405 names the methods the resource does support.
res.writeHead(405, { allow: 'GET, HEAD' })
res.end()
return
}
await handleWorkspaceFile(req, res, deps)
}
const server: Server = createServer((req, res) => {
handle(req, res).catch((error: unknown) => {
// A malformed request must not become an unhandled rejection that takes
// the process down; the API carrier guards its own handler the same way.
if (res.headersSent) {
res.destroy()
return
}
onSocketError(error instanceof Error ? error : new Error(String(error)))
res.writeHead(400)
res.end()
})
})
await new Promise<void>((resolve, reject) => {
server.once('error', reject)
server.listen(0, host, () => {
server.off('error', reject)
server.on('error', onSocketError)
resolve()
})
})
return {
port: (server.address() as AddressInfo).port,
// close + closeAllConnections: a held-open response would otherwise keep
// teardown waiting forever.
close: () => new Promise<void>((resolve) => {
server.close(() => { resolve() })
server.closeAllConnections()
}),
}
}
/** The global the node half hands its port to the browser half through. */
export const FILES_PORT_GLOBAL = '__DSH_FILES_PORT__'
/**
* Inject the workspace-file port into index.html, ahead of the shell bundle
* that reads it. A boot-time fact of the serving host, delivered the way the
* module graph is: synchronously on the page, so the first click on a produced
* file does not race a round trip.
* @param html - the index.html source.
* @param port - the bound workspace-file port.
* @returns the html with the port script injected.
*/
export function injectFilesPort(html: string, port: number): string {
const script = `<script>window.${FILES_PORT_GLOBAL} = ${String(port)}</script>`
const head = html.indexOf('<head>')
if (head !== -1) return `${html.slice(0, head + 6)}${script}${html.slice(head + 6)}`
/* v8 ignore next -- headless fixture pages may lack <head>; prepending keeps read-before-shell ordering. */
return `${script}${html}`
}

View File

@@ -1,16 +1,11 @@
/** Host HTTP bridge for browser-client RPC and workspace-file reads. */
/** 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'
// The merge-free types subpath: pulling the session package's root into this
// client-registered program would merge the host `sessions` service over the
// browser runtime's own.
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { API_PATH } from './api-path.ts'
import { bridge } from './http-bridge.ts'
import { injectFilesPort, listenForWorkspaceFiles } from './files-server.ts'
import { assertTrustedAuthority, isTrustedApiRequest } from './api-request-trust.ts'
export { API_PATH } from './api-path.ts'
@@ -66,17 +61,15 @@ const PRIVILEGED_METHODS = new Set([
])
/**
* Mounts the API gateway and the workspace-file reads under the browser
* transport prefixes. Every request on either prefix passes the browser-trust
* fence first (DNS-rebinding and cross-site defense —
* [api-request-trust](./api-request-trust.ts)); privileged methods
* additionally pass it with an empty trust list, which pins them to loopback.
* 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));
* privileged methods additionally pass it with an empty trust list, which
* pins them to loopback.
* @param ctx - Host plugin context.
* @param config - resolved plugin config (schema defaults applied).
* @returns a promise settling once the workspace-file listener is bound and
* its port published — the page must never render before it can address one.
*/
export async function apply(ctx: Context, config?: ConnectionConfig): Promise<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 ?? []
// Config boundary: a malformed entry fails the load loudly here rather than
@@ -104,24 +97,4 @@ export async function apply(ctx: Context, config?: ConnectionConfig): Promise<vo
}
ctx.effect(() => ctx.httpServer.register(route), 'client-connection: /api route')
// The gateway is the host's session authority: it answers where a Session's
// files live without this package reaching into the core services, which
// would merge their host-side Context declarations into the browser lane.
const cwdFor = (sessionId: string): Promise<string | undefined> =>
ctx.apiProxy.workspaceRootOf(sessionId as SessionId)
// Workspace files get their own port, and therefore their own origin: an
// active document served beside `/api` would reach every method through the
// fence below. The listen is awaited inside the effect so the port is known
// before the index tap that publishes it can run.
await ctx.effect(async () => {
const files = await listenForWorkspaceFiles(
ctx.httpServer.host, trustedHosts, { cwdFor },
(error) => { ctx.logger.error(error) },
)
const untap = ctx.httpServer.tapIndex(html => injectFilesPort(html, files.port))
return async () => {
untap()
await files.close()
}
}, 'client-connection: /f listener')
}

View File

@@ -1,164 +0,0 @@
/**
* The read half of the web transport: streams one file out of a session's
* workspace so the browser can open what the agent just produced. The RPC
* gateway carries structured session state; this route carries bytes, which a
* JSON-RPC envelope cannot stream and a `file://` link cannot reach from an
* http page.
*
* Confinement is the whole contract: a request names a session, the session
* names its cwd, and nothing outside that realpath is ever served. The caller
* owns the browser-trust fence ([api-request-trust](./api-request-trust.ts)) —
* this module is reached only by requests that already passed it.
*
* Isolation is the listener's, not this module's: these responses carry no
* sandbox header because they are served from their own port, and therefore
* their own origin ([files-server](./files-server.ts)). A served document
* keeps `localStorage`, cookies, and its own `fetch`, while the API stays
* cross-origin to it.
*/
import { createReadStream } from 'node:fs'
import { realpath, stat } from 'node:fs/promises'
import type { IncomingMessage, ServerResponse } from 'node:http'
import { extname, resolve, sep } from 'node:path'
import { pipeline } from 'node:stream/promises'
import { parseWorkspaceFilePath } from '@deepseek-ai/dsh-host-apiproxy/api'
/**
* Content types served verbatim. Everything absent is `text/plain`, not
* `application/octet-stream`: a workspace read is a "show me what you made"
* gesture, and an unknown extension is far more often a source file to read
* than a binary to download. `nosniff` keeps that choice binding, so a
* mislabelled document can never be re-interpreted as HTML.
*/
const MIME: Record<string, string> = {
'.html': 'text/html; charset=utf-8',
'.htm': 'text/html; charset=utf-8',
'.xhtml': 'application/xhtml+xml',
'.svg': 'image/svg+xml',
'.css': 'text/css; charset=utf-8',
'.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8',
'.json': 'application/json',
'.pdf': 'application/pdf',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.jpeg': 'image/jpeg',
'.gif': 'image/gif',
'.webp': 'image/webp',
'.avif': 'image/avif',
'.ico': 'image/x-icon',
'.mp4': 'video/mp4',
'.webm': 'video/webm',
'.mp3': 'audio/mpeg',
'.wav': 'audio/wav',
'.wasm': 'application/wasm',
}
const DEFAULT_MIME = 'text/plain; charset=utf-8'
/** How the route learns which directory a session may serve from. */
export interface WorkspaceFileDeps {
/**
* The session's absolute working directory.
* @param sessionId - the session named by the request path.
* @returns its cwd, or `undefined` when the id names no session this host serves.
*/
cwdFor: (sessionId: string) => Promise<string | undefined>
}
function fail(res: ServerResponse, status: number): void {
res.writeHead(status)
res.end()
}
/**
* Resolve one request's segments against a session cwd, refusing anything that
* leaves it. Both sides go through `realpath`, so a symlink inside the
* workspace pointing out of it is refused by its resolved target rather than
* its name. A component swapped between this resolution and the open below
* would still be followed; closing that window needs privileges that already
* imply workspace write access, which is strictly stronger than reading a
* workspace file, so the check stops here.
*/
async function confine(cwd: string, segments: readonly string[]): Promise<string | undefined> {
const root = await realpath(cwd)
// A filesystem root already ends in the separator; appending a second one
// would make every child fail the prefix test and 403 the whole workspace.
const prefix = root.endsWith(sep) ? root : root + sep
const real = await realpath(resolve(root, ...segments))
return real.startsWith(prefix) ? real : undefined
}
/**
* Serve one workspace-file request. The caller has already applied the
* browser-trust fence and rejected non-read methods.
* @param req - the request, read for its url and method only (no body).
* @param res - the response this function owns to completion.
* @param deps - the session-to-cwd lookup this host answers with.
*/
export async function handleWorkspaceFile(
req: IncomingMessage,
res: ServerResponse,
deps: WorkspaceFileDeps,
): Promise<void> {
/* v8 ignore next -- `?? '/'` arm: node:http always sets url on server requests. */
const pathname = new URL(req.url ?? '/', 'http://dsh.internal').pathname
const target = parseWorkspaceFilePath(pathname)
if (target === undefined) {
fail(res, 404)
return
}
const cwd = await deps.cwdFor(target.sessionId)
if (cwd === undefined) {
fail(res, 404)
return
}
let file: string | undefined
let size: number
try {
file = await confine(cwd, target.segments)
if (file === undefined) {
fail(res, 403)
return
}
const info = await stat(file)
// A directory read has no answer here: the route serves files, and listing
// is the directory-picker capability's job, behind its own fence.
if (!info.isFile()) {
fail(res, 404)
return
}
size = info.size
} catch {
// Missing, unreadable, or a path whose ancestor is not a directory: all
// report as absent, so a probe cannot distinguish them.
fail(res, 404)
return
}
const ext = extname(file).toLowerCase()
res.writeHead(200, {
'content-type': MIME[ext] ?? DEFAULT_MIME,
'content-length': String(size),
'content-disposition': 'inline',
'x-content-type-options': 'nosniff',
// Workspace files change under the agent's hands; a cached preview would
// show the previous turn's output after the next edit.
'cache-control': 'no-store',
})
if (req.method === 'HEAD') {
res.end()
return
}
try {
// pipeline (not pipe) so a client disconnect destroys the read stream:
// an abandoned preview must not leave a descriptor open.
await pipeline(createReadStream(file), res)
} catch {
// The status line is already out, so a mid-stream read failure or client
// disconnect can only end the response abruptly.
res.destroy()
}
}

View File

@@ -8,11 +8,10 @@ import { apply, type ConnectionHandle } from '../src/client/index.ts'
import { FixtureApiClient } from '../src/client/fixture.ts'
import { WebApiClient } from '../src/client/web-api-client.ts'
type Win = { location?: { search: string; protocol?: string; hostname?: string }; __DSH_FILES_PORT__?: number }
type Win = { location?: { search: string } }
afterEach(() => {
delete (globalThis as Win).location
delete (globalThis as Win).__DSH_FILES_PORT__
})
async function mount(): Promise<ConnectionHandle> {
@@ -64,27 +63,4 @@ describe('connection client apply', () => {
expect(seen.some(u => u.includes('/api/'))).toBe(true)
})
it('addresses a workspace file on the port the host published, and only inside the workspace', async () => {
const win = globalThis as Win
win.location = { search: '', protocol: 'http:', hostname: '192.168.1.5' }
win.__DSH_FILES_PORT__ = 4321
const handle = await mount()
const session = 's-1' as never
// Same hostname the page was reached by — a LAN client must reach previews
// too — and the published port, which is what makes it another origin.
expect(handle.fileUrl(session, '/w/alpha', '/w/alpha/out/a b.html'))
.toBe('http://192.168.1.5:4321/f/s-1/out/a%20b.html')
// Outside the workspace there is nothing this transport may serve, which
// is the signal a caller falls back to openPath on.
expect(handle.fileUrl(session, '/w/alpha', '/etc/hosts')).toBeUndefined()
})
it('serves no file URL on a page no host published a port into', async () => {
const win = globalThis as Win
win.location = { search: '?fixture', protocol: 'http:', hostname: '127.0.0.1' }
const handle = await mount()
// The keyless fixture lane: no workspace-file origin exists, so the row
// falls back to the Host opener instead of opening a dead tab.
expect(handle.fileUrl('s-1' as never, '/w', 'a.txt')).toBeUndefined()
})
})

View File

@@ -1,44 +0,0 @@
/** The workspace-file listener's own failure and publication paths. */
import { describe, expect, it } from 'vitest'
import { FILES_PATH } from '@deepseek-ai/dsh-host-apiproxy/api'
import { injectFilesPort, listenForWorkspaceFiles } from '../src/files-server.ts'
describe('workspace-file listener', () => {
it('answers 400 and reports the failure when the directory lookup throws', async () => {
const seen: Error[] = []
const files = await listenForWorkspaceFiles(
'127.0.0.1', [],
{ cwdFor: () => Promise.reject(new Error('store unavailable')) },
(error) => { seen.push(error) },
)
try {
// A lookup failure is the host's problem, not a miss: it must not become
// an unhandled rejection, and it must not be reported as "not found".
const response = await fetch(`http://127.0.0.1:${String(files.port)}${FILES_PATH}/s-1/a.txt`)
expect(response.status).toBe(400)
expect(seen.map(error => error.message)).toEqual(['store unavailable'])
} finally {
await files.close()
}
})
it('closes idempotently and stops answering', async () => {
const files = await listenForWorkspaceFiles(
'127.0.0.1', [], { cwdFor: async () => undefined }, () => {},
)
const origin = `http://127.0.0.1:${String(files.port)}`
expect((await fetch(`${origin}${FILES_PATH}/s-1/a.txt`)).status).toBe(404)
await files.close()
await files.close()
await expect(fetch(`${origin}${FILES_PATH}/s-1/a.txt`)).rejects.toThrow()
})
})
describe('injectFilesPort', () => {
it('publishes the port as the first script in head', () => {
const html = injectFilesPort('<html><head><title>x</title></head></html>', 4321)
expect(html).toContain('<head><script>window.__DSH_FILES_PORT__ = 4321</script>')
// Ahead of anything the shell might read it from.
expect(html.indexOf('__DSH_FILES_PORT__')).toBeLessThan(html.indexOf('<title>'))
})
})

View File

@@ -1,9 +1,6 @@
/** Node half: registers the /api and /f prefix routes over the api gateway and the session workspaces. */
/** Node half: registers the /api prefix route bridging to the api gateway. */
import { EventEmitter } from 'node:events'
import { createServer, request as httpRequest } from 'node:http'
import { mkdtemp, rm, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { Readable } from 'node:stream'
import { Context } from 'cordis'
import { describe, expect, it } from 'vitest'
@@ -11,25 +8,17 @@ import type { AddressInfo } from 'node:net'
import type { IncomingMessage, ServerResponse } from 'node:http'
import type { ApiProxy } from '@deepseek-ai/dsh-host-apiproxy/api'
import type { HttpServerService, WebRoute } from '@deepseek-ai/dsh-host-webserver'
import { FILES_PATH } from '@deepseek-ai/dsh-host-apiproxy/api'
import { API_PATH, apply, inject } from '../src/index.ts'
/** Structural httpServer fake: the plugin only touches register(). */
function fakeHttpServer(
routes: WebRoute[],
taps: ((html: string) => string)[] = [],
): Pick<HttpServerService, 'register' | 'tapIndex' | 'port' | 'host'> {
function fakeHttpServer(routes: WebRoute[]): Pick<HttpServerService, 'register' | 'tapIndex' | 'port'> {
return {
register(route) {
routes.push(route)
return () => { routes.splice(routes.indexOf(route), 1) }
},
tapIndex(transform) {
taps.push(transform)
return () => { taps.splice(taps.indexOf(transform), 1) }
},
tapIndex: () => () => {},
port: 0,
host: '127.0.0.1',
}
}
@@ -60,47 +49,14 @@ function fakeResponse(): { response: ServerResponse; state: { status?: number; b
return { response, state }
}
/** The gateway stub: only the session-directory authority the /f route reads. */
function fakeApiProxy(workspaces: Record<string, string> = {}): ApiProxy {
return { workspaceRootOf: async (id: string) => workspaces[id] } as unknown as ApiProxy
}
async function mounted(
config?: { trustedHosts?: string[] },
workspaces: Record<string, string> = {},
): Promise<{ routes: WebRoute[]; taps: ((html: string) => string)[]; dispose: () => Promise<void> }> {
async function mounted(config?: { trustedHosts?: string[] }): Promise<{ routes: WebRoute[]; dispose: () => Promise<void> }> {
const ctx = new Context()
const routes: WebRoute[] = []
const taps: ((html: string) => string)[] = []
ctx.provide('httpServer', fakeHttpServer(routes, taps) as HttpServerService)
ctx.provide('apiProxy', fakeApiProxy(workspaces))
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, taps, dispose: () => fiber.dispose() }
}
/** One raw GET whose Host header is spoofed (fetch forbids setting it). */
function statusWithHost(origin: string, path: string, host: string): Promise<number> {
const url = new URL(origin)
return new Promise((resolve, reject) => {
const request = httpRequest(
{ host: url.hostname, port: url.port, path, method: 'GET', headers: { host } },
(response) => {
response.resume()
response.on('end', () => { resolve(response.statusCode ?? 0) })
},
)
request.on('error', reject)
request.end()
})
}
/** The workspace-file origin the node half published into the index page. */
function filesOrigin(taps: ((html: string) => string)[]): string {
const html = taps.reduce((acc, tap) => tap(acc), '<head></head>')
const port = /__DSH_FILES_PORT__ = (\d+)/.exec(html)?.[1]
if (port === undefined) throw new Error(`no workspace-file port was published: ${html}`)
return `http://127.0.0.1:${port}`
return { routes, dispose: () => fiber.dispose() }
}
describe('connection node half', () => {
@@ -108,25 +64,17 @@ describe('connection node half', () => {
const routes: WebRoute[] = []
const ctx = new Context()
ctx.provide('httpServer', fakeHttpServer(routes) as HttpServerService)
ctx.provide('apiProxy', fakeApiProxy())
ctx.provide('apiProxy', {} as unknown as ApiProxy)
const fiber = ctx.plugin({ inject: [...inject], apply }, { trustedHosts: ['harness.internal/path'] })
await expect(fiber).rejects.toThrow(/not a bare host\[:port\] authority/)
expect(routes).toHaveLength(0)
})
it('registers the /api route and publishes a separate workspace-file origin, both removed with the fiber', async () => {
const { routes, taps, dispose } = await mounted()
// The API keeps one prefix on the shared server; workspace files get a
// port of their own, which is the origin boundary between them.
it('registers the /api prefix route and removes it with the fiber', async () => {
const { routes, dispose } = await mounted()
expect(routes).toMatchObject([{ kind: 'prefix', path: API_PATH }])
const origin = filesOrigin(taps)
expect(new URL(origin).port).not.toBe('')
expect((await fetch(`${origin}${FILES_PATH}/absent/x.txt`)).status).toBe(404)
await dispose()
expect(routes).toHaveLength(0)
expect(taps).toHaveLength(0)
// Disposal reaches quiescence: the socket is gone, not merely unrouted.
await expect(fetch(`${origin}${FILES_PATH}/absent/x.txt`)).rejects.toThrow()
})
it('refuses an untrusted Host on any /api path before the bridge runs', async () => {
@@ -187,48 +135,6 @@ describe('connection node half', () => {
})
})
describe('connection node half: the workspace-file origin', () => {
/** A workspace holding one file, torn down with the returned disposer. */
async function workspace(): Promise<{ cwd: string; remove: () => Promise<void> }> {
const cwd = await mkdtemp(join(tmpdir(), 'dsh-node-half-'))
await writeFile(join(cwd, 'index.html'), '<h1>ok</h1>')
return { cwd, remove: () => rm(cwd, { recursive: true, force: true }) }
}
it('applies the same browser-trust fence as /api, refuses writes, and serves nothing else', async () => {
const { taps, dispose } = await mounted()
const origin = filesOrigin(taps)
// Rebound Host: refused before any filesystem work, exactly as on /api.
// node's fetch refuses to set Host (a forbidden header), so the spoof goes
// through the raw client — the same parse the server really performs.
expect(await statusWithHost(origin, `${FILES_PATH}/s-1/index.html`, 'harness.example')).toBe(403)
const written = await fetch(`${origin}${FILES_PATH}/s-1/index.html`, { method: 'POST' })
expect(written.status).toBe(405)
expect(written.headers.get('allow')).toBe('GET, HEAD')
// This origin is one route wide: no index, no SPA fallback, no API.
expect((await fetch(`${origin}/`)).status).toBe(404)
expect((await fetch(`${origin}${API_PATH}/session.list`, { method: 'POST' })).status).toBe(404)
await dispose()
})
it('confines reads to the directory the gateway names for that session', async () => {
const { cwd, remove } = await workspace()
const { taps, dispose } = await mounted(undefined, { 's-1': cwd })
const origin = filesOrigin(taps)
const served = await fetch(`${origin}${FILES_PATH}/s-1/index.html`)
expect(served.status).toBe(200)
expect(await served.text()).toBe('<h1>ok</h1>')
// A served document keeps its own capabilities: the port is the boundary,
// so nothing here strips the document of its origin.
expect(served.headers.get('content-security-policy')).toBeNull()
// A session the gateway names no directory for has no workspace to confine
// against, so there is nothing to serve.
expect((await fetch(`${origin}${FILES_PATH}/s-absent/index.html`)).status).toBe(404)
await dispose()
await remove()
})
})
describe('connection node half over a real HTTP server', () => {
/** Serve the registered prefix route from a real server and return its port. */
async function serve(routes: WebRoute[]): Promise<{ port: number; close: () => Promise<void> }> {

View File

@@ -1,142 +0,0 @@
/**
* Workspace-file reads over a real HTTP server and a real temporary
* workspace: confinement, content typing, and the sandbox header are wire
* facts, so they are asserted against responses Node actually produced.
*/
import { createServer } from 'node:http'
import type { AddressInfo } from 'node:net'
import type { ServerResponse } from 'node:http'
import { mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join, sep } from 'node:path'
import { Writable } from 'node:stream'
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
import { FILES_PATH } from '@deepseek-ai/dsh-host-apiproxy/api'
import { handleWorkspaceFile } from '../src/workspace-files.ts'
const SESSION = 's-1'
let workspace: string
let outside: string
let origin: string
let close: () => Promise<void>
beforeAll(async () => {
const root = await mkdtemp(join(tmpdir(), 'dsh-files-'))
workspace = join(root, 'workspace')
outside = join(root, 'outside')
await mkdir(join(workspace, 'out'), { recursive: true })
await mkdir(outside, { recursive: true })
await writeFile(join(workspace, 'index.html'), '<h1>产物</h1>')
await writeFile(join(workspace, 'notes.txt'), 'plain')
await writeFile(join(workspace, 'chart.svg'), '<svg xmlns="http://www.w3.org/2000/svg"/>')
await writeFile(join(workspace, 'model.safetensors'), 'unknown extension')
await writeFile(join(workspace, 'out', 'page.html'), '<p>nested</p>')
await writeFile(join(outside, 'secret.html'), 'SECRET')
await symlink(join(outside, 'secret.html'), join(workspace, 'escape.html'))
const server = createServer((req, res) => {
void handleWorkspaceFile(req, res, {
// 'rooted' names the filesystem root, the separator-terminated realpath case.
cwdFor: async sessionId => sessionId === SESSION ? workspace : sessionId === 'rooted' ? sep : undefined,
})
})
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
origin = `http://127.0.0.1:${String((server.address() as AddressInfo).port)}`
close = () => new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error === undefined || error === null) resolve()
else reject(error)
})
})
return async () => { await rm(root, { recursive: true, force: true }) }
})
afterAll(async () => { await close() })
function get(path: string, init?: RequestInit): Promise<Response> {
return fetch(`${origin}${path}`, init)
}
describe('workspace file reads', () => {
it('serves a produced document with its own capabilities intact', async () => {
const response = await get(`${FILES_PATH}/${SESSION}/index.html`)
expect(response.status).toBe(200)
expect(await response.text()).toBe('<h1>产物</h1>')
expect(response.headers.get('content-type')).toBe('text/html; charset=utf-8')
// No isolation header: the listener's own port is the origin boundary, so
// a preview keeps localStorage and cookies (see files-server).
expect(response.headers.get('content-security-policy')).toBeNull()
expect(response.headers.get('x-content-type-options')).toBe('nosniff')
expect(response.headers.get('cache-control')).toBe('no-store')
expect(response.headers.get('content-disposition')).toBe('inline')
})
it('types SVG as a standalone document rather than sniffable bytes', async () => {
const svg = await get(`${FILES_PATH}/${SESSION}/chart.svg`)
expect(svg.headers.get('content-type')).toBe('image/svg+xml')
expect(svg.headers.get('x-content-type-options')).toBe('nosniff')
const text = await get(`${FILES_PATH}/${SESSION}/notes.txt`)
expect(text.headers.get('content-type')).toBe('text/plain; charset=utf-8')
})
it('serves a workspace rooted at a filesystem root, whose realpath already ends in a separator', async () => {
// `realpath('/')` is '/', so a naive `root + sep` prefix is '//' and every
// child of that workspace would 403.
const rooted = await fetch(`${origin}${FILES_PATH}/rooted${new URL(`file://${workspace}/notes.txt`).pathname}`)
expect(rooted.status).toBe(200)
expect(await rooted.text()).toBe('plain')
})
it('shows an unknown extension as text rather than downloading it', async () => {
const response = await get(`${FILES_PATH}/${SESSION}/model.safetensors`)
expect(response.status).toBe(200)
expect(response.headers.get('content-type')).toBe('text/plain; charset=utf-8')
})
it('serves a nested path, so a document reaches its own siblings', async () => {
const response = await get(`${FILES_PATH}/${SESSION}/out/page.html`)
expect(response.status).toBe(200)
expect(await response.text()).toBe('<p>nested</p>')
})
it('answers HEAD with the length and no body', async () => {
const response = await get(`${FILES_PATH}/${SESSION}/notes.txt`, { method: 'HEAD' })
expect(response.status).toBe(200)
expect(response.headers.get('content-length')).toBe('5')
expect(await response.text()).toBe('')
})
it('refuses a symlink whose target leaves the workspace', async () => {
const response = await get(`${FILES_PATH}/${SESSION}/escape.html`)
expect(response.status).toBe(403)
expect(await response.text()).not.toContain('SECRET')
})
it('reports missing files, directories, and unknown sessions as absent', async () => {
expect((await get(`${FILES_PATH}/${SESSION}/nope.html`)).status).toBe(404)
expect((await get(`${FILES_PATH}/${SESSION}/out`)).status).toBe(404)
// A path whose ancestor is a file, not a directory.
expect((await get(`${FILES_PATH}/${SESSION}/notes.txt/child`)).status).toBe(404)
expect((await get(`${FILES_PATH}/s-other/index.html`)).status).toBe(404)
expect((await get(`${FILES_PATH}/${SESSION}`)).status).toBe(404)
})
})
describe('workspace file streaming failures', () => {
it('tears the response down instead of rejecting when the body cannot be written', async () => {
// A client that goes away mid-stream must not surface as a handler
// rejection: the webserver's last-resort guard would log it and try to
// answer 400 on a response whose status line is already out.
const sink = new Writable({
write(_chunk, _encoding, callback) { callback(new Error('socket gone')) },
})
const response = Object.assign(sink, { writeHead: () => response }) as unknown as ServerResponse
await expect(handleWorkspaceFile(
{ url: `${FILES_PATH}/${SESSION}/index.html`, method: 'GET', headers: {} } as never,
response,
{ cwdFor: async () => workspace },
)).resolves.toBeUndefined()
expect(sink.destroyed).toBe(true)
})
})

View File

@@ -26,7 +26,6 @@ async function mount(): Promise<Bench> {
const bench: Bench = { ctx, api, sinks: undefined, stopped: 0 }
const handle: ConnectionHandle = {
api,
fileUrl: () => undefined,
start: (sinks) => {
bench.sinks = sinks
return { stop: () => { bench.stopped += 1 } }

View File

@@ -20,7 +20,6 @@ async function mount(): Promise<Bench> {
const bench: Bench = { ctx, sinks: undefined }
const handle: ConnectionHandle = {
api,
fileUrl: () => undefined,
start: (sinks) => {
bench.sinks = sinks
return { stop: () => {} }

View File

@@ -25,7 +25,6 @@
"vitest": "^4.1.8"
},
"peerDependencies": {
"@deepseek-ai/dsh-client-connection": "^0.0.1",
"@deepseek-ai/dsh-client-runtime": "^0.0.1",
"@deepseek-ai/dsh-client-ui-slots": "^0.0.1",
"@deepseek-ai/dsh-client-web-react": "^0.0.1",
@@ -36,7 +35,6 @@
"react-dom": "^18.2.0"
},
"devDependencies": {
"@deepseek-ai/dsh-client-connection": "workspace:^",
"@deepseek-ai/dsh-client-runtime": "workspace:^",
"@deepseek-ai/dsh-client-ui-slots": "workspace:^",
"@deepseek-ai/dsh-client-web-react": "workspace:^",

View File

@@ -1,48 +0,0 @@
/** Test-owned connection face: the transport members features read off `ctx.connection`. */
import { workspaceFileSegments, workspaceFileUrl } from '@deepseek-ai/dsh-host-apiproxy/api'
import type { ConnectionHandle, IApiClient, SessionId } from '@deepseek-ai/dsh-client-connection/client'
/**
* Connection test double. Implements the same `ConnectionHandle` face features
* receive as `ctx.connection`, so a production face change breaks this double
* at compile time. The wire client is not modelled — a feature that needs one
* composes its own connection over a fake api client; this double exists for
* the transport facts features read synchronously, above all the
* workspace-file URL.
*/
export class TestConnection implements ConnectionHandle {
/**
* The workspace-file port the host would have published into the page.
* Unset — the default, and the keyless fixture lane's real state — makes
* {@link TestConnection.fileUrl} answer `undefined`, which is the signal a
* caller falls back to the Host opener on.
*/
filesPort: number | undefined
/** The wire client; unused by this double's consumers and absent by construction. */
readonly api: IApiClient = undefined as unknown as IApiClient
/**
* Stream-loop starter (inert).
* @returns a stop handle that does nothing.
*/
start(): { stop(): void } {
return { stop: () => {} }
}
/**
* Workspace-file URL, deriving exactly as production does so a feature test
* sees the real inside/outside-workspace split.
* @param sessionId - the Session whose cwd anchors the path.
* @param cwd - that Session's working directory.
* @param path - the path a tool reported.
* @returns the absolute URL on the workspace-file origin, or undefined when
* the path leaves the workspace or no port is published.
*/
fileUrl(sessionId: SessionId, cwd: string | undefined, path: string): string | undefined {
if (this.filesPort === undefined) return undefined
const segments = workspaceFileSegments(cwd, path)
if (segments === undefined) return undefined
return `http://localhost:${String(this.filesPort)}${workspaceFileUrl(sessionId, segments)}`
}
}

View File

@@ -29,13 +29,11 @@ import type {
} from '@deepseek-ai/dsh-client-ui-slots'
import { registerDomSnapshotSerializer } from './snapshot.ts'
import { TestSessions } from './sessions.ts'
import { TestConnection } from './connection.ts'
import { TestWorkspaces } from './workspaces.ts'
import type { Stabilizer } from './fixtures.ts'
export { domSnapshotSerializer, registerDomSnapshotSerializer } from './snapshot.ts'
export { FixtureSession, TestSessions } from './sessions.ts'
export { TestConnection } from './connection.ts'
export { TestWorkspaces } from './workspaces.ts'
export { conversationSnapshot, workspaceListState } from './fixtures.ts'
export type { SessionBehaviorOverrides, SessionFixture, Stabilizer } from './fixtures.ts'
@@ -177,8 +175,6 @@ export class SlotTestRuntime {
readonly sessions: TestSessions
/** Workspaces double (list observable, recorded intent actions). */
readonly workspaces: TestWorkspaces
/** The transport double features read as `ctx.connection`. */
readonly connection: TestConnection
private readonly stabilizer: Stabilizer = async (fn) => {
await act(async () => { await fn() })
@@ -199,10 +195,8 @@ export class SlotTestRuntime {
this.root = new TestRoot(slots, this.stabilizer)
this.sessions = new TestSessions(this.stabilizer, ctx)
this.workspaces = new TestWorkspaces(this.stabilizer)
this.connection = new TestConnection()
ctx.provide('sessions', this.sessions)
ctx.provide('workspaces', this.workspaces)
ctx.provide('connection', this.connection)
// Capturing install: the production renderer does the rendering; the
// wrapper only takes the host face for storeOf (no machinery copied).
const renderer = createSlotRenderer()

View File

@@ -17,9 +17,6 @@
{
"path": "../web-react"
},
{
"path": "../connection"
},
{
"path": "../runtime"
},

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/ui-conversation/README.md
README.md: 8c2075d615eccad1bbc7f5de1255ea4add69fab8
README.zh.md: 634721b4248da75cbd4e81528340936a31ece28d
README.md: a9d4aadf4b0acc21f3909319724645c10f08bd31
README.zh.md: 16be57c9ed8f8101a61eb704ba5e94491803d9b5

View File

@@ -14,7 +14,7 @@ Approvals take over the composer through the chain this package declares: `Appro
Logged non-user messages render as a default-collapsed `上下文注入` disclosure. It shares the Tool calls header geometry and interaction with `ToolRow` through the package-internal `DisclosureRow`, while retaining context semantics: the expanded body follows its content height up to a 141px scrolling cap, shows inline JSON for both `content` and `source`, and synthesizes no tool state, summary, or keyed toolview dispatch ([decision](../../../.agents/notes/implemented/feature/2026-07-30-web-context-injection-disclosure.md)).
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: one inside the session workspace opens in a new browser tab on the transport's workspace-file origin (`ConnectionHandle.fileUrl`), so a client that is not on the Host machine still sees it; one outside the workspace has no served URL and falls back to 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.
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 an underlined link — it reads as one at rest, not only on hover, because a path styled like the surrounding prose is an affordance nobody finds — and it opens the file through the Host (`host.openPath`, relative paths resolve against the session cwd). A document a browser renders opens in the default browser rather than the type's default application, so a produced page is shown rather than edited. The Host opens it on the Host's own machine: a client reached over a network sees nothing, which is the deliberate scope of this surface. 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.
A tool call declaring the `terminal` render intent renders its command output inline, at both conversation render sites, through ui-primitives' `TerminalBlock`. `contract/terminal-card-model.ts` is the single derivation from the snapshot's `callView`/`resultView` pair, so the sites cannot disagree about a command, its cwd, or its exit status; it yields null — the generic path — for any other card tag, including one this client version does not know. Both sites therefore also show the card's run-state dot, which is the same `StateDot` semantic a tool row's leading icon carries, so a row and its own card always agree about one command's state. A multi-line command gets one prompt row per line, with the dot marking the call once on the first row — the exit status is the whole call's, so a dot per line would claim a per-line outcome bash does not report. The keyed `BashRow` carries the card resident below its summary row; since tool rows are no longer details-panel click targets, the card's copy and expand controls are the row's only interactions. The render-site fallback row keeps the card behind its existing expand control. Rows cap at `CHAT_TERMINAL_MAX_LINES` (8) against the panel's 16, which is what keeps a summary surface bounded — the panel stays the single-call reading surface. Inline output is licensed per render intent — the terminal and web cards, each with its own bound; a generic tool's content remains panel-only ([decision](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md)).

View File

@@ -12,7 +12,7 @@
已记录的非用户消息渲染为默认折叠的 `上下文注入` 展开项。它通过包内部的 `DisclosureRow``ToolRow` 共享 Tool calls 标题栏的几何与交互,同时保留上下文语义:展开内容区的高度会随内容自适应,最大为 141px超出后滚动并以内联 JSON 展示 `content``source`,且不会合成工具状态、摘要或键控 toolview 分发([决策](../../../.agents/notes/implemented/feature/2026-07-30-web-context-injection-disclosure.md))。
通用工具行把内置的 bash、read、search、write、edit 和 run_code 名称归入专用视觉变体。文件系统变体会渲染 edit 图标和路径摘要;该路径是悬停下划线链接,点击即打开文件:位于会话工作区之内的文件在新浏览器标签页打开,位于传输层的工作区文件源上(`ConnectionHandle.fileUrl`),因此不在 Host 机器上的客户端也能看到;工作区之外的文件没有可服务的 URL回退到宿主操作系统的默认应用`host.openPath`,相对路径相对会话 cwd 解析)。工具行不再是整行点击目标,也不会打开 details 面板。code 变体以模型撰写的 `description` 作摘要,展开后显示程序本身;其已记录的子调用经由同一个键控 toolview 空位渲染为始终可见的嵌套行(自定义注册和 GenericToolCard fallback 原样适用于子行。Cordis 生命周期工具复用这些通用变体,同时以统一的 Cordis 强调色呈现 `Inspect``Mount temporary Plugin``Unmount temporary Plugin`mount 行保留 code 变体的可展开源码渲染。
通用工具行把内置的 bash、read、search、write、edit 和 run_code 名称归入专用视觉变体。文件系统变体会渲染 edit 图标和路径摘要;该路径是下划线的链接——静止状态下就读得出是链接,而不只在悬停时,因为一条与周围正文同样样式的路径是没人会发现的交互——点击即经由 Host 打开文件(`host.openPath`,相对路径相对会话 cwd 解析。浏览器能渲染的文档会用默认浏览器打开而不是该类型的默认应用因此产出的页面是被展示而不是被编辑。Host 在它自己的机器上打开:经网络访问的客户端看不到任何东西,这是本交互面刻意划定的范围。工具行不再是整行点击目标,也不会打开 details 面板。code 变体以模型撰写的 `description` 作摘要,展开后显示程序本身;其已记录的子调用经由同一个键控 toolview 空位渲染为始终可见的嵌套行(自定义注册和 GenericToolCard fallback 原样适用于子行。Cordis 生命周期工具复用这些通用变体,同时以统一的 Cordis 强调色呈现 `Inspect``Mount temporary Plugin``Unmount temporary Plugin`mount 行保留 code 变体的可展开源码渲染。
声明 `terminal` 渲染意图的工具调用,会在两个对话渲染点上都通过 ui-primitives 的 `TerminalBlock` 内联渲染其命令输出。`contract/terminal-card-model.ts` 是从快照的 `callView``resultView` 对推导的唯一位置因此两个渲染点不可能在命令、cwd 或退出状态上产生分歧;对任何其他 card 标签——包括当前客户端版本不认识的标签——它返回 null落回通用路径。因此两个渲染点也都显示卡片的运行状态点它与工具行行首图标承载同一套 `StateDot` 语义,所以一行与其自身的卡片对同一条命令的状态总是一致。多行命令的每一行各占一个提示行,状态点只在第一行为整次调用标记一次——退出状态属于整次调用,因此每行一枚就会声称一个 bash 并不报告的逐行结果。键控的 `BashRow` 把卡片常驻在摘要行下方;由于工具行已不再是详情面板的点击目标,卡片的复制与展开控件就是该行唯一的交互。渲染点兜底行则保持其既有的展开控件。行的上限是 `CHAT_TERMINAL_MAX_LINES`8面板为 16正是这一点让摘要面保持有界——面板仍是单次调用的阅读面。内联输出按渲染意图开放——终端卡片与 web 卡片,各有自己的上限;通用工具的内容仍然只在面板中呈现([决策](../../../.agents/notes/implemented/feature/2026-07-28-web-terminal-card.md))。

View File

@@ -39,7 +39,6 @@
"clsx": "^2.0.0"
},
"peerDependencies": {
"@deepseek-ai/dsh-client-connection": "^0.0.1",
"@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",
@@ -51,7 +50,6 @@
"react": "^18.2.0"
},
"devDependencies": {
"@deepseek-ai/dsh-client-connection": "workspace:^",
"@deepseek-ai/dsh-client-locale": "workspace:^",
"@deepseek-ai/dsh-client-runtime": "workspace:^",
"@deepseek-ai/dsh-client-test-runtime": "workspace:^",

View File

@@ -2,7 +2,6 @@
import type { Context } from 'cordis'
import { resolveSlotLabel, type BoundActions } from '@deepseek-ai/dsh-client-ui-slots'
import type { ISessions, SessionId } from '@deepseek-ai/dsh-client-runtime/client'
import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'
import type {} from '@deepseek-ai/dsh-client-ui-layout/client'
// Type-only: pulls the locale plugin's Context merge (ctx.locale).
import type {} from '@deepseek-ai/dsh-client-locale/client'
@@ -43,7 +42,7 @@ declare module '@deepseek-ai/dsh-client-ui-slots' {
}
/** Services required by the conversation plugin. */
export const inject = ['slots', 'layout', 'sessions', 'workspaces', 'locale', 'connection']
export const inject = ['slots', 'layout', 'sessions', 'workspaces', 'locale']
// Static no-session sources for the composer-bar hooks compartment: module
// constants so the render side's per-source hook cache (observableHook) keeps
@@ -276,16 +275,6 @@ export function apply(ctx: Context): void {
},
openFile: (path) => {
const cwd = sessions.list.getSnapshot().byId[sessionId]?.cwd
// A file inside the workspace opens in a new tab on the transport's
// workspace-file origin, so a browser that is not on the Host machine
// can still see what the agent produced. Anything outside it has no
// served URL and falls back to the Host's own opener, which is
// loopback-only by the /api trust fence.
const url = (ctx.get('connection') as ConnectionHandle).fileUrl(sessionId, cwd, path)
if (url !== undefined) {
window.open(url, '_blank', 'noopener,noreferrer')
return
}
void workspaces.openPath(resolveToolPath(cwd, path)).catch(() => {
// Host/OS open failures stay silent in the chat row; the native
// app surfaces its own error dialog when the path is unusable.

View File

@@ -84,7 +84,10 @@
color: var(--dsw-alias-label-tertiary);
}
/* File-tool path: same geometry as .summary; hover underline + pointer. */
/* File-tool path: same geometry as .summary, but it must READ as a link. A
path styled exactly like the surrounding prose, underlined only on hover, is
an affordance nobody finds — the reported "I can't open what it made" was
this, not a missing capability. */
.fileLink {
flex: 1 1 auto;
min-width: 0;
@@ -99,12 +102,16 @@
text-align: left;
font-size: 14px;
line-height: 24px;
color: var(--dsw-alias-label-tertiary);
color: var(--dsw-alias-label-secondary);
text-decoration: underline;
text-decoration-color: var(--dsw-alias-label-quaternary);
text-underline-offset: 3px;
cursor: pointer;
}
.fileLink:hover {
text-decoration: underline;
color: var(--dsw-alias-label-primary);
text-decoration-color: currentColor;
}
/* Error row's collapsed summary: the failure's first line in the error color. */

View File

@@ -218,25 +218,13 @@ describe('conversation slot inject surface', () => {
await b.runtime.dispose()
})
it('openFile (chat view face) opens a workspace file in a tab and falls back to the host opener outside it', async () => {
it('openFile (chat view face) resolves against session cwd and calls workspaces.openPath', async () => {
const b = await bench()
// A host that publishes a workspace-file port: previews come from that
// origin, which is what keeps them off the API's.
b.runtime.connection.filesPort = 4321
const open = vi.spyOn(window, 'open').mockReturnValue(null)
const { injected } = b.chatViewSurface(ROOT)
// Inside the session cwd: served on the workspace-file origin, so a browser
// anywhere on the network sees the file the agent produced.
injected.openFile('src/a.ts')
expect(open).toHaveBeenCalledWith(`http://localhost:4321/f/${ROOT}/src/a.ts`, '_blank', 'noopener,noreferrer')
expect(b.runtime.workspaces.calls.some(c => c.method === 'openPath')).toBe(false)
// Outside it there is no served URL, so the Host's own opener answers —
// resolved against the session cwd exactly as before.
injected.openFile('/etc/hosts')
await vi.waitFor(() => {
expect(b.runtime.workspaces.calls).toContainEqual({ method: 'openPath', args: ['/etc/hosts'] })
expect(b.runtime.workspaces.calls).toContainEqual({ method: 'openPath', args: ['/proj/src/a.ts'] })
})
open.mockRestore()
await b.runtime.dispose()
})

View File

@@ -136,9 +136,6 @@ async function bench(snapshot: ConversationSnapshot) {
openPath: vi.fn(async () => {}),
}
ctx.provide('workspaces', workspaces)
// The transport face the chat view reads its workspace-file URLs from.
const connection = { fileUrl: vi.fn((_s: unknown, _cwd: string | undefined, path: string) => `http://localhost:4321/f/s-1/${path}`) }
ctx.provide('connection', connection)
ctx.provide('layout', layout)
const locale = new LocaleService(ctx)
ctx.provide('locale', locale)
@@ -246,14 +243,12 @@ describe('run_code sub-calls through the real chat machinery', () => {
subCall(12, parent, 2, 'bash', { command: 'ls notes', description: 'List notes' }, 'demo.txt'),
]]])
const b = await bench(snapshotWith([codeResult(10, parent)], dispatches))
const open = vi.spyOn(window, 'open').mockReturnValue(null)
const view = mountApp(b.slots)
view.getByText('notes/demo.txt').click()
expect(b.layout.openDetails).not.toHaveBeenCalled()
await vi.waitFor(() => {
expect(open).toHaveBeenCalledWith('http://localhost:4321/f/s-1/notes/demo.txt', '_blank', 'noopener,noreferrer')
expect(b.workspaces.openPath).toHaveBeenCalledWith('notes/demo.txt')
})
open.mockRestore()
view.getByText('List notes').click()
expect(b.layout.openDetails).not.toHaveBeenCalled()
})

View File

@@ -119,17 +119,14 @@ describe('keyed toolview hole through the real machinery', () => {
await b.runtime.dispose()
})
it('file-path clicks travel owner openFile → chat inject → the served workspace URL', async () => {
it('file-path clicks travel owner openFile → chat inject → workspaces.openPath', async () => {
const b = await bench([toolResult(3, 'c1', 'read', '{"path":"src/a.ts"}')])
b.runtime.connection.filesPort = 4321
const open = vi.spyOn(window, 'open').mockReturnValue(null)
const view = b.runtime.renderRoot()
view.getByText('src/a.ts').click()
expect(b.layout.openDetails).not.toHaveBeenCalled()
await vi.waitFor(() => {
expect(open).toHaveBeenCalledWith(expect.stringContaining('/src/a.ts'), '_blank', 'noopener,noreferrer')
expect(b.runtime.workspaces.calls).toContainEqual({ method: 'openPath', args: ['src/a.ts'] })
})
open.mockRestore()
await b.runtime.dispose()
})

View File

@@ -20,9 +20,6 @@
{
"path": "../web-react"
},
{
"path": "../connection"
},
{
"path": "../runtime"
},

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/host/apiproxy/README.md
README.md: ee8e758a68f6efa3e363a36fcc9e8444e589ea40
README.zh.md: 4ec3817e65543d6e248be9d902d0b74674f56e5a
README.md: 3c5a83a468b0cf9e596b8b13fafe40c409576fc5
README.zh.md: f8533564575bf6b716f3fa7241ce47b8d4dd435f

View File

@@ -36,8 +36,6 @@ The `command.*` and `skill.*` domains expose the host command registry and skill
The `settings.*`, `credentials.*`, and `llm.*` domains are the configuration-page wire. The settings domain serves the namespaces addressed by registered configurable providers (`ctx.llm.listConfigurableProviders()`) plus a small explicit allowlist — the Web preference `permission` and the product-owned `ui-onboarding`; adding a Settings registration alone never makes it remotely readable or writable. Any other namespace answers `settings-not-exposed` — the same answer an unregistered namespace gets, so no caller can enumerate the registry by probing. `settings.describe` returns each exposed namespace's serialized schemastery schema, redacted layered values (resolved/`base`/`user` — a field's presence in `user` marks it user-overridden), the `secrets` slot list, and the section's `revision`. `settings.update`/`settings.replace` write the user layer; `settings.mutate` applies path ops (`set`/`unset`) against the section as stored, which is the removal path for a client holding the redacted view — rebuilding a section from it and replacing wholesale would delete the secrets the wire never returned. Any write may carry `expectedRevision`; a stale one answers `settings-conflict` with both revisions rather than overwriting the writer that landed first, and every other seam refusal folds into `settings-rejected`. Secret-role values never ride any response in any layer; a secret crosses the wire in exactly one direction — inside an `update`/`mutate` payload or `credentials.set`. `credentials.describe` returns value-free views (`configured`/`source`/`writable`), and `credentials.set`/`credentials.unset` map a shadowed-reference refusal onto `credential-rejected`. `llm.providers` merges the configurable-provider directory with live routes (dormant entries carry `active: false`; undeclared live routes append with no settings address) and `llm.models` is the session-independent catalog. Three invalidation frames keep every surface converged without polling: `host/settings-changed {ns}` (`settings/document-updated` passthrough, so a raw change whose resolved value is unchanged still reaches clients), `host/credentials-changed {ref}` (reference names only, never values), and `host/models-changed` — fired by `llm/adapters-updated` and by a change to a configurable-provider namespace, whose settings carry that provider's catalog and endpoint; a `permission` or `ui-onboarding` change emits only its settings invalidation. The browser carrier restricts the whole configuration plane, reads included (`settings.describe`/`update`/`replace`/`mutate`, `credentials.describe`/`set`/`unset`), to loopback same-origin requests — the `host.pickDirectory` privileged set. A composition without a settings or credential provider answers those domains with an actionable `internal` error naming the missing plugin.
Two members of `ApiProxy` are deliberately not wire methods. `respond` is the client-response entry (four-quadrant model), and `workspaceRootOf` answers where a Session's files live for an in-process reader — a live agent's header first, then the persistence store, never a resume. It has no wire face: a browser learns a Session's cwd from `sessions.view`, and reaches a file through the web transport's own `/f` route, never by asking for a host path. That route's URL shape (`api/files.ts`: `FILES_PATH`, `workspaceFileSegments`, `workspaceFileUrl`, `parseWorkspaceFilePath`) lives here with the other browser-importable contract surfaces, so the browser half that builds a `/f` URL and the serving half that parses one cannot drift apart; the route itself belongs to [`dsh-client-connection`](../../client/connection/README.md).
## Carrier layer (`/client` + root)
`AbstractApiClient` holds every protocol invariant — rpcId minting, envelope wrap/unwrap, zod parsing, SSE frame decoding, unary timeout, microtask-batched envelope observation (`subscribeEnvelopes`) — while platform subclasses supply only the `doFetch` transport aspect. `InProcessApiClient` over `toFetchHandler(api)` is the isomorphic point: the full wire serialization/validation path with no network, used by `dsh -p` headless.

View File

@@ -36,8 +36,6 @@ Workspace 列表与 Session 列表是相互独立的重连基线。`workspace.cr
`settings.*``credentials.*``llm.*` 领域是配置页协议。settings 领域服务于已注册可配置提供方所指向的 namespace`ctx.llm.listConfigurableProviders()`),并额外服务于一份小型、显式的 allowlist——Web 偏好 `permission` 与产品持有的 `ui-onboarding`;仅新增一项 Settings 注册,绝不会使其可被远程读取或写入。其他任何 namespace 都只会得到 `settings-not-exposed`——未注册的 namespace 得到的是同一个答复,因此没有调用方能靠逐个探测把注册表枚举出来。`settings.describe` 为每个已暴露 namespace 提供其序列化 schemastery schema、脱敏后的分层值resolved/`base`/`user`——字段出现在 `user` 中即标记其被用户覆盖)、`secrets` 槽位列表,以及该分节的 `revision``settings.update`/`settings.replace` 写入用户层;`settings.mutate` 则在已存分节上施加路径 op`set`/`unset`),这是持有脱敏视图的客户端的删除路径——据此重建分节再整体替换,会删掉协议从未回传过的那些机密。任何写入都可携带 `expectedRevision`;过期的期望值会以 `settings-conflict` 连同两个 revision 作答,而不是覆盖先落地的那个写方,其余每种 seam 拒绝则折叠为 `settings-rejected`。secret 角色的值绝不在任何一层搭乘任何响应secret 只沿一个方向跨越协议——在 `update`/`mutate` 载荷或 `credentials.set` 之内。`credentials.describe` 返回不含值的视图(`configured`/`source`/`writable``credentials.set`/`credentials.unset` 则把被遮蔽引用的拒绝映射为 `credential-rejected``llm.providers` 把可配置提供方目录与存活路由合并(休眠条目携带 `active: false`;未声明的存活路由追加在后,不带 settings 地址),`llm.models` 则是与会话无关的目录。三个失效帧让每个面无需轮询即保持收敛:`host/settings-changed {ns}``settings/document-updated` 透传,因此解析值未变的原始变更同样能到达客户端)、`host/credentials-changed {ref}`(只带引用名,绝不带值),以及 `host/models-changed`——它由 `llm/adapters-updated` 和可配置提供方 namespace 的变更触发,因为该提供方的设置正承载着它的目录与端点;`permission``ui-onboarding` 变更只会发出自身的 settings 失效通知。浏览器载体把整个配置面(含读取:`settings.describe`/`update`/`replace`/`mutate``credentials.describe`/`set`/`unset`)限制为仅接受来自回环地址的同源请求——即 `host.pickDirectory` 所在的特权集合。未装 settings 或凭据 provider 的组合会以指名缺失插件、包含解决建议的 `internal` 错误应答这些领域。
`ApiProxy` 上有两个成员刻意不是协议方法。`respond` 是客户端响应入口(四象限模型),`workspaceRootOf` 则为进程内读取方回答某个 Session 的文件位于何处——先看活跃 agent 的 header再看持久化存储绝不恢复会话。它没有协议面浏览器从 `sessions.view` 得知 Session 的 cwd并经由 web 传输自己的 `/f` 路由抵达文件,而不是靠索要一条宿主路径。该路由的 URL 形状(`api/files.ts``FILES_PATH``workspaceFileSegments``workspaceFileUrl``parseWorkspaceFilePath`)与其余浏览器可导入的契约面一同放在这里,因此构造 `/f` URL 的浏览器半侧与解析它的服务半侧不会彼此漂移;路由本身则属于 [`dsh-client-connection`](../../client/connection/README.md)。
## 载体层(`/client` + 根路径)
`AbstractApiClient` 持有全部协议不变量:签发 rpcId、包装解包信封、Zod 解析、SSE 帧解码、一元请求超时,以及按微任务批处理的信封观测(`subscribeEnvelopes`);平台子类只提供 `doFetch` 传输环节。`InProcessApiClient``toFetchHandler(api)` 为基础,是同构接点:它运行完整的协议序列化与校验路径而不经过网络,供 `dsh -p` headless 模式使用。

View File

@@ -2290,20 +2290,5 @@ export function createApiProxy(ctx: Context, defaults: ApiProxyDefaults): ApiPro
pending.resolve(payload.answer)
return Promise.resolve({ accepted: true })
},
async workspaceRootOf(sessionId: SessionId): Promise<string | undefined> {
// A live agent answers from its own header; otherwise the store answers,
// deliberately without resuming — reading a session's directory must not
// pull an agent up the way the cold RPC path does.
const live = ctx.agents.get(sessionId)
if (live !== undefined) return live.session.header.cwd
const persistence = ctx.get('sessionPersistence')
if (persistence === undefined) return undefined
// TODO(persistence/by-id): a full listing per lookup. Harmless while the
// caller is one preview open, but a served document with N relative
// sub-resources pays it N times; a by-id header read on the persistence
// seam would retire it.
return (await persistence.list()).find(meta => meta.id === sessionId)?.cwd
},
}
}

View File

@@ -1,98 +0,0 @@
/**
* The `/f` workspace-file URL shape: the contract half of the web transport
* that carries bytes rather than RPC. The browser turns a tool's file path
* into a URL, the serving side turns that URL back into the segments below a
* session's cwd, and both read this one encoding decision so neither can drift
* into serving a path the other never meant. Pure string work with no Node and
* no DOM, like the rest of `api/` — the browser bundle inlines it.
* @module @deepseek-ai/dsh-host-apiproxy/api/files
*/
/**
* Route prefix owning every workspace-file read (`/f/<sessionId>/<segments…>`).
* The path carries the segments verbatim rather than a query parameter so a
* served document's relative references (`./logo.png`) resolve to their
* siblings in the same workspace directory.
*/
export const FILES_PATH = '/f'
/** One parsed workspace-file request: whose workspace, and where inside it. */
export interface WorkspaceFileTarget {
/** The owning session, still an opaque string — the caller resolves it to a cwd. */
sessionId: string
/** Decoded path segments below that session's cwd; never empty, never `.` or `..`. */
segments: string[]
}
/** A segment that survived decoding but would re-enter path resolution as more than one name. */
function isPlainSegment(segment: string): boolean {
return segment !== '' && segment !== '.' && segment !== '..'
&& !segment.includes('/') && !segment.includes('\\') && !segment.includes('\0')
}
function decode(raw: string): string | undefined {
try {
return decodeURIComponent(raw)
} catch {
// A malformed %-escape is a request we cannot interpret, not a miss.
return undefined
}
}
/**
* Express one tool-reported file path as segments below the session cwd.
* @param cwd - the session's working directory, or `undefined` when unknown.
* @param path - the path the tool reported (absolute, or relative to `cwd`).
* @returns the segments below `cwd`, or `undefined` when the path names
* something outside the workspace (which this route never serves) or resolves
* to the workspace directory itself.
*/
export function workspaceFileSegments(cwd: string | undefined, path: string): string[] | undefined {
const slashed = path.replace(/\\/g, '/')
const absolute = /^\/|^[A-Za-z]:\//.test(slashed)
let relative: string
if (absolute) {
if (cwd === undefined || cwd === '') return undefined
const root = cwd.replace(/\\/g, '/').replace(/\/+$/, '')
if (!slashed.startsWith(`${root}/`)) return undefined
relative = slashed.slice(root.length + 1)
} else {
relative = slashed
}
const segments = relative.split('/').filter(segment => segment !== '' && segment !== '.')
if (segments.length === 0 || segments.some(segment => !isPlainSegment(segment))) return undefined
return segments
}
/**
* Build the origin-relative URL serving one workspace file.
* @param sessionId - the session whose cwd anchors the path.
* @param segments - segments below that cwd, as {@link workspaceFileSegments} returns them.
* @returns the `/f/…` URL, resolved by the browser against the serving origin.
*/
export function workspaceFileUrl(sessionId: string, segments: readonly string[]): string {
const encoded = segments.map(segment => encodeURIComponent(segment)).join('/')
return `${FILES_PATH}/${encodeURIComponent(sessionId)}/${encoded}`
}
/**
* Parse a request pathname back into the session and segments it names.
* @param pathname - the request's raw (still percent-encoded) pathname.
* @returns the target, or `undefined` when the pathname is not a well-formed
* workspace-file read — including every traversal shape, which is refused here
* before any filesystem call rather than being resolved and then judged.
*/
export function parseWorkspaceFilePath(pathname: string): WorkspaceFileTarget | undefined {
if (!pathname.startsWith(`${FILES_PATH}/`)) return undefined
const [rawSession, ...rawSegments] = pathname.slice(FILES_PATH.length + 1).split('/')
if (rawSession === undefined || rawSegments.length === 0) return undefined
const sessionId = decode(rawSession)
if (sessionId === undefined || sessionId === '') return undefined
const segments: string[] = []
for (const raw of rawSegments) {
const segment = decode(raw)
if (segment === undefined || !isPlainSegment(segment)) return undefined
segments.push(segment)
}
return { sessionId, segments }
}

View File

@@ -15,9 +15,6 @@ import type { SettingsApi } from './settings.ts'
import type { CredentialsApi } from './credentials.ts'
import type { LlmApi } from './llm.ts'
import type { ClientResponse, RpcReceipt } from './rpc.ts'
// The merge-free types subpath: api/ is imported from the browser lane, where
// the host session service must not merge over the client runtime's own.
import type { SessionId } from '@deepseek-ai/dsh-session/types'
/** Root interface of the unified API surface. New client-request domain = one new file pair + one field here + one map row. */
export interface ApiProxy {
@@ -33,17 +30,6 @@ export interface ApiProxy {
llm: LlmApi
/** Response entry for server-requests (client-response, echoing their rpcId); not a domain method (four-quadrant model). */
respond(message: ClientResponse): Promise<RpcReceipt>
/**
* The directory a Session's files may be read from — the same `cwd` the
* session summaries carry, in non-envelope form for an in-process reader.
* Not a domain method: it has no wire face, because a browser learns a
* Session's cwd from `sessions.view` and a file it may read from the web
* transport's own `/f` route, never by asking for a host path.
* @param sessionId - the Session to locate.
* @returns its absolute working directory, or `undefined` when this host
* serves no such Session. Resolving one never resumes an agent.
*/
workspaceRootOf(sessionId: SessionId): Promise<string | undefined>
}
// ---- Domain interfaces and payload entities ----
@@ -63,9 +49,6 @@ export type { CredentialsApi, CredentialView } from './credentials.ts'
export type { ConfigurableProviderView, LlmApi } from './llm.ts'
export type { ApprovalResponsePayload } from './approvals.ts'
// ---- Workspace-file URL shape (the transport's byte-carrying half) ----
export { FILES_PATH, workspaceFileSegments, workspaceFileUrl, parseWorkspaceFilePath } from './files.ts'
export type { WorkspaceFileTarget } from './files.ts'
export type { QuestionResponsePayload } from './questions.ts'
// ---- Message layer: narrow forms (domain-signature view) ----

View File

@@ -64,7 +64,6 @@ export class ApiProxyService extends Service implements ApiProxy {
readonly llm: ApiProxy['llm']
readonly events: ApiProxy['events']
readonly respond: ApiProxy['respond']
readonly workspaceRootOf: ApiProxy['workspaceRootOf']
constructor(ctx: Context, config: Config) {
super(ctx, 'apiProxy')
@@ -88,7 +87,6 @@ export class ApiProxyService extends Service implements ApiProxy {
// createApiProxy returns closures (no `this` capture); bind only satisfies
// the unbound-method lint without changing behavior.
this.respond = api.respond.bind(api)
this.workspaceRootOf = api.workspaceRootOf.bind(api)
}
}

View File

@@ -1,5 +1,16 @@
/** Cross-platform open-with-default-application used by the local GUI carrier. */
/**
* Cross-platform open-with-default-application used by the local GUI carrier.
*
* A document a browser RENDERS is opened with the user's default browser
* rather than the default application for its type, when the platform can name
* one: a developer who binds `.html` to an editor would otherwise click a
* produced page and get source code. The contract is uniform — prefer the
* default browser, fall back to the default application — while how completely
* a platform can answer "which browser" differs, and every failure falls back
* rather than surfacing.
*/
import { extname } from 'node:path'
import { runNativeCommand, type NativeCommandRunner } from '@deepseek-ai/dsh-native-command'
/** Testable command boundary; native implementations never invoke a shell. */
@@ -9,6 +20,60 @@ export type PathOpenerRunner = NativeCommandRunner
export interface PathOpenerInternals {
platform?: NodeJS.Platform
run?: PathOpenerRunner
/** Environment the linux browser convention reads; defaults to the process env. */
env?: NodeJS.ProcessEnv
}
/** Documents a browser renders, as opposed to ones an editor merely edits. */
const BROWSER_DOCUMENTS = new Set(['.html', '.htm', '.xhtml', '.svg'])
/**
* The macOS bundle registered for `https` — the default browser, as
* LaunchServices records it. The nested version dict is stripped first
* because it carries its own `LSHandlerRoleAll`.
*/
function macBundleForHttps(plist: string): string | undefined {
const stripped = plist.replace(/LSHandlerPreferredVersions\s*=\s*\{[^}]*\};/g, '')
const block = /\{[^{}]*LSHandlerURLScheme\s*=\s*"?https"?;[^{}]*\}/.exec(stripped)?.[0]
if (block === undefined) return undefined
return /LSHandlerRoleAll\s*=\s*"?([\w.-]+)"?;/.exec(block)?.[1]
}
/**
* Open one browser-renderable document with the default browser.
* @returns true when a browser took it; false when this platform cannot name
* one, or naming it failed — the caller then uses the default application.
*/
async function openInBrowser(
path: string, signal: AbortSignal, platform: NodeJS.Platform,
run: PathOpenerRunner, env: NodeJS.ProcessEnv,
): Promise<boolean> {
if (platform === 'darwin') {
let bundle: string | undefined
try {
const { stdout } = await run(
'defaults', ['read', 'com.apple.LaunchServices/com.apple.launchservices.secure'], signal)
bundle = macBundleForHttps(stdout)
} catch {
// No LaunchServices record (a fresh account never changed a default):
// the content-type handler is then the system's own choice anyway.
return false
}
if (bundle === undefined) return false
await run('open', ['-b', bundle, path], signal)
return true
}
if (platform === 'linux') {
// $BROWSER is the portable convention; desktop-entry resolution through
// xdg-settings needs a launcher this package has no business shipping.
const browser = env.BROWSER
if (browser === undefined || browser === '') return false
await run(browser, [path], signal)
return true
}
// Windows names no browser without reading the UserChoice registry, and its
// .html association is the browser in the ordinary case.
return false
}
/** PowerShell single-quoted literal (doubles embedded quotes). */
@@ -17,10 +82,11 @@ function powershellLiteral(path: string): string {
}
/**
* Open a filesystem path with the operating system's default application.
* Open a filesystem path with the operating system's default application, or
* with the default browser when the path names a document a browser renders.
* @param path - absolute or host-resolvable path (caller owns resolution).
* @param signal - caller/connection lifetime; abort terminates the native command.
* @param internals - platform and runner seam for deterministic tests.
* @param internals - platform, environment, and runner seam for deterministic tests.
*/
export async function openNativePath(
path: string,
@@ -29,6 +95,10 @@ export async function openNativePath(
): Promise<void> {
const platform = internals.platform ?? process.platform
const run = internals.run ?? runNativeCommand
const env = internals.env ?? process.env
if (BROWSER_DOCUMENTS.has(extname(path).toLowerCase())
&& await openInBrowser(path, signal, platform, run, env)) return
if (platform === 'darwin') {
await run('open', [path], signal)

View File

@@ -62,11 +62,7 @@ function stubAgent(session: Session): Agent {
async function harness(
workspaceRoot = realpathSync(mkdtempSync(join(tmpdir(), 'dsh-apiproxy-workspace-'))),
picker: DirectoryPickerCapability = { kind: 'native', pick: async () => null },
extras: {
openPath?: (path: string, signal: AbortSignal) => Promise<void>
/** Store contents behind the gateway, or 'absent' for a composition with no persistence at all. */
persisted?: { id: SessionId; cwd?: string }[] | 'absent'
} = {},
extras: { openPath?: (path: string, signal: AbortSignal) => Promise<void> } = {},
) {
const ctx = new Context()
await ctx.plugin(SessionStore)
@@ -77,10 +73,7 @@ async function harness(
const storageDomain = new DomainFacility(ctx, { backend: 'memory', routes: {} })
ctx.storage.mount('domain', storageDomain)
ctx.provide('storageDomain', storageDomain)
if (extras.persisted !== 'absent') {
const persisted = extras.persisted ?? []
ctx.provide('sessionPersistence', { list: () => Promise.resolve(persisted) } as never)
}
ctx.provide('sessionPersistence', { list: () => Promise.resolve([]) } as never)
await ctx.plugin(WorkspaceRegistry)
const factory: AgentFactory = {
@@ -251,27 +244,6 @@ describe('host.openPath', () => {
})
})
describe('workspaceRootOf', () => {
it('answers from the live agent, then the store, and names nothing for an unknown session', async () => {
const { api, workspaceRoot } = await harness(undefined, undefined, {
persisted: [{ id: 's-cold' as SessionId, cwd: '/w/cold' }],
})
const created = await api.sessions.create(request({ cwd: workspaceRoot }))
const sessionId = (created.result as { ok: true; value: { sessionId: SessionId } }).value.sessionId
// Live: the agent's own header, no store read involved.
await expect(api.workspaceRootOf(sessionId)).resolves.toBe(workspaceRoot)
// Not live: the store answers, and the lookup never resumes an agent —
// this harness's factory throws on resume, so a resuming lookup would fail.
await expect(api.workspaceRootOf('s-cold' as SessionId)).resolves.toBe('/w/cold')
await expect(api.workspaceRootOf('s-absent' as SessionId)).resolves.toBeUndefined()
})
it('names nothing at all when the host keeps no session store', async () => {
const { api } = await harness(undefined, undefined, { persisted: 'absent' })
await expect(api.workspaceRootOf('s-any' as SessionId)).resolves.toBeUndefined()
})
})
describe('workspace.create', () => {
it('serializes concurrent names and rejects the duplicate', async () => {
const { api, workspaceRoot } = await harness()

View File

@@ -108,8 +108,6 @@ function scriptedApi(overrides: {
},
events: { mux: () => empty<MuxFrame>(), host: () => empty<HostFrame>(), ...overrides.events },
respond: overrides.respond ?? (() => Promise.resolve({ accepted: false as const, reason: 'not-pending' as const })),
// No wire face, so the handler map never reaches it.
workspaceRootOf: () => Promise.resolve(undefined),
}
}

View File

@@ -233,8 +233,6 @@ function fakeApi(overrides: Partial<{ muxFrames: MuxFrame[]; hostFrames: HostFra
async respond(message: ClientResponse): Promise<RpcReceipt> {
return message.rpcId === 'known' ? { accepted: true } : { accepted: false, reason: 'not-pending' }
},
// No wire face, so the carrier never reaches it.
workspaceRootOf: () => Promise.resolve(undefined),
}
}

View File

@@ -1,74 +0,0 @@
/** The /f URL shape: one encoding decision, asserted from both ends. */
import { describe, expect, it } from 'vitest'
import {
FILES_PATH, parseWorkspaceFilePath, workspaceFileSegments, workspaceFileUrl,
} from '../src/api/files.ts'
describe('workspaceFileSegments', () => {
it('keeps a relative path as its own segments', () => {
expect(workspaceFileSegments('/w', 'out/index.html')).toEqual(['out', 'index.html'])
expect(workspaceFileSegments(undefined, 'index.html')).toEqual(['index.html'])
expect(workspaceFileSegments('/w', './a/./b.txt')).toEqual(['a', 'b.txt'])
})
it('strips the cwd prefix from an absolute path inside the workspace', () => {
expect(workspaceFileSegments('/w', '/w/a/b.html')).toEqual(['a', 'b.html'])
// A trailing separator on the cwd must not shift the split.
expect(workspaceFileSegments('/w/', '/w/a.html')).toEqual(['a.html'])
})
it('reads Windows paths on either separator', () => {
expect(workspaceFileSegments('C:\\w', 'C:\\w\\a\\b.html')).toEqual(['a', 'b.html'])
expect(workspaceFileSegments('C:/w', 'C:\\w\\a.html')).toEqual(['a.html'])
})
it('refuses everything the route would not serve', () => {
// Absolute, but not under this workspace.
expect(workspaceFileSegments('/w', '/etc/hosts')).toBeUndefined()
// A sibling directory sharing the cwd's name prefix is not inside it.
expect(workspaceFileSegments('/w', '/workspace-other/a')).toBeUndefined()
// Absolute with no cwd to anchor against.
expect(workspaceFileSegments(undefined, '/w/a.html')).toBeUndefined()
expect(workspaceFileSegments('', '/w/a.html')).toBeUndefined()
// Traversal, in either spelling.
expect(workspaceFileSegments('/w', '../secret')).toBeUndefined()
expect(workspaceFileSegments('/w', 'a/../../secret')).toBeUndefined()
// The workspace directory itself is not a file.
expect(workspaceFileSegments('/w', '/w')).toBeUndefined()
expect(workspaceFileSegments('/w', '.')).toBeUndefined()
})
})
describe('workspaceFileUrl', () => {
it('percent-encodes each segment but keeps the separators structural', () => {
expect(workspaceFileUrl('s-1', ['out', 'a b.html'])).toBe(`${FILES_PATH}/s-1/out/a%20b.html`)
expect(workspaceFileUrl('s/1', ['a#b.html'])).toBe(`${FILES_PATH}/s%2F1/a%23b.html`)
})
})
describe('parseWorkspaceFilePath', () => {
it('round-trips what the browser half builds', () => {
const url = workspaceFileUrl('s-1', ['out', 'a b.html'])
expect(parseWorkspaceFilePath(url)).toEqual({ sessionId: 's-1', segments: ['out', 'a b.html'] })
})
it('refuses malformed, prefix-foreign, and traversal pathnames', () => {
expect(parseWorkspaceFilePath('/api/session.list')).toBeUndefined()
expect(parseWorkspaceFilePath(FILES_PATH)).toBeUndefined()
// Session named but no file below it.
expect(parseWorkspaceFilePath(`${FILES_PATH}/s-1`)).toBeUndefined()
expect(parseWorkspaceFilePath(`${FILES_PATH}//a.html`)).toBeUndefined()
// Traversal is refused at parse time, before any filesystem call.
expect(parseWorkspaceFilePath(`${FILES_PATH}/s-1/../etc/hosts`)).toBeUndefined()
expect(parseWorkspaceFilePath(`${FILES_PATH}/s-1/a/./b`)).toBeUndefined()
expect(parseWorkspaceFilePath(`${FILES_PATH}/s-1/a//b`)).toBeUndefined()
// A separator smuggled through percent-encoding stays one segment's problem.
expect(parseWorkspaceFilePath(`${FILES_PATH}/s-1/a%2F..%2Fb`)).toBeUndefined()
expect(parseWorkspaceFilePath(`${FILES_PATH}/s-1/a%5Cb`)).toBeUndefined()
expect(parseWorkspaceFilePath(`${FILES_PATH}/s-1/a%00b`)).toBeUndefined()
// Malformed percent-escapes are uninterpretable, not a miss to resolve.
expect(parseWorkspaceFilePath(`${FILES_PATH}/s-1/a%zz`)).toBeUndefined()
expect(parseWorkspaceFilePath(`${FILES_PATH}/%zz/a.html`)).toBeUndefined()
expect(parseWorkspaceFilePath(`${FILES_PATH}//`)).toBeUndefined()
})
})

View File

@@ -80,3 +80,96 @@ describe('native path opener', () => {
})
})
})
describe('browser-renderable documents', () => {
const LS_PLIST = `{
LSHandlers = (
{
LSHandlerPreferredVersions = {
LSHandlerRoleAll = "-";
};
LSHandlerRoleAll = "com.google.chrome";
LSHandlerURLScheme = https;
}
);
}`
it('opens a page with the default browser rather than the .html handler on darwin', async () => {
const calls: { command: string; args: readonly string[] }[] = []
const run = async (command: string, args: readonly string[]) => {
calls.push({ command, args })
return { stdout: command === 'defaults' ? LS_PLIST : '', stderr: '' }
}
await openNativePath('/w/page.html', new AbortController().signal, { platform: 'darwin', run })
// A developer who bound .html to an editor still gets a rendered page.
expect(calls.map(c => [c.command, ...c.args])).toEqual([
['defaults', 'read', 'com.apple.LaunchServices/com.apple.launchservices.secure'],
['open', '-b', 'com.google.chrome', '/w/page.html'],
])
})
it('leaves every other document to the default application', async () => {
const calls: string[][] = []
const run = async (command: string, args: readonly string[]) => {
calls.push([command, ...args])
return { stdout: '', stderr: '' }
}
await openNativePath('/w/report.md', new AbortController().signal, { platform: 'darwin', run })
// No LaunchServices read at all: markdown is not a browser document.
expect(calls).toEqual([['open', '/w/report.md']])
})
it('falls back to the default application when no browser can be named', async () => {
// LaunchServices has no https record (a fresh account), so the system's
// own content-type choice is the best answer available.
const calls: string[][] = []
const run = async (command: string, args: readonly string[]) => {
calls.push([command, ...args])
if (command === 'defaults') throw new Error('domain not found')
return { stdout: '', stderr: '' }
}
await openNativePath('/w/page.html', new AbortController().signal, { platform: 'darwin', run })
expect(calls).toEqual([
['defaults', 'read', 'com.apple.LaunchServices/com.apple.launchservices.secure'],
['open', '/w/page.html'],
])
// A record without an https handler is the same answer.
const bare: string[][] = []
await openNativePath('/w/page.html', new AbortController().signal, {
platform: 'darwin',
run: async (command, args) => {
bare.push([command, ...args])
return { stdout: '{ LSHandlers = ( ); }', stderr: '' }
},
})
expect(bare[1]).toEqual(['open', '/w/page.html'])
})
it('honors $BROWSER on linux and leaves windows to its association', async () => {
const linux: string[][] = []
await openNativePath('/w/page.html', new AbortController().signal, {
platform: 'linux',
env: { BROWSER: 'firefox' },
run: async (command, args) => { linux.push([command, ...args]); return { stdout: '', stderr: '' } },
})
expect(linux).toEqual([['firefox', '/w/page.html']])
// Unset $BROWSER: xdg-open's association is the fallback.
const bare: string[][] = []
await openNativePath('/w/page.html', new AbortController().signal, {
platform: 'linux',
env: {},
run: async (command, args) => { bare.push([command, ...args]); return { stdout: '', stderr: '' } },
})
expect(bare).toEqual([['xdg-open', '/w/page.html']])
// Windows names no browser without the UserChoice registry.
const win: string[][] = []
await openNativePath('C:\\w\\page.html', new AbortController().signal, {
platform: 'win32',
run: async (command, args) => { win.push([command, ...args]); return { stdout: '', stderr: '' } },
})
expect(win[0]?.[0]).toBe('powershell.exe')
})
})

6
pnpm-lock.yaml generated
View File

@@ -1183,9 +1183,6 @@ importers:
specifier: ^4.1.8
version: 4.1.8(@opentelemetry/api@1.9.1)(@types/node@25.9.3)(@vitest/coverage-v8@4.1.8)(jsdom@29.1.1)(vite@8.0.16(@types/node@25.9.3)(esbuild@0.28.1)(jiti@2.7.0)(tsx@4.22.4)(yaml@2.9.0))
devDependencies:
'@deepseek-ai/dsh-client-connection':
specifier: workspace:^
version: link:../connection
'@deepseek-ai/dsh-client-runtime':
specifier: workspace:^
version: link:../runtime
@@ -1266,9 +1263,6 @@ importers:
specifier: ^2.0.0
version: 2.1.1
devDependencies:
'@deepseek-ai/dsh-client-connection':
specifier: workspace:^
version: link:../connection
'@deepseek-ai/dsh-client-locale':
specifier: workspace:^
version: link:../locale

View File

@@ -38,7 +38,7 @@
"apps/web/tests/access-confirmation.e2e.ts",
"apps/web/tests/shipped-composition.e2e.ts",
"apps/web/tests/startup-auto-selection.e2e.ts",
"apps/web/tests/workspace-file-open.e2e.ts",
"apps/web/tests/produced-files.e2e.ts",
"apps/cli/tests/**/*.ts",
"examples/*/src/**/*.ts",
"examples/*/start.ts",