Skip to content

fix(core): run web terminal PTYs on the bundled ConPTY backend - #11643

Merged
wenshao merged 11 commits into
mainfrom
fix/web-terminal-bundled-conpty
Sep 13, 2026
Merged

wenshao merged 11 commits into
mainfrom
fix/web-terminal-bundled-conpty

Conversation

@yiliang114

@yiliang114 yiliang114 commented Sep 11, 2026 •

Copy link
Copy Markdown
Collaborator

What this PR does

Windows web-terminal and agent-view PTYs use bundled ConPTY to address the inbox backend's natural-exit host leak. Web terminals retry once on the inbox backend if bundled spawn fails, and release the remaining worker resources after exit while retaining scrollback.

The review follow-up keeps terminal output intact. The Windows server answers only primary device-attribute startup probes; the browser owns colors, modes and geometry. Reconnect history is restored without forwarding its automatic replies, while the old visible terminal keeps accepting keyboard input. First-connection output and subsequent live output can still receive replies. This removes the hand-written query filters instead of adding more escape-sequence cases.

Why it's needed

#11352 tracks Windows terminal processes left behind after exit. Selecting bundled ConPTY changes who answers terminal probes, so the backend switch also needs to preserve live answers without injecting historical responses into the shell on reconnect. The original filtering approach lost some color answers and replayed others. #11734 tracks that follow-up; the cross-package replay contract was explicitly approved for this PR.

Reviewer Test Plan

How to verify

  1. On Windows, repeatedly open a web terminal, run a command and exit. Check that conhost/OpenConsole process counts return to baseline. Also check PowerShell startup, cancellation, resize and CJK input. Native Windows acceptance is still required; mocked spawn assertions do not prove process cleanup.
  2. In an active Web Shell terminal, issue background, cursor-color, palette, mode and DCS queries. Live queries should receive the browser's answers. Primary DA should have only one answerer, including when the server responder is unavailable.
  3. Reconnect with those queries in scrollback. Historical queries must not write new replies into the shell. Type during restoration and queue fresh output: the input must arrive once, followed by the live responses after restoration. Interrupt restoration and confirm a stale callback cannot replace the current view.
  4. Update the daemon and Web Shell together. An older client or unmarked old-server snapshot must fail with a reload/restart message, not silently replay replies. Closing a detached terminal must still release it.

Evidence (Before & After)

Before this correction, real package probes at 77257a5 showed OSC 11 losing its only answer and OSC 12/multi-index OSC 4 answering again on replay. The intervening d8975fa restored live color queries; this change preserves that correction and removes replayed replies as well.

After: the actual modified React terminal component, real xterm and FitAddon were mounted in Chromium with controlled surrounding contexts and WebSocket transport. Fresh output produced six color/mode/DCS replies, plus one DA only when browser-owned. On reconnect, 14 native historical reply events produced zero outgoing replies; a real keyboard k arrived once during delayed restoration and the queued live batch produced seven replies once. Canceled restoration and legacy-protocol rejection passed, with no browser errors. This is component-boundary evidence, not a real daemon/PTY or Windows process-count test.

Tested on

OS Status
macOS Focused unit tests and mounted Chromium component checks passed
Windows Not tested on a native host
Linux Not tested locally in this round

Environment (optional)

Node 22.22.0, React 19.2.4, browser xterm 6.0.0, FitAddon 0.11.0, headless xterm 5.5.0 and Chromium 149.0.7827.55. Focused registry, WebSocket-route and terminal-component tests passed, as did ESLint on the six edited TypeScript files. Package typechecks encountered stale project-reference build declarations, including APIs already present in source; they are not reported as passing. No dependency installation or full rebuild was run in this round.

Risk & Scope

  • The Windows backend change covers web terminals and agent view; this round does not expand agent-view behavior. The replay contract applies to Web Shell terminals on every host, not only VS Code. POSIX backend selection remains unchanged.
  • The inbox fallback does not fix the original native leak. A missing headless responder also leaves startup probes dependent on browser attachment. Native Windows cleanup, DLL-failure fallback and full daemon/PTY acceptance remain unverified.
  • Migration: daemon and Web Shell must update together for the replay-marked protocol. Workspace ownership checks, bounded binary output and input/output backpressure are retained. No dependencies are added.
  • Design: English / 简体中文.

Linked Issues

Refs #11352 · Refs #11497 · Refs #11734 · microsoft/node-pty#965. No issue is automatically closed by this description.

中文说明

这个 PR 做了什么

Windows web-terminal 和 agent-view PTY 改用 bundled ConPTY,处理 inbox 后端在自然退出时遗留 host 的问题。web terminal 在 bundled spawn 失败时回退 inbox 重试一次,并在退出后释放剩余 worker 资源,同时保留 scrollback。

本次评审修正保留完整终端输出。Windows 服务端只应答启动时的 primary DA 探测,颜色、模式和几何查询交给浏览器。重连历史恢复时不转发自动应答,旧的可见终端仍接受键盘输入;首次连接输出和随后的实时输出仍能得到应答。删除手写查询过滤器,不再继续枚举转义序列。

为什么需要

#11352 跟踪 Windows 终端退出后残留进程的问题。切换 bundled ConPTY 会改变终端探测的应答方,因此还必须保留实时应答,并防止重连把历史应答重新注入 shell。原有过滤方案会丢失一部分颜色应答,也会重放另一部分。#11734 跟踪该后续问题;这次跨包回放协议已获明确批准,放在本 PR 中修正。

评审测试计划

如何验证

  1. Windows 上反复打开 web terminal、执行命令并退出,检查 conhost/OpenConsole 进程数量是否回到基线。同时检查 PowerShell 启动、取消、resize 和中文输入。仍需 Windows 真机验收;mock spawn 断言不能证明进程已清理。
  2. 在活动的 Web Shell 终端中发出背景色、光标色、调色板、模式和 DCS 查询。实时查询应收到浏览器的答案。primary DA 只能有一个应答方,也需覆盖服务端 responder 不可用的情况。
  3. 携带这些查询的 scrollback 重连。历史查询不能向 shell 写入新的应答。恢复时输入字符并排入新输出:输入应到达一次,恢复后再收到实时应答。中断恢复,确认旧回调不能替换当前视图。
  4. daemon 和 Web Shell 同步升级。旧客户端或旧服务端未标记的快照应明确提示刷新/重启,不能悄悄重放应答。关闭已脱离页面的终端仍应释放会话。

证据(前后对比)

修正前,77257a5 上的真实终端包探测显示 OSC 11 丢失唯一应答,OSC 12 和多下标 OSC 4 在回放时再次应答。期间提交的 d8975fa 已恢复实时颜色查询;本次保留该修复,并消除历史回放应答。

修正后,在 Chromium 中挂载实际修改的 React 终端组件、真实 xterm 和 FitAddon,仅控制外围 context 和 WebSocket 传输。首次输出产生六次颜色/模式/DCS 应答,只有浏览器负责 DA 时才额外产生一次 DA。重连时观察到的 14 次原生历史应答没有任何一次向外转发;延迟恢复期间真实键盘 k 到达一次,排队的实时查询产生七次应答且各一次。中断恢复、旧协议拒绝均通过,浏览器没有错误。这是组件边界验证,不是真实 daemon/PTY 或 Windows 进程计数测试。

测试平台

OS 状态
macOS 定向单测和真实 Chromium 组件检查通过
Windows 未在原生主机测试
Linux 本轮未在本地测试

环境(可选)

Node 22.22.0、React 19.2.4、浏览器 xterm 6.0.0、FitAddon 0.11.0、headless xterm 5.5.0、Chromium 149.0.7827.55。registry、WebSocket 路由和终端组件的定向测试通过,六个改动 TypeScript 文件的 ESLint 通过。包级类型检查遇到过期的 project-reference 构建声明,其中包含源码中已有的 API;不将类型检查报告为通过。本轮没有安装依赖或运行完整构建。

风险与范围

  • Windows 后端变更覆盖 web terminal 和 agent view;本轮不扩展 agent-view 行为。回放协议适用于所有平台的 Web Shell 终端,并非仅限 VS Code。POSIX 后端选择不变。
  • inbox 回退不解决原始原生泄漏。缺少 headless responder 时,启动探测也依赖浏览器连接。Windows 原生清理、DLL 失败回退以及完整 daemon/PTY 验收仍未验证。
  • 迁移:daemon 和 Web Shell 必须同步升级以支持带回放标记的协议。保留工作区归属校验、有界二进制输出以及输入输出背压。不增加依赖。
  • 设计:English / 简体中文。

关联 Issue

Refs #11352 · Refs #11497 · Refs #11734 · microsoft/node-pty#965。本描述不自动关闭任何 issue。

