Files
magpie/internal/update/com.go
T
yetone 2afacd7d18 windows: a terminal waits for magpie, through a magpie.com beside the app (#3737)
The Windows app is linked with -H windowsgui so a double click opens no
console, and PowerShell and cmd don't wait for a GUI program. The prompt
came back before magpie printed, and `magpie plugin login`'s password
keys went to the shell as well as to magpie (tom047784 / TomXPRIME on
Discord, 10-27; the handle error in the same report was 9298d2a).

A shell looks for `magpie` by PATHEXT, which lists .COM before .EXE. So
magpie now writes magpie.com beside the app. It is a 1.9MB console program
(internal/update/launcher), built and embedded by `make release-windows`
(the comlauncher tag). The shell waits for it. It runs the app with its own
std handles, passes MAGPIE_COM=1, waits, and exits with the app's code. The
app keeps those handles and borrows the console for the streams Windows
dropped (a GUI child gets no console handles), so redirection, pipes and
hidden prompts work. A command that opens the window (none, app, gui, tray,
panel, -Embedding, magpie: links) is started DETACHED, and the shell isn't
held. A double click and the Start menu still open magpie.exe.

Why this, and not a console-subsystem copy or a magpie-cli.exe: the
running process is still magpie.exe, so autostart, shortcuts, relaunch and
every os.Executable() use are unchanged. There is no new release asset (still
16), and magpie-releases needs no change. The trailer names the app, so a
download kept as magpie-windows-amd64.exe is run by its own name.

Where it is written:
- Settings › Command line's Add (cliPlace) writes it instead of magpie.cmd
  in a build that carries it.
- A terminal command run as magpie.exe writes it when the folder is on PATH
  or has a magpie.com or magpie.cmd, so existing users get it on their next
  `magpie <cmd>`.
- The app's start (placeExe) writes it again when the bytes differ, so an
  update brings it along.
- A running magpie.com is moved aside and cleared on the next run.
- A copy beside a magpie.exe leaves `magpie` to it (comOwner).
- The Command line row reads magpie.com as this app, with "(which runs
  magpie.exe)".

Run, at 2e165fe9d (main since then touches none of these files):
- gofmt -l: clean
- go vet ./...; GOOS=linux go vet -tags nogui ./...; GOOS=windows go vet ./...
- go build for darwin, linux -tags nogui and windows
- make release-windows: amd64 and arm64 are PE subsystem 2 (GUI), as before
- go test -tags nogui -count=1 -timeout 45m ./internal/update/...
  ./internal/cli/ ./internal/gui/ ./internal/proc/: all ok
- cli-path.test.cjs in chromium and webkit (11 + 11 pass); i18n-keys,
  gui-zh-tw, gui-ja, gui-de pass
- The Windows box, with GOOS=windows test binaries: launcher's TestArgsOf,
  TestOpensWindow and TestTargetName pass; update's TestWriteCom,
  TestComOwner, TestEnsureCompanion, TestFindCLIPrefersCom and
  TestCLIShim pass. TestComMagicIsTheLaunchers reads the source, so it
  can't run from a copied binary there; it passes on macOS.
- The Windows box, sandbox HOME, release build, interactive ConPTY over
  ssh -tt with typed keys:
  - Old v0.1.1675 in PowerShell 7.5.4: the prompt comes back before
    "magpie 0.1.1675", $LASTEXITCODE is empty, `> out.txt` is empty, and
    backup's passphrase is split between the shell and magpie.
  - New build in PowerShell 7.5.4: the first `magpie` as magpie.exe wrote
    magpie.com, and Get-Command then resolves it. `magpie version` prints
    before the next line, with exit 0. A bad command gives 1. `> out.txt`
    holds the version. backup reads "Passphrase for the backup:" and
    "Again:" typed. restore reads "Passphrase:" typed. A piped passphrase
    is read (wrong passphrase, exit 1).
  - New build in cmd: `where` lists magpie.com first. The same version,
    ERRORLEVEL 0 and 1, and typed backup and restore passphrases work.
    Ctrl+C at a prompt ends it with 0xC000013A and leaves no magpie.exe.
  - The update: an older magpie.com in place was moved aside and rewritten
    by the first command of the new build, and the .old was gone after the
    next one.

Broken by hand, red:
- writeCom always rewriting: TestWriteCom
- EnsureCompanion ignoring PATH: TestEnsureCompanion
- comOwner always true: TestComOwner
- app.js's old shim-only condition: the "magpie.com is said to run the app"
  case in en and zh

Not tried:
- A real double click or the Start menu on the box. magpie.exe is still
  GUI-subsystem and is what they open, but no window was opened there. The
  sandbox app would share the gateway's port with the box's own magpie.
- Windows Terminal itself; the ConPTY ssh -tt gives is what it uses.
- The arm64 build on a real ARM machine.
- The full go test ./... at this head. Another session's agent and
  gateway suite was running on the machine (load ~115), so only the
  touched packages and internal/proc ran.
2026-10-27 12:08:16 +08:00

