diff --git a/.agents/notes/implemented/bug-fix/2026-10-14-child-processes-end-with-the-ide.md b/.agents/notes/implemented/bug-fix/2026-10-14-child-processes-end-with-the-ide.md index 21e16bae0b..8094d9c844 100644 --- a/.agents/notes/implemented/bug-fix/2026-10-14-child-processes-end-with-the-ide.md +++ b/.agents/notes/implemented/bug-fix/2026-10-14-child-processes-end-with-the-ide.md @@ -4,7 +4,7 @@ ## 先说结论 -Lithe 启动的运行、服务、预启动任务、测试、构建和插件进程,生命周期都绑定在 Lithe 上:关闭项目或退出时,由 Core 的进程生命周期规则决定哪些进程需要询问,再由所属模块停止自己的会话。Windows 上构建进程放进 Job Object,Lithe 崩溃时内核也会连带结束整组进程。忙碌终端和运行服务在关闭前统一询问,用户可以选择停止或取消。 +Lithe 启动的运行、服务、预启动任务、测试、构建和插件进程,生命周期都绑定在 Lithe 上:关闭项目或退出时,由 Core 的进程生命周期规则决定哪些进程需要询问,再由所属模块停止自己的会话。Windows 上构建进程放进 Job Object,Lithe 崩溃时内核也会连带结束整组进程。进程账本在 macOS 和 Windows 上都登记,崩溃后的残留在下一次启动时清扫;Windows 的账本只通过进程句柄调用系统接口,不启动任何外部程序。忙碌终端和运行服务在关闭前统一询问,用户可以选择停止或取消。 ## 问题 @@ -34,6 +34,15 @@ Viva 客户端(`desktop/internal/workbench/process_exit.go`)把关闭时要 - **探测不在窗口线程上跑。** 窗口线程只取出每个终端的探测函数(`termview.View.BusyProbe`),真正的系统调用(Windows 上是一次进程快照)在后台任务里执行,避免关闭时界面卡住。 - **不要这样做:** 不要在工作台里自己判断“忙碌终端要不要问”,也不要把 `confirm` 当成可以忽略的动作;这两件事由 Core 的规则和用户设置决定。也不要把 shell 有输出当作忙碌的依据:提示符本身也是输出。 +### Windows:账本不启动外部程序 + +2026-11-25 修复:Windows 上每次构建、运行、测试、调试时都会闪出一个立刻关闭的控制台窗口。 + +- **原因。** 账本核对进程身份时运行 `ps -o lstart= -o comm= -p `,结束进程时运行 `kill`,不分平台。Lithe 是没有控制台的图形程序,它不加隐藏标志启动的控制台程序会自己开一个控制台窗口。Windows 本来没有 `ps`,但 Git for Windows 的 `usr\bin`、MSYS2、Cygwin 等工具链会把它们的 `ps.exe` 放进 PATH;这些 `ps` 不认识 `-o`,打开窗口后马上报错退出,看起来就是一闪而过。找不到 `ps` 或 `ps` 报错时身份读不出来,所以账本在 Windows 上实际从来没有登记成功过。 +- **做法。** 平台差异放在 `processledger_unix.go` 和 `processledger_windows.go`,账本的记录、核对和清扫逻辑仍只有 `processledger.go` 一份。Windows 用 `OpenProcess`(`PROCESS_QUERY_LIMITED_INFORMATION`)打开进程,`GetProcessTimes` 的创建时间(100 纳秒精度的十进制数)作为启动时间,`QueryFullProcessImageName` 的完整路径作为命令名;已退出但仍有句柄未关闭的进程也能打开,所以先用 `WaitForSingleObject(handle, 0)` 确认它还在运行。结束用 `TerminateProcess`:Windows 没有可以发给任意进程的停止请求(与 `buildprocess.StopsGracefully` 为 false 一致),所以请求停止和强制结束都直接结束进程,不等宽限期。 +- **覆盖面。** 经 `buildprocess` 启动的构建、运行、测试、调试、项目生成和工具安装进程,插件发起的运行(`pluginservice/runs.go`)和终端 shell(`localshell/backend_windows.go`)都在 Windows 上登记。构建类进程本来就在 kill-on-close 的 Job Object 里,账本是第二道保险;ConPTY 终端不在 Job Object 里,崩溃后的残留只能靠账本在下次启动时清扫。 +- **不要这样做:** 不要在客户端里启动 `ps`、`kill`、`tasklist`、`taskkill` 之类的控制台程序来查询或结束进程:Windows 上它们会弹出控制台窗口,PATH 上同名的程序也不一定是你以为的那个(`ps`、`kill` 在 Windows 上来自第三方工具链,参数和输出格式都不一样)。也不要为了不闪窗口而在 Windows 上关掉账本:账本是崩溃后清扫残留的唯一依据。 + ### 反例 - 只在所有者的停止函数里发信号就返回:所有者漏掉一类会话,或者进程在异步升级前退出,子进程都会变成孤儿。 @@ -54,9 +63,9 @@ Viva 客户端(`desktop/internal/workbench/process_exit.go`)把关闭时要 未覆盖的情况: -- **Lithe 崩溃或被强制结束(macOS)。** 进程内兜底不会执行,崩溃后的残留由进程账本在下一次启动时清理(`startupSweep` 场景)。 +- **Lithe 崩溃或被强制结束。** 进程内兜底不会执行,崩溃后的残留由进程账本在下一次启动时清理(`startupSweep` 场景),macOS 和 Windows 相同;两个平台都还没有监护进程,崩溃当下不清理。 - **不经过宿主进程管理的进程。** 语言服务器由 Core 的语言工具会话停止,内置终端由终端自身管理。 -- **Windows 终端和 Agent。** ConPTY 终端里启动的程序还没有放进 Job Object,Lithe 崩溃时仍可能残留;正常退出由各自的关闭流程处理。 +- **Windows 终端里启动的程序。** ConPTY 终端的 shell 已登记在账本中,但它启动的程序既不在 Job Object 里,也不在账本里;Lithe 崩溃后 shell 自己会在下次启动时被清扫,已脱离 shell 的程序仍可能残留。正常退出由终端的关闭流程处理。 - **已知差异。** shell 被 `exec` 替换(如 `exec vim`)后进程号不变,会读作空闲;Windows 上 WSL 终端里的程序不是 Windows 进程,始终读作空闲。 ## 验证 @@ -65,6 +74,8 @@ Viva 客户端(`desktop/internal/workbench/process_exit.go`)把关闭时要 - `desktop/internal/workbench/process_exit_test.go` 用 Core 规则验证关闭忙碌标签页先问、取消保留、确认关闭,空闲终端直接关闭,以及关闭项目时只列出忙碌终端。 - `desktop/internal/core/plugin_session_test.go` 覆盖插件会话的启动与停止路径。 - `desktop/internal/processledger/processledger_unix_test.go` 覆盖账本的身份匹配与只结束自己记录的进程。 +- `desktop/internal/processledger/processledger_windows_test.go` 在 PATH 最前面放记录调用的 `ps.bat`、`kill.bat`,覆盖 Windows 上登记创建时间和路径、取消登记、启动清扫立即结束残留、保留时只删记录、创建时间不符(PID 被复用)时不结束、已退出但句柄未关的进程不算残留,并断言账本从未调用这两个程序。 +- `desktop/internal/localshell/shell_windows_test.go` 的 `TestConPTYShellIsRecordedWhileItRuns` 覆盖 ConPTY 终端的 shell 运行期间在账本中、退出后记录被删除。 - Core 的 `rust/fixtures/process-lifecycle/`([链接](https://github.com/Lithe-IDEA/Lithe-core-rust/tree/main/rust/fixtures/process-lifecycle/)):运行服务在退出、关闭项目、直接停止设置和崩溃恢复下的动作。 - 实际应用(2026-10-14,macOS):运行 Spring Boot 配置,Java 进程监听 8080 后从菜单退出 Lithe,1 秒内 Lithe、语言服务器和 Spring Boot 进程全部消失,端口释放。 @@ -74,6 +85,9 @@ Viva 客户端(`desktop/internal/workbench/process_exit.go`)把关闭时要 - `desktop/internal/core/plugin_session_test.go` - `desktop/internal/workbench/process_exit.go` - `desktop/internal/processledger/processledger.go` +- `desktop/internal/processledger/processledger_unix.go` +- `desktop/internal/processledger/processledger_windows.go` +- `desktop/internal/localshell/backend_windows.go` - `desktop/internal/buildprocess/process_windows.go` - `shared/platform-feature-matrix/features/run-processes-end-with-ide.json` - Core 仓库的进程生命周期规则与进程树(Job Object)实现,以 [Lithe-core-rust](https://github.com/Lithe-IDEA/Lithe-core-rust) 当前固定的修订为准。 diff --git a/.agents/notes/proposed/architecture/2026-10-16-unified-child-process-lifecycle.md b/.agents/notes/proposed/architecture/2026-10-16-unified-child-process-lifecycle.md index e230416718..a7af8da143 100644 --- a/.agents/notes/proposed/architecture/2026-10-16-unified-child-process-lifecycle.md +++ b/.agents/notes/proposed/architecture/2026-10-16-unified-child-process-lifecycle.md @@ -2,7 +2,7 @@ 状态:提议中 -> Viva 迁移状态:桌面端已有进程账本 `desktop/internal/processledger`,构建、调试、测试、项目生成、本地 shell 和插件服务等启动点登记其中,下次启动时清扫上次遗留的进程。退出时的逐项确认、进程分类、监护进程和 Windows 的 Job Object 仍未落地;Windows 目前无法读取进程启动时间与命令,账本在该平台不登记。下文提案按 Viva 重新核对,实施前以代码为准。 +> Viva 迁移状态:桌面端已有进程账本 `desktop/internal/processledger`,构建、调试、测试、项目生成、本地 shell 和插件服务等启动点登记其中,下次启动时清扫上次遗留的进程。退出时的逐项确认、进程分类和监护进程仍未落地,Windows 的 Job Object 只用于经 `buildprocess` 启动的构建、运行、测试、调试和插件工具进程(`desktop/internal/buildprocess/process_windows.go`),终端 shell 不在其中;Windows 上账本通过进程句柄读取创建时间和程序路径,不启动外部程序(原因见 [Lithe 退出时结束它启动的全部子进程](../../implemented/bug-fix/2026-10-14-child-processes-end-with-the-ide.md))。下文提案按 Viva 重新核对,实施前以代码为准。 ## 先说结论 diff --git a/desktop/internal/localshell/backend_windows.go b/desktop/internal/localshell/backend_windows.go index b9108fc232..bdff949c3f 100644 --- a/desktop/internal/localshell/backend_windows.go +++ b/desktop/internal/localshell/backend_windows.go @@ -12,6 +12,8 @@ import ( "unsafe" "golang.org/x/sys/windows" + + "github.com/1lck/Lithe-IDEA/desktop/internal/processledger" ) // setConsoleCtrlHandler is kernel32!SetConsoleCtrlHandler. x/sys does not wrap @@ -152,6 +154,8 @@ func startBackend(config Config) (backend, error) { } windows.CloseHandle(process.Thread) attributes.Delete() + // A terminal's shell is recorded until it ends, so a leftover can be offered for ending at start-up. + untrack := processledger.Track(processledger.KindTerminal, int(process.ProcessId)) output := os.NewFile(uintptr(outRead), "conpty-out") input := os.NewFile(uintptr(inWrite), "conpty-in") @@ -180,7 +184,9 @@ func startBackend(config Config) (backend, error) { }, wait: func() (int, error) { defer windows.CloseHandle(process.Process) - if event, err := windows.WaitForSingleObject(process.Process, windows.INFINITE); err != nil || event != windows.WAIT_OBJECT_0 { + event, err := windows.WaitForSingleObject(process.Process, windows.INFINITE) + untrack() + if err != nil || event != windows.WAIT_OBJECT_0 { return 0, errors.New("localshell: waiting for the shell failed") } // The console keeps its output pipe open after the program is gone; diff --git a/desktop/internal/localshell/shell_windows_test.go b/desktop/internal/localshell/shell_windows_test.go index 5bb321a252..10607e422b 100644 --- a/desktop/internal/localshell/shell_windows_test.go +++ b/desktop/internal/localshell/shell_windows_test.go @@ -3,14 +3,17 @@ package localshell import ( + "encoding/json" "fmt" "os" "os/exec" + "path/filepath" "strings" "syscall" "testing" "time" + "github.com/1lck/Lithe-IDEA/desktop/internal/processledger" "github.com/1lck/Lithe-IDEA/desktop/internal/term" "github.com/vivaui/viva/gfx" "golang.org/x/sys/windows" @@ -129,6 +132,35 @@ func TestConPTYExitEndsTheShellWithItsStatus(t *testing.T) { } } +// A terminal's shell is in the process ledger while it runs, so a shell an earlier run of the app +// left behind can be offered for ending at start-up; it leaves the ledger when it ends. +func TestConPTYShellIsRecordedWhileItRuns(t *testing.T) { + preferences := t.TempDir() + t.Cleanup(func() { processledger.Activate("") }) + ledger := processledger.Activate(preferences) + shell, _ := startWindows(t, Config{}) + records, err := ledger.Leftovers() + if err != nil || len(records) != 1 || records[0].Kind != processledger.KindTerminal || + !strings.EqualFold(filepath.Base(records[0].Command), "cmd.exe") { + t.Fatalf("leftovers = %+v, %v; want the shell as a terminal", records, err) + } + shell.Write([]byte("exit 0\r\n")) + select { + case <-shell.Done(): + case <-time.After(15 * time.Second): + t.Fatal("the shell did not end") + } + // An ended process is never a leftover, so the file itself shows that the record was removed. + data, err := os.ReadFile(filepath.Join(preferences, processledger.LedgerFile)) + if err != nil { + t.Fatal(err) + } + var recorded []processledger.Record + if err := json.Unmarshal(data, &recorded); err != nil || len(recorded) != 0 { + t.Fatalf("the ended shell is still recorded: %s, %v", data, err) + } +} + func TestConPTYCloseEndsARunningProgram(t *testing.T) { shell, wakes := startWindows(t, Config{}) shell.Write([]byte("ping -n 60 127.0.0.1\r\n")) diff --git a/desktop/internal/processledger/processledger.go b/desktop/internal/processledger/processledger.go index 570a63503e..1f80f73d92 100644 --- a/desktop/internal/processledger/processledger.go +++ b/desktop/internal/processledger/processledger.go @@ -13,12 +13,8 @@ import ( "encoding/json" "errors" "os" - "os/exec" "path/filepath" - "runtime" "slices" - "strconv" - "strings" "sync" "time" ) @@ -26,11 +22,6 @@ import ( // LedgerFile is the name of the ledger in the application's preferences directory. const LedgerFile = "process-ledger.json" -// Supported says this platform can tell a process's start time and command (identity), so -// the ledger records the processes the app starts. On Windows it cannot, and nothing is -// recorded or found at the next start. -const Supported = runtime.GOOS != "windows" - // Record is one process the app started. type Record struct { PID int `json:"pid"` @@ -40,8 +31,8 @@ type Record struct { Kind string `json:"kind,omitempty"` } -// Ledger is the file of records. A nil Ledger records nothing, so platforms without the -// identity check (Windows here) run without one. +// Ledger is the file of records. A nil Ledger, which Open returns without a directory, records +// nothing. type Ledger struct { path string mu sync.Mutex @@ -240,24 +231,6 @@ func (l *Ledger) write(records []Record) error { return os.Rename(temporary, l.path) } -// identity reads the start time and command name of a live process. ok is false when the process -// is gone or the platform cannot tell. -func identity(pid int) (started, command string, ok bool) { - output, err := exec.Command("ps", "-o", "lstart=", "-o", "comm=", "-p", strconv.Itoa(pid)).Output() - if err != nil { - return "", "", false - } - line := strings.TrimSpace(string(output)) - if line == "" { - return "", "", false - } - // lstart has a fixed width of 24 characters on the systems this runs on; the command follows it. - if len(line) < 25 { - return "", "", false - } - return strings.TrimSpace(line[:24]), strings.TrimSpace(line[24:]), true -} - // current reports that record's PID is still the process that was recorded. func current(record Record) bool { started, command, ok := identity(record.PID) @@ -310,7 +283,3 @@ func endProcesses(ctx context.Context, records []Record, grace time.Duration) (i } return ended, errors.Join(failures...) } - -func signal(pid int, name string) error { - return exec.Command("kill", "-"+name, strconv.Itoa(pid)).Run() -} diff --git a/desktop/internal/processledger/processledger_unix.go b/desktop/internal/processledger/processledger_unix.go new file mode 100644 index 0000000000..fd3dbe6c91 --- /dev/null +++ b/desktop/internal/processledger/processledger_unix.go @@ -0,0 +1,32 @@ +//go:build !windows + +package processledger + +import ( + "os/exec" + "strconv" + "strings" +) + +// identity reads the start time and command name of a live process. ok is false when the process +// is gone or the platform cannot tell. +func identity(pid int) (started, command string, ok bool) { + output, err := exec.Command("ps", "-o", "lstart=", "-o", "comm=", "-p", strconv.Itoa(pid)).Output() + if err != nil { + return "", "", false + } + line := strings.TrimSpace(string(output)) + if line == "" { + return "", "", false + } + // lstart has a fixed width of 24 characters on the systems this runs on; the command follows it. + if len(line) < 25 { + return "", "", false + } + return strings.TrimSpace(line[:24]), strings.TrimSpace(line[24:]), true +} + +// signal sends pid the signal called name: TERM asks it to stop, KILL ends it. +func signal(pid int, name string) error { + return exec.Command("kill", "-"+name, strconv.Itoa(pid)).Run() +} diff --git a/desktop/internal/processledger/processledger_windows.go b/desktop/internal/processledger/processledger_windows.go new file mode 100644 index 0000000000..e2b4025525 --- /dev/null +++ b/desktop/internal/processledger/processledger_windows.go @@ -0,0 +1,74 @@ +//go:build windows + +package processledger + +import ( + "fmt" + "math" + "strconv" + + "golang.org/x/sys/windows" +) + +// identity reads the creation time and executable path of a live process. ok is false when the +// process is gone or cannot be opened, as a process of another user or a higher integrity level +// cannot. It asks the system through the process's handle and starts no program: the client is a +// GUI program with no console, so a console program it started without hiding the console, such +// as the ps that Git for Windows or MSYS2 can put on PATH, would open a console window of its own, +// one that flashed up at every build, run, test, debug and terminal start. +func identity(pid int) (started, command string, ok bool) { + id, valid := processID(pid) + if !valid { + return "", "", false + } + handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.SYNCHRONIZE, false, id) + if err != nil { + return "", "", false + } + defer windows.CloseHandle(handle) + // A process that has exited can still be opened while any handle to it is held, and it keeps + // its creation time and path; it is not running all the same. + if event, err := windows.WaitForSingleObject(handle, 0); err != nil || event != uint32(windows.WAIT_TIMEOUT) { + return "", "", false + } + var creation, exit, kernel, user windows.Filetime + if err := windows.GetProcessTimes(handle, &creation, &exit, &kernel, &user); err != nil { + return "", "", false + } + path := make([]uint16, windows.MAX_LONG_PATH) + size := uint32(len(path)) + if err := windows.QueryFullProcessImageName(handle, 0, &path[0], &size); err != nil { + return "", "", false + } + // The creation time is kept exact, in 100-nanosecond intervals: a process that reuses the PID + // was created later. + created := uint64(creation.HighDateTime)<<32 | uint64(creation.LowDateTime) + return strconv.FormatUint(created, 10), windows.UTF16ToString(path[:size]), true +} + +// signal ends pid through its handle, for TERM as for KILL: there is no stop request to send it +// here (see buildprocess.StopsGracefully), so a leftover asked to stop ends at once. Like identity, +// it starts no program. +func signal(pid int, name string) error { + id, valid := processID(pid) + if !valid { + return fmt.Errorf("processledger: %s %d: not a process ID", name, pid) + } + handle, err := windows.OpenProcess(windows.PROCESS_TERMINATE, false, id) + if err != nil { + return fmt.Errorf("processledger: %s %d: %w", name, pid, err) + } + defer windows.CloseHandle(handle) + if err := windows.TerminateProcess(handle, 1); err != nil { + return fmt.Errorf("processledger: %s %d: %w", name, pid, err) + } + return nil +} + +// processID is pid as the system's process ID; a record read from the ledger can hold any number. +func processID(pid int) (uint32, bool) { + if pid <= 0 || uint64(pid) > math.MaxUint32 { + return 0, false + } + return uint32(pid), true +} diff --git a/desktop/internal/processledger/processledger_windows_test.go b/desktop/internal/processledger/processledger_windows_test.go new file mode 100644 index 0000000000..0990096d40 --- /dev/null +++ b/desktop/internal/processledger/processledger_windows_test.go @@ -0,0 +1,239 @@ +//go:build windows + +package processledger + +import ( + "bufio" + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "strconv" + "strings" + "testing" + "time" + + "golang.org/x/sys/windows" +) + +// helperMode names, in the environment, that the test binary runs as TestLedgerHelper. +const helperMode = "LITHE_TEST_PROCESS_LEDGER" + +// TestLedgerHelper is the leftover process the tests end. It prints a line once it runs and waits +// to be ended, for 30 seconds at most. +func TestLedgerHelper(t *testing.T) { + if os.Getenv(helperMode) == "" { + t.Skip("only runs as a leftover process") + } + os.Stdout.WriteString("ready\n") + time.Sleep(30 * time.Second) + os.Exit(2) +} + +// withRecordingProcessTools puts a ps and a kill that record their calls first on PATH, as Git for +// Windows or MSYS2 can put theirs. The client is a GUI program with no console, so each console +// program the ledger ran would open a console window of its own at every start it records; the +// test fails if anything called them. +func withRecordingProcessTools(t *testing.T) { + t.Helper() + tools := t.TempDir() + calls := filepath.Join(tools, "calls.txt") + for _, name := range []string{"ps", "kill"} { + script := "@echo off\r\necho " + name + " %*>>\"%~dp0calls.txt\"\r\n" + if err := os.WriteFile(filepath.Join(tools, name+".bat"), []byte(script), 0o600); err != nil { + t.Fatal(err) + } + } + t.Setenv("PATH", tools+string(os.PathListSeparator)+os.Getenv("PATH")) + if found, err := exec.LookPath("ps"); err != nil || !strings.EqualFold(filepath.Dir(found), tools) { + t.Fatalf("the recording ps is not the one on PATH: %q, %v", found, err) + } + t.Cleanup(func() { + if data, err := os.ReadFile(calls); !errors.Is(err, os.ErrNotExist) { + t.Errorf("the ledger ran process tools: %q, %v", data, err) + } + }) +} + +// leftover is a running helper process recorded in a ledger of its own. +type leftover struct { + ledger *Ledger + cmd *exec.Cmd + // done closes once the process has exited and Wait returned. + done chan struct{} +} + +// startLeftover starts the helper, waits until it runs and records it. The process is killed when +// the test ends, whatever the test did with it. +func startLeftover(t *testing.T) *leftover { + t.Helper() + cmd := exec.Command(os.Args[0], "-test.run=^TestLedgerHelper$") + cmd.Env = append(os.Environ(), helperMode+"=1") + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + l := &leftover{ledger: Open(t.TempDir()), cmd: cmd, done: make(chan struct{})} + ready := make(chan bool, 1) + go func() { + line, _ := bufio.NewReader(stdout).ReadString('\n') + ready <- strings.TrimSpace(line) == "ready" + _ = cmd.Wait() + close(l.done) + }() + t.Cleanup(func() { + _ = cmd.Process.Kill() + select { + case <-l.done: + case <-time.After(5 * time.Second): + t.Error("the leftover process did not end") + } + }) + select { + case ok := <-ready: + if !ok { + t.Fatal("the leftover process did not get ready") + } + case <-time.After(10 * time.Second): + t.Fatal("the leftover process did not get ready within 10s") + } + if err := l.ledger.AddKind(KindRun, cmd.Process.Pid); err != nil { + t.Fatal(err) + } + return l +} + +// recorded returns the ledger's leftovers, which must be exactly the helper. +func (l *leftover) recorded(t *testing.T) []Record { + t.Helper() + records, err := l.ledger.Leftovers() + if err != nil || len(records) != 1 || records[0].PID != l.cmd.Process.Pid || records[0].Kind != KindRun { + t.Fatalf("leftovers = %+v, %v", records, err) + } + return records +} + +// exited reports that the helper ended within limit. +func (l *leftover) exited(limit time.Duration) bool { + select { + case <-l.done: + return true + case <-time.After(limit): + return false + } +} + +// TestWindowsLedgerIdentifiesALeftoverByItsCreationAndPath: the record holds the process's creation +// time and executable, read from the system without running ps. +func TestWindowsLedgerIdentifiesALeftoverByItsCreationAndPath(t *testing.T) { + withRecordingProcessTools(t) + l := startLeftover(t) + record := l.recorded(t)[0] + if _, err := strconv.ParseUint(record.Started, 10, 64); err != nil { + t.Fatalf("Started = %q, want the creation time", record.Started) + } + // The executable's directory can be spelt in short (8.3) form in os.Args, so only its name is compared. + if want := filepath.Base(os.Args[0]); !strings.EqualFold(filepath.Base(record.Command), want) && + !strings.EqualFold(filepath.Base(record.Command), want+".exe") { + t.Fatalf("Command = %q, want the test binary %q", record.Command, want) + } +} + +func TestWindowsTrackRecordsAProcessUntilItIsUntracked(t *testing.T) { + withRecordingProcessTools(t) + t.Cleanup(func() { Activate("") }) + ledger := Activate(t.TempDir()) + if ledger == nil { + t.Fatal("Activate returned no ledger") + } + untrack := Track(KindBuild, os.Getpid()) + if records, err := ledger.Leftovers(); err != nil || len(records) != 1 || records[0].PID != os.Getpid() || records[0].Kind != KindBuild { + t.Fatalf("leftovers = %+v, %v; want this process as a build", records, err) + } + untrack() + if records, err := ledger.Leftovers(); err != nil || len(records) != 0 { + t.Fatalf("an untracked process is still recorded: %+v, %v", records, err) + } +} + +// TestWindowsSettleEndsALeftoverAtOnce: a process has no stop request here, so the one asked to +// stop is ended at once, without waiting out its grace and without running kill. +func TestWindowsSettleEndsALeftoverAtOnce(t *testing.T) { + withRecordingProcessTools(t) + l := startLeftover(t) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + started := time.Now() + count, err := l.ledger.Settle(ctx, l.recorded(t), true, 20*time.Second) + if err != nil || count != 1 { + t.Fatalf("settled %d, %v", count, err) + } + if elapsed := time.Since(started); elapsed >= 10*time.Second { + t.Fatalf("an ended process was waited for %v", elapsed) + } + if !l.exited(5*time.Second) || l.cmd.ProcessState.ExitCode() != 1 { + t.Fatalf("the process was not ended by the ledger: %v", l.cmd.ProcessState) + } + if records, err := l.ledger.Leftovers(); err != nil || len(records) != 0 { + t.Fatalf("the settled process is still recorded: %+v, %v", records, err) + } +} + +func TestWindowsSettleWithoutEndingForgetsTheLeftover(t *testing.T) { + withRecordingProcessTools(t) + l := startLeftover(t) + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + if count, err := l.ledger.Settle(ctx, l.recorded(t), false, time.Minute); err != nil || count != 0 { + t.Fatalf("settled %d, %v", count, err) + } + if records, err := l.ledger.Leftovers(); err != nil || len(records) != 0 { + t.Fatalf("the kept process is still recorded: %+v, %v", records, err) + } + if l.exited(200 * time.Millisecond) { + t.Fatal("a kept process was ended") + } +} + +// TestWindowsSettleLeavesAProcessThatIsNotTheRecordedOne checks the guard against a reused PID: a +// record whose creation time is not the running process's is not ended. +func TestWindowsSettleLeavesAProcessThatIsNotTheRecordedOne(t *testing.T) { + withRecordingProcessTools(t) + l := startLeftover(t) + record := l.recorded(t)[0] + record.Started = "1" + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + if count, err := endProcesses(ctx, []Record{record}, time.Minute); err != nil || count != 0 { + t.Fatalf("ended %d, %v", count, err) + } + if l.exited(200 * time.Millisecond) { + t.Fatal("a process that is not the recorded one was ended") + } +} + +// TestWindowsLeftoversSkipAProcessThatExited: a process that has exited can still be opened while a +// handle to it is held, and keeps its creation time and path; it is not a leftover all the same. +func TestWindowsLeftoversSkipAProcessThatExited(t *testing.T) { + withRecordingProcessTools(t) + l := startLeftover(t) + l.recorded(t) + held, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.SYNCHRONIZE, false, uint32(l.cmd.Process.Pid)) + if err != nil { + t.Fatal(err) + } + defer windows.CloseHandle(held) + if err := l.cmd.Process.Kill(); err != nil { + t.Fatal(err) + } + if !l.exited(5 * time.Second) { + t.Fatal("the killed process did not end") + } + if records, err := l.ledger.Leftovers(); err != nil || len(records) != 0 { + t.Fatalf("an exited process is a leftover: %+v, %v", records, err) + } +} diff --git a/desktop/internal/settingswindow/controller.go b/desktop/internal/settingswindow/controller.go index 4602444605..19ff498901 100644 --- a/desktop/internal/settingswindow/controller.go +++ b/desktop/internal/settingswindow/controller.go @@ -550,9 +550,6 @@ type Options struct { // is false until Core has answered. Nil hides the stop time, for a platform where a // stopped program is ended at once. StopTime func() (rule StopTime, ok bool) - // SweepsLeftovers says the client finds, at start-up, the processes an earlier run left - // behind; false hides the setting for them. - SweepsLeftovers bool // SetKeymap hands a change of Values.Keymap to the settings owner, like SetTabRows. SetKeymap func(shortcuts.Overrides) SetEditorPreferences func(core.EditorStoredPreferences, core.EditorPreferences) diff --git a/desktop/internal/settingswindow/process_termination_view.go b/desktop/internal/settingswindow/process_termination_view.go index f30b8dcbaf..4d0be599aa 100644 --- a/desktop/internal/settingswindow/process_termination_view.go +++ b/desktop/internal/settingswindow/process_termination_view.go @@ -72,25 +72,23 @@ func (w *window) processTerminationPage(c ui.C) { w.setProcessTermination(value, false) } }) - if w.ctrl.opts.SweepsLeftovers { - w.card(c, i18n.Shared(language, "native.afterLitheClosesUnexpectedly"), i18n.Shared(language, "desktop.settings.processTermination.startupSweepHelp"), func() { - sweep := value.StartupSweep - label := func(choice string) string { - if choice == StartupSweepTerminate { - return i18n.Shared(language, "native.endOnNextLaunch") - } - return i18n.Shared(language, "native.askOnNextLaunch") + w.card(c, i18n.Shared(language, "native.afterLitheClosesUnexpectedly"), i18n.Shared(language, "desktop.settings.processTermination.startupSweepHelp"), func() { + sweep := value.StartupSweep + label := func(choice string) string { + if choice == StartupSweepTerminate { + return i18n.Shared(language, "native.endOnNextLaunch") + } + return i18n.Shared(language, "native.askOnNextLaunch") + } + ui.Row(c).FillWidth().Height(28).Items(ui.Center).Gap(12).Children(func() { + ui.Text(c, i18n.Shared(language, "desktop.settings.processTermination.leftoverTerminals")).FontSize(12).Color(w.pal.text).Grow(1).MinWidth(0).Ellipsis() + if ui.Select(c.Part("sweep"), &sweep, startupSweepChoices, label).Width(selectWidth). + Label(i18n.Shared(language, "desktop.settings.processTermination.leftoverTerminals")).Changed() { + value.StartupSweep = sweep + w.setProcessTermination(value, false) } - ui.Row(c).FillWidth().Height(28).Items(ui.Center).Gap(12).Children(func() { - ui.Text(c, i18n.Shared(language, "desktop.settings.processTermination.leftoverTerminals")).FontSize(12).Color(w.pal.text).Grow(1).MinWidth(0).Ellipsis() - if ui.Select(c.Part("sweep"), &sweep, startupSweepChoices, label).Width(selectWidth). - Label(i18n.Shared(language, "desktop.settings.processTermination.leftoverTerminals")).Changed() { - value.StartupSweep = sweep - w.setProcessTermination(value, false) - } - }) }) - } + }) if w.ctrl.opts.StopTime != nil { w.stopTimeCard(c, value) } diff --git a/desktop/internal/settingswindow/visual_capture_test.go b/desktop/internal/settingswindow/visual_capture_test.go index bd8e856c9f..ee48289a4b 100644 --- a/desktop/internal/settingswindow/visual_capture_test.go +++ b/desktop/internal/settingswindow/visual_capture_test.go @@ -74,7 +74,7 @@ func TestVisualSettings(t *testing.T) { }, PluginState: func(string) PluginState { return PluginState{Installed: true, Enabled: true, Version: "1.0.0"} }, SystemDark: func() bool { return theme == "dark" }, SetNetwork: func(NetworkSettings, *string) {}, SetLocalHistory: func(LocalHistorySettings) {}, - StopTime: func() (StopTime, bool) { return StopTime{Default: 5, Min: 1, Max: 30}, true }, SweepsLeftovers: true, + StopTime: func() (StopTime, bool) { return StopTime{Default: 5, Min: 1, Max: 30}, true }, TerminalShells: func() ([]localshell.Choice, string) { return []localshell.Choice{{Name: "zsh", Path: "/bin/zsh", Default: true}, {Name: "bash", Path: "/bin/bash"}}, "/bin/zsh" }, diff --git a/desktop/internal/workbench/settings.go b/desktop/internal/workbench/settings.go index 618923d82c..b029140a9c 100644 --- a/desktop/internal/workbench/settings.go +++ b/desktop/internal/workbench/settings.go @@ -16,7 +16,6 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/marketplace" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginhost" "github.com/1lck/Lithe-IDEA/desktop/internal/pluginicons" - "github.com/1lck/Lithe-IDEA/desktop/internal/processledger" "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" "github.com/vivaui/viva/app" "github.com/vivaui/viva/gfx" @@ -255,7 +254,6 @@ func (a *App) newSettingsWindow() *settingswindow.Controller { a.post(func(a *App) { a.setConsoleEncoding(value) }) }, ConsoleEncodings: a.consoleEncodingsOption, - SweepsLeftovers: processledger.Supported, SteppingAdapters: a.steppingAdapters, NormalizeSteppingFilters: a.kernel.NormalizeSteppingFilters, SetSteppingFilters: func(adapter string, filters *core.DebugSteppingFilters) { diff --git a/docs/viva-migration.md b/docs/viva-migration.md index f741223721..2fbe0bf255 100644 --- a/docs/viva-migration.md +++ b/docs/viva-migration.md @@ -407,7 +407,7 @@ | `plugin-debug-start-and-adapter-features` | 插件后端发起调试并声明适配器行为 | 必须迁移 | 实现/缺 | 部分 | C01,C02 无 desktop/ 证据 | | `viva-debug-session` | Viva 调试面板使用插件声明的 stdio 调试适配器 | 必须迁移 | 本分支新增 | 部分 | C02,C12 | | `process-termination-policy` | 退出前逐个确认仍在运行程序的终端和 Agent 后台任务(Agent… | 必须迁移 | 部分/缺 | 部分 | C07 `workbench/process_exit.go`、`workbench/startup_sweep.go`、`settingswindow/process_termination_view.go` | -| `run-processes-end-with-ide` | 退出 IDE 时结束它启动的全部运行、终端、服务、测试、语言服务器和… | 必须迁移 | 实现/部分 | 部分 | `workbench/startup_sweep.go`、`processledger/processledger.go`(启动清扫仅 macOS) | +| `run-processes-end-with-ide` | 退出 IDE 时结束它启动的全部运行、终端、服务、测试、语言服务器和… | 必须迁移 | 实现/部分 | 部分 | `workbench/startup_sweep.go`、`processledger/processledger.go`(两端都做启动清扫,崩溃当下不清理) | | `run-output-snapshot` | 运行输出快照 | 必须迁移 | 缺/实现 | 完成 | `workbench/runs.go` | | `login-shell-environment` | 从 Finder / Dock 启动时继承登录 shell 的环境 | 平台专属 | 实现/专属 | 完成 | `loginenv/loginenv_unix.go`、`cmd/lithe/main.go` | | `run-discovery` | 入口点与运行配置发现 | 必须迁移 | 实现/实现 | 部分 | `core/run_discovery.go` | diff --git a/shared/platform-feature-matrix/features/process-termination-policy.json b/shared/platform-feature-matrix/features/process-termination-policy.json index f81b6a7fda..5b13d0a570 100644 --- a/shared/platform-feature-matrix/features/process-termination-policy.json +++ b/shared/platform-feature-matrix/features/process-termination-policy.json @@ -37,12 +37,14 @@ "desktop/internal/localshell/shell_windows_test.go", "desktop/internal/settingswindow/process_termination_view.go", "desktop/internal/settingswindow/process_termination_view_test.go", - "desktop/internal/buildprocess/process_windows.go" + "desktop/internal/buildprocess/process_windows.go", + "desktop/internal/processledger/processledger_windows.go", + "desktop/internal/workbench/startup_sweep.go" ] }, "owner": "Run", "verification": "macOS:在两个终端分别运行一个长驻服务和空闲 shell,让 Agent 启动一个长时间命令,再在终端里 setsid 启动一个后台服务;退出时应只对忙碌终端逐个确认(可跳到终端或取消),再逐个确认 Agent 任务(带 --settings JSON 的命令应按层级缩进显示,长命令在命令框内上下滚动,复制得到原始命令),最后在列表中勾选后台服务;选择保留的进程退出后仍存活,取消退出时不结束任何进程。在 Lithe 外启动的进程不出现。修改设置页各选项后流程相应跳过确认;悬停 ⓘ 约 0.3 秒出现说明,点击可固定,读屏可读出;中英文文案齐全;设置搜索能找到该页。 后台服务验证单条跨多屏长命令及不含空格的参数换行、完整选择复制、200 项滚动到最后一项且挂载按钮数随视口有界,滚动不重建文本存储或改变固定容器宽度,返回后保留按资源 ID 的勾选,全选/全不选包含离屏项并更新数量,读屏保留的同一复选框元素在单项和批量变更后实时回读勾选值且身份稳定,变更发送辅助功能值通知,仅识别服务出现记住选项;深浅主题原生弹窗高度有界,真实工作区连续滚动需另做帧性能验收,按选择退出、全部结束和取消继续沿用现有语义。 #2317:启动扫尾与退出确认提示(desktop.startupSweep.body、desktop.exit.body)改为数量中性英文,由 desktop/internal/i18n 与 workbench -race -tags 'dev vivahead' 覆盖,原生端待验收。", - "notes": "关闭窗口或项目时,仍在运行的插件 Run 会话与调试会话交给 Core 的 processLifecycle.resolve,confirmStop 的记录合并成一次确认,取消则保持原样。终端忙闲已接入:macOS 用 pty 前台进程组(TIOCGPGRP)与 shell 进程比较,Windows 看 shell 是否有子进程;忙碌终端在退出(quit)和关闭项目(按 closeTerminalTab,因为项目关闭时终端随之结束)时与运行会话列在同一次确认里,关闭忙碌终端标签页单独确认,空闲终端直接关闭。已知差异:Viva 版把忙碌终端合并进一次“全部结束或取消”的确认,没有逐个确认和“跳到终端”;shell 被 exec 替换(如 exec vim)时读作空闲;WSL 终端在 Windows 上始终读作空闲。设置页“外观与行为 › 进程终止策略”已接入本客户端生效的三项:运行服务退出时询问或直接停止、退出时忙碌终端询问或直接结束、关闭有程序在运行的标签页或项目前是否询问;只保存改过的字段并原样交给 Core(其余取 Core 默认),恢复默认值清空。“意外关闭后遗留的终端”(下次启动时询问或直接结束)和“停止程序”的等待时长也已接入:等待时长由 Core 按设置解析(默认 5 秒,限 1–60 秒,页面的上下限取自 Core),先请求程序退出(SIGTERM 整个进程组),超时再强制结束;对正在停止的运行或构建再点一次“强制结束”立即结束。Windows 停止即结束、也没有进程台账,所以 Windows 页面不显示这两项。Agent 任务和后台服务本客户端不启动,页面不显示;Agent 任务没有对应的进程探测,processLifecycle.inventory 未接入。 #2317:将 desktop.startupSweep.body 与 desktop.exit.body 改为数量中性英文,避免单数与多进程混用;中文不变。", + "notes": "关闭窗口或项目时,仍在运行的插件 Run 会话与调试会话交给 Core 的 processLifecycle.resolve,confirmStop 的记录合并成一次确认,取消则保持原样。终端忙闲已接入:macOS 用 pty 前台进程组(TIOCGPGRP)与 shell 进程比较,Windows 看 shell 是否有子进程;忙碌终端在退出(quit)和关闭项目(按 closeTerminalTab,因为项目关闭时终端随之结束)时与运行会话列在同一次确认里,关闭忙碌终端标签页单独确认,空闲终端直接关闭。已知差异:Viva 版把忙碌终端合并进一次“全部结束或取消”的确认,没有逐个确认和“跳到终端”;shell 被 exec 替换(如 exec vim)时读作空闲;WSL 终端在 Windows 上始终读作空闲。设置页“外观与行为 › 进程终止策略”已接入本客户端生效的三项:运行服务退出时询问或直接停止、退出时忙碌终端询问或直接结束、关闭有程序在运行的标签页或项目前是否询问;只保存改过的字段并原样交给 Core(其余取 Core 默认),恢复默认值清空。“意外关闭后遗留的终端”(下次启动时询问或直接结束)和“停止程序”的等待时长也已接入:等待时长由 Core 按设置解析(默认 5 秒,限 1–60 秒,页面的上下限取自 Core),先请求程序退出(SIGTERM 整个进程组),超时再强制结束;对正在停止的运行或构建再点一次“强制结束”立即结束。Windows 停止即结束,所以 Windows 页面不显示等待时长;遗留终端的选项两端都显示,Windows 的进程台账通过进程句柄核对身份、不启动外部程序。Agent 任务和后台服务本客户端不启动,页面不显示;Agent 任务没有对应的进程探测,processLifecycle.inventory 未接入。 #2317:将 desktop.startupSweep.body 与 desktop.exit.body 改为数量中性英文,避免单数与多进程混用;中文不变。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { diff --git a/shared/platform-feature-matrix/features/run-processes-end-with-ide.json b/shared/platform-feature-matrix/features/run-processes-end-with-ide.json index 562c216438..034c038455 100644 --- a/shared/platform-feature-matrix/features/run-processes-end-with-ide.json +++ b/shared/platform-feature-matrix/features/run-processes-end-with-ide.json @@ -14,6 +14,7 @@ "desktop/internal/workbench/startup_sweep.go", "desktop/internal/workbench/startup_sweep_unix_test.go", "desktop/internal/processledger/processledger.go", + "desktop/internal/processledger/processledger_unix.go", "desktop/internal/processledger/processledger_unix_test.go", "desktop/internal/pluginservice/leftovers.go" ] @@ -25,12 +26,19 @@ "desktop/internal/workbench/app.go", "desktop/internal/workbench/runs.go", "desktop/internal/workbench/process_exit.go", - "desktop/internal/workbench/process_exit_test.go" + "desktop/internal/workbench/process_exit_test.go", + "desktop/internal/workbench/startup_sweep.go", + "desktop/internal/processledger/processledger.go", + "desktop/internal/processledger/processledger_windows.go", + "desktop/internal/processledger/processledger_windows_test.go", + "desktop/internal/pluginservice/leftovers.go", + "desktop/internal/localshell/backend_windows.go", + "desktop/internal/localshell/shell_windows_test.go" ] }, "owner": "Run", "verification": "运行一个长驻服务(如本地 HTTP 服务)、一个 setsid 脱离的后台进程和一个忽略终止信号的程序,分别通过菜单退出、更新重启和对主进程 kill -9 关闭 IDE,确认除用户选择保留的项目外,带本实例 LITHE_PROCESS_SCOPE 的进程全部退出、端口已释放;主进程和监护进程同时被结束后再次启动,确认残留进程出现在启动清扫确认中。 Windows Run 原生测试按父 PID 和 ping.exe 名称唯一识别夹具后代,覆盖快照乱序、大小写、缺失和歧义;停止前持有该后代进程句柄,以两秒退出信号确认根进程和后代结束,以零等待确认另一窗口仍在运行;cmd 禁用 AutoRun,首字节就绪等待有界,夹具在断言失败时也清理所属进程树。", - "notes": "关闭项目或窗口时结束该项目的 Run 会话、调试会话、测试和终端(先确认,见 process-termination-policy)。IDE 异常退出后的遗留进程:macOS 的运行、构建、调试适配器、插件工具和终端写入进程台账(PID 与启动时间,防 PID 复用),下次启动由 Core 的 processLifecycle.resolve(startupSweep)决定,运行、构建、调试适配器和插件工具直接结束,终端按设置询问或直接结束,确认窗口里可结束或保留;Core 不可用时全部交给用户决定、不自动结束。结束时先 SIGTERM,等待 Core 给出的停止时长后再 SIGKILL。Windows 没有进程台账(缺少 ps 的启动时间核对),不做启动清扫;没有监护进程,崩溃当下不清理。", + "notes": "关闭项目或窗口时结束该项目的 Run 会话、调试会话、测试和终端(先确认,见 process-termination-policy)。IDE 异常退出后的遗留进程:运行、构建、调试适配器、插件工具和终端写入进程台账(PID、启动时间和命令,防 PID 复用),macOS 用 ps 读取启动时间和命令名,Windows 通过进程句柄读取创建时间和程序路径、不启动 ps 等外部程序(否则构建时会闪出控制台窗口),下次启动由 Core 的 processLifecycle.resolve(startupSweep)决定,运行、构建、调试适配器和插件工具直接结束,终端按设置询问或直接结束,确认窗口里可结束或保留;Core 不可用时全部交给用户决定、不自动结束。结束时 macOS 先 SIGTERM,等待 Core 给出的停止时长后再 SIGKILL;Windows 没有停止请求,直接 TerminateProcess。两端都没有监护进程,崩溃当下不清理;Windows 构建类进程另有 Job Object 在崩溃时连带结束。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": {