feat(web): carry terminal input over duplex streams

This commit is contained in:
Yichen Jiang committed 2026-10-12 11:18:43 +08:00
1 parent 77dca95039
commit 5379996fcb
32 files changed
+713 -606

No files matched your search

@@ -129,14 +129,14 @@
en: 04e72789417d6e3a
zh: b57c5cc68dff45a5
/agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/consequences:
en: 07524e0c2dc22ad5
zh: 5bf4f27160d78b43
en: 35326fed46e31d74
zh: 6f47baa645a1e370
/agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/testing:
en: 5c8188930b9d4fdb
zh: 1d94e6563cedde13
/agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/deferred:
en: 3b99a327464edc3e
zh: dcffdc75369925dc
en: d350c4761a956550
zh: eb186a74e64fa2a1
/agent-note-remote-duplex-stream-one-kind-of-stream-an-uplink-channel-and-an-invocation-context/related:
en: 85d77fb246564024
zh: 8b400818a91a3e3a
en: 475d212ae1f9c1c9
zh: 21fe6c6cdb900a6b
@@ -574,10 +574,11 @@ for await (const reply of stream) replies.push(reply) // ['> a', '> b']
- **Bought**: one stream with two directions, so interactive scenarios such as terminal keystrokes, approval answers, and background-job stdin no longer each build their own "one stream plus one unary"; a Host method knows its caller; the uplink and downlink types are declared in one place, the return type; uplink items come from the browser and are validated strictly per item at the Host, while downlink items are Host-produced typed values that pass straight through; the generated output and wire frames of existing `AsyncIterable<Out>` methods and unary methods are completely unchanged.
- **`this.ctx.invocation` is `undefined` outside a Remote call**, so a method that reads it must handle the optional; a service method invoked only directly in process correctly reads `undefined`.
- **Web terminals use `attach`** for screen output and input commands, with provider acknowledgements and per-attachment writable state; their Client retains the current generation's handle and never replays input.
- **The inbox limit applies to every stream**: a method that does not read its uplink fails as a whole when it receives many uplink frames. This is a deliberate explicit failure, recorded in the README.
- **The operator is the only Peer**, and `admit` is the only admission point; the first consumer that needs a second Peer must add opening, association, and events in `dsh-client-connection`.
- **No cross-direction ordering guarantee between uplink and downlink**; a protocol that needs request-response pairing carries its own sequence numbers.
- **Upper-layer protocols do not yet expose `send`**: consumers of `$stream`, snapshot, and journal use only the downlink today; the object they receive is already the handle.
- **Upper-layer supervisors expose only the downlink**: `$stream`, snapshot and journal do not expose `send`; a domain that writes uplink retains its generated physical handle for that generation.
- **The worker tunnel behaves differently from the WebSocket carrier**: no inbox limit, and items after `end` are dropped, because page to worker is a same-origin trusted boundary.
## Testing
@@ -595,7 +596,6 @@ Retention cases in `gateway-stream.host.spec.ts` and `gateway.client.spec.ts` co
## Deferred
- `$stream` / snapshot / journal expose the handle's `send` to upper-layer protocols.
- Web terminal: one `attach` stream replaces `follow` plus `write` plus `resize`, and `attachmentId` retires.
- Duplex `$events`: waterfall answers become uplink items on the same `streamId`, and `$events/result` and `clientId` retire.
- Credit frames: wait for a consumer that needs sustained high-volume uplink; the inbox limit is the initial credit.
- The `streamInboxBytes` default of 262144 is far more than keyboard and stdin need; if the first consumer is terminal paste, it may be aligned with the `maxInputBytes` of `terminal-controller`.
@@ -606,4 +606,4 @@ Retention cases in `gateway-stream.host.spec.ts` and `gateway.client.spec.ts` co
- [Remote event delivery](../../../../packages/api/remotes/README.md): the unary `$events/result` answer path; the duplex `$events` item under Deferred partially supersedes it once it lands.
- [Session history and event transport](2026-08-18-session-history-and-event-transport.md): the `$stream()` supervisor and the journal / snapshot protocols above it, which this note leaves unchanged.
- [Web sidebar terminal](../feature/2026-09-09-web-sidebar-terminal.md): the unary terminal `write` and `attachmentId`; the `attach` stream under Deferred replaces it once it lands.
- [Web sidebar terminal](../feature/2026-09-09-web-sidebar-terminal.md): the `attach` stream carries input commands, provider acknowledgements and per-attachment writable state; reconnect never replays input.
@@ -574,10 +574,11 @@ for await (const reply of stream) replies.push(reply) // ['> a', '> b']
- **买到的**:一条流两个方向,终端按键、审批回答、后台任务 stdin 这类交互式场景不再各造一套"一条流加一个 unary";Host 方法知道调用者;上行类型与下行类型在返回类型里一处声明,上行项来自浏览器,在 Host 逐项严格校验,下行项是 Host 自产的类型值,直接透传;既有 `AsyncIterable<Out>` 方法与 unary 方法的生成物与线路帧完全不变。
- **`this.ctx.invocation` 在非 Remote 调用下是 `undefined`**,方法读它要处理可选;一个只被进程内直接调用的服务方法读到 `undefined` 是正确行为。
- **Web 终端使用 `attach`** 传输屏幕输出和输入命令,并提供提供者确认和附件专属可写状态;Client 保留当前代次的句柄,绝不重放输入。
- **inbox 上限对所有流生效**:一个不读上行的方法收到大量上行帧会整流失败。这是刻意的显式失败,README 记明。
- **Peer 只有操作者一个**,`admit` 是唯一的接纳点;第一个需要第二个 Peer 的消费者要在 `dsh-client-connection` 加上打开、关联与事件。
- **上行与下行之间没有跨方向顺序保证**;需要请求应答配对的协议自带序号。
- **上层协议尚未透出 `send`**:`$stream`、snapshot、journal 的消费者今天只用下行;它们拿到的对象已经是句柄。
- **上层监督器仅暴露下行**:`$stream`、snapshot 和 journal 不暴露 `send`;需要写入上行的领域保留该代次的生成物理句柄。
- **worker 隧道与 WebSocket 载体行为不同**:没有 inbox 上限,`end` 之后的项丢弃,因为页面到 worker 是同源可信边界。
## 测试
@@ -595,7 +596,6 @@ for await (const reply of stream) replies.push(reply) // ['> a', '> b']
## 后续
- `$stream` / snapshot / journal 把句柄的 `send` 透出给上层协议。
- Web 终端:一条 `attach` 流取代 `follow` 加 `write` 加 `resize`,`attachmentId` 退场。
- 双工 `$events`:waterfall 的回答成为同一 `streamId` 上的上行项,`$events/result` 与 `clientId` 退场。
- credit 帧:等需要持续大流量上行的消费者出现;inbox 上限就是初始授信。
- `streamInboxBytes` 默认值 262144 对键盘与 stdin 远超需要;若第一个消费者是终端粘贴,可能与 `terminal-controller` 的 `maxInputBytes` 对齐。
@@ -606,4 +606,4 @@ for await (const reply of stream) replies.push(reply) // ['> a', '> b']
- [Remote 事件投递](../../../../packages/api/remotes/README.zh.md):`$events/result` 的 unary 回答路径;「后续」里的双工 `$events` 落地后部分取代它。
- [会话历史与事件传输](2026-08-18-session-history-and-event-transport.zh.md):`$stream()` 监督器与其上的 journal / snapshot 协议,本 Note 不改它们。
- [Web 侧边栏终端](../feature/2026-09-09-web-sidebar-terminal.zh.md):终端按键的 unary `write` 与 `attachmentId`;「后续」里的 `attach` 流落地后取代它。
- [Web 侧边栏终端](../feature/2026-09-09-web-sidebar-terminal.zh.md):`attach` 流承载输入命令、提供者确认和附件专属可写状态;重连绝不重放输入。
@@ -9,8 +9,8 @@
en: 71813b1cb1f750ba
zh: 64d2b999933ccd98
/agent-note-web-sidebar-terminals/decision:
en: 8d28949572d990ef
zh: f6e26790415134d2
en: 2404681c71ad470b
zh: f7568f063e25ee1e
/agent-note-web-sidebar-terminals/alternatives-considered:
en: b0ffb94cd5033e9c
zh: 9294bb76503c858a
@@ -18,5 +18,5 @@
en: d710787595b5dc89
zh: 4df9518c32698f85
/agent-note-web-sidebar-terminals/related:
en: 94540c743da01fc4
zh: 53e3d9d2268153d1
en: 2ae8d413f928803f
zh: 3075efb83112b130
@@ -22,7 +22,7 @@ Close and replacement remove the tab synchronously and run process cleanup in th
The caller retains a terminal ID before creating it. Repeating create with the same Session and open ID does not allocate a second process. Closing an uncertain create uses that ID even when no creation response arrived. The Host records closed IDs before awaiting allocation, preventing a delayed create from reviving a closed terminal. Each attachment begins with a consistent, bounded serialized xterm screen; ordered output follows through the Gateway's existing multiplexed Remote stream. Output and screen snapshots share one operation queue. Followers retain final output on normal closure and fail explicitly on buffer overflow. Browser render acknowledgement prevents React batching from dropping increments.
The latest attachment controls input and dimensions; other attachments remain read-only. Every physical stream opening gets a fresh input attachment identity, including automatic transport recovery. Input RPCs are serialized, and results from a superseded attachment cannot downgrade a replacement connection. Terminal output creates no model input, Agent tool result or Session event. The existing [persistent Agent terminal decision](2026-07-16-persistent-pty-sessions.md) continues to govern model-owned sessions; this feature extends the [portable subprocess provider](../architecture/2026-07-28-portable-execution-world-consumers.md) with terminal environment facts and resize. Control-transfer and process-exit refusals only disable input, preserving the healthy output view. Client-owned error identifiers are translated by the terminal UI, including guidance to close retained exited terminals when the quota is full.
The latest attachment controls input and dimensions; other attachments remain read-only. Each physical `attach` stream owns its input and resize commands, including after automatic transport recovery. The Host orders commands and acknowledges provider acceptance; the Client bounds unacknowledged input bytes without waiting for each round trip. Superseded streams cannot write through their replacements, and unacknowledged input is never replayed. Terminal output creates no model input, Agent tool result or Session event. The existing [persistent Agent terminal decision](2026-07-16-persistent-pty-sessions.md) continues to govern model-owned sessions; this feature extends the [portable subprocess provider](../architecture/2026-07-28-portable-execution-world-consumers.md) with terminal environment facts and resize. Control-transfer and process-exit refusals only disable input, preserving the healthy output view. Client-owned error identifiers are translated by the terminal UI, including guidance to close retained exited terminals when the quota is full.
## Alternatives considered
@@ -52,4 +52,4 @@ The [two-hour unattended-terminal reclamation](2026-09-14-unattended-browser-ter
## Related
- [Remote duplex stream](../architecture/2026-09-19-remote-duplex-stream.md): the transport-layer uplink under which one `attach` stream replaces the unary `write` and `resize` calls and the `attachmentId` correlation; that terminal change is listed under its Deferred section.
- [Remote duplex stream](../architecture/2026-09-19-remote-duplex-stream.md): the transport-layer uplink carrying terminal input and output under one physical attachment lifetime.
@@ -22,7 +22,7 @@ Web 用户需要在 Session 旁使用交互式 shell 检查工作区和运行命
调用者在创建之前保留终端 ID。相同 Session 和未关闭 ID 的重复 create 不再分配进程。创建结果不确定时,关闭仍使用该 ID,即使没有收到创建响应。Host 在等待分配完成前记录已关闭 ID,防止迟到的 create 复活已关闭终端。每次连接先接收一致、有界的 xterm 序列化屏幕,后续有序输出使用 Gateway 已有的复用 Remote stream。输出和屏幕快照共享操作队列。订阅者正常关闭时保留末尾输出,缓存超限时明确失败。浏览器在完成渲染后确认帧,避免 React 批处理丢失增量。
最新连接控制输入和尺寸,其他连接保持只读。每次物理流建立都创建新的输入连接标识,包括传输自动恢复。输入 RPC 按序发送,旧连接的结果不能把新连接降级为失败。终端输出不产生模型输入、Agent 工具结果或 Session 事件。[Agent 持久终端决策](2026-07-16-persistent-pty-sessions.zh.md)仍约束模型拥有的终端;此功能为[可移植 subprocess provider](../architecture/2026-07-28-portable-execution-world-consumers.zh.md)增加执行环境事实和 resize。 控制权转移和进程退出导致的拒绝只禁用输入,保留健康的输出视图。Client 自产错误标识由终端 UI 翻译,包括名额用满时关闭已保留的退出终端的提示。
最新连接控制输入和尺寸,其他连接保持只读。每条物理 `attach` 流拥有自己的输入和尺寸命令,传输自动恢复后亦如此。Host 按序执行命令并确认提供者已接受操作;Client 限制未确认输入字节,无需等待每次往返。旧流不能借用新流写入,未确认输入绝不重放。终端输出不产生模型输入、Agent 工具结果或 Session 事件。[Agent 持久终端决策](2026-07-16-persistent-pty-sessions.zh.md)仍约束模型拥有的终端;此功能为[可移植 subprocess provider](../architecture/2026-07-28-portable-execution-world-consumers.zh.md)增加执行环境事实和 resize。 控制权转移和进程退出导致的拒绝只禁用输入,保留健康的输出视图。Client 自产错误标识由终端 UI 翻译,包括名额用满时关闭已保留的退出终端的提示。
## 考虑过的替代方案
@@ -52,4 +52,4 @@ Agent 终端和可移植执行环境两篇记录仍保留,其所有权与 prov
## 相关
- [Remote 双工流](../architecture/2026-09-19-remote-duplex-stream.zh.md):传输层上行,让一条 `attach` 流取代 unary `write`、`resize` 与 `attachmentId` 关联;该终端改动列在其「后续」中。
- [Remote 双工流](../architecture/2026-09-19-remote-duplex-stream.zh.md):传输层上行在同一物理附件生命周期内承载终端输入和输出。
+61
View File
@@ -286,6 +286,10 @@ describe.skipIf(process.platform === 'win32')('Web sidebar terminal', () => {
it('completes commands, preserves the process through collapse and reload, resizes, and kills on tab close', async () => {
onTestFailed(() => saveFailureShot(page, 'sidebar-terminal'))
const unaryInput: string[] = []
page.on('request', (request) => {
if (/\/api\/terminal\/(write|resize|follow)$/u.test(new URL(request.url()).pathname)) unaryInput.push(request.url())
})
await openTerminal(page)
const terminal = page.locator('[data-sidebar-terminal]')
await command(page, "PS1=''; printf '\\033cTERMINAL_READY\\n'")
@@ -370,6 +374,7 @@ describe.skipIf(process.platform === 'win32')('Web sidebar terminal', () => {
await expect.poll(() => alive(firstProcess), { timeout: 10_000 }).toBe(false)
await expect.poll(() => descendants.some(alive), { timeout: 10_000 }).toBe(false)
await expect.poll(() => scaffold.ctx.terminalController.list(scaffold.ctx.agents.list()[0]!.id).length).toBe(0)
expect(unaryInput).toEqual([])
expect(tripwire.pageErrors).toEqual([])
})
@@ -554,6 +559,62 @@ describe.skipIf(process.platform === 'win32')('Web sidebar terminal', () => {
expect(tripwire.pageErrors).toEqual([])
})
it('validates terminal uplink frames and keeps a read-only attachment following output', async () => {
await openTerminal(page)
const sessionId = scaffold.ctx.agents.list()[0]!.id
const terminalId = scaffold.ctx.terminalController.list(sessionId)[0]!.id
const result = await page.evaluate(async ({ sessionId, terminalId }) => {
const socket = new WebSocket(new URL('/api/remote.mux', location.href).href.replace(/^http/u, 'ws'))
const frames: {
type: string
streamId: string
value?: { type: string; data?: string; sequence?: number; writable?: boolean; refusal?: string }
error?: { code: string }
}[] = []
const waiters = new Set<() => void>()
socket.addEventListener('message', (event) => {
frames.push(JSON.parse(String(event.data)) as (typeof frames)[number])
for (const wake of waiters) wake()
})
const wait = async (predicate: () => boolean) => {
if (predicate()) return
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => { waiters.delete(inspect); reject(new Error('Terminal wire event timed out')) }, 10_000)
const inspect = () => { if (predicate()) { clearTimeout(timer); waiters.delete(inspect); resolve() } }
waiters.add(inspect)
})
}
const send = (frame: object) => { socket.send(JSON.stringify(frame)) }
const open = (streamId: string) => { send({ type: 'open', streamId, endpoint: 'terminal/attach', payload: { args: { agentId: sessionId, id: terminalId } } }) }
await new Promise<void>((resolve, reject) => {
socket.addEventListener('open', () => { resolve() }, { once: true })
socket.addEventListener('error', () => { reject(new Error('Terminal socket failed')) }, { once: true })
})
try {
open('first')
await wait(() => frames.some(frame => frame.streamId === 'first' && frame.value?.type === 'snapshot'))
open('second')
await wait(() => frames.some(frame => frame.streamId === 'second' && frame.value?.type === 'snapshot'))
send({ type: 'item', streamId: 'first', value: { type: 'write', sequence: 1, data: 'IGNORED' } })
await wait(() => frames.some(frame => frame.streamId === 'first' && frame.value?.type === 'ack'))
send({ type: 'item', streamId: 'second', value: { type: 'write', sequence: 1, data: "printf 'DUPLEX_%s\\n' PROOF\r" } })
await wait(() => frames.filter(frame => frame.streamId === 'first').map(frame => frame.value?.data ?? '').join('').includes('DUPLEX_PROOF'))
send({ type: 'item', streamId: 'second', value: { type: 'write', sequence: 2, data: 42 } })
await wait(() => frames.some(frame => frame.streamId === 'second' && frame.type === 'error'))
return frames
} finally {
socket.close()
await new Promise<void>((resolve) => { socket.addEventListener('close', () => { resolve() }, { once: true }) })
}
}, { sessionId, terminalId })
expect(result.some(frame => frame.streamId === 'first' && frame.value?.type === 'state' && !frame.value.writable)).toBe(true)
expect(result.find(frame => frame.streamId === 'first' && frame.value?.type === 'ack')?.value)
.toEqual({ type: 'ack', sequence: 1, refusal: 'read-only' })
expect(result.find(frame => frame.streamId === 'second' && frame.type === 'error')?.error?.code).toBe('gateway/input-invalid')
expect(handles).toHaveLength(1)
expect(tripwire.pageErrors).toEqual([])
})
it('offers reconnection after transport loss and resumes the same process without a new terminal', async () => {
onTestFailed(() => saveFailureShot(page, 'sidebar-terminal-reconnect'))
await openTerminal(page)
+5 -27
View File
@@ -277,35 +277,13 @@ Typed Remote control of transient Session-owned terminal processes.
@Remote({ mode: 'stream' }) retain(sessionId: SessionId, id: WebTerminalId, signal: AbortSignal): AsyncIterable<TerminalRetentionFrame>
/**
* Attach to a terminal without binding its process lifetime to the transport.
* Attach terminal input and output to one physical Remote stream.
* @param agent - Session owner supplied by the Gateway.
* @param id - terminal identity.
* @param attachmentId - new exclusive input attachment.
* @param signal - physical stream cancellation.
* @returns screen recovery followed by output and metadata changes.
* @param signal - attachment cancellation; the process remains alive and input is never replayed.
* @returns screen recovery, output, writable state and provider-acceptance acknowledgements.
*/
@Remote({ mode: 'stream' }) follow(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, signal: AbortSignal): AsyncIterable<TerminalFrame>
/**
* Deliver raw input, including Tab completion and control characters.
* @param agent - Session owner supplied by the Gateway.
* @param id - terminal identity.
* @param attachmentId - current writable attachment.
* @param data - input bytes represented as UTF-8 text.
* @returns after provider input acceptance.
*/
@Remote async write(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, data: string): Promise<void>
/**
* Update the dimensions of the PTY and recovery screen.
* @param agent - Session owner supplied by the Gateway.
* @param id - terminal identity.
* @param attachmentId - current writable attachment.
* @param cols - column count.
* @param rows - row count.
* @returns after the resize completes.
*/
@Remote async resize(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, cols: number, rows: number): Promise<void>
@Remote({ mode: 'stream' }) attach(agent: Agent, id: WebTerminalId, signal: AbortSignal): RemoteStream<TerminalFrame, TerminalInput>
/**
* Rename a terminal without changing its shell.
@@ -324,7 +302,7 @@ Typed Remote control of transient Session-owned terminal processes.
@Remote async close(agent: Agent, id: WebTerminalId): Promise<void>
```
Types: [Agent](core.md) · [SessionId](core.md)
Types: [Agent](core.md) · [RemoteStream](typert.md) · [SessionId](core.md)
Source: [`packages/api/terminal-controller/src/index.ts`](../../packages/api/terminal-controller/src/index.ts)
+5 -27
View File
@@ -277,35 +277,13 @@ Typed Remote control of transient Session-owned terminal processes.
@Remote({ mode: 'stream' }) retain(sessionId: SessionId, id: WebTerminalId, signal: AbortSignal): AsyncIterable<TerminalRetentionFrame>
/**
* Attach to a terminal without binding its process lifetime to the transport.
* Attach terminal input and output to one physical Remote stream.
* @param agent - Session owner supplied by the Gateway.
* @param id - terminal identity.
* @param attachmentId - new exclusive input attachment.
* @param signal - physical stream cancellation.
* @returns screen recovery followed by output and metadata changes.
* @param signal - attachment cancellation; the process remains alive and input is never replayed.
* @returns screen recovery, output, writable state and provider-acceptance acknowledgements.
*/
@Remote({ mode: 'stream' }) follow(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, signal: AbortSignal): AsyncIterable<TerminalFrame>
/**
* Deliver raw input, including Tab completion and control characters.
* @param agent - Session owner supplied by the Gateway.
* @param id - terminal identity.
* @param attachmentId - current writable attachment.
* @param data - input bytes represented as UTF-8 text.
* @returns after provider input acceptance.
*/
@Remote async write(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, data: string): Promise<void>
/**
* Update the dimensions of the PTY and recovery screen.
* @param agent - Session owner supplied by the Gateway.
* @param id - terminal identity.
* @param attachmentId - current writable attachment.
* @param cols - column count.
* @param rows - row count.
* @returns after the resize completes.
*/
@Remote async resize(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, cols: number, rows: number): Promise<void>
@Remote({ mode: 'stream' }) attach(agent: Agent, id: WebTerminalId, signal: AbortSignal): RemoteStream<TerminalFrame, TerminalInput>
/**
* Rename a terminal without changing its shell.
@@ -324,7 +302,7 @@ Typed Remote control of transient Session-owned terminal processes.
@Remote async close(agent: Agent, id: WebTerminalId): Promise<void>
```
Types: [Agent](core.zh.md) · [SessionId](core.zh.md)
Types: [Agent](core.zh.md) · [RemoteStream](typert.zh.md) · [SessionId](core.zh.md)
Source: [`packages/api/terminal-controller/src/index.ts`](../../packages/api/terminal-controller/src/index.ts)
@@ -0,0 +1,16 @@
# Bilingual-pair consistency record for guide.md (docs/i18n/README.md): per heading
# section, a hash of its English and Chinese blocks outside code blocks and generated regions.
# After editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write docs/upgrade-guide/v0.2.1-alpha.2/terminal-duplex/guide.md
/:
en: 027b021f9a291f78
zh: 7551c9a5beb05237
/terminal-input-and-output-share-an-attachment-stream:
en: 5e4a0acab74fdd77
zh: d5a225ba4201a70c
/terminal-input-and-output-share-an-attachment-stream/change:
en: 11300f9f427dce71
zh: e5650275b6fab64f
/terminal-input-and-output-share-an-attachment-stream/migration:
en: 0523c2382060d569
zh: 56d40d8fdc086e0f
@@ -0,0 +1,19 @@
---
kind: upgrade-guide
description: "Terminal Remote clients use one attach stream for screen output, keyboard input and resizing."
---
# Terminal input and output share an attachment stream
English | [中文](guide.zh.md)
## Change
Custom clients of `@deepseek-ai/dsh-api-terminal-controller` replace `terminal.follow`, `terminal.write` and `terminal.resize` with `terminal.attach`. `TerminalAttachmentId` and `WebTerminalInfo.controllerId` are removed. Screen snapshots and state frames carry an attachment-specific `writable` flag. The bundled Web client uses this protocol automatically.
## Migration
1. Upgrade the Host and browser assets together. Custom clients open `remote.terminal.attach(sessionId, terminalId, signal)` and iterate its screen, output, state and acknowledgement frames.
2. Send `TerminalInput` commands with the handle's `send()`: `write` carries `data`; `resize` carries `cols` and `rows`. Number commands consecutively from one for each attachment. An `ack` confirms provider acceptance unless its `refusal` reports lost control or an exited process. Keep unacknowledged input within the advertised byte limit; `send()` alone does not confirm acceptance.
3. Read `writable` from each snapshot or state frame. Stop input after a refusal while continuing to display output. Reconnect with a fresh attachment and screen; never replay unacknowledged input. Keep `retain` and explicit `close` independent of attachment cancellation.
4. Verify keyboard input, resizing, control transfer between two windows, and screen recovery after reconnect. See the [package reference](../../../../packages/api/terminal-controller/README.md) for process ownership and limits.
@@ -0,0 +1,19 @@
---
kind: upgrade-guide
description: "终端 Remote 客户端通过同一 attach 流传输屏幕输出、键盘输入和尺寸调整。"
---
# 终端输入和输出共用附件流
[English](guide.md) | 中文
## 变更
`@deepseek-ai/dsh-api-terminal-controller` 的自定义客户端需将 `terminal.follow`、`terminal.write` 和 `terminal.resize` 替换为 `terminal.attach`。`TerminalAttachmentId` 和 `WebTerminalInfo.controllerId` 已移除。屏幕快照和状态帧携带属于当前附件的 `writable` 标记。内置 Web 客户端自动使用此协议。
## 迁移
1. 同时升级 Host 和浏览器资源。自定义客户端打开 `remote.terminal.attach(sessionId, terminalId, signal)`,迭代其屏幕、输出、状态和确认帧。
2. 通过句柄的 `send()` 发送 `TerminalInput` 命令:`write` 携带 `data`,`resize` 携带 `cols` 和 `rows`。每个附件的命令从一开始连续编号。`ack` 表示提供者已接受操作,除非其 `refusal` 报告失去控制权或进程已退出。未确认输入不得超过公布的字节限制;仅调用 `send()` 并不表示输入已被接受。
3. 从每个快照或状态帧读取 `writable`。输入被拒绝后停止发送,但继续显示输出。重连时使用新的附件和屏幕,绝不重放未确认输入。`retain` 和显式 `close` 继续独立于附件取消。
4. 验证键盘输入、尺寸调整、两个窗口间的控制权转移及重连后的屏幕恢复。进程所有权和限制见[包参考](../../../../packages/api/terminal-controller/README.zh.md)。
@@ -15,11 +15,11 @@
en: d152484eb41ac6b4
zh: 1fa9a72d1ee045cc
/deepseek-ai-dsh-api-terminal-controller/use-this-package:
en: abda92ff99530baa
zh: 67aa726392ae8e05
en: b46d19ac746cdab6
zh: 874ce1abcbc5e8b5
/deepseek-ai-dsh-api-terminal-controller/understand-the-implementation:
en: 94dcd1835c55acc2
zh: cbfeb2da8cb60395
en: bffcbedcdbfa4b72
zh: c90a3085c729ba05
/deepseek-ai-dsh-api-terminal-controller/further-exploration:
en: b1b5d2a2bfb8cc6a
zh: aa0ea568aa63fda5
+4 -4
View File
@@ -25,7 +25,7 @@ Open the execution environment's default shell in the Session's current working
<a id="use-this-package"></a>
## Use this package
The Web bundle mounts this package with the subprocess provider, working-directory service, sandbox policy and Typert Gateway. `remote.terminal` exposes `environment`, `shells`, `list`, `create`, `retain`, `follow`, `write`, `resize`, `rename` and `close`; each operation is scoped by Session identity. Listing reads retained Host terminals directly, so viewing an offline Session neither activates an Agent nor produces a recovery error.
The Web bundle mounts this package with the subprocess provider, working-directory service, sandbox policy and Typert Gateway. `remote.terminal` exposes `environment`, `shells`, `list`, `create`, `retain`, `attach`, `rename` and `close`; each operation is scoped by Session identity. Listing reads retained Host terminals directly, so viewing an offline Session neither activates an Agent nor produces a recovery error.
Shell discovery lists the execution environment's declared default shell first. Only when the provider omits that default does resolution use `/bin/sh` on POSIX or `cmd.exe` on Windows. An optional `shell` profile overrides that choice with executable `path`, display `name` and `args` (default `[]`). The selector also probes `shellCandidates` through the execution provider and omits confirmed lookup misses. It lists each executable name once, ignoring letter case and `.exe`, and keeps the earliest entry, because PATH lookup can reach the default through another directory, such as `/usr/bin/bash` for `/bin/bash` on merged-`/usr` systems. Creation accepts a discovered `shellPath` and verifies it again; resolution or transport failure is reported without launching a different shell. Environment lookup reads the current directory and limits without filesystem validation or shell resolution, so unavailable directories or default shells do not prevent reattaching to an existing process. Automatic POSIX profiles start interactively, and PowerShell uses `-NoLogo`, so completion and startup configuration remain shell-owned. New terminals validate the current directory through the [working-directory service](../../session/working-directory/README.md) before spawning, including its recovery behavior. Existing terminals keep their process directories. User terminals run with the execution environment’s system-user permissions, independently of the Agent’s sandbox mode and approval policy. Operating-system and container restrictions still apply; DSH does not elevate the user. The subprocess provider retains its credential-environment scrubbing.
@@ -37,7 +37,7 @@ Shell discovery lists the execution environment's declared default shell first.
| `maxCols`, `maxRows` | `500`, `200` | Maximum PTY dimensions |
| `scrollback` | `1000` | Retained screen history rows |
| `maxBufferedBytes` | `2097152` | Output queued for one follower |
| `maxInputBytes` | `65536` | Maximum input request bytes |
| `maxInputBytes` | `65536` | Maximum bytes per input command and unacknowledged Client input |
| `disposeGraceMs` | `1000` | Provider termination grace in milliseconds |
| `unattendedTimeoutMs` | `7200000` | Continuous confirmed idle time without window holds before cleanup; `0` disables automatic reclamation |
| `activityPollIntervalMs` | `30000` | Interval between unattended activity observations |
@@ -51,11 +51,11 @@ An open tab in any connected window retains its terminal, including hidden tabs
<details>
<summary>Implementation internals — click to expand</summary>
The Host uses `ctx.subprocess.spawnTerminal` with `TERM=xterm-256color`; it never launches a desktop terminal application. Streaming UTF-8 decoding preserves split characters and leading BOMs, and replaces incomplete trailing bytes at EOF. Unary control uses the Gateway, and `follow` uses its multiplexed Remote stream transport. Headless xterm and its serializer produce each opening screen after all preceding output writes, then monotone output sequences identify subsequent frames. Slow followers fail explicitly; a new attachment restores the current screen.
The Host uses `ctx.subprocess.spawnTerminal` with `TERM=xterm-256color`; it never launches a desktop terminal application. Streaming UTF-8 decoding preserves split characters and leading BOMs, and replaces incomplete trailing bytes at EOF. The duplex `attach` Remote stream carries output and ordered `write`/`resize` commands on the Gateway mux. Each command has a consecutive attachment-local sequence; an `ack` confirms provider acceptance or reports control refusal. Snapshots and state frames carry the receiving attachment's `writable` flag. Headless xterm and its serializer produce each opening screen after all preceding output writes, then monotone output sequences identify subsequent frames. Slow followers fail explicitly; a new attachment restores the current screen.
The latest attachment owns input and resize. Detachment releases input control without killing the process. Explicit close awaits process cleanup and final output; cleanup failure retains the resource for retry. The Session remembers closed identities and rejects their delayed or repeated creation, including creation already in progress when close arrives. A new terminal uses a new identity. Pending allocations remain owned even if cancellation and cleanup both fail. Session owner disposal and controller disposal also terminate owned processes. Changing the Session’s sandbox mode leaves user terminals running with the same permissions. Input or resize refused after control transfer or process exit leaves the output attachment intact and disables input; rejected input is not replayed.
The Client saves each Session/content-to-terminal association before allocation under its own `dsh.terminal.binding.v1.*` localStorage key. The content identity is globally unique; layout-local tab ids only identify live view occurrences. Independent record writes and deletes preserve other windows' bindings. Restored views reuse that identity; the sidebar terminal provider restores its views before querying unrepresented Host terminals. A new view may create a process, while a recovered view reports a missing target without creating a replacement. Explicit close removes the association after saving its cleanup request. The Host supplies current process metadata and screen contents; neither is saved in the browser. The Client model acknowledges screen writes after the browser emulator processes them, serializes input and ignores stale attachment responses. Client-owned errors carry locale keys. Plugin disposal awaits active and previously detached output streams without closing Host processes.
The Client saves each Session/content-to-terminal association before allocation under its own `dsh.terminal.binding.v1.*` localStorage key. The content identity is globally unique; layout-local tab ids only identify live view occurrences. Independent record writes and deletes preserve other windows' bindings. Restored views reuse that identity; the sidebar terminal provider restores its views before querying unrepresented Host terminals. A new view may create a process, while a recovered view reports a missing target without creating a replacement. Explicit close removes the association after saving its cleanup request. The Host supplies current process metadata and screen contents; neither is saved in the browser. The Client model acknowledges screen writes after the browser emulator processes them, pipelines input within its unacknowledged UTF-8 byte budget and ignores stale attachment responses. Reconnection creates a fresh command sequence and never replays unacknowledged input. Provider input failures end the attachment; its process and recovery screen remain available for explicit reconnection. Client-owned errors carry locale keys. Plugin disposal awaits active and previously detached output streams without closing Host processes.
The separate `retain(sessionId, id, signal)` Remote stream acknowledges a window hold without Agent activation, screen output, input transfer or process creation. The terminal provider supplies the sidebar's complete open-tab inventory, and the Client intersects it with its own saved identities. Duplicate occurrences share one hold per window; stale associations alone retain nothing. Restored output attachments wait for an acknowledged current hold. Transport cancellation releases exactly that physical generation; plugin disposal joins all hold streams. Failed cleanup retains ownership and retries without reopening admission or restarting the idle grace.
@@ -25,7 +25,7 @@ kind: "package-reference"
<a id="use-this-package"></a>
## 使用此包
Web bundle 将此包与 subprocess provider、working-directory 服务、sandbox policy 和 Typert Gateway 一起挂载。`remote.terminal` 提供 `environment`、`shells`、`list`、`create`、`retain`、`follow`、`write`、`resize`、`rename` 和 `close`;每个操作均按 Session 标识限定范围。列表直接读取 Host 保留的终端,因此查看离线 Session 不会激活 Agent,也不会产生恢复错误。
Web bundle 将此包与 subprocess provider、working-directory 服务、sandbox policy 和 Typert Gateway 一起挂载。`remote.terminal` 提供 `environment`、`shells`、`list`、`create`、`retain`、`attach`、`rename` 和 `close`;每个操作均按 Session 标识限定范围。列表直接读取 Host 保留的终端,因此查看离线 Session 不会激活 Agent,也不会产生恢复错误。
Shell 探测结果首先列出执行环境声明的默认 shell。仅当 provider 未声明默认值时,才在 POSIX 使用 `/bin/sh`,在 Windows 使用 `cmd.exe`。可选的 `shell` profile 通过可执行路径 `path`、显示名称 `name` 和参数 `args`(默认 `[]`)覆盖这一选择。选择器还会通过执行 provider 探测 `shellCandidates`,并省略确定未找到的候选。同一可执行文件名(不区分大小写,忽略 `.exe`)只列出最早的一项,因为 PATH 查找可能经由其他目录找到默认 shell,例如 merged-`/usr` 系统上 `/bin/bash` 对应的 `/usr/bin/bash`。创建请求接受探测返回的 `shellPath` 并再次验证;解析或传输失败会直接报告,不启动其他 shell。环境查询读取当前目录和限制,不校验文件系统或解析 shell,因此目录或默认 shell 不可用时仍可重新连接已有进程。POSIX 自动 profile 以交互模式启动,PowerShell 使用 `-NoLogo`,补全和启动配置仍由 shell 提供。新终端启动前通过[工作目录服务](../../session/working-directory/README.zh.md)校验当前目录,并采用该服务的恢复行为。已有终端保留其进程目录。用户终端使用执行环境中系统用户的权限,独立于 Agent 的沙箱模式和审批策略。操作系统和容器的限制仍然生效;DSH 不提升用户权限。Subprocess provider 继续清除环境中的凭据变量。
@@ -37,7 +37,7 @@ Shell 探测结果首先列出执行环境声明的默认 shell。仅当 provide
| `maxCols`、`maxRows` | `500`、`200` | PTY 最大尺寸 |
| `scrollback` | `1000` | 屏幕历史行数 |
| `maxBufferedBytes` | `2097152` | 单个订阅者的输出排队上限 |
| `maxInputBytes` | `65536` | 单次输入请求的字节上限 |
| `maxInputBytes` | `65536` | 每条输入命令及 Client 未确认输入的字节上限 |
| `disposeGraceMs` | `1000` | provider 终止宽限期,单位毫秒 |
| `unattendedTimeoutMs` | `7200000` | 无窗口持有且持续确认空闲后开始清理的时长;`0` 禁用自动回收 |
| `activityPollIntervalMs` | `30000` | 无窗口持有时的活动观察间隔 |
@@ -51,11 +51,11 @@ Shell 探测结果首先列出执行环境声明的默认 shell。仅当 provide
<details>
<summary>实现细节</summary>
Host 通过 `ctx.subprocess.spawnTerminal` 创建 `TERM=xterm-256color` 的终端,不启动桌面终端应用。流式 UTF-8 解码保留跨块字符和开头的 BOM,并在 EOF 将不完整的尾部字节替换为替代字符。控制请求走 Gateway,`follow` 使用其复用的 Remote stream。Headless xterm 和序列化 addon 在此前输出写入后生成初始屏幕,后续增量携带单调序号。过慢的订阅者明确失败;重新连接恢复当前屏幕。
Host 通过 `ctx.subprocess.spawnTerminal` 创建 `TERM=xterm-256color` 的终端,不启动桌面终端应用。流式 UTF-8 解码保留跨块字符和开头的 BOM,并在 EOF 将不完整的尾部字节替换为替代字符。双工 `attach` Remote 流通过 Gateway mux 传输输出和有序的 `write`/`resize` 命令。每条命令使用附件内连续递增的序号;`ack` 确认提供者已接受操作,或报告控制权拒绝。快照和状态帧携带接收附件的 `writable` 标记。Headless xterm 和序列化 addon 在此前输出写入后生成初始屏幕,后续增量携带单调序号。过慢的订阅者明确失败;重新连接恢复当前屏幕。
最新连接持有输入和尺寸控制权。断开连接只释放输入权,不结束进程。显式关闭等待进程清理和最后输出;清理失败时保留资源以便重试。Session 记住已关闭的标识并拒绝迟到或重复的创建请求,包括关闭到达时仍在进行的创建。新终端使用新标识。取消创建且清理失败时,已分配的进程仍有所有者。Session owner 和 controller 卸载也会终止所拥有的进程。改变 Session 的沙箱模式时,用户终端继续以原有权限运行。控制权转移或进程退出后被拒绝的输入和尺寸请求保留输出连接并禁用输入,不重发被拒绝的输入。
Client 在分配前将每条 Session/内容与终端身份的关联保存到独立的 localStorage key `dsh.terminal.binding.v1.*`。内容身份全局唯一;布局内的 tab id 只标识活动视图 occurrence。逐条记录的写入和删除会保留其他窗口的关联。恢复视图复用该身份;侧栏 terminal provider 先恢复自己的视图,再查询尚无视图的 Host 终端。新视图可以创建进程,恢复视图在目标缺失时显示错误,不创建替代进程。显式关闭先保存清理请求,再删除关联。当前进程元数据和屏幕内容由 Host 提供,不保存在浏览器中。Client 模型在浏览器完成屏幕解析后确认帧,按序发送输入,并忽略旧连接迟到的响应。Client 自产错误携带本地化键。插件卸载等待活跃及先前断开的输出流结束,不关闭 Host 进程。
Client 在分配前将每条 Session/内容与终端身份的关联保存到独立的 localStorage key `dsh.terminal.binding.v1.*`。内容身份全局唯一;布局内的 tab id 只标识活动视图 occurrence。逐条记录的写入和删除会保留其他窗口的关联。恢复视图复用该身份;侧栏 terminal provider 先恢复自己的视图,再查询尚无视图的 Host 终端。新视图可以创建进程,恢复视图在目标缺失时显示错误,不创建替代进程。显式关闭先保存清理请求,再删除关联。当前进程元数据和屏幕内容由 Host 提供,不保存在浏览器中。Client 模型在浏览器完成屏幕解析后确认帧,在未确认 UTF-8 字节预算内连续发送输入,并忽略旧连接迟到的响应。重连建立新的命令序列,绝不重放未确认输入。提供者输入失败会结束附件;进程和恢复屏幕仍可供显式重连使用。Client 自产错误携带本地化键。插件卸载等待活跃及先前断开的输出流结束,不关闭 Host 进程。
独立的 `retain(sessionId, id, signal)` Remote 流确认窗口持有关系,不激活 Agent、发送屏幕输出、转移输入权或创建进程。终端 provider 提供侧栏的完整打开标签清单,Client 将其与自己保存的身份取交集。同一窗口中的重复 occurrence 共用一个持有流;孤立的旧关联不会保活任何终端。恢复输出连接前必须等待当前持有关系确认。传输取消只释放对应的物理流代次;插件卸载等待全部持有流结束。清理失败时保留所有权并重试,不重新接受连接,也不重新计算空闲宽限期。
@@ -58,9 +58,10 @@
"@deepseek-ai/dsh-deque": "workspace:*",
"@deepseek-ai/dsh-lazy-require": "workspace:*",
"@deepseek-ai/dsh-typert-protocol": "workspace:*",
"@deepseek-ai/dsh-util-values": "workspace:*",
"@deepseek-ai/schemastery": "workspace:~",
"@xterm/headless": "^6.0.0",
"@xterm/addon-serialize": "^0.14.0",
"@xterm/headless": "^6.0.0",
"zod": "4.4.3"
},
"peerDependencies": {
@@ -1,13 +1,12 @@
/** React-free browser terminal state and reconnecting Remote-stream ownership. */
import { preferredShell, rememberShell } from './shell-preference.ts'
import { randomUUID } from '@deepseek-ai/dsh-util-crypto'
import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-store'
import { RemoteStreamCarrierError, type ClientRemote, type RemoteStream } from '@deepseek-ai/dsh-api-gateway/client'
import { RemoteError, remoteErrorOf, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import { RemoteError, remoteErrorOf, type RemoteResult, type RemoteStreamHandle } from '@deepseek-ai/dsh-typert-protocol'
import type {} from '@deepseek-ai/dsh-api-terminal-controller/remote'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import type {
TerminalAttachmentId, TerminalEnvironment, TerminalFrame,
TerminalInput, TerminalEnvironment, TerminalFrame,
WebTerminalId, WebTerminalInfo,
} from '../types.ts'
@@ -46,6 +45,15 @@ export interface TerminalViewState {
readonly issue?: TerminalViewIssue | undefined
}
interface TerminalInputAttachment {
readonly handle: RemoteStreamHandle<TerminalFrame, TerminalInput>
readonly signal: AbortSignal
sequence: number
acknowledged: number
readonly pending: Map<number, number>
bytes: number
}
/** A view survives DOM unmount; its process only ends on explicit close. */
export class TerminalView {
/** Observable controls, process metadata and the next screen update awaiting acknowledgement. */
@@ -53,14 +61,12 @@ export class TerminalView {
private readonly lifetime = new AbortController()
private stream: RemoteStream<TerminalFrame> | undefined
private mounted = false
private attachmentId: TerminalAttachmentId | undefined
private attachment: TerminalInputAttachment | undefined
private pendingRender: { revision: number; resolve: () => void } | undefined
private revision = 0
private creation: Promise<void> | undefined
private loading: Promise<void> | undefined
private closing: Promise<void> | undefined
private writes: Promise<void> = Promise.resolve()
private queuedInput = 0
private readonly detaching = new Set<Promise<void>>()
/**
@@ -164,9 +170,11 @@ export class TerminalView {
open: async function* (this: TerminalView, signal: AbortSignal) {
await this.retain?.(signal)
signal.throwIfAborted()
const attachmentId = randomUUID() as TerminalAttachmentId
this.attachmentId = attachmentId
yield* this.remote.follow(this.sessionId, info.id, attachmentId, signal)
const handle = this.remote.attach(this.sessionId, info.id, signal)
const attachment = { handle, signal, sequence: 0, acknowledged: 0, pending: new Map<number, number>(), bytes: 0 }
this.attachment = attachment
try { yield* handle }
finally { if (this.attachment === attachment) this.attachment = undefined }
}.bind(this),
ended: () => new TerminalViewError('attachmentEnded'),
carrierFailed: () => { if (this.stream === stream) this.patch({ phase: 'disconnected', writable: false }) },
@@ -187,40 +195,41 @@ export class TerminalView {
}
/**
* Serialize raw input so concurrent RPC requests cannot reorder keystrokes.
* @param data - input from the terminal emulator.
* Queue raw input within the current attachment's unacknowledged UTF-8 byte budget.
* @param data - input from the terminal emulator; never replayed after disconnection.
*/
write(data: string): void {
const state = this.state.getSnapshot()
const attachmentId = this.attachmentId
if (!state.writable || state.info === undefined || attachmentId === undefined) return
const attachment = this.attachment
if (!state.writable || state.info === undefined || attachment === undefined || attachment.signal.aborted) return
if (data.length === 0) return
const bytes = new TextEncoder().encode(data).byteLength
if (this.queuedInput + bytes > (state.environment?.maxInputBytes ?? 0)) { this.fail(new TerminalViewError('inputFull')); return }
this.queuedInput += bytes
const id = state.info.id
this.writes = this.writes.then(async () => {
if (this.attachmentId !== attachmentId || !this.state.getSnapshot().writable) return
valueOf(await this.remote.write(this.sessionId, id, attachmentId, data))
}).catch((error: unknown) => { if (this.attachmentId === attachmentId) this.fail(error) }).finally(() => { this.queuedInput -= bytes })
if (attachment.bytes + bytes > (state.environment?.maxInputBytes ?? 0)) { this.fail(new TerminalViewError('inputFull')); return }
this.send(attachment, { type: 'write', sequence: attachment.sequence + 1, data }, bytes)
}
/**
* Resize only from the currently writable view.
* Resize only from the currently writable view, ordered with keyboard input.
* @param cols - measured column count.
* @param rows - measured row count.
*/
resize(cols: number, rows: number): void {
const state = this.state.getSnapshot()
const attachmentId = this.attachmentId
if (!state.writable || state.info === undefined || attachmentId === undefined) return
const attachment = this.attachment
if (!state.writable || state.info === undefined || attachment === undefined || attachment.signal.aborted) return
if (state.info.cols === cols && state.info.rows === rows) return
const id = state.info.id
cols = Math.min(cols, state.environment?.maxCols ?? cols)
rows = Math.min(rows, state.environment?.maxRows ?? rows)
this.writes = this.writes.then(async () => {
if (this.attachmentId !== attachmentId || !this.state.getSnapshot().writable) return
valueOf(await this.remote.resize(this.sessionId, id, attachmentId, cols, rows))
}).catch((error: unknown) => { if (this.attachmentId === attachmentId) this.fail(error) })
this.send(attachment, { type: 'resize', sequence: attachment.sequence + 1, cols, rows }, 0)
}
private send(attachment: TerminalInputAttachment, command: TerminalInput, bytes: number): void {
try {
attachment.handle.send(command)
attachment.sequence = command.sequence
if (bytes > 0) attachment.pending.set(command.sequence, bytes)
attachment.bytes += bytes
} catch (error) { this.fail(error) }
}
/**
@@ -269,7 +278,7 @@ export class TerminalView {
private detach(): void {
const previous = this.stream
this.stream = undefined
this.attachmentId = undefined
this.attachment = undefined
this.pendingRender?.resolve()
this.pendingRender = undefined
if (previous !== undefined) {
@@ -294,8 +303,19 @@ export class TerminalView {
if (frame.sequence !== sequence + 1) throw new TerminalViewError('invalidOutput', 'Terminal output sequence has a gap')
sequence = frame.sequence
} else if (frame.type === 'snapshot') throw new TerminalViewError('invalidOutput', 'Unexpected terminal screen snapshot')
if (frame.type === 'ack') {
const attachment = this.attachment
/* v8 ignore next -- the physical opener retains its handle until this consumer advances. */
if (attachment === undefined) throw new TerminalViewError('invalidOutput', 'Terminal acknowledgement has no attachment')
if (frame.sequence !== attachment.acknowledged + 1 || frame.sequence > attachment.sequence) throw new TerminalViewError('invalidOutput', 'Terminal input acknowledgement is out of order')
attachment.acknowledged = frame.sequence
attachment.bytes -= attachment.pending.get(frame.sequence) ?? 0
attachment.pending.delete(frame.sequence)
if (frame.refusal !== undefined) this.patch({ writable: false })
continue
}
if (frame.type !== 'output') {
this.patch({ info: frame.info, title: frame.info.title, phase: 'connected', writable: frame.info.state === 'running' && frame.info.controllerId === this.attachmentId })
this.patch({ info: frame.info, title: frame.info.title, phase: 'connected', writable: frame.info.state === 'running' && frame.writable })
}
if (frame.type !== 'state') {
const revision = ++this.revision
@@ -324,10 +344,6 @@ export class TerminalView {
private fail(error: unknown): void {
const failure = remoteErrorOf(error)
if (failure?.code === 'terminal/control-unavailable') {
this.patch({ writable: false, error: undefined, issue: undefined })
return
}
const issue = failure?.code === 'terminal/view' ? failure.details.issue : failure?.code === 'terminal/limit-reached' ? 'terminalLimit' : failure?.code === 'terminal/unavailable' ? 'missingTerminal' : undefined
this.patch({ phase: error instanceof RemoteStreamCarrierError ? 'disconnected' : 'failed', writable: false, issue, error: error instanceof Error ? error.message : String(error) })
}
+9 -38
View File
@@ -5,12 +5,12 @@ import type { Agent } from '@deepseek-ai/dsh-agent'
import type { SessionId } from '@deepseek-ai/dsh-session'
import type {} from '@deepseek-ai/dsh-sandbox-policy'
import type {} from '@deepseek-ai/dsh-working-directory'
import { Remote, RemoteError, TypertRemoteService } from '@deepseek-ai/dsh-typert-protocol'
import { Remote, RemoteError, TypertRemoteService, type RemoteStream } from '@deepseek-ai/dsh-typert-protocol'
import { discoverShells, resolveShell } from './shells.ts'
import { BrowserTerminal } from './terminal.ts'
import { TerminalRetention } from './retention.ts'
import type {
TerminalShell, TerminalAttachmentId, TerminalCreateRequest, TerminalEnvironment, TerminalFrame, TerminalRetentionFrame,
TerminalShell, TerminalInput, TerminalCreateRequest, TerminalEnvironment, TerminalFrame, TerminalRetentionFrame,
WebTerminalId, WebTerminalInfo,
} from './types.ts'
@@ -206,46 +206,17 @@ export class TerminalController extends TypertRemoteService {
}
/**
* Attach to a terminal without binding its process lifetime to the transport.
* Attach terminal input and output to one physical Remote stream.
* @param agent - Session owner supplied by the Gateway.
* @param id - terminal identity.
* @param attachmentId - new exclusive input attachment.
* @param signal - physical stream cancellation.
* @returns screen recovery followed by output and metadata changes.
* @param signal - attachment cancellation; the process remains alive and input is never replayed.
* @returns screen recovery, output, writable state and provider-acceptance acknowledgements.
*/
@Remote({ mode: 'stream' })
follow(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, signal: AbortSignal): AsyncIterable<TerminalFrame> {
if (!/^[\w-]{1,128}$/u.test(attachmentId)) throw new Error('Invalid terminal attachment identity')
return this.terminal(agent, id).follow(attachmentId, signal)
}
/**
* Deliver raw input, including Tab completion and control characters.
* @param agent - Session owner supplied by the Gateway.
* @param id - terminal identity.
* @param attachmentId - current writable attachment.
* @param data - input bytes represented as UTF-8 text.
* @returns after provider input acceptance.
*/
@Remote
async write(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, data: string): Promise<void> {
if (Buffer.byteLength(data, 'utf8') > this.config.maxInputBytes) throw new Error('Terminal input exceeds the configured limit')
await this.terminal(agent, id).write(attachmentId, data)
}
/**
* Update the dimensions of the PTY and recovery screen.
* @param agent - Session owner supplied by the Gateway.
* @param id - terminal identity.
* @param attachmentId - current writable attachment.
* @param cols - column count.
* @param rows - row count.
* @returns after the resize completes.
*/
@Remote
async resize(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, cols: number, rows: number): Promise<void> {
this.dimensions(cols, rows)
await this.terminal(agent, id).resize(attachmentId, cols, rows)
attach(agent: Agent, id: WebTerminalId, signal: AbortSignal): RemoteStream<TerminalFrame, TerminalInput> {
const invocation = this.ctx.invocation
if (invocation === undefined) throw new Error('Terminal attachment requires a Remote invocation')
return this.terminal(agent, id).attach(invocation.uplink<TerminalInput>(), this.config, signal)
}
/**
+14 -2
View File
@@ -11,6 +11,9 @@ export class TerminalFollower {
private finished = false
private failure: Error | undefined
/** Whether this attachment still accepts input and output. */
get active(): boolean { return !this.closed && !this.finished }
/** @param maxBytes - maximum queued UTF-8 bytes for this follower. */
constructor(private readonly maxBytes: number) {}
@@ -22,8 +25,7 @@ export class TerminalFollower {
if (this.closed || this.finished) return
const bytes = Buffer.byteLength(JSON.stringify(frame), 'utf8')
if (this.bytes + bytes > this.maxBytes) {
this.failure = new Error('Terminal output consumer exceeded its buffer; reconnect to recover the current screen')
this.close()
this.fail(new Error('Terminal output consumer exceeded its buffer; reconnect to recover the current screen'))
return
}
this.queue.pushBack({ frame, bytes })
@@ -31,6 +33,16 @@ export class TerminalFollower {
this.wake?.()
}
/**
* Fail this attachment without stopping its terminal.
* @param error - input or output failure reported to the attached consumer.
*/
fail(error: Error): void {
if (this.closed) return
this.failure = error
this.close()
}
/** Finish after delivering every queued frame, including the final exit state. */
finish(): void {
this.finished = true
@@ -1,12 +1,13 @@
/** One PTY, a bounded terminal emulator and its detachable browser followers. */
import { RemoteError } from '@deepseek-ai/dsh-typert-protocol'
import { assertNever } from '@deepseek-ai/dsh-util-values'
import { RemoteError, remoteErrorOf } from '@deepseek-ai/dsh-typert-protocol'
import type { Terminal as HeadlessTerminal } from '@xterm/headless'
import type { SerializeAddon as Serializer } from '@xterm/addon-serialize'
import type { SubprocessTerminalHandle } from '@deepseek-ai/dsh-subprocess'
import { createLazyRequire } from '@deepseek-ai/dsh-lazy-require'
import { TerminalFollower } from './stream.ts'
import { TerminalRetention, type TerminalRetentionPolicy } from './retention.ts'
import type { TerminalAttachmentId, TerminalFrame, TerminalRetentionFrame, WebTerminalInfo } from './types.ts'
import type { TerminalEnvironment, TerminalInput, TerminalFrame, TerminalRetentionFrame, WebTerminalInfo } from './types.ts'
const requireHeadless = createLazyRequire<typeof import('@xterm/headless')>('@xterm/headless', import.meta.url)
const requireSerialize = createLazyRequire<typeof import('@xterm/addon-serialize')>('@xterm/addon-serialize', import.meta.url)
@@ -21,7 +22,7 @@ export class BrowserTerminal {
private readonly drained: Promise<void>
private closing: Promise<void> | undefined
private retention: TerminalRetention | undefined
private controller: { id: TerminalAttachmentId; follower: TerminalFollower } | undefined
private controller: TerminalFollower | undefined
/**
* @param handle - allocated terminal process range.
@@ -69,64 +70,87 @@ export class BrowserTerminal {
}
/**
* Attach with exclusive input control; an older attachment becomes read-only.
* @param id - browser attachment identity.
* Attach with exclusive input control; older attachments keep receiving output.
* @param input - Gateway-decoded commands; returning its iterator must interrupt pending reads.
* @param limits - input byte and PTY dimension limits validated at the Remote boundary.
* @param signal - attachment cancellation; never terminates the process.
* @returns a consistent screen followed by ordered output and state changes.
* @returns a screen baseline, output, per-attachment state and ordered command acknowledgements.
*/
async *follow(id: TerminalAttachmentId, signal: AbortSignal): AsyncIterable<TerminalFrame> {
async *attach(input: AsyncIterable<TerminalInput>, limits: Pick<TerminalEnvironment, 'maxInputBytes' | 'maxCols' | 'maxRows'>, signal: AbortSignal): AsyncIterable<TerminalFrame> {
signal.throwIfAborted()
const follower = new TerminalFollower(this.maxBufferedBytes)
const baseline = await this.enqueue(() => {
signal.throwIfAborted()
this.controller = { id, follower }
this.info = { ...this.info, controllerId: id }
this.broadcast({ type: 'state', info: this.info })
const snapshot: TerminalFrame = { type: 'snapshot', sequence: this.sequence, screen: this.serializer.serialize(), info: this.info }
this.controller = follower
this.broadcastState()
const snapshot: TerminalFrame = { type: 'snapshot', sequence: this.sequence, screen: this.serializer.serialize(), info: this.info, writable: this.writable(follower) }
this.followers.add(follower)
return snapshot
})
const uplink = input[Symbol.asyncIterator]()
const commands = this.consumeInput(uplink, follower, limits, signal).catch((error: unknown) => {
follower.fail(error instanceof Error ? error : new Error(String(error)))
})
try {
yield baseline
yield* follower.read(signal)
} finally {
this.followers.delete(follower)
follower.close()
if (this.controller?.follower === follower) {
if (this.controller === follower) {
this.controller = undefined
const { controllerId: _controllerId, ...info } = this.info
this.info = info
this.broadcast({ type: 'state', info })
this.broadcastState()
}
// Gateway's uplink return wakes pending reads before attachment cleanup joins the input pump.
await uplink.return?.()
await commands
}
}
private async consumeInput(input: AsyncIterator<TerminalInput>, follower: TerminalFollower, limits: Pick<TerminalEnvironment, 'maxInputBytes' | 'maxCols' | 'maxRows'>, signal: AbortSignal): Promise<void> {
let sequence = 0
while (true) {
const next = await input.next()
if (next.done === true || signal.aborted || !follower.active) return
const command = next.value
if (!Number.isSafeInteger(command.sequence) || command.sequence !== ++sequence) throw new Error('Terminal input sequence has a gap')
try {
await this.enqueue(async () => {
signal.throwIfAborted()
this.requireController(follower)
switch (command.type) {
case 'write':
if (Buffer.byteLength(command.data, 'utf8') > limits.maxInputBytes) throw new Error('Terminal input exceeds the configured limit')
this.retention?.invalidate()
await this.handle.write(command.data)
break
case 'resize':
if (!Number.isSafeInteger(command.cols) || command.cols < 2 || command.cols > limits.maxCols
|| !Number.isSafeInteger(command.rows) || command.rows < 1 || command.rows > limits.maxRows) throw new Error('Terminal dimensions exceed the configured limits')
await this.handle.resize(command.cols, command.rows)
this.screen.resize(command.cols, command.rows)
this.info = { ...this.info, cols: command.cols, rows: command.rows }
this.broadcastState()
break
/* v8 ignore next -- the Gateway codec validates this closed union. */
default: assertNever(command)
}
})
follower.push({ type: 'ack', sequence })
} catch (error) {
const failure = remoteErrorOf(error)
if (failure?.code !== 'terminal/control-unavailable') throw error
follower.push({ type: 'ack', sequence, refusal: failure.details.reason })
}
}
}
/**
* Send raw terminal input without command interpretation.
* @param id - current writable attachment.
* @param data - UTF-8 input, including shell completion/control keys.
* @returns when the provider accepts the input.
*/
write(id: TerminalAttachmentId, data: string): Promise<void> {
this.retention?.invalidate()
return this.enqueue(async () => { this.requireController(id); await this.handle.write(data) })
private writable(follower: TerminalFollower): boolean {
return this.closing === undefined && this.info.state === 'running' && this.controller === follower
}
/**
* Resize the PTY and recovery screen in the same operation order as output.
* @param id - current writable attachment.
* @param cols - validated column count.
* @param rows - validated row count.
* @returns when the provider and emulator use the new dimensions.
*/
resize(id: TerminalAttachmentId, cols: number, rows: number): Promise<void> {
return this.enqueue(async () => {
this.requireController(id)
await this.handle.resize(cols, rows)
this.screen.resize(cols, rows)
this.info = { ...this.info, cols, rows }
this.broadcast({ type: 'state', info: this.info })
})
private broadcastState(): void {
for (const follower of this.followers) follower.push({ type: 'state', info: this.info, writable: this.writable(follower) })
}
/**
@@ -135,7 +159,7 @@ export class BrowserTerminal {
*/
rename(title: string): void {
this.info = { ...this.info, title }
this.broadcast({ type: 'state', info: this.info })
this.broadcastState()
}
/**
@@ -164,9 +188,9 @@ export class BrowserTerminal {
return this.closing
}
private requireController(id: TerminalAttachmentId): void {
private requireController(follower: TerminalFollower): void {
if (this.closing !== undefined || this.info.state !== 'running') throw new RemoteError('terminal/control-unavailable', 'Terminal is not running', { reason: 'not-running' })
if (this.controller?.id !== id) throw new RemoteError('terminal/control-unavailable', 'Terminal input is controlled by another attachment', { reason: 'read-only' })
if (this.controller !== follower || !follower.active) throw new RemoteError('terminal/control-unavailable', 'Terminal input is controlled by another attachment', { reason: 'read-only' })
}
private broadcast(frame: TerminalFrame): void {
@@ -195,7 +219,7 @@ export class BrowserTerminal {
} catch (error) {
this.info = { ...this.info, state: 'failed', error: error instanceof Error ? error.message : String(error) }
}
this.broadcast({ type: 'state', info: this.info })
this.broadcastState()
}
private async output(data: string): Promise<void> {
@@ -15,8 +15,6 @@ declare module '@deepseek-ai/dsh-typert-protocol' {
/** A terminal identity scoped to one Session and one Host lifetime. */
export type WebTerminalId = Branded<'WebTerminalId'>
/** An attachment allowed to write and resize one terminal. */
export type TerminalAttachmentId = Branded<'TerminalAttachmentId'>
/** Acknowledges one physical window hold without taking screen or input control. */
export interface TerminalRetentionFrame {
@@ -52,7 +50,6 @@ export interface WebTerminalInfo {
readonly state: 'running' | 'exited' | 'failed'
readonly exitCode: number | null
readonly error?: string
readonly controllerId?: TerminalAttachmentId
}
/** Create is idempotent for an open identity; closed identities cannot be recreated. */
@@ -64,8 +61,14 @@ export interface TerminalCreateRequest {
readonly rows: number
}
/** Commands are numbered consecutively from one within each attachment; acknowledgements never authorize replay. */
export type TerminalInput =
| { readonly type: 'write'; readonly sequence: number; readonly data: string }
| { readonly type: 'resize'; readonly sequence: number; readonly cols: number; readonly rows: number }
/** Every attachment begins with a complete bounded screen, then ordered output. */
export type TerminalFrame =
| { readonly type: 'snapshot'; readonly sequence: number; readonly screen: string; readonly info: WebTerminalInfo }
| { readonly type: 'snapshot'; readonly sequence: number; readonly screen: string; readonly info: WebTerminalInfo; readonly writable: boolean }
| { readonly type: 'output'; readonly sequence: number; readonly data: string }
| { readonly type: 'state'; readonly info: WebTerminalInfo }
| { readonly type: 'state'; readonly info: WebTerminalInfo; readonly writable: boolean }
| { readonly type: 'ack'; readonly sequence: number; readonly refusal?: 'read-only' | 'not-running' }
@@ -11,8 +11,10 @@ import { SubprocessExecutableNotFoundError, type SubprocessRuntime, type Subproc
import LocalSubprocessRuntime from '@deepseek-ai/dsh-subprocess-local'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { TerminalController, type Config } from '../src/index.ts'
import { inputChannel } from './input.ts'
import type { RemoteInvocation, PeerId } from '@deepseek-ai/dsh-typert-protocol'
import { resolveShell } from '../src/shells.ts'
import type { TerminalAttachmentId, WebTerminalId } from '../src/types.ts'
import type { TerminalInput, WebTerminalId } from '../src/types.ts'
const roots: Context[] = []
afterEach(async () => { await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) })
@@ -87,7 +89,7 @@ describe('TerminalController', () => {
subprocess.resolveExecutable.mockRejectedValue(new SubprocessExecutableNotFoundError('default shell was removed'))
expect(controller.environment(agent, signal())).toMatchObject({ cwd: '/workspace', maxInputBytes: 1000 })
expect(controller.list(agent.id)).toMatchObject([{ id, state: 'running' }])
const stream = controller.follow(agent, id, 'restored' as TerminalAttachmentId, signal())[Symbol.asyncIterator]()
const stream = attachController(agent, id, signal())[Symbol.asyncIterator]()
try {
expect(await stream.next()).toMatchObject({ done: false, value: { type: 'snapshot', info: { id, state: 'running' } } })
expect(subprocess.resolveExecutable).toHaveBeenCalledOnce()
@@ -181,9 +183,9 @@ describe('TerminalController', () => {
expect(subprocess.spawnTerminal).toHaveBeenCalledOnce()
expect(subprocess.spawnTerminal).toHaveBeenCalledWith(expect.objectContaining({ terminalType: 'xterm-256color', cwd: '/workspace' }))
expect(controller.list('other' as SessionId)).toEqual([])
expect(() => controller.follow(owner(ctx, 'other'), id, 'writer' as TerminalAttachmentId, signal())).toThrow('no longer exists')
expect(() => attachController(owner(ctx, 'other'), id, signal())).toThrow('no longer exists')
const abort = new AbortController()
const stream = controller.follow(agent, id, 'writer' as TerminalAttachmentId, abort.signal)[Symbol.asyncIterator]()
const stream = attachController(agent, id, abort.signal)[Symbol.asyncIterator]()
const firstFrame = await stream.next()
if (firstFrame.done === true) throw new Error('Terminal stream ended before its snapshot')
expect(firstFrame.value.type).toBe('snapshot')
@@ -266,13 +268,13 @@ describe('TerminalController', () => {
expect(controller.list(agent.id)).toHaveLength(0)
})
it('rejects invalid dimensions, unavailable shells and oversized input before executing them', async () => {
it('rejects invalid dimensions and unavailable shells before allocating a process', async () => {
const { controller, agent, subprocess } = fixture()
await expect(controller.create(agent, { ...request, cols: 1 }, signal())).rejects.toThrow('dimensions')
subprocess.resolveExecutable.mockRejectedValueOnce(new SubprocessExecutableNotFoundError('shell unavailable'))
await expect(controller.create(agent, request, signal())).rejects.toThrow('unavailable')
expect(subprocess.spawnTerminal).not.toHaveBeenCalled()
await expect(controller.write(agent, id, 'writer' as TerminalAttachmentId, 'x'.repeat(1001))).rejects.toThrow('input')
})
it('keeps the committed identity on repeated creation and counts pending reservations toward the Session limit', async () => {
@@ -319,27 +321,32 @@ describe('TerminalController', () => {
expect(controller.list(agent.id)).toEqual([])
})
it('routes input, resize and trimmed names through the active attachment', async () => {
it('routes ordered input and resize through the current Remote attachment', async () => {
const { controller, agent, handle } = fixture({ maxInputBytes: 6 })
await controller.create(agent, request, signal())
const attachmentId = 'writer' as TerminalAttachmentId
const stream = controller.follow(agent, id, attachmentId, signal())[Symbol.asyncIterator]()
const input = inputChannel<TerminalInput>()
const stream = attachController(agent, id, signal(), input.source)[Symbol.asyncIterator]()
await stream.next()
try {
await controller.write(agent, id, attachmentId, '终端')
input.push({ type: 'write', sequence: 1, data: '终端' })
expect((await stream.next()).value).toMatchObject({ type: 'ack', sequence: 1 })
expect(handle.write).toHaveBeenCalledWith('终端')
await expect(controller.write(agent, id, attachmentId, '终端!')).rejects.toThrow('input exceeds')
await controller.resize(agent, id, attachmentId, 200, 100)
input.push({ type: 'resize', sequence: 2, cols: 200, rows: 100 })
expect((await stream.next()).value).toMatchObject({ type: 'state', info: { cols: 200, rows: 100 } })
expect((await stream.next()).value).toMatchObject({ type: 'ack', sequence: 2 })
expect(handle.resize).toHaveBeenCalledWith(200, 100)
controller.rename(agent, id, ' server logs ')
expect(controller.list(agent.id)).toMatchObject([{ title: 'server logs', cols: 200, rows: 100 }])
input.push({ type: 'write', sequence: 3, data: '终端!' })
await stream.next()
await expect(stream.next()).rejects.toThrow('input exceeds')
} finally { await stream.return?.() }
})
it.each([{ cols: 1.5, rows: 24 }, { cols: 201, rows: 24 }, { cols: 80, rows: 1.5 }, { cols: 80, rows: 0 }, { cols: 80, rows: 101 }])('rejects dimensions $cols × $rows before allocation or resize', async (dimensions) => {
it.each([{ cols: 1.5, rows: 24 }, { cols: 201, rows: 24 }, { cols: 80, rows: 1.5 }, { cols: 80, rows: 0 }, { cols: 80, rows: 101 }])('rejects dimensions $cols × $rows before allocation', async (dimensions) => {
const { controller, agent, subprocess, handle } = fixture()
await expect(controller.create(agent, { ...request, ...dimensions }, signal())).rejects.toThrow('dimensions')
await expect(controller.resize(agent, id, 'writer' as TerminalAttachmentId, dimensions.cols, dimensions.rows)).rejects.toThrow('dimensions')
expect(subprocess.spawnTerminal).not.toHaveBeenCalled()
expect(handle.resize).not.toHaveBeenCalled()
})
@@ -347,7 +354,7 @@ describe('TerminalController', () => {
it('rejects invalid wire identities and names without changing retained terminals', async () => {
const { controller, agent } = fixture()
await expect(controller.create(agent, { ...request, id: '../terminal' as WebTerminalId }, signal())).rejects.toThrow('Invalid terminal identity')
expect(() => controller.follow(agent, id, '' as TerminalAttachmentId, signal())).toThrow('attachment identity')
expect(() => controller.attach(agent, id, signal())).toThrow('Remote invocation')
expect(() => { controller.rename(agent, id, ' ') }).toThrow('1–120')
expect(() => { controller.rename(agent, id, 'x'.repeat(121)) }).toThrow('1–120')
await controller.close(agent, id)
@@ -699,12 +706,25 @@ it.each(['allocation', 'committed'] as const)('retains failed %s cleanup, report
it('classifies missing and closing terminal identities for localized recovery actions', async () => {
const h = fixture()
expect(() => h.controller.follow(h.agent, id, 'view' as TerminalAttachmentId, signal()))
expect(() => attachController(h.agent, id, signal()))
.toThrow(expect.objectContaining({ code: 'terminal/unavailable' }))
await h.controller.create(h.agent, request, signal())
h.handle.terminate.mockRejectedValueOnce(new Error('cleanup pending'))
await expect(h.controller.close(h.agent, id)).rejects.toThrow('cleanup pending')
expect(() => h.controller.follow(h.agent, id, 'view' as TerminalAttachmentId, signal()))
expect(() => attachController(h.agent, id, signal()))
.toThrow(expect.objectContaining({ code: 'terminal/unavailable' }))
await expect(h.controller.create(h.agent, request, signal())).rejects.toMatchObject({ code: 'terminal/unavailable' })
})
function attachController(
agent: Agent, terminalId: WebTerminalId, signal: AbortSignal,
input: AsyncIterable<unknown> = inputChannel<TerminalInput>().source,
) {
const invocation: RemoteInvocation = {
request: { namespace: 'terminal', method: 'attach', args: {} }, service: 'terminalController', signal,
peer: { id: 'test-peer' as PeerId, ctx: agent.ctx, dispose: async () => {} },
uplink: <In>() => input as AsyncIterable<In>,
}
return agent.ctx.extend({ invocation }).terminalController.attach(agent, terminalId, signal)
}
@@ -0,0 +1,16 @@
/** A typed uplink whose return interrupts a pending read, matching Gateway invocation cleanup. */
export function inputChannel<T>() {
let controller!: ReadableStreamDefaultController<T>
const stream = new ReadableStream<T>({ start(value) { controller = value } })
const reader = stream.getReader()
const source: AsyncIterable<T> = {
[Symbol.asyncIterator]: () => ({
async next() {
const result = await reader.read()
return result.done ? { done: true, value: undefined } : { done: false, value: result.value }
},
async return() { await reader.cancel(); return { done: true, value: undefined } },
}),
}
return { source, push: (value: T) => { controller.enqueue(value) }, end: () => { controller.close() } }
}
@@ -1,14 +1,13 @@
/** Browser view ownership across slow RPCs, remounts and transport generations. */
import { setImmediate } from 'node:timers/promises'
import { afterEach, expect, it, vi } from 'vitest'
import { RemoteStream, RemoteStreamCarrierError, type ClientRemote, type RemoteStreamOptions } from '@deepseek-ai/dsh-api-gateway/client'
import { createSnapshotStore } from '@deepseek-ai/dsh-client-store'
import { RemoteError, type RemoteResult } from '@deepseek-ai/dsh-typert-protocol'
import { streamMethod } from '@deepseek-ai/dsh-remote-mock'
import { RemoteMock, streamMethod, type StreamHandle } from '@deepseek-ai/dsh-remote-mock'
import type {} from '@deepseek-ai/dsh-api-terminal-controller/remote'
import type { SessionId } from '@deepseek-ai/dsh-session/types'
import { TerminalView, type TerminalRemote } from '../src/client/model.ts'
import type { TerminalEnvironment, TerminalFrame, WebTerminalId, WebTerminalInfo } from '../src/types.ts'
import type { TerminalInput, TerminalEnvironment, TerminalFrame, WebTerminalId, WebTerminalInfo } from '../src/types.ts'
const sessionId = 'session' as SessionId
const info: WebTerminalInfo = { id: 'terminal' as WebTerminalId, shell: { name: 'bash', path: '/bin/bash', args: ['-i'] }, title: 'bash', cwd: '/workspace', rows: 24, cols: 80, state: 'running', exitCode: null }
@@ -31,6 +30,15 @@ function failure(message: string): RemoteResult<never> {
}
function fixture(prepareStream?: <Item>(stream: RemoteStream<Item>) => void) {
const attachments: StreamHandle[] = []
const sent: TerminalInput[][] = []
const mock = RemoteMock.create().stream('terminal/attach', async (args, stream) => {
attachments.push(stream)
const commands: TerminalInput[] = []
sent.push(commands)
stream.push({ type: 'snapshot', sequence: 0, screen: 'ready', info: { ...info, id: args[1] }, writable: true })
for await (const command of stream.uplink) commands.push(command as TerminalInput)
})
const remote: TerminalRemote = {
retain: vi.fn<TerminalRemote['retain']>(streamMethod<TerminalRemote['retain']>(async function* (_session, _id, signal) {
yield { type: 'retained' }
@@ -43,11 +51,7 @@ function fixture(prepareStream?: <Item>(stream: RemoteStream<Item>) => void) {
environment: vi.fn<TerminalRemote['environment']>(async () => success(environment)), list: vi.fn<TerminalRemote['list']>(async () => success([])),
create: vi.fn<TerminalRemote['create']>(async (_sessionId, request) => success({ ...info, id: request.id })),
close: vi.fn<TerminalRemote['close']>(async () => success(undefined)), rename: vi.fn<TerminalRemote['rename']>(async () => success(undefined)),
write: vi.fn<TerminalRemote['write']>(async () => success(undefined)), resize: vi.fn<TerminalRemote['resize']>(async () => success(undefined)),
follow: vi.fn<TerminalRemote['follow']>(streamMethod<TerminalRemote['follow']>(async function* (_sessionId, id, attachmentId, signal) {
yield { type: 'snapshot', sequence: 0, screen: 'ready', info: { ...info, id, controllerId: attachmentId } }
await untilAborted(signal)
})),
attach: mock.remote.terminal.attach,
}
const options: RemoteStreamOptions<unknown>[] = []
const streams: { dispose(): Promise<void>; restart(): void }[] = []
@@ -64,7 +68,7 @@ function fixture(prepareStream?: <Item>(stream: RemoteStream<Item>) => void) {
cleanups.push(async () => { await Promise.all(streams.map(stream => stream.dispose())) })
const model = new TerminalView(sessionId, remote, gateway, info.id)
cleanups.push(() => model.dispose())
return { model, remote, gateway, options, streams, generation }
return { model, remote, gateway, options, streams, generation, attachments, sent }
}
async function mount(model: TerminalView) {
@@ -84,29 +88,11 @@ async function connected(model: TerminalView): Promise<void> {
acknowledge(model)
}
it('does not let a late input failure downgrade a newer connection', async () => {
const { model, remote } = fixture()
await mount(model)
await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
acknowledge(model)
const input = Promise.withResolvers<RemoteResult<void>>()
vi.mocked(remote.write).mockReturnValueOnce(input.promise)
model.write('x')
await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(1)
model.connect()
await expect.poll(() => vi.mocked(remote.follow).mock.calls.length).toBe(2)
await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
model.write('current input')
input.reject(new Error('old attachment was replaced'))
await expect.poll(() => vi.mocked(remote.write).mock.calls.some(call => call[3] === 'current input')).toBe(true)
expect(model.state.getSnapshot()).toMatchObject({ phase: 'connected', writable: true, error: undefined })
})
it('waits for render acknowledgement before publishing subsequent output', async () => {
const { model, remote } = fixture()
vi.mocked(remote.follow).mockImplementation(streamMethod<TerminalRemote['follow']>(async function* (_sessionId, id, controllerId, signal) {
vi.mocked(remote.attach).mockImplementation(streamMethod<TerminalRemote['attach']>(async function* (_sessionId, id, signal) {
const frames: TerminalFrame[] = [
{ type: 'snapshot', sequence: 0, screen: '', info: { ...info, id, controllerId } },
{ type: 'snapshot', writable: true, sequence: 0, screen: '', info: { ...info, id } },
{ type: 'output', sequence: 1, data: 'first' },
{ type: 'output', sequence: 2, data: 'second' },
]
@@ -121,77 +107,6 @@ it('waits for render acknowledgement before publishing subsequent output', async
await expect.poll(() => model.state.getSnapshot().render?.frame).toMatchObject({ type: 'output', sequence: 2 })
})
it('serializes input and resizes, clamps geometry, and suppresses unchanged sizes', async () => {
const { model, remote } = fixture()
await connected(model)
const input = Promise.withResolvers<RemoteResult<void>>()
vi.mocked(remote.write).mockReturnValueOnce(input.promise)
model.resize(80, 24)
model.write('first')
model.write('second')
model.resize(500, 300)
await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(1)
expect(remote.resize).not.toHaveBeenCalled()
input.resolve(success(undefined))
await expect.poll(() => vi.mocked(remote.resize).mock.calls.length).toBe(1)
const attachmentId = vi.mocked(remote.follow).mock.calls[0]![2]
const id = model.state.getSnapshot().info!.id
expect(vi.mocked(remote.write).mock.calls.map(call => call[3])).toEqual(['first', 'second'])
expect(remote.resize).toHaveBeenCalledWith(sessionId, id, attachmentId, 200, 100)
model.resize(90, 24)
await expect.poll(() => vi.mocked(remote.resize).mock.calls.length).toBe(2)
})
it('bounds queued input by UTF-8 bytes and releases the byte budget after settlement', async () => {
const { model, remote } = fixture()
vi.mocked(remote.environment).mockResolvedValue(success({ ...environment, maxInputBytes: 6 }))
await connected(model)
const input = Promise.withResolvers<RemoteResult<void>>()
vi.mocked(remote.write).mockReturnValueOnce(input.promise)
model.write('界界')
await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(1)
model.write('a')
expect(model.state.getSnapshot()).toMatchObject({ phase: 'failed', issue: 'inputFull' })
input.resolve(success(undefined))
model.connect()
await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
model.write('界界')
await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(2)
expect(vi.mocked(remote.write).mock.calls.map(call => call[3])).toEqual(['界界', '界界'])
})
it('drops queued commands from a detached attachment and ignores its late resize failure', async () => {
const { model, remote } = fixture()
await connected(model)
const input = Promise.withResolvers<RemoteResult<void>>()
vi.mocked(remote.resize).mockReturnValueOnce(input.promise)
model.resize(100, 30)
await expect.poll(() => vi.mocked(remote.resize).mock.calls.length).toBe(1)
model.write('stale')
model.resize(110, 35)
model.connect()
await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
model.write('current')
input.resolve(failure('old attachment'))
await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(1)
expect(vi.mocked(remote.write).mock.calls[0]?.[3]).toBe('current')
expect(remote.resize).toHaveBeenCalledOnce()
expect(model.state.getSnapshot().phase).toBe('connected')
})
it('publishes current input and resize failures and can reconnect for another attempt', async () => {
const { model, remote } = fixture()
await connected(model)
vi.mocked(remote.write).mockResolvedValueOnce(failure('input refused'))
model.write('x')
await expect.poll(() => model.state.getSnapshot().error).toBe('input refused')
model.connect()
await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
vi.mocked(remote.resize).mockResolvedValueOnce(failure('resize refused'))
model.resize(100, 30)
await expect.poll(() => model.state.getSnapshot().error).toBe('resize refused')
})
it('treats carrier loss as disconnected only for the active attachment', async () => {
const { model, options } = fixture()
await connected(model)
@@ -206,11 +121,11 @@ it('treats carrier loss as disconnected only for the active attachment', async (
it.each([
['output before snapshot', [{ type: 'output', sequence: 1, data: 'orphan' }], 'missing its screen snapshot'],
['sequence gap', [{ type: 'snapshot', sequence: 4, screen: '', info }, { type: 'output', sequence: 6, data: 'gap' }], 'sequence has a gap'],
['repeated snapshot', [{ type: 'snapshot', sequence: 4, screen: '', info }, { type: 'snapshot', sequence: 4, screen: '', info }], 'Unexpected terminal screen snapshot'],
['sequence gap', [{ type: 'snapshot', writable: true, sequence: 4, screen: '', info }, { type: 'output', sequence: 6, data: 'gap' }], 'sequence has a gap'],
['repeated snapshot', [{ type: 'snapshot', writable: true, sequence: 4, screen: '', info }, { type: 'snapshot', writable: true, sequence: 4, screen: '', info }], 'Unexpected terminal screen snapshot'],
] satisfies readonly (readonly [string, readonly TerminalFrame[], string])[])('refuses a malformed output stream: %s', async (_name, frames, message) => {
const { model, remote } = fixture()
vi.mocked(remote.follow).mockImplementation(streamMethod<TerminalRemote['follow']>(async function* () { yield* frames }))
vi.mocked(remote.attach).mockImplementation(streamMethod<TerminalRemote['attach']>(async function* () { yield* frames }))
await mount(model)
if (frames[0]?.type === 'snapshot') {
await expect.poll(() => model.state.getSnapshot().render).toBeDefined()
@@ -222,9 +137,9 @@ it.each([
it('retains an exited screen and closes controls when its stream ends', async () => {
const { model, remote } = fixture()
vi.mocked(remote.follow).mockImplementation(streamMethod<TerminalRemote['follow']>(async function* (_sessionId, id, controllerId) {
yield { type: 'snapshot', sequence: 0, screen: 'last screen', info: { ...info, id, controllerId } }
yield { type: 'state', info: { ...info, id, controllerId, state: 'exited', exitCode: 3 } }
vi.mocked(remote.attach).mockImplementation(streamMethod<TerminalRemote['attach']>(async function* (_sessionId, id) {
yield { type: 'snapshot', writable: true, sequence: 0, screen: 'last screen', info: { ...info, id } }
yield { type: 'state', writable: true, info: { ...info, id, state: 'exited', exitCode: 3 } }
}))
await connected(model)
await expect.poll(() => model.state.getSnapshot().phase).toBe('closed')
@@ -233,8 +148,8 @@ it('retains an exited screen and closes controls when its stream ends', async ()
it('reports an attachment ending while the shell is still running and permits manual reconnect', async () => {
const { model, remote } = fixture()
vi.mocked(remote.follow).mockImplementationOnce(streamMethod<TerminalRemote['follow']>(async function* (_sessionId, id, controllerId) {
yield { type: 'snapshot', sequence: 0, screen: '', info: { ...info, id, controllerId } }
vi.mocked(remote.attach).mockImplementationOnce(streamMethod<TerminalRemote['attach']>(async function* (_sessionId, id) {
yield { type: 'snapshot', writable: true, sequence: 0, screen: '', info: { ...info, id } }
}))
await connected(model)
await expect.poll(() => model.state.getSnapshot().issue).toBe('attachmentEnded')
@@ -244,14 +159,14 @@ it('reports an attachment ending while the shell is still running and permits ma
it('publishes remote control transfer without replacing the retained screen', async () => {
const { model, remote } = fixture()
vi.mocked(remote.follow).mockImplementation(streamMethod<TerminalRemote['follow']>(async function* (_sessionId, id, controllerId, signal) {
yield { type: 'snapshot', sequence: 0, screen: 'retained', info: { ...info, id, controllerId } }
yield { type: 'state', info: { ...info, id } }
vi.mocked(remote.attach).mockImplementation(streamMethod<TerminalRemote['attach']>(async function* (_sessionId, id, signal) {
yield { type: 'snapshot', writable: true, sequence: 0, screen: 'retained', info: { ...info, id } }
yield { type: 'state', writable: false, info: { ...info, id } }
await untilAborted(signal)
}))
await connected(model)
await expect.poll(() => model.state.getSnapshot().writable).toBe(false)
expect(model.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', screen: 'retained' })
expect(model.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', writable: true, screen: 'retained' })
})
/** Pause delivery after the real Gateway iterator settles, before the model observes it. */
@@ -293,13 +208,13 @@ it('ignores an already delivered screen when its attachment is replaced before t
barrier.release()
await model.rename('settled')
expect(model.state.getSnapshot().render).toBe(current.render)
expect(remote.follow).toHaveBeenCalledTimes(2)
expect(remote.attach).toHaveBeenCalledTimes(2)
})
it('ignores an already settled stream error after a newer attachment has become writable', async () => {
const barrier = deliveryBarrier()
const { model, remote } = fixture(barrier.prepare)
vi.mocked(remote.follow).mockImplementationOnce(streamMethod<TerminalRemote['follow']>(async function* () {
vi.mocked(remote.attach).mockImplementationOnce(streamMethod<TerminalRemote['attach']>(async function* () {
yield* []
throw new Error('retired attachment failed')
}))
@@ -319,7 +234,7 @@ it('releases a pending screen render on carrier generation cancellation and acce
const revision = model.state.getSnapshot().render!.revision
streams[0]!.restart()
await expect.poll(() => model.state.getSnapshot().render?.revision).toBe(revision + 1)
expect(remote.follow).toHaveBeenCalledTimes(2)
expect(remote.attach).toHaveBeenCalledTimes(2)
expect(model.state.getSnapshot().writable).toBe(true)
})
@@ -331,96 +246,10 @@ it('does not wait for the DOM callback of a screen whose generation was already
streams[0]!.restart()
barrier.release()
await expect.poll(() => model.state.getSnapshot().render?.revision).toBe(2)
expect(remote.follow).toHaveBeenCalledTimes(2)
expect(remote.attach).toHaveBeenCalledTimes(2)
expect(model.state.getSnapshot().writable).toBe(true)
})
it.each(['write', 'resize'] as const)('keeps a fresh attachment writable when a pending %s fails after automatic transport recovery', async (operation) => {
const { model, remote, generation } = fixture()
generation.set({ id: 1, host: { home: '/home/fixture' } })
const disconnected = Promise.withResolvers<undefined>()
vi.mocked(remote.follow).mockImplementationOnce(streamMethod<TerminalRemote['follow']>(async function* (_sessionId, id, controllerId, signal) {
yield { type: 'snapshot', sequence: 0, screen: 'before disconnect', info: { ...info, id, controllerId } }
await Promise.race([disconnected.promise, untilAborted(signal)])
if (signal?.aborted) return
throw new RemoteStreamCarrierError('connection lost')
}))
await connected(model)
const pending = Promise.withResolvers<RemoteResult<void>>()
if (operation === 'write') {
vi.mocked(remote.write).mockReturnValueOnce(pending.promise)
model.write('old input')
} else {
vi.mocked(remote.resize).mockReturnValueOnce(pending.promise)
model.resize(100, 30)
}
await expect.poll(() => vi.mocked(remote[operation]).mock.calls.length).toBe(1)
const oldAttachmentId = vi.mocked(remote.follow).mock.calls[0]![2]
generation.set(undefined)
disconnected.resolve(undefined)
await expect.poll(() => model.state.getSnapshot().phase).toBe('disconnected')
expect(model.state.getSnapshot().writable).toBe(false)
expect(remote.follow).toHaveBeenCalledOnce()
generation.set({ id: 2, host: { home: '/home/fixture' } })
await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
expect(remote.follow).toHaveBeenCalledTimes(2)
const attachmentId = vi.mocked(remote.follow).mock.calls[1]![2]
expect(attachmentId).not.toBe(oldAttachmentId)
expect(model.state.getSnapshot().info?.controllerId).toBe(attachmentId)
expect(model.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', screen: 'ready' })
model.write('fresh input')
pending.reject(new Error('old attachment was replaced'))
await expect.poll(() => vi.mocked(remote.write).mock.calls.some(call => call[3] === 'fresh input')).toBe(true)
expect(model.state.getSnapshot()).toMatchObject({ phase: 'connected', writable: true, error: undefined })
expect(vi.mocked(remote.write).mock.calls.at(-1)?.[2]).toBe(attachmentId)
expect(remote.create).toHaveBeenCalledOnce()
expect(remote.close).not.toHaveBeenCalled()
})
it('ignores controls before discovery and reconnects an existing process after remount', async () => {
const { model, remote } = fixture()
model.connect()
model.write('early')
model.resize(100, 30)
model.acknowledge(100)
expect(remote.follow).not.toHaveBeenCalled()
expect(remote.write).not.toHaveBeenCalled()
expect(remote.resize).not.toHaveBeenCalled()
const unmount = await mount(model)
await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
unmount()
model.connect()
model.write('detached')
model.resize(100, 30)
expect(remote.follow).toHaveBeenCalledOnce()
expect(remote.write).not.toHaveBeenCalled()
expect(remote.resize).not.toHaveBeenCalled()
model.mount()
await expect.poll(() => remote.follow).toHaveBeenCalledTimes(2)
await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
expect(remote.create).toHaveBeenCalledOnce()
})
it('keeps controls inert when process metadata or the attachment is unavailable', async () => {
const { model, remote } = fixture()
await connected(model)
const state = model.state.getSnapshot()
model.state.set({ ...state, info: undefined })
model.write('missing metadata')
model.resize(100, 30)
expect(remote.write).not.toHaveBeenCalled()
expect(remote.resize).not.toHaveBeenCalled()
model.state.set({ ...state, environment: undefined })
model.resize(100, 30)
await expect.poll(() => remote.resize).toHaveBeenCalledOnce()
expect(vi.mocked(remote.resize).mock.calls[0]?.slice(-2)).toEqual([100, 30])
model.write('unknown budget')
expect(model.state.getSnapshot().issue).toBe('inputFull')
expect(remote.write).not.toHaveBeenCalled()
})
it('renames an existing terminal, skips unchanged names, and exposes rename failures', async () => {
const { model, remote } = fixture()
await connected(model)
@@ -462,7 +291,7 @@ it('retains state when disposal overtakes successful allocation or a failed disc
else discovery.reject(new Error('late discovery failure'))
await loading
expect(model.state.getSnapshot()).toBe(before)
expect(remote.follow).not.toHaveBeenCalled()
expect(remote.attach).not.toHaveBeenCalled()
}
})
@@ -487,7 +316,7 @@ it('allows retry after failed process cleanup and never reconnects while close i
const first = model.close()
expect(model.close()).toBe(first)
model.connect()
expect(remote.follow).toHaveBeenCalledOnce()
expect(remote.attach).toHaveBeenCalledOnce()
closing.resolve(failure('close refused'))
await expect(first).rejects.toThrow('close refused')
expect(model.state.getSnapshot()).toMatchObject({ phase: 'failed', error: 'close refused' })
@@ -509,55 +338,7 @@ it('does not publish a close result or reconnect after disposal', async () => {
model.mount()
model.connect()
expect(model.state.getSnapshot()).toBe(before)
expect(remote.follow).toHaveBeenCalledOnce()
})
it.each(['write', 'resize'] as const)('keeps the output connection when %s loses control before its state frame arrives', async (operation) => {
const { model, remote } = fixture()
const transfer = Promise.withResolvers<undefined>()
const response = Promise.withResolvers<RemoteResult<void>>()
cleanups.push(() => { transfer.resolve(undefined); response.resolve(success(undefined)) })
vi.mocked(remote.follow).mockImplementation(streamMethod<TerminalRemote['follow']>(async function* (_session, id, controllerId, signal) {
yield { type: 'snapshot', sequence: 0, screen: 'retained screen', info: { ...info, id, controllerId } }
await transfer.promise
yield { type: 'state', info: { ...info, id } }
await untilAborted(signal)
}))
await connected(model)
vi.mocked(remote[operation]).mockReturnValueOnce(response.promise)
if (operation === 'write') model.write('before transfer')
else model.resize(100, 30)
model.write('queued before transfer')
await expect.poll(() => vi.mocked(remote[operation]).mock.calls.length).toBe(1)
response.resolve({ ok: false, error: new RemoteError('terminal/control-unavailable', 'Another window owns input', { reason: 'read-only' }) })
await expect.poll(() => model.state.getSnapshot().writable).toBe(false)
expect(model.state.getSnapshot()).toMatchObject({ phase: 'connected', error: undefined, issue: undefined, render: { frame: { screen: 'retained screen' } } })
transfer.resolve(undefined)
await expect.poll(() => model.state.getSnapshot().info?.controllerId).toBeUndefined()
expect(remote.follow).toHaveBeenCalledOnce()
expect(vi.mocked(remote.write).mock.calls.some(call => call[3] === 'queued before transfer')).toBe(false)
})
it('keeps an exited screen when a pending input is refused after the exit state arrives', async () => {
const { model, remote } = fixture()
const exit = Promise.withResolvers<undefined>()
const response = Promise.withResolvers<RemoteResult<void>>()
cleanups.push(() => { exit.resolve(undefined); response.resolve(success(undefined)) })
vi.mocked(remote.follow).mockImplementation(streamMethod<TerminalRemote['follow']>(async function* (_session, id, controllerId, signal) {
yield { type: 'snapshot', sequence: 0, screen: 'final screen', info: { ...info, id, controllerId } }
await exit.promise
yield { type: 'state', info: { ...info, id, state: 'exited', exitCode: 0 } }
await untilAborted(signal)
}))
await connected(model)
vi.mocked(remote.write).mockReturnValueOnce(response.promise)
model.write('exit race')
await expect.poll(() => vi.mocked(remote.write).mock.calls.length).toBe(1)
exit.resolve(undefined)
await expect.poll(() => model.state.getSnapshot().info?.state).toBe('exited')
response.resolve({ ok: false, error: new RemoteError('terminal/control-unavailable', 'Terminal is not running', { reason: 'not-running' }) })
await setImmediate()
expect(model.state.getSnapshot()).toMatchObject({ phase: 'connected', writable: false, error: undefined, issue: undefined, render: { frame: { screen: 'final screen' } } })
expect(remote.attach).toHaveBeenCalledOnce()
})
it('exposes a localized quota error and clears it after a successful retry', async () => {
@@ -568,3 +349,119 @@ it('exposes a localized quota error and clears it after a successful retry', asy
await connected(model)
expect(model.state.getSnapshot()).toMatchObject({ phase: 'connected', issue: undefined, error: undefined })
})
it('sends input and clamped resize in order without waiting for acknowledgements', async () => {
const h = fixture()
await connected(h.model)
h.model.resize(80, 24)
h.model.write('first')
h.model.write('second')
h.model.resize(500, 300)
await expect.poll(() => h.sent[0]?.length).toBe(3)
expect(h.sent[0]).toEqual([
{ type: 'write', sequence: 1, data: 'first' },
{ type: 'write', sequence: 2, data: 'second' },
{ type: 'resize', sequence: 3, cols: 200, rows: 100 },
])
})
it('releases the UTF-8 input budget only on acknowledgement', async () => {
const h = fixture()
vi.mocked(h.remote.environment).mockResolvedValue(success({ ...environment, maxInputBytes: 6 }))
await connected(h.model)
h.model.write('界界')
await expect.poll(() => h.sent[0]?.length).toBe(1)
h.attachments[0]!.push({ type: 'ack', sequence: 1 })
h.attachments[0]!.push({ type: 'state', info: { ...info, cols: 90 }, writable: true })
await expect.poll(() => h.model.state.getSnapshot().info?.cols).toBe(90)
h.model.write('界界')
await expect.poll(() => h.sent[0]?.length).toBe(2)
h.model.write('a')
expect(h.model.state.getSnapshot()).toMatchObject({ phase: 'failed', issue: 'inputFull' })
})
it('keeps output attached after an input refusal and stops further input', async () => {
const h = fixture()
await connected(h.model)
h.model.write('before transfer')
h.attachments[0]!.push({ type: 'ack', sequence: 1, refusal: 'read-only' })
await expect.poll(() => h.model.state.getSnapshot().writable).toBe(false)
h.model.write('refused')
h.model.resize(100, 30)
h.attachments[0]!.push({ type: 'output', sequence: 1, data: 'still following' })
await expect.poll(() => h.model.state.getSnapshot().render?.frame).toMatchObject({ data: 'still following' })
expect(h.model.state.getSnapshot()).toMatchObject({ phase: 'connected', error: undefined })
expect(h.remote.attach).toHaveBeenCalledOnce()
expect(h.sent[0]).toHaveLength(1)
})
it('discards the old generation budget and never replays unacknowledged input after reconnect', async () => {
const h = fixture()
h.generation.set({ id: 1, host: { home: '/home/fixture' } })
await connected(h.model)
h.model.write('unconfirmed')
await expect.poll(() => h.sent[0]?.length).toBe(1)
h.generation.set(undefined)
h.attachments[0]!.fail(new RemoteStreamCarrierError('connection lost'))
await expect.poll(() => h.model.state.getSnapshot().phase).toBe('disconnected')
h.model.write('offline')
h.generation.set({ id: 2, host: { home: '/home/fixture' } })
await expect.poll(() => h.attachments.length).toBe(2)
await expect.poll(() => h.model.state.getSnapshot().writable).toBe(true)
acknowledge(h.model)
h.model.write('fresh')
await expect.poll(() => h.sent[1]?.length).toBe(1)
expect(h.sent[1]).toEqual([{ type: 'write', sequence: 1, data: 'fresh' }])
h.attachments[0]!.push({ type: 'ack', sequence: 1, refusal: 'read-only' })
expect(h.model.state.getSnapshot().writable).toBe(true)
expect(h.remote.create).toHaveBeenCalledOnce()
})
it('ignores controls before mount and after detach, then reuses the process on remount', async () => {
const h = fixture()
h.model.write('early')
h.model.resize(100, 30)
const unmount = await mount(h.model)
await expect.poll(() => h.model.state.getSnapshot().writable).toBe(true)
unmount()
h.model.write('detached')
h.model.resize(100, 30)
expect(h.sent[0]).toEqual([])
h.model.mount()
await expect.poll(() => h.remote.attach).toHaveBeenCalledTimes(2)
expect(h.remote.create).toHaveBeenCalledOnce()
})
it('rejects an out-of-order acknowledgement and reports synchronous send failures', async () => {
const h = fixture()
await connected(h.model)
h.model.write('input')
h.attachments[0]!.push({ type: 'ack', sequence: 2 })
await expect.poll(() => h.model.state.getSnapshot().issue).toBe('invalidOutput')
h.model.connect()
await expect.poll(() => h.model.state.getSnapshot().writable).toBe(true)
const handle = vi.mocked(h.remote.attach).mock.results.at(-1)!.value as ReturnType<TerminalRemote['attach']>
vi.spyOn(handle, 'send').mockImplementation(() => { throw new Error('send failed') })
h.model.write('next')
expect(h.model.state.getSnapshot()).toMatchObject({ phase: 'failed', error: 'send failed' })
})
it('ignores empty input and stale render acknowledgements and handles missing view metadata', async () => {
const h = fixture()
await connected(h.model)
h.model.acknowledge(-1)
h.model.write('')
const state = h.model.state.getSnapshot()
h.model.state.set({ ...state, info: undefined })
h.model.write('missing')
h.model.resize(100, 30)
expect(h.sent[0]).toEqual([])
h.model.state.set({ ...state, environment: undefined })
h.model.resize(100, 30)
await expect.poll(() => h.sent[0]?.length).toBe(1)
h.attachments[0]!.push({ type: 'ack', sequence: 1 })
h.attachments[0]!.push({ type: 'state', info: { ...info, cols: 100 }, writable: true })
await expect.poll(() => h.model.state.getSnapshot().info?.cols).toBe(100)
h.model.write('no budget')
expect(h.model.state.getSnapshot().issue).toBe('inputFull')
})
@@ -41,9 +41,8 @@ function fixture() {
environment: vi.fn<TerminalRemote['environment']>(async () => success(environment)), list: vi.fn<TerminalRemote['list']>(async () => success([])),
create: vi.fn<TerminalRemote['create']>(async (_session, request) => success({ ...info, id: request.id })),
close: vi.fn<TerminalRemote['close']>(async () => success(undefined)), rename: vi.fn<TerminalRemote['rename']>(async () => success(undefined)),
write: vi.fn<TerminalRemote['write']>(async () => success(undefined)), resize: vi.fn<TerminalRemote['resize']>(async () => success(undefined)),
follow: vi.fn<TerminalRemote['follow']>(streamMethod<TerminalRemote['follow']>(async function* (_session, id, controllerId, signal) {
yield { type: 'snapshot', sequence: 0, screen: 'retained', info: { ...info, id, controllerId } }
attach: vi.fn<TerminalRemote['attach']>(streamMethod<TerminalRemote['attach']>(async function* (_session, id, signal) {
yield { type: 'snapshot', writable: true, sequence: 0, screen: 'retained', info: { ...info, id } }
await new Promise<void>((resolve) => {
if (signal?.aborted) resolve()
else signal?.addEventListener('abort', () => { resolve() }, { once: true })
@@ -93,8 +92,8 @@ it('recovers a listed process without creating another, including its title and
model.mount()
await model.refresh()
expect(h.remote.create).not.toHaveBeenCalled()
await expect.poll(() => model.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', screen: 'retained' })
expect(h.remote.follow).toHaveBeenCalledWith(sessionId, info.id, expect.any(String), expect.any(AbortSignal))
await expect.poll(() => model.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', writable: true, screen: 'retained' })
expect(h.remote.attach).toHaveBeenCalledWith(sessionId, info.id, expect.any(AbortSignal))
})
it('does not recreate a recovered terminal that disappeared after the recovery list was shown', async () => {
@@ -140,7 +139,7 @@ it('waits for an in-flight creation while close detaches immediately and prevent
await starting
await closing
expect(h.remote.close).toHaveBeenCalledWith(sessionId, info.id)
expect(h.remote.follow).not.toHaveBeenCalled()
expect(h.remote.attach).not.toHaveBeenCalled()
})
it('does not allocate after close or disposal overtakes discovery', async () => {
@@ -361,7 +360,7 @@ it('restores the same terminal in the same occurrence after reload without openi
await restored.refresh()
expect(restored.id).toBe(original.id)
expect(h.remote.create).toHaveBeenCalledOnce()
await expect.poll(() => restored.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', screen: 'retained' })
await expect.poll(() => restored.state.getSnapshot().render?.frame).toMatchObject({ type: 'snapshot', writable: true, screen: 'retained' })
})
it('offers retained processes when their saved occurrence is absent from the restored layout', async () => {
@@ -490,10 +489,10 @@ it('waits for both active and detached stream finalizers during plugin disposal
const finished = [Promise.withResolvers<undefined>(), Promise.withResolvers<undefined>()]
cleanups.push(() => { for (const barrier of release) barrier.resolve(undefined) })
let index = 0
vi.mocked(h.remote.follow).mockImplementation(streamMethod<TerminalRemote['follow']>(async function* (_session, id, controllerId, signal) {
vi.mocked(h.remote.attach).mockImplementation(streamMethod<TerminalRemote['attach']>(async function* (_session, id, signal) {
const current = index++
try {
yield { type: 'snapshot', sequence: 0, screen: 'screen', info: { ...info, id, controllerId } }
yield { type: 'snapshot', writable: true, sequence: 0, screen: 'screen', info: { ...info, id } }
await new Promise<void>((resolve) => {
if (signal?.aborted) resolve()
else signal?.addEventListener('abort', () => { resolve() }, { once: true })
@@ -611,7 +610,7 @@ it('retains only open saved occurrences across inactive Sessions and deduplicate
expect(h.remote.environment).not.toHaveBeenCalled()
expect(h.remote.create).not.toHaveBeenCalled()
expect(h.remote.list).not.toHaveBeenCalled()
expect(h.remote.follow).not.toHaveBeenCalled()
expect(h.remote.attach).not.toHaveBeenCalled()
const calls = vi.mocked(h.remote.retain).mock.calls
service.retainTabs([{ sessionId: otherSession, tabId: 'b', contentId: 'b' }])
await expect.poll(() => calls.find(call => call[0] === sessionId)?.[2]?.aborted).toBe(true)
@@ -639,7 +638,7 @@ it('waits for the window hold acknowledgement before restoring an output attachm
const model = service.view(sessionId, 'restored', 'restored')
model.mount()
await model.refresh()
expect(h.remote.follow).not.toHaveBeenCalled()
expect(h.remote.attach).not.toHaveBeenCalled()
acknowledge.resolve(undefined)
await expect.poll(() => model.state.getSnapshot().writable).toBe(true)
expect(h.remote.retain).toHaveBeenCalledOnce()
@@ -657,7 +656,7 @@ it('shows a missing terminal when retention loses the race to Host cleanup, with
const model = service.view(sessionId, 'restored', 'restored')
model.mount()
await expect.poll(() => model.state.getSnapshot().issue).toBe('missingTerminal')
expect(h.remote.follow).not.toHaveBeenCalled()
expect(h.remote.attach).not.toHaveBeenCalled()
expect(h.remote.create).not.toHaveBeenCalled()
})
@@ -78,3 +78,10 @@ describe('TerminalFollower', () => {
expect(await follower.read(signal())[Symbol.asyncIterator]().next()).toEqual({ done: true, value: undefined })
})
})
it('does not replace an ended attachment with a late input failure', async () => {
const follower = new TerminalFollower(1000)
follower.close()
follower.fail(new Error('late write failed'))
expect(await follower.read(signal())[Symbol.asyncIterator]().next()).toEqual({ done: true, value: undefined })
})
@@ -3,11 +3,11 @@ import { PassThrough } from 'node:stream'
import { afterEach, describe, expect, it, vi } from 'vitest'
import type { SubprocessOutcome, SubprocessTerminalHandle } from '@deepseek-ai/dsh-subprocess'
import { BrowserTerminal } from '../src/terminal.ts'
import { inputChannel } from './input.ts'
import { TerminalFollower } from '../src/stream.ts'
import type { TerminalAttachmentId, TerminalFrame, WebTerminalId, WebTerminalInfo } from '../src/types.ts'
import type { TerminalInput, TerminalFrame, WebTerminalId, WebTerminalInfo } from '../src/types.ts'
const info: WebTerminalInfo = { id: 'terminal-test' as WebTerminalId, title: 'bash', shell: { path: '/bin/bash', name: 'bash', args: ['-i'] }, cwd: '/workspace', cols: 80, rows: 24, state: 'running', exitCode: null }
const attachment = (id: string): TerminalAttachmentId => id as TerminalAttachmentId
const cleanups: (() => Promise<void>)[] = []
afterEach(async () => { await Promise.all(cleanups.splice(0).map(close => close())) })
@@ -26,12 +26,14 @@ function fixture() {
return { terminal, output, outcome, handle }
}
async function attach(terminal: BrowserTerminal, id = 'first') {
async function attach(terminal: BrowserTerminal) {
const controller = new AbortController()
const iterator = terminal.follow(attachment(id), controller.signal)[Symbol.asyncIterator]()
const input = inputChannel<TerminalInput>()
const frames = terminal.attach(input.source, { maxInputBytes: 1000, maxCols: 200, maxRows: 100 }, controller.signal)
const iterator = frames[Symbol.asyncIterator]()
const baseline = await readFrame(iterator)
cleanups.push(async () => { controller.abort(); await iterator.return?.() })
return { controller, iterator, baseline }
return { controller, iterator, baseline, input }
}
describe('BrowserTerminal', () => {
@@ -46,7 +48,7 @@ describe('BrowserTerminal', () => {
expect(handle.terminate).not.toHaveBeenCalled()
output.write(Buffer.from('world'))
await expect.poll(() => terminal.info.state).toBe('running')
const second = await attach(terminal, 'second')
const second = await attach(terminal)
// The baseline and its output queue share the same ordered screen write queue.
const frames = [second.baseline]
if (second.baseline.type === 'snapshot' && !second.baseline.screen.includes('world')) frames.push(await readFrame(second.iterator))
@@ -55,25 +57,7 @@ describe('BrowserTerminal', () => {
expect(handle.terminate).not.toHaveBeenCalled()
})
it('preserves split UTF-8, gives the newest attachment input, and resizes both PTY and recovery screen', async () => {
const { terminal, output, handle } = fixture()
const first = await attach(terminal)
const encoded = Buffer.from('终端')
output.write(encoded.subarray(0, 2))
await expect.poll(() => output.readableLength).toBe(0)
output.write(encoded.subarray(2))
expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', data: '终端' })
const second = await attach(terminal, 'second')
await expect(terminal.write(attachment('first'), 'ignored')).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'read-only' } })
await terminal.write(attachment('second'), '\t')
expect(handle.write).toHaveBeenCalledWith('\t')
await terminal.resize(attachment('second'), 100, 30)
expect(handle.resize).toHaveBeenCalledWith(100, 30)
expect(terminal.info).toMatchObject({ cols: 100, rows: 30 })
second.controller.abort()
await second.iterator.return?.()
expect(terminal.info.controllerId).toBeUndefined()
})
it('keeps exit facts and screen until explicit cleanup and never starts a replacement process', async () => {
const { terminal, output, outcome, handle } = fixture()
@@ -83,7 +67,7 @@ describe('BrowserTerminal', () => {
expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', data: 'done' })
expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', info: { state: 'exited', exitCode: 7 } })
expect(handle.terminate).not.toHaveBeenCalled()
const second = await attach(terminal, 'second')
const second = await attach(terminal)
expect(second.baseline).toMatchObject({ type: 'snapshot', info: { state: 'exited', exitCode: 7 } })
await terminal.close()
expect(handle.terminate).toHaveBeenCalledOnce()
@@ -102,71 +86,13 @@ describe('BrowserTerminal', () => {
expect((await first.iterator.next()).done).toBe(true)
})
it('rejects input before attachment, during close and after process exit', async () => {
const { terminal, handle, output, outcome } = fixture()
await expect(terminal.write(attachment('first'), 'ignored')).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'read-only' } })
const first = await attach(terminal)
output.end()
outcome.resolve({ exitCode: 0, signal: null })
expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', info: { state: 'exited' } })
await expect(terminal.write(attachment('first'), 'ignored')).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'not-running' } })
await expect(terminal.resize(attachment('first'), 100, 30)).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'not-running' } })
const closing = terminal.close()
await expect(terminal.write(attachment('first'), 'ignored')).rejects.toMatchObject({ code: 'terminal/control-unavailable', details: { reason: 'not-running' } })
await closing
expect(handle.write).not.toHaveBeenCalled()
expect(handle.resize).not.toHaveBeenCalled()
})
it('preserves the input controller when an older follower detaches', async () => {
const { terminal, handle } = fixture()
const first = await attach(terminal)
const second = await attach(terminal, 'second')
first.controller.abort()
await first.iterator.return?.()
expect(terminal.info.controllerId).toBe(attachment('second'))
terminal.rename('build output')
expect(await readFrame(second.iterator)).toMatchObject({ type: 'state', info: { title: 'build output', controllerId: 'second' } })
await terminal.write(attachment('second'), 'pwd\r')
expect(handle.write).toHaveBeenCalledWith('pwd\r')
})
it('does not grant input to attachments cancelled before their snapshot is ready', async () => {
const { terminal, handle } = fixture()
const aborted = new AbortController()
aborted.abort(new Error('already detached'))
await expect(terminal.follow(attachment('cancelled'), aborted.signal)[Symbol.asyncIterator]().next()).rejects.toThrow('already detached')
await attach(terminal)
const writing = Promise.withResolvers<undefined>()
const written = Promise.withResolvers<undefined>()
handle.write.mockImplementationOnce(async () => { writing.resolve(undefined); await written.promise })
const pendingWrite = terminal.write(attachment('first'), 'pwd\r')
try {
await writing.promise
const abort = new AbortController()
const pendingAttachment = terminal.follow(attachment('late'), abort.signal)[Symbol.asyncIterator]().next()
const rejected = expect(pendingAttachment).rejects.toThrow('detached while waiting')
abort.abort(new Error('detached while waiting'))
written.resolve(undefined)
await pendingWrite
await rejected
expect(terminal.info.controllerId).toBe(attachment('first'))
} finally { written.resolve(undefined) }
})
it('continues accepting operations after a provider write or resize fails', async () => {
const { terminal, handle } = fixture()
await attach(terminal)
handle.write.mockRejectedValueOnce(new Error('input transport failed'))
handle.resize.mockRejectedValueOnce(new Error('resize transport failed'))
await expect(terminal.write(attachment('first'), 'failed')).rejects.toThrow('input transport failed')
await expect(terminal.resize(attachment('first'), 100, 30)).rejects.toThrow('resize transport failed')
expect(terminal.info).toMatchObject({ cols: 80, rows: 24 })
await terminal.write(attachment('first'), 'accepted')
await terminal.resize(attachment('first'), 90, 25)
expect(handle.write).toHaveBeenLastCalledWith('accepted')
expect(terminal.info).toMatchObject({ cols: 90, rows: 25 })
})
it.each([new Error('process wait failed'), 'remote process wait failed'])('publishes a failed process outcome and retains its recovery screen: %s', async (failure) => {
const { terminal, output, outcome } = fixture()
@@ -175,7 +101,7 @@ describe('BrowserTerminal', () => {
outcome.reject(failure)
expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', data: 'last output' })
expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', info: { state: 'failed', error: failure instanceof Error ? failure.message : failure } })
const second = await attach(terminal, 'second')
const second = await attach(terminal)
expect(second.baseline).toMatchObject({ type: 'snapshot', screen: 'last output', info: { state: 'failed' } })
})
@@ -205,12 +131,13 @@ describe('BrowserTerminal', () => {
it('shares concurrent close attempts and permits retry after termination fails', async () => {
const { terminal, handle } = fixture()
await attach(terminal)
const view = await attach(terminal)
handle.terminate.mockRejectedValueOnce(new Error('process range remains alive'))
const first = terminal.close()
expect(terminal.close()).toBe(first)
await expect(first).rejects.toThrow('remains alive')
await terminal.write(attachment('first'), 'retry cleanup next')
view.input.push({ type: 'write', sequence: 1, data: 'retry cleanup next' })
expect(await readFrame(view.iterator)).toMatchObject({ type: 'ack', sequence: 1 })
await terminal.close()
expect(handle.terminate).toHaveBeenCalledTimes(2)
})
@@ -234,3 +161,147 @@ it('refuses retention before allocation commit and disposes an uncommitted scree
await terminal.dispose()
expect(handle.terminate).toHaveBeenCalledOnce()
})
it('preserves split UTF-8 and gives input control only to the newest attachment', async () => {
const { terminal, output, handle } = fixture()
const first = await attach(terminal)
const encoded = Buffer.from('终端')
output.write(encoded.subarray(0, 2))
await expect.poll(() => output.readableLength).toBe(0)
output.write(encoded.subarray(2))
expect(await readFrame(first.iterator)).toMatchObject({ type: 'output', data: '终端' })
const second = await attach(terminal)
expect(second.baseline).toMatchObject({ writable: true })
expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', writable: false })
first.input.push({ type: 'write', sequence: 1, data: 'refused' })
expect(await readFrame(first.iterator)).toEqual({ type: 'ack', sequence: 1, refusal: 'read-only' })
second.input.push({ type: 'write', sequence: 1, data: '\t' })
expect(await readFrame(second.iterator)).toEqual({ type: 'ack', sequence: 1 })
expect(handle.write).toHaveBeenCalledExactlyOnceWith('\t')
first.controller.abort()
await first.iterator.return?.()
second.input.push({ type: 'resize', sequence: 2, cols: 100, rows: 30 })
expect(await readFrame(second.iterator)).toMatchObject({ type: 'state', writable: true, info: { cols: 100, rows: 30 } })
expect(await readFrame(second.iterator)).toEqual({ type: 'ack', sequence: 2 })
expect(handle.resize).toHaveBeenCalledWith(100, 30)
})
it('acknowledges provider acceptance in order and joins in-flight input on detach', async () => {
const { terminal, handle } = fixture()
const view = await attach(terminal)
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
handle.write.mockImplementationOnce(async () => { entered.resolve(undefined); await release.promise })
cleanups.push(async () => { release.resolve(undefined) })
view.input.push({ type: 'write', sequence: 1, data: 'accepted' })
view.input.push({ type: 'write', sequence: 2, data: 'cancelled' })
view.input.push({ type: 'resize', sequence: 3, cols: 100, rows: 30 })
await entered.promise
expect(handle.write).toHaveBeenCalledOnce()
expect(handle.resize).not.toHaveBeenCalled()
view.controller.abort()
let detached = false
const closing = view.iterator.return?.().then(() => { detached = true })
await Promise.resolve()
expect(detached).toBe(false)
release.resolve(undefined)
await closing
expect(handle.write).toHaveBeenCalledExactlyOnceWith('accepted')
expect(handle.resize).not.toHaveBeenCalled()
expect(handle.terminate).not.toHaveBeenCalled()
})
it('half-closes input while continuing to publish output and exit state', async () => {
const { terminal, output, outcome } = fixture()
const view = await attach(terminal)
view.input.push({ type: 'write', sequence: 1, data: 'exit\r' })
view.input.end()
expect(await readFrame(view.iterator)).toEqual({ type: 'ack', sequence: 1 })
output.end('last output')
outcome.resolve({ exitCode: 3, signal: null })
expect(await readFrame(view.iterator)).toMatchObject({ type: 'output', data: 'last output' })
expect(await readFrame(view.iterator)).toMatchObject({ type: 'state', writable: false, info: { exitCode: 3 } })
})
it.each([
{ type: 'write', sequence: 2, data: 'gap' },
{ type: 'write', sequence: 1, data: '界'.repeat(334) },
{ type: 'resize', sequence: 1, cols: 201, rows: 24 },
{ type: 'resize', sequence: 1, cols: 80, rows: 0 },
{ type: 'resize', sequence: 1, cols: 1.5, rows: 24 },
] satisfies TerminalInput[])('rejects invalid input before executing it: %j', async (command) => {
const { terminal, handle } = fixture()
const view = await attach(terminal)
view.input.push(command)
await expect(view.iterator.next()).rejects.toThrow()
expect(handle.write).not.toHaveBeenCalled()
expect(handle.resize).not.toHaveBeenCalled()
expect(handle.terminate).not.toHaveBeenCalled()
})
it.each(['write', 'resize'] as const)('fails the attachment on a provider %s error and permits fresh attachment recovery', async (operation) => {
const { terminal, handle } = fixture()
const first = await attach(terminal)
handle[operation].mockRejectedValueOnce(new Error('provider failed'))
first.input.push(operation === 'write' ? { type: 'write', sequence: 1, data: 'failed' } : { type: 'resize', sequence: 1, cols: 90, rows: 25 })
await expect(first.iterator.next()).rejects.toThrow('provider failed')
expect(terminal.info).toMatchObject({ cols: 80, rows: 24 })
const second = await attach(terminal)
second.input.push({ type: 'write', sequence: 1, data: 'fresh' })
expect(await readFrame(second.iterator)).toEqual({ type: 'ack', sequence: 1 })
expect(handle.write).toHaveBeenLastCalledWith('fresh')
})
it('refuses input after exit without ending the screen attachment', async () => {
const { terminal, output, outcome, handle } = fixture()
const view = await attach(terminal)
output.end()
outcome.resolve({ exitCode: 0, signal: null })
expect(await readFrame(view.iterator)).toMatchObject({ type: 'state', writable: false })
view.input.push({ type: 'write', sequence: 1, data: 'late' })
expect(await readFrame(view.iterator)).toEqual({ type: 'ack', sequence: 1, refusal: 'not-running' })
terminal.rename('finished')
expect(await readFrame(view.iterator)).toMatchObject({ type: 'state', info: { title: 'finished' } })
expect(handle.write).not.toHaveBeenCalled()
})
it('does not grant input to an attachment cancelled before its screen baseline', async () => {
const { terminal } = fixture()
const input = inputChannel<TerminalInput>()
const abort = new AbortController()
abort.abort(new Error('already detached'))
await expect(terminal.attach(input.source, { maxInputBytes: 1000, maxCols: 200, maxRows: 100 }, abort.signal)[Symbol.asyncIterator]().next()).rejects.toThrow('already detached')
})
it('reports a non-Error provider input rejection through the attachment', async () => {
const { terminal, handle } = fixture()
const view = await attach(terminal)
handle.write.mockRejectedValueOnce('remote input failed')
view.input.push({ type: 'write', sequence: 1, data: 'input' })
await expect(view.iterator.next()).rejects.toThrow('remote input failed')
})
it('preserves the current controller when a queued attachment is cancelled during an input write', async () => {
const { terminal, handle } = fixture()
const first = await attach(terminal)
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
cleanups.push(async () => { release.resolve(undefined) })
handle.write.mockImplementationOnce(async () => { entered.resolve(undefined); await release.promise })
first.input.push({ type: 'write', sequence: 1, data: 'first' })
await entered.promise
const abort = new AbortController()
const input = inputChannel<TerminalInput>()
const iterator = terminal.attach(input.source, { maxInputBytes: 1000, maxCols: 200, maxRows: 100 }, abort.signal)[Symbol.asyncIterator]()
cleanups.push(async () => { abort.abort(); await iterator.return?.() })
const failed = expect(iterator.next()).rejects.toThrow('cancelled while queued')
abort.abort(new Error('cancelled while queued'))
release.resolve(undefined)
await failed
expect(await readFrame(first.iterator)).toEqual({ type: 'ack', sequence: 1 })
terminal.rename('retained control')
expect(await readFrame(first.iterator)).toMatchObject({ type: 'state', writable: true })
first.input.push({ type: 'write', sequence: 2, data: 'still writable' })
expect(await readFrame(first.iterator)).toEqual({ type: 'ack', sequence: 2 })
expect(handle.write).toHaveBeenLastCalledWith('still writable')
})
@@ -55,6 +55,9 @@
},
{
"path": "../../util/lazy-require"
},
{
"path": "../../util/values"
}
]
}
@@ -140,7 +140,7 @@ it('shows only the terminal screen while connected and detaches on unmount', ()
})
it('keeps one emulator across rename and locale updates, applies snapshots and output once, and releases listeners', () => {
const snapshot: TerminalViewState = { ...idle, info, phase: 'connected', writable: true, render: { revision: 1, frame: { type: 'snapshot', sequence: 0, info, screen: 'restored' } } }
const snapshot: TerminalViewState = { ...idle, info, phase: 'connected', writable: true, render: { revision: 1, frame: { type: 'snapshot', writable: true, sequence: 0, info, screen: 'restored' } } }
const h = mount(snapshot)
const terminal = fake.terminals[0]!
expect(terminal.reset).toHaveBeenCalledOnce()
@@ -3144,22 +3144,10 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
returns: 'a hold acknowledgement followed by an open lifetime stream.',
},
{
signature: '@Remote({ mode: \'stream\' }) follow(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, signal: AbortSignal): AsyncIterable<TerminalFrame>',
description: 'Attach to a terminal without binding its process lifetime to the transport.',
parameters: [{ name: 'agent', description: 'Session owner supplied by the Gateway.' }, { name: 'id', description: 'terminal identity.' }, { name: 'attachmentId', description: 'new exclusive input attachment.' }, { name: 'signal', description: 'physical stream cancellation.' }],
returns: 'screen recovery followed by output and metadata changes.',
},
{
signature: '@Remote async write(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, data: string): Promise<void>',
description: 'Deliver raw input, including Tab completion and control characters.',
parameters: [{ name: 'agent', description: 'Session owner supplied by the Gateway.' }, { name: 'id', description: 'terminal identity.' }, { name: 'attachmentId', description: 'current writable attachment.' }, { name: 'data', description: 'input bytes represented as UTF-8 text.' }],
returns: 'after provider input acceptance.',
},
{
signature: '@Remote async resize(agent: Agent, id: WebTerminalId, attachmentId: TerminalAttachmentId, cols: number, rows: number): Promise<void>',
description: 'Update the dimensions of the PTY and recovery screen.',
parameters: [{ name: 'agent', description: 'Session owner supplied by the Gateway.' }, { name: 'id', description: 'terminal identity.' }, { name: 'attachmentId', description: 'current writable attachment.' }, { name: 'cols', description: 'column count.' }, { name: 'rows', description: 'row count.' }],
returns: 'after the resize completes.',
signature: '@Remote({ mode: \'stream\' }) attach(agent: Agent, id: WebTerminalId, signal: AbortSignal): RemoteStream<TerminalFrame, TerminalInput>',
description: 'Attach terminal input and output to one physical Remote stream.',
parameters: [{ name: 'agent', description: 'Session owner supplied by the Gateway.' }, { name: 'id', description: 'terminal identity.' }, { name: 'signal', description: 'attachment cancellation; the process remains alive and input is never replayed.' }],
returns: 'screen recovery, output, writable state and provider-acceptance acknowledgements.',
},
{
signature: '@Remote rename(agent: Agent, id: WebTerminalId, title: string): void',
@@ -6488,6 +6476,10 @@ export const TYPE_API: readonly TypeApiEntry[] = [
name: 'RemoteEventHostInfo',
declaration: 'export interface RemoteEventHostInfo {\n readonly home: string;\n}',
},
{
name: 'RemoteStream',
declaration: 'export type RemoteStream<Out, In = never> = AsyncIterable<Out> & {\n readonly [STREAM_UPLINK]?: In;\n};',
},
{
name: 'RenderedDocumentBytes',
declaration: 'export interface RenderedDocumentBytes extends WorkspaceFileBytes {\n readonly missingFonts: string[];\n readonly generation: OfficeToPdfGeneration;\n}',
@@ -7784,10 +7776,6 @@ export const TYPE_API: readonly TypeApiEntry[] = [
name: 'TeamWaitResult',
declaration: 'export interface TeamWaitResult {\n readonly timedOut: boolean;\n}',
},
{
name: 'TerminalAttachmentId',
declaration: 'export type TerminalAttachmentId = Branded<\'TerminalAttachmentId\'>;',
},
{
name: 'TerminalBackend',
declaration: 'export interface TerminalBackend {\n readonly type: string;\n spawn(spec: TerminalBackendSpawnSpec): Promise<TerminalBackendSession>;\n}',
@@ -7814,7 +7802,11 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'TerminalFrame',
declaration: 'export type TerminalFrame = {\n readonly type: \'snapshot\';\n readonly sequence: number;\n readonly screen: string;\n readonly info: WebTerminalInfo;\n} | {\n readonly type: \'output\';\n readonly sequence: number;\n readonly data: string;\n} | {\n readonly type: \'state\';\n readonly info: WebTerminalInfo;\n};',
declaration: 'export type TerminalFrame = {\n readonly type: \'snapshot\';\n readonly sequence: number;\n readonly screen: string;\n readonly info: WebTerminalInfo;\n readonly writable: boolean;\n} | {\n readonly type: \'output\';\n readonly sequence: number;\n readonly data: string;\n} | {\n readonly type: \'state\';\n readonly info: WebTerminalInfo;\n readonly writable: boolean;\n} | {\n readonly type: \'ack\';\n readonly sequence: number;\n readonly refusal?: \'read-only\' | \'not-running\';\n};',
},
{
name: 'TerminalInput',
declaration: 'export type TerminalInput = {\n readonly type: \'write\';\n readonly sequence: number;\n readonly data: string;\n} | {\n readonly type: \'resize\';\n readonly sequence: number;\n readonly cols: number;\n readonly rows: number;\n};',
},
{
name: 'TerminalReadRequest',
@@ -8370,7 +8362,7 @@ export const TYPE_API: readonly TypeApiEntry[] = [
},
{
name: 'WebTerminalInfo',
declaration: 'export interface WebTerminalInfo {\n readonly id: WebTerminalId;\n readonly title: string;\n readonly shell: TerminalShell;\n readonly cwd: string;\n readonly cols: number;\n readonly rows: number;\n readonly state: \'running\' | \'exited\' | \'failed\';\n readonly exitCode: number | null;\n readonly error?: string;\n readonly controllerId?: TerminalAttachmentId;\n}',
declaration: 'export interface WebTerminalInfo {\n readonly id: WebTerminalId;\n readonly title: string;\n readonly shell: TerminalShell;\n readonly cwd: string;\n readonly cols: number;\n readonly rows: number;\n readonly state: \'running\' | \'exited\' | \'failed\';\n readonly exitCode: number | null;\n readonly error?: string;\n}',
},
{
name: 'WebUpgradeRoute',
+3
View File
@@ -1582,6 +1582,9 @@ importers:
'@deepseek-ai/dsh-typert-protocol':
specifier: workspace:*
version: link:../../typert/protocol
'@deepseek-ai/dsh-util-values':
specifier: workspace:*
version: link:../../util/values
'@deepseek-ai/schemastery':
specifier: link:../../../vendor/schemastery
version: link:../../../vendor/schemastery
+2 -1
View File
@@ -281,6 +281,7 @@ export const EVENT_WALK_EXEMPTIONS: Record<string, string> = {
* appear on more than one page.
*/
export const LINK_MAP: Readonly<Record<string, string>> = {
RemoteStream: 'typert.md',
EventLogOptions: 'otel.md',
EventLogReporter: 'otel.md',
SessionLogOptions: 'otel.md',
@@ -957,7 +958,7 @@ export const TYPE_LINK_EXEMPTIONS: Readonly<Record<string, string>> = {
TerminalEnvironment: 'Browser terminal environment fields are owned by packages/api/terminal-controller/README.md',
WebTerminalInfo: 'Browser terminal metadata is owned by packages/api/terminal-controller/README.md',
TerminalCreateRequest: 'Browser terminal allocation fields are owned by packages/api/terminal-controller/README.md',
TerminalAttachmentId: 'Browser terminal input ownership is owned by packages/api/terminal-controller/README.md',
TerminalInput: 'Browser terminal input commands are owned by packages/api/terminal-controller/README.md',
TerminalFrame: 'Browser terminal stream frames are owned by packages/api/terminal-controller/README.md',
TerminalRetentionFrame: 'Browser terminal window holds are owned by packages/api/terminal-controller/README.md',
WebTerminalId: 'Browser terminal identity is owned by packages/api/terminal-controller/README.md',