diff --git a/desktop/internal/core/process_memory.go b/desktop/internal/core/process_memory.go new file mode 100644 index 0000000000..b769dc3766 --- /dev/null +++ b/desktop/internal/core/process_memory.go @@ -0,0 +1,96 @@ +package core + +import "context" + +// MemoryProcess is one row of the process table the client read for processMemory.summarize. +type MemoryProcess struct { + ProcessID int64 `json:"processId"` + ParentProcessID int64 `json:"parentProcessId"` + // ResponsibleProcessID is the process the system holds responsible for this one, nil + // where the system has no such notion. + ResponsibleProcessID *int64 `json:"responsibleProcessId,omitempty"` + // StartTime is when the process started, in microseconds since 1970, nil when it was not + // read. Core ignores a parent link to a process that started later. + StartTime *uint64 `json:"startTime,omitempty"` + Name string `json:"name"` + Bytes uint64 `json:"bytes"` +} + +// MemoryRole kinds: what the client started a process for. +const ( + MemoryRoleLanguageServer = "languageServer" + MemoryRolePluginService = "pluginService" +) + +// MemoryRole names a process the client started for a role. An empty Name shows the +// process name. +type MemoryRole struct { + ProcessID int64 `json:"processId"` + Kind string `json:"kind"` + Name string `json:"name"` +} + +// MemoryRequest is the process table of one moment and the roles of the processes the +// client started. HostProcessID must be one of Processes. A nil EntryLimit takes Core's +// default; it is capped at 200. +type MemoryRequest struct { + HostProcessID int64 `json:"hostProcessId"` + Processes []MemoryProcess `json:"processes"` + Roles []MemoryRole `json:"roles,omitempty"` + EntryLimit *int `json:"entryLimit,omitempty"` +} + +// Memory kinds: the part of the instance a process counts in, in the order the summary +// lists its categories. +const ( + MemoryHost = "host" + MemoryLanguageServer = "languageServer" + MemoryPluginService = "pluginService" + MemorySystemHelper = "systemHelper" + MemoryChildProcess = "childProcess" +) + +// MemoryCategory is the sum of one part. +type MemoryCategory struct { + Kind string `json:"kind"` + Bytes uint64 `json:"bytes"` + ProcessCount int `json:"processCount"` +} + +// MemoryEntry is one process of the instance other than the host, with the processes Core +// counts under it. +type MemoryEntry struct { + Kind string `json:"kind"` + Name string `json:"name"` + ProcessID int64 `json:"processId"` + Bytes uint64 `json:"bytes"` + ProcessCount int `json:"processCount"` +} + +// MemoryOmitted is the count and sum of the entries past the limit. +type MemoryOmitted struct { + Count int `json:"count"` + Bytes uint64 `json:"bytes"` +} + +// MemorySummary is Core's account of what the instance holds: the total, every part in a +// fixed order with the empty ones included, and the largest entries. +type MemorySummary struct { + TotalBytes uint64 `json:"totalBytes"` + Categories []MemoryCategory `json:"categories"` + Entries []MemoryEntry `json:"entries"` + Omitted MemoryOmitted `json:"omitted"` +} + +// SummarizeProcessMemory has Core attribute every process of the table to the instance or +// leave it out, and sum what each part holds. +func (c *Client) SummarizeProcessMemory(ctx context.Context, request MemoryRequest) (MemorySummary, error) { + request.Processes = nonNil(request.Processes) + var summary MemorySummary + if err := c.Execute(ctx, "processMemory.summarize", request, &summary); err != nil { + return MemorySummary{}, err + } + summary.Categories = nonNil(summary.Categories) + summary.Entries = nonNil(summary.Entries) + return summary, nil +} diff --git a/desktop/internal/core/process_memory_test.go b/desktop/internal/core/process_memory_test.go new file mode 100644 index 0000000000..4388acc4e7 --- /dev/null +++ b/desktop/internal/core/process_memory_test.go @@ -0,0 +1,93 @@ +package core + +import ( + "encoding/json" + "errors" + "reflect" + "testing" +) + +// memoryFixture is rust/fixtures/process-lifecycle/memory-summary-v1.json of the linked Core. +type memoryFixture struct { + Cases []struct { + Name string `json:"name"` + Request json.RawMessage `json:"request"` + Expected MemorySummary `json:"expected"` + } `json:"cases"` + Invalid []struct { + Name string `json:"name"` + Request json.RawMessage `json:"request"` + } `json:"invalid"` +} + +// typedMemoryRequest decodes raw into the client's request and reports whether encoding it +// again gives the same document, so the client sends what the fixture holds. +func typedMemoryRequest(t *testing.T, raw json.RawMessage) (MemoryRequest, bool) { + t.Helper() + var request MemoryRequest + if json.Unmarshal(raw, &request) != nil { + return MemoryRequest{}, false + } + encoded, err := json.Marshal(request) + if err != nil { + t.Fatal(err) + } + var want, got any + if err := json.Unmarshal(raw, &want); err != nil { + t.Fatal(err) + } + if err := json.Unmarshal(encoded, &got); err != nil { + t.Fatal(err) + } + return request, reflect.DeepEqual(got, want) +} + +// TestProcessMemorySummarizeFollowsTheContractFixture replays every summary: Core attributes +// and sums, the client only carries the table and the roles. +func TestProcessMemorySummarizeFollowsTheContractFixture(t *testing.T) { + var fixture memoryFixture + if err := json.Unmarshal(readLifecycleFixture(t, "memory-summary-v1.json"), &fixture); err != nil { + t.Fatal(err) + } + if len(fixture.Cases) == 0 || len(fixture.Invalid) == 0 { + t.Fatal("the fixture has no cases") + } + ctx := debugContext(t) + for _, test := range fixture.Cases { + t.Run(test.Name, func(t *testing.T) { + request, exact := typedMemoryRequest(t, test.Request) + if !exact { + t.Fatalf("the client cannot send the request %s as it is", test.Request) + } + got, err := NewClient().SummarizeProcessMemory(ctx, request) + if err != nil { + t.Fatal(err) + } + test.Expected.Categories = nonNil(test.Expected.Categories) + test.Expected.Entries = nonNil(test.Expected.Entries) + if !reflect.DeepEqual(got, test.Expected) { + t.Fatalf("summary = %+v, want %+v", got, test.Expected) + } + }) + } + // Some invalid requests, such as negative bytes, cannot be written with the client's + // types; the ones that can are rejected as invalid. + sent := 0 + for _, test := range fixture.Invalid { + request, exact := typedMemoryRequest(t, test.Request) + if !exact { + continue + } + sent++ + t.Run(test.Name, func(t *testing.T) { + _, err := NewClient().SummarizeProcessMemory(ctx, request) + var coreErr *Error + if !errors.As(err, &coreErr) || coreErr.Code != CodeInvalidRequest { + t.Fatalf("error = %v, want %s", err, CodeInvalidRequest) + } + }) + } + if sent == 0 { + t.Fatal("no invalid request could be sent") + } +} diff --git a/desktop/internal/i18n/en.go b/desktop/internal/i18n/en.go index c701d8e8c8..d50ff2cb21 100644 --- a/desktop/internal/i18n/en.go +++ b/desktop/internal/i18n/en.go @@ -327,7 +327,6 @@ var english = Messages{ Encoding: Shared(English, "desktop.status.encoding"), Problems: func(count int) string { return statusProblems(English, count) }, Memory: Shared(English, "desktop.status.memory"), - MemoryValue: func(megabytes int) string { return statusMemory(English, megabytes) }, FPS: Shared(English, "desktop.status.fPS"), FPSValue: func(fps int) string { return statusFPS(English, fps) }, NoChanges: Shared(English, "desktop.status.noChanges"), diff --git a/desktop/internal/i18n/i18n_test.go b/desktop/internal/i18n/i18n_test.go index 343e572de0..c0c3a58e16 100644 --- a/desktop/internal/i18n/i18n_test.go +++ b/desktop/internal/i18n/i18n_test.go @@ -201,7 +201,7 @@ func TestTerminalAndStatusValuesPreserveExistingWording(t *testing.T) { {Chinese, "本地", "本地 (2)", "会话已结束,退出状态 -1。", "1 个更改", "2 个更改"}, } { messages := For(test.language) - if messages.Terminal.Tab(1) != test.local || messages.Terminal.Tab(2) != test.second || messages.Terminal.SessionEndedStatus(-1) != test.ended || messages.Status.Changes(1) != test.one || messages.Status.Changes(2) != test.many || messages.Status.MemoryValue(12) != "12 MB" || messages.Status.FPSValue(60) != "60 FPS" { + if messages.Terminal.Tab(1) != test.local || messages.Terminal.Tab(2) != test.second || messages.Terminal.SessionEndedStatus(-1) != test.ended || messages.Status.Changes(1) != test.one || messages.Status.Changes(2) != test.many || messages.Status.FPSValue(60) != "60 FPS" { t.Fatalf("language %s: terminal or status wording changed", test.language.Code()) } } diff --git a/desktop/internal/i18n/messages.go b/desktop/internal/i18n/messages.go index e907793a67..ccff75cfe8 100644 --- a/desktop/internal/i18n/messages.go +++ b/desktop/internal/i18n/messages.go @@ -527,9 +527,7 @@ type StatusMessages struct { // "3 problems". One problem has its own wording. Problems func(count int) string Memory string - // MemoryValue is the memory readout, for example "312 MB". - MemoryValue func(megabytes int) string - FPS string + FPS string // FPSValue is the frame rate readout, for example "60 FPS". FPSValue func(fps int) string NoChanges string diff --git a/desktop/internal/i18n/runtime_messages.go b/desktop/internal/i18n/runtime_messages.go index a596b85f2b..8048c8a591 100644 --- a/desktop/internal/i18n/runtime_messages.go +++ b/desktop/internal/i18n/runtime_messages.go @@ -21,10 +21,6 @@ func terminalTab(language Language, number int) string { return SharedFormat(language, "desktop.terminal.localNumber", map[string]string{"number": strconv.Itoa(number)}) } -func statusMemory(language Language, value int) string { - return SharedFormat(language, "desktop.status.memoryValue", map[string]string{"value": strconv.Itoa(value)}) -} - func statusFPS(language Language, value int) string { return SharedFormat(language, "desktop.status.fpsValue", map[string]string{"value": strconv.Itoa(value)}) } diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 8bd5ce68ad..1c3b70ae1f 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -892,17 +892,28 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.sourceUnavailable": "Source unavailable: {source}", "desktop.marketplace.tab.settings": "Settings", "desktop.marketplace.uninstall": "Uninstall", - "desktop.memory.kindServer": "language server", - "desktop.memory.kindService": "plugin service", + "desktop.memory.belowMegabyte": "< 1 MB", + "desktop.memory.childProcesses": "Other child processes", + "desktop.memory.gigabytes": "{value} GB", + "desktop.memory.help": "Counts the Lithe main process and every process that belongs to it: language servers, plugin services, child processes such as terminals and runs, and the helpers the system starts for Lithe, such as the WebKit processes that show web pages and previews.", + "desktop.memory.helpLinux": "Each figure is the resident memory less its shared pages.", + "desktop.memory.helpMacOS": "Each figure is what the Memory column of Activity Monitor shows.", + "desktop.memory.helpWindows": "Each figure is the private working set, which the Memory column of Task Manager shows.", + "desktop.memory.host": "Lithe main process", + "desktop.memory.languageServer": "{plugin} · {language}", "desktop.memory.languageServers": "Language servers", - "desktop.memory.lithe": "Lithe", - "desktop.memory.noProcesses": "No language servers or plugin services are running.", + "desktop.memory.megabytes": "{value} MB", + "desktop.memory.noOtherProcesses": "Lithe has not started any other process.", + "desktop.memory.omitted": "{count} more, {value} in total", + "desktop.memory.processCount": "{count} processes", + "desktop.memory.processes": "Processes", + "desktop.memory.reading": "Reading processes…", "desktop.memory.services": "Plugin services", - "desktop.memory.status": "{total} MB · Lithe {lithe} MB", + "desktop.memory.status": "{total} · Lithe {lithe}", + "desktop.memory.systemHelpers": "System helpers", "desktop.memory.title": "Memory", - "desktop.memory.tooltip": "Memory: {total} MB in total. Lithe {lithe} MB, language servers {lsp} MB, services {services} MB.", - "desktop.memory.total": "Total", - "desktop.memory.value": "{value} MB", + "desktop.memory.tooltip": "Memory: {total} in total, {lithe} of it in the Lithe main process.", + "desktop.memory.unavailable": "Process memory could not be read.", "desktop.menu.open": "Menu", "desktop.nativePanel.empty": "Nothing to show.", "desktop.nativePanel.failed": "The plugin could not run this action.", @@ -1387,7 +1398,6 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.status.lspStarting": "LSP starting", "desktop.status.lspStopped": "LSP stopped", "desktop.status.memory": "Memory", - "desktop.status.memoryValue": "{value} MB", "desktop.status.noChanges": "No changes", "desktop.status.oneProblem": "1 problem", "desktop.status.path": "Path", @@ -3398,17 +3408,28 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.marketplace.sourceUnavailable": "来源不可用:{source}", "desktop.marketplace.tab.settings": "设置", "desktop.marketplace.uninstall": "卸载", - "desktop.memory.kindServer": "语言服务器", - "desktop.memory.kindService": "插件服务", + "desktop.memory.belowMegabyte": "< 1 MB", + "desktop.memory.childProcesses": "其他子进程", + "desktop.memory.gigabytes": "{value} GB", + "desktop.memory.help": "统计 Lithe 主进程和属于它的全部进程:语言服务器、插件服务、终端和运行任务等子进程,以及系统代 Lithe 启动的辅助进程,例如显示网页和预览的 WebKit 进程。", + "desktop.memory.helpLinux": "数值是常驻内存减去共享页。", + "desktop.memory.helpMacOS": "数值与活动监视器“内存”一列显示的一致。", + "desktop.memory.helpWindows": "数值是专用工作集,即任务管理器“内存”一列显示的值。", + "desktop.memory.host": "Lithe 主进程", + "desktop.memory.languageServer": "{plugin} · {language}", "desktop.memory.languageServers": "语言服务器", - "desktop.memory.lithe": "Lithe", - "desktop.memory.noProcesses": "没有运行中的语言服务器或插件服务。", + "desktop.memory.megabytes": "{value} MB", + "desktop.memory.noOtherProcesses": "Lithe 目前没有启动其他进程。", + "desktop.memory.omitted": "另有 {count} 项,共 {value}", + "desktop.memory.processCount": "{count} 个进程", + "desktop.memory.processes": "进程", + "desktop.memory.reading": "正在读取进程…", "desktop.memory.services": "插件服务", - "desktop.memory.status": "{total} MB · Lithe {lithe} MB", + "desktop.memory.status": "{total} · Lithe {lithe}", + "desktop.memory.systemHelpers": "系统辅助进程", "desktop.memory.title": "内存", - "desktop.memory.tooltip": "内存:共 {total} MB。Lithe {lithe} MB,语言服务器 {lsp} MB,服务 {services} MB。", - "desktop.memory.total": "总计", - "desktop.memory.value": "{value} MB", + "desktop.memory.tooltip": "内存:共 {total},其中 Lithe 主进程 {lithe}。", + "desktop.memory.unavailable": "无法读取进程内存。", "desktop.menu.open": "菜单", "desktop.nativePanel.empty": "没有可显示的内容。", "desktop.nativePanel.failed": "插件无法执行此操作。", @@ -3893,7 +3914,6 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.status.lspStarting": "LSP 启动中", "desktop.status.lspStopped": "LSP 已停止", "desktop.status.memory": "内存", - "desktop.status.memoryValue": "{value} MB", "desktop.status.noChanges": "没有更改", "desktop.status.oneProblem": "1 个问题", "desktop.status.path": "路径", diff --git a/desktop/internal/i18n/zh.go b/desktop/internal/i18n/zh.go index 0d935f5172..7a5a86e0a6 100644 --- a/desktop/internal/i18n/zh.go +++ b/desktop/internal/i18n/zh.go @@ -327,7 +327,6 @@ var chinese = Messages{ Encoding: Shared(Chinese, "desktop.status.encoding"), Problems: func(count int) string { return statusProblems(Chinese, count) }, Memory: Shared(Chinese, "desktop.status.memory"), - MemoryValue: func(megabytes int) string { return statusMemory(Chinese, megabytes) }, FPS: Shared(Chinese, "desktop.status.fPS"), FPSValue: func(fps int) string { return statusFPS(Chinese, fps) }, NoChanges: Shared(Chinese, "desktop.status.noChanges"), diff --git a/desktop/internal/pluginservice/processsample.go b/desktop/internal/pluginservice/processsample.go index 6ee340b840..bc7614c46a 100644 --- a/desktop/internal/pluginservice/processsample.go +++ b/desktop/internal/pluginservice/processsample.go @@ -126,26 +126,3 @@ func parseWindowsTable(output []byte, root int) (memoryBytes uint64, cpuSeconds } return memoryBytes, float64(ticks) / 1e7, true } - -// SampleProcessMemory reads the process table once and sums the resident memory of the tree under -// each pid, in bytes. A pid that is gone is left out. Like SampleProcessTree it runs a short-lived -// command, so it is called off the window thread. -func SampleProcessMemory(ctx context.Context, pids []int) map[int]uint64 { - if len(pids) == 0 { - return nil - } - output, err := processTable(ctx) - if err != nil { - return nil - } - memory := make(map[int]uint64, len(pids)) - for _, pid := range pids { - if pid <= 0 { - continue - } - if bytes, ok := treeMemory(output, pid); ok { - memory[pid] = bytes - } - } - return memory -} diff --git a/desktop/internal/pluginservice/processsample_unix.go b/desktop/internal/pluginservice/processsample_unix.go index 22ea994602..f86efb9b89 100644 --- a/desktop/internal/pluginservice/processsample_unix.go +++ b/desktop/internal/pluginservice/processsample_unix.go @@ -13,10 +13,3 @@ func sampleProcessTree(ctx context.Context, pid int) (ProcessSample, bool) { } return parsePSTable(output, pid) } - -func processTable(ctx context.Context) ([]byte, error) { return psCommand(ctx) } - -func treeMemory(output []byte, pid int) (uint64, bool) { - sample, ok := parsePSTable(output, pid) - return sample.MemoryBytes, ok -} diff --git a/desktop/internal/pluginservice/processsample_windows.go b/desktop/internal/pluginservice/processsample_windows.go index bc192919bc..19077b7563 100644 --- a/desktop/internal/pluginservice/processsample_windows.go +++ b/desktop/internal/pluginservice/processsample_windows.go @@ -48,12 +48,3 @@ func sampleProcessTree(ctx context.Context, pid int) (ProcessSample, bool) { } return sample, true } - -func processTable(ctx context.Context) ([]byte, error) { - return exec.CommandContext(ctx, "powershell", "-NoProfile", "-NonInteractive", "-Command", windowsTableCommand).Output() -} - -func treeMemory(output []byte, pid int) (uint64, bool) { - memory, _, ok := parseWindowsTable(output, pid) - return memory, ok -} diff --git a/desktop/internal/sysinfo/process.go b/desktop/internal/sysinfo/process.go new file mode 100644 index 0000000000..38e60c9b22 --- /dev/null +++ b/desktop/internal/sysinfo/process.go @@ -0,0 +1,27 @@ +package sysinfo + +// Process is one row of the system's process table, with what the memory readout of the +// status bar needs to place the process and weigh it. +type Process struct { + // PID is the process's ID and ParentPID its parent's, as the system reports them. + PID, ParentPID int + // ResponsiblePID is the process the system holds responsible for this one, which macOS + // reports for the XPC services it starts for an app, such as the WebKit processes of a + // web view. It is zero where the system has no such notion or did not say. + ResponsiblePID int + // StartTime is when the process started, in microseconds since 1970; zero when not read. + // Windows keeps the ID of a parent that exited, which a later process may reuse; a parent + // that started after its child is such a reused ID. + StartTime uint64 + // Name is the process's short name. + Name string + // MemoryBytes is the memory the system charges to the process: the physical footprint + // Activity Monitor shows on macOS, the private working set Task Manager shows on Windows + // and the resident pages less the shared ones on Linux. It is zero for a process whose + // memory this user may not read. + MemoryBytes uint64 +} + +// Processes reads the process table: every process this user can see. A fact the system does +// not give for one process is zero; the error says the table could not be listed at all. +func Processes() ([]Process, error) { return processes() } diff --git a/desktop/internal/sysinfo/process_darwin.go b/desktop/internal/sysinfo/process_darwin.go new file mode 100644 index 0000000000..94c196846d --- /dev/null +++ b/desktop/internal/sysinfo/process_darwin.go @@ -0,0 +1,106 @@ +package sysinfo + +/* +#include +#include +#include +#include +#include +#include +#include + +typedef struct { + int pid; + int ppid; + int responsible; + unsigned long long start; + unsigned long long footprint; + char name[2 * MAXCOMLEN + 1]; +} lithe_process; + +// responsibility_get_pid_responsible_for_pid is the libsystem function Activity Monitor uses +// to put XPC services under the app they work for. It is not declared in the SDK, so it is +// looked up once; without it no process has a responsible process. +typedef pid_t (*lithe_responsible_fn)(pid_t); +static lithe_responsible_fn lithe_responsible; +static pthread_once_t lithe_responsible_once = PTHREAD_ONCE_INIT; + +static void lithe_find_responsible(void) { + lithe_responsible = (lithe_responsible_fn)dlsym(RTLD_DEFAULT, "responsibility_get_pid_responsible_for_pid"); +} + +static int lithe_process_count(void) { + return proc_listallpids(NULL, 0); +} + +// lithe_read_processes writes up to capacity rows and returns how many it wrote, or -1 when the +// process IDs cannot be listed. A process that exits while it is read is left out. +static int lithe_read_processes(lithe_process *rows, int capacity) { + pthread_once(&lithe_responsible_once, lithe_find_responsible); + int *pids = calloc((size_t)capacity, sizeof(int)); + if (pids == NULL) { + return -1; + } + int count = proc_listallpids(pids, capacity * (int)sizeof(int)); + if (count < 0) { + free(pids); + return -1; + } + if (count > capacity) { + count = capacity; + } + int written = 0; + for (int i = 0; i < count; i++) { + struct proc_bsdinfo info; + if (proc_pidinfo(pids[i], PROC_PIDTBSDINFO, 0, &info, sizeof(info)) != (int)sizeof(info)) { + continue; + } + lithe_process *row = &rows[written++]; + row->pid = pids[i]; + row->ppid = (int)info.pbi_ppid; + row->start = (unsigned long long)info.pbi_start_tvsec * 1000000ULL + (unsigned long long)info.pbi_start_tvusec; + const char *name = info.pbi_name[0] != '\0' ? info.pbi_name : info.pbi_comm; + strlcpy(row->name, name, sizeof(row->name)); + struct rusage_info_v4 usage; + row->footprint = proc_pid_rusage(pids[i], RUSAGE_INFO_V4, (rusage_info_t *)&usage) == 0 ? usage.ri_phys_footprint : 0; + int responsible = lithe_responsible != NULL ? (int)lithe_responsible(pids[i]) : 0; + row->responsible = responsible > 0 ? responsible : 0; + } + free(pids); + return written; +} +*/ +import "C" + +import ( + "errors" + "unsafe" +) + +// processSlack is how many more rows than the system listed a moment before are made room +// for, for the processes that start between the two calls. +const processSlack = 64 + +func processes() ([]Process, error) { + listed := int(C.lithe_process_count()) + if listed <= 0 { + return nil, errors.New("sysinfo: the process IDs cannot be listed") + } + rows := make([]C.lithe_process, listed+processSlack) + written := int(C.lithe_read_processes((*C.lithe_process)(unsafe.Pointer(&rows[0])), C.int(len(rows)))) + if written < 0 { + return nil, errors.New("sysinfo: the process IDs cannot be listed") + } + table := make([]Process, written) + for i, row := range rows[:written] { + table[i] = Process{ + PID: int(row.pid), + ParentPID: int(row.ppid), + ResponsiblePID: int(row.responsible), + StartTime: uint64(row.start), + Name: C.GoString(&row.name[0]), + MemoryBytes: uint64(row.footprint), + } + } + return table, nil +} diff --git a/desktop/internal/sysinfo/process_linux.go b/desktop/internal/sysinfo/process_linux.go new file mode 100644 index 0000000000..71b96b4f1e --- /dev/null +++ b/desktop/internal/sysinfo/process_linux.go @@ -0,0 +1,75 @@ +package sysinfo + +import ( + "os" + "strconv" + "strings" +) + +// processes reads /proc. Linux gives an orphan to init or a subreaper, so the parent IDs are +// never stale and the start time is not read. +func processes() ([]Process, error) { + entries, err := os.ReadDir("/proc") + if err != nil { + return nil, err + } + page := uint64(os.Getpagesize()) + table := make([]Process, 0, len(entries)) + for _, entry := range entries { + pid, err := strconv.Atoi(entry.Name()) + if err != nil || pid <= 0 { + continue + } + if row, ok := readProcess(pid, page); ok { + table = append(table, row) + } + } + return table, nil +} + +// readProcess reads the parent and name from /proc/pid/stat and the memory from +// /proc/pid/statm; false when the process exited while it was read. +func readProcess(pid int, page uint64) (Process, bool) { + dir := "/proc/" + strconv.Itoa(pid) + "/" + stat, err := os.ReadFile(dir + "stat") + if err != nil { + return Process{}, false + } + // The name is in parentheses and may itself hold spaces and parentheses, so the fields + // after it start at the last closing one: the state, then the parent ID. + text := string(stat) + open, close := strings.IndexByte(text, '('), strings.LastIndexByte(text, ')') + if open < 0 || close < open { + return Process{}, false + } + fields := strings.Fields(text[close+1:]) + if len(fields) < 2 { + return Process{}, false + } + parent, err := strconv.Atoi(fields[1]) + if err != nil { + return Process{}, false + } + row := Process{PID: pid, ParentPID: parent, Name: text[open+1 : close]} + if statm, err := os.ReadFile(dir + "statm"); err == nil { + row.MemoryBytes = privatePages(string(statm)) * page + } + return row, true +} + +// privatePages is the resident pages of a statm line less its shared ones. +func privatePages(statm string) uint64 { + fields := strings.Fields(statm) + if len(fields) < 3 { + return 0 + } + resident, err := strconv.ParseUint(fields[1], 10, 64) + if err != nil { + return 0 + } + shared, err := strconv.ParseUint(fields[2], 10, 64) + if err != nil || shared > resident { + return 0 + } + return resident - shared +} diff --git a/desktop/internal/sysinfo/process_test.go b/desktop/internal/sysinfo/process_test.go new file mode 100644 index 0000000000..f4adb01e1e --- /dev/null +++ b/desktop/internal/sysinfo/process_test.go @@ -0,0 +1,85 @@ +package sysinfo + +import ( + "io" + "os" + "os/exec" + "runtime" + "testing" + "time" +) + +// helperEnvironment marks the copy of the test binary that TestProcessesListsThisProcessAndItsChild +// starts as its child. +const helperEnvironment = "LITHE_SYSINFO_PROCESS_HELPER" + +// TestProcessHelper is the child: it waits until its parent closes its standard input. +func TestProcessHelper(t *testing.T) { + if os.Getenv(helperEnvironment) != "1" { + t.Skip("only runs as the child of TestProcessesListsThisProcessAndItsChild") + } + _, _ = io.Copy(io.Discard, os.Stdin) +} + +// TestProcessesListsThisProcessAndItsChild checks that the table has this process under its +// parent, with a name and memory, and a child it started under it. +func TestProcessesListsThisProcessAndItsChild(t *testing.T) { + switch runtime.GOOS { + case "darwin", "linux", "windows": + default: + t.Skip("the process table is not read on " + runtime.GOOS) + } + child := exec.Command(os.Args[0], "-test.run=^TestProcessHelper$") + child.Env = append(os.Environ(), helperEnvironment+"=1") + stdin, err := child.StdinPipe() + if err != nil { + t.Fatal(err) + } + if err := child.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = stdin.Close() + done := make(chan error, 1) + go func() { done <- child.Wait() }() + select { + case <-done: + case <-time.After(10 * time.Second): + _ = child.Process.Kill() + <-done + t.Error("the helper process did not exit within 10s of its input closing") + } + }) + + table, err := Processes() + if err != nil { + t.Fatal(err) + } + rows := map[int]Process{} + for _, row := range table { + if _, seen := rows[row.PID]; seen { + t.Fatalf("process %d is listed twice", row.PID) + } + rows[row.PID] = row + } + self, ok := rows[os.Getpid()] + if !ok { + t.Fatalf("this process %d is not in a table of %d processes", os.Getpid(), len(table)) + } + if self.ParentPID != os.Getppid() || self.Name == "" || self.MemoryBytes == 0 { + t.Fatalf("this process = %+v, want parent %d, a name and memory", self, os.Getppid()) + } + started, ok := rows[child.Process.Pid] + if !ok { + t.Fatalf("the child %d is not in the table", child.Process.Pid) + } + if started.ParentPID != os.Getpid() { + t.Fatalf("the child = %+v, want parent %d", started, os.Getpid()) + } + if self.StartTime != 0 && started.StartTime != 0 && started.StartTime < self.StartTime { + t.Fatalf("the child started at %d, before this process at %d", started.StartTime, self.StartTime) + } + if runtime.GOOS == "darwin" && self.ResponsiblePID == 0 { + t.Fatalf("this process = %+v, want a responsible process", self) + } +} diff --git a/desktop/internal/sysinfo/process_windows.go b/desktop/internal/sysinfo/process_windows.go new file mode 100644 index 0000000000..803427d1df --- /dev/null +++ b/desktop/internal/sysinfo/process_windows.go @@ -0,0 +1,87 @@ +package sysinfo + +import ( + "errors" + "unsafe" + + "golang.org/x/sys/windows" +) + +// processMemoryCountersEx2 is PROCESS_MEMORY_COUNTERS_EX2, which Windows 10 1809 and later fill. +type processMemoryCountersEx2 struct { + processMemoryCounters + privateUsage uintptr + privateWorkingSetSize uintptr + sharedCommitUsage uint64 +} + +// processes reads a Toolhelp snapshot, then each process's start time and memory. A process +// this user may not open keeps a zero start time and memory. +func processes() ([]Process, error) { + snapshot, err := windows.CreateToolhelp32Snapshot(windows.TH32CS_SNAPPROCESS, 0) + if err != nil { + return nil, err + } + defer windows.CloseHandle(snapshot) + var entry windows.ProcessEntry32 + entry.Size = uint32(unsafe.Sizeof(entry)) + var table []Process + for err = windows.Process32First(snapshot, &entry); err == nil; err = windows.Process32Next(snapshot, &entry) { + row := Process{ + PID: int(entry.ProcessID), + ParentPID: int(entry.ParentProcessID), + Name: windows.UTF16ToString(entry.ExeFile[:]), + } + row.StartTime, row.MemoryBytes = processFacts(entry.ProcessID) + table = append(table, row) + } + if !errors.Is(err, windows.ERROR_NO_MORE_FILES) { + return nil, err + } + return table, nil +} + +// processFacts is when the process of pid started, in microseconds since 1970, and its private +// working set; zero for what cannot be read. +func processFacts(pid uint32) (start, memory uint64) { + if pid == 0 { + // The System Idle Process cannot be opened. + return 0, 0 + } + // Reading the memory counters needs PROCESS_VM_READ as well; without it the start time + // is still read. + handle, err := windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION|windows.PROCESS_VM_READ, false, pid) + readMemory := err == nil + if !readMemory { + if handle, err = windows.OpenProcess(windows.PROCESS_QUERY_LIMITED_INFORMATION, false, pid); err != nil { + return 0, 0 + } + } + defer windows.CloseHandle(handle) + var creation, exit, kernel, user windows.Filetime + if windows.GetProcessTimes(handle, &creation, &exit, &kernel, &user) == nil { + start = uint64(max(0, creation.Nanoseconds()/1000)) + } + if readMemory { + memory = privateWorkingSet(handle) + } + return start, memory +} + +// privateWorkingSet is what Task Manager's Memory column shows for the process of handle. On +// a system older than Windows 10 1809 it is the whole working set. +func privateWorkingSet(handle windows.Handle) uint64 { + if getProcessMemoryInfo.Find() != nil { + return 0 + } + var counters processMemoryCountersEx2 + counters.cb = uint32(unsafe.Sizeof(counters)) + if ok, _, _ := getProcessMemoryInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&counters)), uintptr(counters.cb)); ok != 0 { + return uint64(counters.privateWorkingSetSize) + } + counters.cb = uint32(unsafe.Sizeof(counters.processMemoryCounters)) + if ok, _, _ := getProcessMemoryInfo.Call(uintptr(handle), uintptr(unsafe.Pointer(&counters)), uintptr(counters.cb)); ok != 0 { + return uint64(counters.workingSetSize) + } + return 0 +} diff --git a/desktop/internal/sysinfo/sysinfo.go b/desktop/internal/sysinfo/sysinfo.go index b84393d9ed..a0b26b8686 100644 --- a/desktop/internal/sysinfo/sysinfo.go +++ b/desktop/internal/sysinfo/sysinfo.go @@ -1,7 +1,8 @@ -// Package sysinfo reads the facts about the machine a diagnostic bundle's manifest records: -// the operating system, the processor count, how much memory the process holds and how much -// room is left on the disk of the log directory. A fact the system does not give is zero or -// empty rather than an error, so a bundle can always be made. +// Package sysinfo reads facts about the machine: what a diagnostic bundle's manifest records +// (the operating system, the processor count, how much memory the process holds and how much +// room is left on the disk of the log directory), and the process table the status bar's +// memory readout is summed from. A fact the system does not give is zero or empty rather than +// an error, so a bundle can always be made; only a table that cannot be listed at all fails. package sysinfo import "runtime" @@ -36,6 +37,3 @@ func Current(volume string) Snapshot { DiskFreeBytes: diskFree(volume), } } - -// Resident is the memory the process holds in RAM now, in bytes; zero when the system does not say. -func Resident() uint64 { return residentBytes() } diff --git a/desktop/internal/sysinfo/sysinfo_other.go b/desktop/internal/sysinfo/sysinfo_other.go index dbf9e96466..c99ccc204b 100644 --- a/desktop/internal/sysinfo/sysinfo_other.go +++ b/desktop/internal/sysinfo/sysinfo_other.go @@ -2,7 +2,10 @@ package sysinfo -import "runtime" +import ( + "errors" + "runtime" +) var osName = runtime.GOOS @@ -12,3 +15,5 @@ func Version() string { return "" } func residentBytes() uint64 { return 0 } func diskFree(string) uint64 { return 0 } + +func processes() ([]Process, error) { return nil, errors.ErrUnsupported } diff --git a/desktop/internal/workbench/app.go b/desktop/internal/workbench/app.go index 263f9ca55b..c9e837d87d 100644 --- a/desktop/internal/workbench/app.go +++ b/desktop/internal/workbench/app.go @@ -21,7 +21,6 @@ import ( "os" "path/filepath" "runtime" - "runtime/metrics" "sync" "sync/atomic" "time" @@ -88,6 +87,7 @@ type Kernel interface { debugTransportKernel debugStateKernel processExitKernel + processMemoryKernel MatchOutputLinks(context.Context, core.OutputLinkRequest) ([]core.OutputLink, error) CreateDebugSession(ctx context.Context, request core.DebugCreateSessionRequest) (core.DebugUpdate, error) LaunchDebug(ctx context.Context, sessionID, operationID string, configuration core.DebugLaunchConfiguration) (core.DebugUpdate, error) @@ -1042,8 +1042,7 @@ func (a *App) activate(index int) { a.editor.lsp.menu = !a.editor.lsp.menu } case it.id == itemMemory: - a.memory.open = !a.memory.open - a.memory.sampledAt = time.Time{} + a.toggleMemoryDetails() case it.id == itemEncoding: if a.project != nil && a.project.selectedDocument(a.project.docs.group) != nil { a.editor.encoding.open = !a.editor.encoding.open @@ -1267,19 +1266,8 @@ type statusState struct { frames []time.Time // fps is the number of paints in the second before the last paint. fps int - // memory is the memory the process's Go runtime holds, in bytes, sampled at most - // once a second. - memory uint64 - sampledAt time.Time - sample []metrics.Sample } -// memoryMetric is the memory the Go runtime has mapped and not returned to the system. -const ( - memoryMetric = "/memory/classes/total:bytes" - releasedMetric = "/memory/classes/heap/released:bytes" -) - // frame counts a paint at now. While the window paints, the count of the last second is // shown; after the last paint of a burst one more paint is asked for a second later, so // the readout settles instead of keeping the count of the burst. That paint asks for no @@ -1296,15 +1284,4 @@ func (s *statusState) frame(canvas *gfx.Canvas, now time.Time) { if s.fps > 1 { canvas.RequestFrameIn(time.Second) } - if !s.sampledAt.IsZero() && now.Sub(s.sampledAt) < time.Second { - return - } - s.sampledAt = now - if s.sample == nil { - s.sample = []metrics.Sample{{Name: memoryMetric}, {Name: releasedMetric}} - } - metrics.Read(s.sample) - if s.sample[0].Value.Kind() == metrics.KindUint64 && s.sample[1].Value.Kind() == metrics.KindUint64 { - s.memory = s.sample[0].Value.Uint64() - s.sample[1].Value.Uint64() - } } diff --git a/desktop/internal/workbench/memory_details_visual_test.go b/desktop/internal/workbench/memory_details_visual_test.go new file mode 100644 index 0000000000..c7c0e6371e --- /dev/null +++ b/desktop/internal/workbench/memory_details_visual_test.go @@ -0,0 +1,68 @@ +//go:build vivahead && lithevisual + +package workbench + +import ( + "os" + "path/filepath" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/store" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/headless" +) + +// TestVisualMemoryDetails captures the memory details above the status bar: an instance with a +// language server, system helpers and child processes, and one whose main process is all it holds. +func TestVisualMemoryDetails(t *testing.T) { + out := os.Getenv("LITHE_VISUAL_OUTPUT_DIR") + if out == "" { + t.Skip("set LITHE_VISUAL_OUTPUT_DIR") + } + if err := os.MkdirAll(out, 0755); err != nil { + t.Fatal(err) + } + only := core.MemorySummary{ + TotalBytes: 302 * mib, + Categories: []core.MemoryCategory{{Kind: core.MemoryHost, Bytes: 302 * mib, ProcessCount: 1}}, + } + for _, look := range []struct{ theme, language, empty string }{ + {"dark", "zh-Hans", "Lithe 目前没有启动其他进程。"}, + {"light", "en", "Lithe has not started any other process."}, + } { + for _, scene := range []struct { + id string + summary core.MemorySummary + shows string + }{ + {"memory-details", memorySummaryFixture(), "Quill Tools · Quill"}, + {"memory-details-host-only", only, look.empty}, + } { + t.Run(scene.id+"-"+look.theme, func(t *testing.T) { + prefs := store.At(t.TempDir()) + if err := prefs.Save(settingsFile, settings{Theme: themeChoice(look.theme), Language: look.language, DisableAutoSave: true}); err != nil { + t.Fatal(err) + } + kernel := &memoryKernel{Client: core.NewClient(), summary: scene.summary} + var session *headless.Session + h := newHarnessWithDriver(t, Options{Kernel: kernel, Store: prefs, Languages: []string{look.language}}, func(config app.Config) (*app.Driver, func(), error) { + config.Width, config.Height = 1200, 760 + var err error + session, err = headless.Open(config, nil, headless.Options{}) + if err != nil { + return nil, nil, err + } + return session.Driver(), session.Close, nil + }) + h.open(t.TempDir()) + h.await("the first reading", func() bool { return h.app.memory.read }) + openMemoryDetails(h, scene.shows) + h.settleChain() + if err := session.Screenshot(filepath.Join(out, scene.id+"-"+look.theme+".png")); err != nil { + t.Fatal(err) + } + }) + } + } +} diff --git a/desktop/internal/workbench/memory_monitor.go b/desktop/internal/workbench/memory_monitor.go index d71f00695a..8fc2ff4e65 100644 --- a/desktop/internal/workbench/memory_monitor.go +++ b/desktop/internal/workbench/memory_monitor.go @@ -2,86 +2,147 @@ package workbench import ( "context" + "os" "runtime" - "sort" "strconv" + "strings" "time" + "github.com/1lck/Lithe-IDEA/desktop/internal/core" "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" "github.com/1lck/Lithe-IDEA/desktop/internal/icons" - "github.com/1lck/Lithe-IDEA/desktop/internal/pluginservice" + "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" "github.com/1lck/Lithe-IDEA/desktop/internal/sysinfo" + "github.com/vivaui/viva/components" "github.com/vivaui/viva/gfx" "github.com/vivaui/viva/ui" ) -// The memory monitor reads what Lithe and the processes it started hold: Lithe's own resident -// memory, the language servers and the plugin backends (each with its child processes). The -// status bar item shows the total; on macOS it is only a chip icon, as the earlier client had, -// with the figures in its tooltip. A click opens the details, which are sampled more often -// while they are shown. Sampling runs in the background and a failure only leaves the figures -// out: it never holds up the window. +// The memory monitor shows what this Lithe instance holds: the main process and every process +// that belongs to it, which Core picks out of the system's process table and sums by part +// (processMemory.summarize). The window only reads the table and names the processes it +// started: the language servers and the plugin services. The status bar item shows the total; +// on macOS it is only a chip icon, as the earlier client had, with the figures in its tooltip. +// A click opens the details, which are read more often while they are shown. Reading runs in +// the background and a failure only leaves the figures out: it never holds up the window. const ( // memorySampleInterval is how often the processes are read while the details are shut, - // and memoryDetailInterval while they are open. + // and memoryDetailInterval while they are open. A reading only starts from a paint of the + // status item, so a window that does not paint does not read. memorySampleInterval = 10 * time.Second memoryDetailInterval = 2 * time.Second memorySampleTimeout = 5 * time.Second + + memoryPanelWidth = 340 + memoryListHeight = 220 + memoryBarHeight = 6 + memoryBarGap = 2 + memoryDotSize = 8 + memoryRowHeight = 22 + memoryHeaderGap = 6 + memorySectionGap = 10 ) -// memoryProcess is one process tree Lithe started, as the details list it. -type memoryProcess struct { - name string - kind memoryKind - bytes uint64 +// processMemoryKernel is the Core command the memory monitor asks. +type processMemoryKernel interface { + SummarizeProcessMemory(ctx context.Context, request core.MemoryRequest) (core.MemorySummary, error) } -type memoryKind int - -const ( - memoryLanguageServer memoryKind = iota - memoryPluginBackend -) - // memoryState is the last reading. type memoryState struct { open bool sampling bool sampledAt time.Time - lithe uint64 - processes []memoryProcess - // read is true once a reading of the other processes arrived. - read bool -} - -// sums is the language-server and plugin-backend totals of the reading. -func (m *memoryState) sums() (servers, backends uint64) { - for _, process := range m.processes { - if process.kind == memoryLanguageServer { - servers += process.bytes - } else { - backends += process.bytes + // summary is the last reading Core summed; read is true once one arrived and failed while + // the last one failed, which hides the figures rather than leaving stale ones. + summary core.MemorySummary + read bool + failed bool + // names are the display names of the installed plugins, read as the details open; nil + // until then, which names a process by its plugin ID. + names *memoryNames +} + +// memoryNames are the display names the details give the processes started for plugins. +type memoryNames struct { + // plugins maps a plugin ID to its manifest's name. + plugins map[string]string + // languages maps a plugin ID and a language ID to the title the plugin declares. + languages map[[2]string]string +} + +// memoryNamesOf collects the names of the installed plugins and of their language servers. +func memoryNamesOf(facts []settingswindow.PluginFacts) *memoryNames { + names := &memoryNames{plugins: map[string]string{}, languages: map[[2]string]string{}} + for _, item := range facts { + names.plugins[item.ID] = pluginFactsName(item) + for _, capability := range item.Capabilities { + if capability.Kind == settingswindow.CapabilityLanguageServer && capability.Title != "" { + names.languages[[2]string{item.ID, capability.ID}] = capability.Title + } } } - return servers, backends + return names } -// total is Lithe and every process it started. -func (m *memoryState) total() uint64 { - servers, backends := m.sums() - return m.lithe + servers + backends +// plugin is the name of the plugin with the ID, or the ID when its manifest was not read. +func (n *memoryNames) plugin(id string) string { + if n != nil && n.plugins[id] != "" { + return n.plugins[id] + } + return id } -// memoryTarget is a process tree to read: the pid Core reported and how to name it. -type memoryTarget struct { - pid int - name string - kind memoryKind +// languageServer names the language server a plugin started for a language: the plugin, then +// the language unless the plugin's name already is the language's. +func (n *memoryNames) languageServer(language i18n.Language, pluginID, languageID string) string { + name := n.plugin(pluginID) + if languageID == "" { + return name + } + title := languageID + if n != nil && n.languages[[2]string{pluginID, languageID}] != "" { + title = n.languages[[2]string{pluginID, languageID}] + } + if strings.EqualFold(title, name) { + return name + } + return i18n.SharedFormat(language, "desktop.memory.languageServer", map[string]string{"plugin": name, "language": title}) +} + +// toggleMemoryDetails opens or shuts the details. Opening them reads at once and reads the +// plugin names again, so a plugin installed since is named. +func (a *App) toggleMemoryDetails() { + m := &a.memory + m.open = !m.open + m.sampledAt = time.Time{} + if m.open { + a.readMemoryNames() + } +} + +// readMemoryNames reads the installed plugins' manifests in the background for the names of +// the processes started for them, then reads the memory again with those names. +func (a *App) readMemoryNames() { + if a.plugins == nil { + return + } + a.background(nil, pluginStateTimeout, func(ctx context.Context) func(*App) { + entries, err := a.plugins.CurrentInstalled(ctx) + names := memoryNamesOf(installedPluginFacts(entries, nil)) + return func(a *App) { + if err != nil { + a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("memory_plugin_names", err)) + } + a.memory.names = names + a.memory.sampledAt = time.Time{} + } + }) } -// sampleMemory starts a background reading when the last one is old enough. It is called on -// every paint; the status sampling already limits paints that reach it to about one a second. +// sampleMemory starts a background reading when the last one is old enough. The status item +// calls it as it is declared, so a hidden item reads nothing. func (a *App) sampleMemory(now time.Time) { m := &a.memory interval := memorySampleInterval @@ -92,85 +153,151 @@ func (a *App) sampleMemory(now time.Time) { return } m.sampling, m.sampledAt = true, now - targets := a.memoryTargets() - go func() { - ctx, cancel := context.WithTimeout(context.Background(), memorySampleTimeout) - defer cancel() - lithe := sysinfo.Resident() - pids := make([]int, 0, len(targets)) - for _, target := range targets { - pids = append(pids, target.pid) + roles := a.memoryRoles() + host := int64(os.Getpid()) + kernel := a.kernel + a.background(nil, memorySampleTimeout, func(ctx context.Context) func(*App) { + summary, err := readProcessMemory(ctx, kernel, host, roles) + return func(a *App) { a.memorySampled(summary, err) } + }) +} + +// memorySampled keeps a reading. Only the first failure after a reading is logged, so a +// table that cannot be read is not logged every few seconds. +func (a *App) memorySampled(summary core.MemorySummary, err error) { + m := &a.memory + m.sampling = false + if err != nil { + if !m.failed { + a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("memory_sample", err)) } - read := pluginservice.SampleProcessMemory(ctx, pids) - processes := make([]memoryProcess, 0, len(targets)) - for _, target := range targets { - if bytes, ok := read[target.pid]; ok { - processes = append(processes, memoryProcess{name: target.name, kind: target.kind, bytes: bytes}) - } + m.failed = true + return + } + m.summary, m.read, m.failed = summary, true, false +} + +// readProcessMemory reads the process table and has Core sum what the instance of host holds. +func readProcessMemory(ctx context.Context, kernel processMemoryKernel, host int64, roles []core.MemoryRole) (core.MemorySummary, error) { + table, err := sysinfo.Processes() + if err != nil { + return core.MemorySummary{}, err + } + processes := make([]core.MemoryProcess, 0, len(table)) + for _, row := range table { + process := core.MemoryProcess{ + ProcessID: int64(row.PID), + ParentProcessID: int64(row.ParentPID), + Name: row.Name, + Bytes: row.MemoryBytes, } - sort.SliceStable(processes, func(i, j int) bool { return processes[i].bytes > processes[j].bytes }) - a.post(func(a *App) { - m := &a.memory - m.sampling = false - m.lithe, m.processes, m.read = lithe, processes, read != nil || len(targets) == 0 - }) - }() + // A zero is a fact the system did not give, which the request leaves out. + if row.ResponsiblePID != 0 { + responsible := int64(row.ResponsiblePID) + process.ResponsibleProcessID = &responsible + } + if row.StartTime != 0 { + start := row.StartTime + process.StartTime = &start + } + processes = append(processes, process) + } + return kernel.SummarizeProcessMemory(ctx, core.MemoryRequest{HostProcessID: host, Processes: processes, Roles: roles}) } -// memoryTargets lists the language servers and plugin backends that are running with a pid. -func (a *App) memoryTargets() []memoryTarget { - var targets []memoryTarget +// memoryRoles names the processes this window started: each language server and each plugin +// service that runs with a process ID. +func (a *App) memoryRoles() []core.MemoryRole { + language := a.language() + names := a.memory.names + var roles []core.MemoryRole for _, server := range a.lspServers() { if pid := server.session.Session.ProcessID; pid > 0 { - name := server.session.PluginID - if server.session.LanguageID != "" { - name += " (" + server.session.LanguageID + ")" - } - targets = append(targets, memoryTarget{pid: pid, name: name, kind: memoryLanguageServer}) + roles = append(roles, core.MemoryRole{ + ProcessID: int64(pid), + Kind: core.MemoryRoleLanguageServer, + Name: names.languageServer(language, server.session.PluginID, server.session.LanguageID), + }) } } if a.plugins != nil && a.plugins.Host != nil { for _, id := range a.plugins.Host.RunningPlugins() { if session := a.plugins.Host.Running(id); session != nil && session.Session.ProcessID > 0 { - targets = append(targets, memoryTarget{pid: session.Session.ProcessID, name: id, kind: memoryPluginBackend}) + roles = append(roles, core.MemoryRole{ + ProcessID: int64(session.Session.ProcessID), + Kind: core.MemoryRolePluginService, + Name: names.plugin(id), + }) } } } - return targets + return roles +} + +// memorySize writes bytes as the monitor shows them: whole megabytes below a gigabyte, then +// gigabytes with two decimals below ten and one above. Both are binary units, as Activity +// Monitor and Task Manager count; a process that holds less than a megabyte is not shown as 0. +func memorySize(language i18n.Language, bytes uint64) string { + const megabyte, gigabyte = 1 << 20, 1 << 30 + if bytes > 0 && bytes < megabyte { + return i18n.Shared(language, "desktop.memory.belowMegabyte") + } + if rounded := (bytes + megabyte/2) / megabyte; rounded < 1024 { + return i18n.SharedFormat(language, "desktop.memory.megabytes", map[string]string{"value": strconv.FormatUint(rounded, 10)}) + } + gigabytes := float64(bytes) / gigabyte + decimals := 2 + if gigabytes >= 9.995 { + decimals = 1 + } + return i18n.SharedFormat(language, "desktop.memory.gigabytes", map[string]string{"value": strconv.FormatFloat(gigabytes, 'f', decimals, 64)}) } -// memoryStatusText is the status bar readout: the total and Lithe's share, or Lithe alone before -// the first reading. macOS shows the icon instead. +// category is the reading's sum of one part. +func (m *memoryState) category(kind string) core.MemoryCategory { + for _, category := range m.summary.Categories { + if category.Kind == kind { + return category + } + } + return core.MemoryCategory{Kind: kind} +} + +// shown is true when the figures of the last reading can be shown. +func (m *memoryState) shown() bool { return m.read && !m.failed } + +// memoryStatusText is the status bar readout: the total and the main process's share, or the +// item's name while there is no reading. macOS shows the icon instead. func (a *App) memoryStatusText() string { m := &a.memory - lithe := m.lithe - if lithe == 0 { - lithe = a.status.memory - } - if !m.read { - return a.text.Status.MemoryValue(int(lithe >> 20)) + if !m.shown() { + return a.text.Status.Memory } - return i18n.SharedFormat(a.language(), "desktop.memory.status", map[string]string{ - "total": megabytes(m.total()), "lithe": megabytes(lithe), + language := a.language() + return i18n.SharedFormat(language, "desktop.memory.status", map[string]string{ + "total": memorySize(language, m.summary.TotalBytes), "lithe": memorySize(language, m.category(core.MemoryHost).Bytes), }) } -// memoryTooltip is the breakdown the status item's tooltip and accessibility value give. +// memoryTooltip is what the status item's tooltip and accessibility value give. func (a *App) memoryTooltip() string { m := &a.memory - servers, backends := m.sums() - return i18n.SharedFormat(a.language(), "desktop.memory.tooltip", map[string]string{ - "total": megabytes(m.total()), "lithe": megabytes(m.lithe), "lsp": megabytes(servers), "services": megabytes(backends), + if !m.shown() { + return a.text.Status.Memory + } + language := a.language() + return i18n.SharedFormat(language, "desktop.memory.tooltip", map[string]string{ + "total": memorySize(language, m.summary.TotalBytes), "lithe": memorySize(language, m.category(core.MemoryHost).Bytes), }) } // memoryShowsIcon is true where the status item is the chip icon alone. func memoryShowsIcon() bool { return runtime.GOOS == "darwin" } -func megabytes(bytes uint64) string { return strconv.FormatUint(bytes>>20, 10) } - -// memoryStatusItem declares the status item's content: the chip icon on macOS, the readout elsewhere. +// memoryStatusItem declares the status item's content, the chip icon on macOS and the readout +// elsewhere, and reads the memory when the last reading is old enough. func (a *App) memoryStatusItem(c ui.C) { + a.sampleMemory(a.now()) if memoryShowsIcon() { ui.Icon(c, icons.Cpu).Size(chromeMarkSize, chromeMarkSize).Color(a.colors.Subtle) return @@ -178,7 +305,66 @@ func (a *App) memoryStatusItem(c ui.C) { a.chromeStatusLabel(c, a.memoryStatusText()) } -// memoryDetails is the popover the status item opens: the totals and every process Lithe started. +// memoryKindLabel names a part of the instance. +func memoryKindLabel(language i18n.Language, kind string) string { + switch kind { + case core.MemoryHost: + return i18n.Shared(language, "desktop.memory.host") + case core.MemoryLanguageServer: + return i18n.Shared(language, "desktop.memory.languageServers") + case core.MemoryPluginService: + return i18n.Shared(language, "desktop.memory.services") + case core.MemorySystemHelper: + return i18n.Shared(language, "desktop.memory.systemHelpers") + } + return i18n.Shared(language, "desktop.memory.childProcesses") +} + +// memoryColor is the color that marks a part in the bar, the legend and the list. No part +// is red, which would read as a fault; the system helpers take the purple of IDEA's expUI. +func (a *App) memoryColor(kind string) gfx.Color { + switch kind { + case core.MemoryHost: + return a.colors.Accent + case core.MemoryLanguageServer: + return a.colors.Success + case core.MemoryPluginService: + return a.colors.Warning + case core.MemorySystemHelper: + return pick(a.colors.Dark, 0xB589EC, 0x834DF0) + } + return a.colors.Subtle +} + +// memoryHelp is the explanation behind the details' ⓘ: what is counted, and which figure the +// system gives for each process. +func memoryHelp(language i18n.Language) string { + help := i18n.Shared(language, "desktop.memory.help") + switch runtime.GOOS { + case "darwin": + help += "\n\n" + i18n.Shared(language, "desktop.memory.helpMacOS") + case "windows": + help += "\n\n" + i18n.Shared(language, "desktop.memory.helpWindows") + case "linux": + help += "\n\n" + i18n.Shared(language, "desktop.memory.helpLinux") + } + return help +} + +// memoryParts are the parts the details show: the main process always, the others while they +// hold something. +func (m *memoryState) parts() []core.MemoryCategory { + parts := make([]core.MemoryCategory, 0, len(m.summary.Categories)) + for _, category := range m.summary.Categories { + if category.Kind == core.MemoryHost || category.Bytes > 0 || category.ProcessCount > 0 { + parts = append(parts, category) + } + } + return parts +} + +// memoryDetails is the popover the status item opens: the total, a bar of the parts and their +// sums, then the largest processes of the instance other than the main one. func (a *App) memoryDetails(c ui.C, anchor ui.Box) { m := &a.memory if !m.open { @@ -187,38 +373,96 @@ func (a *App) memoryDetails(c ui.C, anchor ui.Box) { // The details refresh on their own: the next paint takes the next reading. c.Canvas().RequestFrameIn(memoryDetailInterval) language := a.language() - ui.Popover(c.Key("memoryDetails"), anchor, &m.open, func() { - ui.Column(c).Gap(6).MinWidth(300).Children(func() { - ui.Text(c, i18n.Shared(language, "desktop.memory.title")).FontSize(13).Weight(gfx.WeightSemibold) - servers, backends := m.sums() - row := func(label string, bytes uint64, strong bool) { - ui.Row(c).FillWidth().Items(ui.Center).Gap(12).Children(func() { - text := ui.Text(c, label).Grow(1).Shrink(1).MinWidth(0).FontSize(12).Ellipsis() - value := ui.Text(c, i18n.SharedFormat(language, "desktop.memory.value", map[string]string{"value": megabytes(bytes)})).FontSize(12).Shrink(0) - if strong { - text.Weight(gfx.WeightSemibold) - value.Weight(gfx.WeightSemibold) - } else { - text.Color(a.colors.Subtle) - } - }) - } - row(i18n.Shared(language, "desktop.memory.total"), m.total(), true) - row(i18n.Shared(language, "desktop.memory.lithe"), m.lithe, false) - row(i18n.Shared(language, "desktop.memory.languageServers"), servers, false) - row(i18n.Shared(language, "desktop.memory.services"), backends, false) - if len(m.processes) == 0 { - ui.Text(c, i18n.Shared(language, "desktop.memory.noProcesses")).FontSize(12).Color(a.colors.Subtle) - return - } - ui.Row(c).FillWidth().Height(1).Background(a.colors.Line) - for _, process := range m.processes { - kind := i18n.Shared(language, "desktop.memory.kindServer") - if process.kind == memoryPluginBackend { - kind = i18n.Shared(language, "desktop.memory.kindService") - } - row(process.name+" · "+kind, process.bytes, false) + spec := ui.PopoverSpec{Side: components.PopoverTop, Align: ui.End, Offset: chromeMenuOffset, Width: memoryPanelWidth, ConsumeOutsidePress: true} + ui.PopoverWith(c.Key("memoryDetails"), anchor, spec, &m.open, func() { + ui.Column(c).FillWidth().Gap(memorySectionGap).Children(func() { + a.memoryHeader(c, language) + switch { + case m.failed: + ui.Text(c, i18n.Shared(language, "desktop.memory.unavailable")).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + case !m.read: + ui.Text(c, i18n.Shared(language, "desktop.memory.reading")).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + default: + parts := m.parts() + a.memoryBar(c.Part("bar"), parts) + a.memoryLegend(c.Part("legend"), language, parts) + ui.Divider(c) + a.memoryEntries(c.Part("entries"), language) } }) }) } + +// memoryHeader declares the details' title, the ⓘ with what is counted, and the total. +func (a *App) memoryHeader(c ui.C, language i18n.Language) { + m := &a.memory + ui.Row(c).FillWidth().Height(28).Items(ui.Center).Gap(memoryHeaderGap).Children(func() { + ui.Text(c, i18n.Shared(language, "desktop.memory.title")).Weight(gfx.WeightSemibold).Shrink(0) + ui.Button(c.Part("help"), i18n.Shared(language, "native.moreInformation")).Icon(icons.Info).IconOnly().Ghost().Size(18, 18). + Tooltip(memoryHelp(language)) + ui.Row(c).Grow(1) + if m.shown() { + ui.Text(c, memorySize(language, m.summary.TotalBytes)).Weight(gfx.WeightSemibold).Shrink(0) + } + }) +} + +// memoryBar declares the parts side by side, each as wide as its share of the total. +func (a *App) memoryBar(c ui.C, parts []core.MemoryCategory) { + total := a.memory.summary.TotalBytes + ui.Row(c).FillWidth().Height(memoryBarHeight).Gap(memoryBarGap).Children(func() { + for i, part := range parts { + if part.Bytes == 0 || total == 0 { + continue + } + ui.Row(c.KeyInt(i)).Basis(0).Grow(float32(float64(part.Bytes) / float64(total))).MinWidth(memoryBarHeight). + Height(memoryBarHeight).Radius(memoryBarHeight / 2).Background(a.memoryColor(part.Kind)) + } + }) +} + +// memoryLegend declares one row per part: its color, name, process count and sum. +func (a *App) memoryLegend(c ui.C, language i18n.Language, parts []core.MemoryCategory) { + ui.Column(c).FillWidth().Children(func() { + for i, part := range parts { + a.memoryRow(c.KeyInt(i), language, part.Kind, memoryKindLabel(language, part.Kind), part.ProcessCount, part.Bytes) + } + }) +} + +// memoryEntries declares the largest processes of the instance other than the main one, each +// with what Core counts under it, and the sum of the ones past the list. +func (a *App) memoryEntries(c ui.C, language i18n.Language) { + summary := &a.memory.summary + ui.Text(c, i18n.Shared(language, "desktop.memory.processes")).FontSize(a.theme.Metrics.FontSizeS).Weight(gfx.WeightSemibold).Color(a.colors.Subtle) + if len(summary.Entries) == 0 { + ui.Text(c, i18n.Shared(language, "desktop.memory.noOtherProcesses")).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + return + } + ui.Scroll(c.Part("list")).FillWidth().MaxHeight(memoryListHeight).Children(func() { + for i, entry := range summary.Entries { + a.memoryRow(c.KeyInt(i), language, entry.Kind, entry.Name, entry.ProcessCount, entry.Bytes) + } + }) + if summary.Omitted.Count > 0 { + ui.Text(c, i18n.SharedFormat(language, "desktop.memory.omitted", map[string]string{ + "count": strconv.Itoa(summary.Omitted.Count), "value": memorySize(language, summary.Omitted.Bytes), + })).FontSize(a.theme.Metrics.FontSizeS).Color(a.colors.Subtle) + } +} + +// memoryRow declares a row of the legend or the list: the part's dot, the name, how many +// processes it sums when more than one, and the size at the end. +func (a *App) memoryRow(k ui.C, language i18n.Language, kind, name string, processes int, bytes uint64) { + small := a.theme.Metrics.FontSizeS + ui.Row(k).FillWidth().Height(memoryRowHeight).Shrink(0).Items(ui.Center).Gap(8).Children(func() { + ui.Row(k).Size(memoryDotSize, memoryDotSize).Shrink(0).Radius(memoryDotSize / 2).Background(a.memoryColor(kind)) + ui.Text(k, name).FontSize(small).Shrink(1).MinWidth(0).Ellipsis() + if processes > 1 { + ui.Text(k, i18n.SharedFormat(language, "desktop.memory.processCount", map[string]string{"count": strconv.Itoa(processes)})). + FontSize(small).Color(a.colors.Subtle).Shrink(0) + } + ui.Row(k).Grow(1) + ui.Text(k, memorySize(language, bytes)).FontSize(small).Shrink(0) + }) +} diff --git a/desktop/internal/workbench/memory_monitor_test.go b/desktop/internal/workbench/memory_monitor_test.go new file mode 100644 index 0000000000..a4e2906716 --- /dev/null +++ b/desktop/internal/workbench/memory_monitor_test.go @@ -0,0 +1,210 @@ +package workbench + +import ( + "context" + "errors" + "os" + "sync" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/settingswindow" +) + +// memoryKernel answers processMemory.summarize with the summary or the error the test chose and +// keeps the requests the window sent. +type memoryKernel struct { + *core.Client + mu sync.Mutex + requests []core.MemoryRequest + summary core.MemorySummary + err error +} + +func (k *memoryKernel) SummarizeProcessMemory(_ context.Context, request core.MemoryRequest) (core.MemorySummary, error) { + k.mu.Lock() + defer k.mu.Unlock() + k.requests = append(k.requests, request) + return k.summary, k.err +} + +// answer sets what the next requests are answered. +func (k *memoryKernel) answer(summary core.MemorySummary, err error) { + k.mu.Lock() + defer k.mu.Unlock() + k.summary, k.err = summary, err +} + +// last is the last request the window sent, and how many it sent. +func (k *memoryKernel) last() (core.MemoryRequest, int) { + k.mu.Lock() + defer k.mu.Unlock() + if len(k.requests) == 0 { + return core.MemoryRequest{}, 0 + } + return k.requests[len(k.requests)-1], len(k.requests) +} + +const mib = 1 << 20 + +// memorySummaryFixture is an instance with a main process, two language-server processes, +// three system helpers and no plugin service, of which the list shows three entries and sums +// two more. +func memorySummaryFixture() core.MemorySummary { + return core.MemorySummary{ + TotalBytes: 1536 * mib, + Categories: []core.MemoryCategory{ + {Kind: core.MemoryHost, Bytes: 302 * mib, ProcessCount: 1}, + {Kind: core.MemoryLanguageServer, Bytes: 1012 * mib, ProcessCount: 2}, + {Kind: core.MemoryPluginService}, + {Kind: core.MemorySystemHelper, Bytes: 210 * mib, ProcessCount: 3}, + {Kind: core.MemoryChildProcess, Bytes: 12 * mib, ProcessCount: 2}, + }, + Entries: []core.MemoryEntry{ + {Kind: core.MemoryLanguageServer, Name: "Quill Tools · Quill", ProcessID: 41, Bytes: 1012 * mib, ProcessCount: 2}, + {Kind: core.MemorySystemHelper, Name: "PageRenderer", ProcessID: 52, Bytes: 180 * mib, ProcessCount: 1}, + {Kind: core.MemorySystemHelper, Name: "PageNetwork", ProcessID: 53, Bytes: 30 * mib, ProcessCount: 2}, + }, + Omitted: core.MemoryOmitted{Count: 2, Bytes: 12 * mib}, + } +} + +// openMemoryDetails clicks the status item and waits until the details show want. +func openMemoryDetails(h *harness, want string) { + h.t.Helper() + item := center(h.button(itemMemory)) + if err := h.driver.Click(item.X, item.Y); err != nil { + h.t.Fatal(err) + } + h.await("the memory details", func() bool { return h.app.memory.open && h.shows(want) }) +} + +// TestMemoryDetailsShowTheSummaryOfTheWholeInstance checks that the window sends Core the +// process table with itself as the host, and that the details show Core's sums: the total, every +// part that holds something with its process count, the largest entries and the rest summed. +func TestMemoryDetailsShowTheSummaryOfTheWholeInstance(t *testing.T) { + kernel := &memoryKernel{Client: core.NewClient(), summary: memorySummaryFixture()} + h := newHarness(t, kernel) + h.open(t.TempDir()) + h.await("the first reading", func() bool { return h.app.memory.read }) + + request, sent := kernel.last() + if sent == 0 { + t.Fatal("the status item did not read the memory") + } + if request.HostProcessID != int64(os.Getpid()) { + t.Fatalf("host = %d, want this process %d", request.HostProcessID, os.Getpid()) + } + host := false + for _, process := range request.Processes { + if process.ProcessID == request.HostProcessID { + host = process.Bytes > 0 && process.Name != "" + } + } + if !host { + t.Fatalf("the table of %d processes has no named row with memory for the host", len(request.Processes)) + } + if got, want := h.app.memoryTooltip(), "内存:共 1.50 GB,其中 Lithe 主进程 302 MB。"; got != want { + t.Fatalf("tooltip = %q, want %q", got, want) + } + + openMemoryDetails(h, "Quill Tools · Quill") + for _, want := range []string{ + "1.50 GB", "Lithe 主进程", "302 MB", "语言服务器", "1012 MB", "系统辅助进程", "3 个进程", "210 MB", + "其他子进程", "PageRenderer", "180 MB", "PageNetwork", "另有 2 项,共 12 MB", + } { + if !h.shows(want) { + t.Errorf("the details do not show %q", want) + } + } + if h.shows("插件服务") { + t.Error("the details show the plugin services, which hold nothing") + } + if _, after := kernel.last(); after <= sent { + t.Fatalf("opening the details sent %d requests in all, want a reading beyond the first %d", after, sent) + } +} + +// TestMemoryDetailsHideTheFiguresWhileTheReadingFails checks that a failed reading hides the +// figures instead of keeping stale ones, and that the next reading shows them again. +func TestMemoryDetailsHideTheFiguresWhileTheReadingFails(t *testing.T) { + kernel := &memoryKernel{Client: core.NewClient(), err: errors.New("the table could not be read")} + h := newHarness(t, kernel) + h.open(t.TempDir()) + + openMemoryDetails(h, "无法读取进程内存。") + if h.shows("1.50 GB") || h.app.memoryStatusText() != h.app.text.Status.Memory { + t.Fatalf("a failed reading shows figures: status %q", h.app.memoryStatusText()) + } + + kernel.answer(core.MemorySummary{ + TotalBytes: 302 * mib, + Categories: []core.MemoryCategory{{Kind: core.MemoryHost, Bytes: 302 * mib, ProcessCount: 1}}, + }, nil) + // The next paint reads again without waiting for the interval. + h.app.post(func(a *App) { a.memory.sampledAt = time.Time{} }) + h.await("a reading after the failure", func() bool { return h.shows("Lithe 目前没有启动其他进程。") }) + if h.shows("无法读取进程内存。") || !h.shows("302 MB") { + t.Fatal("the details do not show the reading that followed the failure") + } +} + +// TestMemorySizeWritesWholeMegabytesThenGigabytes checks the units: a process that holds a little +// is not 0 MB, megabytes round, and a gigabyte or more has two decimals below ten. +func TestMemorySizeWritesWholeMegabytesThenGigabytes(t *testing.T) { + for _, test := range []struct { + bytes uint64 + want string + }{ + {0, "0 MB"}, + {1, "< 1 MB"}, + {mib - 1, "< 1 MB"}, + {mib, "1 MB"}, + {302*mib + mib/2, "303 MB"}, + {1023 * mib, "1023 MB"}, + {1024*mib - mib/2, "1.00 GB"}, + {1536 * mib, "1.50 GB"}, + {10189 * mib, "9.95 GB"}, + {10240 * mib, "10.0 GB"}, + {30 * 1024 * mib, "30.0 GB"}, + } { + if got := memorySize(i18n.English, test.bytes); got != test.want { + t.Errorf("memorySize(%d) = %q, want %q", test.bytes, got, test.want) + } + } +} + +// TestMemoryNamesNameTheProcessesStartedForPlugins checks that a language server is named by its +// plugin and its language, once when they are the same, and by the IDs before the manifests are read. +func TestMemoryNamesNameTheProcessesStartedForPlugins(t *testing.T) { + names := memoryNamesOf([]settingswindow.PluginFacts{ + {ID: "io.example.quill", Name: "Quill Tools", Capabilities: []settingswindow.PluginCapability{ + {Kind: settingswindow.CapabilityLanguageServer, ID: "quill", Title: "Quill"}, + {Kind: settingswindow.CapabilityBuildSystem, ID: "quill-build", Title: "Quill Build"}, + }}, + {ID: "io.example.ink", Name: "Ink", Capabilities: []settingswindow.PluginCapability{ + {Kind: settingswindow.CapabilityLanguageServer, ID: "ink", Title: "Ink"}, + }}, + {ID: "io.example.unread"}, + }) + for _, test := range []struct { + names *memoryNames + plugin, language string + wantServer, wantID string + }{ + {names, "io.example.quill", "quill", "Quill Tools · Quill", "Quill Tools"}, + {names, "io.example.ink", "ink", "Ink", "Ink"}, + {names, "io.example.quill", "", "Quill Tools", "Quill Tools"}, + {names, "io.example.unread", "paper", "io.example.unread · paper", "io.example.unread"}, + {nil, "io.example.quill", "quill", "io.example.quill · quill", "io.example.quill"}, + } { + if got := test.names.languageServer(i18n.English, test.plugin, test.language); got != test.wantServer { + t.Errorf("languageServer(%s, %s) = %q, want %q", test.plugin, test.language, got, test.wantServer) + } + if got := test.names.plugin(test.plugin); got != test.wantID { + t.Errorf("plugin(%s) = %q, want %q", test.plugin, got, test.wantID) + } + } +} diff --git a/desktop/internal/workbench/root.go b/desktop/internal/workbench/root.go index c82d69fe0a..61fc19320c 100644 --- a/desktop/internal/workbench/root.go +++ b/desktop/internal/workbench/root.go @@ -114,12 +114,12 @@ func (a *App) sessionConfig() app.Config { // beginPaint settles the look of the paint about to be declared and forgets what the last // paint declared that this one declares afresh. func (a *App) beginPaint(canvas *gfx.Canvas) { + a.wakeForEarlyResults() a.applyLook(a.settings.Theme) a.rememberWindowBackground(a.colors.Ground) a.shared.text.Store(a.text) a.shared.dark.Store(a.colors.Dark) a.status.frame(canvas, a.now()) - a.sampleMemory(a.now()) a.chrome.beginFrame() a.beginTerminalFrame() if a.clone.open || a.newProject.open { diff --git a/desktop/internal/workbench/tasks.go b/desktop/internal/workbench/tasks.go index 4f49bfab91..99d8baada9 100644 --- a/desktop/internal/workbench/tasks.go +++ b/desktop/internal/workbench/tasks.go @@ -14,6 +14,9 @@ type taskQueue struct { mu sync.Mutex pending []func(*App) running sync.WaitGroup + // painted is set by the first paint, which asks for the wake that results posted before + // the window opened lost (wakeForEarlyResults). The window thread alone reads and sets it. + painted bool } // post queues a result and wakes the window. @@ -24,6 +27,24 @@ func (a *App) post(apply func(*App)) { a.invalidator.Invalidate() } +// wakeForEarlyResults asks for a wake when the first paint finds results queued. The window +// binds its Invalidator when it opens and drops a wake asked for before that, so a result that +// work started in New posts early (restoreBackground decodes the saved background there) would +// wait for an unrelated wake. The first paint runs once the window is bound; a result posted +// after it wakes the window itself. +func (a *App) wakeForEarlyResults() { + if a.tasks.painted { + return + } + a.tasks.painted = true + a.tasks.mu.Lock() + queued := len(a.tasks.pending) > 0 + a.tasks.mu.Unlock() + if queued { + a.invalidator.Invalidate() + } +} + // drain applies the queued results on the window thread, then takes in the output the // project's shell produced. It is the window's OnWake, which runs before every repaint a // wake asks for, so output reaches the screen without a timer. diff --git a/desktop/internal/workbench/workbench_background_test.go b/desktop/internal/workbench/workbench_background_test.go index 50cdc54b09..7243a7f381 100644 --- a/desktop/internal/workbench/workbench_background_test.go +++ b/desktop/internal/workbench/workbench_background_test.go @@ -377,6 +377,33 @@ func TestMissingBackgroundCopyShowsNoImageQuietly(t *testing.T) { } } +// The restore New starts can post its result before the window binds its wake, which the +// window then never gets: the first paint asks for one, so the result is applied all the same. +func TestBackgroundRestoredBeforeTheWindowOpensIsApplied(t *testing.T) { + dir := t.TempDir() + saved := `{"theme":"dark","workbenchBackground":{"name":"gone.png"}}` + if err := os.WriteFile(filepath.Join(dir, settingsFile), []byte(saved), 0o600); err != nil { + t.Fatal(err) + } + a := New(Options{Kernel: &testKernel{Client: core.NewClient()}, Store: store.At(dir), Languages: []string{"zh-Hans"}}) + // The restore has posted before any window exists, so the wake it asked for was dropped. + a.wait() + driver, err := app.NewDriver(a.Config(), nil) + if err != nil { + t.Fatalf("NewDriver: %v", err) + } + t.Cleanup(func() { + a.wait() + driver.Close() + }) + if err := driver.Pump(); err != nil { + t.Fatalf("Pump: %v", err) + } + if shown := a.backgroundSnapshot(a.language()); shown.Set || shown.Loading { + t.Fatalf("background restored before the window opened = %+v, want it applied and switched off", shown) + } +} + // A choice whose copy cannot be written is told and leaves the last image shown and kept: the // shown image is replaced only once its copy is written. func TestBackgroundWhoseCopyCannotBeWrittenLeavesTheLastImage(t *testing.T) { diff --git a/docs/assets/memory-details/README.md b/docs/assets/memory-details/README.md new file mode 100644 index 0000000000..b71ad1c796 --- /dev/null +++ b/docs/assets/memory-details/README.md @@ -0,0 +1,14 @@ +# 状态栏内存详情测试截图 + +来自生产 Viva Page 的无头渲染,使用隔离的临时项目和配置。内存汇总由测试直接注入(虚构的 +Quill Tools 语言服务器和系统辅助进程),不代表真实进程的读数。深色使用中文、浅色使用英文。 +截图不代表 macOS/Windows 原生窗口验收。 + +| 场景 | 深色中文 | 浅色英文 | +| --- | --- | --- | +| 实例启动了语言服务器、系统辅助进程和其他子进程:顶部是总量和 ⓘ 说明,下面是按类别堆叠的条、各类别图例(多个进程时显示进程数),以及占用最多的进程和其余项的合计 | [截图](memory-details-dark.png) | [截图](memory-details-light.png) | +| 只有 Lithe 主进程:只显示主进程一类,进程列表给出说明,不列 0 MB 的类别 | [截图](memory-details-host-only-dark.png) | [截图](memory-details-host-only-light.png) | + +复验:设置 `LITHE_VISUAL_OUTPUT_DIR`,通过 `scripts/desktop/desktop-go.sh test +-tags vivahead,lithevisual ./internal/workbench -run '^TestVisualMemoryDetails$' +-count=1 -timeout 180s` 生成。 diff --git a/docs/assets/memory-details/memory-details-dark.png b/docs/assets/memory-details/memory-details-dark.png new file mode 100644 index 0000000000..e7cb06f58c Binary files /dev/null and b/docs/assets/memory-details/memory-details-dark.png differ diff --git a/docs/assets/memory-details/memory-details-host-only-dark.png b/docs/assets/memory-details/memory-details-host-only-dark.png new file mode 100644 index 0000000000..86d91b0879 Binary files /dev/null and b/docs/assets/memory-details/memory-details-host-only-dark.png differ diff --git a/docs/assets/memory-details/memory-details-host-only-light.png b/docs/assets/memory-details/memory-details-host-only-light.png new file mode 100644 index 0000000000..c1965d5bf2 Binary files /dev/null and b/docs/assets/memory-details/memory-details-host-only-light.png differ diff --git a/docs/assets/memory-details/memory-details-light.png b/docs/assets/memory-details/memory-details-light.png new file mode 100644 index 0000000000..15a2459c5b Binary files /dev/null and b/docs/assets/memory-details/memory-details-light.png differ diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index de781b4a33..ad70e23418 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -28,11 +28,15 @@ native_path() { } PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" -# Lithe-core-rust #42, squash-merged into main: htmlPreview.site names the -# folder an HTML file is previewed from as a static site, and htmlPreview.resolveRequest decides -# what each request of the preview serves. It is on top of #41, squash-merged into main: -# markdown.outline outlines the headings of Markdown source as a document-symbol tree for the -# Structure tool window. It is on top of #40, squash-merged into main: the update.delta.cleanup_failed event, which the +# Lithe-core-rust #43 (branch feat/process-memory-summary, not yet merged): processMemory.summarize +# sorts the native process table into the parts of a Lithe instance (main process, language +# servers, plugin services, their child processes and the system helpers macOS holds the main +# process responsible for) for the memory details of the status bar. It is on top of #42, +# squash-merged into main: htmlPreview.site names the folder an HTML file is previewed from as a +# static site, and htmlPreview.resolveRequest decides what each request of the preview serves. It +# is on top of #41, squash-merged into main: markdown.outline outlines the headings of Markdown +# source as a document-symbol tree for the Structure tool window. It is on top of #40, +# squash-merged into main: the update.delta.cleanup_failed event, which the # desktop logs when it cannot remove the application a delta update rebuilt in the temporary # directory. It is on top of #39, squash-merged into main: plugins.installed.lifecycle keeps one # enabled plugin per language server language; installed versions carry languageServers, and @@ -81,7 +85,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="f88bc49562fbc5066dfb8783054611ee4e80e348" +PINNED_CORE_REVISION="5e2a5803966c953004f4c9730d91c156b64f422e" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index b93ef16bee..6d3c09fee8 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -1480,7 +1480,6 @@ "desktop.status.lspStarting": "LSP starting", "desktop.status.lspStopped": "LSP stopped", "desktop.status.memory": "Memory", - "desktop.status.memoryValue": "{value} MB", "desktop.status.noChanges": "No changes", "desktop.status.oneProblem": "1 problem", "desktop.status.path": "Path", @@ -10976,17 +10975,28 @@ "desktop.settings.updates.check": "Check Now", "desktop.settings.updates.notes": "Release Notes", "desktop.updates.available": "Lithe {version} is available. Open Settings > About to update.", - "desktop.memory.status": "{total} MB · Lithe {lithe} MB", - "desktop.memory.tooltip": "Memory: {total} MB in total. Lithe {lithe} MB, language servers {lsp} MB, services {services} MB.", + "desktop.memory.status": "{total} · Lithe {lithe}", + "desktop.memory.tooltip": "Memory: {total} in total, {lithe} of it in the Lithe main process.", "desktop.memory.title": "Memory", - "desktop.memory.value": "{value} MB", - "desktop.memory.total": "Total", - "desktop.memory.lithe": "Lithe", + "desktop.memory.megabytes": "{value} MB", + "desktop.memory.gigabytes": "{value} GB", + "desktop.memory.belowMegabyte": "< 1 MB", + "desktop.memory.host": "Lithe main process", "desktop.memory.languageServers": "Language servers", "desktop.memory.services": "Plugin services", - "desktop.memory.noProcesses": "No language servers or plugin services are running.", - "desktop.memory.kindServer": "language server", - "desktop.memory.kindService": "plugin service", + "desktop.memory.languageServer": "{plugin} · {language}", + "desktop.memory.systemHelpers": "System helpers", + "desktop.memory.childProcesses": "Other child processes", + "desktop.memory.processes": "Processes", + "desktop.memory.processCount": "{count} processes", + "desktop.memory.omitted": "{count} more, {value} in total", + "desktop.memory.reading": "Reading processes…", + "desktop.memory.unavailable": "Process memory could not be read.", + "desktop.memory.noOtherProcesses": "Lithe has not started any other process.", + "desktop.memory.help": "Counts the Lithe main process and every process that belongs to it: language servers, plugin services, child processes such as terminals and runs, and the helpers the system starts for Lithe, such as the WebKit processes that show web pages and previews.", + "desktop.memory.helpMacOS": "Each figure is what the Memory column of Activity Monitor shows.", + "desktop.memory.helpWindows": "Each figure is the private working set, which the Memory column of Task Manager shows.", + "desktop.memory.helpLinux": "Each figure is the resident memory less its shared pages.", "desktop.command.fold": "Fold", "desktop.command.unfold": "Unfold", "desktop.command.foldAll": "Fold All", diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 377f6ef216..8990b861b5 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -1480,7 +1480,6 @@ "desktop.status.lspStarting": "LSP 启动中", "desktop.status.lspStopped": "LSP 已停止", "desktop.status.memory": "内存", - "desktop.status.memoryValue": "{value} MB", "desktop.status.noChanges": "没有更改", "desktop.status.oneProblem": "1 个问题", "desktop.status.path": "路径", @@ -10976,17 +10975,28 @@ "desktop.settings.updates.check": "立即检查", "desktop.settings.updates.notes": "发布说明", "desktop.updates.available": "Lithe {version} 已发布,可在“设置 > 关于”中一键更新。", - "desktop.memory.status": "{total} MB · Lithe {lithe} MB", - "desktop.memory.tooltip": "内存:共 {total} MB。Lithe {lithe} MB,语言服务器 {lsp} MB,服务 {services} MB。", + "desktop.memory.status": "{total} · Lithe {lithe}", + "desktop.memory.tooltip": "内存:共 {total},其中 Lithe 主进程 {lithe}。", "desktop.memory.title": "内存", - "desktop.memory.value": "{value} MB", - "desktop.memory.total": "总计", - "desktop.memory.lithe": "Lithe", + "desktop.memory.megabytes": "{value} MB", + "desktop.memory.gigabytes": "{value} GB", + "desktop.memory.belowMegabyte": "< 1 MB", + "desktop.memory.host": "Lithe 主进程", "desktop.memory.languageServers": "语言服务器", "desktop.memory.services": "插件服务", - "desktop.memory.noProcesses": "没有运行中的语言服务器或插件服务。", - "desktop.memory.kindServer": "语言服务器", - "desktop.memory.kindService": "插件服务", + "desktop.memory.languageServer": "{plugin} · {language}", + "desktop.memory.systemHelpers": "系统辅助进程", + "desktop.memory.childProcesses": "其他子进程", + "desktop.memory.processes": "进程", + "desktop.memory.processCount": "{count} 个进程", + "desktop.memory.omitted": "另有 {count} 项,共 {value}", + "desktop.memory.reading": "正在读取进程…", + "desktop.memory.unavailable": "无法读取进程内存。", + "desktop.memory.noOtherProcesses": "Lithe 目前没有启动其他进程。", + "desktop.memory.help": "统计 Lithe 主进程和属于它的全部进程:语言服务器、插件服务、终端和运行任务等子进程,以及系统代 Lithe 启动的辅助进程,例如显示网页和预览的 WebKit 进程。", + "desktop.memory.helpMacOS": "数值与活动监视器“内存”一列显示的一致。", + "desktop.memory.helpWindows": "数值是专用工作集,即任务管理器“内存”一列显示的值。", + "desktop.memory.helpLinux": "数值是常驻内存减去共享页。", "desktop.command.fold": "折叠", "desktop.command.unfold": "展开", "desktop.command.foldAll": "全部折叠", diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 951d22b90b..b386f1e68f 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -12324,95 +12324,184 @@ ] }, { - "id": "desktop.memory.kindServer", + "id": "desktop.memory.belowMegabyte", "description": "Memory monitor in the status bar.", "platforms": [ "desktop" ] }, { - "id": "desktop.memory.kindService", + "id": "desktop.memory.childProcesses", "description": "Memory monitor in the status bar.", "platforms": [ "desktop" ] }, { - "id": "desktop.memory.languageServers", + "id": "desktop.memory.gigabytes", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ], + "parameters": { + "value": "string" + } + }, + { + "id": "desktop.memory.help", "description": "Memory monitor in the status bar.", "platforms": [ "desktop" ] }, { - "id": "desktop.memory.lithe", + "id": "desktop.memory.helpLinux", "description": "Memory monitor in the status bar.", "platforms": [ "desktop" ] }, { - "id": "desktop.memory.noProcesses", + "id": "desktop.memory.helpMacOS", "description": "Memory monitor in the status bar.", "platforms": [ "desktop" ] }, { - "id": "desktop.memory.services", + "id": "desktop.memory.helpWindows", "description": "Memory monitor in the status bar.", "platforms": [ "desktop" ] }, { - "id": "desktop.memory.status", + "id": "desktop.memory.host", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.memory.languageServer", "description": "Memory monitor in the status bar.", "platforms": [ "desktop" ], "parameters": { - "total": "string", - "lithe": "string" + "plugin": "string", + "language": "string" } }, { - "id": "desktop.memory.title", + "id": "desktop.memory.languageServers", "description": "Memory monitor in the status bar.", "platforms": [ "desktop" ] }, { - "id": "desktop.memory.tooltip", + "id": "desktop.memory.megabytes", "description": "Memory monitor in the status bar.", "platforms": [ "desktop" ], "parameters": { - "total": "string", - "lithe": "string", - "lsp": "string", - "services": "string" + "value": "string" } }, { - "id": "desktop.memory.total", + "id": "desktop.memory.noOtherProcesses", "description": "Memory monitor in the status bar.", "platforms": [ "desktop" ] }, { - "id": "desktop.memory.value", + "id": "desktop.memory.omitted", "description": "Memory monitor in the status bar.", "platforms": [ "desktop" ], "parameters": { + "count": "string", "value": "string" } }, + { + "id": "desktop.memory.processCount", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ], + "parameters": { + "count": "string" + } + }, + { + "id": "desktop.memory.processes", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.memory.reading", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.memory.services", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.memory.status", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ], + "parameters": { + "total": "string", + "lithe": "string" + } + }, + { + "id": "desktop.memory.systemHelpers", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.memory.title", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.memory.tooltip", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ], + "parameters": { + "total": "string", + "lithe": "string" + } + }, + { + "id": "desktop.memory.unavailable", + "description": "Memory monitor in the status bar.", + "platforms": [ + "desktop" + ] + }, { "id": "desktop.menu.open", "description": "Compact title bar menu button: opens the menu of command groups (Windows and Linux)", @@ -16037,16 +16126,6 @@ "desktop" ] }, - { - "id": "desktop.status.memoryValue", - "description": "Desktop terminal or status value.", - "platforms": [ - "desktop" - ], - "parameters": { - "value": "integer" - } - }, { "id": "desktop.status.noChanges", "description": "Desktop status: NoChanges", diff --git a/shared/platform-feature-matrix/features/memory-monitor.json b/shared/platform-feature-matrix/features/memory-monitor.json index 6242eb9eab..b99567b22f 100644 --- a/shared/platform-feature-matrix/features/memory-monitor.json +++ b/shared/platform-feature-matrix/features/memory-monitor.json @@ -4,23 +4,29 @@ "group": "通知与资源", "capability": "应用与语言服务内存监控", "macos": { - "implementationStatus": "partial", + "implementationStatus": "implemented", "verificationStatus": "pending", "evidence": [ - "desktop/internal/workbench/chrome.go", - "desktop/internal/sysinfo/sysinfo.go" + "desktop/internal/workbench/memory_monitor.go", + "desktop/internal/workbench/memory_monitor_test.go", + "desktop/internal/core/process_memory.go", + "desktop/internal/sysinfo/process.go", + "desktop/internal/sysinfo/process_darwin.go" ] }, "windows": { - "implementationStatus": "partial", + "implementationStatus": "implemented", "verificationStatus": "pending", "evidence": [ - "desktop/internal/workbench/chrome.go", - "desktop/internal/sysinfo/sysinfo.go" + "desktop/internal/workbench/memory_monitor.go", + "desktop/internal/workbench/memory_monitor_test.go", + "desktop/internal/core/process_memory.go", + "desktop/internal/sysinfo/process.go", + "desktop/internal/sysinfo/process_windows.go" ] }, "owner": "Workbench", - "verification": "打开内存指标并观察应用、语言服务和总内存变化,确认采样失败不会阻塞工作台。macOS 状态栏只显示内存芯片图标,不再显示总计与 Lithe 数值;悬停提示显示总计、Lithe、LSP 和服务内存,点击图标打开托管内存详情并在关闭后停止详细采样,VoiceOver 读出托管内存及当前总计。同一状态栏中帧率只显示数字和 FPS 单位,不带图标;只读锁和内存图标按钮使用 18pt 紧凑尺寸,相邻项之间不再留出大块空白。Windows 状态栏仍显示总计与 Lithe 数值。", + "verification": "运行带语言服务器、终端和 Markdown/HTML 预览的项目,点击状态栏内存项打开详情:顶部总计等于各类别之和,按类别堆叠的条与图例显示 Lithe 主进程、语言服务器(插件名 · 语言)、插件服务、系统辅助进程(macOS 的 WebKit 进程)和其他子进程,0 字节的类别不显示;进程列表按占用从大到小,超过上限的合计为“另有 N 项”。macOS 对照活动监视器“内存”列,Windows 对照任务管理器“内存”列(专用工作集),数值一致。弹窗内容不被截断;关闭详情后每 10 秒采样一次,打开时每 2 秒;读取失败时隐藏数字并显示无法读取,恢复后重新显示。从终端启动时 macOS 把 WebKit 进程归给终端,系统辅助进程不计入,应从 Finder 或 Dock 启动验证。macOS 状态栏只显示内存图标,悬停提示显示总计和 Lithe 主进程;Windows 状态栏显示总计与 Lithe 主进程数值。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -40,5 +46,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva:状态栏内存项(chrome.go 的 itemMemory,显示进程常驻内存)与进程内存采样(sysinfo.go 的 ResidentBytes)已存在;未找到语言服务内存采样、内存详情弹出或悬停分项,迁移表也记录语言服务内存监控缺失。" + "notes": "Viva:进程表由 sysinfo 原生读取(macOS proc_pid_rusage 物理占用与 responsible PID、Windows 专用工作集、Linux 常驻内存减共享页),Core 的 processMemory.summarize 把进程归到实例的各类别并求和;工作台只负责采样、命名与呈现。Linux 只有组件实现,不在矩阵平台范围内。" }