fix(terminal-controller): reopen a failed roster stream for its remaining watchers
A roster stream that failed while watched used to drop its watchers, so Agent terminals stopped opening tabs until the Session header remounted. The stream now reopens in place on the next watch of that Session or when the connection resets.
This commit is contained in:
1 parent
f1e90e5845
commit
6be8e43bcd
7 files changed
+82
-13
No files matched your search
@@ -21,8 +21,8 @@
|
||||
en: 9e970d5709e5e68c
|
||||
zh: 7f1bcb09e9a026ce
|
||||
/deepseek-ai-dsh-api-terminal-controller/understand-the-implementation:
|
||||
en: e6509446e718fd93
|
||||
zh: 459e4768384b1060
|
||||
en: 138e9cc1c4110496
|
||||
zh: 8a3d13a1a60091a2
|
||||
/deepseek-ai-dsh-api-terminal-controller/further-exploration:
|
||||
en: b1b5d2a2bfb8cc6a
|
||||
zh: aa0ea568aa63fda5
|
||||
|
||||
@@ -68,7 +68,7 @@ The opening snapshot advertises the carrier's complete-frame `inputWindow`; in-p
|
||||
|
||||
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.
|
||||
|
||||
Client discovery belongs to each Session in the current window. Concurrent and later restored views share one list, including an empty result; new identities allocate directly from `create`. Explicit retry replaces a settled result or failure, and reconnection refreshes each previously discovered Session once. Remounting a failed view preserves its error without retrying. Confirmed mutations and attachment metadata take precedence over an older pending list response, and responses from replaced connections cannot publish. A view releasing its DOM or lifetime does not cancel another view’s lookup. Plugin disposal discards cached metadata and joins outstanding discovery. Other windows’ unrepresented terminals become discoverable through explicit refresh or reconnection; current attachments carry their own live metadata. `watch(sessionId, listener)` shares one roster stream per Session in a window and updates the shared list before listeners run; `bind` saves a tab's association with an existing terminal before its body mounts. Environment lookup remains separate because its working directory can change.
|
||||
Client discovery belongs to each Session in the current window. Concurrent and later restored views share one list, including an empty result; new identities allocate directly from `create`. Explicit retry replaces a settled result or failure, and reconnection refreshes each previously discovered Session once. Remounting a failed view preserves its error without retrying. Confirmed mutations and attachment metadata take precedence over an older pending list response, and responses from replaced connections cannot publish. A view releasing its DOM or lifetime does not cancel another view’s lookup. Plugin disposal discards cached metadata and joins outstanding discovery. Other windows’ unrepresented terminals become discoverable through explicit refresh or reconnection; current attachments carry their own live metadata. `watch(sessionId, listener)` shares one roster stream per Session in a window and updates the shared list before listeners run; a stream that fails while watched reopens for its remaining listeners on the next watch of that Session or after the connection resets; `bind` saves a tab's association with an existing terminal before its body mounts. Environment lookup remains separate because its working directory can change.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ Agent 终端复用同一套分配、回滚和保留流程,标识由 Host 生
|
||||
|
||||
Client 在分配前将每条 Session/内容与终端身份的关联保存到独立的 localStorage key `dsh.terminal.binding.v1.*`。内容身份全局唯一;布局内的 tab id 只标识活动视图 occurrence。逐条记录的写入和删除会保留其他窗口的关联。恢复视图复用该身份;侧栏 terminal provider 先恢复自己的视图,再查询尚无视图的 Host 终端。新视图可以创建进程,恢复视图在目标缺失时显示错误,不创建替代进程。显式关闭先保存清理请求,再删除关联。当前进程元数据和屏幕内容由 Host 提供,不保存在浏览器中。Client 模型在浏览器完成屏幕解析后确认帧,在未确认 UTF-8 字节预算内连续发送输入,并忽略旧连接迟到的响应。重连建立新的命令序列,绝不重放未确认输入。提供者输入失败会结束附件;进程和恢复屏幕仍可供显式重连使用。Client 自产错误携带本地化键。插件卸载等待活跃及先前断开的输出流结束,不关闭 Host 进程。
|
||||
|
||||
客户端发现状态由当前窗口中的各个 Session 持有。并发及稍后恢复的视图共享一次列表查询,包括空结果;新标识直接通过 `create` 分配终端。显式重试会替换已完成的结果或失败,重连则为每个已经查询过的 Session 刷新一次列表。失败视图重新挂载时保留错误,不会重试。已确认的操作和 attachment 元数据优先于较早发起的列表响应,被替换连接的响应不能发布状态。单个视图释放 DOM 或结束生命周期不会取消其他视图的查询。插件卸载会丢弃缓存元数据并等待未完成的发现请求结束。其他窗口中尚未出现在本窗口的终端可通过显式刷新或重连发现;当前 attachment 自行传递实时元数据。`watch(sessionId, listener)` 在一个窗口内为每个 Session 共享一条终端列表流,并在调用监听者前更新共享列表;`bind` 在标签内容挂载前保存标签与已有终端的关联。环境查询保持独立,因为工作目录可能变化。
|
||||
客户端发现状态由当前窗口中的各个 Session 持有。并发及稍后恢复的视图共享一次列表查询,包括空结果;新标识直接通过 `create` 分配终端。显式重试会替换已完成的结果或失败,重连则为每个已经查询过的 Session 刷新一次列表。失败视图重新挂载时保留错误,不会重试。已确认的操作和 attachment 元数据优先于较早发起的列表响应,被替换连接的响应不能发布状态。单个视图释放 DOM 或结束生命周期不会取消其他视图的查询。插件卸载会丢弃缓存元数据并等待未完成的发现请求结束。其他窗口中尚未出现在本窗口的终端可通过显式刷新或重连发现;当前 attachment 自行传递实时元数据。`watch(sessionId, listener)` 在一个窗口内为每个 Session 共享一条终端列表流,并在调用监听者前更新共享列表;监听期间失败的列表流会在该 Session 下一次被监听时或连接重置后为剩余监听者重新打开;`bind` 在标签内容挂载前保存标签与已有终端的关联。环境查询保持独立,因为工作目录可能变化。
|
||||
|
||||
独立的 `retain(sessionId, id, signal)` Remote 流确认窗口持有关系,不激活 Agent、发送屏幕输出、转移输入权或创建进程。终端 provider 提供侧栏的完整打开标签清单,Client 将其与自己保存的身份取交集。同一窗口中的重复 occurrence 共用一个持有流;孤立的旧关联不会保活任何终端。恢复输出连接前必须等待当前持有关系确认。传输取消只释放对应的物理流代次;插件卸载等待全部持有流结束。清理失败时保留所有权并重试,不重新接受连接,也不重新计算空闲宽限期。
|
||||
|
||||
|
||||
@@ -69,6 +69,7 @@ export class ClientTerminals extends Service {
|
||||
const connection = ctx.get('connection') as ConnectionHandle
|
||||
let connected = connection.generation.getSnapshot() !== undefined
|
||||
ctx.on('connection/reset', () => {
|
||||
this.rosters.resume()
|
||||
if (!connected) { connected = true; return }
|
||||
for (const [sessionId, inventory] of this.inventories) {
|
||||
void inventory.reset()?.catch((error: unknown) => {
|
||||
|
||||
@@ -11,10 +11,14 @@ interface RosterEntry {
|
||||
readonly listeners: Set<TerminalRosterListener>
|
||||
latest: readonly WebTerminalInfo[] | undefined
|
||||
stopped: boolean
|
||||
readonly dispose: () => Promise<void>
|
||||
/** Disposes the live stream; undefined after the stream failed and before it reopens. */
|
||||
dispose: (() => Promise<void>) | undefined
|
||||
}
|
||||
|
||||
/** Shares one Host roster stream among a Session's watchers and stops it with the last watcher. */
|
||||
/**
|
||||
* Shares one Host roster stream among a Session's watchers and stops it with the last watcher. A stream that fails
|
||||
* while watched reopens for its remaining watchers on the next watch of that Session or on {@link TerminalRosters.resume}.
|
||||
*/
|
||||
export class TerminalRosters {
|
||||
private readonly entries = new Map<SessionId, RosterEntry>()
|
||||
private readonly stopping = new Set<Promise<void>>()
|
||||
@@ -41,9 +45,10 @@ export class TerminalRosters {
|
||||
watch(sessionId: SessionId, listener: TerminalRosterListener): () => void {
|
||||
let entry = this.entries.get(sessionId)
|
||||
if (entry === undefined || entry.stopped) {
|
||||
entry = this.start(sessionId)
|
||||
entry = { listeners: new Set(), latest: undefined, stopped: false, dispose: undefined }
|
||||
this.entries.set(sessionId, entry)
|
||||
}
|
||||
if (entry.dispose === undefined) this.open(sessionId, entry)
|
||||
entry.listeners.add(listener)
|
||||
if (entry.latest !== undefined) this.notify(listener, entry.latest)
|
||||
const owned = entry
|
||||
@@ -58,6 +63,15 @@ export class TerminalRosters {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reopen the streams that failed while watched, for example after the connection is replaced.
|
||||
*/
|
||||
resume(): void {
|
||||
for (const [sessionId, entry] of this.entries) {
|
||||
if (entry.dispose === undefined) this.open(sessionId, entry)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop every stream.
|
||||
* @returns after every stream has closed.
|
||||
@@ -68,7 +82,7 @@ export class TerminalRosters {
|
||||
await Promise.all(this.stopping)
|
||||
}
|
||||
|
||||
private start(sessionId: SessionId): RosterEntry {
|
||||
private open(sessionId: SessionId, entry: RosterEntry): void {
|
||||
const name = `terminal roster ${String(sessionId)}`
|
||||
const stream = this.gateway.$stream<WebTerminalInfo[]>({
|
||||
name,
|
||||
@@ -78,7 +92,8 @@ export class TerminalRosters {
|
||||
? new RemoteStreamCarrierError(`${name} ended before release`)
|
||||
: new Error(`${name} ended before its first frame`),
|
||||
})
|
||||
const entry: RosterEntry = { listeners: new Set(), latest: undefined, stopped: false, dispose: () => stream.dispose() }
|
||||
const dispose = (): Promise<void> => stream.dispose()
|
||||
entry.dispose = dispose
|
||||
void (async () => {
|
||||
try {
|
||||
for await (const item of stream) {
|
||||
@@ -91,11 +106,12 @@ export class TerminalRosters {
|
||||
// Disposal ends the stream without an error, so every caught failure is a live stream failure.
|
||||
this.failed(error)
|
||||
} finally {
|
||||
if (this.entries.get(sessionId) === entry) this.entries.delete(sessionId)
|
||||
this.stop(entry)
|
||||
if (entry.dispose === dispose) {
|
||||
entry.dispose = undefined
|
||||
this.track(dispose())
|
||||
}
|
||||
}
|
||||
})()
|
||||
return entry
|
||||
}
|
||||
|
||||
private notify(listener: TerminalRosterListener, terminals: readonly WebTerminalInfo[]): void {
|
||||
@@ -105,7 +121,13 @@ export class TerminalRosters {
|
||||
private stop(entry: RosterEntry): void {
|
||||
if (entry.stopped) return
|
||||
entry.stopped = true
|
||||
const stopping = entry.dispose().finally(() => { this.stopping.delete(stopping) })
|
||||
const dispose = entry.dispose
|
||||
entry.dispose = undefined
|
||||
if (dispose !== undefined) this.track(dispose())
|
||||
}
|
||||
|
||||
private track(disposal: Promise<void>): void {
|
||||
const stopping = disposal.finally(() => { this.stopping.delete(stopping) })
|
||||
this.stopping.add(stopping)
|
||||
}
|
||||
}
|
||||
@@ -916,3 +916,23 @@ it('logs a failed roster stream', async () => {
|
||||
await expect.poll(() => warn.mock.calls.length).toBe(1)
|
||||
expect(warn).toHaveBeenCalledWith('Terminal roster failed', expect.objectContaining({ message: 'roster unavailable' }))
|
||||
})
|
||||
|
||||
it('reopens a failed roster stream when the connection resets', async () => {
|
||||
storage()
|
||||
const h = fixture()
|
||||
vi.mocked(h.remote.watch).mockImplementationOnce(streamMethod<TerminalRemote['watch']>(async function* () {
|
||||
yield* []
|
||||
throw new Error('roster unavailable')
|
||||
}))
|
||||
const agentTerminal: WebTerminalInfo = { ...info, id: 'agent-terminal' as WebTerminalId, origin: 'agent', control: 'agent' }
|
||||
h.rosterFrames.push([agentTerminal])
|
||||
const { service, ctx } = await h.service()
|
||||
const warn = vi.spyOn(ctx.logger, 'warn')
|
||||
const seen = vi.fn()
|
||||
service.watch(sessionId, seen)
|
||||
await expect.poll(() => warn.mock.calls.length).toBe(1)
|
||||
ctx.emit('connection/reset')
|
||||
await expect.poll(() => seen.mock.calls.length).toBe(1)
|
||||
expect(seen).toHaveBeenCalledWith([agentTerminal])
|
||||
expect(h.remote.watch).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
@@ -120,3 +120,29 @@ it('keeps a replacement stream when an earlier watcher releases after its stream
|
||||
h.sources[1]?.enqueue([info])
|
||||
await expect.poll(() => current.mock.calls.length).toBe(1)
|
||||
})
|
||||
|
||||
it('reopens a failed stream for its remaining watchers on resume and leaves live streams alone', async () => {
|
||||
const h = fixture()
|
||||
const watcher = vi.fn()
|
||||
h.rosters.watch(sessionId, watcher)
|
||||
await expect.poll(() => h.sources.length).toBe(1)
|
||||
h.rosters.resume()
|
||||
expect(h.remote.watch).toHaveBeenCalledOnce()
|
||||
h.sources[0]?.error(new Error('Host method unavailable'))
|
||||
await expect.poll(() => h.failed.mock.calls.length).toBe(1)
|
||||
h.rosters.resume()
|
||||
await expect.poll(() => h.sources.length).toBe(2)
|
||||
h.sources[1]?.enqueue([info])
|
||||
await expect.poll(() => watcher.mock.calls.length).toBe(1)
|
||||
expect(watcher).toHaveBeenCalledWith([info])
|
||||
})
|
||||
|
||||
it('accepts a release that arrives after disposal', async () => {
|
||||
const h = fixture()
|
||||
const release = h.rosters.watch(sessionId, vi.fn())
|
||||
await expect.poll(() => h.sources.length).toBe(1)
|
||||
await h.rosters.dispose()
|
||||
expect(h.cancelled).toEqual([0])
|
||||
release()
|
||||
expect(h.remote.watch).toHaveBeenCalledOnce()
|
||||
})
|
||||
Reference in new issue
Block a user