Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Agent 笔记:语言服务器里的调试适配器要等命令注册后再请求端口

状态:已实现

## 先说结论

有的调试适配器运行在插件的语言服务器里(`transport: tcpLanguageServer`,例如 Java Support 的 `java` 适配器跑在 JDT LS 里)。宿主通过 `workspace/executeCommand` 向语言服务器要调试端口。JDT LS 在“就绪”(初始化完成)之后,才用 `client/registerCapability` 动态注册它的命令;在注册之前,Core 会以 `not_supported`(“The language server did not advertise this capability.”)拒绝这个命令。现在宿主在语言服务器就绪之后,还要等它声明 `executeCommand` 能力,再请求端口。

## 问题

`discoverHostedPort` 以前只等语言服务器就绪(`waitReadyPluginServer`),就立即执行端点命令。如果语言服务器早已在运行,命令早就注册好了,不会出问题。但如果调试是第一个用到语言服务器的操作,例如打开项目后直接调试一个 Spring Boot 服务,那么服务器一就绪宿主就发出命令,这时注册还没到,Core 就会拒绝。用户看到的是调试启动失败,服务也随之被停止。

## 决策

- `discoverHostedPort` 在 `waitReadyPluginServer` 之后调用 `waitPluginServerFeature(ctx, server, "executeCommand", pluginServerStartTimeout)`。
- 能力以 Core 的 `featuresChanged` 事件为准。动态注册之后,Core 会重新发送这个事件,宿主把它记在 `pluginServer.features` 里。这个字段只在窗口线程读写,所以等待方每 50 ms 往窗口线程投递一次检查。
- 超时后返回 `errPluginServerFeatureMissing`,说明服务器从来没有提供这个能力,而不是一直等下去。

正确做法:等语言服务器提供某项能力时,以 `features` 为准。

不要这样做:把“就绪”当成“所有能力都已就位”;或者在命令返回 `not_supported` 时盲目重试。盲目重试分不清“还没注册”和“永远不会提供”。

## 考虑过的备选方案

- 在 Core 里把发给语言服务器的命令排队,等注册以后再发。所有宿主都能受益,但这样 Core 就要替动态注册猜测时序,和它“没有声明就拒绝”的现有规则冲突。另外宿主已经掌握做这个判断所需的事件。
- 在 Java Support 插件里改成静态声明命令。动态还是静态注册由 JDT LS 根据客户端能力自己决定,插件改不了;而且其他语言服务器也可能动态注册。
- 遇到 `not_supported` 时有界重试。能绕过问题,但每次重试都会产生一次失败的请求和日志,也无法提前判断服务器根本不提供该能力。

## 后果

- 调试作为第一个用到语言服务器的操作时也能启动;JDT LS 从冷启动到连上调试器,实测约 15 秒(包含 Maven 编译和服务启动)。
- 等待最长 `pluginServerStartTimeout`(2 分钟)。一个就绪但永远不注册命令的服务器,要等这么久才会失败。

## 验证

- `./scripts/desktop/desktop-go.sh test ./internal/workbench/ -run TestHostedDebugWaitsForTheServerToOfferCommands -count=1`:服务器声明命令之前,等待不会结束;声明之后立刻返回;从不声明时,在时限内返回 `errPluginServerFeatureMissing`。
- 这个问题是在真实的 JDT LS 上发现的:修复前,调试冷启动的 Spring Boot 服务会失败,报 `lsp.request: The language server did not advertise this capability. (not_supported)`。宿主测试只使用合成插件,所以回归测试直接驱动 `features`,模拟这个时序。

## 适用范围

- `desktop/internal/workbench/debug_start.go`
- `desktop/internal/workbench/debug_tcp_test.go`
- `desktop/internal/workbench/editor_requests.go`
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Agent 笔记:运行进程不受准备阶段的时限约束

状态:已实现

## 先说结论

工作台启动一个运行(构建插件准备的运行,或命令型运行)时,以前把整段后台任务放在 30 分钟的请求时限(`buildRequestTimeout`)下,进程也用这个上下文启动。`buildprocess.Start` 在上下文结束时会杀掉进程,所以 Spring Boot 这类常驻服务运行满 30 分钟就被结束。现在只有“准备”阶段受时限约束(`runPreparationTimeout`),进程本身一直运行到自己退出、用户停止或项目关闭。以后新增启动长时间进程的路径,进程不能用带时限的上下文启动。

## 问题

`a.background(p, timeout, work)` 给 `work` 的上下文带着 `timeout`。运行路径在同一个 `work` 里先做准备(Core 计划、解析工具、请求构建插件的 `lithe/build/prepareRun`),再用同一个上下文调用 `buildprocess.Start`。准备需要时限,防止插件或工具卡住时永远等下去;进程不需要,它的结束由用户的停止、项目关闭或进程自己决定。两者共用一个上下文,进程就继承了本该只给准备用的 30 分钟。

