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
Expand Up @@ -24,6 +24,17 @@ Run 的首次调试复用既有适配器加载入口,完成后检查原调用

真实插件测试在创建工作台后就登记无交互清理,不依赖成功路径的关闭动作。即使断言在断点暂停或文档未保存时中止,也直接关闭测试拥有的项目,等待后台任务、停止剩余运行,并验证 Core 调试会话已移除;不能把需要用户确认的关闭弹窗当作失败清理。

## 当前文件入口与附加界面

标题栏运行按构建提供者给出的入口保存配置。提供者未声明入口或返回空列表时,
窗口复用当前文件行号栏已经提供的 Run 动作。标题栏调试优先使用相应的 Debug
动作。窗口只派发当前文档版本的动作,等待查询时切换文件或继续编辑都会使旧结果失效。

宿主从操作系统读取被启动进程及其子进程的监听状态,让调试适配器建立第一条
连接。此前先拨号再断开的探测会让运行时记录一次握手失败,部分调试目标还会
用掉唯一的附加机会。观察监听状态只在启动等待期进行。附加建立后显示 Debug
窗口,用户可以切回 Run 查看进程输出。

## 项目 JDK 与语言服务器的编译目标

普通源码目录没有 Maven 的目标版本约束时,Viva 曾只把项目选择的 JDK 交给 Run,没有在后端解析语言服务器启动时传入契约已有的可选 `tools`。JDT 因而按随包 Java 21 编译,Run 却使用用户选择的 Java 8,生成的 major 65 class 会被 Java 8 拒绝。只检查 Maven 构建的 class 无法发现这个问题,必须也检查 JDT 的运行前构建。
Expand Down
63 changes: 53 additions & 10 deletions desktop/internal/pluginservice/runs.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost"
"github.com/1lck/Lithe-IDEA/desktop/internal/pluginmanager"
"github.com/1lck/Lithe-IDEA/desktop/internal/pluginpkg"
"github.com/1lck/Lithe-IDEA/desktop/internal/sysinfo"
)

const (
Expand Down Expand Up @@ -585,7 +586,10 @@ func (r *Runs) attachDebugger(ctx context.Context, run *hostRun) {
r.stopRun(run, false)
}
}
if err := WaitForDebugPort(ctx, port, run.done, RunDebugConnectTimeout); err != nil {
err := waitForDebugPort(ctx, port, run.done, RunDebugConnectTimeout, func(context.Context) (bool, error) {
return debuggeeListening(run.pid, uint16(port))
})
if err != nil {
fail(err)
return
}
Expand Down Expand Up @@ -616,25 +620,64 @@ var (
// 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)
defer ticker.Stop()
address := net.JoinHostPort("127.0.0.1", strconv.Itoa(port))
for {
return waitForDebugPort(ctx, port, ended, timeout, func(ctx context.Context) (bool, error) {
dialer := net.Dialer{Timeout: time.Second}
connection, err := dialer.DialContext(ctx, "tcp", address)
if err == nil {
_ = connection.Close()
return nil
if err != nil {
// log-exempt: 预期的缺失:目标还没监听时继续等待,超时由调用方处理。
return false, nil
}
// log-exempt: best-effort 清理:探测连接没有要送达的数据。
_ = connection.Close()
return true, nil
})
}

// A connection probe can consume a debuggee's first handshake. For host-owned
// runs, observe the listener through the OS and leave the first connection to DAP.
func debuggeeListening(pid int, port uint16) (bool, error) {
processes, err := sysinfo.Processes(sysinfo.Options{})
if err != nil {
return false, err
}
sockets, err := sysinfo.ListeningSockets(sysinfo.ProcessTreeIDs(pid, processes))
if err != nil {
return false, err
}
for _, socket := range sockets {
if socket.Port == port {
return true, nil
}
}
return false, nil
}

func waitForDebugPort(ctx context.Context, port int, ended <-chan struct{}, timeout time.Duration, ready func(context.Context) (bool, error)) error {
probeContext, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
ticker := time.NewTicker(runDebugPollInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-ended:
return ErrDebuggeeEnded
case <-deadline.C:
case <-probeContext.Done():
return fmt.Errorf("%w (port %d)", ErrDebugPortTimeout, port)
default:
}
listening, err := ready(probeContext)
if err != nil {
return err
}
if listening {
return nil
}
select {
case <-probeContext.Done():
case <-ended:
case <-ticker.C:
}
}
Expand Down
56 changes: 55 additions & 1 deletion desktop/internal/pluginservice/runs_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,12 +67,30 @@ func TestRunHelperProcess(t *testing.T) {
fmt.Printf("file %x\n", data)
}
os.Exit(0)
case "listen":
case "listen", "listen-once":
listener, err := net.Listen("tcp", "127.0.0.1:"+os.Getenv("LITHE_RUN_PORT"))
if err != nil {
os.Exit(2)
}
defer listener.Close()
if os.Getenv("LITHE_RUN_HELPER") == "listen-once" {
if err := listener.(*net.TCPListener).SetDeadline(time.Now().Add(10 * time.Second)); err != nil {
t.Fatal(err)
}
connection, err := listener.Accept()
if err != nil {
t.Fatal(err)
}
defer connection.Close()
if err := connection.SetReadDeadline(time.Now().Add(5 * time.Second)); err != nil {
t.Fatal(err)
}
var handshake [1]byte
if _, err := connection.Read(handshake[:]); err != nil || handshake[0] != 'D' {
t.Fatalf("first debugger connection did not handshake: %v", err)
}
return
}
time.Sleep(time.Minute)
os.Exit(0)
}
Expand Down Expand Up @@ -463,6 +481,42 @@ func TestRunStartAttachesTheDebuggerOnceThePortOpens(t *testing.T) {
}
}

func TestRunDebuggeeFirstConnectionBelongsToTheAdapter(t *testing.T) {
h := newRunHarness(t)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatal(err)
}
port := listener.Addr().(*net.TCPAddr).Port
if err := listener.Close(); err != nil {
t.Fatal(err)
}
h.service.Runs.Debug = func(ctx context.Context, request RunDebugRequest) (string, error) {
dialer := net.Dialer{Timeout: time.Second}
connection, err := dialer.DialContext(ctx, "tcp", net.JoinHostPort(request.Host, fmt.Sprint(request.Port)))
if err != nil {
return "", err
}
defer connection.Close()
if err := connection.SetWriteDeadline(time.Now().Add(time.Second)); err != nil {
return "", err
}
_, err = connection.Write([]byte{'D'})
return "debug-session", err
}
params := h.params(t, "listen-once", map[string]any{
"port": port,
"debug": map[string]any{"configurationType": "script", "target": map[string]any{"kind": "connection", "port": port}},
})
result, refusal := respond(t, h.service, runFixturePlugin, "run/start", params)
startedRunID(t, result, refusal)
events := h.await(t, "the fake debug handshake to finish", func(events []RunEvent) bool { return exitedEvent(events) != nil })
exited := exitedEvent(events)
if exited.ExitCode == nil || *exited.ExitCode != 0 {
t.Fatalf("run never received the expected first debugger connection: %+v", events)
}
}

