diff --git a/.agents/notes/implemented/architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md b/.agents/notes/implemented/architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md
index 6c5e376490..48d34b8302 100644
--- a/.agents/notes/implemented/architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md
+++ b/.agents/notes/implemented/architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md
@@ -20,6 +20,22 @@ Viva 客户端现在由 `pluginservice.BackendHost` 为每个插件保持至多
- **上下文**:`WorkspaceContexts` 每个打开的项目一个 context,项目关闭即失效,重新打开得到新 ID;`listContexts` 不创建目录,只有 `getContext` 创建并返回状态目录。变化时发送 `didChangeContexts` 并向 Core 重新配置跨插件调用快照。
- **语言服务器会话**:`LanguageSession` 记录 context 与每次启动递增的 generation;`ServeLanguageSession` 在窗口观察者之前处理 `requestCompleted`(唤醒转发请求)、`stateChanged`(映射为 `didChangeState`)和 `pluginServerNotification`(转为 `didReceiveNotification`)。服务器停止时仍在等待的请求以 `languageServerUnavailable` 结束。
+### 2026-11-13:编辑器注册与首次调试的时序
+
+插件注册编辑器动作或语言功能时,`context` 是宿主定位工作区的路由信息,不属于交给 Core 的动作/Provider 声明。宿主先检查调用方与工作区,再移除这层路由信息;不得放宽 Core 对未知字段的检查。回归必须经过真实 Core 解码,只有假宿主通过会漏掉这个问题。
+
+动作注册和撤回后,窗口重新收集当前打开文档的动作;语言服务器就绪时同样刷新。窗口只排队刷新,不在注册请求里同步调用插件,否则注册应答和动作收集可能互相等待。正确做法是注册完成后发窗口事件;不要要求用户编辑一下文件才出现 Run/Debug 标记。
+
+插件通过 `run/start` 发起调试时,适配器目录由宿主按需读取,完成后再进入既有启动或附加流程,并检查原请求是否已取消。不要要求用户先打开 Debug 工具窗口来触发目录加载。这些都是宿主的通用接线;JDT(Java 语言服务器)、Java 编译、classpath(运行时类路径)和 JDWP(Java 调试连接协议)的知识仍留在 Java 插件。
+
+Run 自己启动的进程还必须随附加的调试会话释放。单独发送 DAP disconnect 只断开连接,上游可能把仍暂停的进程留下;因此原生 Run 适配器向调试会话传入有界停止回调,在后台关闭调试连接后回收所拥有的进程。手动附加到用户外部进程时没有该回调,不改变外部进程所有权。这个内部生命周期接线不增加插件 API,也不由插件猜测或杀死宿主进程。
+
+真实 ZIP 集成测试覆盖含第三方依赖的 Maven 编译、补全、运行、断点变量、继续退出、再次调试后停止及编译错误拒绝旧 class;同时核对 Core 操作日志与包哈希不变。这是 macOS arm64 无头工作台的证据,原生窗口与其他平台仍需分别验收。
+
+旧项目的实际运行时与源码级别必须分别验证。JDK 8 可以为 Java 5/7 源码生成旧 class,当前 ECJ(Eclipse 的 Java 编译器)却只接受 Java 8 及以上,运行前 JDT 构建因此失败。`TestJavaPluginLegacySourceBoundaries` 验证的是安全拒绝,不能当成 Java 5/7 Run/Debug 验收。不得恢复“编译失败也运行旧产物”,也不得由宿主改写用户 POM 升级源码级别;历史项目的临时 POM 改动只能发生在测试副本,并单独报告。
+
+多工作区关闭还暴露既有 `pluginbackend.Runner.Stop` 通过销毁失败循环等待终态的问题:进程最终退出,但正常关闭产生 Core WARN。它属于本次之前已有的共享状态职责债务,独立记录为 [#1860](https://github.com/1lck/Lithe-IDEA/issues/1860),不混入 Java 接入修复。
+
## 考虑过的备选方案
- 在 `Handler` 签名里加调用方参数:改动所有处理器;用 context 携带身份同样隐含在 Core 的会话归属里,改动更小。
@@ -38,6 +54,9 @@ Viva 客户端现在由 `pluginservice.BackendHost` 为每个插件保持至多
## 验证
+- `scripts/desktop/desktop-go.sh test ./internal/pluginservice -run 'TestEditorActionRegistrationRefreshesOpenDocuments|TestEditorProviderRegistrationBindsEveryRoutedFunction' -count=1`:经过真实 Core 校验动作和 Provider 注册,并验证动作注册/撤回会刷新窗口。
+- `scripts/desktop/desktop-go.sh test ./internal/workbench -run 'TestRunAttachLoadsAdaptersWithoutOpeningDebugPanel|TestRunLaunchTargetBindsTheRunsProcessIntoTheLaunch' -count=1`:不打开调试面板也能加载目录;适配器启动与参数绑定保持原有流程。
+
- `scripts/desktop/desktop-go.sh test ./internal/pluginservice/... ./internal/pluginbackend/... ./internal/pluginhost/... -race -count=1`。
- 设置 `LITHE_JAVA_PLUGIN_MANIFEST` 指向 Java Support 的 `plugin.json` 时,`TestJavaSupportManifestOnlyLacksOtherLanesCapabilities` 用 Core 验证清单仅缺上述其他车道的能力。
diff --git a/.agents/notes/implemented/bug-fix/2026-11-13-viva-plugin-run-debug-lifecycle.md b/.agents/notes/implemented/bug-fix/2026-11-13-viva-plugin-run-debug-lifecycle.md
new file mode 100644
index 0000000000..868bed3cf2
--- /dev/null
+++ b/.agents/notes/implemented/bug-fix/2026-11-13-viva-plugin-run-debug-lifecycle.md
@@ -0,0 +1,54 @@
+# Agent 笔记:Viva 插件动作注册、首次调试与运行进程回收
+
+状态:已实现
+
+## 先说结论
+
+插件声明本身符合契约,也可能因为宿主接线不完整而无法显示 Run 或首次调试失败。Viva 现在把动作声明与工作区路由分开交给 Core 校验,注册变化后异步刷新文档,首次调试按需加载适配器。Run 启动的进程还会随附加调试会话在后台有界回收;Java 规则仍由独立插件和上游工具负责。
+
+## 问题
+
+这些路径来自 `0faecba491` 的 Viva 迁移:注册请求中的 context 被一并交给严格声明解码器,真实 Core 因额外字段拒绝;轻量假宿主没有解码器,原测试未覆盖。注册完成后也没有刷新已打开文档,动作可能要等用户再编辑才出现。
+
+Run 发起调试时直接要求适配器目录已加载,但目录之前只会在 Debug 面板打开时加载。调试工具栏停止又只断开调试适配器协议(DAP)连接,没有回收 Run 自己启动的进程,真实 Java 调试中会留下仍暂停的 JVM(Java 虚拟机)。
+
+## 决策
+
+声明校验仍由 Core 严格执行;Go 只移除已经检查过的路由 context,不放宽未知字段规则。注册和撤回通知窗口排队刷新,锁内不调用插件,避免注册应答和动作查询相互等待。语言服务器就绪后也重新收集动作。
+
+模型刷新未必修改文本,不能只凭文档文本版本接受动作查询的异步结果。窗口为每份文档持有动作呈现代际,清空或重新查询时推进它;晚到的旧结果不能覆盖新动作,也不能替换当前失败提示。Java 插件另行监听渐进导入的项目/classpath 事件并校验服务器代际,不将第一次 ServiceReady 等同于所有模块导入完毕。
+
+Run 的首次调试复用既有适配器加载入口,完成后检查原调用是否取消。Run 原生进程所有者给附加会话一个有界停止回调,调试连接关闭后在后台调用;手动附加到外部进程没有回调,不接管外部进程所有权。
+
+关闭项目可能同时从调试会话和工作区请求停止同一个 Run。自动清理重复到达时只保留第一次停止及退出宽限;只有用户或插件再次明确请求停止,才立即强制结束。调试清理先销毁 Core 会话,再等待 Run 的退出宽限,避免进程的较长收尾耗尽 Core 销毁的截止时间。例如,工作区和调试会话都关闭属于一次自动回收,不能等同于用户连续点击两次停止。
+
+真实插件测试在创建工作台后就登记无交互清理,不依赖成功路径的关闭动作。即使断言在断点暂停或文档未保存时中止,也直接关闭测试拥有的项目,等待后台任务、停止剩余运行,并验证 Core 调试会话已移除;不能把需要用户确认的关闭弹窗当作失败清理。
+
+## 考虑过的备选方案
+
+- 放宽 Core 声明解码:掩盖宿主把路由信息当成声明的错误,也允许其他无效字段通过。
+- 要求用户编辑文件或先打开 Debug 面板:把接线时序变成操作前提,不能修复首次使用。
+- 在 Java 插件里按 PID 杀进程:插件不拥有宿主进程树,会重复实现原生清理并误伤外部附加目标。
+
+## 后果
+
+首次打开 Java 文档即可出现动作,首次 Debug 不依赖面板预热,停止会清理所拥有的运行。代价是窗口多一个内部刷新通知和调试会话多一个进程清理回调;不增加公共插件 API。
+
+旧源码兼容性另行判断:当前随包 ECJ 编译器拒绝 Java 5/7 源码级别,安全拒绝测试不能当成这些工程完整可运行。正常关闭的既有销毁重试噪声独立记录为 [#1860](https://github.com/1lck/Lithe-IDEA/issues/1860),本修复不改变该策略。
+
+## 验证
+
+- 真实 Core 解码回归:动作/Provider 注册在修复前报 `plugin.host.invalidParams`,修复后接受并刷新;拒绝重复注册不触发刷新。
+- 同文本版本下倒序送达两次收集结果:修复前旧空结果覆盖新动作,修复后保留新动作;测试直接控制送达顺序,无时间竞争。
+- 未打开 Debug 面板的 attach/launch 回归:修复前返回适配器仍在加载,修复后按需加载并进入既有调试流程。
+- `TestJavaPluginMavenWorkflow` 与旧布局矩阵:真实 ZIP、Maven、JDT 和调试器,验证断点变量、继续退出、再次调试后停止,以及安装目录哈希不变;停止回收回归在修复前超时,修复后退出。
+- 自动停止重复到达和销毁顺序用事件控制:修复前分别提前强制终止、先等待进程再销毁 Core;修复后保留宽限,且进程等待开始前已销毁 Core。用户再次停止的强制结束行为仍保留。
+- `TestJavaPluginCleanupWhilePaused` 在真实 Java 断点暂停后直接返回,跳过成功路径关闭,由始终执行的清理收回运行并确认 Core 返回会话不存在。
+- `scripts/desktop/desktop-go.sh test ./...` 与受影响包的 `-race`;本机证据来自 macOS arm64 无头工作台,原生窗口与其他平台未据此标记已验收。
+
+## 适用范围
+
+- `desktop/internal/pluginservice/hostactions.go`、`hostproviders.go`、`runs.go`
+- `desktop/internal/workbench/debug_start.go`、`debug.go`、`pluginworkbench.go`、`pluginbackends.go`
+- `desktop/internal/workbench/java_plugin_e2e_test.go`、`java_legacy_e2e_test.go`
+- 通用职责边界见 [插件后端会话与宿主服务](../architecture/2026-11-10-viva-plugin-host-services-and-backend-sessions.md)。
diff --git a/desktop/internal/pluginservice/hostactions.go b/desktop/internal/pluginservice/hostactions.go
index fb793beddb..fc12ebd2e9 100644
--- a/desktop/internal/pluginservice/hostactions.go
+++ b/desktop/internal/pluginservice/hostactions.go
@@ -133,7 +133,11 @@ func (s *Service) handleRegisterEditorActions(ctx context.Context, params json.R
return nil, failure(CodePreconditionFailed, "The function is not registered on this session.")
}
if decoder, ok := s.kernel.(editorActionDecoder); ok {
- if _, err := decoder.DecodeEditorActions(ctx, map[string]any{"kind": "registration", "value": json.RawMessage(params), "version": core.EditorActionDecodeVersion, "icons": core.EditorHost.ActionIcons, "sourceBytes": core.EditorHost.ActionSourceBytes}); err != nil {
+ value, err := editorRegistrationValue(params)
+ if err != nil {
+ return nil, invalidParams(err)
+ }
+ if _, err := decoder.DecodeEditorActions(ctx, map[string]any{"kind": "registration", "value": value, "version": core.EditorActionDecodeVersion, "icons": core.EditorHost.ActionIcons, "sourceBytes": core.EditorHost.ActionSourceBytes}); err != nil {
return nil, failure(codeInvalidParams, err.Error())
}
}
@@ -167,12 +171,33 @@ func (s *Service) handleRegisterEditorActions(ctx context.Context, params json.R
s.actions.mu.Unlock()
id := s.resources.add(caller, workspace.ContextID, func() {
s.actions.mu.Lock()
- defer s.actions.mu.Unlock()
s.actions.list = removeBinding(s.actions.list, binding)
+ s.actions.mu.Unlock()
+ s.editorActionsChanged(workspace.Path)
})
+ s.editorActionsChanged(workspace.Path)
return marshalResult(map[string]string{"subscriptionID": id})
}
+// editorRegistrationValue separates the host routing envelope from the Core declaration.
+// Context has already been checked by workspaceRequest; Core validates only the declaration.
+func editorRegistrationValue(params json.RawMessage) (map[string]json.RawMessage, error) {
+ var value map[string]json.RawMessage
+ if err := json.Unmarshal(params, &value); err != nil {
+ return nil, err
+ }
+ delete(value, "context")
+ return value, nil
+}
+
+// editorActionsChanged invalidates the window's presentation after a binding changes.
+// The window queues work; it must not call the backend synchronously from this handler.
+func (s *Service) editorActionsChanged(root string) {
+ if window, ok := s.workbench.(interface{ EditorActionsChanged(string) }); ok {
+ window.EditorActionsChanged(root)
+ }
+}
+
func removeBinding(list []*editorActionBinding, target *editorActionBinding) []*editorActionBinding {
kept := list[:0]
for _, binding := range list {
diff --git a/desktop/internal/pluginservice/hostactions_refresh_test.go b/desktop/internal/pluginservice/hostactions_refresh_test.go
new file mode 100644
index 0000000000..c71b69fe62
--- /dev/null
+++ b/desktop/internal/pluginservice/hostactions_refresh_test.go
@@ -0,0 +1,76 @@
+package pluginservice
+
+import (
+ "context"
+ "encoding/json"
+ "path/filepath"
+ "testing"
+
+ "github.com/1lck/Lithe-IDEA/desktop/internal/core"
+ "github.com/1lck/Lithe-IDEA/desktop/internal/pluginbackend"
+ "github.com/1lck/Lithe-IDEA/desktop/internal/store"
+)
+
+type actionRefreshWorkbench struct {
+ *fakeWorkbench
+ roots []string
+}
+
+func (w *actionRefreshWorkbench) EditorActionsChanged(root string) { w.roots = append(w.roots, root) }
+
+func TestEditorActionRegistrationRefreshesOpenDocuments(t *testing.T) {
+ observer := &actionRefreshWorkbench{fakeWorkbench: &fakeWorkbench{}}
+ service, workspace := openDecodedEditorService(t, observer)
+ service.Host.mu.Lock()
+ service.Host.sessions["a"] = &BackendSession{host: service.Host, PluginID: "a", Session: pluginbackend.Session{ID: "session-a"}, functions: map[string]bool{"actions.collect": true}, waiters: map[string]chan core.BackendEvent{}, done: make(chan struct{}), changed: make(chan struct{}), ready: true}
+ service.Host.mu.Unlock()
+ body := `{` + contextJSONOf(workspace) + `,"id":"actions","function":"actions.collect","selector":{"fileExtensions":["java"]}}`
+ if _, refusal := respond(t, service, "a", "editor/registerActions", body); refusal != nil {
+ t.Fatalf("register: %+v", refusal)
+ }
+ if len(observer.roots) != 1 || observer.roots[0] != workspace.Path {
+ t.Fatalf("registration did not refresh documents: %v", observer.roots)
+ }
+ if _, refusal := respond(t, service, "a", "editor/registerActions", body); refusal == nil {
+ t.Fatal("duplicate accepted")
+ }
+ if len(observer.roots) != 1 {
+ t.Fatal("rejected registration refreshed documents")
+ }
+ service.resources.releaseContext(workspace.ContextID)
+ if len(observer.roots) != 2 {
+ t.Fatalf("withdrawal did not clear actions: %v", observer.roots)
+ }
+}
+
+// Use the real decoder: the lightweight host test kernel deliberately omits it.
+type realActionDecoder struct{ *notifyKernel }
+
+func (k *realActionDecoder) DecodeEditorActions(ctx context.Context, payload any) (json.RawMessage, error) {
+ return core.NewClient().DecodeEditorActions(ctx, payload)
+}
+
+func (k *realActionDecoder) DecodeEditorProviders(ctx context.Context, payload any) (json.RawMessage, error) {
+ return core.NewClient().DecodeEditorProviders(ctx, payload)
+}
+
+// Assemble dependencies before opening the context. Function relay startup is not
+// part of declaration validation; keep this unit test free of background observers.
+func openDecodedEditorService(t *testing.T, window Workbench) (*Service, WorkspaceContext) {
+ t.Helper()
+ kernel := &realActionDecoder{notifyKernel: ¬ifyKernel{}}
+ service, err := Open(kernel, store.At(t.TempDir()), t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := service.AttachWorkbench(window); err != nil {
+ t.Fatal(err)
+ }
+ service.Contexts.SetObserver(nil)
+ t.Cleanup(service.Contexts.CloseAll)
+ root, err := filepath.EvalSymlinks(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ return service, service.Contexts.Open(root)
+}
diff --git a/desktop/internal/pluginservice/hostproviders.go b/desktop/internal/pluginservice/hostproviders.go
index 0f397aa86c..dd60003159 100644
--- a/desktop/internal/pluginservice/hostproviders.go
+++ b/desktop/internal/pluginservice/hostproviders.go
@@ -117,7 +117,11 @@ func (s *Service) handleRegisterEditorProviders(ctx context.Context, params json
return nil, failure(codeInvalidParams, "The selector needs one to 32 entries.")
}
if decoder, ok := s.kernel.(editorProviderDecoder); ok {
- if _, err := decoder.DecodeEditorProviders(ctx, map[string]any{"kind": "registration", "value": json.RawMessage(params), "types": routedProviderTypes}); err != nil {
+ value, err := editorRegistrationValue(params)
+ if err != nil {
+ return nil, invalidParams(err)
+ }
+ if _, err := decoder.DecodeEditorProviders(ctx, map[string]any{"kind": "registration", "value": value, "types": routedProviderTypes}); err != nil {
return nil, failure(codeInvalidParams, err.Error())
}
}
diff --git a/desktop/internal/pluginservice/hostproviders_routes_test.go b/desktop/internal/pluginservice/hostproviders_routes_test.go
index 71cc2ba666..322d0e59ad 100644
--- a/desktop/internal/pluginservice/hostproviders_routes_test.go
+++ b/desktop/internal/pluginservice/hostproviders_routes_test.go
@@ -30,12 +30,14 @@ func TestProviderFunctionFieldsMatchRoutedTypes(t *testing.T) {
}
func TestEditorProviderRegistrationBindsEveryRoutedFunction(t *testing.T) {
- service, _, workspace, _ := openWorkbenchService(t)
+ service, workspace := openDecodedEditorService(t, &fakeWorkbench{})
+ service.Host.mu.Lock()
service.Host.sessions["a"] = &BackendSession{
host: service.Host, PluginID: "a", Session: pluginbackend.Session{ID: "session-a"},
functions: map[string]bool{"keys.lens": true, "keys.tokens": true, "keys.complete": true},
waiters: map[string]chan core.BackendEvent{}, done: make(chan struct{}), changed: make(chan struct{}), ready: true,
}
+ service.Host.mu.Unlock()
selector := `"selector":{"fileExtensions":["properties"]}`
if _, refusal := respond(t, service, "a", "editor/registerProviders", `{`+contextJSONOf(workspace)+`,"id":"fold",`+selector+`,"providers":{"foldingRange":{"function":"keys.lens"}}}`); refusal == nil || refusal.Code != codeInvalidParams {
t.Fatalf("unrouted type = %+v", refusal)
diff --git a/desktop/internal/pluginservice/runs.go b/desktop/internal/pluginservice/runs.go
index d5043ace05..651d253b0c 100644
--- a/desktop/internal/pluginservice/runs.go
+++ b/desktop/internal/pluginservice/runs.go
@@ -86,6 +86,10 @@ type RunDebugRequest struct {
ConfigurationType string
Host string
Port int
+ // StopRun ends the host-owned process when its attached debug session is
+ // released. It requests bounded cleanup off the UI thread; another owner
+ // already stopping the run keeps its grace and remains responsible for waiting.
+ StopRun func()
}
// RunDebugAttacher starts a debug session on the adapter a configuration type
@@ -235,15 +239,18 @@ func (r *Runs) Stop(runID string) {
if run == nil {
return
}
- r.stopRun(run)
+ r.stopRun(run, true)
}
// stopRun stops a run and waits, bounded, for its process tree. The tree first gets the
// stop time to end on its own (buildprocess.StopGrace). Stopping a run that is already
-// stopping kills it at once and returns: the first stop is the one still waiting.
-func (r *Runs) stopRun(run *hostRun) {
+// stopping kills it only for a repeated explicit request; automatic cleanup is
+// idempotent, so closing a workspace and its debug session preserve the grace.
+func (r *Runs) stopRun(run *hostRun, forceIfStopping bool) {
if run.stopped.Swap(true) {
- run.process.Kill()
+ if forceIfStopping {
+ run.process.Kill()
+ }
return
}
run.cancel()
@@ -265,7 +272,7 @@ func (r *Runs) StopWorkspace(path string) {
}
r.mu.Unlock()
for _, run := range stopping {
- r.stopRun(run)
+ r.stopRun(run, false)
}
}
@@ -279,7 +286,7 @@ func (r *Runs) StopAll() {
}
r.mu.Unlock()
for _, run := range stopping {
- r.stopRun(run)
+ r.stopRun(run, false)
}
r.wait.Wait()
}
@@ -568,7 +575,7 @@ func (r *Runs) attachDebugger(ctx context.Context, run *hostRun) {
fail := func(err error) {
if ctx.Err() == nil {
r.emit(RunEvent{Type: RunOutput, RunID: run.id, PluginID: run.pluginID, Text: err.Error() + "\n"})
- r.stopRun(run)
+ r.stopRun(run, false)
}
}
if err := waitForPort(ctx, port, run.done, runDebugConnectTimeout); err != nil {
@@ -582,6 +589,7 @@ func (r *Runs) attachDebugger(ctx context.Context, run *hostRun) {
session, err := r.Debug(ctx, RunDebugRequest{
PluginID: run.pluginID, WorkspaceRoot: run.workspace.Path, Label: run.start.Label,
ConfigurationType: run.start.Debug.ConfigurationType, Host: "127.0.0.1", Port: port,
+ StopRun: func() { r.stopRun(run, false) },
})
if err != nil {
fail(err)
@@ -651,7 +659,7 @@ func (r *Runs) handleStop(ctx context.Context, params json.RawMessage) (json.Raw
}
r.mu.Unlock()
if target != nil {
- r.stopRun(target)
+ r.stopRun(target, true)
} else if request.SessionID != "" {
r.stopDebugSession(caller.PluginID, request.SessionID)
}
diff --git a/desktop/internal/pluginservice/runs_test.go b/desktop/internal/pluginservice/runs_test.go
index dece0c4544..fd3099d905 100644
--- a/desktop/internal/pluginservice/runs_test.go
+++ b/desktop/internal/pluginservice/runs_test.go
@@ -11,6 +11,7 @@ import (
"path/filepath"
"strings"
"sync"
+ "sync/atomic"
"testing"
"time"
@@ -293,6 +294,47 @@ func TestRunStopEndsTheRunAndOnlyForItsOwner(t *testing.T) {
}
}
+type controlledStopProcess struct {
+ stopping chan struct{}
+ kills atomic.Int32
+}
+
+func (p *controlledStopProcess) Wait() error { return nil }
+func (p *controlledStopProcess) Stop() { close(p.stopping) }
+func (p *controlledStopProcess) Kill() { p.kills.Add(1) }
+
+func TestRunAutomaticStopsPreserveGraceAndUserCanForce(t *testing.T) {
+ process := &controlledStopProcess{stopping: make(chan struct{})}
+ done := make(chan struct{})
+ run := &hostRun{id: "owned", workspace: WorkspaceContext{Path: t.TempDir()}, process: process, cancel: func() {}, done: done}
+ runs := &Runs{runs: map[string]*hostRun{run.id: run}}
+ stopped := make(chan struct{})
+ go func() { runs.StopWorkspace(run.workspace.Path); close(stopped) }()
+ defer func() {
+ close(done)
+ select {
+ case <-stopped:
+ case <-time.After(5 * time.Second):
+ t.Error("the first automatic stop did not finish")
+ }
+ }()
+ select {
+ case <-process.stopping:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the automatic stop did not start")
+ }
+ // Closing a project and releasing its debug session can both request cleanup.
+ // Repetition by owners must preserve grace; an explicit second user Stop kills.
+ runs.StopWorkspace(run.workspace.Path)
+ if got := process.kills.Load(); got != 0 {
+ t.Fatalf("automatic cleanup forced %d kills before grace ended", got)
+ }
+ runs.Stop(run.id)
+ if got := process.kills.Load(); got != 1 {
+ t.Fatalf("a user Stop did not force the stopping process: %d kills", got)
+ }
+}
+
func TestRunStartRefusals(t *testing.T) {
h := newRunHarness(t)
@@ -409,6 +451,11 @@ func TestRunStartAttachesTheDebuggerOnceThePortOpens(t *testing.T) {
if request.Port != port || request.Host != "127.0.0.1" || request.ConfigurationType != "script" || request.PluginID != runFixturePlugin {
t.Fatalf("attach request = %+v", request)
}
+ if request.StopRun == nil {
+ t.Fatal("the debug session cannot release its owned run")
+ }
+ request.StopRun()
+ h.await(t, "the attached run to stop with its session", func(events []RunEvent) bool { return exitedEvent(events) != nil })
case <-time.After(20 * time.Second):
t.Fatal("the debugger was never attached")
}
diff --git a/desktop/internal/workbench/debug.go b/desktop/internal/workbench/debug.go
index ae7308b35e..6b27dc4454 100644
--- a/desktop/internal/workbench/debug.go
+++ b/desktop/internal/workbench/debug.go
@@ -270,6 +270,8 @@ type debugSession struct {
// adapter reported one. ended, when set, receives it once the session is released.
exitCode atomic.Pointer[int]
ended chan *int
+ // stopRun reaps an attached process owned by Run after the adapter disconnects.
+ stopRun func()
// hosted is the lifecycle-driven stream of a tcpLanguageServer adapter; nil
// for a stdio adapter. It is also the session's transport.
hosted *debugTransport
@@ -805,6 +807,7 @@ func (a *App) stopDebugByUser(p *project) {
// releaseDebugSession closes transport immediately and destroys Core state only
// after startup returned, so cancellation cannot race a late session creation.
+// Note: Run 进程所有权见 .agents/notes/implemented/bug-fix/2026-11-13-viva-plugin-run-debug-lifecycle.md。
func (a *App) releaseDebugSession(p *project, session *debugSession) {
session.cleanupOnce.Do(func() {
// A child that ends before its start was answered fails the parent's request.
@@ -846,6 +849,11 @@ func (a *App) releaseDebugSession(p *project, session *debugSession) {
if session.created && !session.coreGone {
destroyed, cleanupErr = a.kernel.DestroyDebugSession(ctx, session.id)
}
+ // The owned run can use the user's full exit grace. Finish Core
+ // destruction first so that wait cannot consume its deadline.
+ if session.stopRun != nil {
+ session.stopRun()
+ }
process := session.process.Load()
if process != nil {
_ = process.Wait()
diff --git a/desktop/internal/workbench/debug_start.go b/desktop/internal/workbench/debug_start.go
index 7a905bc7d8..72d0a31658 100644
--- a/desktop/internal/workbench/debug_start.go
+++ b/desktop/internal/workbench/debug_start.go
@@ -54,6 +54,8 @@ type debugStart struct {
// ended, when set, receives the debuggee's exit code once the session has been
// released, so the run that stands for it can end.
ended chan *int
+ // stopRun owns only a process started by Run, never a user's external attach target.
+ stopRun func()
// parent and startRequestID mark a child session an adapter started through
// startDebugging; its configuration is the adapter's, and parent answers the request.
parent *debugSession
@@ -219,31 +221,34 @@ func (a *App) attachDebugForRun(ctx context.Context, request pluginservice.RunDe
result <- outcome{err: errors.New("the run's workspace is not open")}
return
}
- if !p.debug.loaded {
- result <- outcome{err: errors.New("the debug adapters are still loading")}
- return
- }
- if p.debug.activeSession() != nil {
- result <- outcome{err: errors.New("a debug session is already running")}
- return
- }
- for _, adapter := range p.debug.adapters {
- if adapter.PluginID != request.PluginID || !adapter.Declaration.Serves("attach") || !adapter.Declaration.AcceptsConnection {
- continue
+ a.whenDebugAdaptersLoaded(p, func() {
+ if err := ctx.Err(); err != nil {
+ result <- outcome{err: err}
+ return
}
- for _, configurationType := range adapter.Declaration.ConfigurationTypes {
- if configurationType != request.ConfigurationType {
+ if p.debug.activeSession() != nil {
+ result <- outcome{err: errors.New("a debug session is already running")}
+ return
+ }
+ for _, adapter := range p.debug.adapters {
+ if adapter.PluginID != request.PluginID || !adapter.Declaration.Serves("attach") || !adapter.Declaration.AcceptsConnection {
continue
}
- a.beginDebug(p, debugStart{
- adapter: adapter, request: "attach", confirmed: true,
- target: &core.DebugTargetFacts{Kind: "connection", Host: request.Host, Port: request.Port},
- })
- result <- outcome{id: p.debug.activeSession().id}
- return
+ for _, configurationType := range adapter.Declaration.ConfigurationTypes {
+ if configurationType != request.ConfigurationType {
+ continue
+ }
+ a.beginDebug(p, debugStart{
+ adapter: adapter, request: "attach", confirmed: true,
+ target: &core.DebugTargetFacts{Kind: "connection", Host: request.Host, Port: request.Port},
+ stopRun: request.StopRun,
+ })
+ result <- outcome{id: p.debug.activeSession().id}
+ return
+ }
}
- }
- result <- outcome{err: fmt.Errorf("no debug adapter answers to %q", request.ConfigurationType)}
+ result <- outcome{err: fmt.Errorf("no debug adapter answers to %q", request.ConfigurationType)}
+ })
})
select {
case r := <-result:
@@ -269,43 +274,45 @@ func (a *App) launchDebugForRun(ctx context.Context, request pluginservice.RunDe
result <- outcome{err: errors.New("the run's workspace is not open")}
return
}
- if !p.debug.loaded {
- result <- outcome{err: errors.New("the debug adapters are still loading")}
- return
- }
- if p.debug.activeSession() != nil {
- result <- outcome{err: errors.New("a debug session is already running")}
- return
- }
- for _, adapter := range p.debug.adapters {
- if adapter.PluginID != request.PluginID || !adapter.Declaration.Serves("launch") ||
- !slices.Contains(adapter.Declaration.ConfigurationTypes, request.ConfigurationType) {
- continue
- }
- ended := make(chan *int, 1)
- arguments := slices.Clone(request.Arguments)
- if arguments == nil {
- arguments = []string{}
+ a.whenDebugAdaptersLoaded(p, func() {
+ if err := ctx.Err(); err != nil {
+ result <- outcome{err: err}
+ return
}
- environment := maps.Clone(request.Environment)
- if environment == nil {
- environment = map[string]string{}
+ if p.debug.activeSession() != nil {
+ result <- outcome{err: errors.New("a debug session is already running")}
+ return
}
- a.beginDebug(p, debugStart{
- adapter: adapter, request: "launch", ended: ended,
- launchTarget: &core.DebugTargetFacts{
- Kind: "executable", Path: request.Executable, Executable: request.Executable,
- WorkingDirectory: request.WorkingDirectory, Arguments: arguments, Environment: environment,
- },
- })
- if p.debug.activeSession() == nil || p.debug.activeSession().ended != ended {
- result <- outcome{err: fmt.Errorf("the debug session did not start: %s", p.debug.failure)}
+ for _, adapter := range p.debug.adapters {
+ if adapter.PluginID != request.PluginID || !adapter.Declaration.Serves("launch") ||
+ !slices.Contains(adapter.Declaration.ConfigurationTypes, request.ConfigurationType) {
+ continue
+ }
+ ended := make(chan *int, 1)
+ arguments := slices.Clone(request.Arguments)
+ if arguments == nil {
+ arguments = []string{}
+ }
+ environment := maps.Clone(request.Environment)
+ if environment == nil {
+ environment = map[string]string{}
+ }
+ a.beginDebug(p, debugStart{
+ adapter: adapter, request: "launch", ended: ended,
+ launchTarget: &core.DebugTargetFacts{
+ Kind: "executable", Path: request.Executable, Executable: request.Executable,
+ WorkingDirectory: request.WorkingDirectory, Arguments: arguments, Environment: environment,
+ },
+ })
+ if p.debug.activeSession() == nil || p.debug.activeSession().ended != ended {
+ result <- outcome{err: fmt.Errorf("the debug session did not start: %s", p.debug.failure)}
+ return
+ }
+ result <- outcome{session: pluginservice.RunDebugSession{ID: p.debug.activeSession().id, Ended: ended}}
return
}
- result <- outcome{session: pluginservice.RunDebugSession{ID: p.debug.activeSession().id, Ended: ended}}
- return
- }
- result <- outcome{err: fmt.Errorf("no debug adapter launches %q", request.ConfigurationType)}
+ result <- outcome{err: fmt.Errorf("no debug adapter launches %q", request.ConfigurationType)}
+ })
})
select {
case r := <-result:
@@ -426,6 +433,7 @@ func (a *App) beginDebug(p *project, start debugStart) {
exitObserved: make(chan struct{}),
generation: generation,
ended: start.ended,
+ stopRun: start.stopRun,
adapter: adapter,
parent: start.parent,
startRequestID: start.startRequestID,
diff --git a/desktop/internal/workbench/debug_test.go b/desktop/internal/workbench/debug_test.go
index 79d38968e5..3bca161b0e 100644
--- a/desktop/internal/workbench/debug_test.go
+++ b/desktop/internal/workbench/debug_test.go
@@ -366,6 +366,50 @@ func TestDebugStopBeforeCreateReturnsDestroysLateSession(t *testing.T) {
}
}
+type debugDestroyOrderKernel struct {
+ Kernel
+ destroyed chan struct{}
+}
+
+func (k *debugDestroyOrderKernel) DestroyDebugSession(ctx context.Context, _ string) ([]string, error) {
+ if err := ctx.Err(); err != nil {
+ return nil, err
+ }
+ close(k.destroyed)
+ return nil, nil
+}
+
+func TestDebugReleasesCoreBeforeWaitingForOwnedRun(t *testing.T) {
+ h := newHarness(t, &testKernel{Client: core.NewClient()})
+ h.open(t.TempDir())
+ p := h.app.project
+ kernel := &debugDestroyOrderKernel{Kernel: h.app.kernel, destroyed: make(chan struct{})}
+ h.app.kernel = kernel
+ startupDone := make(chan struct{})
+ close(startupDone)
+ ordered := make(chan bool, 1)
+ session := &debugSession{id: "owned-run", created: true, startupDone: startupDone, cancel: func() {}, stopRun: func() {
+ // No wall-clock delay: reaching the potentially slow process wait must
+ // already imply Core destruction, which owns its own bounded budget.
+ select {
+ case <-kernel.destroyed:
+ ordered <- true
+ default:
+ ordered <- false
+ }
+ }}
+ h.app.releaseDebugSession(p, session)
+ h.settle()
+ select {
+ case ok := <-ordered:
+ if !ok {
+ t.Fatal("the owned process wait can consume Core destruction's deadline")
+ }
+ default:
+ t.Fatal("the owned run was not released")
+ }
+}
+
func TestDebugBlockedWriteEndsOnCancellation(t *testing.T) {
reader, writer, err := os.Pipe()
if err != nil {
@@ -538,7 +582,8 @@ func TestRunLaunchTargetBindsTheRunsProcessIntoTheLaunch(t *testing.T) {
if err := os.WriteFile(filepath.Join(root, "debug.marker"), []byte("debug\n"), 0o600); err != nil {
t.Fatal(err)
}
- p := openDebugPanel(t, h, root)
+ h.open(root)
+ p := h.app.project
gate := &captureDebugLaunch{Kernel: h.app.kernel, configurations: make(chan core.DebugLaunchConfiguration, 1)}
h.app.kernel = gate
program := filepath.Join(root, "app")
@@ -588,3 +633,21 @@ func TestRunLaunchTargetBindsTheRunsProcessIntoTheLaunch(t *testing.T) {
}
})
}
+
+func TestRunAttachLoadsAdaptersWithoutOpeningDebugPanel(t *testing.T) {
+ h := debugHarness(t)
+ root := t.TempDir()
+ h.open(root)
+ p := h.app.project
+ done := make(chan error, 1)
+ ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
+ defer cancel()
+ go func() {
+ _, err := h.app.attachDebugForRun(ctx, pluginservice.RunDebugRequest{PluginID: "dev.lithe.test.debug-adapter", WorkspaceRoot: root, ConfigurationType: "missing"})
+ done <- err
+ }()
+ err := awaitValueWithin(t, h, 10*time.Second, done, "attach to resolve adapters")
+ if !p.debug.loaded || err == nil || !strings.Contains(err.Error(), "no debug adapter") {
+ t.Fatalf("adapter discovery loaded=%v error=%v", p.debug.loaded, err)
+ }
+}
diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go
index f2ebbc7e38..0a56436e47 100644
--- a/desktop/internal/workbench/documents.go
+++ b/desktop/internal/workbench/documents.go
@@ -134,6 +134,9 @@ type document struct {
// actions are the plugin editor actions the last collection answered for this text, and
// actionTimer the pending collection after an edit (editor_actions.go).
actions []pluginservice.EditorAction
+ // actionCollection invalidates pending presentation results when bindings
+ // change without changing this document's text revision.
+ actionCollection uint64
// links are the document links of the current text, from the plugin providers, indexed by
// the ID the view reports them with.
links []pluginservice.EditorLink
diff --git a/desktop/internal/workbench/editor_actions.go b/desktop/internal/workbench/editor_actions.go
index 416f8b3e5a..dd97f97d5a 100644
--- a/desktop/internal/workbench/editor_actions.go
+++ b/desktop/internal/workbench/editor_actions.go
@@ -40,6 +40,7 @@ func (a *App) scheduleEditorActions(p *project, d *document) {
// clearEditorActions forgets the document's actions and their annotations.
func (a *App) clearEditorActions(d *document) {
+ d.actionCollection++
d.actionPanel = editorActionPanel{}
d.pluginLinks = nil
d.serverLinks = documentServerLinks{revision: d.serverLinks.revision, seen: d.serverLinks.seen, changedAt: d.serverLinks.changedAt}
@@ -64,8 +65,10 @@ func (a *App) collectEditorActions(p *project, d *document) {
return
}
data, _ := d.view.Text()
+ d.actionCollection++
text, version, id, path, root, language := string(data), d.view.Revision(), strconv.Itoa(d.id), d.path, p.root, d.languageID
plugins := a.plugins
+ snapshot := editorActionSnapshot{documentID: d.id, version: version, collection: d.actionCollection}
a.background(p, 15*time.Second, func(ctx context.Context) func(*App) {
actions, err := plugins.CollectEditorActions(ctx, root, path, id, version, text)
// Code lenses come from the provider of the same document, as actions do, and join them.
@@ -74,21 +77,32 @@ func (a *App) collectEditorActions(p *project, d *document) {
// Document links come from the same document's providers and are shown on hover.
links, linkErr := plugins.PluginDocumentLinks(ctx, root, path, language, id, version)
err = errors.Join(err, lensErr, linkErr)
- return func(a *App) {
- if p.docs.find(d.id) != d || d.view.Revision() != version {
- return
- }
- if err != nil {
- a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_actions", err))
- }
- d.actions = actions
- a.annotateEditorActions(d)
- d.pluginLinks = links
- a.refreshDocumentLinks(d)
- }
+ return func(a *App) { a.presentEditorActions(p, snapshot, actions, links, err) }
})
}
+// editorActionSnapshot identifies the presentation request, including model
+// refreshes that leave the document text at the same revision.
+type editorActionSnapshot struct {
+ documentID int
+ version int
+ collection uint64
+}
+
+func (a *App) presentEditorActions(p *project, snapshot editorActionSnapshot, actions []pluginservice.EditorAction, links []pluginservice.EditorLink, err error) {
+ d := p.docs.find(snapshot.documentID)
+ if a.project != p || d == nil || d.view.Revision() != snapshot.version || d.actionCollection != snapshot.collection {
+ return
+ }
+ if err != nil {
+ a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("editor_actions", err))
+ }
+ d.actions = actions
+ a.annotateEditorActions(d)
+ d.pluginLinks = links
+ a.refreshDocumentLinks(d)
+}
+
// annotateEditorActions puts icons in the gutter. The icon area has one slot per lane in use, left to
// right in editorActionLanes order, so the run, debug, test and navigation icons of a line sit side by
// side. A line shows the first action of each lane; a press on that icon opens the lane's menu, or
diff --git a/desktop/internal/workbench/editoractions_test.go b/desktop/internal/workbench/editoractions_test.go
new file mode 100644
index 0000000000..d5ed99938b
--- /dev/null
+++ b/desktop/internal/workbench/editoractions_test.go
@@ -0,0 +1,47 @@
+package workbench
+
+import (
+ "errors"
+ "path/filepath"
+ "testing"
+
+ "github.com/1lck/Lithe-IDEA/desktop/internal/core"
+ "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice"
+)
+
+func TestEditorActionBindingRefreshDropsEarlierCollectionAtSameTextVersion(t *testing.T) {
+ h := newHarness(t, &testKernel{Client: core.NewClient()})
+ root := t.TempDir()
+ writeFixture(t, root, map[string]string{"source.txt": "content\n"})
+ h.open(root)
+ p := h.app.project
+ h.app.openFile(p, filepath.Join(root, "source.txt"))
+ h.settle()
+ d := documentNamed(p, "source.txt")
+ if d == nil {
+ t.Fatal("source document unavailable")
+ }
+ logger := &treeRecordingLog{}
+ h.app.logSink = logger
+
+ // The model, rather than the text, changed while an earlier collection
+ // was in flight. Deliver the latest result first and the earlier empty
+ // result/error last, with no clock or subprocess race in this regression.
+ h.app.clearEditorActions(d)
+ old := editorActionSnapshot{documentID: d.id, version: d.view.Revision(), collection: d.actionCollection}
+ h.app.clearEditorActions(d)
+ current := editorActionSnapshot{documentID: d.id, version: d.view.Revision(), collection: d.actionCollection}
+ want := []pluginservice.EditorAction{{ID: "latest", Title: "Latest", Range: pluginservice.EditorActionRange{StartLine: 1, StartColumn: 1, EndLine: 1, EndColumn: 1}}}
+ h.app.presentEditorActions(p, current, want, nil, nil)
+ h.app.presentEditorActions(p, old, nil, nil, errors.New("earlier collection failed"))
+ if len(d.actions) != 1 || d.actions[0].ID != "latest" {
+ t.Fatalf("earlier collection replaced current actions: %+v", d.actions)
+ }
+ logger.mu.Lock()
+ defer logger.mu.Unlock()
+ for _, event := range logger.events {
+ if event.Event == operationFailedEvent && event.Fields["operation"] == "editor_actions" {
+ t.Fatal("earlier collection replaced current failure presentation")
+ }
+ }
+}
diff --git a/desktop/internal/workbench/java_legacy_e2e_test.go b/desktop/internal/workbench/java_legacy_e2e_test.go
new file mode 100644
index 0000000000..65cf08d9e1
--- /dev/null
+++ b/desktop/internal/workbench/java_legacy_e2e_test.go
@@ -0,0 +1,212 @@
+package workbench
+
+import (
+ "fmt"
+ "io/fs"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+const javaWorkflowMain = "package demo;\npublic class Main {\n public static void main(String[] args) {\n int answer = 41;\n answer += 1;\n System.out.println(org.apache.commons.lang3.StringUtils.reverse(\"avaj\") + \"-result=\" + answer + \";vm=\" + System.getProperty(\"java.specification.version\"));\n }\n}\n"
+
+func javaFixturePOM(source, body string) string {
+ return fmt.Sprintf(`4.0.0demojava-pilot1.0%s%sUTF-8org.apache.commonscommons-lang33.17.0%s`, source, source, body)
+}
+
+// A fixed historical checkout is supplied externally and copied; this test
+// never changes the downloaded baseline or vendors upstream code into Lithe.
+func TestJavaPluginHistoricalProject(t *testing.T) {
+ root := os.Getenv("LITHE_TEST_JAVA_HISTORICAL_ROOT")
+ if root == "" {
+ t.Skip("set LITHE_TEST_JAVA_HISTORICAL_ROOT and LITHE_TEST_JAVA_HISTORICAL_PROBE")
+ }
+ probe := os.Getenv("LITHE_TEST_JAVA_HISTORICAL_PROBE")
+ java8 := os.Getenv("LITHE_TEST_JAVA8_HOME")
+ if probe == "" || java8 == "" {
+ t.Fatal("historical project requires a Java 8 home and a Java expression probing its API")
+ }
+ fixture := standardJavaFixture()
+ fixture.files = map[string]string{fixture.mainPath: strings.Replace(javaWorkflowMain, `org.apache.commons.lang3.StringUtils.reverse("avaj")`, `"java"`, 1)}
+ fixture.files[fixture.mainPath] = strings.Replace(fixture.files[fixture.mainPath], `System.getProperty("java.specification.version")`, `System.getProperty("java.specification.version") + ";probe=" + (`+probe+`)`, 1)
+ fixture.projectRoot, fixture.javaHome, fixture.vmVersion = root, java8, "1.8"
+ fixture.expectBuildRefused = os.Getenv("LITHE_TEST_JAVA_EXPECT_BUILD_REFUSAL") == "1"
+ if level := os.Getenv("LITHE_TEST_JAVA_HISTORICAL_SOURCE"); level != "" {
+ if level != "1.8" {
+ t.Fatal("historical override only supports explicit source/target 1.8")
+ }
+ pom, err := os.ReadFile(filepath.Join(root, "pom.xml"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ text := string(pom)
+ for _, key := range []string{"source", "target"} {
+ old := "1.5"
+ if !strings.Contains(text, old) {
+ t.Fatalf("historical POM lacks exact %s=1.5 property", key)
+ }
+ text = strings.ReplaceAll(text, old, "1.8")
+ }
+ fixture.files["pom.xml"] = text
+ t.Log("temporary copy only: POM compiler source/target changed from 1.5 to 1.8; this does not verify original Java 5 configuration")
+ }
+ runJavaPluginWorkflow(t, fixture)
+}
+
+func copyHistoricalJavaProject(t *testing.T, source, target string) {
+ t.Helper()
+ files, bytes := 0, int64(0)
+ err := filepath.WalkDir(source, func(path string, entry fs.DirEntry, err error) error {
+ if err != nil {
+ return err
+ }
+ if entry.IsDir() && (entry.Name() == ".git" || entry.Name() == "target") {
+ return filepath.SkipDir
+ }
+ if entry.IsDir() {
+ return nil
+ }
+ if !entry.Type().IsRegular() {
+ return fmt.Errorf("historical fixture must contain regular files: %s", path)
+ }
+ info, err := entry.Info()
+ if err != nil {
+ return err
+ }
+ files++
+ bytes += info.Size()
+ if files > 5000 || bytes > 100<<20 {
+ return fmt.Errorf("historical fixture exceeds 5000 files or 100 MiB")
+ }
+ rel, err := filepath.Rel(source, path)
+ if err != nil {
+ return err
+ }
+ data, err := os.ReadFile(path)
+ if err != nil {
+ return err
+ }
+ destination := filepath.Join(target, rel)
+ if err := os.MkdirAll(filepath.Dir(destination), 0700); err != nil {
+ return err
+ }
+ return os.WriteFile(destination, data, 0600)
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Logf("historical project copied: %d files, %d bytes; upstream POM unchanged", files, bytes)
+}
+
+func standardJavaFixture() javaWorkflowFixture {
+ return javaWorkflowFixture{files: map[string]string{"pom.xml": javaFixturePOM("17", ""), "src/main/java/demo/Main.java": javaWorkflowMain}, mainPath: "src/main/java/demo/Main.java", classPath: "target/classes/demo/Main.class"}
+}
+
+// These are deliberately opt-in real-tool integrations, not unit tests. Each
+// subtest owns a separate install, workspace, JDT data area and process lifetime.
+func TestJavaPluginLegacyWorkflows(t *testing.T) {
+ if os.Getenv("LITHE_TEST_JAVA_LEGACY") != "1" {
+ t.Skip("set LITHE_TEST_JAVA_LEGACY=1 and JAVA8/JAVA11 test homes")
+ }
+ java8, java11 := os.Getenv("LITHE_TEST_JAVA8_HOME"), os.Getenv("LITHE_TEST_JAVA11_HOME")
+ if java8 == "" || java11 == "" {
+ t.Fatal("legacy matrix requires LITHE_TEST_JAVA8_HOME and LITHE_TEST_JAVA11_HOME")
+ }
+ for _, source := range []struct {
+ name, level string
+ major byte
+ }{{"java8", "1.8", 52}} {
+ t.Run(source.name, func(t *testing.T) {
+ fixture := standardJavaFixture()
+ fixture.files["pom.xml"] = javaFixturePOM(source.level, "")
+ fixture.javaHome, fixture.vmVersion, fixture.classVersion = java8, "1.8", source.major
+ runJavaPluginWorkflow(t, fixture)
+ })
+ }
+ t.Run("maven2-custom-layout", func(t *testing.T) {
+ fixture := standardJavaFixture()
+ fixture.files = map[string]string{
+ "pom.xml": javaFixturePOM("1.8", `src/javabuild/classes`),
+ "src/java/demo/Main.java": javaWorkflowMain,
+ }
+ fixture.mainPath, fixture.classPath = "src/java/demo/Main.java", "build/classes/demo/Main.class"
+ fixture.javaHome, fixture.vmVersion = java8, "1.8"
+ runJavaPluginWorkflow(t, fixture)
+ })
+ t.Run("reactor-unicode-space-path", func(t *testing.T) {
+ fixture := standardJavaFixture()
+ fixture.files = map[string]string{
+ "pom.xml": `4.0.0demoparent1.0pomlibrary旧 模块`,
+ "library/pom.xml": strings.Replace(javaFixturePOM("11", ""), "java-pilot", "legacy-library", 1),
+ "library/src/main/java/demo/LegacyLibrary.java": `package demo; public class LegacyLibrary { public static String label() { return "java"; } }`,
+ "旧 模块/pom.xml": strings.Replace(javaFixturePOM("11", ""), "", "demolegacy-library1.0", 1),
+ "旧 模块/src/main/java/demo/Main.java": strings.Replace(javaWorkflowMain, `org.apache.commons.lang3.StringUtils.reverse("avaj")`, `LegacyLibrary.label()`, 1),
+ }
+ fixture.mainPath, fixture.classPath = "旧 模块/src/main/java/demo/Main.java", "旧 模块/target/classes/demo/Main.class"
+ fixture.javaHome, fixture.vmVersion, fixture.classVersion = java11, "11", 55
+ runJavaPluginWorkflow(t, fixture)
+ })
+ t.Run("active-profile-source-root", func(t *testing.T) {
+ fixture := standardJavaFixture()
+ fixture.files = map[string]string{
+ "pom.xml": javaFixturePOM("1.8", `${legacy.source}legacytrueold-src`),
+ "old-src/demo/Main.java": javaWorkflowMain,
+ }
+ fixture.mainPath, fixture.javaHome, fixture.vmVersion = "old-src/demo/Main.java", java8, "1.8"
+ runJavaPluginWorkflow(t, fixture)
+ })
+ t.Run("java8-javax-jaxb", func(t *testing.T) {
+ fixture := standardJavaFixture()
+ fixture.files["pom.xml"] = javaFixturePOM("1.8", "")
+ fixture.files[fixture.mainPath] = strings.Replace(javaWorkflowMain, `org.apache.commons.lang3.StringUtils.reverse("avaj")`, `new String(javax.xml.bind.DatatypeConverter.parseHexBinary("6A617661"), java.nio.charset.StandardCharsets.UTF_8)`, 1)
+ fixture.javaHome, fixture.vmVersion = java8, "1.8"
+ runJavaPluginWorkflow(t, fixture)
+ })
+ for _, framework := range []struct{ name, version, source string }{
+ {"junit3", "3.8.2", "package demo; public class LegacyTest extends junit.framework.TestCase { public void testLegacy() { assertEquals(42, 41+1); } }"},
+ {"junit4", "4.12", "package demo; public class LegacyTest { @org.junit.Test public void legacy() { org.junit.Assert.assertEquals(42,41+1); } }"},
+ } {
+ t.Run(framework.name, func(t *testing.T) {
+ fixture := standardJavaFixture()
+ fixture.files["pom.xml"] = strings.Replace(javaFixturePOM("1.8", ""), "", "junitjunit"+framework.version+"test", 1)
+ fixture.files["src/test/java/demo/LegacyTest.java"] = framework.source
+ fixture.javaHome, fixture.vmVersion, fixture.testGoal = java8, "1.8", true
+ runJavaPluginWorkflow(t, fixture)
+ })
+ }
+ t.Run("eclipse-ant-layout", func(t *testing.T) {
+ fixture := standardJavaFixture()
+ fixture.files = map[string]string{
+ ".project": `legacy-antorg.eclipse.jdt.core.javabuilderorg.eclipse.jdt.core.javanature`,
+ ".classpath": ``,
+ ".settings/org.eclipse.jdt.core.prefs": "eclipse.preferences.version=1\norg.eclipse.jdt.core.compiler.codegen.targetPlatform=1.8\norg.eclipse.jdt.core.compiler.compliance=1.8\norg.eclipse.jdt.core.compiler.source=1.8\n",
+ "build.xml": ``,
+ "src/demo/Main.java": strings.ReplaceAll(javaWorkflowMain, `org.apache.commons.lang3.StringUtils.reverse("avaj")`, `"java"`),
+ }
+ fixture.mainPath, fixture.classPath = "src/demo/Main.java", "bin/demo/Main.class"
+ fixture.javaHome, fixture.vmVersion, fixture.noMaven = java8, "1.8", true
+ runJavaPluginWorkflow(t, fixture)
+ })
+}
+
+func TestJavaPluginLegacySourceBoundaries(t *testing.T) {
+ if os.Getenv("LITHE_TEST_JAVA_LEGACY") != "1" {
+ t.Skip("set LITHE_TEST_JAVA_LEGACY=1")
+ }
+ java8 := os.Getenv("LITHE_TEST_JAVA8_HOME")
+ if java8 == "" {
+ t.Fatal("set LITHE_TEST_JAVA8_HOME")
+ }
+ for _, source := range []struct {
+ name, level string
+ major byte
+ }{{"java5", "1.5", 49}, {"java7", "1.7", 51}} {
+ t.Run(source.name, func(t *testing.T) {
+ fixture := standardJavaFixture()
+ fixture.files["pom.xml"] = javaFixturePOM(source.level, "")
+ fixture.javaHome, fixture.classVersion, fixture.expectBuildRefused = java8, source.major, true
+ runJavaPluginWorkflow(t, fixture)
+ })
+ }
+}
diff --git a/desktop/internal/workbench/java_plugin_e2e_test.go b/desktop/internal/workbench/java_plugin_e2e_test.go
new file mode 100644
index 0000000000..476acbf8df
--- /dev/null
+++ b/desktop/internal/workbench/java_plugin_e2e_test.go
@@ -0,0 +1,445 @@
+package workbench
+
+import (
+ "context"
+ "errors"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/1lck/Lithe-IDEA/desktop/internal/core"
+ "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost"
+ "github.com/1lck/Lithe-IDEA/desktop/internal/plugininstall"
+ "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice"
+ "github.com/1lck/Lithe-IDEA/desktop/internal/plugintrust"
+ "github.com/1lck/Lithe-IDEA/desktop/internal/store"
+ "github.com/vivaui/viva/app"
+)
+
+// Opt-in integration: install the actual Java archive, then drive the same editor,
+// run and DAP paths as the native window. All Java knowledge lives in the archive.
+func TestJavaPluginMavenWorkflow(t *testing.T) {
+ runJavaPluginWorkflow(t, standardJavaFixture())
+}
+
+func TestJavaPluginCleanupWhilePaused(t *testing.T) {
+ fixture := standardJavaFixture()
+ fixture.cleanupWhilePaused = true
+ runJavaPluginWorkflow(t, fixture)
+}
+
+type javaWorkflowFixture struct {
+ files map[string]string
+ mainPath string
+ classPath string
+ javaHome string
+ vmVersion string
+ classVersion byte
+ noMaven bool
+ projectRoot string
+ expectBuildRefused bool
+ testGoal bool
+ cleanupWhilePaused bool
+}
+
+func runJavaPluginWorkflow(t *testing.T, fixture javaWorkflowFixture) {
+ t.Helper()
+ if fixture.javaHome != "" {
+ t.Setenv("JAVA_HOME", fixture.javaHome)
+ }
+
+ archive := os.Getenv("LITHE_TEST_JAVA_PLUGIN_ARCHIVE")
+ if archive == "" {
+ t.Skip("set LITHE_TEST_JAVA_PLUGIN_ARCHIVE to the built Java plugin zip")
+ }
+ mavenArchive := os.Getenv("LITHE_TEST_MAVEN_PLUGIN_ARCHIVE")
+ if mavenArchive == "" {
+ t.Skip("set LITHE_TEST_MAVEN_PLUGIN_ARCHIVE to the compatible Maven plugin zip")
+ }
+ preferences := store.At(t.TempDir())
+ if err := os.WriteFile(filepath.Join(preferences.Dir(), settingsFile), []byte(`{"theme":"dark","autoSave":false}`), 0600); err != nil {
+ t.Fatal(err)
+ }
+ kernel := &testKernel{Client: core.NewClient()}
+ h := newHarnessWithOptions(t, Options{Kernel: kernel, PluginKernel: kernel, PluginRoot: t.TempDir(), Store: preferences, Languages: []string{"en"}})
+ if h.app.plugins == nil {
+ t.Fatal("plugin service unavailable")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute)
+ defer cancel()
+ service := h.app.plugins
+ t.Cleanup(func() {
+ // Assertions can abort while a Run is paused or a document is dirty.
+ // This fixture owns the project: bypass interactive save/exit prompts.
+ var sessionID string
+ if p := h.app.project; p != nil {
+ if session := p.debug.activeSession(); session != nil {
+ sessionID = session.id
+ }
+ h.app.finishCloseProject(p, nil)
+ }
+ h.settle()
+ service.Runs.StopAll()
+ if active := service.Runs.Active(); len(active) != 0 {
+ t.Errorf("fixture cleanup left runs: %v", active)
+ }
+ if sessionID != "" {
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ _, err := kernel.ReceiveDebug(ctx, sessionID, nil)
+ var failure *core.Error
+ if !errors.As(err, &failure) || failure.Code != core.CodeInvalidRequest || failure.Message != "Debug session was not found." {
+ t.Errorf("fixture cleanup did not remove its Core debug session: %v", err)
+ }
+ t.Log("unconditional cleanup: no active runs; Core debug session removed")
+ }
+ })
+ plan, err := service.Installer.Prepare(ctx, plugininstall.Request{ArchivePath: archive, Root: service.Root, Source: plugintrust.Disk})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = service.Installer.Discard(plan) })
+ installed, err := service.Installer.Commit(plan)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := service.Manager.SetEnabled(plan.ID, true); err != nil {
+ t.Fatal(err)
+ }
+ mavenPlan, err := service.Installer.Prepare(ctx, plugininstall.Request{ArchivePath: mavenArchive, Root: service.Root, Source: plugintrust.Disk})
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(func() { _ = service.Installer.Discard(mavenPlan) })
+ mavenInstalled, err := service.Installer.Commit(mavenPlan)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := service.Manager.SetEnabled(mavenPlan.ID, true); err != nil {
+ t.Fatal(err)
+ }
+ mavenBefore := packageDigest(t, mavenInstalled.Path)
+ before := packageDigest(t, installed.Path)
+ closeAndVerify := func() {
+ h.app.closeProject()
+ awaitStateWithin(t, h, 30*time.Second, "closed project", func() bool { return h.app.project == nil })
+ h.settle()
+ assertPackageUnchanged(t, installed.Path, before)
+ assertPackageUnchanged(t, mavenInstalled.Path, mavenBefore)
+ }
+ logger := &treeRecordingLog{}
+ h.app.logSink = logger
+ t.Cleanup(func() {
+ if t.Failed() {
+ logger.mu.Lock()
+ defer logger.mu.Unlock()
+ for _, event := range logger.events {
+ t.Logf("host event: %s %v", event.Event, event.Fields)
+ }
+ }
+ })
+ h.app.reloadPluginLanguages()
+ root, err := filepath.EvalSymlinks(t.TempDir())
+ if err != nil {
+ t.Fatal(err)
+ }
+ content := fixture.files[fixture.mainPath]
+ if fixture.projectRoot != "" {
+ copyHistoricalJavaProject(t, fixture.projectRoot, root)
+ }
+ writeFixture(t, root, fixture.files)
+ gitRun(t, root, "init")
+ h.open(root)
+ p := h.app.project
+ if !fixture.noMaven {
+ h.app.loadBuildSystems(p)
+ awaitBuildModel(t, h, p, "maven", 90*time.Second)
+ output := runBuildTaskToEnd(t, h, p, "", "compile", 90*time.Second)
+ if !strings.Contains(output, "BUILD SUCCESS") {
+ t.Fatalf("Maven compile: %s", output)
+ }
+ t.Log("Maven compile succeeded")
+ if fixture.testGoal {
+ output := runBuildTaskToEnd(t, h, p, "", "test", 90*time.Second)
+ if !strings.Contains(output, "BUILD SUCCESS") || !strings.Contains(output, "Tests run: 1") {
+ t.Fatalf("legacy Maven test goal: %s", output)
+ }
+ t.Log("legacy test framework: Maven test goal passed one test")
+ }
+ if fixture.classVersion != 0 {
+ compiled, err := os.ReadFile(filepath.Join(root, fixture.classPath))
+ if err != nil || len(compiled) < 8 || compiled[7] != fixture.classVersion {
+ t.Fatalf("Maven class target: header=%x err=%v, expected major %d", compiled[:min(len(compiled), 8)], err, fixture.classVersion)
+ }
+ }
+ }
+ h.app.openFile(p, filepath.Join(root, fixture.mainPath))
+ awaitStateWithin(t, h, 30*time.Second, "Java document", func() bool { return documentNamed(p, "Main.java") != nil })
+ d := documentNamed(p, "Main.java")
+ defer func() {
+ if t.Failed() {
+ t.Logf("document language=%s actions=%d ", d.languageID, len(d.actions))
+ t.Logf("notice=%s debug state=%s failure=%s", h.app.notice, p.debug.state, p.debug.failure)
+ t.Logf("JDT problems: %v", problemMessages(h.app))
+ for _, run := range p.build.runs {
+ t.Logf("run: running=%v summary=%s output=%s", run.running, run.summary, strings.Join(run.output, ""))
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ events, err := core.NewClient().DrainCoreEvents(ctx)
+ t.Logf("Core diagnostics: %+v err=%v", events, err)
+ if backend := h.app.plugins.Host.Running(plan.ID); backend != nil {
+ t.Logf("backend grants: %v", backend.Session.Granted)
+ }
+ for id, server := range h.app.pluginServers {
+ t.Logf("server %s ready=%v", id, server.isReady())
+ }
+ }
+ }()
+ awaitStateWithin(t, h, 120*time.Second, "JDT ready", func() bool {
+ server, _ := h.app.documentSyncServer(d)
+ return server != nil && server.isReady()
+ })
+ awaitStateWithin(t, h, 15*time.Second, "JDT editor actions", func() bool {
+ if len(d.actions) > 0 {
+ return true
+ }
+ return false
+ })
+ t.Logf("Run/Debug action ready: %s", d.actions[0].Title)
+ if server, _ := h.app.documentSyncServer(d); server != nil {
+ sampleContext, cancelSample := context.WithTimeout(context.Background(), 5*time.Second)
+ sample, ok := pluginservice.SampleProcessTree(sampleContext, server.session.Session.ProcessID)
+ cancelSample()
+ if ok {
+ t.Logf("JDT process tree RSS after import: %.1f MiB", float64(sample.MemoryBytes)/(1024*1024))
+ }
+ }
+ if !d.view.GoToNavigation(5, 13, false) {
+ t.Fatal("completion caret")
+ }
+ h.app.startPluginCompletion(p, d, 5, 13)
+ awaitStateWithin(t, h, 30*time.Second, "JDT completion", func() bool { return len(h.app.semantics.completion.items) > 0 })
+ found := false
+ for _, item := range h.app.semantics.completion.items {
+ if strings.Contains(item.Label, "println") {
+ found = true
+ }
+ }
+ if !found {
+ t.Fatalf("no println completion: %+v", h.app.semantics.completion.items)
+ }
+ t.Logf("JDT completion: %d candidates including println", len(h.app.semantics.completion.items))
+ h.app.closeSemanticCompletion()
+ noticeBeforeRun := h.app.notice
+ h.app.runEditorAction(p, d, d.actions[0], -1)
+ if fixture.expectBuildRefused {
+ // This is an explicit compatibility-boundary test, not a passing full
+ // workflow: the current bundled ECJ rejects source levels below Java 8.
+ awaitStateWithin(t, h, 30*time.Second, "legacy build refusal", func() bool { return h.app.notice != noticeBeforeRun })
+ if len(p.build.runs) != 0 {
+ t.Fatal("unsupported build launched a process")
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ events, err := core.NewClient().DrainCoreEvents(ctx)
+ cancel()
+ if err != nil {
+ t.Fatal(err)
+ }
+ failures := 0
+ for _, event := range events.Events {
+ if event.Channel == "plugins/"+plan.ID+"/host" && event.Fields["operation"] == "java.runAction" {
+ if event.Event != "plugins.operation.failed" || event.Fields["code"] != "run.build_failed" || event.Level != core.LevelError {
+ t.Fatalf("unexpected legacy build result: %+v", event)
+ }
+ failures++
+ }
+ }
+ if failures != 1 {
+ t.Fatalf("legacy build refusal count: %d", failures)
+ }
+ t.Log("COMPATIBILITY BOUNDARY: Maven compile and completion work; Run/Debug remain unsupported at this source level")
+ closeAndVerify()
+ return
+ }
+ awaitStateWithin(t, h, 90*time.Second, "Java run", func() bool {
+ if h.app.notice != noticeBeforeRun {
+ t.Fatalf("Java run refused: %s", h.app.notice)
+ }
+ for _, r := range p.build.runs {
+ if !r.running && strings.Contains(strings.Join(r.output, ""), "java-result=42") {
+ if fixture.vmVersion != "" && !strings.Contains(strings.Join(r.output, ""), "vm="+fixture.vmVersion) {
+ t.Fatalf("wrong project JVM: %s", strings.Join(r.output, ""))
+ }
+ return true
+ }
+ }
+ return false
+ })
+ if _, err := os.Stat(filepath.Join(root, fixture.classPath)); err != nil {
+ t.Fatalf("compiled class: %v", err)
+ }
+ t.Log("compiled Main.class and ran java-result=42")
+ if !d.view.GoToNavigation(4, 2, false) {
+ t.Fatal("breakpoint caret")
+ }
+ h.app.toggleBreakpoint(p)
+ logger.mu.Lock()
+ logger.events = nil
+ logger.mu.Unlock()
+ t.Log("starting Java breakpoint session")
+ h.app.runEditorAction(p, d, d.actions[0], 0)
+ awaitStateWithin(t, h, 90*time.Second, "Java breakpoint", func() bool {
+ if len(p.build.runs) > 1 {
+ r := p.build.runs[len(p.build.runs)-1]
+ if !r.running {
+ t.Fatalf("debug run exited: %s %s", r.summary, strings.Join(r.output, ""))
+ }
+ }
+
+ logger.mu.Lock()
+ for _, event := range logger.events {
+ if event.Event == operationFailedEvent {
+ logger.mu.Unlock()
+ t.Fatalf("host operation failed: %v", event.Fields)
+ }
+ }
+ logger.mu.Unlock()
+ if p.debug.failure != "" {
+ t.Fatalf("debug: %s", p.debug.failure)
+ }
+ return p.debug.state == "paused" && len(p.debug.frames) > 0
+ })
+ if frame := p.debug.frames[0]; !strings.Contains(frame.Name, "Main.main") || frame.Line != 5 {
+ t.Fatalf("wrong breakpoint: %+v", frame)
+ }
+ t.Logf("Java paused in %s at line %d", p.debug.frames[0].Name, p.debug.frames[0].Line)
+ awaitStateWithin(t, h, 15*time.Second, "Java local variable", func() bool {
+ for _, scope := range p.debug.vars.scopes {
+ if scope.container != nil {
+ if node := findDebugVariable(scope.container.nodes, "answer"); node != nil {
+ return node.value == "41"
+ }
+ }
+ }
+ return false
+ })
+ t.Log("Java local variable answer=41")
+ if fixture.cleanupWhilePaused {
+ // Return without the success-path closeAndVerify, just as an assertion
+ // failure would. t.Cleanup must stop the paused JVM and destroy Core state.
+ if p.debug.activeSession() == nil || len(service.Runs.Active()) == 0 {
+ t.Fatal("cleanup probe has no active debug session and owned run")
+ }
+ t.Log("leaving the paused workflow to its unconditional fixture cleanup")
+ return
+ }
+ h.app.executeDebug(p, "continue")
+ awaitStateWithin(t, h, 30*time.Second, "debuggee exit", func() bool { return p.debug.activeSession() == nil })
+ awaitStateWithin(t, h, 15*time.Second, "run exit notifications", func() bool {
+ for _, r := range p.build.runs {
+ if r.running {
+ return false
+ }
+ }
+ return true
+ })
+ t.Log("Java run and debug session exited")
+
+ // Stop a second live debuggee through the same control as the toolbar.
+ h.app.runEditorAction(p, d, d.actions[0], 0)
+ awaitStateWithin(t, h, 90*time.Second, "second Java breakpoint", func() bool {
+ return p.debug.activeSession() != nil && p.debug.state == "paused"
+ })
+ h.app.stopDebugByUser(p)
+ awaitStateWithin(t, h, 30*time.Second, "cancelled Java debuggee", func() bool {
+ if p.debug.activeSession() != nil {
+ return false
+ }
+ for _, r := range p.build.runs {
+ if r.running {
+ return false
+ }
+ }
+ return true
+ })
+ t.Log("Java debug cancellation stopped the run")
+
+ // A failed compilation must never execute the successful build's old class.
+ d.view.SelectAll()
+ input := d.view.TextInput(app.TextInputContext{ID: d.hit})
+ if _, err := input.OnEvent(app.TextEvent{Kind: app.TextInsert, Text: strings.Replace(content, "int answer = 41;", "int answer = missing;", 1)}); err != nil {
+ t.Fatal(err)
+ }
+ h.app.saveDocument(p, d.id)
+ awaitStateWithin(t, h, 30*time.Second, "invalid Java saved and recollected", func() bool {
+ return !d.dirty() && len(d.actions) > 0 && d.actions[0].Version() == d.view.Revision()
+ })
+ runsBeforeFailure := len(p.build.runs)
+ noticeBeforeFailure := h.app.notice
+ h.app.runEditorAction(p, d, d.actions[0], -1)
+ awaitStateWithin(t, h, 90*time.Second, "Java compile failure", func() bool { return h.app.notice != noticeBeforeFailure })
+ if len(p.build.runs) != runsBeforeFailure {
+ t.Fatal("compiler errors launched stale bytecode")
+ }
+
+ // Inspect the real Core facts before a log-store writer consumes them. Collection
+ // is high frequency and must not add success INFO; user runs own one terminal fact.
+ logCtx, cancelLogs := context.WithTimeout(context.Background(), 5*time.Second)
+ events, err := core.NewClient().DrainCoreEvents(logCtx)
+ cancelLogs()
+ if err != nil {
+ t.Fatal(err)
+ }
+ successes, failures := 0, 0
+ for _, event := range events.Events {
+ if event.Channel != "plugins/"+plan.ID+"/host" {
+ continue
+ }
+ operation, _ := event.Fields["operation"].(string)
+ if event.Event == "plugins.operation.finished" && operation == "java.collectActions" {
+ t.Fatal("high-frequency collection emitted success INFO")
+ }
+ if operation != "java.runAction" {
+ continue
+ }
+ if event.Op == "" {
+ t.Fatal("run diagnostic lost its operation identity")
+ }
+ switch event.Event {
+ case "plugins.operation.finished":
+ if event.Level != core.LevelInfo {
+ t.Fatalf("run success level: %s", event.Level)
+ }
+ successes++
+ case "plugins.operation.failed":
+ if event.Level != core.LevelError || event.Fields["code"] != "run.build_failed" {
+ t.Fatalf("compile failure diagnostic: %+v", event)
+ }
+ failures++
+ }
+ }
+ if successes != 3 || failures != 1 {
+ t.Fatalf("run terminal diagnostics: successes=%d failures=%d; events=%+v", successes, failures, events)
+ }
+ t.Log("compiler errors blocked stale class; Core logging success/failure and collection suppression verified")
+ closeAndVerify()
+}
+
+func TestJavaPluginCurrentManifestContract(t *testing.T) {
+ path := os.Getenv("LITHE_TEST_JAVA_PLUGIN_MANIFEST")
+ if path == "" {
+ t.Skip("set LITHE_TEST_JAVA_PLUGIN_MANIFEST")
+ }
+ manifest, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+ if _, err := core.NewClient().ValidatePluginManifest(ctx, manifest, pluginhost.Declared()); err != nil {
+ t.Fatal(err)
+ }
+}
diff --git a/desktop/internal/workbench/pluginbackends.go b/desktop/internal/workbench/pluginbackends.go
index 90e14bdc02..5d8f77defe 100644
--- a/desktop/internal/workbench/pluginbackends.go
+++ b/desktop/internal/workbench/pluginbackends.go
@@ -249,6 +249,11 @@ func (a *App) servePluginServer(server *pluginServer, ctx context.Context) {
a.post(func(a *App) {
if a.isCurrentPluginServer(server.session.PluginID, server) {
a.resumeDeferredSemantics()
+ if p := a.project; p != nil && p == server.project {
+ for _, d := range p.docs.list {
+ a.scheduleEditorActions(p, d)
+ }
+ }
}
})
}
diff --git a/desktop/internal/workbench/pluginworkbench.go b/desktop/internal/workbench/pluginworkbench.go
index ee9ee57e0c..e1bcf84941 100644
--- a/desktop/internal/workbench/pluginworkbench.go
+++ b/desktop/internal/workbench/pluginworkbench.go
@@ -23,6 +23,20 @@ type pluginWorkbench struct{ app *App }
var _ pluginservice.Workbench = pluginWorkbench{}
+// EditorActionsChanged recollects annotations when a plugin registers or withdraws actions,
+// including registrations made after a language server finishes importing a project.
+func (w pluginWorkbench) EditorActionsChanged(root string) {
+ w.app.post(func(a *App) {
+ p, err := a.projectAt(root)
+ if err != nil {
+ return // The window moved on; the old context has no visible documents.
+ }
+ for _, d := range p.docs.list {
+ a.scheduleEditorActions(p, d)
+ }
+ })
+}
+
// onWindow runs fn on the window thread and waits for its result.
func onWindow[T any](a *App, ctx context.Context, fn func(*App) (T, error)) (T, error) {
type outcome struct {
diff --git a/shared/platform-feature-matrix/features/plugin-backend-run-start.json b/shared/platform-feature-matrix/features/plugin-backend-run-start.json
index 6724ff7aef..4477b58c8f 100644
--- a/shared/platform-feature-matrix/features/plugin-backend-run-start.json
+++ b/shared/platform-feature-matrix/features/plugin-backend-run-start.json
@@ -15,7 +15,10 @@
"desktop/internal/workbench/build_view.go",
".agents/notes/implemented/architecture/2026-11-10-viva-java-admission-run-debug-output-links.md",
"desktop/internal/workbench/debug_start.go",
- "desktop/internal/workbench/debug_test.go"
+ "desktop/internal/workbench/debug_test.go",
+ "desktop/internal/workbench/java_plugin_e2e_test.go",
+ "desktop/internal/workbench/debug.go",
+ "desktop/internal/workbench/java_legacy_e2e_test.go"
]
},
"windows": {
@@ -28,12 +31,17 @@
"desktop/internal/core/run_start_test.go",
"desktop/internal/workbench/runs.go",
"desktop/internal/workbench/build_view.go",
- ".agents/notes/implemented/architecture/2026-11-10-viva-java-admission-run-debug-output-links.md"
+ ".agents/notes/implemented/architecture/2026-11-10-viva-java-admission-run-debug-output-links.md",
+ "desktop/internal/workbench/debug_start.go",
+ "desktop/internal/workbench/debug_test.go",
+ "desktop/internal/workbench/java_plugin_e2e_test.go",
+ "desktop/internal/workbench/debug.go",
+ "desktop/internal/workbench/java_legacy_e2e_test.go"
]
},
"owner": "Extensions / Run",
"verification": "macOS:用声明 requires.serverProcess 4 与 permissions run.start 的测试插件,让后端依次发起(1)工具 ID 运行:Run 窗口出现以 label 命名的条目,进程使用用户在设置里选中的安装,参数、工作目录和环境符合请求,插件显式给出的环境变量覆盖工具导出;(2)插件包内可执行文件运行,路径逃出包目录、文件不存在或不可执行时返回 plugin.host.notFound;(3)带 temporaryFiles 的运行,进程内能读到文件内容,结束后临时目录被删除;(4)带 debug.target connection 的运行,进程监听后调试器附加并命中断点,声明 target launch 时宿主不启动进程,由适配器按 targetBindings 启动程序并命中断点,Run 窗口停止该运行会结束调试会话,会话结束后运行条目以退出码结束;(5)带 rerun 的运行,在 Run 窗口点击再次运行会调用插件函数,函数失败时用户看到提示;(6)run/stop 只停止调用方插件的运行,用户点击停止后后端收到不带 exitCode 的 lithe/host/run/didExit,进程自然退出时收到 exitCode。工具未安装时返回 plugin.host.toolUnresolved,details.reason 为 notFound,所选安装不可运行时为 unusable,两种情况都不启动进程。禁用插件或后端退出后,已启动的进程继续运行,后端不再收到通知。远程工作区返回 plugin.host.authorityUnsupported。启动后 app bundle 文件清单不变(scripts/desktop/verify/verify-runtime-bundle-immutability.sh)。Windows:宿主尚未接入 run/start,Core 校验通过不代表 Windows 能运行插件请求的进程。",
- "notes": "Viva 注册 run/start、run/stop 并在进程结束时发送 run/didExit(只发给发起它的那次后端会话);Core 的 run.decodeStart 校验参数,宿主解析工具或包内可执行文件、写入临时文件、启动进程并把输出放进 Build 面板里的运行视图,支持停止与再次运行。debug.target 为 connection 时等待端口打开再附加适配器;target 为 launch 时宿主不启动进程,而是按 configurationType 找到本插件能 launch 的适配器,把解析好的程序、参数、绝对工作目录与环境作为 executable 目标事实交给 Core,经适配器的 launch targetBindings 绑定后启动调试会话;运行条目代表该会话,停止运行即停止会话,会话释放后运行以 terminated 事件的退出码结束(适配器未报时不带 exitCode),进程输出在调试控制台。没有调试能力的宿主仍返回 plugin.host.unavailable。debug/start 已实现(见 plugin-debug-start-and-adapter-features)。原生产品验收仍 pending。",
+ "notes": "Viva 注册 run/start、run/stop 并在进程结束时发送 run/didExit(只发给发起它的那次后端会话);Core 的 run.decodeStart 校验参数,宿主解析工具或包内可执行文件、写入临时文件、启动进程并把输出放进 Build 面板里的运行视图,支持停止与再次运行。debug.target 为 connection 时等待端口打开再附加适配器;target 为 launch 时宿主不启动进程,而是按 configurationType 找到本插件能 launch 的适配器,把解析好的程序、参数、绝对工作目录与环境作为 executable 目标事实交给 Core,经适配器的 launch targetBindings 绑定后启动调试会话;运行条目代表该会话,停止运行即停止会话,会话释放后运行以 terminated 事件的退出码结束(适配器未报时不带 exitCode),进程输出在调试控制台。没有调试能力的宿主仍返回 plugin.host.unavailable。debug/start 已实现(见 plugin-debug-start-and-adapter-features)。原生产品验收仍 pending。 2026-11-13:插件 run/start 的调试附加与启动会按需读取适配器目录,不要求用户先打开 Debug 工具窗口;目录返回后检查调用取消,关闭项目不会启动旧请求。 Run 持有的进程在附加调试会话释放后由后台有界回收,Debug 工具栏停止不再留下暂停的 Run 进程;手动附加的外部进程保持原有所有权。 无头旧项目验证区分实际 JDK 与源码级别:Java 8+ 工作流与 Java 5/7 的 ECJ 构建拒绝分别记录,安全拒绝测试不代表旧源码级别可运行;正常关闭的既有重试日志债务见 #1860。",
"legacy": {
"revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36",
"macos": {
diff --git a/shared/platform-feature-matrix/features/plugin-editor-actions.json b/shared/platform-feature-matrix/features/plugin-editor-actions.json
index bd86e86748..29ff81ff1c 100644
--- a/shared/platform-feature-matrix/features/plugin-editor-actions.json
+++ b/shared/platform-feature-matrix/features/plugin-editor-actions.json
@@ -12,7 +12,12 @@
"desktop/internal/pluginservice/hostcodelens.go",
"desktop/internal/workbench/editor_actions.go",
"desktop/internal/core/editor_actions.go",
- "desktop/internal/core/workbench_test.go"
+ "desktop/internal/core/workbench_test.go",
+ "desktop/internal/pluginservice/hostactions_refresh_test.go",
+ "desktop/internal/workbench/pluginworkbench.go",
+ "desktop/internal/workbench/java_plugin_e2e_test.go",
+ "desktop/internal/workbench/java_legacy_e2e_test.go",
+ "desktop/internal/workbench/editoractions_test.go"
]
},
"windows": {
@@ -24,12 +29,17 @@
"desktop/internal/pluginservice/hostcodelens.go",
"desktop/internal/workbench/editor_actions.go",
"desktop/internal/core/editor_actions.go",
- "desktop/internal/core/workbench_test.go"
+ "desktop/internal/core/workbench_test.go",
+ "desktop/internal/pluginservice/hostactions_refresh_test.go",
+ "desktop/internal/workbench/pluginworkbench.go",
+ "desktop/internal/workbench/java_plugin_e2e_test.go",
+ "desktop/internal/workbench/java_legacy_e2e_test.go",
+ "desktop/internal/workbench/editoractions_test.go"
]
},
"owner": "Extensions",
"verification": "用 HTTP 与 SQL 两种解析函数注册动作;验证当前脏文档版本、同一行多动作、明确点击执行、编辑取消旧解析、撤回/关闭/会话替换清理,不自动重试副作用。慢收集保持未完成时刷新立即确认,仍能输入并完成保存屏障;整批只使用八秒预算。版本 2:同一行运行车道与导航车道各自排列且折叠箭头随之让位;备选项各自调用自己的函数;点击后返回的 reveal 位置由宿主展示,插件自己的返回成员不被解释;宿主图标表之外的图标名被 Core 拒绝,且与网页图标键一致。",
- "notes": "Viva:工具插件经 editor/registerActions 为所选文件注册动作,停止输入后宿主调用收集函数取得当前文档的动作,文本一变即丢弃;动作显示为行首图标(运行、调试、测试、导航各一条通道,同一行多图标并排、点击打开该通道的菜单或直接运行唯一选项)并进入该行的编辑器菜单,点击再次调用插件;CodeLens 作为无图标的动作显示。消息全部由 Core 校验(editor_actions.go)。",
+ "notes": "Viva:工具插件经 editor/registerActions 为所选文件注册动作,停止输入后宿主调用收集函数取得当前文档的动作,文本一变即丢弃;动作显示为行首图标(运行、调试、测试、导航各一条通道,同一行多图标并排、点击打开该通道的菜单或直接运行唯一选项)并进入该行的编辑器菜单,点击再次调用插件;CodeLens 作为无图标的动作显示。消息全部由 Core 校验(editor_actions.go)。 2026-11-13:宿主先检查工作区 context,再只把动作声明交给 Core;注册与撤回动作会通知窗口重新收集已打开文档,语言服务器 ready 后也会刷新动作。回归使用真实 Core 解码,避免测试替身漏掉 context 被当作未知字段的问题。 同一文本版本的模型刷新使用文档本地呈现代际隔离旧收集结果;旧空结果或错误不能覆盖后到的当前动作。",
"legacy": {
"revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36",
"macos": {
diff --git a/shared/platform-feature-matrix/features/plugin-editor-providers.json b/shared/platform-feature-matrix/features/plugin-editor-providers.json
index 785fadf0a5..9e2c9a6f34 100644
--- a/shared/platform-feature-matrix/features/plugin-editor-providers.json
+++ b/shared/platform-feature-matrix/features/plugin-editor-providers.json
@@ -15,7 +15,8 @@
"desktop/internal/pluginservice/hostdocumentlinks.go",
"desktop/internal/pluginservice/hostproviders_routes_test.go",
"desktop/internal/workbench/editor_actions.go",
- "desktop/internal/core/editor_providers_test.go"
+ "desktop/internal/core/editor_providers_test.go",
+ "desktop/internal/workbench/java_legacy_e2e_test.go"
]
},
"windows": {
@@ -30,12 +31,13 @@
"desktop/internal/pluginservice/hostdocumentlinks.go",
"desktop/internal/pluginservice/hostproviders_routes_test.go",
"desktop/internal/workbench/editor_actions.go",
- "desktop/internal/core/editor_providers_test.go"
+ "desktop/internal/core/editor_providers_test.go",
+ "desktop/internal/workbench/java_legacy_e2e_test.go"
]
},
"owner": "Extensions",
"verification": "用一个资源 key 在模板与 .properties 之间跳转的第二工具插件注册 definition、hover、completion、codeLens、semanticTokens;验证语言服务器的答案先出现、插件的位置只追加、重复位置只显示一次、服务器只指回自身时让位;悬浮和补全超过期限、文档已变化、注册被撤回时安静丢弃;触发字符只问声明过它的注册;点击 CodeLens 与文档链接只回传宿主生成的键,command: 链接不会被执行,工作区外的 file: 目标不会打开;只读预览不询问插件;停用、卸载、关闭项目后旧结果不再出现。",
- "notes": "Viva:普通插件经 editor/registerProviders 按语言、扩展名、文件名注册跳转、悬浮、补全(含触发字符)、CodeLens、语义着色与文档链接,绑定到同插件已注册的函数;注册与答案都由 Core 校验和归一化,只在没有语言服务器服务该文档时调用插件。CodeLens 在编辑器行上显示为可点击的动作。折叠(foldingRange)未路由,Core 会拒绝该类型的注册。",
+ "notes": "Viva:普通插件经 editor/registerProviders 按语言、扩展名、文件名注册跳转、悬浮、补全(含触发字符)、CodeLens、语义着色与文档链接,绑定到同插件已注册的函数;注册与答案都由 Core 校验和归一化,只在没有语言服务器服务该文档时调用插件。CodeLens 在编辑器行上显示为可点击的动作。折叠(foldingRange)未路由,Core 会拒绝该类型的注册。 2026-11-13:编辑器 Provider 注册在宿主确认工作区后,剥离路由用的 context 再交给 Core 校验声明;真实 Core 回归覆盖多个 Provider 的绑定。",
"legacy": {
"revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36",
"macos": {