From e773688305c055572c9e02b36ff7f8ccb3d6dc96 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jeffry=20W=C3=BCrmli?= Date: Thu, 12 Nov 2026 13:27:19 +0100 Subject: [PATCH] fix: keep process names with spaces in the ps reader Read the executable path via ps -o comm= and use it to split the command column, so names like "LM Studio" are no longer cut to "LM". --- internal/proc/ps.go | 54 +++++++++++-- internal/proc/ps_test.go | 81 +++++++++++++++++++- internal/proc/testdata/darwin/ps_special.txt | 1 + 3 files changed, 126 insertions(+), 10 deletions(-) create mode 100644 internal/proc/testdata/darwin/ps_special.txt diff --git a/internal/proc/ps.go b/internal/proc/ps.go index 990331c..735dfb9 100644 --- a/internal/proc/ps.go +++ b/internal/proc/ps.go @@ -56,7 +56,7 @@ func (r *psReader) readPS(ctx context.Context, pid int) (Process, error) { if err != nil { return Process{}, classifyPSError(pid, err) } - p, err := parsePS(out) + p, err := parsePS(out, r.readComm(ctx, pid)) if err != nil { if errors.Is(err, ErrNotFound) { return Process{}, err @@ -66,6 +66,17 @@ func (r *psReader) readPS(ctx context.Context, pid int) (Process, error) { return p, nil } +// readComm returns the executable path of pid as reported by "ps -o comm=", +// which is not split on spaces. It returns "" when ps fails, so the caller +// falls back to the lossy whitespace split. +func (r *psReader) readComm(ctx context.Context, pid int) string { + out, err := r.runner.Run(ctx, "ps", "-o", "comm=", "-p", strconv.Itoa(pid)) + if err != nil { + return "" + } + return parsePSComm(out) +} + // classifyPSError maps a failed ps run to a Reader error. ps exits 1 with no // output when the PID does not exist; any other failure (ps missing, timeout, // other exit codes) is not "not found" and keeps its cause. @@ -112,11 +123,16 @@ func (r *psReader) readAncestors(ctx context.Context, ppid, self int) []Ancestor // "ps -o pid=,ppid=,user=,lstart=,command= -p ". Empty output yields // ErrNotFound. // -// Cmdline is the command column split on whitespace. This is lossy: ps joins -// the arguments with single spaces, so arguments that contain spaces cannot be -// told apart from several arguments. Name is the base name of the first -// token, so an executable path containing spaces is cut off as well. -func parsePS(out []byte) (Process, error) { +// comm is the executable path from "ps -o comm=" (see parsePSComm). When the +// command column starts with it, comm is kept as the first Cmdline element and +// Name is its base name, so executables whose path contains spaces survive. +// With comm empty or not a prefix of the command, the first whitespace token +// is used instead, which cuts such paths off. +// +// The remaining Cmdline is the command column split on whitespace. This is +// lossy: ps joins the arguments with single spaces, so arguments that contain +// spaces cannot be told apart from several arguments. +func parsePS(out []byte, comm string) (Process, error) { line := strings.TrimSpace(string(out)) if line == "" { return Process{}, ErrNotFound @@ -130,6 +146,8 @@ func parsePS(out []byte) (Process, error) { return Process{}, fmt.Errorf("parse ps output %q: want at least %d fields, got %d", line, psLeadingFields+1, len(fields)) } + command := commandColumn(line) + pid, err := strconv.Atoi(fields[0]) if err != nil { return Process{}, fmt.Errorf("parse ps pid %q: %w", fields[0], err) @@ -145,6 +163,9 @@ func parsePS(out []byte) (Process, error) { } cmdline := fields[psLeadingFields:] + if rest, ok := strings.CutPrefix(command, comm); ok && comm != "" && (rest == "" || rest[0] == ' ') { + cmdline = append([]string{comm}, strings.Fields(rest)...) + } return Process{ PID: pid, PPID: ppid, @@ -155,6 +176,27 @@ func parsePS(out []byte) (Process, error) { }, nil } +// commandColumn returns line without its leading psLeadingFields +// whitespace-separated fields, with the command's own spacing intact. +func commandColumn(line string) string { + rest := line + for range psLeadingFields { + rest = strings.TrimLeft(rest, " \t") + i := strings.IndexAny(rest, " \t") + if i < 0 { + return "" + } + rest = rest[i:] + } + return strings.TrimSpace(rest) +} + +// parsePSComm parses "ps -o comm= -p " output: the first line, trimmed. +func parsePSComm(out []byte) string { + line, _, _ := strings.Cut(string(out), "\n") + return strings.TrimSpace(line) +} + // parseLsofCwd extracts the path from "lsof -Fn" output: the first line that // starts with "n". It returns "" when there is none. func parseLsofCwd(out []byte) string { diff --git a/internal/proc/ps_test.go b/internal/proc/ps_test.go index fb61c08..1d69002 100644 --- a/internal/proc/ps_test.go +++ b/internal/proc/ps_test.go @@ -39,6 +39,10 @@ func psKey(pid int) string { return execx.Key("ps", "-o", "pid=,ppid=,user=,lstart=,command=", "-p", fmt.Sprint(pid)) } +func commKey(pid int) string { + return execx.Key("ps", "-o", "comm=", "-p", fmt.Sprint(pid)) +} + func lsofKey(pid int) string { return execx.Key("lsof", "-a", "-p", fmt.Sprint(pid), "-d", "cwd", "-Fn") } @@ -48,7 +52,7 @@ func psLine(pid, ppid int, command string) []byte { } func TestParsePS_ParsesFields(t *testing.T) { - p, err := parsePS(fixture(t, "ps_one.txt")) + p, err := parsePS(fixture(t, "ps_one.txt"), "") if err != nil { t.Fatalf("parsePS: %v", err) } @@ -73,7 +77,7 @@ func TestParsePS_ParsesFields(t *testing.T) { } func TestParsePS_CommandWithSpaces(t *testing.T) { - p, err := parsePS(fixture(t, "ps_spaces.txt")) + p, err := parsePS(fixture(t, "ps_spaces.txt"), "") if err != nil { t.Fatalf("parsePS: %v", err) } @@ -93,6 +97,75 @@ func TestParsePS_CommandWithSpaces(t *testing.T) { } } +func TestParsePS_NameWithSpaces(t *testing.T) { + tests := map[string]struct { + fixture string + comm string + wantName string + wantCmd []string + }{ + "spaces": { + "ps_spaces.txt", "/Applications/My App.app/Contents/MacOS/My App", "My App", + []string{"/Applications/My App.app/Contents/MacOS/My App", "--flag"}, + }, + "special characters": { + "ps_special.txt", + "/Applications/Google Chrome.app/Contents/Frameworks/Google Chrome Helper (Renderer).app/Contents/MacOS/Google Chrome Helper (Renderer)", + "Google Chrome Helper (Renderer)", + []string{"/Applications/Google Chrome.app/Contents/Frameworks/Google Chrome Helper (Renderer).app/Contents/MacOS/Google Chrome Helper (Renderer)", "--type=renderer"}, + }, + "no spaces unchanged": { + "ps_one.txt", "/usr/local/bin/node", "node", + []string{"/usr/local/bin/node", "/home/devuser/app/server.js", "--port", "3000"}, + }, + "comm not a prefix falls back": { + "ps_one.txt", "/other/path", "node", + []string{"/usr/local/bin/node", "/home/devuser/app/server.js", "--port", "3000"}, + }, + } + for name, tt := range tests { + t.Run(name, func(t *testing.T) { + p, err := parsePS(fixture(t, tt.fixture), tt.comm) + if err != nil { + t.Fatalf("parsePS: %v", err) + } + if p.Name != tt.wantName { + t.Errorf("Name = %q, want %q", p.Name, tt.wantName) + } + if !slices.Equal(p.Cmdline, tt.wantCmd) { + t.Errorf("Cmdline = %v, want %v", p.Cmdline, tt.wantCmd) + } + }) + } +} + +func TestParsePSComm(t *testing.T) { + if got := parsePSComm([]byte("/Applications/LM Studio.app/Contents/MacOS/LM Studio\n")); got != "/Applications/LM Studio.app/Contents/MacOS/LM Studio" { + t.Errorf("comm = %q", got) + } + if got := parsePSComm(nil); got != "" { + t.Errorf("comm of empty output = %q, want empty", got) + } +} + +func TestDarwinReader_NameWithSpaces(t *testing.T) { + comm := "/Applications/LM Studio.app/Contents/MacOS/LM Studio" + f := &execx.Fake{Responses: map[string][]byte{ + psKey(70): psLine(70, 1, comm+" --port 1234"), + commKey(70): []byte(comm + "\n"), + lsofKey(70): nil, + psKey(1): psLine(1, 0, "/sbin/launchd"), + lsofKey(1): nil, + }} + p, err := newPSReader(f).Read(context.Background(), 70) + if err != nil { + t.Fatalf("Read: %v", err) + } + if p.Name != "LM Studio" { + t.Errorf("Name = %q, want %q", p.Name, "LM Studio") + } +} + func TestParsePS_Malformed(t *testing.T) { tests := map[string]string{ "too few fields": "12 1 devuser Thu Nov 12\n", @@ -102,7 +175,7 @@ func TestParsePS_Malformed(t *testing.T) { } for name, in := range tests { t.Run(name, func(t *testing.T) { - _, err := parsePS([]byte(in)) + _, err := parsePS([]byte(in), "") if err == nil { t.Fatal("parsePS returned nil error") } @@ -114,7 +187,7 @@ func TestParsePS_Malformed(t *testing.T) { } func TestParsePS_EmptyIsNotFound(t *testing.T) { - if _, err := parsePS([]byte(" \n")); !errors.Is(err, ErrNotFound) { + if _, err := parsePS([]byte(" \n"), ""); !errors.Is(err, ErrNotFound) { t.Fatalf("error = %v, want ErrNotFound", err) } } diff --git a/internal/proc/testdata/darwin/ps_special.txt b/internal/proc/testdata/darwin/ps_special.txt new file mode 100644 index 0000000..07833fd --- /dev/null +++ b/internal/proc/testdata/darwin/ps_special.txt @@ -0,0 +1 @@ +812 1 devuser Wed Nov 11 10:00:00 2026 /Applications/Google Chrome.app/Contents/Frameworks/Google Chrome Helper (Renderer).app/Contents/MacOS/Google Chrome Helper (Renderer) --type=renderer