func TestRunDebugStopsTheRunWhenTheAdapterCannotAttach(t *testing.T) {
h := newRunHarness(t)
listener, err := net.Listen("tcp", "127.0.0.1:0")
Expand Down
32 changes: 32 additions & 0 deletions desktop/internal/sysinfo/process.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,35 @@ type Options struct {
// Processes reads the process table: every process this user can see. A fact the system does
// not give for one process is zero or nil; the error says the table could not be listed at all.
func Processes(options Options) ([]Process, error) { return processes(options) }

// ProcessTreeIDs returns the root and the descendants visible in a native process snapshot.
// Callers use it to scope native per-process queries before reading details.
func ProcessTreeIDs(rootPID int, table []Process) []int {
byPID := make(map[int]Process, len(table))
children := make(map[int][]Process)
for _, row := range table {
if _, seen := byPID[row.PID]; row.PID <= 0 || seen {
continue
}
byPID[row.PID] = row
children[row.ParentPID] = append(children[row.ParentPID], row)
}
pids := []int{rootPID}
seen := map[int]bool{rootPID: true}
for index := 0; index < len(pids); index++ {
parentPID := pids[index]
parent, hasParent := byPID[parentPID]
for _, child := range children[parentPID] {
if seen[child.PID] {
continue
}
// Guard against OS PID reuse where a child appears older than its recycled parent.
if hasParent && parent.StartTime > 0 && child.StartTime > 0 && parent.StartTime > child.StartTime {
continue
}
seen[child.PID] = true
pids = append(pids, child.PID)
}
}
return pids
}
8 changes: 7 additions & 1 deletion desktop/internal/workbench/debug_start.go
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,13 @@ func (a *App) attachDebugForRun(ctx context.Context, request pluginservice.RunDe
target: &core.DebugTargetFacts{Kind: "connection", Host: request.Host, Port: request.Port},
stopRun: request.StopRun,
})
result <- outcome{id: p.debug.activeSession().id}
session := p.debug.activeSession()
if session == nil {
result <- outcome{err: errors.New("the debug session did not start")}
return
}
a.openToolWindow(itemDebug)
result <- outcome{id: session.id}
return
}
}
Expand Down
37 changes: 37 additions & 0 deletions desktop/internal/workbench/debug_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -655,3 +655,40 @@ func TestRunAttachLoadsAdaptersWithoutOpeningDebugPanel(t *testing.T) {
t.Fatalf("adapter discovery loaded=%v error=%v", p.debug.loaded, err)
}
}

func attachRunDebugOptions(t *testing.T, theme string) Options {
t.Helper()
manifest := strings.Replace(debugAttachManifest, `"requests": ["attach"]`, `"requests": ["attach"], "configurationTypes": ["fixture-attach"]`, 1)
return debugPluginOptions(t, "dev.lithe.test.debug-attach", manifest, true, &testKernel{Client: core.NewClient()}, theme)
}

func TestRunAttachShowsDebugWindow(t *testing.T) {
h := newHarnessWithOptions(t, attachRunDebugOptions(t, "dark"))
p := attachRunDebugFixture(t, h)
h.app.stopDebug(p)
}

func attachRunDebugFixture(t *testing.T, h *harness) *project {
t.Helper()
root, _ := fixtureWorkspace(t)
h.open(root)
p := h.app.project
h.app.openToolWindow(itemRun)
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
defer cancel()
done := make(chan error, 1)
go func() {
_, err := h.app.attachDebugForRun(ctx, pluginservice.RunDebugRequest{
PluginID: "dev.lithe.test.debug-attach", WorkspaceRoot: root,
ConfigurationType: "fixture-attach", Host: "127.0.0.1", Port: 12345,
})
done <- err
}()
if err := awaitValueWithin(t, h, 10*time.Second, done, "the run's attach request"); err != nil {
t.Fatal(err)
}
if !h.app.chrome.isOpen(catalogIndex[itemDebug]) {
t.Fatal("the run started an attach session without showing the Debug window")
}
return p
}
Loading