Files
magpie/internal/gui/terminal_rex.go
T
yetone 7d11f7d428 gui: Rex opens sessions in a Rex session of magpie's own, with none, one or several open (#4565, StringKe)
StringKe tried b9e5bc6cb with the real Rex (server 0.0.1793131181,
Rex Beta 0.1.0) on v0.1.2391: it opened only when Rex had exactly one
session. Outside Rex, `rex run` with no -s exits 3 both for no session
and for several ("session target default is ambiguous"), and exit 3
means not found or ambiguous; magpie then ran `rex new <t> --label <t>`,
and `rex new` has no --label (exit 2). run's --label also names the
block, not the tab, and the CLI can't tell which session the app shows.

Now magpie keeps a Rex session of its own, labelled magpie. openInRex
lists sessions with `rex ls --json` and takes the one labelled exactly
magpie (else magpie in another case), by its full ID since labels can be
shared. It runs `rex run -s <id> --label=<t> --json -- /bin/sh -c ...`
and names the new tab with `rex window rename -s <id> -- <window_id> <t>`
from run's JSON. With no such session, or a 3 from run because it ended
since the list, it runs `rex new magpie --window=<t> -- /bin/sh -c ...`,
whose first tab is so named. Labels go as --flag=value and the rename's
positionals after --, so a title starting with "-" stays a title. Exit 4
still says to open Rex. rexRun now gives stdout only (for the JSON), and
rex's stderr comes back through ExitError for the message.
docs/reference.md's Session terminal paragraph says it.

Every flag was checked against the real rex CLI, not the report: the
snapshot build 0.0.1793420730-g6d0d9a (rex-darwin-arm64.zip from
blob.superlogical.com, sha256 checked against the release API) on mote,
in a sandbox HOME and XDG_RUNTIME_DIR, where rex autostarts a server of
its own. `rex new --help`, `run --help`, `window rename --help`; by hand
with 0, 1, 2 sessions and two labelled magpie/MAGPIE: no -s exits 3
"not found: no sessions" with 0 and "ambiguous" with 2; `new --label`
exits 2; `run -s <full id>` works with any number; `-s magpie` with two
so labelled exits 3 ambiguous; `rex new magpie --window=<t>` names the
first tab; rename sets the tab's label.

Tests: TestOpenInRex runs a fake rex modelled on those answers (target
by full ID or any-case label, 3 for not found and ambiguous alike, 2 for
new --label) with no session, one other, two others, magpie's among two
and two labelled magpie, opening twice each: one magpie session made,
then used, both tabs named. Also a session that ends between ls and run,
exit 4 and exit 1. TestOpenInRexReal runs the same cases against the real
rex when MAGPIE_TEST_REX names one (skipped otherwise), with a server of
its own that it kills and stops at the end.
TestDiscoverTerminalsOffersRex uses the fake with two sessions.