调试会把这个问题放大:断点停住时服务看起来空闲,用户调试半小时左右,服务和调试会话会一起消失,没有任何提示原因。

## 决策

- 运行路径(`runBuildTargetWith`、`runBuildEntry`)的后台任务不再带时限,上下文仍然在项目关闭时结束。
- 在任务内部用 `context.WithTimeout(ctx, runPreparationTimeout)` 派生出准备阶段的上下文,再交给 `op.bind`(用户停止时也结束)。计划、工具解析和构建插件请求都用这个上下文。
- `buildprocess.Start` 和等待调试端口用不带时限的上下文。

正确做法:

```go
a.background(p, 0, func(ctx context.Context) func(*App) {
bounded, cancel := context.WithTimeout(ctx, runPreparationTimeout)
defer cancel()
prepare, release := op.bind(bounded)
defer release()
// 用 prepare 做准备;用 ctx 启动进程
})
```

不要这样做:`a.background(p, buildRequestTimeout, ...)` 里直接 `buildprocess.Start(ctx, ...)` 启动用户会长期运行的进程。

## 考虑过的备选方案

- 把 `buildRequestTimeout` 调大(例如 24 小时)。服务仍然会在某个时刻被无故结束,只是更难发现;准备阶段的保护也随之失效。
- 进程用 `context.Background()` 启动。项目关闭时进程不再随上下文结束,只能依赖其他清理路径,容易留下孤儿进程。
- 构建任务(`runBuildTask`)也一起改。任务是有终点的构建,30 分钟时限能防止卡死的构建一直占着唯一的操作位;这次没有改,任务时限是否合适另行判断。

## 后果

- 常驻服务和调试中的服务可以一直运行;停止仍然走 `stopBuildOperation`,项目关闭仍然结束进程。
- 准备阶段的时限变成包级变量 `runPreparationTimeout`(默认仍是 30 分钟),测试可以缩短它。
- 进程的生命周期不再有兜底时限:一个忘了停的服务会一直占用资源,直到用户停止或关闭项目,这和 IDEA 的行为一致。

## 验证

- `./scripts/desktop/desktop-go.sh test ./internal/workbench/ -run TestServiceRunOutlivesItsPreparationBound -count=1`:把准备时限缩短到 5 秒,服务运行 6 秒后写出标记文件。修复前服务在第 5 秒被结束(`signal: killed`),修复后通过。

## 适用范围

- `desktop/internal/workbench/build.go`
- `desktop/internal/workbench/build_connection_debug_test.go`
23 changes: 22 additions & 1 deletion desktop/internal/core/run_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,13 +124,34 @@ type RunLaunchOptions struct {
Environment map[string]string `json:"environment"`
Entrypoint string `json:"entrypoint,omitempty"`
WorkingDirectory string `json:"workingDirectory,omitempty"`
// Debug asks for a service suspended until the selected adapter attaches
// (registry connection debugging); nil runs it without a debugger. Core
// resolves no debug choice from the saved layers: the host sets it per launch.
Debug *RunLaunchDebug `json:"debug,omitempty"`
}

// RunLaunchDebug is `launchOptions.debug`: the registry adapter the host selected
// for the run's declared type, and the loopback endpoint the host owns, on which
// the service waits for that adapter.
type RunLaunchDebug struct {
// AdapterID is the selected adapter's qualified identity, `pluginID/adapterID`.
AdapterID string `json:"adapterID"`
ConfigurationType string `json:"configurationType"`
Target RunDebugConnection `json:"target"`
}

// RunDebugConnection is a debuggee endpoint: Kind "connection" on Host:Port.
type RunDebugConnection struct {
Kind string `json:"kind"`
Host string `json:"host"`
Port int `json:"port"`
}

// Customized says whether the options ask for anything a launch without them
// would not do, so an application run with none keeps the version 4 request.
func (o RunLaunchOptions) Customized() bool {
return (o.Execution != "" && o.Execution != "application") || len(o.RuntimeArguments) > 0 || len(o.Arguments) > 0 ||
len(o.Environment) > 0 || o.Entrypoint != "" || o.WorkingDirectory != ""
len(o.Environment) > 0 || o.Entrypoint != "" || o.WorkingDirectory != "" || o.Debug != nil
}

// RunProviderLaunchInputs is what `runConfig.providerLaunchInputs` resolves for
Expand Down
10 changes: 10 additions & 0 deletions desktop/internal/i18n/shared.generated.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