162 lines
5.4 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package update
import (
"bytes"
"fmt"
"os"
"path/filepath"
"strings"
)
// The Windows app is linked as a GUI program, so a double click opens no
// console window; but a shell doesn't wait for a GUI program either. In
// PowerShell or cmd, `magpie plugin login` gave the prompt back at once,
// printed after it, and the shell and magpie both read the keys typed:
// a hidden password never reached magpie (TomXPRIME, #3737). A shell looks
// for `magpie` by PATHEXT, which lists .COM before .EXE, so magpie writes
// magpie.com beside the app: a small console program (./launcher) that
// the shell waits for, which runs the app with its console and exits with
// the app's code. Double clicks and the Start menu still open magpie.exe.
//
// It is written wherever a terminal runs magpie from: when the app's
// folder is on PATH, where Settings › Command line puts it, or a magpie.com
// or magpie.cmd is there already. The app writes it again as it starts
// when its bytes differ, so an update brings it along.
// ComEnv is set by magpie.com for the app it runs: the standard handles it
// hands over are the terminal's console or a redirection, and its console
// is the one to borrow (cli's console_windows.go).
const ComEnv = "MAGPIE_COM"
// comName is the companion's file name; it runs as `magpie`.
const comName = "magpie.com"
// comMagic ends magpie.com; the app it runs is named just before it,
// after a NUL (launcher's targetName).
const comMagic = "\x00magpie-com-target"
// comLauncher is the launcher program, built for this system and put in
// the Windows app by `make release-windows` (com_embed_windows_*.go); nil
// in any other build, which writes no magpie.com.
var comLauncher []byte
// comText is the magpie.com that runs the program exe in its folder.
func comText(launcher []byte, exe string) []byte {
name := filepath.Base(strings.ReplaceAll(exe, `\`, "/"))
out := make([]byte, 0, len(launcher)+1+len(name)+len(comMagic))
out = append(out, launcher...)
out = append(out, 0)
out = append(out, name...)
return append(out, comMagic...)
}
// comTarget is the program name in a magpie.com's last bytes, "" when it
// has none.
func comTarget(b []byte) string {
if !bytes.HasSuffix(b, []byte(comMagic)) {
return ""
}
b = b[:len(b)-len(comMagic)]
return string(b[bytes.LastIndexByte(b, 0)+1:])
}
// comRuns says whether cmd is a magpie.com beside exe that runs it.
func comRuns(cmd, exe string) bool {
if !strings.EqualFold(filepath.Base(cmd), comName) || !strings.EqualFold(filepath.Dir(cmd), filepath.Dir(exe)) {
return false
}
f, err := os.Open(cmd)
if err != nil {
return false
}
defer f.Close()
st, err := f.Stat()
if err != nil || st.Size() < int64(len(comMagic)) {
return false
}
n := min(st.Size(), 1024)
b := make([]byte, n)
if _, err := f.ReadAt(b, st.Size()-n); err != nil {
return false
}
return strings.EqualFold(comTarget(b), filepath.Base(exe))
}
// comOwner says whether exe is the program a magpie.com in its folder
// should run: a magpie.exe there is what `magpie` ran before, so another
// copy beside it (magpie-windows-amd64 (1).exe) leaves it be.
func comOwner(exe string) bool {
if strings.EqualFold(filepath.Base(exe), "magpie.exe") {
return true
}
st, err := os.Stat(filepath.Join(filepath.Dir(exe), "magpie.exe"))
return err != nil || st.IsDir()
}
// EnsureCompanion writes the magpie.com that runs exe beside it when a
// terminal runs magpie from that folder (on PATH, or a magpie.com or
// magpie.cmd there), or brings one there up to this version. Nothing in
// a build without the launcher, or when it is as it should be already.
func EnsureCompanion(exe string) error {
if comLauncher == nil || !comOwner(exe) {
return nil
}
dir := filepath.Dir(exe)
if !onPath(dir, os.Getenv("PATH")) && !exists(filepath.Join(dir, comName)) && !exists(filepath.Join(dir, shimName)) {
return nil
}
_, err := writeCom(comLauncher, exe)
return err
}
// writeCom writes the magpie.com that runs exe beside it, unless it is
// there already, and is its path. A magpie.com running now (a `magpie
// serve` in a terminal) can't be written over, but can be moved aside,
// as an update moves the running app; the next run clears it.
func writeCom(launcher []byte, exe string) (string, error) {
p := filepath.Join(filepath.Dir(exe), comName)
want := comText(launcher, exe)
// the one moved aside last time, running then, is let go of now
RemoveOld(p)
if b, err := os.ReadFile(p); err == nil && bytes.Equal(b, want) {
return p, nil
}
f, err := os.CreateTemp(filepath.Dir(p), ".magpie-com-*")
if err != nil {
return "", fmt.Errorf("writing %s, which runs %s as magpie: %w", p, filepath.Base(exe), err)
}
tmp := f.Name()
_, err = f.Write(want)
if cerr := f.Close(); err == nil {
err = cerr
}
if err == nil {
if err = os.Rename(tmp, p); err != nil && exists(p) {
if aerr := os.Rename(p, oldName(p)); aerr == nil {
err = os.Rename(tmp, p)
}
}
}
if err != nil {
os.Remove(tmp)
return "", fmt.Errorf("writing %s, which runs %s as magpie: %w", p, filepath.Base(exe), err)
}
return p, nil
}
// onPath is whether dir is one of path's (Windows', ;-separated) folders.
func onPath(dir, path string) bool {
dir = strings.TrimRight(dir, `\/`)
for _, d := range strings.Split(path, string(os.PathListSeparator)) {
if d = strings.TrimRight(strings.TrimSpace(d), `\/`); d != "" && strings.EqualFold(d, dir) {
return true
}
}
return false
}
func exists(p string) bool {
_, err := os.Stat(p)
return err == nil
}