The web terminal spawned its PTYs with node-pty's default inbox ConPTY
backend, where a natural shell exit orphans the conhost.exe --headless
the backend spawned: the native exit watcher erases the pty baton before
delivering onExit, pty_baton has no destructor, and the erased HPCON is
unreachable from JS (microsoft/node-pty#965). Every exited web terminal
leaked ~8 MB for the life of the CLI, and a pin bump does not fix it.

Mirror the #11497 shell path: spawn with useConptyDll on Windows so the
bundled backend releases its host reference right after spawn and the
host exits with its last client. The bundled backend adds one
synchronous throw point — a missing or unloadable conpty.dll — and a
web terminal has no child_process fallback, so a failed bundled spawn
retries once on the inbox backend: the pre-fix leaking behavior beats a
terminal that cannot start at all. A failed spawn produced no child, so
the retry cannot double-spawn. The 4001 non-retryable close path is
unchanged.

Also switch the agent-view PTY host to the bundled backend (same leak,
lower rate), refresh the conpty-host release docs, and add a
VERIFIED_NODE_PTY pin test so a node-pty bump forces re-verification of
the native teardown semantics the release path depends on.

Refs #11352
@yiliang114
yiliang114 force-pushed the fix/web-terminal-bundled-conpty branch from 5cb5f11 to cce1866 Compare September 11, 2026 09:07
@github-actions

Copy link
Copy Markdown
Contributor

Please do not rebase or force-push to an active PR as it invalidates existing review comments. Note for future reference, the bots always squash all changes into a single commit automatically as part of the integration.

中文

请勿对活跃的 PR 执行 rebase 或 force-push,因为这会使已有的评审评论失效。另外,供日后参考:作为集成流程的一部分,机器人始终会自动将所有改动压缩(squash)为单个提交。

@doudouOUC doudouOUC left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agent-assisted review at cce1866c0b8eb028130b5618923de7c51ce83423 — no confirmed code Criticals in this static review.

Reviewed the full six-file diff against base 518f6795f9eda4b9911c2a1e8ea76ddc787551cb, the complete changed production files, and the added tests. Traced useConptyDll from both spawn sites through the actual PTY loaders; checked the registry's failed-spawn retry, creation bookkeeping, early output/exit, live release and exit-time cleanup. Downstream inspection included the terminal WebSocket handler, server registry ownership/workspace drain, the shell-service precedent, and Agent View's host-process launch/exit cleanup. No daemon route is added or changed here; the terminal handler continues to supply its resolved workspace cwd/environment to the registry.

Suggestion (non-blocking): packages/cli/src/agent-view/pty-host.ts:346-357 has no inbox-backend retry, unlike web-terminal-registry.ts:325-336. A bundled-DLL load failure propagates through runAgentViewPtyHostProcess before it starts the host server (pty-host-process.ts:477-481). Please confirm that failing Agent View startup, rather than using the web terminal's compatibility fallback, is intentional. This is not a claim that the shipped DLL is missing or that normal Windows launches fail.

History / scope: There were no prior formal review Criticals in the fetched history; the triage comment's fallback asymmetry is the suggestion above, not an independently reproduced native failure. Core/cross-package policy: approximately 57 changed production-file lines including comments; this is a small fix, not a 500+ line refactor. The author has repository admin permission, verified via GitHub's collaborator-permission endpoint.

Verification limits: Static source/test inspection only; no PR code, unit tests, builds, Windows PTYs, or native leak measurements were executed. The mock tests verify option propagation and cleanup calls, not native conhost.exe reclamation. The deliberately retained inbox fallback's natural-exit leak is documented, not presented as fixed.

Comment only; no approval implied.

yiliang114 and others added 3 commits September 12, 2026 00:52
Co-authored-by: Qwen-Coder <[email protected]>

Patrol-Run: qwen-pr-conflict/jmtx6sqi9yb
The six `@lydell/node-pty*` pins live in three unsynchronized places — the
root manifest, packages/core's manifest, and a hardcoded map in
scripts/prepare-package.js — but the conpty-host tripwire asserted only
one key of one manifest, so bumping the win32 prebuild keys or the root
manifest left it green and skipped the human re-check it exists to force.

Derive the six pins in writeDistPackageJson from packages/core's manifest
(deleting the third hardcoded table), and widen the tripwire to assert all
six core keys plus an equality against the root manifest's six — the
declaration packages/cli's agent-view actually resolves in a dev tree.

Co-authored-by: Qwen-Coder <[email protected]>
Patrol-Run: qwen-pr-closeout/jmtxennouyn
…eb terminal

Switching the web-terminal registry to the bundled ConPTY backend let a
probing shell's DA / DSR query bytes into the recorded scrollback; a
reconnect that replays the buffer made the client's xterm.js re-answer
each query and write the fresh reply back into the still-live shell's
stdin. The bundled backend answers no queries itself, and the browser is
not guaranteed to be attached when the startup probe fires.

Mirror the other half of the shell path (#11497): on win32, feed a
headless terminal the PTY stream so it answers the probe server-side, and
strip the query bytes from both the scrollback and the live stream so a
replay cannot re-emit them. Also bring the releasePtyResources docstring
in line with the bundled backend (R1-8).

Co-authored-by: Qwen-Coder <[email protected]>
Patrol-Run: qwen-pr-closeout/jmtxennouyn
@yiliang114

Copy link
Copy Markdown
Collaborator Author

@qwen-code /triage

1 similar comment
@yiliang114

Copy link
Copy Markdown
Collaborator Author

@qwen-code /triage

@wenshao

wenshao commented Sep 11, 2026

Copy link
Copy Markdown
Collaborator

Maintainer verification — the Windows half, on a real Windows machine

I verified this locally as a maintainer, deliberately aimed at the one thing the PR lists as not validated: "Windows real-machine acceptance (conhost/OpenConsole counting, pwsh latency, interactive rendering) — needs a Windows environment; PR CI skips the Windows job." The sandboxed verification above also had to leave exactly that uncovered ("This container is Linux").

So I ran the PR on a real windows-2022 runner (Windows Server 2022 Datacenter 10.0.20348.5499, Node 22.23.2, the pinned @lydell/[email protected]), driving this tree's own WebTerminalRegistry, plus the local macOS stack for the POSIX side.

Verdict: LGTM — the central claim holds on real Windows, and the fix is exactly as large as advertised. Three non-blocking follow-ups below; two of them independently reproduce findings the sandbox report already filed.


1 · The leak, and its absence, measured on Windows

18 web terminals opened and exited through the real registry (3 rounds × 6, each shell exits naturally), counting conhost.exe/OpenConsole.exe parented to the daemon process:

Windows registry A/B

The same A/B at the raw backend level (6 PTYs, no registry) isolates it to the backend rather than to anything in this diff, and the interactive arms answer the rest of the manual acceptance list — COMSPEC=powershell first output 107 ms / prompt ready 1212 ms, echo round-trip ok under both cmd.exe and powershell.exe:

Backend A/B and queries

Two results in that figure are worth calling out:

  • R2-1 was a real defect and the new responder/strip half really fixes it. With the strip mutated off, a Device-Attributes probe (ESC[c) does reach the registry on the bundled backend and lands in the replayable scrollback — under both cmd and PowerShell. With the PR as written: zero on every arm. That is the first confirmation on the actual platform (the sandbox had to synthesize the probe from a script under a forced win32).
  • The ~2 s DA stall did not reproduce here. With the responder mutated off, the PowerShell prompt was still ready in 877 ms. On this host (Windows PowerShell 5.1 / Server 2022) the responder is not buying latency — it is insurance for a shell that does block on the answer. Not an objection; just don't cite the latency argument as measured on this configuration.

Also: the PR's own unit tests actually executed on Windows — the platform PR CI skips. web-terminal-registry.test.ts + conpty-host.test.ts 42 passed / 2 skipped, pty-host.test.ts 35 passed / 2 skipped. No Windows-only breakage.

2 · POSIX is unchanged, and the built product still works

npm ci && npm run build && npm run bundle at head, then the real qwen serve Web Shell in a browser: two live web terminals, colour/bold/CJK/vim intact, a full page reload replays the scrollback and the terminal keeps streaming afterwards.

macOS real stack

Against a real PTY and a real shell, head·native ≡ base·native on every observable, and the new behaviour appears only behind the win32 gate (2 × 2 matrix in the next figure). useConptyDll is also literally absent from the POSIX prebuild — it appears only in node-pty.d.ts, and spawning with it on macOS is accepted and inert. Feeding every byte through the extra parser cost nothing measurable on a 4 MB burst (1824 ms vs 1823 ms).

3 · Do the new tests hold the new behaviour down?

10 mutations, each applied alone, then the PR's own suites re-run — 7 killed, 3 survived:

Test discrimination

Two of the survivors are the same gaps the sandbox report filed (responder dispose; the prepare-package.js derivation). One is new: stripping only from the scrollback while still emitting the raw query to live listeners passes 44/44. That property is not cosmetic — it is what stops the browser's xterm.js from answering the same probe a second time into the still-live shell.

4 · Follow-ups (none blocks the merge)

Findings

  1. The responder never follows the client's resize — independently reproduced (same defect as F-1 in the sandbox report). In my lane: after registry.resize(id, 120, 24) the shell sees 120 columns, prints 100 characters, asks ESC[6n, and is answered ESC[8;21R — wrapped at 80. The precedent this PR mirrors already does both halves: shellExecutionService.ts:2615-2616 resizes the PTY and the headless terminal.
  2. The derived pin table has no test of its own — corroborates F-5/M11. Driving the real writeDistPackageJson() from both trees: today's dist manifest is byte-identical base vs head ✅, a core-manifest bump propagates at head ✅, and a broken derivation ships 0 of 6 pins with test:scripts 37/37 green. The sharp derivation two lines above throws when it cannot resolve; this one is silent.
  3. scrollback: 0 on the responder — measured, 8 responders each fed 3000 lines at 80 cols, post-warm-up RSS: 2.76 MB per live session (22.1 MB at the 8-terminal cap) vs 0.05 MB with scrollback: 0. Tiny next to the ≈6.2 MB × unbounded this PR removes, but it is per live terminal on the same platform, and a query responder never needs history.

5 · The description has drifted from the head commit

9e54d5ab3b introduces a headless xterm into the registry, but the body still says under Risk & Scope: "A theoretical ~2s first-output stall … is accepted: no headless xterm is introduced into the registry." The Evidence section still says "N/A", and the Tested-on table still marks Windows ⚠️. Worth a refresh before merge — and Windows can now be ticked with the numbers above if you want them in the body.

Environment, harnesses and how to reproduce
  • Windows lane: GitHub-hosted windows-2022, full npm ci at PR head, harnesses bundled with esbuild (@lydell/node-pty and @xterm/headless left external, i.e. loaded exactly as the product loads them) and run on plain node — tsx segfaults with node-pty on that runner (exit 139). The BASE arm is the identical harness after git checkout 78bbd9f55c -- packages/core/src packages/cli/src scripts. Hosts counted through Get-CimInstance Win32_Process filtered to children of the daemon process. Workflow + harnesses: probe/pr11643-conhost on my fork; run 34657592687 (all steps green, raw JSON in the probe-11643 artifact).
  • macOS lane: macOS 26.0 / Node 24.18.1, two isolated worktrees at 78bbd9f55c and 9e54d5ab3b, npm ci in head and the same node_modules cloned into base (the PR changes no lockfile). Gates re-run: npm run typecheck exit 0, eslint + prettier --check clean on all 7 changed files, core 44/44, cli 37/37.
  • Emulated-win32 lane (for the platform-independent half of the new logic): os.platform() is flipped to 'win32' before the registry module loads, so the Windows-gated branches run against a real /bin/bash PTY on macOS. Used for the 2 × 2 matrix and the resize/CPR demonstration.
  • Mutations were applied one at a time to a committed tree and reverted from a file copy, never with git checkout.
中文版

维护者本地验证 —— 在真实 Windows 机器上补齐 Windows 那一半

我以维护者身份在本地做了一轮验证,目标明确对准 PR 自己列为未验证的那一项:「Windows 真机验收(conhost/OpenConsole 计数、pwsh 延迟、交互渲染)—— 需要 Windows 环境;PR CI 跳过 Windows job」。上面那份沙箱验证同样把这块留空了("This container is Linux")。

所以我在真实的 windows-2022 runner(Windows Server 2022 Datacenter 10.0.20348.5499、Node 22.23.2、pin 的 @lydell/[email protected])上跑了本仓库自己的 WebTerminalRegistry,POSIX 侧则用本机 macOS 真实栈。

结论:LGTM —— 核心声明在真机上成立,修复范围与描述一致。 下面三条后续项均不阻塞合并,其中两条与沙箱报告的发现相互独立复现。

1 · Windows 上实测到的泄漏与其消失

通过真实 registry 开/关 18 个 web terminal(3 轮 × 6,每个 shell 自然退出),统计挂在 daemon 进程下的 conhost.exe/OpenConsole.exe:

裸后端层面的同款 A/B(6 个 PTY,不经 registry)说明泄漏来自后端本身而非本 diff 的任何代码;交互臂回答了手工验收清单的其余部分 —— COMSPEC=powershell 首输出 107 ms、prompt 就绪 1212 ms,cmd 与 powershell 下 echo 往返均正常。

其中两点值得单独说:

  • R2-1 是真实缺陷,新增的应答器/剥离这一半确实修好了。 把 strip 变异掉之后,DA 探测(ESC[c)确实会在 bundled 后端下抵达 registry 并进入可重放的 scrollback —— cmd 和 PowerShell 都是;按 PR 现状则各臂皆为 0。这是该结论第一次在真实平台上被确认(沙箱只能在强制 win32 下用脚本合成探测)。
  • ~2 s 的 DA 卡顿在这里没有复现。 把应答器变异掉之后,PowerShell 的 prompt 仍在 877 ms 就绪。在这个宿主(Windows PowerShell 5.1 / Server 2022)上应答器并没有带来延迟收益,它是给「真的会阻塞等待应答的 shell」买的保险。这不是反对意见,只是别把延迟论据当作已在该配置下实测。

另外,PR 自带单测这次真的在 Windows 上跑过了(PR CI 跳过的那个平台):web-terminal-registry.test.ts + conpty-host.test.ts 42 通过 / 2 跳过,pty-host.test.ts 35 通过 / 2 跳过,无 Windows 专属失败。

2 · POSIX 行为不变,打出来的产物照常可用

head 上 npm ci && npm run build && npm run bundle,再起真实 qwen serve Web Shell 用浏览器操作:两个 live web terminal,颜色/加粗/中文宽度/vim 均正常;整页刷新后 scrollback 正确重放且终端继续实时输出。

对真实 PTY + 真实 shell,head·native 与 base·native 在每一个可观测量上完全一致,新行为只出现在 win32 门后(见 2 × 2 矩阵)。useConptyDll 在 POSIX 预编译产物中根本不存在(只出现在 node-pty.d.ts),在 macOS 上带该选项 spawn 会被接受且无效果。多一个 parser 吃掉每个字节,在 4 MB 突发下没有可测开销(1824 ms vs 1823 ms)。

3 · 新增测试能否钉住新行为

10 个变异逐个施加后重跑 PR 自带套件:7 个被杀、3 个存活。其中两个与沙箱报告所报的缺口相同(应答器 dispose;prepare-package.js 的派生)。有一个是新的:只从 scrollback 剥离、仍把原始 query 发给 live listener,44/44 全绿。 这条性质并不只是好看 —— 它正是阻止浏览器端 xterm.js 对同一探测第二次作答、把回包注入仍然活着的 shell 的那条性质。

4 · 后续项(都不阻塞合并)

  1. 应答器不跟随客户端 resize —— 独立复现(与沙箱报告的 F-1 同一缺陷)。我这边:registry.resize(id, 120, 24) 后 shell 看到 120 列,打印 100 个字符再问 ESC[6n,得到的回答是 ESC[8;21R —— 在 80 列处折行了。本 PR 对齐的那个实现两半都做了:shellExecutionService.ts:2615-2616 同时 resize PTY 和 headless terminal。
  2. 派生出来的 pin 表没有自己的测试 —— 与 F-5/M11 相互印证。用两棵树里真实的 writeDistPackageJson() 跑:今天的 dist manifest base 与 head 逐字节相同 ✅;core manifest 提升版本时 head 会跟着走 ✅;而派生逻辑本身被改坏时会一个 pin 都不发,test:scripts 仍然 37/37 全绿。上面两行的 sharp 派生解析不到会抛错,这个则是静默的。
  3. 给应答器加 scrollback: 0 —— 实测:8 个应答器各喂 3000 行 80 列内容、预热后按 RSS 计,每个 live 会话 2.76 MB(8 终端上限下 22.1 MB),设 scrollback: 0 后为 0.05 MB。相对本 PR 消掉的「≈6.2 MB × 无上限」不值一提,但它是按 live 终端计、且落在同一个平台上,而 query 应答器本来就不需要历史。

5 · PR 描述已与 head commit 脱节

9e54d5ab3b 恰恰往 registry 里引入了 headless xterm,而正文 Risk & Scope 仍写着:「~2s 首输出卡顿……予以接受:registry 未引入 headless xterm」;Evidence 一节仍是 "N/A",测试平台表里 Windows 仍是 ⚠️。建议合并前刷新一下 —— Windows 这一行现在可以用上面的数据打勾了。

(复现环境与方法见英文正文折叠块;证据图托管在 wenshao/qwen-code 的 assets-pr11643 分支。)

wenshao
wenshao previously approved these changes Sep 12, 2026
@wenshao

wenshao commented Sep 12, 2026

Copy link
Copy Markdown
Collaborator

@qwen-code /triage

@wenshao
wenshao enabled auto-merge September 12, 2026 00:24
Three review findings on the bundled-ConPTY web terminal path:

- The scrollback scrub was a stateless per-chunk regex over only the `c`/`n`
  finals, so the query families xterm.js answers beyond those (tertiary DA,
  DECRQM, DECRQSS, XTVERSION, DECREQTPARM, OSC colour queries) still reached
  the scrollback and were re-answered into the live shell on reconnect. Replace
  it with a stateful stripper covering every family and carrying a probe split
  across two chunks.

- resize() resized only session.pty, leaving the headless query responder on
  its 80x24 spawn grid, so geometry-dependent replies were computed against
  the wrong size. Forward the resize to session.queryTerminal.

- loadXtermHeadless() was a second suspension point whose cancelledCreations/
  disposed guards were not re-checked, so a release()/releaseWorkspace()/
  dispose() landing during the import leaked a PTY the caller had cancelled.
  Re-check both after the import.

Co-authored-by: Qwen-Coder <[email protected]>
Patrol-Run: qwen-pr-closeout/jmtxrimarz8

@yiliang114 yiliang114 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A bounded reproduction found one correctness blocker at this head; see the inline finding. The issue remains scoped to web-terminal PTYs, while agent-view also switches backend and has no equivalent validation. The PR body also still says no headless xterm is introduced, although the implementation now contains a responder. Recommend correcting the actual query handling, removing the unrelated agent-view switch, and updating the description before another triage. No Windows conhost/OpenConsole-count or latency acceptance test was run, so this is not a Windows end-to-end sign-off.

Co-authored-by: Qwen-Coder <[email protected]>

Patrol-Run: qwen-pr-closeout/jmty6iqs0zv
@yiliang114

Copy link
Copy Markdown
Collaborator Author

@qwen-code /triage

yiliang114 and others added 2 commits September 12, 2026 21:43
The stateful stripper held any unterminated OSC (a title SET included) with no cap, so one stray ESC ] swallowed every later chunk and grew pending unbounded; the DCS alternative also required the full introducer, leaking its halves that reassemble into a re-answered DECRQSS. Hold only viable query prefixes, cap the hold, end an OSC partial at a bare ESC (accepting the C1 ST terminator), hold the DCS introducer, and gate the stripper on the responder so a failed headless load no longer strips with nobody left to answer. Correct the query-set doc comment.

Co-authored-by: Qwen-Coder <[email protected]>
Patrol-Run: qwen-pr-closeout/jmtyf3dx109
Co-authored-by: Qwen-Coder <[email protected]>
Patrol-Run: qwen-pr-conflict/jmtyhy9mj0e
@yiliang114

yiliang114 commented Sep 12, 2026 •

Copy link
Copy Markdown
Collaborator Author

Closeout at b7934e39c60c: the approved R2-1 correction is pushed to the existing branch. The intervening d8975fa color-query fix and its regression test were preserved; there was no history rewrite or replacement PR.

The registry no longer rewrites terminal bytes. Its Windows responder forwards only primary DA, and snapshot metadata tells the browser when that probe is server-owned. A new PTY's initial output can receive replies. Reconnect history restores into a detached terminal with no forwarding listener; the old visible terminal keeps accepting input, and the snapshot callback swaps views and enables replies before queued live output parses. Both sides reject incompatible replay protocols explicitly. This applies to Web Shell on all hosts, not only VS Code; daemon and Web Shell must update together.

Verification:

  • 93 focused tests passed: registry 43, WebSocket route 28, TerminalPanel 22. Scoped ESLint, Prettier and diff checks passed.
  • Five real-browser checks mounted the actual modified TerminalPanel with React 19.2.4, xterm 6.0.0 and FitAddon 0.11.0 in Chromium 149.0.7827.55. Only surrounding contexts and WebSocket transport were controlled. Fresh output produced six color/mode/DCS replies, plus exactly one DA only when browser-owned.
  • During delayed reconnect restoration, a passive observer saw 14 native historical responses but the socket received none. A real keyboard k arrived once through the old terminal; the queued live batch then produced seven replies once. A stale callback ran after disposal without replacing the newer view. Legacy unmarked output failed with 4002. No browser errors.
  • Package typechecks did not pass: project-reference build declarations are stale relative to existing source APIs, including this round's new field. No unrelated source changes, dependency installation or full rebuild were used to conceal that limitation. Browser/component evidence does not establish full daemon/PTY integration or native Windows process cleanup.

Scope integrity (changed lines = additions + deletions, including comments/scripts; not pure production-logic LOC):

Original reviewed baseline Previous ledger Current
Implementation files / changed lines 3 / 57 4 / 244 6 / 306
Test files / changed lines 3 / 323 3 / 687 5 / 738
Design files / changed lines 0 / 0 0 / 0 2 / 107

The two added implementation files are the existing terminal WebSocket route and Web Shell component, both required by the explicitly approved replay contract. This additive commit touches three implementation files, +123/-131, replacing the handwritten filters with the boundary above; it does not add dependencies or extend agent view. The original baseline is preserved and the conservative round count is now five. Scope verdict: corrected under the recorded user approval, not a new baseline. Four obsolete tests were deleted and two payload/display cases merged into the exact-stream regression after independent deletion defense; the parallel color regression remains.

Feedback: R2-1 is addressed by this correction. The two overlapping color threads were already resolved by the parallel patrol; their correction was retained. Public onColor forwarding was not added because that API is unavailable in the pinned headless package. PR description claims about missing headless, unchanged protocol and passing local typechecks have been corrected.

Status snapshot: the pushed head is mergeable, but CI/review gates are still pending. Lint & Static, Ubuntu tests and no-AK integration were in progress; the native Windows unit job was skipped. No automated-review wait or merge was performed. Native Windows process counts, startup/DLL-fallback behavior and real-daemon/PTY acceptance remain outstanding; the existing inbox fallback is not claimed to fix the leak. No further Suggestions or unrelated agent-view changes are included in this round.

chiga0
chiga0 previously approved these changes Sep 12, 2026

@chiga0 chiga0 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review Summary

Files reviewed

  • packages/core/src/services/web-terminal-registry.ts (+185/-16)
  • packages/core/src/services/web-terminal-registry.test.ts (+466/-43)
  • packages/core/src/services/conpty-host.ts (+10/-8)
  • packages/core/src/services/conpty-host.test.ts (+156, new file)
  • packages/cli/src/agent-view/pty-host.ts (+5)
  • packages/cli/src/agent-view/pty-host.test.ts (+22)
  • scripts/prepare-package.js (+14/-6)

Findings

No blockers found. All previously raised Critical findings (query scrub, resize forwarding, loadXtermHeadless cancellation, stripper/responder gate mismatch, DCS DECRQSS coverage, chunk-split handling) are resolved at HEAD.

Clean areas

  • ConPTY backend selection: useConptyDll: os.platform() === 'win32' is correct; bundled spawn with inbox fallback on failure is sound (failed synchronous spawn produces no child, no double-spawn risk).
  • TerminalQueryStripper regex correctness: Covers all xterm.js query families (DA1/2/3, DSR, DECRQM, DECRQSS, XTVERSION, DECREQTPARM, OSC colour queries). PARTIAL_ESCAPE_SUFFIX_RE correctly identifies viable query prefixes without swallowing non-query OSC title sets. Non-query escapes (SGR, erase, cursor) preserved.
  • Lifecycle management: releasePtyResources with ptyResourcesReleased flag prevents double-disposal. queryTerminal and queryReplyDisposable properly disposed. No resource leaks — all synchronous code between creation and sessions.set() prevents event-loop interleaving.
  • Concurrency: Each session has its own TerminalQueryStripper and queryTerminal instance. No shared mutable state between terminal sessions.
  • prepare-package.js: Derivation from packages/core/package.json optionalDependencies is correct. Version tripwire test asserts all 6 pins match across both manifests.
  • Platform gating: Off Windows, queryTerminal stays undefined, stripping is a no-op. Test-pinned.
  • Test coverage: Comprehensive — bundled backend spawn, DA probe answer/strip, split chunks, DCS DECRQSS (complete and split), OSC partial handling, non-query escape preservation, responder resize, cancellation during headless load, inbox retry on bundled failure, double-failure cleanup.

Needs human review

  • Windows CI skipped: windows-latest job was not run. Actual native ConPTY behavior, bundled-to-inbox fallback with real conpty.dll, and conhost.exe leak reclamation are unverified on real Windows.
  • @xterm/headless dependency: Dynamically imported on every Windows terminal creation. Verify it's in the published package's dependencies (not just devDependencies) — runtime import() requires it to be installed.

Reviewed with AI assistance.

@qqqys qqqys left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

COMMENT

核对基线:head 77257a5acc1d1e663f2b42433f0d3d21bb456bbf。

本次不 Approve:唯一未解决的线程是一条 Critical(R2-1,web-terminal-registry.ts:112),作者已明确说明只修了其中两个症状、其余三个转入 #11734 并刻意不关闭该线程。我在当前 head 的代码上独立复核,确认其中症状 (3) 仍然成立。

已确认修好的部分:症状 (1) 与 (4)

我逐条对过 web-terminal-registry.ts:83-122,缓解措施与线程里给出的方案一致且实现正确:

  • pending 现在有上界,吞字节不会永不结束。 MAX_HELD_ESCAPE_CHARS = 256(:110)配合 strip() 里的 const hold = partial !== null && partial[0].length <= MAX_HELD_ESCAPE_CHARS;(:118)——超界时 pending 清空、complete 取整个 combined,也就是把累积内容当 payload 整体放行。原报告里「之后每个 chunk 都返回 ''、pending 在 MAX_BUFFER_BYTES 之外持续增长、$ 锚定正则反复全量重扫」这条失效路径已经关掉。
  • OSC 挂起分支收窄成只hold 颜色查询前缀。 PARTIAL_ESCAPE_SUFFIX_RE 的 OSC 分支是 \x1b\](?:10|11|4;[0-9]+);\?(?:[^\x07\x1b\x9c])*:保留 ? 谓词(因此未终结的标题/颜色 SET 不会被误当查询挂起,也就不会被从两个出口丢掉)、字符类排除 \x1b(遇到裸 ESC 即结束,与 xterm 取消 OSC 的行为一致)、排除 \x9c(接受 C1 ST 作为终结符)。三点都对上了。
  • DCS 引导符已纳入挂起。 正则末尾新增的 |\x1bP\$? 让 ESC P 与 ESC P $ 这两种落在引导符中间的切分也被hold,因此不会再两半漏进 session.buffer 重新拼成一个完整 DECRQSS 被浏览器二次应答。症状 (4) 关闭。

作者记录的红绿确认(移除 OSC 上界会让 does not swallow payload after an unterminated non-query OSC 变红、移除 DCS 分支会让 DECRQSS 用例变红,48/48 registry 测试通过)与我在代码上看到的一致。

仍然存在的阻塞:症状 (3) —— OSC 12 与多下标 OSC 4 逃过过滤,回放会把应答写进仍然存活的 shell

这一条我不是转述,而是在当前 head 的正则上直接核出来的。TERMINAL_QUERY_SEQUENCE_RE(:83-85)的 OSC 分支是:

\x1b\](?:10|11|4;[0-9]+);\?(?:\x07|\x1b\\)

它只覆盖 OSC 10、OSC 11,以及单下标形式的 OSC 4,且要求 ;? 之后紧跟 BEL 或 ESC \。因此:

  • OSC 12(光标色查询)\x1b]12;?\x07 不在 (?:10|11|4;[0-9]+) 的候选里,原样通过 strip()。
  • 多下标 OSC 4 如 \x1b]4;0;?;1;?\x07:4;0;? 之后跟的是 ; 而不是 \x07 或 \x1b\\,无法匹配,同样原样通过。

而按该 Critical 的实测,声明的客户端对这两者都会应答。于是它们会被记进 scrollback,每次重连回放都把它们重新应答进仍然存活的 shell 的 stdin —— 正是这个特性要消除的危害本身。这与「过滤清单在服务端手工枚举」是同一个根因:漏掉一族就漏掉一族,且漏掉的那一族恰好是会写回 stdin 的。

其余两个症状

  • 症状 (2)(OSC 10/11/4 从两个出口都被删掉,但 pin 住的 @xterm/headless 5.5.0 responder 结构上无法应答,导致 Neovim/bat/delta 的 ESC ] 11 ; ? 背景探测从「merge base 上浏览器会应答」变成「无人应答」):我没有独立复核 responder 的能力边界,按现有 GitHub 数据记为作者已承认、仍未关闭。若成立,这是一条明确回归。
  • 症状 (5)(responder 按自身 DECRQM 状态作答,36 个模式里 1 处与出货客户端分歧):影响面小,我未独立复核。

