diff --git a/.agents/notes/implemented/bug-fix/2026-11-17-hosted-debug-waits-for-registered-commands.md b/.agents/notes/implemented/bug-fix/2026-11-17-hosted-debug-waits-for-registered-commands.md new file mode 100644 index 0000000000..092d78952a --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-17-hosted-debug-waits-for-registered-commands.md @@ -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` diff --git a/.agents/notes/implemented/bug-fix/2026-11-17-run-process-outlives-preparation-timeout.md b/.agents/notes/implemented/bug-fix/2026-11-17-run-process-outlives-preparation-timeout.md new file mode 100644 index 0000000000..1d2f85c5a8 --- /dev/null +++ b/.agents/notes/implemented/bug-fix/2026-11-17-run-process-outlives-preparation-timeout.md @@ -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` diff --git a/desktop/internal/core/run_config.go b/desktop/internal/core/run_config.go index 46c32f655f..2f55220907 100644 --- a/desktop/internal/core/run_config.go +++ b/desktop/internal/core/run_config.go @@ -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 diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index c8ba27bc0f..1a56c0a683 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -74,11 +74,15 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.branch.search": "Search for branches and actions", "desktop.branch.smartCheckout": "Smart Checkout", "desktop.branch.tagsIn": "Tags in {repository}", + "desktop.build.ambiguousConnectionDebugAdapter": "Several enabled debug adapters of type “{type}” can attach to this run ({adapters}). Disable all but one in Settings > Plugins.", "desktop.build.argumentsRequired": "This task asks for arguments, which this window cannot collect yet.", "desktop.build.cancelled": "Build cancelled", "desktop.build.chooseTask": "Choose a build task first.", "desktop.build.chooseTaskScope": "Choose a project or target this task runs on first.", "desktop.build.commandUnsupported": "This build system answered with a command plan; provider-backed tasks are required here.", + "desktop.build.connectionDebugAdapterGone": "The debug adapter “{name}” was disabled or updated before the run was ready, so the run was stopped. Debug it again.", + "desktop.build.debugPortTimeout": "The run did not wait for a debugger within {seconds} seconds, so it was stopped. See the Run window for its output.", + "desktop.build.debugSessionRunning": "A debug session is already running. Stop it before debugging another run.", "desktop.build.debugTarget": "Debug", "desktop.build.dependenciesHelp": "The build tool reads the dependency tree only when this is first opened, which can take a while as the tool runs. The tree is then kept until the build systems are detected again or Reload is chosen on the build system or on Dependencies.", "desktop.build.detection": "Detection", @@ -104,6 +108,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.build.modelFailed": "The build model could not be loaded: {error}", "desktop.build.modelStopped": "Build model loading stopped", "desktop.build.noBuildSystems": "No provider-backed build system was detected.", + "desktop.build.noConnectionDebugAdapter": "No enabled plugin can debug this run: it needs a debug adapter of type “{type}” that attaches to a running program. Install or enable one in Settings > Plugins.", "desktop.build.noDebugAdapter": "The build provider's own plugin declares no debug adapter that can start a prepared program.", "desktop.build.noMatches": "No matching build items", "desktop.build.noOptions": "This build system declares no options.", @@ -2891,11 +2896,15 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.branch.search": "搜索分支和操作", "desktop.branch.smartCheckout": "智能检出", "desktop.branch.tagsIn": "{repository} 中的标签", + "desktop.build.ambiguousConnectionDebugAdapter": "有多个已启用的“{type}”类型调试适配器都能连接这个运行({adapters})。请在 设置 > 插件 中只保留一个。", "desktop.build.argumentsRequired": "此任务需要额外参数,当前窗口尚不能收集。", "desktop.build.cancelled": "构建已取消", "desktop.build.chooseTask": "请先选择一个构建任务。", "desktop.build.chooseTaskScope": "请先选择此任务可以运行的项目或目标。", "desktop.build.commandUnsupported": "此构建系统返回了命令计划;当前接入需要提供者驱动的任务。", + "desktop.build.connectionDebugAdapterGone": "调试适配器“{name}”在运行就绪前被停用或更新,运行已停止。请重新调试。", + "desktop.build.debugPortTimeout": "运行在 {seconds} 秒内没有等待调试器连接,已停止。输出见运行窗口。", + "desktop.build.debugSessionRunning": "已有调试会话在运行。请先停止它,再调试其他运行。", "desktop.build.debugTarget": "调试", "desktop.build.dependenciesHelp": "第一次展开时才让构建工具读取依赖树,构建工具运行期间可能要等一会儿。读到的依赖会一直保留,直到重新检测构建系统,或在构建系统或“依赖”上选“重新加载”。", "desktop.build.detection": "检测", @@ -2921,6 +2930,7 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.build.modelFailed": "构建模型加载失败:{error}", "desktop.build.modelStopped": "构建模型加载已停止", "desktop.build.noBuildSystems": "没有检测到由提供者驱动的构建系统。", + "desktop.build.noConnectionDebugAdapter": "没有已启用的插件能调试这个运行:它需要一个类型为“{type}”、能连接到运行中程序的调试适配器。请在 设置 > 插件 中安装或启用。", "desktop.build.noDebugAdapter": "该构建插件所属的插件没有声明可以启动已准备程序的调试适配器。", "desktop.build.noMatches": "没有匹配的构建项", "desktop.build.noOptions": "此构建系统没有声明可配置的选项。", diff --git a/desktop/internal/pluginservice/builds.go b/desktop/internal/pluginservice/builds.go index 194942201f..f1ca491122 100644 --- a/desktop/internal/pluginservice/builds.go +++ b/desktop/internal/pluginservice/builds.go @@ -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 @@ -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 { @@ -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) } diff --git a/desktop/internal/pluginservice/runs.go b/desktop/internal/pluginservice/runs.go index 651d253b0c..88ad1d7232 100644 --- a/desktop/internal/pluginservice/runs.go +++ b/desktop/internal/pluginservice/runs.go @@ -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. @@ -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 } @@ -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) @@ -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: } } diff --git a/desktop/internal/pluginservice/runs_test.go b/desktop/internal/pluginservice/runs_test.go index fd3099d905..d6a1bdf142 100644 --- a/desktop/internal/pluginservice/runs_test.go +++ b/desktop/internal/pluginservice/runs_test.go @@ -497,16 +497,16 @@ func TestWaitForPortGivesUpWhenTheProcessEnds(t *testing.T) { _ = listener.Close() ended := make(chan struct{}) close(ended) - err = waitForPort(context.Background(), port, ended, time.Minute) + err = WaitForDebugPort(context.Background(), port, ended, time.Minute) if err == nil || !strings.Contains(err.Error(), "ended") { t.Fatalf("err = %v, want the process-ended failure", err) } - if err := waitForPort(context.Background(), port, make(chan struct{}), 150*time.Millisecond); err == nil || !strings.Contains(err.Error(), "did not open") { + if err := WaitForDebugPort(context.Background(), port, make(chan struct{}), 150*time.Millisecond); err == nil || !strings.Contains(err.Error(), "did not open") { t.Fatalf("err = %v, want the timeout", err) } ctx, cancel := context.WithCancel(context.Background()) cancel() - if err := waitForPort(ctx, port, make(chan struct{}), time.Minute); err == nil { + if err := WaitForDebugPort(ctx, port, make(chan struct{}), time.Minute); err == nil { t.Fatal("a cancelled wait succeeded") } } diff --git a/desktop/internal/workbench/build.go b/desktop/internal/workbench/build.go index 4023d9b503..b12570e9a2 100644 --- a/desktop/internal/workbench/build.go +++ b/desktop/internal/workbench/build.go @@ -35,6 +35,11 @@ const ( buildOutputBytes = 4 << 20 ) +// runPreparationTimeout bounds what precedes a run's process: planning, resolving its tools and +// the provider's preparation. The process itself runs until it exits, the user stops it or the +// project closes: a service runs for as long as the user works with it. Tests shorten it. +var runPreparationTimeout = buildRequestTimeout + // buildState is the Run tool window's state for one project. All fields are // read and written on the window thread; provider and process objects may be // used from background goroutines but their own operations are synchronized. @@ -119,6 +124,10 @@ type buildOperation struct { session *runEntry // decoder decodes the execution's output on the goroutines that read it. decoder *outputDecoder + // debug is the adapter and port of a service run started for registry connection + // debugging, nil for a plain run; debugSession is the session attached to it, once it is. + debug *connectionDebug + debugSession *debugSession } // beginBuildOperation makes a new operation the window's current one and gives it the IDE @@ -1393,8 +1402,10 @@ func (a *App) runBuildEntry(p *project, entryID string) { op := a.beginBuildOperation(p, "run", entry.Name, "", restartWithInstance(instance.ID, func(a *App, p *project) { a.runBuildEntry(p, entryID) })) - a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { - prepare, release := op.bind(ctx) + 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() if err := a.runCommandTask(ctx, prepare, p, op, captured, plan, messages); err != nil { return func(a *App) { a.finishBuildError(p, op, err) } @@ -1406,6 +1417,24 @@ func (a *App) runBuildEntry(p *project, entryID string) { // runBuildTarget runs one target of the selected instance through the provider's run // declaration runID, under the project the target belongs to. func (a *App) runBuildTarget(p *project, targetID, runID string) { + instance := p.selectedBuildInstance() + if instance == nil { + return + } + run, ok := buildRunDeclaration(instance.System, runID) + if !ok { + a.operationRejected("build_run_target", "run_missing") + a.notifyError(a.text.Build.TargetMissing) + return + } + a.startBuildTarget(p, targetID, run, nil) +} + +// startBuildTarget runs one target of the selected instance through run, a target the user +// chose without a run configuration: an application run sends no launch options, as older +// providers expect, and a service or task run the empty ones Core requires. debug, when set, +// prepares the service suspended for its adapter. +func (a *App) startBuildTarget(p *project, targetID string, run pluginservice.BuildRunDeclaration, debug *connectionDebug) { instance := p.selectedBuildInstance() if instance == nil || p.build.operation != nil { return @@ -1416,15 +1445,37 @@ func (a *App) runBuildTarget(p *project, targetID, runID string) { a.notifyError(a.text.Build.TargetMissing) return } + runID := run.ID op := a.beginBuildOperation(p, "run", target.Name, "", restartWithInstance(instance.ID, func(a *App, p *project) { + if debug != nil { + a.debugBuildTarget(p, targetID, runID) + return + } a.runBuildTarget(p, targetID, runID) })) - a.runBuildTargetWith(p, op, instance, target.ProjectID, targetID, runID, nil) + var options *core.RunLaunchOptions + if (run.Execution != "" && run.Execution != "application") || debug != nil { + options = &core.RunLaunchOptions{Execution: run.Execution, RuntimeArguments: []string{}, Arguments: []string{}, Environment: map[string]string{}} + } + if debug != nil { + op.debug = debug + options.Debug = &debug.launch + } + a.runBuildTargetWith(p, op, instance, target.ProjectID, targetID, runID, options) } // debugBuildTarget debugs one target of the Build window's selected instance and project -// through the provider's run declaration runID. +// through the provider's run declaration runID: through the adapter of the run's own plugin +// when it names one, otherwise as a service the registered adapter of its type attaches to. func (a *App) debugBuildTarget(p *project, targetID, runID string) { + instance := p.selectedBuildInstance() + if instance == nil { + return + } + if run, ok := buildRunDeclaration(instance.System, runID); ok && run.DebugAdapter == "" && run.DebugConfigurationType != "" { + a.debugServiceTarget(p, targetID, run) + return + } a.debugProviderTarget(p, p.build.selected, p.build.projectID, targetID, runID) } @@ -1599,8 +1650,10 @@ func (a *App) runBuildTargetWith(p *project, op *buildOperation, instance *build captured := *instance kernel := a.kernel messages := a.text.Build - a.background(p, buildRequestTimeout, func(ctx context.Context) func(*App) { - prepare, release := op.bind(ctx) + 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() request := core.BuildPlanRequest{ Root: captured.Root, @@ -1681,7 +1734,12 @@ func (a *App) runBuildTargetWith(p *project, op *buildOperation, instance *build return func(a *App) { a.finishBuildError(p, op, err) } } a.post(func(a *App) { a.attachProcess(p, op, process) }) + ended := make(chan struct{}) + if op.debug != nil { + go a.attachServiceDebugger(ctx, p, op, *op.debug, ended) + } err = process.Wait() + close(ended) return func(a *App) { a.finishBuildRun(p, op, err) } }) } @@ -1814,6 +1872,7 @@ func (a *App) finishBuildTask(p *project, op *buildOperation, result json.RawMes // finishBuildRun ends a host process with how it exited: a non-zero exit fails with its code, // and a process that could not be waited for or ended on a signal fails without one. func (a *App) finishBuildRun(p *project, op *buildOperation, err error) { + a.endServiceDebugSession(p, op) var exit *exec.ExitError switch { case op.cancelled: diff --git a/desktop/internal/workbench/build_connection_debug.go b/desktop/internal/workbench/build_connection_debug.go new file mode 100644 index 0000000000..a12a845664 --- /dev/null +++ b/desktop/internal/workbench/build_connection_debug.go @@ -0,0 +1,216 @@ +package workbench + +import ( + "context" + "errors" + "net" + "slices" + "strconv" + "strings" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" +) + +// Registry connection debugging of build provider service runs: a run declares a public debug +// adapter type (`debug.configurationType`) instead of an adapter of its own plugin. The host +// selects the one enabled adapter of that type that attaches over a connection, chooses a +// loopback port, asks the provider to prepare the service suspended on that port +// (`launchOptions.debug`), starts it as an ordinary run and attaches the adapter once the port +// accepts. The run and the debug session end together. The contract is Core's "Registry +// connection debugging"; the adapter may belong to any plugin. + +// connectionDebug is one debug launch of a service run: the adapter the host selected, kept to +// attach exactly that registration, and the debug options the provider prepares the run with. +type connectionDebug struct { + adapter debugAdapter + launch core.RunLaunchDebug +} + +// connectionDebugRefusal is why no adapter can attach to a run's declared type: reason is the +// fixed log token, message the notice. +type connectionDebugRefusal struct { + reason, message string +} + +func (r *connectionDebugRefusal) Error() string { return r.reason } + +// connectionDebugAdapter selects the enabled adapter that attaches over a connection and answers +// to configurationType. None, or more than one, is refused: nothing would attach to a suspended +// service, and picking one of several would be a guess. +func (a *App) connectionDebugAdapter(p *project, configurationType string) (debugAdapter, error) { + var matches []debugAdapter + for _, adapter := range p.debug.adapters { + if adapter.Declaration.Serves("attach") && adapter.Declaration.AcceptsConnection && + slices.Contains(adapter.Declaration.ConfigurationTypes, configurationType) { + matches = append(matches, adapter) + } + } + lang := a.language() + switch len(matches) { + case 1: + return matches[0], nil + case 0: + return debugAdapter{}, &connectionDebugRefusal{"no_adapter", i18n.SharedFormat(lang, "desktop.build.noConnectionDebugAdapter", map[string]string{"type": configurationType})} + } + names := make([]string, len(matches)) + for index, adapter := range matches { + names[index] = adapter.Declaration.DisplayName + } + return debugAdapter{}, &connectionDebugRefusal{"ambiguous_adapter", i18n.SharedFormat(lang, "desktop.build.ambiguousConnectionDebugAdapter", map[string]string{ + "type": configurationType, "adapters": strings.Join(names, ", "), + })} +} + +// sameDebugAdapter reports whether two adapters are the same registration of the same installed +// plugin version. +func sameDebugAdapter(a, b debugAdapter) bool { + return a.PluginID == b.PluginID && a.Version == b.Version && a.Directory == b.Directory && a.Declaration.ID == b.Declaration.ID +} + +// freeLoopbackPort returns a loopback TCP port nothing listens on now; the debuggee binds it. +func freeLoopbackPort() (int, error) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + return 0, err + } + port := listener.Addr().(*net.TCPAddr).Port + return port, listener.Close() +} + +// prepareConnectionDebug selects the adapter for a run's declared type once the installed +// adapters are read, chooses the port and hands both to start, on the window thread. A debug +// session that already runs, or a refused selection, starts nothing and says why. +func (a *App) prepareConnectionDebug(p *project, configurationType string, start func(connectionDebug)) { + if p == nil { + return + } + if p.build.operation != nil { + a.notifyInfo(i18n.Shared(a.language(), "desktop.title.runBusy")) + return + } + a.whenDebugAdaptersLoaded(p, func() { + if p.debug.activeSession() != nil { + a.operationRejected("build_debug_connection", "session_running") + a.notifyInfo(i18n.Shared(a.language(), "desktop.build.debugSessionRunning")) + return + } + adapter, err := a.connectionDebugAdapter(p, configurationType) + if err != nil { + var refusal *connectionDebugRefusal + if errors.As(err, &refusal) { + a.operationRejected("build_debug_connection", refusal.reason) + a.notifyError(refusal.message) + } + return + } + port, err := freeLoopbackPort() + if err != nil { + a.operationFailed("build_debug_port", err) + a.notifyError(err.Error()) + return + } + start(connectionDebug{adapter: adapter, launch: core.RunLaunchDebug{ + AdapterID: adapter.PluginID + "/" + adapter.Declaration.ID, + ConfigurationType: configurationType, + Target: core.RunDebugConnection{Kind: "connection", Host: "127.0.0.1", Port: port}, + }}) + }) +} + +// debugRunConfiguration debugs configuration id, whose run declares a public debug type: the +// configuration's saved launch options apply as for Run, with the service suspended for the +// selected adapter. +func (a *App) debugRunConfiguration(p *project, id, configurationType string) { + a.prepareConnectionDebug(p, configurationType, func(debug connectionDebug) { + if _, err := a.startRunConfigurationWith(p, id, &debug); errors.Is(err, errBuildBusy) { + a.notifyInfo(i18n.Shared(a.language(), "desktop.title.runBusy")) + } + }) +} + +// debugServiceTarget debugs one target of the selected instance through run, a service run that +// declares a public debug type, with the launch options of a run that has no configuration. +func (a *App) debugServiceTarget(p *project, targetID string, run pluginservice.BuildRunDeclaration) { + a.prepareConnectionDebug(p, run.DebugConfigurationType, func(debug connectionDebug) { + a.startBuildTarget(p, targetID, run, &debug) + }) +} + +// attachServiceDebugger waits off the window thread until the debuggee listens on its port, then +// attaches the selected adapter on the window thread. A debuggee that never listens ends the run +// with the reason; one that exits first ends the run the ordinary way, as its exit reports. +func (a *App) attachServiceDebugger(ctx context.Context, p *project, op *buildOperation, debug connectionDebug, ended <-chan struct{}) { + err := pluginservice.WaitForDebugPort(ctx, debug.launch.Target.Port, ended, pluginservice.RunDebugConnectTimeout) + a.post(func(a *App) { + if a.project != p || p.build.operation != op || op.cancelled { + return + } + switch { + case err == nil: + // A plugin change since the selection is read first, so the adapter is checked + // against the plugins as they are now. + a.whenDebugAdaptersLoaded(p, func() { + if p.build.operation == op && !op.cancelled { + a.attachServiceDebugSession(p, op, debug) + } + }) + case errors.Is(err, pluginservice.ErrDebuggeeEnded) || errors.Is(err, context.Canceled): + default: + a.operationFailed("build_debug_attach", err) + a.notifyError(i18n.SharedFormat(a.language(), "desktop.build.debugPortTimeout", map[string]string{ + "seconds": strconv.Itoa(int(pluginservice.RunDebugConnectTimeout.Seconds())), + })) + a.stopBuildOperation(p) + } + }) +} + +// attachServiceDebugSession starts the debug session on the selected adapter, which must still +// be installed and enabled as selected, attached to the service's port. The session owns the +// run: stopping it stops the service. +func (a *App) attachServiceDebugSession(p *project, op *buildOperation, debug connectionDebug) { + index := slices.IndexFunc(p.debug.adapters, func(adapter debugAdapter) bool { return sameDebugAdapter(adapter, debug.adapter) }) + if index < 0 { + a.operationFailed("build_debug_attach", errors.New("the selected debug adapter was disabled or replaced")) + a.notifyError(i18n.SharedFormat(a.language(), "desktop.build.connectionDebugAdapterGone", map[string]string{"name": debug.adapter.Declaration.DisplayName})) + a.stopBuildOperation(p) + return + } + if p.debug.activeSession() != nil { + a.operationRejected("build_debug_connection", "session_running") + a.notifyInfo(i18n.Shared(a.language(), "desktop.build.debugSessionRunning")) + a.stopBuildOperation(p) + return + } + a.beginDebug(p, debugStart{ + adapter: p.debug.adapters[index], request: "attach", confirmed: true, + target: &core.DebugTargetFacts{Kind: "connection", Host: debug.launch.Target.Host, Port: debug.launch.Target.Port}, + // Release calls stopRun off the window thread. + stopRun: func() { + a.post(func(a *App) { + if p.build.operation == op { + a.stopBuildOperation(p) + } + }) + }, + }) + session := p.debug.activeSession() + if session == nil { + // beginDebug reported why the session did not start; nothing debugs the suspended service. + a.stopBuildOperation(p) + return + } + op.debugSession = session +} + +// endServiceDebugSession ends the debug session attached to op's service once the service +// ended, so a session never outlives the process it debugs. +func (a *App) endServiceDebugSession(p *project, op *buildOperation) { + session := op.debugSession + if session == nil || !slices.Contains(p.debug.sessions, session) { + return + } + a.endDebugSession(p, session) +} diff --git a/desktop/internal/workbench/build_connection_debug_test.go b/desktop/internal/workbench/build_connection_debug_test.go new file mode 100644 index 0000000000..97aade036e --- /dev/null +++ b/desktop/internal/workbench/build_connection_debug_test.go @@ -0,0 +1,381 @@ +package workbench + +import ( + "encoding/json" + "net" + "os" + "path/filepath" + "runtime" + "strconv" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginstate" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" +) + +// fixtureServicePortVariable carries the debug port from the fixture provider's run plan to the +// fixture service process (TestFixtureServiceRunner). +const fixtureServicePortVariable = "LITHE_FIXTURE_SERVICE_PORT" + +// fixtureServiceLifetime bounds a fixture service the host never stops, so a broken test cannot +// leave it listening. +const fixtureServiceLifetime = 2 * time.Minute + +// fixtureServiceAliveVariable names a file the fixture service writes once it has run for +// fixtureServiceAliveAfter, which proves the host let it run that long. +const ( + fixtureServiceAliveVariable = "LITHE_FIXTURE_SERVICE_ALIVE" + fixtureServiceAliveAfter = 6 * time.Second +) + +// TestFixtureServiceRunner is the fixture service a provider run starts for debugging: the +// copied test binary, found on PATH as fixture-service. It listens on the debug port the host +// chose, as a runtime suspended until a debugger attaches does, and accepts and closes +// connections until the host stops it. +func TestFixtureServiceRunner(t *testing.T) { + port := os.Getenv(fixtureServicePortVariable) + if port == "" { + t.Skip("not a fixture service run") + } + listener, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", port)) + if err != nil { + os.Exit(2) + } + go func() { + for { + connection, err := listener.Accept() + if err != nil { + return + } + _ = connection.Close() + } + }() + if alive := os.Getenv(fixtureServiceAliveVariable); alive != "" { + // The parent waits on the file this writes, never on a timer. + // test-stability: allow(go-real-sleep) reason: whether the host lets a service outlive its preparation bound only shows after that much time has passed. + time.Sleep(fixtureServiceAliveAfter) + if err := os.WriteFile(alive, []byte("alive\n"), 0o600); err != nil { + os.Exit(3) + } + } + // test-stability: allow(go-real-sleep) reason: this is the service process itself, which serves until the host stops it; the bound only ends a service a broken test never stopped. + time.Sleep(fixtureServiceLifetime) + os.Exit(0) +} + +// providerServiceDebugManifest is the provider fixture with a service run of the targets tagged +// app that debugs through any enabled adapter of the public type fixture-attach. +var providerServiceDebugManifest = strings.Replace(providerTestsManifest, `"model": {"source": "provider"},`, + `"model": {"source": "provider"}, + "run": [{"id": "service", "source": "provider", "fromTargets": {"tags": ["app"]}, "execution": "service", "debug": {"configurationType": "fixture-attach"}}],`, 1) + +// registryAttachManifest is an attach adapter of another plugin that answers to the type +// fixture-attach and binds a connection target. +func registryAttachManifest(id string) string { + manifest := strings.Replace(debugAttachManifest, `"dev.lithe.test.debug-attach"`, `"`+id+`"`, 1) + return strings.Replace(manifest, `"requests": ["attach"],`, `"requests": ["attach"], + "configurationTypes": ["fixture-attach"],`, 1) +} + +// connectionDebugHarness installs the provider plugin and the given adapter plugins (ID to +// manifest), each with the copied test binary as its program, and puts the fixture build tool +// and the fixture service on PATH. +func connectionDebugHarness(t *testing.T, adapters map[string]string) *harness { + t.Helper() + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, settingsFile), []byte(`{"theme":"dark"}`), 0o600); err != nil { + t.Fatal(err) + } + preferences := store.At(dir) + pluginRoot := t.TempDir() + install := func(id, manifest, program string) { + installed := filepath.Join(pluginRoot, id, "1.0.0") + if err := os.MkdirAll(installed, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(installed, "plugin.json"), []byte(manifest), 0o600); err != nil { + t.Fatal(err) + } + copyTestBinary(t, filepath.Join(installed, program)) + if err := pluginstate.New(preferences).SetEnabled(id, true); err != nil { + t.Fatal(err) + } + } + install("dev.lithe.test.provider-tests", providerServiceDebugManifest, "provider") + for id, manifest := range adapters { + if runtime.GOOS == "windows" { + manifest = strings.ReplaceAll(manifest, `"path": "adapter"`, `"path": "adapter.exe"`) + } + install(id, manifest, debugFixtureProgramName()) + } + // The host resolves the provider's build tool before it starts the provider, which never + // runs it; the run plan names the fixture service as a command on PATH. + bin := t.TempDir() + tool, service := filepath.Join(bin, "fixture-tool"), filepath.Join(bin, "fixture-service") + if runtime.GOOS == "windows" { + tool, service = tool+".exe", service+".exe" + t.Setenv("PATHEXT", ".EXE") + } + if err := writeFakeExecutable(tool); err != nil { + t.Fatal(err) + } + copyTestBinary(t, service) + t.Setenv("PATH", bin+string(filepath.ListSeparator)+os.Getenv("PATH")) + return newHarnessWithOptions(t, Options{ + Kernel: &testKernel{Client: core.NewClient()}, + PluginKernel: &testKernel{Client: core.NewClient()}, + PluginRoot: pluginRoot, + Store: preferences, + Languages: []string{"zh-Hans"}, + // The provider is a copy of this large instrumented test binary: under load its start + // can exceed Core's 10s default. The bound stays finite. + PluginInitializeTimeout: 60 * time.Second, + }) +} + +// openServiceDebugProject opens the provider fixture workspace with its service target and +// returns the project once its run configurations list the service. +func openServiceDebugProject(t *testing.T, h *harness) (*project, string) { + t.Helper() + root := t.TempDir() + // debug.marker lets the fixture adapter serve DAP in this workspace (TestDebugAdapterRunner). + for _, marker := range []string{"fixture.marker", "discovery.marker", "service.marker", "debug.marker"} { + if err := os.WriteFile(filepath.Join(root, marker), []byte("fixture\n"), 0o600); err != nil { + t.Fatal(err) + } + } + if err := os.MkdirAll(filepath.Join(root, "lib"), 0o700); err != nil { + t.Fatal(err) + } + h.open(root) + p := h.app.project + h.app.post(func(a *App) { a.loadTitleRunConfigs(p) }) + awaitStateWithin(t, h, time.Minute, "the service configuration", func() bool { + return len(p.build.instances) == 1 && p.build.instances[0].modelLoaded && p.runConfigsSettled() && len(p.runConfigs.list) > 0 + }) + configuration := p.runConfigs.list[0] + if len(p.runConfigs.list) != 1 || configuration.Execution != "service" { + t.Fatalf("run configurations = %+v, want the one service", p.runConfigs.list) + } + return p, configuration.ID +} + +// preparedDebug is the launchOptions.debug the fixture provider received. +type preparedDebug struct { + Execution string `json:"execution"` + Debug *struct { + AdapterID string `json:"adapterID"` + ConfigurationType string `json:"configurationType"` + Target struct { + Kind string `json:"kind"` + Host string `json:"host"` + Port int `json:"port"` + } `json:"target"` + } `json:"debug"` +} + +// readPreparedRun reads what the fixture provider was asked to prepare. +func readPreparedRun(t *testing.T, root string) preparedDebug { + t.Helper() + data, err := os.ReadFile(filepath.Join(root, "prepare-run.json")) + if err != nil { + t.Fatal(err) + } + var params struct { + LaunchOptions preparedDebug `json:"launchOptions"` + } + if err := json.Unmarshal(data, ¶ms); err != nil { + t.Fatal(err) + } + return params.LaunchOptions +} + +// Debug on a service configuration whose run names a public debug type starts the service +// through its provider with a host-chosen loopback port, then attaches the one enabled adapter +// of that type, which another plugin installs. Stopping the debug session stops the service. +// The host used to read only same-plugin adapters, so it called the configuration not +// debuggable. +func TestTitleDebugAttachesTheRegisteredAdapterToAServiceRun(t *testing.T) { + h := connectionDebugHarness(t, map[string]string{"dev.lithe.test.registry-attach": registryAttachManifest("dev.lithe.test.registry-attach")}) + gate := &captureDebugLaunch{Kernel: h.app.kernel, configurations: make(chan core.DebugLaunchConfiguration, 1)} + h.app.kernel = gate + p, id := openServiceDebugProject(t, h) + t.Cleanup(func() { + if !t.Failed() { + return + } + console := "" + if runs := p.build.runs; len(runs) > 0 { + console = runs[len(runs)-1].output.all() + } + t.Logf("notice %q, build status %q, debug failure %q, run console:\n%s", lastNotice(h), p.build.status, p.debug.failure, console) + }) + + h.app.post(func(a *App) { + a.chooseTitleConfiguration(p, id) + a.titleDebug(p) + }) + configuration := awaitValueWithin(t, h, time.Minute, gate.configurations, "the attach to the service") + prepared := readPreparedRun(t, p.root) + if prepared.Execution != "service" || prepared.Debug == nil { + t.Fatalf("the provider prepared %+v, want a service run with a debug target", prepared) + } + debug := prepared.Debug + if debug.AdapterID != "dev.lithe.test.registry-attach/attach" || debug.ConfigurationType != "fixture-attach" || + debug.Target.Kind != "connection" || debug.Target.Host != "127.0.0.1" || debug.Target.Port <= 0 { + t.Fatalf("launchOptions.debug = %+v", *debug) + } + if configuration.Request != "attach" || configuration.Arguments["hostName"] != "127.0.0.1" || !sameDebugPort(configuration.Arguments["port"], debug.Target.Port) { + t.Fatalf("attach configuration = %+v, want the service's port %d", configuration, debug.Target.Port) + } + session := p.debug.activeSession() + if session == nil || session.adapter.PluginID != "dev.lithe.test.registry-attach" { + t.Fatalf("debug session = %+v, want the registered adapter's", session) + } + if p.build.operation == nil { + t.Fatal("the service is not running while it is debugged") + } + + // Stop in the Debug window ends the service it attached to. + h.app.post(func(a *App) { a.stopDebugByUser(p) }) + awaitStateWithin(t, h, time.Minute, "the stopped service", func() bool { return p.build.operation == nil && p.debug.activeSession() == nil }) + listener, err := net.Listen("tcp", net.JoinHostPort("127.0.0.1", strconv.Itoa(debug.Target.Port))) + if err != nil { + t.Fatalf("the service still holds its debug port after Stop: %v", err) + } + _ = listener.Close() +} + +// sameDebugPort reports whether a DAP argument decoded from JSON is port. +func sameDebugPort(value any, port int) bool { + switch number := value.(type) { + case float64: + return number == float64(port) + case int64: + return number == int64(port) + case uint64: + return number == uint64(port) + } + return false +} + +// Without an enabled adapter of the run's type, or with two of them, Debug refuses before the +// provider prepares anything: nothing would attach to the suspended service, and choosing one of +// two would be a guess. +func TestServiceDebugRefusesAMissingOrAmbiguousAdapterBeforePreparing(t *testing.T) { + for _, tc := range []struct { + name string + adapters map[string]string + notice func(lang i18n.Language) string + }{ + { + name: "missing", + adapters: map[string]string{"dev.lithe.test.debug-attach": debugAttachManifest}, + notice: func(lang i18n.Language) string { + return i18n.SharedFormat(lang, "desktop.build.noConnectionDebugAdapter", map[string]string{"type": "fixture-attach"}) + }, + }, + { + name: "ambiguous", + adapters: map[string]string{ + "dev.lithe.test.registry-attach": registryAttachManifest("dev.lithe.test.registry-attach"), + "dev.lithe.test.registry-attach2": registryAttachManifest("dev.lithe.test.registry-attach2"), + }, + notice: func(lang i18n.Language) string { + return i18n.SharedFormat(lang, "desktop.build.ambiguousConnectionDebugAdapter", map[string]string{"type": "fixture-attach", "adapters": "Attach DAP, Attach DAP"}) + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + h := connectionDebugHarness(t, tc.adapters) + p, id := openServiceDebugProject(t, h) + h.app.post(func(a *App) { + a.chooseTitleConfiguration(p, id) + a.titleDebug(p) + }) + want := tc.notice(h.app.language()) + if want == "" || strings.Contains(want, "desktop.build.") { + t.Fatalf("the refusal has no message: %q", want) + } + awaitStateWithin(t, h, time.Minute, "the refusal", func() bool { return lastNotice(h) == want }) + if p.build.operation != nil || p.debug.activeSession() != nil { + t.Fatalf("a refused debug started something: operation %v, session %v", p.build.operation, p.debug.activeSession()) + } + if _, err := os.Stat(filepath.Join(p.root, "prepare-run.json")); !os.IsNotExist(err) { + t.Fatalf("the provider prepared a run that nothing could debug: %v", err) + } + }) + } +} + +// The project reads the debug adapters again when the plugins change, so Debug offers an +// adapter the user just enabled and no longer offers one just disabled. The list used to be +// read once per project, so a plugin enabled after the first Debug stayed unavailable until the +// project was opened again. +func TestDebugAdaptersAreReadAgainWhenPluginsChange(t *testing.T) { + const id = "dev.lithe.test.registry-attach" + h := connectionDebugHarness(t, map[string]string{id: registryAttachManifest(id)}) + h.open(t.TempDir()) + p := h.app.project + h.app.post(func(a *App) { a.loadDebugAdapters(p) }) + awaitStateWithin(t, h, time.Minute, "the installed adapters", func() bool { return p.debug.loaded && !p.debug.loading }) + if len(p.debug.adapters) != 1 || p.debug.adapters[0].PluginID != id { + t.Fatalf("adapters = %+v, want the registry adapter", p.debug.adapters) + } + + h.app.post(func(a *App) { a.setPluginEnabled(id, false) }) + awaitStateWithin(t, h, time.Minute, "the adapters without the disabled plugin", func() bool { + return p.debug.loaded && !p.debug.loading && len(p.debug.adapters) == 0 + }) + + h.app.post(func(a *App) { a.setPluginEnabled(id, true) }) + awaitStateWithin(t, h, time.Minute, "the adapters with the enabled plugin", func() bool { + return p.debug.loaded && !p.debug.loading && len(p.debug.adapters) == 1 + }) + if p.debug.selectedAdapter != 0 { + t.Fatalf("selected adapter %d of %d", p.debug.selectedAdapter, len(p.debug.adapters)) + } +} + +// A run's process outlives the bound on its preparation: a service runs until it exits, the +// user stops it or the project closes. The host used to start the process under the request's +// 30-minute deadline, so every service that ran that long was killed. The test shortens the +// bound to 5 seconds and checks that the service still runs after 6. +func TestServiceRunOutlivesItsPreparationBound(t *testing.T) { + previous := runPreparationTimeout + runPreparationTimeout = 5 * time.Second + t.Cleanup(func() { runPreparationTimeout = previous }) + alive := filepath.Join(t.TempDir(), "alive") + t.Setenv(fixtureServiceAliveVariable, alive) + h := connectionDebugHarness(t, nil) + p, id := openServiceDebugProject(t, h) + + started := make(chan *buildOperation, 1) + h.app.post(func(a *App) { + op, err := a.startRunConfiguration(p, id) + if err != nil { + t.Errorf("start the service: %v", err) + } + started <- op + }) + op := awaitValueWithin(t, h, 30*time.Second, started, "the service run") + if op == nil { + t.FailNow() + } + awaitStateWithin(t, h, time.Minute, "the service to outlive its preparation bound or end", func() bool { + _, err := os.Stat(alive) + return err == nil || !op.session.running + }) + if _, err := os.Stat(alive); err != nil { + t.Fatalf("the service ended before it ran for %s: status %q, console:\n%s", fixtureServiceAliveAfter, p.build.status, op.session.output.all()) + } + if p.build.operation != op { + t.Fatal("the service is not running after it outlived its preparation bound") + } + h.app.post(func(a *App) { a.stopBuildOperation(p) }) + awaitStateWithin(t, h, time.Minute, "the stopped service", func() bool { return p.build.operation == nil }) +} diff --git a/desktop/internal/workbench/build_connection_debug_visual_test.go b/desktop/internal/workbench/build_connection_debug_visual_test.go new file mode 100644 index 0000000000..d0a6caa30a --- /dev/null +++ b/desktop/internal/workbench/build_connection_debug_visual_test.go @@ -0,0 +1,86 @@ +//go:build vivahead + +package workbench + +import ( + "os" + "path/filepath" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +// TestVisualServiceDebugWithoutAnAdapter captures the notice Debug shows on a service run whose +// declared debug type no enabled adapter answers to, as a toast and in the notification history +// (#2107). +func TestVisualServiceDebugWithoutAnAdapter(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 _, scene := range []struct{ theme, language string }{{"light", "zh-CN"}, {"dark", "en-US"}} { + name := scene.theme + "-" + scene.language + t.Run(name, func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, map[string]string{"theme": scene.theme}); err != nil { + t.Fatal(err) + } + var session *headless.Session + // An empty plugin root: no plugin is installed, so no adapter answers the run's type. + options := Options{ + Kernel: &testKernel{Client: core.NewClient()}, PluginKernel: &testKernel{Client: core.NewClient()}, + PluginRoot: t.TempDir(), Store: prefs, Languages: []string{scene.language}, + } + h := newHarnessWithDriver(t, options, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1280, 800 + var err error + session, err = headless.Open(config, nil, headless.Options{Scale: 1}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + h.open(runConfigRoot(t)) + p := h.app.project + h.app.post(func(a *App) { + instance := runConfigInstance("app") + instance.System.Runs = []pluginservice.BuildRunDeclaration{{ + ID: "service", Name: "Serve", Execution: "service", Tags: []string{"app"}, DebugConfigurationType: "fixture-attach", + }} + p.build.loaded = true + p.build.instances = []buildInstance{instance} + a.refreshRunConfigurations(p) + }) + awaitStateWithin(t, h, 10*time.Second, "the run configurations", func() bool { return p.runConfigs.generation > 0 && !p.runConfigs.loading }) + language := h.app.language() + want := i18n.SharedFormat(language, "desktop.build.noConnectionDebugAdapter", map[string]string{"type": "fixture-attach"}) + h.app.post(func(a *App) { a.titleDebug(p) }) + awaitStateWithin(t, h, 10*time.Second, "the refusal", func() bool { return lastNotice(h) == want }) + h.settle() + if err := session.Screenshot(filepath.Join(out, "service-debug-no-adapter-"+name+".png")); err != nil { + t.Fatal(err) + } + // The toast shows one line; the notification history holds the whole notice. + h.click(center(h.button(itemNotifications))) + h.settle() + if err := session.Screenshot(filepath.Join(out, "service-debug-no-adapter-history-"+name+".png")); err != nil { + t.Fatal(err) + } + if !h.shows(want) { + t.Fatal("the notification history did not paint the whole notice") + } + if p.build.operation != nil || p.debug.activeSession() != nil { + t.Fatal("a refused debug started something") + } + }) + } +} diff --git a/desktop/internal/workbench/build_menus.go b/desktop/internal/workbench/build_menus.go index 8314171dbb..9d3bb260d0 100644 --- a/desktop/internal/workbench/build_menus.go +++ b/desktop/internal/workbench/build_menus.go @@ -57,9 +57,10 @@ func (a *App) buildRowMenu(c ui.C, row ui.Box, p *project, instance *buildInstan a.showBuildConsole(p) }) } - // The same target under the debugger, when the run names an adapter of its own - // plugin: the provider prepares the native debug program and that adapter starts it. - if run.DebugAdapter != "" && menu.Item(i18n.Shared(lang, "desktop.build.debugTarget")).Disabled(b.operation != nil || instance.modelLoading || p.debug.preparing).Clicked() { + // The same target under the debugger, when the run declares how: an adapter of its + // own plugin starts the program the provider prepares, or the registered adapter of + // its public type attaches to the service the provider starts. + if run.Debuggable() && menu.Item(i18n.Shared(lang, "desktop.build.debugTarget")).Disabled(b.operation != nil || instance.modelLoading || p.debug.preparing).Clicked() { c.After(func() { a.performed("build.target.debug", surfaceContextMenu) choose() diff --git a/desktop/internal/workbench/build_tree.go b/desktop/internal/workbench/build_tree.go index 643e9d6b6c..f33ff14a1b 100644 --- a/desktop/internal/workbench/build_tree.go +++ b/desktop/internal/workbench/build_tree.go @@ -516,7 +516,7 @@ func buildPrimaryAction(instance *buildInstance, target *core.BuildTarget) (buil } for _, run := range instance.System.Runs { if buildRunApplies(run, *target) { - return buildTargetAction{runID: run.ID, name: run.ActionName(target.Name), debug: run.DebugAdapter != ""}, true + return buildTargetAction{runID: run.ID, name: run.ActionName(target.Name), debug: run.Debuggable()}, true } } if entries := buildTargetRunEntries(instance, target.ID); len(entries) != 0 { diff --git a/desktop/internal/workbench/debug.go b/desktop/internal/workbench/debug.go index 3484ba83fb..c2446338e7 100644 --- a/desktop/internal/workbench/debug.go +++ b/desktop/internal/workbench/debug.go @@ -54,6 +54,9 @@ type debugState struct { loading bool adapters []debugAdapter selectedAdapter int + // adaptersStale is set when the plugins change while the adapters are read: that answer + // may predate the change, so they are read again before anyone uses them. + adaptersStale bool // afterLoad are the starts waiting for the installed adapters, run once they are read. afterLoad []func() // preparing is set while a build provider prepares a program for debugging. @@ -463,14 +466,45 @@ func (a *App) finishDebugAdapters(p *project, adapters []debugAdapter, err error return } p.debug.loading = false + if p.debug.adaptersStale { + // The plugins changed during the read: read again, and keep the waiting starts for the + // answer that follows the change. + p.debug.adaptersStale = false + a.loadDebugAdapters(p) + return + } p.debug.loaded = true - p.debug.adapters = adapters + // The selection stays on the same adapter when it is still installed. + selected := 0 + if previous := p.debug.selectedAdapter; previous < len(p.debug.adapters) { + if index := slices.IndexFunc(adapters, func(adapter debugAdapter) bool { return sameDebugAdapter(adapter, p.debug.adapters[previous]) }); index >= 0 { + selected = index + } + } + p.debug.adapters, p.debug.selectedAdapter = adapters, selected if err != nil && len(adapters) == 0 { p.debug.failure = err.Error() } a.flushDebugAdapterWaiters(p) } +// invalidateDebugAdapters reads the installed adapters again after the plugins changed: +// installed, updated, enabled, disabled or removed. A list read before keeps adapters of +// plugins that are disabled or gone and misses the ones just installed, so Debug would refuse +// an adapter the user just enabled. A list never read is read when first needed. +func (a *App) invalidateDebugAdapters(p *project) { + if p == nil { + return + } + switch { + case p.debug.loading: + p.debug.adaptersStale = true + case p.debug.loaded: + p.debug.loaded = false + a.loadDebugAdapters(p) + } +} + // whenDebugAdaptersLoaded runs start on the window thread once the installed adapters are // read: now when they are, or after loadDebugAdapters answers. A project that closes before // the answer drops start with it. diff --git a/desktop/internal/workbench/debug_start.go b/desktop/internal/workbench/debug_start.go index fb3f72debd..b8fed6d4f2 100644 --- a/desktop/internal/workbench/debug_start.go +++ b/desktop/internal/workbench/debug_start.go @@ -870,6 +870,11 @@ func (a *App) discoverHostedPort(ctx context.Context, p *project, adapter debugA if err != nil { return 0, err } + // A server may offer its commands only after it is ready, by registering them (JDT LS + // does): Core refuses the command until then. + if err := a.waitPluginServerFeature(ctx, server, featureExecuteCommand, pluginServerStartTimeout); err != nil { + return 0, err + } // Core's discovery timer bounds the whole wait; the command itself only // needs a ceiling so a stuck server cannot outlive the stream. answer, err := a.plugins.ExecuteLanguageCommand(ctx, server.session, endpoint.Command, nil, pluginServerStartTimeout) @@ -927,6 +932,41 @@ func (a *App) waitReadyPluginServer(ctx context.Context, p *project, pluginID, l } } +// errPluginServerFeatureMissing is a ready language server that did not offer a feature the +// host needs within the wait. +var errPluginServerFeatureMissing = errors.New("the language server does not offer the feature") + +// waitPluginServerFeature waits until the ready server offers feature, as Core's +// featuresChanged event reports it, or at most timeout. The features belong to the window +// thread, so each look is posted there. +func (a *App) waitPluginServerFeature(ctx context.Context, server *pluginServer, feature string, timeout time.Duration) error { + deadline := time.NewTimer(timeout) + defer deadline.Stop() + ticker := time.NewTicker(debugHostedPollInterval) + defer ticker.Stop() + for { + offered := make(chan bool, 1) + a.post(func(a *App) { offered <- server.features[feature] }) + select { + case ok := <-offered: + if ok { + return nil + } + case <-ctx.Done(): + return ctx.Err() + case <-deadline.C: + return fmt.Errorf("%w: %s", errPluginServerFeatureMissing, feature) + } + select { + case <-ctx.Done(): + return ctx.Err() + case <-deadline.C: + return fmt.Errorf("%w: %s", errPluginServerFeatureMissing, feature) + case <-ticker.C: + } + } +} + // parseDebugPort reads the loopback port a language server answered: an integer // or a numeric string from 1 to 65535, as the contract defines. func parseDebugPort(raw json.RawMessage) (int, error) { diff --git a/desktop/internal/workbench/debug_tcp_test.go b/desktop/internal/workbench/debug_tcp_test.go index c163c29283..7df12734da 100644 --- a/desktop/internal/workbench/debug_tcp_test.go +++ b/desktop/internal/workbench/debug_tcp_test.go @@ -502,3 +502,38 @@ func TestSteppingAdaptersListsDeclaredDefaults(t *testing.T) { t.Fatalf("adapters = %+v", adapters) } } + +// A language server can register workspace/executeCommand after it is ready, as JDT LS does, +// and Core refuses the command until then. The debug port is asked for only once the server +// offers the feature, and a server that never offers it ends the wait with a reason. +func TestHostedDebugWaitsForTheServerToOfferCommands(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + server := &pluginServer{features: map[string]bool{featureDocumentSymbols: true}} + done := make(chan error, 1) + go func() { + done <- h.app.waitPluginServerFeature(context.Background(), server, featureExecuteCommand, time.Minute) + }() + for range 4 { + h.settle() + } + select { + case err := <-done: + t.Fatalf("the wait ended before the server offered commands: %v", err) + default: + } + // Core's featuresChanged event after the server registered its commands. + h.app.post(func(*App) { + server.features = map[string]bool{featureDocumentSymbols: true, featureExecuteCommand: true} + }) + if err := awaitValueWithin(t, h, 30*time.Second, done, "the wait after the registration"); err != nil { + t.Fatalf("the wait failed after the server offered commands: %v", err) + } + + never := &pluginServer{} + go func() { + done <- h.app.waitPluginServerFeature(context.Background(), never, featureExecuteCommand, 200*time.Millisecond) + }() + if err := awaitValueWithin(t, h, 30*time.Second, done, "the bounded wait"); !errors.Is(err, errPluginServerFeatureMissing) { + t.Fatalf("the wait on a server without commands = %v, want errPluginServerFeatureMissing", err) + } +} diff --git a/desktop/internal/workbench/editor_requests.go b/desktop/internal/workbench/editor_requests.go index d414c97430..876b1261eb 100644 --- a/desktop/internal/workbench/editor_requests.go +++ b/desktop/internal/workbench/editor_requests.go @@ -27,6 +27,7 @@ const ( // The features a server is offered with, as Core's featuresChanged event names them. featureDocumentSymbols = "documentSymbols" featureSemanticTokens = "semanticTokens" + featureExecuteCommand = "executeCommand" ) // editorServer is the ready language server of d that offers feature, and false when there diff --git a/desktop/internal/workbench/plugins.go b/desktop/internal/workbench/plugins.go index f7aa45938e..689d6968e1 100644 --- a/desktop/internal/workbench/plugins.go +++ b/desktop/internal/workbench/plugins.go @@ -62,8 +62,10 @@ func (a *App) refreshPluginState() { previous := a.pluginState.Load() changed := previous == nil || !maps.Equal(*previous, states) if changed { - // An open New Project window lists the generators again. + // An open New Project window lists the generators again, and the open project + // reads the debug adapters the changed plugins declare. a.newProject.revision++ + a.invalidateDebugAdapters(a.project) } a.pluginState.Store(&states) if changed && a.settingsWindow != nil { diff --git a/desktop/internal/workbench/runconfig.go b/desktop/internal/workbench/runconfig.go index 68fc6c8f7f..a317a36f49 100644 --- a/desktop/internal/workbench/runconfig.go +++ b/desktop/internal/workbench/runconfig.go @@ -169,6 +169,12 @@ func (a *App) runConfiguration(p *project, id string) { // refused start returns a *buildRefusal and reserves nothing; a reserved run that cannot launch // ends as failed with the reason, which the returned operation's IDE record keeps. func (a *App) startRunConfiguration(p *project, id string) (*buildOperation, error) { + return a.startRunConfigurationWith(p, id, nil) +} + +// startRunConfigurationWith is startRunConfiguration; debug, when set, prepares the service +// suspended for the adapter the host selected (debugRunConfiguration), and Rerun debugs again. +func (a *App) startRunConfigurationWith(p *project, id string, debug *connectionDebug) (*buildOperation, error) { configuration := p.runConfigs.configuration(id) if configuration == nil { return nil, refuseBuild(refusalNotFound, "unknown run configuration") @@ -186,9 +192,18 @@ func (a *App) startRunConfiguration(p *project, id string) (*buildOperation, err a.notifyError(a.text.Build.TargetMissing) return nil, refuseBuild(refusalNotReady, a.text.Build.TargetMissing) } + configurationType := "" + if debug != nil { + configurationType = debug.launch.ConfigurationType + } op := a.beginBuildOperation(p, "run", configuration.Name, id, func(a *App, p *project) { + if debug != nil { + a.debugRunConfiguration(p, id, configurationType) + return + } a.runConfiguration(p, id) }) + op.debug = debug // The run starts a process on the files on disk, so unsaved documents are saved first, // as a rerun does; a failed save keeps the run from starting. The save reports its own // failure, so the window's status only drops the preparation. @@ -220,9 +235,13 @@ func (a *App) startRunConfiguration(p *project, id string) (*buildOperation, err return } var options *core.RunLaunchOptions + launch := inputs.LaunchOptions + if debug != nil { + launch.Debug = &debug.launch + } // An application run without choices keeps the request older providers serve. - if inputs.LaunchOptions.Customized() { - options = &inputs.LaunchOptions + if launch.Customized() { + options = &launch } a.runBuildTargetWith(p, op, &p.build.instances[index], inputs.Reference.ProjectID, inputs.Reference.TargetID, inputs.Reference.Run, options) } diff --git a/desktop/internal/workbench/tests_provider_test.go b/desktop/internal/workbench/tests_provider_test.go index ca2a4f9858..b1bb8c0cf7 100644 --- a/desktop/internal/workbench/tests_provider_test.go +++ b/desktop/internal/workbench/tests_provider_test.go @@ -219,6 +219,37 @@ func TestProviderTestRunner(t *testing.T) { }, }) case "lithe/build/prepareRun": + // service.marker selects the service fixture (build_connection_debug_test.go): the + // provider records what the host asked for and answers with a process that listens + // on the debug port the host chose, as a runtime suspended for a debugger does. + if _, err := os.Stat("service.marker"); err == nil { + if err := os.WriteFile("prepare-run.json", request.Params, 0o600); err != nil { + os.Exit(9) + } + var params struct { + LaunchOptions struct { + Debug *struct { + Target struct { + Port int `json:"port"` + } `json:"target"` + } `json:"debug"` + } `json:"launchOptions"` + } + if err := json.Unmarshal(request.Params, ¶ms); err != nil { + os.Exit(10) + } + port := 0 + if params.LaunchOptions.Debug != nil { + port = params.LaunchOptions.Debug.Target.Port + } + reply(request.ID, map[string]any{ + "executable": map[string]any{"kind": "command", "value": "fixture-service"}, + "arguments": []string{"-test.run=^TestFixtureServiceRunner$"}, + "workingDirectory": "lib", + "environment": map[string]string{fixtureServicePortVariable: strconv.Itoa(port)}, + }) + continue + } // A provider builds before it answers: it streams the build's output, here the // compile error that makes the preparation fail. notify("lithe/build/progress", map[string]any{ diff --git a/desktop/internal/workbench/title_run.go b/desktop/internal/workbench/title_run.go index 9c76af2778..a218f0f187 100644 --- a/desktop/internal/workbench/title_run.go +++ b/desktop/internal/workbench/title_run.go @@ -243,6 +243,12 @@ func (a *App) decideTitleAction(p *project, action titleAction, trigger string) a.notifyInfo(i18n.Shared(a.language(), "desktop.title.runBusy")) } case "debug": + // A run that names a public debug type debugs as a service the registered adapter of + // that type attaches to; one that names its own plugin's adapter debugs a prepared program. + if run, ok := buildRunDeclaration(p.build.instances[index].System, reference.Run); ok && run.DebugAdapter == "" && run.DebugConfigurationType != "" { + a.debugRunConfiguration(p, configuration.ID, run.DebugConfigurationType) + return + } a.debugProviderTarget(p, index, reference.ProjectID, reference.TargetID, reference.Run) case "notDebuggable": a.notifyInfo(i18n.SharedFormat(a.language(), "desktop.title.notDebuggable", map[string]string{"name": configuration.Name})) @@ -262,7 +268,7 @@ func (p *project) titleConfigurationFacts(index int, reference core.RunProviderR return &core.TitleConfiguration{Kind: "modelNotLoaded", Failed: &failed} } run, ok := buildRunDeclaration(instance.System, reference.Run) - debuggable := ok && run.DebugAdapter != "" + debuggable := ok && run.Debuggable() return &core.TitleConfiguration{Kind: "modelLoaded", Debuggable: &debuggable} } diff --git a/docs/assets/service-debug/service-debug-no-adapter-dark-en-US.png b/docs/assets/service-debug/service-debug-no-adapter-dark-en-US.png new file mode 100644 index 0000000000..ac34937d03 Binary files /dev/null and b/docs/assets/service-debug/service-debug-no-adapter-dark-en-US.png differ diff --git a/docs/assets/service-debug/service-debug-no-adapter-history-dark-en-US.png b/docs/assets/service-debug/service-debug-no-adapter-history-dark-en-US.png new file mode 100644 index 0000000000..d27922539e Binary files /dev/null and b/docs/assets/service-debug/service-debug-no-adapter-history-dark-en-US.png differ diff --git a/docs/assets/service-debug/service-debug-no-adapter-history-light-zh-CN.png b/docs/assets/service-debug/service-debug-no-adapter-history-light-zh-CN.png new file mode 100644 index 0000000000..c4488ed179 Binary files /dev/null and b/docs/assets/service-debug/service-debug-no-adapter-history-light-zh-CN.png differ diff --git a/docs/assets/service-debug/service-debug-no-adapter-light-zh-CN.png b/docs/assets/service-debug/service-debug-no-adapter-light-zh-CN.png new file mode 100644 index 0000000000..00230eb9ea Binary files /dev/null and b/docs/assets/service-debug/service-debug-no-adapter-light-zh-CN.png differ diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index eed64395ef..bf5cc6d25a 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -11246,6 +11246,11 @@ "desktop.build.treeTruncated": "Too many build items to list them all; only the first ones are shown.", "desktop.build.treeFailed": "The build tree could not be shown: {error}", "desktop.build.noDebugAdapter": "The build provider's own plugin declares no debug adapter that can start a prepared program.", + "desktop.build.noConnectionDebugAdapter": "No enabled plugin can debug this run: it needs a debug adapter of type “{type}” that attaches to a running program. Install or enable one in Settings > Plugins.", + "desktop.build.ambiguousConnectionDebugAdapter": "Several enabled debug adapters of type “{type}” can attach to this run ({adapters}). Disable all but one in Settings > Plugins.", + "desktop.build.connectionDebugAdapterGone": "The debug adapter “{name}” was disabled or updated before the run was ready, so the run was stopped. Debug it again.", + "desktop.build.debugPortTimeout": "The run did not wait for a debugger within {seconds} seconds, so it was stopped. See the Run window for its output.", + "desktop.build.debugSessionRunning": "A debug session is already running. Stop it before debugging another run.", "desktop.debug.consoleEmpty": "The debug session's output appears here.", "desktop.debug.evaluatePlaceholder": "Evaluate expression ({evaluate}) or add a watch ({watch})", "desktop.debug.unmuteBreakpoints": "Unmute breakpoints", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 614e80bd48..82517619ca 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -11246,6 +11246,11 @@ "desktop.build.treeTruncated": "构建项太多,只列出了前面一部分。", "desktop.build.treeFailed": "无法显示构建树:{error}", "desktop.build.noDebugAdapter": "该构建插件所属的插件没有声明可以启动已准备程序的调试适配器。", + "desktop.build.noConnectionDebugAdapter": "没有已启用的插件能调试这个运行:它需要一个类型为“{type}”、能连接到运行中程序的调试适配器。请在 设置 > 插件 中安装或启用。", + "desktop.build.ambiguousConnectionDebugAdapter": "有多个已启用的“{type}”类型调试适配器都能连接这个运行({adapters})。请在 设置 > 插件 中只保留一个。", + "desktop.build.connectionDebugAdapterGone": "调试适配器“{name}”在运行就绪前被停用或更新,运行已停止。请重新调试。", + "desktop.build.debugPortTimeout": "运行在 {seconds} 秒内没有等待调试器连接,已停止。输出见运行窗口。", + "desktop.build.debugSessionRunning": "已有调试会话在运行。请先停止它,再调试其他运行。", "desktop.debug.consoleEmpty": "调试会话的输出会显示在这里。", "desktop.debug.evaluatePlaceholder": "对表达式求值({evaluate})或添加监视({watch})", "desktop.debug.unmuteBreakpoints": "恢复断点", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 91f2776fd5..3b3f3fbbce 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -6821,6 +6821,54 @@ "desktop" ] }, + { + "id": "desktop.build.noConnectionDebugAdapter", + "description": "Debug pressed on a service run whose declared public debug type no enabled plugin's attach adapter answers to", + "platforms": [ + "desktop" + ], + "parameters": { + "type": "string" + } + }, + { + "id": "desktop.build.ambiguousConnectionDebugAdapter", + "description": "Debug pressed on a service run whose declared public debug type several enabled attach adapters answer to; lists their display names", + "platforms": [ + "desktop" + ], + "parameters": { + "type": "string", + "adapters": "string" + } + }, + { + "id": "desktop.build.connectionDebugAdapterGone", + "description": "The attach adapter selected for a service run was disabled or replaced before the service was ready; the run is stopped", + "platforms": [ + "desktop" + ], + "parameters": { + "name": "string" + } + }, + { + "id": "desktop.build.debugPortTimeout", + "description": "A service run started for debugging never opened its debug port in time; the run is stopped", + "platforms": [ + "desktop" + ], + "parameters": { + "seconds": "string" + } + }, + { + "id": "desktop.build.debugSessionRunning", + "description": "Debug pressed on a service run while the project already has a debug session; a project debugs one session at a time", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.build.noOptions", "description": "Build options dialog message when the build system declares no options", diff --git a/shared/platform-feature-matrix/features/viva-title-run-debug.json b/shared/platform-feature-matrix/features/viva-title-run-debug.json index 2e2e895f05..a384c10d5e 100644 --- a/shared/platform-feature-matrix/features/viva-title-run-debug.json +++ b/shared/platform-feature-matrix/features/viva-title-run-debug.json @@ -2,7 +2,7 @@ "id": "viva-title-run-debug", "area": "运行与调试", "group": "运行配置", - "capability": "标题栏右上角的运行配置下拉、运行和调试按钮:下拉列出构建提供者检测到的运行配置并可选择“当前文件”,运行按所选配置交给提供者启动并打开运行窗口,调试让提供者准备该运行声明的调试适配器后在调试窗口启动会话;配置尚未读出时按下会等读出后再执行;按下后做什么(等待、先加载模型、运行、调试或提示)由 Core 判定;没有运行配置时,下拉说明被隐藏的已保存配置数,“编辑运行配置…”提示原因而不是无反应;未声明名称的提供者运行以目标名命名;提供者准备运行时输出的构建日志(如编译错误)显示在该运行的控制台;声明了提供者进程、但用命令读取模型和依赖的构建系统按各自声明的来源读取", + "capability": "标题栏右上角的运行配置下拉、运行和调试按钮:下拉列出构建提供者检测到的运行配置并可选择“当前文件”,运行按所选配置交给提供者启动并打开运行窗口,调试让提供者准备该运行声明的调试适配器后在调试窗口启动会话;声明了公共调试类型(`debug.configurationType`)的服务运行,宿主选出唯一一个已启用、能连接该类型的调试适配器(可来自其他插件),分配本机端口让提供者以等待调试器的方式启动服务,端口打开后连接调试器,调试会话和服务一起结束;没有或有多个匹配适配器时在准备前提示原因;插件安装、启用、停用或卸载后,项目重新读取调试适配器;运行在语言服务器里的调试适配器,要等语言服务器声明可执行命令后才请求调试端口(有的语言服务器在就绪后才动态注册命令);运行的进程(包括常驻服务)一直运行到自己退出、用户停止或项目关闭,只有运行前的准备受时限约束;配置尚未读出时按下会等读出后再执行;按下后做什么(等待、先加载模型、运行、调试或提示)由 Core 判定;没有运行配置时,下拉说明被隐藏的已保存配置数,“编辑运行配置…”提示原因而不是无反应;未声明名称的提供者运行以目标名命名;提供者准备运行时输出的构建日志(如编译错误)显示在该运行的控制台;声明了提供者进程、但用命令读取模型和依赖的构建系统按各自声明的来源读取", "macos": { "implementationStatus": "implemented", "verificationStatus": "pending", @@ -17,7 +17,12 @@ "desktop/internal/core/run_config.go", "desktop/internal/workbench/build_dependencies.go", "desktop/internal/workbench/tests_provider_test.go", - "desktop/internal/workbench/build_command_record_test.go" + "desktop/internal/workbench/build_command_record_test.go", + "desktop/internal/workbench/build_connection_debug.go", + "desktop/internal/workbench/build_connection_debug_test.go", + "desktop/internal/workbench/plugins.go", + "desktop/internal/workbench/debug_start.go", + "desktop/internal/workbench/debug_tcp_test.go" ] }, "windows": { @@ -34,10 +39,15 @@ "desktop/internal/core/run_config.go", "desktop/internal/workbench/build_dependencies.go", "desktop/internal/workbench/tests_provider_test.go", - "desktop/internal/workbench/build_command_record_test.go" + "desktop/internal/workbench/build_command_record_test.go", + "desktop/internal/workbench/build_connection_debug.go", + "desktop/internal/workbench/build_connection_debug_test.go", + "desktop/internal/workbench/plugins.go", + "desktop/internal/workbench/debug_start.go", + "desktop/internal/workbench/debug_tcp_test.go" ] }, "owner": "Run", - "verification": "打开带构建提供者的项目(测试内联的合成 Build Provider 即可):标题栏下拉列出检测到的运行配置并记住所选项;运行按钮启动所选配置并打开运行窗口;调试按钮对声明了调试适配器的运行准备并启动调试会话、打开调试窗口,未声明时提示该配置不能调试;准备失败时结束“准备中”并显示原因;选择“当前文件”时提示需要运行配置;项目没有运行配置时点“编辑运行配置…”提示原因,有旧版或其他提供方的已保存配置时说明隐藏了几条。提供者运行准备失败时,运行控制台显示提供者输出的构建日志;未声明名称的运行,配置名就是目标名。单元测试覆盖等待配置读出后运行、没有配置时编辑入口的提示和隐藏条数、当前文件提示、无适配器提示、不经构建提供者启动的配置提示、提供者准备请求、按名称选择适配器和拒绝插件未安装的适配器、准备运行时转发提供者输出、未命名运行按目标命名,以及声明提供者进程但用命令读取模型和写文件的依赖命令。", - "notes": "Viva 标题栏按钮此前只有外观。运行忙碌时仅提示,不排队;当前文件运行尚未实现,只提示需要配置;提供者调试暂不携带运行配置的启动选项;按配置类型连接的服务运行调试(`run[].debug.configurationType`)尚未实现,这类运行点调试时提示不能调试(#2107)。macOS、Windows 原生窗口验收 pending。" + "verification": "打开带构建提供者的项目(测试内联的合成 Build Provider 即可):标题栏下拉列出检测到的运行配置并记住所选项;运行按钮启动所选配置并打开运行窗口;调试按钮对声明了调试适配器的运行准备并启动调试会话、打开调试窗口,未声明时提示该配置不能调试;声明了公共调试类型的服务运行(合成提供者 + 另一个合成插件的 attach 适配器),调试时提供者收到 `launchOptions.debug`(选中的适配器、类型、本机端口),服务监听后适配器以 attach 连接该端口,在调试窗口停止后服务结束、端口释放;没有或有两个匹配适配器时提示原因且不请求提供者;停用、再启用适配器所在插件后,调试适配器列表随之更新;运行超过准备时限的服务不会被结束(测试把时限缩短到 5 秒);语言服务器就绪后才声明命令时,宿主等到声明再请求端口,从不声明时在时限内结束;准备失败时结束“准备中”并显示原因;选择“当前文件”时提示需要运行配置;项目没有运行配置时点“编辑运行配置…”提示原因,有旧版或其他提供方的已保存配置时说明隐藏了几条。提供者运行准备失败时,运行控制台显示提供者输出的构建日志;未声明名称的运行,配置名就是目标名。单元测试覆盖等待配置读出后运行、没有配置时编辑入口的提示和隐藏条数、当前文件提示、无适配器提示、不经构建提供者启动的配置提示、提供者准备请求、按名称选择适配器和拒绝插件未安装的适配器、准备运行时转发提供者输出、未命名运行按目标命名,声明提供者进程但用命令读取模型和写文件的依赖命令,以及按配置类型连接调试服务运行(选择、拒绝、停止联动)。", + "notes": "Viva 标题栏按钮此前只有外观。运行忙碌时仅提示,不排队;当前文件运行尚未实现,只提示需要配置;同包适配器的提供者调试暂不携带运行配置的启动选项;按配置类型连接的服务运行调试一个项目同时只有一个调试会话。macOS、Windows 原生窗口验收 pending。" }