16 changes: 14 additions & 2 deletions desktop/internal/pluginservice/builds.go
Original file line number Diff line number Diff line change
Expand Up @@ -111,8 +111,18 @@ type BuildRunDeclaration struct {
Execution string
Tags []string
// DebugAdapter is the local ID of the plugin's own adapter the run declares for native
// debug preparation (`debug.adapter`), empty when the run cannot be debugged.
// debug preparation (`debug.adapter`), empty when the run does not debug that way.
DebugAdapter string
// DebugConfigurationType is the public debug adapter type a service run declares for
// registry connection debugging (`debug.configurationType`): the run listens on a port the
// host chooses, and the one enabled adapter of that type attaches to it. Empty when the
// run does not debug that way.
DebugConfigurationType string
}

// Debuggable reports whether the run declares a way to debug it.
func (r BuildRunDeclaration) Debuggable() bool {
return r.DebugAdapter != "" || r.DebugConfigurationType != ""
}

// BuildPlugins reads the newest enabled version of every plugin that declares
Expand Down Expand Up @@ -175,7 +185,8 @@ type rawBuildManifest struct {
Tags []string `json:"tags"`
} `json:"fromTargets"`
Debug *struct {
Adapter string `json:"adapter"`
Adapter string `json:"adapter"`
ConfigurationType string `json:"configurationType"`
} `json:"debug"`
} `json:"run"`
Test *struct {
Expand Down Expand Up @@ -235,6 +246,7 @@ func parseBuildSystems(manifest json.RawMessage) (map[string]BuildSystemDeclarat
}
if run.Debug != nil {
declaration.DebugAdapter = run.Debug.Adapter
declaration.DebugConfigurationType = run.Debug.ConfigurationType
}
system.Runs = append(system.Runs, declaration)
}
Expand Down
26 changes: 17 additions & 9 deletions desktop/internal/pluginservice/runs.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@ const (
methodRunStop = pluginhost.MethodPrefix + "run/stop"
notifyRunDidExit = pluginhost.MethodPrefix + "run/didExit"

// runDebugConnectTimeout bounds waiting for a debuggee to open the port the
// backend named. A runtime that never listens must not hold the run forever.
runDebugConnectTimeout = 30 * time.Second
// RunDebugConnectTimeout bounds waiting for a debuggee to open the port its
// run listens on. A runtime that never listens must not hold the run forever.
RunDebugConnectTimeout = 30 * time.Second
// runDebugPollInterval is how often the port is probed while waiting.
runDebugPollInterval = 100 * time.Millisecond
// runStopTimeout bounds waiting, beyond the stop time, for a stopped run's process tree to be reaped.
Expand Down Expand Up @@ -578,7 +578,7 @@ func (r *Runs) attachDebugger(ctx context.Context, run *hostRun) {
r.stopRun(run, false)
}
}
if err := waitForPort(ctx, port, run.done, runDebugConnectTimeout); err != nil {
if err := WaitForDebugPort(ctx, port, run.done, RunDebugConnectTimeout); err != nil {
fail(err)
return
}
Expand All @@ -598,9 +598,17 @@ func (r *Runs) attachDebugger(ctx context.Context, run *hostRun) {
run.debug.Store(&session)
}

// waitForPort polls a loopback port until something accepts, the run ends, or the
// timeout passes.
func waitForPort(ctx context.Context, port int, ended <-chan struct{}, timeout time.Duration) error {
// ErrDebuggeeEnded and ErrDebugPortTimeout are why WaitForDebugPort gave up: the
// debuggee's process ended, or its port did not open within the timeout.
var (
ErrDebuggeeEnded = errors.New("the process ended before its debug port opened")
ErrDebugPortTimeout = errors.New("the debug port did not open in time")
)

// WaitForDebugPort polls a debuggee's loopback port until something accepts, ended
// is closed, or the timeout passes. The probe connects and closes without a
// handshake; a runtime suspended for a debugger keeps listening after it.
func WaitForDebugPort(ctx context.Context, port int, ended <-chan struct{}, timeout time.Duration) error {
deadline := time.NewTimer(timeout)
defer deadline.Stop()
ticker := time.NewTicker(runDebugPollInterval)
Expand All @@ -617,9 +625,9 @@ func waitForPort(ctx context.Context, port int, ended <-chan struct{}, timeout t
case <-ctx.Done():
return ctx.Err()
case <-ended:
return errors.New("the process ended before its debug port opened")
return ErrDebuggeeEnded
case <-deadline.C:
return fmt.Errorf("the debug port %d did not open in time", port)
return fmt.Errorf("%w (port %d)", ErrDebugPortTimeout, port)
case <-ticker.C:
}
}
Expand Down
Loading
Loading