关于结论分歧

chiga0 已在同一 head(16:34:27Z)APPROVED。我的结论不同,原因是本渠道的判定规则:只要有一条历史阻塞问题在当前 head 上仍然存在,就不能 Approve——而症状 (3) 我已在代码上确认仍成立,且作者本人也说明 (2)/(3)/(5) 未被本次缓解关闭。把结构性修复拆到 #11734 是合理的工程安排,但它不改变「当前 head 上这条 Critical 的一部分仍在」这个事实。

CI:Lint & Static、Test (ubuntu-latest, Node 22.x)、Integration Tests (no-AK, No Sandbox) 在当前 head 上均为 pass;review-pr pending,按策略不作为门禁。Test (windows-latest, Node 22.x) 为 skipped,而本 PR 的主题正是 Windows 上的 ConPTY 后端,真机确认仍欠着。

下一步

两个方向任选其一:

  1. 按线程里的结构性方案收口(也是我认同的方向):不再在服务端改写字节,而是只在回放期间抑制应答——serve/routes/terminal.ts 已有 CONTROL_FRAME_PREFIX 的服务端到客户端控制帧通道,把 snapshot 作为 { type: 'replay', output } 下发,在 TerminalPanel.tsx 里用 replaying = true; term.write(output, () => { replaying = false; }) 包住写入并在该标志期间丢弃 onData。这样现有与未来的所有查询族一次覆盖,两个正则和它们的逐角落测试都可以删掉;headless responder 保留给 bundled backend 的 DA 停顿,但收窄到它本来要解决的 DA 族,避免它按自身模式状态作答。
  2. 若本轮必须保留服务端过滤,则至少把 OSC 分支从手工枚举改成能覆盖 OSC 12 与多下标 OSC 4 的形式(例如按 OSC <数字>;? 的通用查询形态匹配,并保留 ? 谓词以免误删 SET),同时补上线程里点名的两个用例。

