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 @@ -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 的会话归属里,改动更小。
Expand All @@ -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 验证清单仅缺上述其他车道的能力。

Expand Down
Original file line number Diff line number Diff line change
@@ -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)。
29 changes: 27 additions & 2 deletions desktop/internal/pluginservice/hostactions.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}
Expand Down Expand Up @@ -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 {
Expand Down
76 changes: 76 additions & 0 deletions desktop/internal/pluginservice/hostactions_refresh_test.go
Original file line number Diff line number Diff line change
@@ -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: &notifyKernel{}}
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)
}
6 changes: 5 additions & 1 deletion desktop/internal/pluginservice/hostproviders.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}
Expand Down
4 changes: 3 additions & 1 deletion desktop/internal/pluginservice/hostproviders_routes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
24 changes: 16 additions & 8 deletions desktop/internal/pluginservice/runs.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand All @@ -265,7 +272,7 @@ func (r *Runs) StopWorkspace(path string) {
}
r.mu.Unlock()
for _, run := range stopping {
r.stopRun(run)
r.stopRun(run, false)
}
}

Expand All @@ -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()
}
Expand Down Expand Up @@ -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 {
Expand All @@ -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)
Expand Down Expand Up @@ -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)
}
Expand Down
Loading
Loading