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 @@ -4,7 +4,7 @@

## 先说结论

Lithe 启动的运行、服务、预启动任务、测试、构建和插件进程,生命周期都绑定在 Lithe 上:关闭项目或退出时,由 Core 的进程生命周期规则决定哪些进程需要询问,再由所属模块停止自己的会话。Windows 上构建进程放进 Job Object,Lithe 崩溃时内核也会连带结束整组进程。忙碌终端和运行服务在关闭前统一询问,用户可以选择停止或取消。
Lithe 启动的运行、服务、预启动任务、测试、构建和插件进程,生命周期都绑定在 Lithe 上:关闭项目或退出时,由 Core 的进程生命周期规则决定哪些进程需要询问,再由所属模块停止自己的会话。Windows 上构建进程放进 Job Object,Lithe 崩溃时内核也会连带结束整组进程。进程账本在 macOS 和 Windows 上都登记,崩溃后的残留在下一次启动时清扫;Windows 的账本只通过进程句柄调用系统接口,不启动任何外部程序。忙碌终端和运行服务在关闭前统一询问,用户可以选择停止或取消。

## 问题

Expand Down Expand Up @@ -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 <pid>`,结束进程时运行 `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 上关掉账本:账本是崩溃后清扫残留的唯一依据。

### 反例

- 只在所有者的停止函数里发信号就返回:所有者漏掉一类会话,或者进程在异步升级前退出,子进程都会变成孤儿。
Expand All @@ -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 进程,始终读作空闲。

## 验证
Expand All @@ -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 进程全部消失,端口释放。

Expand All @@ -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) 当前固定的修订为准。
Original file line number Diff line number Diff line change
Expand Up @@ -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 重新核对,实施前以代码为准。

## 先说结论

Expand Down
8 changes: 7 additions & 1 deletion desktop/internal/localshell/backend_windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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;
Expand Down
32 changes: 32 additions & 0 deletions desktop/internal/localshell/shell_windows_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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"))
Expand Down
35 changes: 2 additions & 33 deletions desktop/internal/processledger/processledger.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,15 @@ import (
"encoding/json"
"errors"
"os"
"os/exec"
"path/filepath"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"time"
)

// 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"`
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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()
}
32 changes: 32 additions & 0 deletions desktop/internal/processledger/processledger_unix.go
Original file line number Diff line number Diff line change
@@ -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()
}
74 changes: 74 additions & 0 deletions desktop/internal/processledger/processledger_windows.go
Original file line number Diff line number Diff line change
@@ -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
}
Loading
Loading