无论走哪条,请把症状 (2) 的回归一并给出结论:要么让 responder 能应答颜色查询,要么不要从客户端出口删掉这些查询。

@yiliang114 yiliang114 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed at 77257a5acc (7 files, +858/-73) against ea10c604bf.

Verdict: the standing [Critical] R2-1 is stale at this head, and I could not reproduce any of its blocking witnesses. What is left is a wiring gap in the responder, which is non-blocking.

I transcribed the two regexes from this head and ran R2-1's own witnesses against them.

R2-1 witness as reported (at 1bd418b328) this head (77257a5acc)
\x1b]0;title, then visible, then more visible text\r\n listener payloads ["","",""], snapshot "" \x1b]0;titlevisiblemore visible text\r\n -- nothing is swallowed
DCS split after \x1bP, and after \x1bP$ the report measured leaks in that window both deliver AFTER; the \x1bP\$? alternative closes them

Symptoms (1) and (4) -- the two the report itself named as the urgent mitigation -- landed in f6c306adfd, which is one commit after the round-4 review at 1bd418b328. The thread is describing code that is no longer here, so it can be resolved.

One measured correction to that finding's evidence. Symptom (2) rests on grep -c "onColor(" returning 0 for the pinned headless build. That count is an artifact of the minified bundle: @xterm/headless 5.5.0 does ship the handlers -- setOrReportSpecialColor (x4) and setOrReportIndexedColor (x2) are present, and the OSC 4 / 10 / 11 / 12 handlers are registered. The real gap is narrower, and it is a channel mismatch:

// @xterm/headless 5.5.0, driven directly
t.write('\x1b]11;?\x07'); t.write('\x1b]10;?\x07'); t.write('\x1b]4;1;?\x07');
t.write('\x1b[6n');        t.write('\x1b[c');
// onData  = ["\u001b[1;1R", "\u001b[?1;2c"]   <- DSR + DA1 answered here
// onColor = []                                <- colour reports do not touch this channel

_setOrReportSpecialColor only calls this._onColor.fire(...); it never routes the reply through the data event. This registry subscribes to onData only (web-terminal-registry.ts:507), so the OSC 10/11/4 arm of the strip removes those queries from the browser's stream while the server-side responder cannot answer them on the channel it uses. Either also forward onColor into proc.write, or drop the colour arm from TERMINAL_QUERY_SEQUENCE_RE -- as it stands that is the one family that is stripped with no server-side answerer. (xterm 6.0.0's browser build takes the same _onColor path and the web-shell app has no onColor subscription, so I could not establish that main answered colour probes either; treat this as an unproven benefit rather than a demonstrated regression.)

Also confirmed at this head:

  • The earlier blocking item -- the responder constructed at 80x24 and never resized -- is fixed: resize() now carries session.queryTerminal?.resize(cols, rows).
  • R2-1 symptom (3) still stands: strip('\x1b]12;?\x07') and strip('\x1b]4;0;?;1;?\x07') return their input unchanged while \x1b]11;?\x07 is removed. Inconsistent within one family, and main is no worse, so it is a coverage gap rather than a regression.
  • The agent-view host sets useConptyDll: win32 with no inbox retry (packages/cli/src/agent-view/pty-host.ts:356) while the registry retries once. The description's reasoning -- a web terminal has no child_process fallback -- applies equally there, so either add the same single retry or say in a comment why the two sites differ.

None of these block merge.

@qwen-code-dev-bot qwen-code-dev-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

REQUEST_CHANGES

