proc: a probe never runs a Windows GUI program, so asking opencode's version doesn't open OpenCode there either (saint carol)

saint carol, on Windows with OpenCode's desktop app: opening magpie,
often right after an update, brings up OpenCode. af0cd09c9 covered only a
Mac's app bundles.

OpenCode's desktop app installs per user, to
%LOCALAPPDATA%\Programs\ai.opencode.desktop\OpenCode.exe (electron-builder
NSIS; @opencodedesktop before), with its CLI at
resources\opencode-cli.exe. The installer puts nothing on PATH, and
"Install CLI" is Mac-only. With that folder on PATH, `opencode` finds
OpenCode.exe, since Windows looks names up without case and PATHEXT adds
.exe. magpie's `opencode --version` at each start and after a CLI update
(proc.Version, library openCodeVersion, cliupdate runCheck) then started
the Electron app. Nothing else in magpie starts OpenCode on Windows: no
App Paths lookup, no opencode:// link, and scoop's opencode-desktop gives
a shortcut, not a shim.

ProbeContext now also refuses (cmd.Err, nothing started) a program whose
PE header names the GUI subsystem (guiExe: e_lfanew, PE signature,
optional header Subsystem == 2). Console programs run as before: CLIs,
bun's, npm's and WinGet's shims, opencode-cli.exe. Anything that isn't a
PE, or whose header can't be read, also runs as before. On the Windows
box, every program magpie probes that is installed there is console
(claude.exe, codex.exe, git.exe). The GUI ones on PATH are system32
tools, git-gui, gitk and Codex's codex-command-runner, which no probe
asks.

Tests:
- TestGuiPE: GUI PE32 and PE32+ headers are a window's program; console,
  a bad magic, a cut-short header, a script and empty bytes are not.
- TestProbeNeverOpensAWindowsApp (Windows): the install's layout is made
  from copies of the test binary, which notes that it ran (TestMain's
  MAGPIE_PROC_RAN). OpenCode.exe is patched to the GUI subsystem as
  Electron's is. With the folder on PATH, `opencode` resolves to
  OpenCode.exe and isn't run, and Version is "". opencode-cli.exe still
  answers 2.2.5.

