From 1c79b718bfd9abad76dd8717862cbe1763cf0173 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sun, 15 Nov 2026 12:44:20 +0800 Subject: [PATCH] =?UTF-8?q?feat(desktop):=20=E6=89=98=E7=AE=A1=20tcpAnnoun?= =?UTF-8?q?ced=20=E8=B0=83=E8=AF=95=E9=80=82=E9=85=8D=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 插件声明 tcpAnnounced 传输的调试适配器(例如 Delve 的 `dlv dap`) 现在由宿主拉起进程,按 Core 的 debug.adapters.readAnnouncement 逐行读取它声明的输出流,读到回环端点后用 Core 驱动的 TCP 生命周期连接。 - 公告行不进调试控制台,其余输出照常显示;单行超过 64 KiB 不缓存。 - 传输先于进程启动,Core 默认的 10 秒发现期限同时覆盖进程启动与公告。 - 公告前退出、公告非本机地址、超时都以明确原因结束并停止进程; 新增词条 desktop.debug.notAnnounced(中英)。 - 用户停止时先把 DAP disconnect 排空到网络栈,再停止进程树。 - PINNED_CORE_REVISION 升到 Lithe-core-rust main 的 a58e07e(#47 合入提交)。 - 新增无头截图场景 TestVisualDebugAnnouncedAdapterExitedFirst; debugPluginHarnessOn 拆出 debugPluginOptions 供它复用,行为不变。 - 功能矩阵与三份 Agent Note 去掉 tcpAnnounced 未实现的说法,只保留 tcpPort。 Refs #1953 --- ...026-10-27-debug-tcp-transport-lifecycle.md | 8 +- ...a-java-admission-run-debug-output-links.md | 2 +- ...ified-debug-engine-and-adapter-registry.md | 2 +- .../internal/core/debug_announcement_test.go | 56 +++ desktop/internal/core/debug_transport.go | 38 +- desktop/internal/i18n/debug_messages.go | 2 + desktop/internal/i18n/shared.generated.go | 2 + desktop/internal/pluginhost/pluginhost.go | 5 +- desktop/internal/pluginservice/debug.go | 5 +- desktop/internal/workbench/app.go | 1 + desktop/internal/workbench/debug.go | 24 +- .../internal/workbench/debug_adapter_start.go | 7 +- desktop/internal/workbench/debug_announced.go | 171 ++++++++ .../workbench/debug_announced_test.go | 411 ++++++++++++++++++ desktop/internal/workbench/debug_launch.go | 7 +- desktop/internal/workbench/debug_start.go | 121 ++++-- desktop/internal/workbench/debug_tcp_test.go | 13 +- .../internal/workbench/visual_capture_test.go | 51 +++ scripts/desktop/build-desktop-core.sh | 6 +- shared/i18n/locales/en-US.json | 1 + shared/i18n/locales/zh-CN.json | 1 + shared/i18n/messages.json | 9 +- .../features/debug-tcp-transport.json | 12 +- .../features/plugin-debug-adapters.json | 8 +- 24 files changed, 900 insertions(+), 63 deletions(-) create mode 100644 desktop/internal/core/debug_announcement_test.go create mode 100644 desktop/internal/workbench/debug_announced.go create mode 100644 desktop/internal/workbench/debug_announced_test.go diff --git a/.agents/notes/implemented/architecture/2026-10-27-debug-tcp-transport-lifecycle.md b/.agents/notes/implemented/architecture/2026-10-27-debug-tcp-transport-lifecycle.md index 65bbcd7ac6..ba82824c94 100644 --- a/.agents/notes/implemented/architecture/2026-10-27-debug-tcp-transport-lifecycle.md +++ b/.agents/notes/implemented/architecture/2026-10-27-debug-tcp-transport-lifecycle.md @@ -27,6 +27,7 @@ - 停止、EOF、读写失败和超时先由 Core 递增代次,再由 `close` 效果取消解析任务、全部剩余计时器和 socket,清空回调与缓冲。旧连接回调以及旧写入完成不能影响新连接。显式停止由会话层投影结果,传输不重复发送终止通知。失败时 Core 先给出 `close`、`reportFailure`、`notifyTermination`;宿主执行每个效果前核对代次,观察者在错误输出回调里重新 `start` 会使剩余的旧终止通知作废。已处于停止状态的传输再收到 `stop` 则被 Core 忽略,所以观察者在错误输出回调里调用 `stop()` 时终止通知仍然送达,且只送达一次;旧实现把这种情况也当作“生命周期已被替换”而吞掉通知,这个差异是有意接受的。 - 宿主若发现 Core 调用本身失败(桥接故障而不是生命周期结果,包含 `send`),在本地静默拆除 socket 与计时器、释放登记,并向所有者报告一次,不让资源在故障后残留。释放会重置 Core 内部的代次与计时器编号,重启前必须换用新的登记 ID,并在宿主回调入口同时核对登记 ID;不能只依赖重置后的代次。故障观察者重启后也不得再收到旧终止通知。 - `DebugAdapterConnectionProviding` 是未来代理的替换点:返回尚未启动、可取消的连接,握手纳入已有启动期限;停止必须释放它自己拥有的资源。本次唯一实现为直连,不提前增加代理配置、密码或进程字段。 +- 插件声明 `tcpAnnounced` 的适配器复用同一条生命周期,只把端点发现换成“读进程公告”:宿主拉起插件声明的适配器进程(stdin 不接管),把 `launch.endpoint` 声明的输出流按行切开,每一整行(去掉行尾的 `\r\n`)交给 Core 的 `debug.adapters.readAnnouncement`。Core 判定这一行是 `none`(不是公告)、`announced`(回环主机和端口)还是 `invalid`(公告了非本机地址或非法端口),哪一行算公告、哪些地址允许连接都只由 Core 决定。公告行本身不进调试控制台,其余输出(含公告之前的和另一个流的)照常显示;单行超过 64 KiB 不再缓存,原样交给控制台。传输先于进程启动,所以 Core 默认的 10 秒端点发现期限同时覆盖进程启动和公告;进程在公告前退出时以“还没输出监听端口就退出”结束,公告无效时以端点无效结束,两者和超时都会停止进程。进程用不随启动请求取消的上下文启动,归会话所有:用户停止时先把 DAP disconnect 排空到网络栈,再停止进程树(`buildprocess.Stop`:Unix 先向进程组发 SIGTERM,宽限期后强制结束;Windows 直接结束 Job Object 里的整棵树);其他结束方式直接关闭连接并停止进程。宿主实现在 `desktop/internal/workbench/debug_announced.go`。 - `tcpLanguageServer` 仍只解析同插件语言服务器返回的回环端口。外部入口在 Debug 的更多操作中,由当前文件选择已安装的调试提供方(当前文件没有提供方时菜单项不可用),单独填写 DAP 地址、请求种类和适配器 JSON 参数;不猜测语言协议,不启动本地替代进程。连接对话框在连接启动前保持打开:被拒绝的地址、未获批准的确认、已有活动会话、连接失败或初始化超时都留在对话框里显示原因,已填的主机、端口和参数不丢失,表单通过 Application 层的 `ExternalDebugAdapterConnection` 等待会话越过初始化阶段,而不是把同步 `start` 返回视为网络连接成功。用户取消或关闭表单会停止本次尝试的会话 ID,即使此时已选中另一会话也不会误停它;已有初始化期限负责等待上界,表单不再添加第二套网络超时。Core 先校验地址,非回环端点每次连接前确认,明确警告裸 TCP 没有加密或认证;确认时间不计入网络建连期限。 - 外部服务只归用户所有。关闭 socket 本身不停止共享语言服务器、外部适配器或用户隧道;目标程序的结束策略由 DAP 协议层负责,`attach` 断开使用 `terminateDebuggee=false`,`launch` 断开则可能结束该会话启动的程序。不要把字节流所有权等同于目标程序的 DAP 生命周期。配置不持久化,源码映射继续由适配器参数表达。 @@ -45,7 +46,7 @@ ## 后果 -普通 TCP 连接可独立测试,stdio 原有路径不变,用户提供的外部地址与语言服务器端口遵守各自的信任边界。代价是外部连接需要用户了解其适配器参数,没有保存配置、通路自动建立或断线恢复;插件 `tcpPort`、`tcpAnnounced` 的托管进程模式也仍未实现。 +普通 TCP 连接可独立测试,stdio 原有路径不变,用户提供的外部地址与语言服务器端口遵守各自的信任边界。代价是外部连接需要用户了解其适配器参数,没有保存配置、通路自动建立或断线恢复。插件 `tcpAnnounced` 的托管进程已接入;`tcpPort`(宿主先分配端口再交给进程)仍未实现,声明它的适配器在启动进程前被拒绝。 此处代码实现不等于所有语言适配器都已验收。真实 JVM、debugpy、GDB 的兼容性仍需对应插件和端到端场景证明;Windows 共享地址校验与这套生命周期状态机,但尚无宿主 TCP 实现,接入时只需实现 socket、解析和计时器这些 I/O 并执行 Core 返回的效果,状态机本身不需要再写一遍。 @@ -54,7 +55,8 @@ ## 验证 - `./scripts/desktop/desktop-go.sh test ./internal/workbench -run 'DebugTransport'`:可控时钟、队列预算、取消与晚到回调、外部表单初始化成功/失败/超时与按会话取消,以及回环监听器上的真实字节往返。 -- `./scripts/desktop/desktop-go.sh test ./internal/core -run 'Debug'`:调试会话的启动、停止与传输登记。 +- `./scripts/desktop/desktop-go.sh test ./internal/core -run 'Debug'`:调试会话的启动、停止与传输登记,以及逐条重放 Core 的 `rust/fixtures/debug/adapter-announcements-v1.json`。 +- `./scripts/desktop/desktop-go.sh test ./internal/workbench -run 'DebugAnnounce'`:真实子进程公告回环端口后命中断点、暂停、继续,停止时对端先收到 disconnect 再看到进程结束;公告前退出、公告远程地址、一直不公告三种失败都停止进程;按行切分、分流、超长行与等待取消的单元测试。 - 在 Core 仓库运行 `cargo test -p lithe-core debug_adapter_endpoint` 和 `cargo test -p lithe-core dap_endpoint_contract`:共享 fixture 校验及 JSON dispatcher 边界。 - 在 Core 仓库运行 `cargo test -p lithe-core transport_lifecycle`:状态机单元测试,并逐步回放 `Lithe-core-rust/rust/fixtures/debug/transport-lifecycle-v1.json` 中的场景。新平台实现同一份 fixture 即可证明规则一致。 - `./scripts/desktop/verify/verify-runtime-bundle-immutability.sh`、`./scripts/agent-notes/verify-agent-notes.sh`。 @@ -63,6 +65,8 @@ - `desktop/internal/core/debug_transport.go` - `desktop/internal/workbench/debug_transport_test.go` +- `desktop/internal/workbench/debug_announced.go` +- `desktop/internal/workbench/debug_announced_test.go` - Lithe-core-rust 锁定修订:[rust/lithe-core/src/debug/endpoint.rs](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/0ffd327b4329261e393b08ed76fbd134b4dd17e9/rust/lithe-core/src/debug/endpoint.rs) - Lithe-core-rust 锁定修订:[rust/lithe-core/src/debug/transport_lifecycle.rs](https://github.com/Lithe-IDEA/Lithe-core-rust/blob/0ffd327b4329261e393b08ed76fbd134b4dd17e9/rust/lithe-core/src/debug/transport_lifecycle.rs) diff --git a/.agents/notes/implemented/architecture/2026-11-10-viva-java-admission-run-debug-output-links.md b/.agents/notes/implemented/architecture/2026-11-10-viva-java-admission-run-debug-output-links.md index eae6fdb882..67c0dfec3f 100644 --- a/.agents/notes/implemented/architecture/2026-11-10-viva-java-admission-run-debug-output-links.md +++ b/.agents/notes/implemented/architecture/2026-11-10-viva-java-admission-run-debug-output-links.md @@ -33,7 +33,7 @@ Java Support 的插件清单要求宿主提供 `settings` 2、`outputLinkMatcher ## 已知缺口 -- `debug.target: launch`、launch.json 导入、`tcpPort` / `tcpAnnounced`(插件进程托管)、远程 attach 的路径映射输入。 +- `debug.target: launch`、launch.json 导入、`tcpPort`(宿主分配端口的插件进程托管)、远程 attach 的路径映射输入。`tcpAnnounced` 已接入,见 `2026-10-27-debug-tcp-transport-lifecycle.md`。 - Build 输出区只在检测到构建系统后显示;运行视图不受影响。 - 运行视图和 Debug 表单已在 Page 迁移中改为 Viva Page(`workbench/runpanels.go`;工作台根窗口改为一个 Page 后它们是根 Page 调用的组件,见 `2026-11-10-workbench-root-page-and-viva-upgrade.md`)。 diff --git a/.agents/notes/proposed/architecture/2026-10-25-unified-debug-engine-and-adapter-registry.md b/.agents/notes/proposed/architecture/2026-10-25-unified-debug-engine-and-adapter-registry.md index fa19133125..2988bac7dd 100644 --- a/.agents/notes/proposed/architecture/2026-10-25-unified-debug-engine-and-adapter-registry.md +++ b/.agents/notes/proposed/architecture/2026-10-25-unified-debug-engine-and-adapter-registry.md @@ -142,7 +142,7 @@ P3 的声明层已在 Rust Core 落地:`plugin.json.debugAdapters[]` 作为插 - Core 提供 `languageServerLaunchPlan` 的 `debugAdapterID` 选择器和 `debug.adapters.startArguments` 命令;后者按 manifest、adapterID、request 与事实(注册代次、目标、运行时选择)返回启动参数,拒绝码为 `debug.provider.stale`、`debug.request.unsupported`、`debug.runtime.stale`、`debug.target.invalid`、`plugin.launch.unavailable`。 - 宿主启用模块 `.debug-adapters`(只承载启用、隔离与安全模式状态)。宿主按语言 ID 建立插件适配器会话;Java 等内置语言优先,宿主不按插件名字分支。 - 启动计划在会话启动时才解析,因为启动依赖工作区;被拒绝的计划就是启动错误。`adapterID` 声明时默认等于 `id`,会话创建时即需要(DAP `initialize.adapterId`),所以随描述符提前提供。 -- 适配器可执行文件只允许来自插件包或 `systemCommand`。桌面端目前只接入 `stdio` 和 `tcpLanguageServer` 两种传输(见 `desktop/internal/workbench/debug_start.go` 的 `debugTransportServed`);`tcpPort`、`tcpAnnounced` 和 `runSelectedRuntime` 还没有接入宿主,之后再做。 +- 适配器可执行文件只允许来自插件包或 `systemCommand`。桌面端目前接入 `stdio`、`tcpAnnounced` 和 `tcpLanguageServer` 三种传输(见 `desktop/internal/workbench/debug_start.go` 的 `debugTransportServed`,`tcpAnnounced` 在 `debug_announced.go`);`tcpPort` 和 `runSelectedRuntime` 还没有接入宿主。 - 生命周期与所有权:适配器进程归会话,随会话停止。适配器状态目录由平台存储 adapter 提供,位于插件状态目录下的 `debug-adapters/`,不写入插件包或安装目录,不影响代码签名和 Sparkle 增量更新;`${workspaceStateDir}` 按工作区摘要隔离。被调试程序的启动配置由 `startArguments` 生成,宿主只在没有内置适配器处理时回落到它。 P4 的纵向验收用 `lldb-dap` 推进:官方 LLDB 插件(`io.github.lithe-idea.lldb-debug`,仓库 [lithe-plugin-lldb](https://github.com/Lithe-IDEA/lithe-plugin-lldb))已作为预发布收录在 Lithe Store,需要支持 API 4 的 Lithe 才能安装;必选层全流程的验收结果还没有记录,不算 P4 完成。这一轮在契约里补了三件事,全部在尚未发布的 API 4 / `debugAdapters` v1 内,没有已发布的契约被改动: diff --git a/desktop/internal/core/debug_announcement_test.go b/desktop/internal/core/debug_announcement_test.go new file mode 100644 index 0000000000..03ad7273d2 --- /dev/null +++ b/desktop/internal/core/debug_announcement_test.go @@ -0,0 +1,56 @@ +package core + +import ( + "encoding/json" + "errors" + "testing" +) + +// TestDebugAnnouncementFollowsTheContractFixture reads every line of the shared +// announcement fixture through the typed wrapper: a case with a result must read +// exactly that, a case without one must fail as an invalid request. A case whose +// request does not have exactly the endpoint, stream and line fields cannot be +// sent through the wrapper, so Core's own tests cover it instead. +func TestDebugAnnouncementFollowsTheContractFixture(t *testing.T) { + var fixture struct { + Cases []struct { + Name string `json:"name"` + Input map[string]json.RawMessage `json:"input"` + Result *DebugAnnouncement `json:"result"` + } `json:"cases"` + } + if err := json.Unmarshal(readDebugFixture(t, "adapter-announcements-v1.json"), &fixture); err != nil { + t.Fatal(err) + } + if len(fixture.Cases) == 0 { + t.Fatal("the announcement fixture has no cases") + } + ctx := debugContext(t) + client := NewClient() + for _, item := range fixture.Cases { + t.Run(item.Name, func(t *testing.T) { + var stream, line string + endpoint, hasEndpoint := item.Input["endpoint"] + rawStream, hasStream := item.Input["stream"] + rawLine, hasLine := item.Input["line"] + if len(item.Input) != 3 || !hasEndpoint || !hasStream || !hasLine || + json.Unmarshal(rawStream, &stream) != nil || json.Unmarshal(rawLine, &line) != nil { + t.Skip("the wrapper always sends exactly the endpoint and the stream and line strings") + } + got, err := client.ReadDebugAnnouncement(ctx, endpoint, stream, line) + if item.Result == nil { + var coreErr *Error + if !errors.As(err, &coreErr) || coreErr.Code != CodeInvalidRequest { + t.Fatalf("reading = %+v, %v; want an invalid_request error", got, err) + } + return + } + if err != nil { + t.Fatal(err) + } + if got != *item.Result { + t.Fatalf("reading = %+v, want %+v", got, *item.Result) + } + }) + } +} diff --git a/desktop/internal/core/debug_transport.go b/desktop/internal/core/debug_transport.go index 50eca542b5..33d60bab0f 100644 --- a/desktop/internal/core/debug_transport.go +++ b/desktop/internal/core/debug_transport.go @@ -1,6 +1,9 @@ package core -import "context" +import ( + "context" + "encoding/json" +) // DebugTransportEvent is one platform event applied to an IDE-to-adapter byte // stream lifecycle. Type selects which of the other fields Core requires; a @@ -77,3 +80,36 @@ func (c *Client) DebugTransportRelease(ctx context.Context, transportID string) TransportID string `json:"transportId"` }{transportID}, nil) } + +// DebugAnnouncement is Core's reading of one output line of a tcpAnnounced +// adapter. Status is "none" for a line that does not announce the endpoint, +// "announced" with the loopback Host and Port to connect to, or "invalid" with +// the Reason ("malformed" or "notLoopback") the announced endpoint is refused. +type DebugAnnouncement struct { + Status string `json:"status"` + Host string `json:"host,omitempty"` + Port int `json:"port,omitempty"` + Reason string `json:"reason,omitempty"` +} + +// ReadDebugAnnouncement asks Core whether line, read from stream ("stdout" or +// "stderr") of a tcpAnnounced adapter's process without its line break, +// announces the adapter's endpoint. endpoint is the launch plan's +// `debugAdapter.endpoint`, passed unchanged: Core owns which line is the +// announcement and which endpoints may be connected to. +func (c *Client) ReadDebugAnnouncement(ctx context.Context, endpoint json.RawMessage, stream, line string) (DebugAnnouncement, error) { + const command = "debug.adapters.readAnnouncement" + var announcement DebugAnnouncement + if err := c.Execute(ctx, command, struct { + Endpoint json.RawMessage `json:"endpoint"` + Stream string `json:"stream"` + Line string `json:"line"` + }{endpoint, stream, line}, &announcement); err != nil { + return DebugAnnouncement{}, err + } + switch announcement.Status { + case "none", "announced", "invalid": + return announcement, nil + } + return DebugAnnouncement{}, newParseError(command, "invalid announcement reading", "") +} diff --git a/desktop/internal/i18n/debug_messages.go b/desktop/internal/i18n/debug_messages.go index 3871b6aac2..9bbee03b32 100644 --- a/desktop/internal/i18n/debug_messages.go +++ b/desktop/internal/i18n/debug_messages.go @@ -55,6 +55,7 @@ type DebugMessages struct { Reload string BufferLimit string InvalidEndpoint string + NotAnnounced string // RemotePrompt asks whether to attach to a debuggee that is not local. RemotePrompt func(endpoint string) string // ConnectFailed reports a failed connection to the debug adapter. @@ -131,6 +132,7 @@ func debugMessages(language Language) DebugMessages { Reload: Shared(language, "desktop.debug.reload"), BufferLimit: Shared(language, "desktop.debug.bufferLimit"), InvalidEndpoint: Shared(language, "desktop.debug.invalidEndpoint"), + NotAnnounced: Shared(language, "desktop.debug.notAnnounced"), RemotePrompt: func(endpoint string) string { return SharedFormat(language, "desktop.debug.remotePrompt", map[string]string{"endpoint": endpoint}) }, diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 1fc68855e6..2ac03fe6f9 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -306,6 +306,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.debug.noFrames": "No stack frames", "desktop.debug.noMemory": "The adapter cannot read memory for this frame.", "desktop.debug.noVariables": "Pause the debuggee to inspect its variables.", + "desktop.debug.notAnnounced": "The debug adapter exited before printing the port it listens on.", "desktop.debug.openFrame": "Open the frame's source location", "desktop.debug.pause": "Pause", "desktop.debug.paused": "Paused", @@ -2896,6 +2897,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.debug.noFrames": "没有栈帧", "desktop.debug.noMemory": "适配器无法读取当前栈帧的内存。", "desktop.debug.noVariables": "暂停后在这里查看变量。", + "desktop.debug.notAnnounced": "调试适配器还没输出它监听的端口就退出了。", "desktop.debug.openFrame": "打开栈帧的源码位置", "desktop.debug.pause": "暂停", "desktop.debug.paused": "已暂停", diff --git a/desktop/internal/pluginhost/pluginhost.go b/desktop/internal/pluginhost/pluginhost.go index 6dd3dba3c6..919a16c5f2 100644 --- a/desktop/internal/pluginhost/pluginhost.go +++ b/desktop/internal/pluginhost/pluginhost.go @@ -107,8 +107,9 @@ type Capabilities map[string][]int // runs the plan in a staging directory. // - settings: pages per language and build system, sections, every control // type, the project layer, setting effects and page buttons. -// - debugAdapters: stdio adapters and adapters inside the plugin's language -// server over loopback TCP, launch and attach (a remote host after the user +// - debugAdapters: stdio adapters, adapter processes that print the loopback +// TCP endpoint they listen on (tcpAnnounced) and adapters inside the +// plugin's language server over loopback TCP, launch and attach (a remote host after the user // confirms it), argument and environment bindings, features and defaults. // - outputLinkMatchers: Build, Run and Test console lines become links at the // ranges Core finds; a matcher with resolve asks the backend on click. diff --git a/desktop/internal/pluginservice/debug.go b/desktop/internal/pluginservice/debug.go index 7d04518c3f..0ee784ee2b 100644 --- a/desktop/internal/pluginservice/debug.go +++ b/desktop/internal/pluginservice/debug.go @@ -23,7 +23,7 @@ type DebugPlugin struct { } // DebugAdapterDeclaration is the subset of one `debugAdapters` entry the host -// uses to start a stdio adapter and present it. Adapter behaviour stays in +// uses to start an adapter and present it. Adapter behaviour stays in // Core; the host never interprets DAP payloads. type DebugAdapterDeclaration struct { ID string @@ -38,7 +38,8 @@ type DebugAdapterDeclaration struct { // ConfigurationTypes are the imported launch.json types the adapter answers to. ConfigurationTypes []string // Endpoint names the language server and command a tcpLanguageServer adapter - // asks for its loopback port. + // asks for its loopback port. A tcpAnnounced adapter's endpoint describes the + // output line its process prints; only Core reads it, from the launch plan. Endpoint DebugAdapterEndpoint // AcceptsConnection is true when the attach configuration binds a remote // host and port, so the host may offer the host-and-port form. diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 365ec063e1..b913d77dbc 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -85,6 +85,7 @@ type Kernel interface { PlanDebugExecutable(context.Context, json.RawMessage, string, string, string, map[string]json.RawMessage, map[string]json.RawMessage) (*core.DebugExecutablePlan, error) PlanDebugStart(context.Context, json.RawMessage, string, string, core.DebugStartFacts, map[string]any) (core.DebugStart, error) DebugTransportPolicy(context.Context) (core.DebugTransportPolicy, error) + ReadDebugAnnouncement(ctx context.Context, endpoint json.RawMessage, stream, line string) (core.DebugAnnouncement, error) debugTransportKernel debugStateKernel processExitKernel diff --git a/desktop/internal/workbench/debug.go b/desktop/internal/workbench/debug.go index eb9239d245..79cf520f65 100644 --- a/desktop/internal/workbench/debug.go +++ b/desktop/internal/workbench/debug.go @@ -36,7 +36,8 @@ const ( ) // debugAdapter is one installed plugin's debug adapter declaration, reached over -// stdio or through its plugin's language server (tcpLanguageServer). +// stdio, over the loopback TCP endpoint its process prints (tcpAnnounced), or +// through its plugin's language server (tcpLanguageServer). type debugAdapter struct { PluginID string Directory string @@ -243,7 +244,8 @@ type debugSession struct { project *project process atomic.Pointer[buildprocess.Process] // transport is the write side of the adapter's byte stream: the adapter - // process's stdin, or the TCP connection of a tcpLanguageServer adapter. + // process's stdin, or the TCP stream of a tcpLanguageServer or tcpAnnounced + // adapter. // Closing it interrupts a blocked write, so Stop and shutdown use that. transportMu sync.Mutex transport io.WriteCloser @@ -276,8 +278,9 @@ type debugSession struct { ended chan *int // stopRun reaps an attached process owned by Run after the adapter disconnects. stopRun func() - // hosted is the lifecycle-driven stream of a tcpLanguageServer adapter; nil - // for a stdio adapter. It is also the session's transport. + // hosted is the lifecycle-driven stream of a tcpLanguageServer or + // tcpAnnounced adapter; nil for a stdio adapter. It is also the session's + // transport. hosted *debugTransport // drainOnStop marks a user stop: a live hosted session sends its disconnect // and lets Core's drain flush it instead of closing the stream at once. @@ -853,9 +856,11 @@ func (a *App) releaseDebugSession(p *project, session *debugSession) { drain := session.drainOnStop.Load() && session.hosted != nil if !drain { session.closeTransport() - } - if process := session.process.Load(); process != nil { - process.Stop() + // A tcpAnnounced adapter's process outlives the session's context; a + // drained one is stopped once its disconnect was flushed. + if process := session.process.Load(); process != nil { + process.Stop() + } } // Cleanup belongs to the app, not the now-cancelled project. a.background(nil, 0, func(_ context.Context) func(*App) { @@ -877,6 +882,11 @@ func (a *App) releaseDebugSession(p *project, session *debugSession) { // session that never got to send a disconnect. _ = session.hosted.Close() } + // The adapter had its disconnect; a process the startup stored after + // the stop began is also stopped here. A repeated Stop does nothing. + if process := session.process.Load(); process != nil { + process.Stop() + } if session.created && !session.coreGone { destroyed, cleanupErr = a.kernel.DestroyDebugSession(ctx, session.id) } diff --git a/desktop/internal/workbench/debug_adapter_start.go b/desktop/internal/workbench/debug_adapter_start.go index fac986b618..77cfd9bbb6 100644 --- a/desktop/internal/workbench/debug_adapter_start.go +++ b/desktop/internal/workbench/debug_adapter_start.go @@ -66,13 +66,14 @@ func (a *App) debugWriteFailed(p *project, session *debugSession, err error) fun if errors.Is(err, errDebugTransportNotRunning) { return nil } - stage := debugWriteFailureStage(session.process.Load() != nil, session.reached.Load()) + stage := debugWriteFailureStage(session.hosted == nil, session.reached.Load()) a.recordDebugStart(session.ctx, session, stage, err) return func(a *App) { a.finishDebugError(p, session, err) } } // debugWriteFailureStage is the stage a failed write ends the adapter start at, for a stdio -// adapter whose process runs, or a hosted one whose socket connected or not. +// adapter whose process runs, or one reached over TCP (tcpLanguageServer or tcpAnnounced) +// whose socket connected or not. func debugWriteFailureStage(stdio, reached bool) core.PluginStage { switch { case stdio: @@ -84,7 +85,7 @@ func debugWriteFailureStage(stdio, reached bool) core.PluginStage { } } -// hostedFailureStage is the stage at which Core's failure of a hosted adapter's stream ends +// hostedFailureStage is the stage at which Core's failure of a TCP-reached adapter's stream ends // its start: its startup deadline is a timeout; any other failure is a launch until the socket // connected and an initialize failure after. func hostedFailureStage(reached bool, reason string) core.PluginStage { diff --git a/desktop/internal/workbench/debug_announced.go b/desktop/internal/workbench/debug_announced.go new file mode 100644 index 0000000000..d4a3e6bbee --- /dev/null +++ b/desktop/internal/workbench/debug_announced.go @@ -0,0 +1,171 @@ +package workbench + +import ( + "context" + "errors" + "strings" + "sync" + + "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" +) + +// debugAnnouncementLineLimit bounds the unfinished line kept per output stream +// while the announcement is awaited. A longer line goes to the console unread. +const debugAnnouncementLineLimit = 64 << 10 + +// openAnnouncedTransport starts a tcpAnnounced adapter: its process, whose +// output Core reads line by line until a line announces the loopback endpoint +// the adapter listens on, and the stream Core's transport lifecycle drives to +// that endpoint. Core owns which line is the announcement, which endpoints may +// be connected to and every deadline; the host splits lines, keeps the process +// and the socket, and runs the effects Core returns. Output that is not the +// announcement, and all output after it, is the debug console's. +func (a *App) openAnnouncedTransport(ctx context.Context, p *project, session *debugSession, prepared preparedDebugLaunch, messages i18n.DebugMessages) error { + reader := newDebugAnnouncementReader( + func(stream, line string) (core.DebugAnnouncement, error) { + readContext, cancel := context.WithTimeout(session.ctx, debugOperationTimeout) + defer cancel() + return a.kernel.ReadDebugAnnouncement(readContext, prepared.Endpoint, stream, line) + }, + func(text string) { a.post(func(a *App) { a.appendDebugOutput(p, session, text) }) }, + errors.New(messages.InvalidEndpoint), + ) + hooks := a.debugStreamHooks(p, session, messages) + hooks.Discover = reader.wait + transport := newDebugTransport(a.kernel, session.id+"-transport", hooks) + if !session.setTransport(transport) { + return context.Canceled + } + session.hosted = transport + // The stream starts before the process: Core's default discovery limit then + // bounds the process start and its announcement together, and a process that + // exits at once finds a started stream to stop. + if err := transport.Start(nil); err != nil { + return err + } + return a.startAdapterProcess(ctx, p, session, prepared, nil, reader.observe, errors.New(messages.NotAnnounced)) +} + +// debugAnnouncedEndpoint is the result of waiting for an announcement: the +// endpoint to connect to, or why there is none. +type debugAnnouncedEndpoint struct { + host string + port int + err error +} + +// debugAnnouncementReader splits a tcpAnnounced adapter's output into lines +// and asks Core about each one until one decides the endpoint. The process's +// two output streams call observe concurrently, so a mutex orders them. +type debugAnnouncementReader struct { + // read asks Core whether one line, without its line break, announces the endpoint. + read func(stream, line string) (core.DebugAnnouncement, error) + // console shows output that is not the announcement. + console func(text string) + // invalid is what an announced endpoint Core refuses reports. + invalid error + // found receives the one result once a line decided it. + found chan debugAnnouncedEndpoint + + mu sync.Mutex + done bool + // pending is each stream's unfinished line; overlong marks a stream whose + // current line passed the limit and goes to the console unread to its end. + pending map[buildprocess.Stream]string + overlong map[buildprocess.Stream]bool +} + +func newDebugAnnouncementReader(read func(stream, line string) (core.DebugAnnouncement, error), console func(text string), invalid error) *debugAnnouncementReader { + return &debugAnnouncementReader{ + read: read, + console: console, + invalid: invalid, + found: make(chan debugAnnouncedEndpoint, 1), + pending: make(map[buildprocess.Stream]string), + overlong: make(map[buildprocess.Stream]bool), + } +} + +// wait is the transport's Discover: it returns once a line decided the +// endpoint, or when the transport stops waiting. +func (r *debugAnnouncementReader) wait(ctx context.Context) (string, int, error) { + select { + case endpoint := <-r.found: + return endpoint.host, endpoint.port, endpoint.err + case <-ctx.Done(): + return "", 0, ctx.Err() + } +} + +// observe receives one chunk of the process's output, which may hold part of +// a line or several lines. +func (r *debugAnnouncementReader) observe(stream buildprocess.Stream, text string) { + r.mu.Lock() + defer r.mu.Unlock() + if r.done { + r.console(text) + return + } + text = r.pending[stream] + text + delete(r.pending, stream) + var shown strings.Builder + for !r.done { + end := strings.IndexByte(text, '\n') + if end < 0 { + break + } + line := text[:end+1] + text = text[end+1:] + if r.overlong[stream] { + delete(r.overlong, stream) + shown.WriteString(line) + continue + } + if !r.announces(stream, strings.TrimSuffix(strings.TrimSuffix(line, "\n"), "\r")) { + shown.WriteString(line) + } + } + switch { + case r.done || r.overlong[stream]: + shown.WriteString(text) + case len(text) > debugAnnouncementLineLimit: + r.overlong[stream] = true + shown.WriteString(text) + default: + r.pending[stream] = text + } + if shown.Len() > 0 { + r.console(shown.String()) + } +} + +// announces asks Core about one complete line and reports whether the line is +// the announcement itself, which the console does not show. A line that +// announces an endpoint Core refuses, or a failed reading, also ends the wait. +func (r *debugAnnouncementReader) announces(stream buildprocess.Stream, line string) bool { + reading, err := r.read(string(stream), line) + switch { + case err != nil: + r.finish(debugAnnouncedEndpoint{err: err}) + case reading.Status == "announced": + r.finish(debugAnnouncedEndpoint{host: reading.Host, port: reading.Port}) + return true + case reading.Status == "invalid": + r.finish(debugAnnouncedEndpoint{err: r.invalid}) + } + return false +} + +func (r *debugAnnouncementReader) finish(endpoint debugAnnouncedEndpoint) { + r.done = true + r.found <- endpoint + // Everything left unread is the debuggee's output now. + for stream, text := range r.pending { + if text != "" { + r.console(text) + } + delete(r.pending, stream) + } +} diff --git a/desktop/internal/workbench/debug_announced_test.go b/desktop/internal/workbench/debug_announced_test.go new file mode 100644 index 0000000000..58a19e4642 --- /dev/null +++ b/desktop/internal/workbench/debug_announced_test.go @@ -0,0 +1,411 @@ +package workbench + +import ( + "bytes" + "context" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/buildprocess" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" +) + +// debugAnnouncedManifest declares an adapter process that listens on a loopback +// port it picks itself and prints on stdout, for adapters with no stdio mode. +const debugAnnouncedManifest = `{ + "schemaVersion": 0, + "id": "dev.lithe.test.debug-announced", + "displayName": "Announced Debug Fixture", + "version": "1.0.0", + "pluginAPIVersion": 0, + "requires": {"debugAdapters": 0}, + "vendor": {"id": "dev.lithe.test", "displayName": "Test", "signatureRequirement": "publisherPackage"}, + "permissions": ["debug.launch"], + "activationEvents": ["onDebug:announced"], + "languages": [], + "debugAdapters": [{ + "id": "announced", + "displayName": "Announced DAP", + "adapterID": "announced-dap", + "requests": ["launch"], + "configurations": {"launch": {"arguments": {"stopOnEntry": true}}}, + "launch": { + "process": {"launch": {"kind": "packaged", "path": "adapter"}, "arguments": ["-test.run=^TestDebugAnnouncedAdapterRunner$"]}, + "transport": "tcpAnnounced", + "endpoint": {"stream": "stdout", "prefix": "DAP server listening at: ", "value": "hostPort"} + } + }] +}` + +// announcedFixtureLifetime bounds the fixture process: one the host failed to +// stop still ends by itself, and the test that waits for its end fails first. +const announcedFixtureLifetime = 2 * time.Minute + +// announcedFixture is what the workspace's announce.marker tells the runner: +// how the adapter behaves, and the test's watch address it holds a connection +// to, which closes when the process ends. +type announcedFixture struct { + Mode string `json:"mode"` + Watch string `json:"watch"` +} + +// TestDebugAnnouncedAdapterRunner is the fixture tcpAnnounced adapter. The host +// starts the copied test binary with the manifest's -test.run argument and the +// fixture workspace as its working directory. Its modes: +// +// - "" listens on a free loopback port, prints a line on each stream and then +// the announcement, serves the fixture DAP on the one connection, and tells +// the watch connection when the host sent disconnect; +// - "exit" prints a line and exits before announcing; +// - "silent" prints a line and never announces; +// - "remote" announces an address that is not on this computer. +// +// The last two stay up until the host stops them or the test closes the watch +// connection, so the watch's end shows the process ended. +func TestDebugAnnouncedAdapterRunner(t *testing.T) { + marker, err := os.ReadFile("announce.marker") + if err != nil { + t.Skip("not the announced debug adapter fixture workspace") + } + var fixture announcedFixture + if err := json.Unmarshal(marker, &fixture); err != nil { + os.Exit(2) + } + watch, err := net.DialTimeout("tcp", fixture.Watch, 10*time.Second) + if err != nil { + os.Exit(2) + } + _ = watch.SetDeadline(time.Now().Add(announcedFixtureLifetime)) + hold := func() { + _, _ = io.Copy(io.Discard, watch) + os.Exit(0) + } + switch fixture.Mode { + case "exit": + fmt.Println("started without a listener") + os.Exit(0) + case "silent": + fmt.Println("started") + hold() + case "remote": + fmt.Println("DAP server listening at: 192.0.2.1:5678") + hold() + } + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + os.Exit(3) + } + _ = listener.(*net.TCPListener).SetDeadline(time.Now().Add(announcedFixtureLifetime)) + fmt.Fprintln(os.Stderr, "stderr before the announcement") + fmt.Println("stdout before the announcement") + // A CRLF line end, as a Windows adapter may print it. + fmt.Printf("DAP server listening at: %s\r\n", listener.Addr()) + conn, err := listener.Accept() + _ = listener.Close() + if err != nil { + os.Exit(3) + } + _ = conn.SetDeadline(time.Now().Add(announcedFixtureLifetime)) + workspace, err := os.Getwd() + if err != nil { + os.Exit(2) + } + var requests bytes.Buffer + code := serveFixtureAdapter(io.TeeReader(conn, &requests), conn, workspace) + if bytes.Contains(requests.Bytes(), []byte(`"disconnect"`)) { + fmt.Fprintln(watch, "disconnected") + } + os.Exit(code) +} + +// announcedWatch accepts the fixture process's watch connection. +type announcedWatch struct { + listener net.Listener + accepted chan net.Conn +} + +// announcedWorkspace is the fixture workspace for one mode, and the watch the +// fixture process connects to. +func announcedWorkspace(t *testing.T, mode string) (root, source string, watch *announcedWatch) { + t.Helper() + root, source = fixtureWorkspace(t) + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + watch = &announcedWatch{listener: listener, accepted: make(chan net.Conn, 1)} + t.Cleanup(func() { + _ = listener.Close() + select { + case conn := <-watch.accepted: + _ = conn.Close() + default: + } + }) + go func() { + conn, err := listener.Accept() + if err == nil { + watch.accepted <- conn + } + }() + marker, err := json.Marshal(announcedFixture{Mode: mode, Watch: listener.Addr().String()}) + if err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(root, "announce.marker"), marker, 0o600); err != nil { + t.Fatal(err) + } + return root, source, watch +} + +// ended waits for the fixture process to end and returns what it reported +// before it did. The connection goes back for the cleanup to close. +func (w *announcedWatch) ended(t *testing.T, limit time.Duration) string { + t.Helper() + var conn net.Conn + select { + case conn = <-w.accepted: + case <-time.After(limit): + t.Fatal("the adapter process never connected to the watch") + } + defer func() { w.accepted <- conn }() + if err := conn.SetReadDeadline(time.Now().Add(limit)); err != nil { + t.Fatal(err) + } + reported, err := io.ReadAll(conn) + if err != nil { + t.Fatalf("the adapter process still runs after %v (read: %v)", limit, err) + } + return string(reported) +} + +func TestDebugAnnouncedAdapterBreakpointPauseContinueStop(t *testing.T) { + h := debugPluginHarness(t, "dev.lithe.test.debug-announced", debugAnnouncedManifest, true) + root, source, watch := announcedWorkspace(t, "") + p := openHostedPanel(t, h, root) + if declaration := p.debug.adapters[0].Declaration; declaration.Transport != "tcpAnnounced" || declaration.LaunchKind != "packaged" { + t.Fatalf("declaration = %+v, want the announced adapter's process", declaration) + } + h.app.openFileAtPosition(p, source, 2, 0) + h.settle() + toggleBreakpointInDialog(h) + + h.clickNamed(h.app.text.Debug.Start) + awaitStateWithin(t, h, 30*time.Second, "the paused announced session and its output", func() bool { + if p.debug.failure != "" { + t.Fatalf("debug start failed: %s", p.debug.failure) + } + output := strings.Join(p.debug.output, "\n") + return p.debug.state == "paused" && len(p.debug.frames) == 2 && + strings.Contains(output, "stdout before the announcement") && strings.Contains(output, "stderr before the announcement") + }) + // The announcement is the host's reading, not the adapter's console output. + if output := strings.Join(p.debug.output, "\n"); strings.Contains(output, "DAP server listening at") { + t.Fatalf("the console shows the announcement: %q", output) + } + + h.clickNamed(h.app.text.Debug.Continue) + awaitStateWithin(t, h, 20*time.Second, "the continued session", func() bool { + return p.debug.state == "running" && len(p.debug.frames) == 0 + }) + h.clickNamed(h.app.text.Debug.Pause) + awaitStateWithin(t, h, 20*time.Second, "the paused session", func() bool { + return p.debug.state == "paused" && len(p.debug.frames) == 2 + }) + + h.clickNamed(h.app.text.Debug.Stop) + awaitStateWithin(t, h, 20*time.Second, "the stopped session", func() bool { + return p.debug.activeSession() == nil && p.debug.state == "idle" + }) + // The process outlives the session's context, so the disconnect reaches it + // before it is stopped. + if reported := watch.ended(t, 20*time.Second); !strings.Contains(reported, "disconnected") { + t.Fatalf("the adapter process ended without its disconnect (reported %q)", reported) + } +} + +func TestDebugAnnouncedAdapterThatExitsFirstFailsWithAMessage(t *testing.T) { + h := debugPluginHarness(t, "dev.lithe.test.debug-announced", debugAnnouncedManifest, true) + root, _, watch := announcedWorkspace(t, "exit") + p := openHostedPanel(t, h, root) + h.clickNamed(h.app.text.Debug.Start) + awaitStateWithin(t, h, 20*time.Second, "the failure", func() bool { return p.debug.failure != "" }) + if p.debug.failure != h.app.text.Debug.NotAnnounced || p.debug.activeSession() != nil { + t.Fatalf("failure = %q, session = %v; want the missing announcement", p.debug.failure, p.debug.activeSession()) + } + watch.ended(t, 20*time.Second) +} + +func TestDebugAnnouncedRemoteEndpointFailsAndStopsTheProcess(t *testing.T) { + h := debugPluginHarness(t, "dev.lithe.test.debug-announced", debugAnnouncedManifest, true) + root, _, watch := announcedWorkspace(t, "remote") + p := openHostedPanel(t, h, root) + h.clickNamed(h.app.text.Debug.Start) + awaitStateWithin(t, h, 20*time.Second, "the failure", func() bool { return p.debug.failure != "" }) + if p.debug.failure != h.app.text.Debug.InvalidEndpoint || p.debug.activeSession() != nil { + t.Fatalf("failure = %q, session = %v; want the refused endpoint", p.debug.failure, p.debug.activeSession()) + } + watch.ended(t, 20*time.Second) +} + +func TestDebugAnnouncedAdapterThatNeverAnnouncesTimesOut(t *testing.T) { + h := debugPluginHarness(t, "dev.lithe.test.debug-announced", debugAnnouncedManifest, true) + root, _, watch := announcedWorkspace(t, "silent") + h.app.debugInitializeWindow = 300 * time.Millisecond + p := openHostedPanel(t, h, root) + h.clickNamed(h.app.text.Debug.Start) + awaitStateWithin(t, h, 20*time.Second, "the timeout", func() bool { return p.debug.failure != "" }) + if p.debug.failure != h.app.text.Debug.TimedOut || p.debug.activeSession() != nil { + t.Fatalf("failure = %q, want the timeout message", p.debug.failure) + } + watch.ended(t, 20*time.Second) +} + +// announcementRecorder is a reader whose Core answer is a fixed rule: a line +// "announce " announces 127.0.0.1, "remote" is refused, and "broken" is a +// failed reading. Callers run on one goroutine, so it needs no lock. +type announcementRecorder struct { + lines []string + console []string +} + +var errBrokenReading = errors.New("broken reading") + +func (r *announcementRecorder) reader() *debugAnnouncementReader { + return newDebugAnnouncementReader(func(stream, line string) (core.DebugAnnouncement, error) { + r.lines = append(r.lines, stream+":"+line) + var port int + switch { + case line == "remote": + return core.DebugAnnouncement{Status: "invalid", Reason: "notLoopback"}, nil + case line == "broken": + return core.DebugAnnouncement{}, errBrokenReading + case stream == "stdout": + if _, err := fmt.Sscanf(line, "announce %d", &port); err == nil { + return core.DebugAnnouncement{Status: "announced", Host: "127.0.0.1", Port: port}, nil + } + } + return core.DebugAnnouncement{Status: "none"}, nil + }, func(text string) { r.console = append(r.console, text) }, errors.New("refused endpoint")) +} + +// decided returns the endpoint the observed output decided. observe decides +// synchronously, so the result is either there already or missing. +func decided(t *testing.T, reader *debugAnnouncementReader) (string, int, error) { + t.Helper() + select { + case endpoint := <-reader.found: + return endpoint.host, endpoint.port, endpoint.err + default: + t.Fatal("no line decided the endpoint") + return "", 0, nil + } +} + +func TestDebugAnnouncementReaderJoinsChunksAndHidesTheAnnouncement(t *testing.T) { + recorder := &announcementRecorder{} + reader := recorder.reader() + reader.observe(buildprocess.Stream("stdout"), "building\nannou") + reader.observe(buildprocess.Stream("stdout"), "nce 4711\r\nafter\npartial") + host, port, err := decided(t, reader) + if host != "127.0.0.1" || port != 4711 || err != nil { + t.Fatalf("endpoint = %s:%d, %v", host, port, err) + } + if want := []string{"stdout:building", "stdout:announce 4711"}; strings.Join(recorder.lines, "|") != strings.Join(want, "|") { + t.Fatalf("read lines = %q, want %q", recorder.lines, want) + } + // Output after the announcement is the console's as it arrives, unread. + reader.observe(buildprocess.Stream("stdout"), " line\nannounce 9\n") + if got := strings.Join(recorder.console, ""); got != "building\nafter\npartial line\nannounce 9\n" { + t.Fatalf("console = %q", got) + } + if len(recorder.lines) != 2 { + t.Fatalf("lines after the announcement were read: %q", recorder.lines) + } +} + +func TestDebugAnnouncementReaderKeepsEachStreamsLineApart(t *testing.T) { + recorder := &announcementRecorder{} + reader := recorder.reader() + reader.observe(buildprocess.Stream("stderr"), "warning: ") + reader.observe(buildprocess.Stream("stdout"), "announce ") + reader.observe(buildprocess.Stream("stderr"), "slow disk\nannounce 1\n") + select { + case <-reader.found: + t.Fatal("a stderr line decided the endpoint") + default: + } + reader.observe(buildprocess.Stream("stdout"), "4712\n") + if _, port, err := decided(t, reader); port != 4712 || err != nil { + t.Fatalf("port = %d, %v", port, err) + } + if got := strings.Join(recorder.console, ""); got != "warning: slow disk\nannounce 1\n" { + t.Fatalf("console = %q", got) + } +} + +func TestDebugAnnouncementReaderShowsUnfinishedOutputOnceDecided(t *testing.T) { + recorder := &announcementRecorder{} + reader := recorder.reader() + reader.observe(buildprocess.Stream("stderr"), "progress 50%") + reader.observe(buildprocess.Stream("stdout"), "announce 4713\n") + decided(t, reader) + if got := strings.Join(recorder.console, ""); got != "progress 50%" { + t.Fatalf("console = %q, want the other stream's unfinished line", got) + } +} + +func TestDebugAnnouncementReaderPassesAnOverlongLineUnread(t *testing.T) { + recorder := &announcementRecorder{} + reader := recorder.reader() + long := strings.Repeat("x", debugAnnouncementLineLimit+1) + reader.observe(buildprocess.Stream("stdout"), long) + reader.observe(buildprocess.Stream("stdout"), "announce 1 tail\nannounce 4714\n") + if _, port, err := decided(t, reader); port != 4714 || err != nil { + t.Fatalf("port = %d, %v", port, err) + } + if len(recorder.lines) != 1 || recorder.lines[0] != "stdout:announce 4714" { + t.Fatalf("read lines = %q, want only the line after the overlong one", recorder.lines) + } + if got := strings.Join(recorder.console, ""); got != long+"announce 1 tail\n" { + t.Fatalf("console shows %d bytes, want the overlong line whole", len(got)) + } +} + +func TestDebugAnnouncementReaderRefusalAndFailedReadingEndTheWait(t *testing.T) { + for _, test := range []struct { + line string + want string + }{ + {line: "remote", want: "refused endpoint"}, + {line: "broken", want: errBrokenReading.Error()}, + } { + recorder := &announcementRecorder{} + reader := recorder.reader() + reader.observe(buildprocess.Stream("stdout"), test.line+"\nannounce 4715\n") + if _, _, err := decided(t, reader); err == nil || err.Error() != test.want { + t.Fatalf("%s: err = %v, want %q", test.line, err, test.want) + } + // The refused line stays visible, and what follows is the console's. + if got := strings.Join(recorder.console, ""); got != test.line+"\nannounce 4715\n" { + t.Fatalf("%s: console = %q", test.line, got) + } + } +} + +func TestDebugAnnouncementReaderWaitEndsWithItsContext(t *testing.T) { + reader := (&announcementRecorder{}).reader() + ctx, cancel := context.WithCancel(context.Background()) + cancel() + if _, _, err := reader.wait(ctx); !errors.Is(err, context.Canceled) { + t.Fatalf("wait = %v, want cancellation", err) + } +} diff --git a/desktop/internal/workbench/debug_launch.go b/desktop/internal/workbench/debug_launch.go index 879f63e1cf..65002b85dd 100644 --- a/desktop/internal/workbench/debug_launch.go +++ b/desktop/internal/workbench/debug_launch.go @@ -44,9 +44,13 @@ type preparedDebugLaunch struct { DisabledCapabilities []string Features json.RawMessage Defaults json.RawMessage + // Endpoint is the plan's endpoint descriptor, passed unchanged to Core when + // it reads the output of a tcpAnnounced adapter for its announcement. + Endpoint json.RawMessage } -// resolveAdapterProcess resolves the program of a stdio adapter from Core's plan: +// resolveAdapterProcess resolves the program of a stdio or tcpAnnounced adapter +// from Core's plan: // a packaged file, a system command, or a tool the toolchain registry resolves. // Packaged paths are verified against the installed package, never the workspace. func (a *App) resolveAdapterProcess(ctx context.Context, adapter debugAdapter, plan core.PluginBackendPlan, root, stateDirectory string) (string, []string, map[string]string, error) { @@ -247,6 +251,7 @@ func (a *App) prepareDebugLaunch(ctx context.Context, start debugStart, stateDir prepared.DisabledCapabilities = descriptor.DisabledCapabilities prepared.Features = descriptor.Features prepared.Defaults = descriptor.Defaults + prepared.Endpoint = descriptor.Endpoint } return prepared, ctx.Err() } diff --git a/desktop/internal/workbench/debug_start.go b/desktop/internal/workbench/debug_start.go index 3207e55c85..ca6307619e 100644 --- a/desktop/internal/workbench/debug_start.go +++ b/desktop/internal/workbench/debug_start.go @@ -30,7 +30,8 @@ const ( // debugReadChunk is the size of one read from the adapter's TCP stream. debugReadChunk = 32 << 10 // debugLoopback is where a tcpLanguageServer adapter listens: the contract - // allows loopback endpoints only for language-server-provided ports. + // allows loopback endpoints only for language-server-provided ports. A + // tcpAnnounced adapter's loopback host is the one Core read from its output. debugLoopback = "127.0.0.1" ) @@ -92,11 +93,12 @@ type debugAttachFields struct { } // debugTransportServed reports whether this client can start the adapter: a -// process it launches over stdio, or an adapter inside its plugin's language -// server reached over loopback TCP. +// process it launches over stdio, a process it launches that prints the +// loopback TCP endpoint it listens on (tcpAnnounced), or an adapter inside its +// plugin's language server reached over loopback TCP. func debugTransportServed(declaration pluginservice.DebugAdapterDeclaration) bool { switch declaration.Transport { - case "stdio": + case "stdio", "tcpAnnounced": switch declaration.LaunchKind { case pluginhost.LaunchPackaged, pluginhost.LaunchSystemCommand, pluginhost.LaunchRuntime: return true @@ -399,6 +401,7 @@ func (a *App) beginDebug(p *project, start debugStart) { pluginRoot := a.plugins.Root targetUnavailable := i18n.Shared(a.language(), "desktop.debug.targetUnavailable") hosted := adapter.Declaration.Transport == "tcpLanguageServer" + announced := adapter.Declaration.Transport == "tcpAnnounced" // Background work reads this copy, never a.text, which the window thread owns. messages := a.text.Debug // A child shares its parent's generation, so the parent's replies stay current. @@ -458,8 +461,10 @@ func (a *App) beginDebug(p *project, start debugStart) { parentSessionID = start.parent.id } stateRoot := filepath.Join(pluginRoot, ".state", adapter.PluginID, adapter.Version) + // Only a stdio adapter is written through its standard input; the other + // transports are written through their TCP stream. var stdinReader *os.File - if !hosted { + if !hosted && !announced { reader, writer, err := os.Pipe() if err != nil { cancel() @@ -536,7 +541,12 @@ func (a *App) beginDebug(p *project, start debugStart) { a.recordDebugStart(ctx, session, core.StageLaunch, err) return func(a *App) { a.finishDebugError(p, session, err) } } - } else if err := a.startAdapterProcess(ctx, p, session, prepared, stdinReader); err != nil { + } else if announced { + if err := a.openAnnouncedTransport(ctx, p, session, prepared, messages); err != nil { + a.recordDebugStart(ctx, session, core.StageLaunch, err) + return func(a *App) { a.finishDebugError(p, session, err) } + } + } else if err := a.startAdapterProcess(ctx, p, session, prepared, stdinReader, a.stdioDebugOutput(p, session), nil); err != nil { a.recordDebugStart(ctx, session, core.StageLaunch, err) return func(a *App) { a.finishDebugError(p, session, err) } } @@ -562,6 +572,10 @@ func (a *App) beginDebug(p *project, start debugStart) { // The session clock starts before discovery here, so it also covers // the language-server start the discovery limit was raised for. window += pluginServerStartTimeout + } else if announced { + // Likewise it covers the wait for the adapter to print its endpoint, + // which Core's default discovery limit bounds. + window += time.Duration(policy.Limits.DiscoveryMilliseconds) * time.Millisecond } if override := a.debugInitializeWindow; override > 0 { window = override @@ -649,38 +663,71 @@ func (a *App) watchDebugInitialize(p *project, session *debugSession, window tim context.AfterFunc(session.ctx, func() { timer.Stop() }) } -// startAdapterProcess starts a stdio adapter and watches for its exit, so an -// adapter that dies without a DAP terminated event still ends the session. -func (a *App) startAdapterProcess(ctx context.Context, p *project, session *debugSession, prepared preparedDebugLaunch, stdin *os.File) error { - process, err := buildprocess.Start(ctx, buildprocess.Spec{ - Kind: processledger.KindDebug, - Executable: prepared.Executable, - Arguments: prepared.Arguments, - Environment: prepared.Environment, - WorkingDirectory: p.root, - Stdin: stdin, - }, func(stream buildprocess.Stream, text string) { +// stdioDebugOutput routes a stdio adapter's output: standard output is its DAP +// stream, standard error goes to the debug console. +func (a *App) stdioDebugOutput(p *project, session *debugSession) func(buildprocess.Stream, string) { + return func(stream buildprocess.Stream, text string) { if stream == buildprocess.Stderr { a.post(func(a *App) { a.appendDebugOutput(p, session, text) }) return } a.receiveDebug(p, session, []byte(text)) - }) - _ = stdin.Close() + } +} + +// startAdapterProcess starts an adapter process and watches for its exit, so +// an adapter that dies without a DAP terminated event still ends the session. +// A stdio adapter (stdin set) is reached once it runs. A tcpAnnounced adapter +// (stdin nil) is reached once its socket connects, and it outlives the +// session's context: a user stop first drains its DAP disconnect through the +// stream, and the session's release stops the process after that. unreached is +// what an exit before the stream connected reports when nothing failed first. +func (a *App) startAdapterProcess(ctx context.Context, p *project, session *debugSession, prepared preparedDebugLaunch, stdin *os.File, observe func(buildprocess.Stream, string), unreached error) error { + spec := buildprocess.Spec{ + Kind: processledger.KindDebug, + Executable: prepared.Executable, + Arguments: prepared.Arguments, + Environment: prepared.Environment, + WorkingDirectory: p.root, + } + processContext := context.WithoutCancel(ctx) + if stdin != nil { + // A nil *os.File would be a non-nil reader, so the field is set only here. + spec.Stdin = stdin + processContext = ctx + } + process, err := buildprocess.Start(processContext, spec, observe) + if stdin != nil { + _ = stdin.Close() + } if err != nil { return err } session.process.Store(process) - session.reached.Store(true) + if stdin != nil { + session.reached.Store(true) + } // Observe native exit even when the adapter cannot send a DAP terminated event. go func() { defer close(session.exitObserved) err := process.Wait() // An exit before initialize was answered ends the start, whatever its status. It is // read before the session's context ends, which would make it a stop by the user. - a.recordDebugStart(session.ctx, session, core.StageExit, errDebugAdapterExited) + stage := core.StageExit + if !session.reached.Load() { + stage = core.StageLaunch + } + a.recordDebugStart(session.ctx, session, stage, errDebugAdapterExited) session.cancel() session.closeTransport() + if err == nil && !session.reached.Load() { + // A tcpAnnounced adapter that ends before its stream connected never + // served the session, whatever its exit status. + err = session.recordedFailure() + if err == nil { + err = unreached + } + } a.debugStreamEnded(p, session, err) }() return nil @@ -733,8 +780,26 @@ func (a *App) openHostedTransport(p *project, session *debugSession, adapter deb } return debugLoopback, port, err } - hooks := debugTransportHooks{ - Discover: discover, + hooks := a.debugStreamHooks(p, session, messages) + hooks.Discover = discover + transport := newDebugTransport(a.kernel, session.id+"-transport", hooks) + if !session.setTransport(transport) { + return context.Canceled + } + session.hosted = transport + // Core's default discovery budget is a cold-start allowance; the language + // server's own start budget is the one this host already owns, so it raises + // only the discovery limit (an override the contract allows). + discovery := int(pluginServerStartTimeout / time.Millisecond) + return transport.Start(&core.DebugTransportLimitOverrides{DiscoveryMilliseconds: &discovery}) +} + +// debugStreamHooks are a TCP-reached session's side of its stream, for every +// transport but Discover, which the caller sets: the socket connecting reaches +// the adapter, its bytes are DAP, and a failure or the peer closing ends the +// session. +func (a *App) debugStreamHooks(p *project, session *debugSession, messages i18n.DebugMessages) debugTransportHooks { + return debugTransportHooks{ Connected: func() { session.reached.Store(true) }, Deliver: func(data []byte) { a.receiveDebug(p, session, data) }, Failure: func(reason, message string) { @@ -764,16 +829,6 @@ func (a *App) openHostedTransport(p *project, session *debugSession, adapter deb a.debugStreamEnded(p, session, failure) }, } - transport := newDebugTransport(a.kernel, session.id+"-transport", hooks) - if !session.setTransport(transport) { - return context.Canceled - } - session.hosted = transport - // Core's default discovery budget is a cold-start allowance; the language - // server's own start budget is the one this host already owns, so it raises - // only the discovery limit (an override the contract allows). - discovery := int(pluginServerStartTimeout / time.Millisecond) - return transport.Start(&core.DebugTransportLimitOverrides{DiscoveryMilliseconds: &discovery}) } // debugTransportFailureText turns Core's failure reason into the words shown. diff --git a/desktop/internal/workbench/debug_tcp_test.go b/desktop/internal/workbench/debug_tcp_test.go index b03119cb5b..c163c29283 100644 --- a/desktop/internal/workbench/debug_tcp_test.go +++ b/desktop/internal/workbench/debug_tcp_test.go @@ -81,9 +81,16 @@ func debugPluginHarness(t *testing.T, id, manifest string, withBinary bool) *har // debugPluginHarnessOn is debugPluginHarness whose plugin service runs on plugins. func debugPluginHarnessOn(t *testing.T, id, manifest string, withBinary bool, plugins pluginservice.Kernel) *harness { + t.Helper() + return newHarnessWithOptions(t, debugPluginOptions(t, id, manifest, withBinary, plugins, "dark")) +} + +// debugPluginOptions installs one fixture plugin, as debugPluginHarnessOn does, and +// returns the window's options in theme, for a harness that opens its own driver. +func debugPluginOptions(t *testing.T, id, manifest string, withBinary bool, plugins pluginservice.Kernel, theme string) Options { t.Helper() dir := t.TempDir() - if err := os.WriteFile(filepath.Join(dir, settingsFile), []byte(`{"theme":"dark"}`), 0o600); err != nil { + if err := os.WriteFile(filepath.Join(dir, settingsFile), []byte(`{"theme":"`+theme+`"}`), 0o600); err != nil { t.Fatal(err) } preferences := store.At(dir) @@ -106,13 +113,13 @@ func debugPluginHarnessOn(t *testing.T, id, manifest string, withBinary bool, pl if err := pluginstate.New(preferences).SetEnabled(id, true); err != nil { t.Fatal(err) } - return newHarnessWithOptions(t, Options{ + return Options{ Kernel: &testKernel{Client: core.NewClient()}, PluginKernel: plugins, PluginRoot: pluginRoot, Store: preferences, Languages: []string{"zh-Hans"}, - }) + } } // fixtureWorkspace is a project the fixture adapter accepts. diff --git a/desktop/internal/workbench/visual_capture_test.go b/desktop/internal/workbench/visual_capture_test.go index 964e792017..2656de12a6 100644 --- a/desktop/internal/workbench/visual_capture_test.go +++ b/desktop/internal/workbench/visual_capture_test.go @@ -8,6 +8,7 @@ import ( "path/filepath" "strings" "testing" + "time" "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" @@ -367,3 +368,53 @@ func TestVisualNewProjectFieldDescriptions(t *testing.T) { } } } + +// TestVisualDebugAnnouncedAdapterExitedFirst captures the debug view after a synthetic +// tcpAnnounced adapter exited before it announced its port: the session ends and the +// view shows why. It needs only LITHE_VISUAL_OUTPUT_DIR. +func TestVisualDebugAnnouncedAdapterExitedFirst(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + for _, theme := range []string{"dark", "light"} { + for _, language := range []string{"zh-Hans", "en-US"} { + t.Run(theme+"-"+language, func(t *testing.T) { + var session *headless.Session + options := debugPluginOptions(t, "dev.lithe.test.debug-announced", debugAnnouncedManifest, true, &testKernel{Client: core.NewClient()}, theme) + options.Languages = []string{language} + h := newHarnessWithDriver(t, options, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1200, 760 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + root, _, watch := announcedWorkspace(t, "exit") + p := openHostedPanel(t, h, root) + h.clickNamed(h.app.text.Debug.Start) + awaitStateWithin(t, h, 20*time.Second, "the failure", func() bool { return p.debug.failure != "" }) + if p.debug.failure != h.app.text.Debug.NotAnnounced { + t.Fatalf("failure = %q, want the missing announcement", p.debug.failure) + } + watch.ended(t, 20*time.Second) + // The pointer leaves the start button so its tip does not cover the reason. + if err := h.driver.Move(800, 150); err != nil { + t.Fatal(err) + } + h.settle() + if tips := h.tooltips(); len(tips) != 0 { + t.Fatalf("tips still shown: %+v", tips) + } + if err := session.Screenshot(filepath.Join(out, "debug-announced-exited-"+theme+"-"+language+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index dc0a334377..5672c53b2c 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -28,6 +28,10 @@ native_path() { } PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" +# Lithe-core-rust #47, squash-merged into main as a58e07e: +# debug.adapters.readAnnouncement reads one line of a tcpAnnounced adapter's output against its +# declared endpoint (none, announced with a loopback host and port, or invalid), and an adapter's +# launch arguments may bind target.directory, the selected target's directory. It is on top of # Lithe-core-rust #46, squash-merged into main: the logging event catalog declares the events the # desktop records (terminal.session.start_failed, vcs.provider.skipped, # app.background.operation_failed, app.startup.leftovers_resolved, editor.recovery.applied and the @@ -96,7 +100,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="e81106827b3f0e5c8178742b6ef61a7a8a225f57" +PINNED_CORE_REVISION="a58e07e000627c37843b242525c46de5474ae37b" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index 2d868944c1..f3062afb3d 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -897,6 +897,7 @@ "desktop.debug.noExceptionFilters": "This debug adapter offers no exception breakpoints.", "desktop.debug.noFrames": "No stack frames", "desktop.debug.noVariables": "Pause the debuggee to inspect its variables.", + "desktop.debug.notAnnounced": "The debug adapter exited before printing the port it listens on.", "desktop.debug.openFrame": "Open the frame's source location", "desktop.debug.pause": "Pause", "desktop.debug.paused": "Paused", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 1ad40c2661..b6ed61e0ad 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -897,6 +897,7 @@ "desktop.debug.noExceptionFilters": "此调试适配器没有可选的异常断点。", "desktop.debug.noFrames": "没有栈帧", "desktop.debug.noVariables": "暂停后在这里查看变量。", + "desktop.debug.notAnnounced": "调试适配器还没输出它监听的端口就退出了。", "desktop.debug.openFrame": "打开栈帧的源码位置", "desktop.debug.pause": "暂停", "desktop.debug.paused": "已暂停", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 3854717852..7f26dbf63c 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -8144,7 +8144,7 @@ }, { "id": "desktop.debug.invalidEndpoint", - "description": "The debug adapter endpoint was outside the valid port range", + "description": "The debug adapter endpoint was outside the valid port range, or the address the adapter printed is malformed or not on this computer", "platforms": [ "desktop" ] @@ -8323,6 +8323,13 @@ "desktop" ] }, + { + "id": "desktop.debug.notAnnounced", + "description": "A debug adapter that should print the port it listens on exited before printing it", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.debug.openFrame", "description": "Open the frame's source location", diff --git a/shared/platform-feature-matrix/features/debug-tcp-transport.json b/shared/platform-feature-matrix/features/debug-tcp-transport.json index c88dc0aeec..fa322cd6dc 100644 --- a/shared/platform-feature-matrix/features/debug-tcp-transport.json +++ b/shared/platform-feature-matrix/features/debug-tcp-transport.json @@ -11,8 +11,11 @@ "desktop/internal/workbench/debug_transport_test.go", "desktop/internal/workbench/debug_start.go", "desktop/internal/workbench/debug_tcp_test.go", + "desktop/internal/workbench/debug_announced.go", + "desktop/internal/workbench/debug_announced_test.go", "desktop/internal/core/debug_transport.go", - "desktop/internal/core/debug_state_test.go" + "desktop/internal/core/debug_state_test.go", + "desktop/internal/core/debug_announcement_test.go" ] }, "windows": { @@ -23,13 +26,16 @@ "desktop/internal/workbench/debug_transport_test.go", "desktop/internal/workbench/debug_start.go", "desktop/internal/workbench/debug_tcp_test.go", + "desktop/internal/workbench/debug_announced.go", + "desktop/internal/workbench/debug_announced_test.go", "desktop/internal/core/debug_transport.go", - "desktop/internal/core/debug_state_test.go" + "desktop/internal/core/debug_state_test.go", + "desktop/internal/core/debug_announcement_test.go" ] }, "owner": "Debug", "verification": "macOS:在有已安装调试提供方的源码文件上,从 Debug 更多操作打开连接调试适配器,填写已运行的 DAP 服务地址、launch/attach 与适配器参数。分别验证回环、IPv4/IPv6/DNS 外部地址、非回环默认取消的逐次确认、错误 JSON 与非法端点。确认 IDE 到 DAP 的地址不覆盖适配器到 debuggee 的地址,既有 stdio 与 tcpLanguageServer 回环限制不变。验证端点发现与建连两段独立超时(冷启动发现不缩短也不拉长建连)、被拒绝/不可达端口立即以系统原因结束、连接拒绝或 initialize 超时/未获批准/已有活动会话时对话框保持打开并保留已填内容,初始化完成后才关闭;取消等待只停止本次连接,不能误停后来选中的会话、当前文件无调试提供方时菜单项不可用、单个在途写入、字节/消息预算、写入超时、EOF、解析/建连/已连接时取消和旧回调隔离(含 Core 桥接失败清理后重新登记的连接);停止时断开帧最多排空 1 秒且 attach 的 terminateDebuggee 为 false,超时仍回收;停止后外部服务、共享 LSP、attach 目标与用户隧道仍存活。真实回环测试覆盖 Core initialize/attach 帧;真实适配器和界面全链路仍待验收。Windows 未接入此 TCP 宿主。", - "notes": "语言服务器托管适配器的环回 TCP 连接改为按 Core 的 debug.transport.handle 生命周期驱动:帧先入队、同时只有一个写在途,发现/连接/写入期限与排空期限都是 Core 下发的定时器,用户停止时先发 DAP disconnect 再有界排空。直接连接用户指定的远程适配器端点(adapterEndpoint)仍未接入。", + "notes": "语言服务器托管适配器(tcpLanguageServer)和自行输出监听端口的适配器进程(tcpAnnounced)的环回 TCP 连接都按 Core 的 debug.transport.handle 生命周期驱动;tcpAnnounced 的端点由 Core 的 debug.adapters.readAnnouncement 从进程输出行读出,发现期限沿用 Core 默认值:帧先入队、同时只有一个写在途,发现/连接/写入期限与排空期限都是 Core 下发的定时器,用户停止时先发 DAP disconnect 再有界排空。直接连接用户指定的远程适配器端点(adapterEndpoint)仍未接入。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/plugin-debug-adapters.json b/shared/platform-feature-matrix/features/plugin-debug-adapters.json index 7ab029956d..df32cd3847 100644 --- a/shared/platform-feature-matrix/features/plugin-debug-adapters.json +++ b/shared/platform-feature-matrix/features/plugin-debug-adapters.json @@ -12,6 +12,8 @@ "desktop/internal/workbench/debug_launch.go", "desktop/internal/workbench/debug_view.go", "desktop/internal/workbench/debug_tcp_test.go", + "desktop/internal/workbench/debug_announced.go", + "desktop/internal/workbench/debug_announced_test.go", ".agents/notes/implemented/architecture/2026-11-10-viva-java-admission-run-debug-output-links.md" ] }, @@ -24,12 +26,14 @@ "desktop/internal/workbench/debug_launch.go", "desktop/internal/workbench/debug_view.go", "desktop/internal/workbench/debug_tcp_test.go", + "desktop/internal/workbench/debug_announced.go", + "desktop/internal/workbench/debug_announced_test.go", ".agents/notes/implemented/architecture/2026-11-10-viva-java-admission-run-debug-output-links.md" ] }, "owner": "Debug", - "verification": "macOS:安装声明了 debugAdapters 的插件,在其语言文件上启动调试,确认适配器按声明的 stdio 传输由宿主拉起并命中断点;可执行文件缺失时显示插件设置里的安装提示而不是笼统错误;声明 tcpPort 或 tcpAnnounced 传输的适配器在启动进程前被拒绝并说明原因。声明 tcpLanguageServer 传输的适配器(调试服务随同一插件的语言服务器运行)不由宿主拉起进程:宿主启动该插件声明的语言服务器,用 endpoint.command 向它要端口并连接 127.0.0.1,端口无效、语言服务器不属于该插件或不可用时会话以原因结束。从保存配置直接启动且未打开源码时也会激活、登记语言服务器并探测工具;停止调试取消端口命令而不停止共享语言服务器,拒绝工作区或会话替换后的旧端口。适配器只声明 attach,或 selectors 的 targetKinds 不含 file 时,不会被选作文件启动的调试器。capabilities.disabled 中的能力在调试会话里不可用,并随 debug.createSession 传给 Core。会话进行中禁用、更新或卸载该插件,或在模块设置里停用它,只停止该插件拥有的会话,同语言其他插件的会话继续运行。启动后 app bundle 文件清单不变(scripts/desktop/verify/verify-runtime-bundle-immutability.sh)。远程 attach 目前只有 Core 契约:attach 配置可声明 targetBindings.connection,Core 校验主机、端口与路径映射并按适配器自己的参数路径写入启动参数,非 localhost、127.0.0.0/8、::1 的端点返回 remote:true;macOS 宿主尚未接入 attach 与“附加到远程”对话框,因此本项暂不能在应用里验证远程附加,接入后补充:连接新的非回环端点前必须弹确认且默认不记住,附加结束只断开不结束远端程序。Windows:宿主尚未接入 debugAdapters,Core 校验通过不代表 Windows 能调试插件语言。 原生宿主路由回归:使用 Core 的 rust/fixtures/debug/adapter-selection-v1.json 验证自动文件选择、明确身份、无源文件目标、空身份、已撤回身份和 launch/attach 不匹配;同语言多个适配器分别收到断点,重试保持身份,附加会话启动失败保留原会话。这里只验证宿主交接与受控会话,Provider 原生程序准备 RPC 有受控流程与真实 SDK 进程覆盖;真实适配器的完整工作流与 Windows 接入仍未验收。 真实原生调试集成:公开 Node SDK Provider 用 Clang 编译 C 程序,经生产 macOS 会话、Core 准备、Registry 明确身份、生产 stdio 传输和 LLDB 命中源码断点、读取 main 栈帧、保留空格参数后继续并退出码 0;包 SHA-256/权限不变,所有本次进程回收。测试显式选择 SDK/工具,完整 UI、正式发行与 Windows 尚未验收,verification 保持 pending。 与显式 DAP 端点同时使用时,先按当前 Registry 身份校验请求能力,再调用端点工厂;launch/attach 与默认/明确身份的组合回归覆盖不会回退到本地适配器,配置编码与步进变换保留两个字段。 Windows 增量:服务目标显式保存并调试,唯一当前 Registry 类型/身份、Core 连接绑定、stdio/同包语言服务器、完整参数/初始化身份/禁用能力;覆盖重复/缺失适配器、包和设置变化、注册 ABA、监听取消、迟到启动回执、Run 退出/替换、清理失败重试。原生能力准入仍关闭,正式 Windows 适配器与真实框架断点 UI 尚未验收。 日志验收:在最新macOS宿主分别启动、初始化、暂停/继续、正常结束、取消、超时和适配器拒绝,确认debug/的关键生命周期INFO、内部状态DEBUG、真实失败ERROR;启动与原生进程非零退出固定stage/exit_code进入debug,原始stderr、DAP正文、源码、变量、内存和程序输出不进入诊断日志。同一次launch失败不能重复记session失败,取消不记ERROR。共享Core组件验证不能替代macOS真实UI和Windows v2验收。", - "notes": "Viva 声明 debugAdapters 1、2、3:stdio 与 tcpLanguageServer 适配器、launch 与 attach、远程 attach(Core 判定非本机的端点需用户确认,不记住答案;暂无路径映射输入)、features 与 defaults 随 debug.createSession 交给调试引擎。debug/start 宿主方法与 run/start 的 launch 目标已接入;launch.json 导入、tcpPort/tcpAnnounced 与 startDebugging 子会话暂未实现。原生产品验收仍 pending。", + "verification": "macOS:安装声明了 debugAdapters 的插件,在其语言文件上启动调试,确认适配器按声明的 stdio 传输由宿主拉起并命中断点;可执行文件缺失时显示插件设置里的安装提示而不是笼统错误;声明 tcpPort 传输的适配器在启动进程前被拒绝并说明原因。声明 tcpAnnounced 传输的适配器由宿主拉起进程,按 Core 的 debug.adapters.readAnnouncement 逐行读取声明的输出流:公告行不进调试控制台,其余输出照常显示;公告回环端点后连接并命中断点,暂停/继续正常,停止时先送达 disconnect 再停止进程;公告前退出显示“还没输出监听端口就退出”,公告非本机地址显示端点无效并停止进程,10 秒内没有公告按启动超时结束并停止进程。声明 tcpLanguageServer 传输的适配器(调试服务随同一插件的语言服务器运行)不由宿主拉起进程:宿主启动该插件声明的语言服务器,用 endpoint.command 向它要端口并连接 127.0.0.1,端口无效、语言服务器不属于该插件或不可用时会话以原因结束。从保存配置直接启动且未打开源码时也会激活、登记语言服务器并探测工具;停止调试取消端口命令而不停止共享语言服务器,拒绝工作区或会话替换后的旧端口。适配器只声明 attach,或 selectors 的 targetKinds 不含 file 时,不会被选作文件启动的调试器。capabilities.disabled 中的能力在调试会话里不可用,并随 debug.createSession 传给 Core。会话进行中禁用、更新或卸载该插件,或在模块设置里停用它,只停止该插件拥有的会话,同语言其他插件的会话继续运行。启动后 app bundle 文件清单不变(scripts/desktop/verify/verify-runtime-bundle-immutability.sh)。远程 attach 目前只有 Core 契约:attach 配置可声明 targetBindings.connection,Core 校验主机、端口与路径映射并按适配器自己的参数路径写入启动参数,非 localhost、127.0.0.0/8、::1 的端点返回 remote:true;macOS 宿主尚未接入 attach 与“附加到远程”对话框,因此本项暂不能在应用里验证远程附加,接入后补充:连接新的非回环端点前必须弹确认且默认不记住,附加结束只断开不结束远端程序。Windows:宿主尚未接入 debugAdapters,Core 校验通过不代表 Windows 能调试插件语言。 原生宿主路由回归:使用 Core 的 rust/fixtures/debug/adapter-selection-v1.json 验证自动文件选择、明确身份、无源文件目标、空身份、已撤回身份和 launch/attach 不匹配;同语言多个适配器分别收到断点,重试保持身份,附加会话启动失败保留原会话。这里只验证宿主交接与受控会话,Provider 原生程序准备 RPC 有受控流程与真实 SDK 进程覆盖;真实适配器的完整工作流与 Windows 接入仍未验收。 真实原生调试集成:公开 Node SDK Provider 用 Clang 编译 C 程序,经生产 macOS 会话、Core 准备、Registry 明确身份、生产 stdio 传输和 LLDB 命中源码断点、读取 main 栈帧、保留空格参数后继续并退出码 0;包 SHA-256/权限不变,所有本次进程回收。测试显式选择 SDK/工具,完整 UI、正式发行与 Windows 尚未验收,verification 保持 pending。 与显式 DAP 端点同时使用时,先按当前 Registry 身份校验请求能力,再调用端点工厂;launch/attach 与默认/明确身份的组合回归覆盖不会回退到本地适配器,配置编码与步进变换保留两个字段。 Windows 增量:服务目标显式保存并调试,唯一当前 Registry 类型/身份、Core 连接绑定、stdio/同包语言服务器、完整参数/初始化身份/禁用能力;覆盖重复/缺失适配器、包和设置变化、注册 ABA、监听取消、迟到启动回执、Run 退出/替换、清理失败重试。原生能力准入仍关闭,正式 Windows 适配器与真实框架断点 UI 尚未验收。 日志验收:在最新macOS宿主分别启动、初始化、暂停/继续、正常结束、取消、超时和适配器拒绝,确认debug/的关键生命周期INFO、内部状态DEBUG、真实失败ERROR;启动与原生进程非零退出固定stage/exit_code进入debug,原始stderr、DAP正文、源码、变量、内存和程序输出不进入诊断日志。同一次launch失败不能重复记session失败,取消不记ERROR。共享Core组件验证不能替代macOS真实UI和Windows v2验收。", + "notes": "Viva 声明 debugAdapters 0(契约版本已统一归 0,原 1、2、3 的内容都在其中):stdio、tcpAnnounced(宿主拉起进程,读取它输出的回环端口后连接)与 tcpLanguageServer 适配器、launch 与 attach、远程 attach(Core 判定非本机的端点需用户确认,不记住答案;暂无路径映射输入)、features 与 defaults 随 debug.createSession 交给调试引擎。debug/start 宿主方法与 run/start 的 launch 目标已接入;适配器的 startDebugging 子会话已接入(debug_child.go);launch.json 导入与 tcpPort 暂未实现。原生产品验收仍 pending。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": {