已核对 head 77257a5acc1d1e663f2b42433f0d3d21bb456bbf(vs merge-base ea10c604)。required 四项全部 success(Test (ubuntu-latest, Node 22.x)、Lint & Static、Integration Tests (no-AK, No Sandbox)、web-shell E2E Smoke)。ConPTY 后端切换、创建期取消、退出期资源释放与打包那几块我复核没有发现问题。

拦的是线程 R2-1(未解决,且作者自己写明「(2)/(3)/(5) 未被本轮缓解关闭,留档在 #11734」)。先说清楚已确认修好的部分:PARTIAL_ESCAPE_SUFFIX_RE(web-terminal-registry.ts:99)的 OSC 分支现在保留 ? 谓词、遇裸 ESC 即终止并接受 C1 ST \x9c,DCS 引导串 ESC P / ESC P$ 也被兜住。我在该 head 复跑基线 Tests 48 passed (48),并分别注入两个变异:把 OSC 分支退回「任何未终止的 ESC ]」、删掉 |\x1bP\$? 这一支 → 各自恰好打红 1 条具名用例,所以「吃掉渲染字节」和「chunk 边界分裂」两条性质确实已经闭合。

阻塞项:剥离集合与服务端应答器的能力不匹配(症状 (2)(3)(5),我实测)

应答器是 core 钉死的 @xterm/[email protected](packages/core/package.json:69;实例 web-terminal-registry.ts:328,其 onData 在 :506 回灌进 PTY)。我用本机这份 5.5.0 直接量各族查询的应答:

OSC 10;? / OSC 11;? / OSC 4;1;? / OSC 4;1;2;? / OSC 12;?  -> ""(完全不应答)
CSI 6n                                                     -> ESC [ 1 ; 1 R
DECRQM  ?2026;$p                                           -> ESC [ ?2026;0$y
DECRQSS  ESC P $ q ... ESC \                               -> ESC P 0 $ r ESC \

而 TERMINAL_QUERY_SEQUENCE_RE(:85)剥掉的恰是 10|11|4;[0-9]+ 这三族颜色查询。于是这些探针既不再到达浏览器、服务端也答不出来,结果退化成代码里为「无应答器」写明的「查询被丢弃、最多等约 2 秒」——合并基线上它们本可得到应答。这是本 PR 引入的行为回归(Neovim / bat / delta 的背景色探测是直接触发方)。

同一处的另两点:OSC 12 与多索引 OSC 4;1;2;?... 不在交替式里,仍会原样落入 buffer 并在每次重连回放时被浏览器再应答进仍然存活的 shell stdin(即本功能要消除的害处对这两族依旧存在);而剥掉查询等于把回答者从「正在使用的客户端」换成另一份状态的 headless —— 我用随包的 @xterm/[email protected] 对同一输入实测得到 ESC [ ?2026;2$y(识别),服务端给的是 ;0(不识别),应用据此会判定同步输出不可用而放弃使用。

不必等 #11734 的结构化方案,最小修法即可:把剥离集合收窄到「这份应答器确实会答的族」,暂时让 10|11|4(以及本就未剥的 12、多索引 4)继续到达浏览器,恢复合并基线行为;或为这几族补上服务端应答并在用例里钉住。若决定维持现状,请至少把「颜色查询此后不再被任何一侧应答」与 OSC 12/多索引 4 的处理差异写进 :66-84 的注释与 docs/——现在那段注释把这三族描述成已由服务端职责覆盖,与实测不符。

一处缓解自身缺见证(同一线程,顺手补)

把 strip() 里的 partial[0].length <= MAX_HELD_ESCAPE_CHARS 整个删掉(即恢复 R2-1 症状 (1) 里「pending 无上限、每个 chunk 重扫整段累积」的形态)后,48 条用例全部仍绿:256 字符封顶这一条目前没有可失败的见证。请补一条:喂入超过该长度且始终以 ESC ] / ESC P 前缀结尾的输出,断言前缀之外的字节仍然落到 buffer 与 readSnapshot(),并确认去掉封顶会让它变红。

其余

另外 17 条线程(readSnapshot 回放不再携带查询、退出期 releasePtyResources、ConPTY 探测、prepare-package.js 打包面等)逐条对过当前 head,作者回复所述与代码一致,本轮不再重复提出。review-pr 在本 head 仍 pending,属评审机器人自身档,不计入门禁。

…nnot answer

The stateful stripper added here removed the OSC 10/11/12/4 colour queries from
both the scrollback and the live listener, but the pinned @xterm/headless 5.5.0
responder answers none of them: `onData` carries DA/DSR/DECRQM/DECRQSS only,
while `_setOrReportSpecialColor` reports on the internal `_onColor` emitter that
the headless Terminal does not expose (`term.onColor` is undefined) and that
nothing in this file subscribes to. Deleting the family from the browser's
stream as well left a probing program unanswered, where the browser's own
xterm.js 6.0.0 `_handleColorEvent` is the answerer and answered it at the merge
base.

Narrow both regexes to the families the responder actually answers (plus the
never-display-content DA3 / XTVERSION / DECREQTPARM trio that no build answers),
drop the half-covered colour arm from the partial matcher — so the strip set and
the doc block no longer disagree about what the colour family is — and correct
the doc block to state the split. Covered by a new test asserting the whole
family reaches both the live listener and the snapshot untouched, and that
nothing is written back; it fails if the colour arm is restored.

The colour queries that a reconnect replay re-answers are part of the
replay-suppression redesign tracked in #11734.

Co-authored-by: Qwen-Coder <[email protected]>
Patrol-Run: qwen-pr-closeout/jmtyno0zh0n
Preserve raw PTY bytes and limit the Windows server responder to primary DA. Mark snapshots explicitly and restore history into a detached browser terminal while the old terminal continues forwarding user input. Activate live replies at the snapshot write callback, reject incompatible peers, and preserve the parallel color-query regression fix. Refs #11734.

Co-authored-by: Qwen-Coder <[email protected]>
@yiliang114
yiliang114 requested a review from qqqys September 12, 2026 18:05
@yiliang114

Copy link
Copy Markdown
Collaborator Author

@qwen-code /triage

@yiliang114

Copy link
Copy Markdown
Collaborator Author

11643 — state at the current head, and a re-review request

The standing CHANGES_REQUESTED on this PR is from @qwen-code-dev-bot at 2026-09-12T16:54, submitted against head 77257a5. The head has since moved twice; it is now b7934e3 (2026-09-12T17:59).

  • All review threads are resolved — reviewThreads reports 0 unresolved out of 20.
  • The review's single blocking item was thread R2-1 (the strip set removed colour queries that the server-side responder never answers). The remedy the review itself proposed — take the colour family out of the strip set so OSC 10/11/4 keep reaching the browser — landed in d8975fa, after the review was submitted: TERMINAL_QUERY_SEQUENCE_RE loses its OSC alternative and PARTIAL_ESCAPE_SUFFIX_RE loses its OSC arm, so no colour family is stripped on either side. The same commit closed the intra-family inconsistency nit.
  • @qwen-code-ci-bot reviewed head b7934e3 and APPROVED it at 2026-09-12T18:59.

So the change-request is stale: it predates both the fix and the approval. Requesting a fresh review of b7934e39c6 so the verdict reflects the current head — no code change is being made in this pass.

— 巡检 jmtyrycka0u (pr-closeout-sweep)

@wenshao

wenshao commented Sep 12, 2026

Copy link
Copy Markdown
Collaborator

Maintainer verification, round 2 — b7934e39: the replay contract on the real stack, and Windows again at the new head

Round 1 verified the Windows leak fix at 9e54d5ab3b. Since then the head has replaced the server-side query stripper with the replay protocol, so this round covers only that delta — plus the two things every earlier round (mine, the sandbox's, and the author's Chromium component check) left open: a real daemon + real PTY + the built Web Shell, and the Windows DLL-failure paths.

Verdict: no blocking finding at b7934e39c6. The replay contract holds end to end on a real qwen serve driving a real bash, with the daemon-served Web Shell in Chromium, and the Windows half still holds at this head on a real windows-2022 host — including both DLL-failure paths, which nobody had exercised. Non-blocking items are in §3. One pre-existing bug surfaced along the way (§5); it reproduces identically on the merge-base and deserves its own fix.

1 · Real stack on Linux

A TCP proxy between Chromium and the daemon severs the connection on command. The oracle is a small program running inside the terminal that logs every byte reaching the live shell's stdin, so the numbers below are replies actually written into the shell.

Real-stack E2E matrix

  • Reconnect after a transport drop: base writes 6 replies into the live shell — a fresh answer to every query already in scrollback. Head writes 0. After a full page reload with two query batches in scrollback, base writes 12 and head 0. In both cases a new live batch afterwards gets exactly one reply per query.
  • Primary-DA ownership, with a control that can fail:
    • srvDA is the head bundle with useBundledConpty forced true. The real headless responder answers DA1 and the browser receives handlesPrimaryDa:true: DA1 is answered once.
    • noHeadless is the same bundle with loadXtermHeadless() rejecting, so handlesPrimaryDa:false: the browser answers DA1 once.
    • Negative control: the same arm with the browser's suppression removed answers DA1 twice. This shows the oracle does see a double answer.
  • Typing during restoration: keys typed mid-restoration arrive once, and a live batch queued behind the snapshot is answered once.
  • Interrupted restoration: a restoration interrupted by a second drop ends with one terminal showing the newest content, and no page errors.
  • How the restoration window was observed: both of the above were driven with the page's zero-delay timers stretched to 40 ms. The old view was confirmed present before and after the keypress, and at the second cut, so the window was actually observed rather than raced.
  • Closing the tab releases the shell process.
  • Version skew fails loudly:
    • Old Web Shell → new daemon: close 4002, "reload this page", and no PTY spawned.
    • New Web Shell → old daemon: close 4002, "restart the daemon".

What that looks like at a real bash prompt (answers to a query printed at the prompt, then reload, then type a command):

What a user sees

2 · Windows round 2 at b7934e39

Windows round 2

  • Leak: 18 natural exits through this tree's WebTerminalRegistry leave 0 conhost and 0 OpenConsole behind.
  • Ownership on the real backend:
    • Bundled ConPTY emits a DA1 of its own at startup. The server answers it exactly once, before any browser attaches.
    • A live probe inside the console sends DA1, DA2, CPR, DECRQM and OSC 11. All five reach the registry through bundled ConPTY, and the server answers only DA1, which is the ownership split the design describes.
    • Every PTY write was recorded by wrapping node-pty's spawn before the registry loads.
  • conpty.dll removed:
    • The bundled spawn throws synchronously (Cannot find conpty.dll at …), and the inbox retry creates a working shell.
    • Each exit then leaks one conhost (6 terminals → 6, 37.3 MB). That is exactly the cost Risk & Scope discloses.
  • OpenConsole.exe removed: nothing throws. conpty.dll launches the system conhost instead, and nothing leaks.
  • Responder disabled: the prompt is ready in 868–876 ms versus 967–1388 ms with it, with no stall on cmd, Windows PowerShell or pwsh 7.6.5. Same conclusion as round 1, now for all three shells: the responder is insurance, not a latency win on this host.
  • PR unit suites on Windows: core 46 passed / 2 skipped, cli 63 / 2, web-shell 22.

3 · Non-blocking items

  1. Queries emitted while no browser is attached are never answered. In head, 3 batches emitted during a 7 s disconnect got 0 replies after the reconnect. Base re-answered the whole scrollback instead, 54 replies including batches answered long before. That is the right trade-off against injection. The design doc, though, says reconnect history "has" been answered, which is only true for output a browser actually saw. A program that blocks on a CPR/DA reply while the tab is closed or the network is down will not get one after reconnecting. One sentence in docs/design/web-terminal-replay.md would cover it.
  2. New Web Shell ↔ old daemon strands a shell. By the time the client sees the unmarked snapshot and closes with 4002, the old daemon has already created the PTY. That shell lives until idle reclaim (bash under the old daemon: 1 → 2). Sending the {type:'release'} control frame, which old daemons already understand, before closing would free it. This only matters during a mixed-version window.
  3. Nit: the client-side mismatch notice (Terminal protocol changed; restart the daemon and reload this page.) is a hard-coded, uncoloured English string. The neighbouring notices go through t('terminal.notice.*').
  4. Status of round-1 items:
    • Still open: the derived node-pty pins have no assertion in package-assets.test.js (sandbox S-2; not re-measured here).
    • Closed at this head: the responder no longer needs to follow resize, because the only reply it forwards is DA1, which is geometry-independent; scrollback: 0 has been added; the description has been refreshed.
    • The Tested-on table can now mark Windows and Linux with these two rounds.

4 · Correction to sandbox S-3 ("~181 MB per live Windows terminal")

This is not a cost that scales with output volume.

  • Cause: the sandbox's buffer scenario emits one unterminated OSC 8 (ESC]8;;https://example.com) before its ladder. Headless xterm then stays in OSC-string state and accumulates every later byte as payload, bounded by its 10 MB PAYLOAD_LIMIT.
  • Proof from their own harness: re-running the sandbox's buffer scenario here gives win32 257.7 MB above baseline with that line and 13.1 MB without it (linux: 13.0 MB either way).
  • On the product path: the real registry with a real PTY and 8 MB of output costs +2.3 MB (wrapped lines) or +1.4 MB (one unbroken line) over the no-responder arm. A standalone responder retains about 0.55 MB after draining 8 MB.
  • Scope: the unterminated-OSC case is real but pathological. It is bounded, freed at exit, and the browser's own xterm has the same property.

5 · Pre-existing, not caused by this PR: one DECRQM freezes the built Web Shell terminal

DECRQM freeze

  • Cause:
    • In both the base and head builds, xterm's requestMode() ships as (void 0||(n={})) with its let declaration dropped.
    • A minimal repro isolates esbuild 0.25.6 lowering r ||= {} for the es2020 target under minify. Target es2021 and esbuild 0.28.2 are both fine.
    • A vite build --target es2021 of this web-shell contains 0 such sites.
  • What it does:
    • Every DECRQM (CSI ? Ps $ p) throws ReferenceError: n is not defined. The throw stalls xterm's write queue, so nothing printed afterwards renders.
    • I confirmed the stall on real @xterm/xterm 6.0.0: with a throwing handler, that write's callback and all later writes never run.
  • End to end, both builds:
    • A DA1 control gets a 7-byte reply and output keeps rendering.
    • DECRQM gets 0 reply bytes, and nothing after it renders.
    • A reload does not recover. Base re-renders up to the query and freezes again; head shows a blank pane, because the restoration's write callback never fires.
  • Windows: DECRQM reaches the browser through both ConPTY backends there too.
  • Effect on this PR: test-plan step 2 cannot pass for mode queries in the shipped bundle; the colour/OSC queries do work.
  • Not a blocker here. It is a one-line build fix (build.target: 'es2021' in packages/web-shell) that deserves its own PR.

Gates at head

  • web-terminal-registry + conpty-host: 48/48.
  • routes/terminal + agent-view/pty-host: 65/65.
  • TerminalPanel: 22/22.
  • package-assets: 36 passed, 1 skipped.
  • eslint --max-warnings 0 on the 11 changed TS/JS files and prettier --check: clean.
Environment, arms and how to reproduce

Linux lane

  • Platform: Debian 13 (kernel 6.12), Node 22.22.2, Chromium 145.0.7632.6 via Playwright, @xterm/xterm 6.0.0, @xterm/headless 5.5.0, vite 5.4.21 / esbuild 0.25.6.
  • Trees: two worktrees, head b7934e39 and merge-base ea10c604. The PR changes no manifest or lockfile, so both share one node_modules.
  • Builds: each tree is built package by package, then node esbuild.config.js and copy_bundle_assets.js. Every daemon serves its own built Web Shell.
  • Mutation arms:
    • Each is a hard-linked copy of the head dist/ with exactly one line edited: useBundledConpty forced true; loadXtermHeadless() rejected; or the Web Shell's registerCsiHandler({final:"c"},…) returning false.
    • Every edit was checked with an exact-count grep, and the originals were checked intact.
  • Round-2 query corpus: excludes DECRQM, because the §5 freeze contaminated the first pass.

Windows lane

  • Runner: GitHub-hosted windows-2022 (Windows Server 2022 10.0.20348), npm ci at head.
  • Harness: bundled with esbuild, with @lydell/node-pty and @xterm/headless left external so they load exactly as the product loads them.
  • Base arm: the same harness after git checkout ea10c604 -- packages/core/src packages/cli/src scripts. Its registry loop segfaulted on this runner (exit 139), so the base leak numbers are round 1's.
  • Workflow: probe/pr11643r2-run1 on my fork, run 34716313011.

Harness sources are on the assets-pr11643 branch under pr11643-r2/harness/. They include:

  • the stdin recorder, the E2E drivers and the TCP cut proxy;
  • the xterm stall and esbuild repros;
  • the heap measurements.
中文版

维护者验证第 2 轮 —— b7934e39:真实栈上的回放协议,以及新 head 上再测一遍 Windows

第 1 轮在 9e54d5ab3b 上验证了 Windows 泄漏修复。之后 head 用回放协议替换了服务端的查询剥离器,所以本轮只覆盖这部分增量,再补上此前各轮(我的、沙箱的、作者的 Chromium 组件检查)都没覆盖到的两块:真实 daemon + 真实 PTY + 构建产物 Web Shell,以及 Windows 下 DLL 失败的两条回退路径。

结论:b7934e39c6 上没有阻塞项。 真实 qwen serve 驱动真实 bash、Chromium 打开 daemon 自带的 Web Shell,回放协议端到端成立。在真实 windows-2022 主机上,Windows 这一半在新 head 上同样成立,此前没人跑过的两条 DLL 失败路径也在内。非阻塞项见 §3。验证过程中还发现一个已有问题(§5),在 merge-base 上完全一样能复现,值得单独修。

1 · Linux 真实栈

Chromium 与 daemon 之间架一个 TCP 代理,可以按指令切断连接。判定依据是一个运行在终端里面的小程序,它记录到达活动 shell stdin 的每一个字节,所以下面的数字是真正写进 shell 的应答。

  • 断连后重连: base 往活着的 shell 写入 6 条应答,也就是对 scrollback 里每个历史查询重新作答一次;head 写入 0 条。scrollback 里有两批查询时整页刷新,base 写入 12 条,head 0 条。之后的新实时批次在两边都是每个查询恰好应答一次。
  • primary DA 的归属,带一个能失败的对照:
    • srvDA:head bundle 里 useBundledConpty 强制为 true。真实 headless 应答器负责 DA1,浏览器收到 handlesPrimaryDa:true。结果 DA1 被应答一次。
    • noHeadless:同一 bundle 里让 loadXtermHeadless() reject,handlesPrimaryDa:false,由浏览器应答 DA1,也是一次。
    • 负对照:在上一臂基础上去掉浏览器的抑制,DA1 被应答两次。这说明判定确实能发现重复应答。
  • 恢复期间输入: 按键到达一次;排在快照后面的实时批次被应答一次。
  • 打断恢复: 被第二次断连打断的恢复,最后只剩一个终端、显示最新内容、没有页面错误。
  • 如何观测到恢复窗口: 上面两项都是把页面的零延迟计时器拉长到 40 ms 后测的。按键前后、以及第二次切断的那一刻,都确认了旧视图仍然在,所以是真正落在恢复窗口里,而不是赌时序。
  • 关闭页签后 shell 进程被释放。
  • 版本错配明确报错:
    • 旧 Web Shell → 新 daemon:关闭码 4002,提示 "reload this page",不会创建 PTY。
    • 新 Web Shell → 旧 daemon:关闭码 4002,提示 "restart the daemon"。

第二张图是在真实 bash 提示符下的效果:在提示符执行打印查询的命令,查询的应答落入输入行,Ctrl+C 后刷新页面,再输入命令。base 刷新后应答被重新注入提示符、命令被搅乱,head 的提示符干净、命令正常执行。

2 · Windows 第 2 轮(b7934e39)

  • 泄漏: 经本仓库 WebTerminalRegistry 自然退出 18 次,残留 0 个 conhost、0 个 OpenConsole。
  • 真实后端上的应答归属:
    • bundled ConPTY 启动时会自己发出一个 DA1。服务端在任何浏览器连接之前就应答它,而且恰好一次。
    • 在控制台里跑一个实时探测,发出 DA1、DA2、CPR、DECRQM、OSC 11。五个查询都经 bundled ConPTY 到达 registry,服务端只应答 DA1,与设计描述的归属划分一致。
    • PTY 的每次写入都有记录,方法是在 registry 加载前包装 node-pty 的 spawn。
  • 删除 conpty.dll:
    • bundled spawn 同步抛错(Cannot find conpty.dll at …),inbox 重试成功创建出可用的 shell。
    • 此后每次退出泄漏一个 conhost(6 个终端 → 6 个,37.3 MB),与 Risk & Scope 披露的代价完全一致。
  • 删除 OpenConsole.exe: 不抛错,conpty.dll 改为启动系统 conhost,没有泄漏。
  • 关闭应答器: 提示符就绪 868–876 ms,开启时是 967–1388 ms;cmd、Windows PowerShell、pwsh 7.6.5 都不卡顿。与第 1 轮结论相同,而且这次覆盖了三种 shell:在这台主机上应答器是保险,不带来延迟收益。
  • PR 单测在 Windows 上: core 46 通过 / 2 跳过,cli 63 / 2,web-shell 22。

3 · 非阻塞项

  1. 没有浏览器连接时发出的查询永远得不到应答。 head 上断开 7 秒期间发出 3 批查询,重连后应答 0 条。base 则把整个 scrollback 重新作答一遍,一共 54 条,里面包括早就答过的批次。为了防注入,这个取舍是对的。但设计文档说重连历史"已经"被应答过,这只对浏览器实际看到过的输出成立。如果某个程序在页签关闭或网络中断期间阻塞等待 CPR/DA 应答,重连后也等不到。建议在 docs/design/web-terminal-replay.md 里补一句。
  2. 新 Web Shell ↔ 旧 daemon 会遗留一个 shell。 客户端发现快照未标记、以 4002 关闭时,旧 daemon 已经创建了 PTY。这个 shell 会一直留到空闲回收(旧 daemon 下的 bash 数 1 → 2)。关闭前发一个 {type:'release'} 控制帧(旧 daemon 本来就认识)就能释放。只在新旧版本混用期间出现。
  3. 小问题: 客户端的版本不匹配提示(Terminal protocol changed; restart the daemon and reload this page.)是硬编码、无颜色的英文字符串。相邻的其它提示都经过 t('terminal.notice.*')。
  4. 第 1 轮各项的状态:
    • 仍未解决:派生出来的 node-pty pin 在 package-assets.test.js 里没有断言(沙箱 S-2;本轮未重测)。
    • 本 head 已关闭:应答器不再需要跟随 resize,因为它唯一转发的 DA1 与几何无关;已加上 scrollback: 0;PR 描述已刷新。
    • "测试平台"表里 Windows 和 Linux 现在可以凭这两轮打勾。

4 · 更正沙箱 S-3("每个活跃 Windows 终端约 181 MB")

这不是随输出量增长的开销。

  • 原因: 沙箱的 buffer 场景在阶梯开始前先发了一个未终结的 OSC 8(ESC]8;;https://example.com)。headless xterm 于是一直停在 OSC 字符串状态,把后面所有字节都当作 payload 累积,上限是它的 10 MB PAYLOAD_LIMIT。
  • 用它自己的 harness 证明: 在本机重跑沙箱的 buffer 场景,带着这一行时 win32 比基线高 257.7 MB,删掉后只有 13.1 MB(linux 两种情况都是 13.0 MB)。
  • 产品路径上的实测: 真实 registry + 真实 PTY、输出 8 MB,比无应答器臂多 +2.3 MB(折行输出)或 +1.4 MB(一整行不换行)。单独一个应答器在排空 8 MB 后常驻约 0.55 MB。
  • 影响范围: 未终结 OSC 的情况确实存在,但属于病态输入,有上限,退出时释放;浏览器自己的 xterm 也有同样的特性。

5 · 已有问题,不是本 PR 引入的:一个 DECRQM 就会让构建产物 Web Shell 的终端永久冻结

  • 原因:
    • base 和 head 的构建产物里,xterm 的 requestMode() 都变成了 (void 0||(n={})),对应的 let 声明被丢掉了。
    • 最小复现把问题定位到 esbuild 0.25.6:在 es2020 target 下开启 minify 时,它会把 r ||= {} 降级成这种形式。改用 es2021 target,或者用 esbuild 0.28.2,都没有问题。
    • 用 vite build --target es2021 重新构建这个 web-shell 后,这类位置数为 0。
  • 后果:
    • 每个 DECRQM(CSI ? Ps $ p)都会抛出 ReferenceError: n is not defined。这个异常会让 xterm 的写队列停住,之后输出的任何内容都不再渲染。
    • 我在真实 @xterm/xterm 6.0.0 上确认了这一点:处理器抛异常后,那次写入的回调和之后的所有写入都不会再执行。
  • 两个构建的端到端结果:
    • DA1 对照得到 7 字节应答,后续输出正常渲染。
    • DECRQM 得到 0 字节应答,之后的内容一律不渲染。
    • 刷新也恢复不了:base 重新渲染到该查询处再次冻结;head 显示空白面板,因为恢复写入的回调永远不会触发。
  • Windows: DECRQM 在两种 ConPTY 后端上都会到达浏览器,同样受影响。
  • 对本 PR 的影响: 在实际发布的 bundle 里,测试计划第 2 步中的模式查询无法通过;颜色/OSC 查询正常。
  • 不阻塞本 PR。 修复只需一行构建配置(在 packages/web-shell 里设 build.target: 'es2021'),值得单独提一个 PR。

head 上的门禁

  • web-terminal-registry + conpty-host:48/48。
  • routes/terminal + agent-view/pty-host:65/65。
  • TerminalPanel:22/22。
  • package-assets:36 通过、1 跳过。
  • 11 个改动的 TS/JS 文件上 eslint --max-warnings 0 与 prettier --check:干净。

(环境、各对照臂与复现方法见英文正文的折叠块;证据图与 harness 源码托管在 wenshao/qwen-code 的 assets-pr11643 分支 pr11643-r2/ 目录下。)

🤖 Generated with Claude Code — Claude Opus 5

@wenshao
wenshao added this pull request to the merge queue Sep 13, 2026
Merged via the queue into main with commit b5567bb Sep 13, 2026
89 of 90 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants