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
@@ -1,17 +1,17 @@
# Agent 笔记:当前文件运行(按需运行入口)
# Agent 笔记:当前文件的运行与调试

状态:已实现

## 先说结论

标题栏选“当前文件”后点运行,可以直接运行当前文件里的入口,例如没有在 POM 里写明主类、但带 `main` 方法的 Java 类(#2104):
标题栏选“当前文件”后点运行或调试,可以使用构建提供者按需发现的入口,无须预先创建运行配置(#2104、#2074):

- 插件在构建系统里声明入口运行 `{"id": "main", "source": "provider", "entrypoints": true}`,需要 `requires.buildProviders: 1`。入口运行不对应构建目标,不出现在构建树和运行配置列表里,只在用户运行某个文件时才产生配置。
- 宿主把当前文件(工作区相对路径)交给根目录包含它的构建实例(内层优先)。Core 用 `build.runEntrypointsPlan` 规划 `lithe/build/runEntrypoints` 请求,插件按文件回答入口,Core 用 `build.decodeRunEntrypoints` 校验:运行必须是入口运行、名称和入口长度受限、项目在实例根目录内,答案不合法时整份拒绝。
- 宿主取第一个入口,按项目路径找到模型里的项目,用 `runConfig.createUserConfiguration` 保存本机配置:名称取入口名(类名),引用的 `targetID` 为空,入口存为 `extensions.build-run.entrypoint`,入口是配置身份的一部分。同一入口再次运行复用已保存的配置。
- 保存后重新读取配置、在标题栏选中并运行。准备运行时请求不带 `target`,入口通过 `launchOptions.entrypoint` 交给插件。之后用户可以像编辑其他构建提供者运行一样修改参数、环境变量和工作目录。
- 没有打开文件、没有可回答的构建实例或文件里没有入口时,提示“当前文件没有可运行的入口”。
- Maven 插件按源码文本回答:文件所在的最近一个含 `pom.xml` 的模块,包名加文件名作为类名,必须有 `static void main(String[])` 或 `String...`;测试源码不算,因为运行使用的运行时类路径不含测试类。不编译,回答很快。
- 提供者声明 `buildSystems: 2` 后,可以给应用入口加 `debug.configurationType`。调试只在声明该类型的入口中查找,保存或复用同一份配置,然后使用已注册的适配器连接暂停的进程。没有匹配入口或调试查找失败时,继续尝试编辑器提供的操作。

## 问题

Expand All @@ -25,23 +25,28 @@
- 入口作为配置身份的一部分,同一模块里不同类各存一条配置,同一个类不会重复保存。
- 一个文件有多个入口时先运行第一个;选择菜单以后需要时再加。

- 构建提供者按磁盘内容查找入口,因此先通过编辑器原有的流程保存修改并处理冲突。查找期间切换文件或修改内容时,丢弃这次查找结果。
- 调试查找失败时记录失败原因,当前文档仍可使用自己的 Debug 动作。没有可用的编辑器动作时显示查找错误。

## 考虑过的备选方案

- 模型读取时扫描源码把所有 main 类列成目标:读取变慢、工具类和测试辅助类会淹没下拉(#2074 已否决)。
- 行号旁运行图标:需要编辑器按语言识别 main 方法或额外的插件协议;标题栏“当前文件”已有入口,先复用它。
- 入口运行支持调试:Maven 的调试需要声明调试方式(服务运行用 `debug.configurationType`),入口运行的调试和准备方式另行设计,本轮只做运行。
- 为源码入口增加独立调试协议:现有注册适配器和回环连接已能表达启动方式,应用入口复用同一机制。

## 后果

- 插件可以按文件提供可运行的入口;新增语言或构建工具时只需在插件里回答 `lithe/build/runEntrypoints`。
- 使用入口运行的插件版本需要支持 `buildProviders` 1 的宿主,插件应和支持它的桌面版本一起发布。
- 以后加入口运行的调试,需要在契约里给入口运行声明调试方式,并在 `decideTitleAction` 的可调试判断里覆盖入口运行。
- 仅声明运行的入口仍可正常运行。调试依赖相应适配器可用,旧插件仍可通过编辑器动作启动调试。

## 验证

- Core:`cargo test -p lithe-core provider_run_entrypoints_are_found_by_file_and_start_without_a_target entrypoint_runs_are_saved_per_entrypoint_without_a_target`。
- 宿主:`./scripts/desktop/desktop-go.sh test ./internal/workbench/ -run TestRunOnCurrentFile -count=1`(合成构建提供者回答入口、准备运行);截图 `TestVisualRunOnCurrentFile`。
- Maven 插件:`node scripts/test.mjs` 中的入口查找和入口运行检查(真实 Maven)。
- 宿主:`TestCurrentFileDebugSavesAndAttachesToTheDiscoveredEntrypoint` 验证首次调试保存入口,并让已注册的适配器连接该入口的回环端口。

- 宿主:`TestCurrentFileDebugSavesEditsBeforeDiscoveringAnEntrypoint` 验证从缓冲区删除入口时,提供者读取的是保存后的文件。`TestCurrentFileDebugFallsBackWhenProviderDiscoveryFails` 验证提供者失败后仍能启动当前文档的 Debug 动作。

## 适用范围

Expand All @@ -52,4 +57,4 @@
- `desktop/internal/pluginservice/builds.go`(`EntrypointRuns`)
- `desktop/internal/pluginhost/pluginhost.go`(`buildProviders` 声明 `[0, 1]`)
- Core:`rust/crates/build/src/run_entrypoints.rs`、`rust/crates/execution/src/configuration/editing.rs`
- Maven 插件:`provider/src/main/java/io/github/litheidea/maven/provider/RunEntrypoints.java`
- `desktop/internal/workbench/build_connection_debug.go`(使用注册适配器连接暂停的进程)
3 changes: 2 additions & 1 deletion desktop/internal/pluginhost/pluginhost.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,8 @@ func Declared() Capabilities {
// settings window's source forms render.
declared["sourceSettings"] = []int{0, 1}
// Version 1 adds command-sourced discovery in the Build test tree.
declared["buildSystems"] = []int{0, 1}
// Version 2 adds registry connection debugging for provider applications.
declared["buildSystems"] = []int{0, 1, 2}
// Version 1 adds entrypoint runs, which Run on Current File starts.
declared["buildProviders"] = []int{0, 1}
// Version 1 adds a definition's category and audience, by which the
Expand Down
4 changes: 2 additions & 2 deletions desktop/internal/pluginhost/pluginhost_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,9 @@ func TestDeclaredServesTheBaselineOfEveryWiredCapability(t *testing.T) {
if name == "sourceSettings" {
wanted = []int{0, 1}
}
// The Build test tree supports the discovery command version 1 adds.
// Version 1 adds test discovery, and version 2 adds registry attach for provider applications.
if name == "buildSystems" {
wanted = []int{0, 1}
wanted = []int{0, 1, 2}
}
// Run on Current File starts the entrypoint runs version 1 adds.
if name == "buildProviders" {
Expand Down
15 changes: 8 additions & 7 deletions desktop/internal/pluginservice/builds.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,24 +243,25 @@ func parseBuildSystems(manifest json.RawMessage) (map[string]BuildSystemDeclarat
})
}
for _, run := range raw.Run {
if run.ID != "" && run.Source == "provider" && run.Entrypoints {
system.EntrypointRuns = append(system.EntrypointRuns, BuildRunDeclaration{ID: run.ID, Name: run.Name, Execution: "application"})
continue
}
if run.ID == "" || run.Source != "provider" || run.FromTargets == nil {
if run.ID == "" || run.Source != "provider" {
continue
}
declaration := BuildRunDeclaration{
ID: run.ID,
Name: run.Name,
Execution: run.Execution,
Tags: append([]string(nil), run.FromTargets.Tags...),
}
if run.Debug != nil {
declaration.DebugAdapter = run.Debug.Adapter
declaration.DebugConfigurationType = run.Debug.ConfigurationType
}
system.Runs = append(system.Runs, declaration)
if run.Entrypoints {
declaration.Execution = "application"
system.EntrypointRuns = append(system.EntrypointRuns, declaration)
} else if run.FromTargets != nil {
declaration.Tags = append([]string(nil), run.FromTargets.Tags...)
system.Runs = append(system.Runs, declaration)
}
}
if raw.Test != nil {
system.Test = &BuildTestDeclaration{
Expand Down
8 changes: 5 additions & 3 deletions desktop/internal/workbench/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -1963,9 +1963,11 @@ func (a *App) redebugProviderTarget(p *project, reference core.RunProviderRefere

// buildRunDeclaration is the run declaration id of system.
func buildRunDeclaration(system pluginservice.BuildSystemDeclaration, id string) (pluginservice.BuildRunDeclaration, bool) {
for _, run := range system.Runs {
if run.ID == id {
return run, true
for _, runs := range [][]pluginservice.BuildRunDeclaration{system.Runs, system.EntrypointRuns} {
for _, run := range runs {
if run.ID == id {
return run, true
}
}
}
return pluginservice.BuildRunDeclaration{}, false
Expand Down
2 changes: 1 addition & 1 deletion desktop/internal/workbench/build_connection_debug.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ func (a *App) prepareConnectionDebug(p *project, configurationType string, start
}

// 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
// configuration's saved launch options apply as for Run, with the debuggee suspended for the
// selected adapter.
func (a *App) debugRunConfiguration(p *project, id, configurationType string) {
a.prepareConnectionDebug(p, configurationType, func(debug connectionDebug) {
Expand Down
141 changes: 138 additions & 3 deletions desktop/internal/workbench/build_connection_debug_test.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,23 @@
package workbench

import (
"context"
"encoding/json"
"errors"
"net"
"os"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"testing"
"time"

"github.com/1lck/Lithe-IDEA/desktop/internal/core"
"github.com/1lck/Lithe-IDEA/desktop/internal/editorview"
"github.com/1lck/Lithe-IDEA/desktop/internal/i18n"
"github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice"
"github.com/1lck/Lithe-IDEA/desktop/internal/pluginstate"
"github.com/1lck/Lithe-IDEA/desktop/internal/store"
)
Expand Down Expand Up @@ -85,6 +90,11 @@ func registryAttachManifest(id string) string {
// 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()
return connectionDebugHarnessWithProvider(t, providerServiceDebugManifest, adapters)
}

func connectionDebugHarnessWithProvider(t *testing.T, providerManifest string, adapters map[string]string) *harness {
t.Helper()
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, settingsFile), []byte(`{"theme":"dark"}`), 0o600); err != nil {
Expand All @@ -105,7 +115,7 @@ func connectionDebugHarness(t *testing.T, adapters map[string]string) *harness {
t.Fatal(err)
}
}
install("dev.lithe.test.provider-tests", providerServiceDebugManifest, "provider")
install("dev.lithe.test.provider-tests", providerManifest, "provider")
for id, manifest := range adapters {
if runtime.GOOS == "windows" {
manifest = strings.ReplaceAll(manifest, `"path": "adapter"`, `"path": "adapter.exe"`)
Expand Down Expand Up @@ -166,8 +176,9 @@ func openServiceDebugProject(t *testing.T, h *harness) (*project, string) {

// preparedDebug is the launchOptions.debug the fixture provider received.
type preparedDebug struct {
Execution string `json:"execution"`
Debug *struct {
Execution string `json:"execution"`
Entrypoint string `json:"entrypoint"`
Debug *struct {
AdapterID string `json:"adapterID"`
ConfigurationType string `json:"configurationType"`
Target struct {
Expand Down Expand Up @@ -250,6 +261,130 @@ func TestTitleDebugAttachesTheRegisteredAdapterToAServiceRun(t *testing.T) {
_ = listener.Close()
}

func TestCurrentFileDebugSavesAndAttachesToTheDiscoveredEntrypoint(t *testing.T) {
const adapterID = "dev.lithe.test.registry-attach"
h := connectionDebugHarnessWithProvider(t, debugEntrypointsManifest(), map[string]string{adapterID: registryAttachManifest(adapterID)})
gate := &captureDebugLaunch{Kernel: h.app.kernel, configurations: make(chan core.DebugLaunchConfiguration, 1)}
h.app.kernel = gate
root := entrypointWorkspace(t)
writeFixture(t, root, map[string]string{"debug.marker": "fixture\n"})
h.open(root)
p := h.app.project
openSource(t, h, p, filepath.Join(root, "src", "Main.java"))
h.app.post(func(a *App) {
a.chooseTitleConfiguration(p, "")
a.titleDebug(p)
})
configuration := awaitValueWithin(t, h, time.Minute, gate.configurations, "the attach to the discovered entrypoint")
prepared := readPreparedRun(t, root)
if prepared.Execution != "application" || prepared.Entrypoint != "example.Main" || prepared.Debug == nil {
t.Fatalf("the provider prepared %+v, want the application entrypoint with a debug target", prepared)
}
if configuration.Request != "attach" || !sameDebugPort(configuration.Arguments["port"], prepared.Debug.Target.Port) {
t.Fatalf("attach configuration = %+v, want the entrypoint's port %d", configuration, prepared.Debug.Target.Port)
}
saved := p.titleConfiguration()
if saved == nil || saved.Name != "Main" || len(p.runConfigs.list) != 1 {
t.Fatalf("selected configuration = %+v, configurations = %+v", saved, p.runConfigs.list)
}
h.app.post(func(a *App) { a.stopDebugByUser(p) })
awaitStateWithin(t, h, time.Minute, "the stopped entrypoint", func() bool { return !p.build.active() && p.debug.activeSession() == nil })
}

func debugEntrypointsManifest() string {
manifest := strings.Replace(providerEntrypointsManifest, `"buildSystems": 0`, `"buildSystems": 2`, 1)
return strings.Replace(manifest, `"entrypoints": true`, `"entrypoints": true, "debug": {"configurationType": "fixture-attach"}`, 1)
}

type entrypointDiscoveryKernel struct {
Kernel
discover func(context.Context, core.BuildPlanRequest) error
}

func (k entrypointDiscoveryKernel) PlanBuildRunEntrypoints(ctx context.Context, manifest json.RawMessage, system string, request core.BuildPlanRequest) (core.BuildPlan, error) {
if err := k.discover(ctx, request); err != nil {
return core.BuildPlan{}, err
}
return k.Kernel.PlanBuildRunEntrypoints(ctx, manifest, system, request)
}

func TestCurrentFileDebugFallsBackWhenProviderDiscoveryFails(t *testing.T) {
h := connectionDebugHarnessWithProvider(t, debugEntrypointsManifest(), nil)
failure := errors.New("fixture entrypoint discovery failed")
discovering := make(chan struct{}, 1)
finishDiscovery := make(chan struct{})
h.app.kernel = entrypointDiscoveryKernel{
Kernel: h.app.kernel,
discover: func(ctx context.Context, _ core.BuildPlanRequest) error {
discovering <- struct{}{}
select {
case <-finishDiscovery:
return failure
case <-ctx.Done():
return ctx.Err()
}
},
}
root := entrypointWorkspace(t)
h.open(root)
p := h.app.project
openSource(t, h, p, filepath.Join(root, "src", "Main.java"))
d := p.selectedDocument(p.docs.group)
h.app.post(func(a *App) {
a.chooseTitleConfiguration(p, "")
a.titleDebug(p)
})
awaitValueWithin(t, h, 15*time.Second, discovering, "the provider discovery request")
h.app.post(func(a *App) {
d.actions = []pluginservice.EditorAction{{
Title: "Debug editor entry", Icon: "debug",
Range: pluginservice.EditorActionRange{StartLine: 1, StartColumn: 1},
}}
close(finishDiscovery)
})
want := i18n.SharedFormat(h.app.language(), "desktop.editorActions.starting", map[string]string{"label": "Debug editor entry"})
awaitStateWithin(t, h, 15*time.Second, "the editor debug action", func() bool {
notices := noticeTexts(h.app)
if slices.Contains(notices, failure.Error()) {
t.Fatalf("provider failure blocked editor debug: %v", notices)
}
return slices.Contains(notices, want)
})
}

func TestCurrentFileDebugSavesEditsBeforeDiscoveringAnEntrypoint(t *testing.T) {
h := connectionDebugHarnessWithProvider(t, debugEntrypointsManifest(), nil)
const modified = "package example;\n\npublic final class Main {}\n"
sourceAtDiscovery := make(chan string, 1)
h.app.kernel = entrypointDiscoveryKernel{
Kernel: h.app.kernel,
discover: func(_ context.Context, request core.BuildPlanRequest) error {
data, err := os.ReadFile(filepath.Join(request.WorkspaceRoot, filepath.FromSlash(request.File)))
if err != nil {
return err
}
sourceAtDiscovery <- string(data)
return errors.New("fixture stops after reading the source")
},
}
root := entrypointWorkspace(t)
h.open(root)
p := h.app.project
openSource(t, h, p, filepath.Join(root, "src", "Main.java"))
d := p.selectedDocument(p.docs.group)
data, _ := d.view.Text()
if err := d.view.ApplyEdits([]editorview.TextEdit{{Range: editorview.Range{End: len(data)}, Text: modified}}); err != nil {
t.Fatal(err)
}
h.app.post(func(a *App) {
a.chooseTitleConfiguration(p, "")
a.titleDebug(p)
})
if got := awaitValueWithin(t, h, 15*time.Second, sourceAtDiscovery, "the source read by the provider"); got != modified {
t.Fatalf("provider read stale source: %q", got)
}
}

// sameDebugPort reports whether a DAP argument decoded from JSON is port.
func sameDebugPort(value any, port int) bool {
switch number := value.(type) {
Expand Down
11 changes: 10 additions & 1 deletion desktop/internal/workbench/editor_actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,8 +346,12 @@ func (a *App) editorActionMenuItems(c ui.C, p *project, d *document, menu *ui.Me

// runCurrentFileEditorAction presents the same plugin invocation the gutter
// offers. An absent cached action may mean its initial collection is still in flight.
func (a *App) runCurrentFileEditorAction(p *project, d *document, mode titleAction) {
func (a *App) runCurrentFileEditorAction(p *project, d *document, mode titleAction, discoveryErr error) {
fallback := func(a *App) {
if discoveryErr != nil {
a.notifyError(discoveryErr.Error())
return
}
if mode == titleActionDebug {
a.whenDebugAdaptersLoaded(p, func() {
if p.selectedDocument(p.docs.group) == d {
Expand Down Expand Up @@ -401,6 +405,11 @@ func (a *App) runCurrentFileEditorAction(p *project, d *document, mode titleActi
return
}
if err != nil {
if discoveryErr != nil {
a.backgroundFailed("editor_actions", err)
fallback(a)
return
}
a.operationFailed("title_run_current_file", err)
a.notifyError(i18n.Shared(a.language(), "desktop.editorActions.failed"))
return
Expand Down
20 changes: 13 additions & 7 deletions desktop/internal/workbench/runconfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,11 @@ type runConfigState struct {
// beforeLaunch is the start that waits for the user to allow the steps a project file
// names before it (runconfig_before_launch.go).
beforeLaunch *beforeLaunchConfirmation
// start is the configuration a save asked to run, started once the next refresh lists it
// so the run reads what was saved.
start string
// findingEntrypoint says Run on Current File is asking the build providers for the open
// start is the configuration a save asked to start once the next refresh lists it.
// startAction is Debug for a discovered debug entrypoint and defaults to Run.
start string
startAction titleAction
// findingEntrypoint says Current File is asking the build providers for the open
// file's entrypoint (title_run_entrypoints.go), so another press does not ask again.
findingEntrypoint bool
// browser is the list that shows the configurations by scope and build system.
Expand Down Expand Up @@ -167,7 +168,7 @@ func (a *App) finishRunConfigurations(p *project, generation uint64, resolved co
a.loadRunConfigTypes(p, false)
if err != nil {
s.failure = err.Error()
s.reveal, s.start = "", ""
s.reveal, s.start, s.startAction = "", "", titleActionNone
return
}
s.failure = ""
Expand Down Expand Up @@ -204,10 +205,15 @@ func (a *App) finishRunConfigurations(p *project, generation uint64, resolved co
}
s.reveal = ""
if start := s.start; start != "" {
s.start = ""
action := s.startAction
s.start, s.startAction = "", titleActionNone
if s.configuration(start) != nil {
s.selected = start
a.runConfiguration(p, start)
if action == titleActionDebug {
a.titleStart(p, action)
} else {
a.runConfiguration(p, start)
}
}
}
if s.configuration(s.selected) == nil {
Expand Down
Loading
Loading