Ran, through mote-run at this tree rebased on origin/main f85a221c9:
- MAGPIE_TEST_REX=<real rex> go test -count=1 ./internal/gui: every test
  ok, TestOpenInRexReal included, except TestSettingsSaveKeepsWhatItDoes-
  NotSend (#4514) and TestMainWindowCorners/macOS_26_SDK (#3949), both
  red the same run alone on a detached origin/main f85a221c9.
- gofmt -l; go vet ./internal/gui; GOOS=linux -tags nogui and
  GOOS=windows go vet ./internal/gui and go build .: ok.
- No rex server or /tmp/rx* left after the tests.

Broke by hand, each red, then restored: the old openInRex (run with no
-s, then new --label): every TestOpenInRex case, the discovery test and
TestOpenInRexReal red ("unknown flag: --label"); the session lookup made
to find none: a second magpie session each time, red in the fake and
the real test; the window rename left out: tabs "Window <id>", red in
both.

Not tried: the Rex app itself (its download needs a Discord sign-in),
so whether Rex.app switches to the magpie session when a tab is added
from outside is not seen; nor whether an autostarted CLI server could
differ from the app's when the app is closed. Not the full go test ./...
(only internal/gui changed), no GUI Playwright run (no JS changed), not
run on Linux or Windows.
2026-10-31 21:38:56 +08:00

265 lines
7.6 KiB
Go

package gui
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"time"
"unicode/utf8"
"github.com/yetone/magpie/internal/proc"
)
// Rex (superlogical.com/rex, a terminal multiplexer) claims no .command
// file, only public.item and rex://, so Launch Services never lists it as
// a terminal and `open -a` can't hand it a script (StringKe, #4565). Its
// own CLI opens a command in it, in a tab of a Rex session of magpie's own
// (openInRex). Rex is offered when its CLI is found, on PATH or in the app.
const rexBundleID = "com.superlogical.rex"
// rexFound is the rex CLI, or "" with none: a var so a test puts a fake.
var rexFound = findRex
var rexMemo struct {
sync.Mutex
at time.Time
path string
}
// findRex is the rex program: one on PATH, else one in a Rex app in
// /Applications or ~/Applications (the app puts its own on PATH only in
// the terminals it opens). Only a native program counts: Rex, the Perl
// deployment tool, installs a script named rex too. Kept a minute, as
// the settings ask on every state.
func findRex() string {
rexMemo.Lock()
defer rexMemo.Unlock()
if !rexMemo.at.IsZero() && time.Since(rexMemo.at) < time.Minute {
return rexMemo.path
}
rexMemo.at, rexMemo.path = time.Now(), lookRex()
return rexMemo.path
}
func lookRex() string {
if p, err := proc.Look("rex"); err == nil && nativeProgram(p) {
return p
}
var apps []string
for _, dir := range []string{"/Applications", filepath.Join(os.Getenv("HOME"), "Applications")} {
m, _ := filepath.Glob(filepath.Join(dir, "Rex*.app"))
apps = append(apps, m...)
}
for _, app := range apps {
if p := rexInApp(app); p != "" {
return p
}
}
return ""
}
// rexInApp is an executable named rex under app's Contents, not in a
// framework, at most four folders down.
func rexInApp(app string) string {
root := filepath.Join(app, "Contents")
found := ""
filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error {
if err != nil || found != "" {
return fs.SkipDir
}
if d.IsDir() {
rel, _ := filepath.Rel(root, p)
if strings.Count(rel, string(filepath.Separator)) >= 4 || strings.HasSuffix(d.Name(), ".framework") || d.Name() == "Frameworks" {
return fs.SkipDir
}
return nil
}
if d.Name() == "rex" && nativeProgram(p) {
found = p
return fs.SkipAll
}
return nil
})
return found
}
// nativeProgram says p is an executable Mach-O or ELF file, not a script.
func nativeProgram(p string) bool {
st, err := os.Stat(p)
if err != nil || !st.Mode().IsRegular() || st.Mode().Perm()&0o111 == 0 {
return false
}
f, err := os.Open(p)
if err != nil {
return false
}
defer f.Close()
head := make([]byte, 4)
if _, err := f.Read(head); err != nil {
return false
}
for _, magic := range [][]byte{
{0xcf, 0xfa, 0xed, 0xfe}, {0xce, 0xfa, 0xed, 0xfe}, // Mach-O 64, 32
{0xca, 0xfe, 0xba, 0xbe}, // universal
{0x7f, 'E', 'L', 'F'},
} {
if bytes.Equal(head, magic) {
return true
}
}
return false
}
// withRex adds Rex to the terminals found when its CLI is, as the program
// that opens it.
func withRex(found terminalDiscovery) terminalDiscovery {
for _, app := range found.Apps {
if app.ID == rexBundleID {
return found
}
}
if p := rexFound(); p != "" {
found.Apps = append(found.Apps, terminalApp{ID: rexBundleID, Name: "Rex", Path: p})
}
return found
}
// rexScript is what a Rex tab runs: the command in sh, as the .command
// file runs it, then the login shell, so the tab stays when the agent
// quits. It and the label reach rex as arguments of their own, never
// parsed by a shell on the way.
func rexScript(command string) []string {
return []string{"--", "/bin/sh", "-c", command + "\nexec \"${SHELL:-/bin/zsh}\" -l"}
}
// rexLabel is a tab's label: the session's or agent's name on one line,
// cut to 60 characters; "magpie" when it has none.
func rexLabel(s string) string {
s = strings.Join(strings.Fields(s), " ")
if s == "" {
return "magpie"
}
if utf8.RuneCountInString(s) > 60 {
s = string([]rune(s)[:59]) + "…"
}
return s
}
// rexRun runs the rex CLI and gives its standard output; a failure is an
// *exec.ExitError holding what it wrote to standard error. A var so a test
// runs none.
var rexRun = func(ctx context.Context, bin string, args ...string) ([]byte, error) {
return proc.CommandContext(ctx, bin, args...).Output()
}
// rexShow brings Rex forward, a var so a test opens nothing.
var rexShow = func() { proc.Command("open", "-b", rexBundleID).Run() }
// rexSessionLabel labels the Rex session magpie opens its tabs in.
const rexSessionLabel = "magpie"
// openInRex opens command in a new tab of Rex, through its CLI at bin.
//
// Outside Rex the CLI has no session of its own, and `rex run` with no -s
// takes the only session there is: with none, or more than one (the usual
// case), it exits 3, which means a target not found or ambiguous (StringKe,
// #4565). Nor can the CLI tell which session the app shows. So magpie keeps
// a session of its own, labelled magpie: found by `rex ls`, given by its full
// ID (a label can be shared), a tab added with `rex run -s` and named for
// the session or agent with `rex window rename` (run's --label names the
// block, not the tab). With none, `rex new magpie --window <label>` makes it,
// its first tab so named; so does a 3 from run, the session having ended
// since the list.
func openInRex(bin, command, label string) error {
label = rexLabel(label)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
id, err := rexOwnSession(ctx, bin)
if err != nil {
return rexError(err)
}
if id != "" {
out, err := rexRun(ctx, bin, append([]string{"run", "-s", id, "--label=" + label, "--json"}, rexScript(command)...)...)
if err == nil {
var made struct {
WindowID string `json:"window_id"`
}
if json.Unmarshal(out, &made) == nil && made.WindowID != "" {
// the tab's name only: the tab is open either way
rexRun(ctx, bin, "window", "rename", "-s", id, "--", made.WindowID, label)
}
rexShow()
return nil
}
if rexExit(err) != 3 {
return rexError(err)
}
}
if _, err := rexRun(ctx, bin, append([]string{"new", rexSessionLabel, "--window=" + label}, rexScript(command)...)...); err != nil {
return rexError(err)
}
rexShow()
return nil
}
// rexOwnSession is the full ID of magpie's own Rex session, "" with none:
// one labelled exactly magpie, else one so labelled in another case.
func rexOwnSession(ctx context.Context, bin string) (string, error) {
out, err := rexRun(ctx, bin, "ls", "--json")
if err != nil {
return "", err
}
var list struct {
Sessions []struct {
ID string `json:"session_id"`
Label string `json:"label"`
} `json:"sessions"`
}
if err := json.Unmarshal(out, &list); err != nil {
return "", fmt.Errorf("rex ls --json: %w", err)
}
id := ""
for _, s := range list.Sessions {
if s.ID == "" {
continue
}
if s.Label == rexSessionLabel {
return s.ID, nil
}
if id == "" && strings.EqualFold(s.Label, rexSessionLabel) {
id = s.ID
}
}
return id, nil
}
// rexExit is the exit status of a rex that ran and failed, else -1.
func rexExit(err error) int {
if ee := (*exec.ExitError)(nil); errors.As(err, &ee) {
return ee.ExitCode()
}
return -1
}
// rexError says why rex failed: its own words, or that Rex's server
// couldn't be reached (exit 4).
func rexError(err error) error {
if rexExit(err) == 4 {
return errors.New("rex couldn't reach the Rex server: open Rex and try again")
}
if ee := (*exec.ExitError)(nil); errors.As(err, &ee) {
if msg := strings.TrimSpace(string(ee.Stderr)); msg != "" {
return fmt.Errorf("rex: %s", msg)
}
}
return fmt.Errorf("rex: %w", err)
}