Broken by hand on xiaomi-gpu: with guiExe out of ProbeContext,
TestProbeNeverOpensAWindowsApp goes red ("OpenCode.exe was run and said
2.2.5").

Run at 4b407bb79 plus this change (go test -count=1 -timeout 45m):
- mote (macOS): internal/proc, library, agent, provider, wslrun ok;
  GOOS=windows go vet ./... ok, GOOS=linux go vet -tags nogui ./... ok;
  gofmt -l empty.
- xiaomi-gpu (Windows, win-run): internal/proc ok. internal/library red
  on TestGoneAgentListedToTakeOut and TestCheckMixedServerEachSide, the
  same at 4b407bb79 without this change, both listed in #4115.
- magpie-desktop (Linux, wsl-run): internal/proc ok.

Not tried: the real OpenCode desktop app on Windows (not installed on the
test box; the layout is from OpenCode's electron-builder config and NSIS
include), the reporter's PATH, and a .cmd or .ps1 the user wrote that
starts OpenCode.exe (still run).
This commit is contained in:
yetone
2026-11-02 16:24:51 +08:00
parent f9595e7684
commit b2f7818d2e
6 changed files with 189 additions and 5 deletions
+3 -2
View File
@@ -8,8 +8,9 @@ import (
"strings"
)
// errAppMain is what a probe of an app's own program ends with, unrun.
var errAppMain = errors.New("not run: it is a macOS app's own program, which opens the app's window")
// errAppMain is what a probe of an app's own program (a Mac bundle's, a
// Windows GUI program) ends with, unrun.
var errAppMain = errors.New("not run: it is an app's own program, which opens the app's window")
// appMain reports whether the program at path is the main executable of
// an app a user opens (…/X.app/Contents/MacOS/<CFBundleExecutable>, X.app
+49
View File
@@ -0,0 +1,49 @@
package proc
import (
"encoding/binary"
"io"
"os"
)
// guiExe reports whether the program at path is a Windows program of the
// GUI subsystem (IMAGE_SUBSYSTEM_WINDOWS_GUI in its PE header): one that
// opens a window, has no console, and never answers --version on one.
// OpenCode's desktop app is OpenCode.exe in
// %LOCALAPPDATA%\Programs\ai.opencode.desktop, an Electron program; with
// that folder on PATH, Windows' case-blind search finds it as opencode,
// and magpie's version check put OpenCode's window up at every start and
// after each update (saint carol on Discord). Its CLI (resources\
// opencode-cli.exe), npm's, bun's and scoop's shims are console programs
// and are run. Anything that isn't a PE, or whose header can't be read,
// is run as before.
func guiExe(path string) bool {
f, err := os.Open(path)
if err != nil {
return false
}
defer f.Close()
var b [4096]byte
n, _ := io.ReadFull(f, b[:])
return guiPE(b[:n])
}
const peSubsystemGUI = 2
// guiPE reads the subsystem from a PE image's first bytes: DOS header,
// PE signature at e_lfanew, the 20-byte COFF header, then the optional
// header, whose Subsystem is at 68 in PE32 and PE32+ alike.
func guiPE(b []byte) bool {
if len(b) < 0x40 || b[0] != 'M' || b[1] != 'Z' {
return false
}
pe := int(binary.LittleEndian.Uint32(b[0x3c:]))
opt := pe + 4 + 20
if pe < 0x40 || opt+70 > len(b) || string(b[pe:pe+4]) != "PE\x00\x00" {
return false
}
if magic := binary.LittleEndian.Uint16(b[opt:]); magic != 0x10b && magic != 0x20b {
return false
}
return binary.LittleEndian.Uint16(b[opt+68:]) == peSubsystemGUI
}
+40
View File
@@ -0,0 +1,40 @@
package proc
import (
"encoding/binary"
"testing"
)
// peHeader is the start of a PE image with the given optional-header
// magic and subsystem.
func peHeader(magic, subsystem uint16) []byte {
b := make([]byte, 0x200)
b[0], b[1] = 'M', 'Z'
binary.LittleEndian.PutUint32(b[0x3c:], 0x80)
copy(b[0x80:], "PE\x00\x00")
opt := 0x80 + 4 + 20
binary.LittleEndian.PutUint16(b[opt:], magic)
binary.LittleEndian.PutUint16(b[opt+68:], subsystem)
return b
}
// Only a PE of the GUI subsystem is a window's program: a console one
// (a CLI, a shim) and anything that isn't a whole PE header are not.
func TestGuiPE(t *testing.T) {
for name, c := range map[string]struct {
b []byte
want bool
}{
"gui pe32+": {peHeader(0x20b, 2), true},
"gui pe32": {peHeader(0x10b, 2), true},
"console pe32+": {peHeader(0x20b, 3), false},
"bad magic": {peHeader(0x107, 2), false},
"cut short": {peHeader(0x20b, 2)[:0x90], false},
"script": {[]byte("#!/bin/sh\necho 1\n"), false},
"empty": {nil, false},
} {
if got := guiPE(c.b); got != c.want {
t.Errorf("%s: guiPE = %v, want %v", name, got, c.want)
}
}
}
+79
View File
@@ -0,0 +1,79 @@
package proc
import (
"context"
"encoding/binary"
"os"
"path/filepath"
"strings"
"testing"
"time"
)
// openCodeInstall lays out OpenCode's desktop app as its installer puts it
// (%LOCALAPPDATA%\Programs\ai.opencode.desktop): OpenCode.exe, a GUI
// program, and resources\opencode-cli.exe, a console one. Both are copies
// of this test binary, which notes in ran that it was started
// (TestMain); OpenCode.exe has its subsystem set to GUI, as Electron's is.
func openCodeInstall(t *testing.T) (dir, ran string) {
self, err := os.Executable()
if err != nil {
t.Fatal(err)
}
b, err := os.ReadFile(self)
if err != nil {
t.Fatal(err)
}
if guiPE(b) {
t.Fatal("the test binary is already a GUI program")
}
root := t.TempDir()
ran = filepath.Join(root, "ran")
t.Setenv("MAGPIE_PROC_RAN", ran)
dir = filepath.Join(root, "Programs", "ai.opencode.desktop")
if err := os.MkdirAll(filepath.Join(dir, "resources"), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(filepath.Join(dir, "resources", "opencode-cli.exe"), b, 0o755); err != nil {
t.Fatal(err)
}
gui := append([]byte(nil), b...)
opt := int(binary.LittleEndian.Uint32(gui[0x3c:])) + 4 + 20
binary.LittleEndian.PutUint16(gui[opt+68:], peSubsystemGUI)
if err := os.WriteFile(filepath.Join(dir, "OpenCode.exe"), gui, 0o755); err != nil {
t.Fatal(err)
}
return dir, ran
}
// With OpenCode's install folder on PATH, `opencode` is OpenCode.exe
// (Windows looks names up without case), and a version probe never runs
// it: run, it opens OpenCode's window, which magpie's version check did at
// each start and after each update (saint carol on Discord). The CLI
// beside it still answers.
func TestProbeNeverOpensAWindowsApp(t *testing.T) {
dir, ran := openCodeInstall(t)
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := ProbeContext(ctx, "opencode", "--version")
if !strings.EqualFold(filepath.Base(cmd.Path), "OpenCode.exe") {
t.Fatalf("opencode found as %s, want OpenCode.exe", cmd.Path)
}
if out, err := cmd.Output(); err == nil {
t.Fatalf("OpenCode.exe was run and said %q", out)
}
if v := Version(filepath.Join(dir, "OpenCode.exe")); v != "" {
t.Fatalf("OpenCode.exe said version %q", v)
}
if b, _ := os.ReadFile(ran); len(b) != 0 {
t.Fatalf("a probe started %s", b)
}
out, err := ProbeContext(ctx, filepath.Join(dir, "resources", "opencode-cli.exe"), "--version").Output()
if err != nil || strings.TrimSpace(string(out)) != "2.2.5" {
t.Fatalf("the bundled CLI answered %q, %v", out, err)
}
if b, _ := os.ReadFile(ran); !strings.Contains(string(b), "opencode-cli") || strings.Contains(strings.ToLower(string(b)), "opencode.exe") {
t.Fatalf("ran %q, want only the CLI", b)
}
}
+16 -1
View File
@@ -1,10 +1,25 @@
package proc
import (
"fmt"
"os"
"testing"
"github.com/yetone/magpie/internal/testenv"
)
// The tests run in a home of their own, never the user's real files.
func TestMain(m *testing.M) { testenv.Main(m) }
// With MAGPIE_PROC_RAN set, the test binary stands in for a program a
// probe asks its version (guiexe_windows_test.go): it notes that it was
// started there and answers.
func TestMain(m *testing.M) {
if ran := os.Getenv("MAGPIE_PROC_RAN"); ran != "" {
if f, err := os.OpenFile(ran, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644); err == nil {
fmt.Fprintln(f, os.Args[0])
f.Close()
}
fmt.Println("2.2.5")
os.Exit(0)
}
testenv.Main(m)
}
+2 -2
View File
@@ -21,8 +21,8 @@ func ProbeContext(ctx context.Context, name string, args ...string) *exec.Cmd {
p := &probe{cancel: cancel, killing: make(chan struct{}), ended: make(chan struct{})}
cmd := CommandContext(ctx, name, args...)
// a probe never opens an app: asked its version, an app's own program
// puts its window up instead (appMain)
if cmd.Err == nil && appMain(cmd.Path) {
// puts its window up instead (appMain on a Mac, guiExe on Windows)
if cmd.Err == nil && (appMain(cmd.Path) || guiExe(cmd.Path)) {
cmd.Err = errAppMain
}
probeGroup(cmd, p)