gui: Rex is a session terminal, opened through its rex CLI (#4565)

Rex (com.superlogical.rex) claims no .command file, so Launch Services
never listed it and `open -a` can't hand it a script (StringKe).
Sessions' terminal list now offers Rex when its CLI is found: a native
`rex` on PATH, or one inside a Rex*.app in /Applications or
~/Applications (Rex puts rex on PATH only in its own terminals). Perl's
Rex installs a script named rex too, so only a Mach-O or ELF program
counts. Resume, carry and an agent's Open then run
`rex run --label <title> -- /bin/sh -c '<command>; exec login shell'`:
no shell parses the label or the command on the way. With no session
to add a tab to (exit 3) it runs `rex new`; with Rex's server not
running (exit 4) the error says to open Rex. Rex is then brought
forward with `open -b`. The GUI already lists s.terminalApps, so no
JS changed. reference.md's Session terminal says it.

Parts 2 to 4 of #4565 (accounts run per account, OSC 7501 status,
folder mapping) build on #992, which isn't merged; not done here.

Ran, at this tree on origin/main e90a635a9, through mote-run:
- go test ./internal/gui -run 'TestFindRex|TestOpenInRex|
  TestDiscoverTerminals|TestTerminalOpenArgs|TestAgentOpen': ok.
  TestOpenInRex runs the real sh script with SHELL=/usr/bin/true and
  checks the command ran in its folder, and a label holding $(...) and
  quotes stays one argument.
- go vet ./...; GOOS=linux (-tags nogui) and GOOS=windows go vet and
  go build: ok (at the pre-rebase head; go vet ./... again rebased).
- Full suite, go test -tags nogui -timeout 45m ./..., at the
  pre-rebase head: every package ok but internal/gui, red on
  TestSettingsSaveKeepsWhatItDoesNotSend (#4514, red the same on
  origin/main e90a635a9) and TestColdTurnsTaken (#4510). Rebased,
  internal/gui and internal/provider whole again: red on #4514 only.

Broke by hand, each red, then restored: withRex taken out of
discovery (TestDiscoverTerminalsOffersRex); the exit-3 fallback to
rex new turned off (TestOpenInRex: "rex: Error: no session"); the
native-program check dropped for PATH (TestFindRex took the Perl
script).

Not tried: the real Rex app or rex binary. Its installer needs a
Discord sign-in, so the CLI was driven from Rex's docs only; whether
`rex run` with no -s from outside Rex targets the shown session or
exits 3 is not confirmed. Not run on Linux or Windows (Rex's Linux
build, and the tests skip on Windows). No GUI Playwright run, as no
JS changed.
This commit is contained in:
yetone
2026-10-31 19:35:16 +08:00
parent 01813c681a
commit b9e5bc6cb3
7 changed files with 408 additions and 11 deletions
+11
View File
@@ -2996,6 +2996,17 @@ default listed once. With no saved choice, magpie follows that default, or
Terminal when the default is not a terminal. The *Resume* button still copies
the command.
Rex (superlogical.com/rex) is listed too when its `rex` program is found,
on `PATH` or inside a `Rex*.app` in `/Applications` or `~/Applications`
(only a native program counts, so the Perl tool also called `rex` is not
taken). Rex claims no `.command` files, so magpie opens it through its CLI:
`rex run --label <session or agent> -- /bin/sh -c '<command>; exec $SHELL -l'`
adds a tab to the session Rex shows. When there is no session to add to
(exit 3) it runs `rex new` instead, and when Rex's server can't be reached
(exit 4) it says to open Rex. The same applies to an agent's *Open in
terminal* and a carried-over session (StringKe, #4565;
[`terminal_rex.go`](../internal/gui/terminal_rex.go)).
Keys in the terminal version:
| Key | Action |
+1 -1
View File
@@ -39,7 +39,7 @@ func TestAgentOpenRunsOnlyTheAgent(t *testing.T) {
var opened []string
was := agentTerminal
agentTerminal = func(run, choice string) error { opened = append(opened, run); return nil }
agentTerminal = func(run, label, choice string) error { opened = append(opened, run); return nil }
t.Cleanup(func() { agentTerminal = was })
h := Handler(nil, nil)
+15 -7
View File
@@ -367,7 +367,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) {
fail(rw, errors.New("no such session"))
return
}
if err := openTerminal(run, settings.Load().SessionTerminal); err != nil {
if err := openTerminal(run, s.Title, settings.Load().SessionTerminal); err != nil {
fail(rw, err)
return
}
@@ -386,17 +386,17 @@ func sessionRoutes(mux *http.ServeMux, w Windows) {
fail(rw, errors.New("opening Terminal is only for the Mac app"))
return
}
run := ""
run, name := "", ""
for _, a := range agent.Detected() {
if a.ID == in.Agent {
run = agentCommand(a)
run, name = agentCommand(a), a.Name
}
}
if run == "" {
fail(rw, errors.New("no command starts this agent"))
return
}
if err := agentTerminal(run, settings.Load().SessionTerminal); err != nil {
if err := agentTerminal(run, name, settings.Load().SessionTerminal); err != nil {
fail(rw, err)
return
}
@@ -431,7 +431,7 @@ func sessionRoutes(mux *http.ServeMux, w Windows) {
return
}
if in.Open {
if err := openTerminal(c.Command, settings.Load().SessionTerminal); err != nil {
if err := openTerminal(c.Command, s.Title, settings.Load().SessionTerminal); err != nil {
fail(rw, err)
return
}
@@ -906,9 +906,10 @@ var agentTerminal = openTerminal
func shellQuote(s string) string { return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'" }
// openTerminal runs a command in the chosen Mac terminal through a .command
// file, as it would open from Finder: no Automation consent.
// file, as it would open from Finder: no Automation consent; in Rex,
// through its CLI, in a tab labelled label (terminal_rex.go).
// The shell is left open when the agent quits.
func openTerminal(command, choice string) error {
func openTerminal(command, label, choice string) error {
var found terminalDiscovery
if choice != terminalBundleID {
var err error
@@ -917,6 +918,13 @@ func openTerminal(command, choice string) error {
return err
}
}
if choice == rexBundleID {
for _, app := range found.Apps {
if app.ID == rexBundleID {
return openInRex(app.Path, command, label)
}
}
}
args, err := terminalOpenArgs(choice, found)
if err != nil {
return err
+3 -2
View File
@@ -15,7 +15,8 @@ import (
"unsafe"
)
// discoverTerminals asks Launch Services for apps that claim .command files.
// discoverTerminals asks Launch Services for apps that claim .command files,
// and adds Rex when its CLI is found (withRex).
func discoverTerminals() (terminalDiscovery, error) {
raw := C.magpieTerminalAppsJSON()
if raw == nil {
@@ -26,5 +27,5 @@ func discoverTerminals() (terminalDiscovery, error) {
if err := json.Unmarshal([]byte(C.GoString(raw)), &found); err != nil {
return terminalDiscovery{}, err
}
return found, nil
return withRex(found), nil
}
+43 -1
View File
@@ -2,7 +2,12 @@
package gui
import "testing"
import (
"context"
"slices"
"strings"
"testing"
)
func TestDiscoverTerminals(t *testing.T) {
found, err := discoverTerminals()
@@ -22,3 +27,40 @@ func TestDiscoverTerminals(t *testing.T) {
t.Fatalf("Terminal.app missing from .command handlers: %+v", found.Apps)
}
}
// StringKe (#4565): Rex claims no .command file, so Launch Services never
// lists it; it is offered when its CLI is found, and opened through it.
func TestDiscoverTerminalsOffersRex(t *testing.T) {
was := rexFound
t.Cleanup(func() { rexFound = was })
rexFound = func() string { return "/opt/rex/bin/rex" }
found, err := discoverTerminals()
if err != nil {
t.Fatal(err)
}
rex := slices.IndexFunc(found.Apps, func(a terminalApp) bool { return a.ID == rexBundleID })
if rex < 0 || found.Apps[rex].Path != "/opt/rex/bin/rex" || found.Apps[rex].Name != "Rex" {
t.Fatalf("Rex not offered with its CLI found: %+v", found.Apps)
}
var ran [][]string
wasRun, wasShow := rexRun, rexShow
t.Cleanup(func() { rexRun, rexShow = wasRun, wasShow })
rexRun = func(_ context.Context, bin string, args ...string) ([]byte, error) {
ran = append(ran, append([]string{bin}, args...))
return nil, nil
}
rexShow = func() {}
if err := openTerminal("cd '/tmp' && claude --resume x", "Fix the build", rexBundleID); err != nil {
t.Fatal(err)
}
if len(ran) != 1 || ran[0][0] != "/opt/rex/bin/rex" || ran[0][1] != "run" || !slices.Contains(ran[0], "Fix the build") {
t.Fatalf("rex ran %q, want one rex run labelled with the session's title", ran)
}
rexFound = func() string { return "" }
if err := openTerminal("claude", "", rexBundleID); err == nil || !strings.Contains(err.Error(), "no longer available") {
t.Fatalf("Rex chosen with no CLI found: %v, want it said to be unavailable", err)
}
if len(ran) != 1 {
t.Fatalf("rex ran again with none found: %q", ran)
}
}
+193
View File
@@ -0,0 +1,193 @@
package gui
import (
"bytes"
"context"
"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: `rex run` adds a tab to the session the
// app shows, running the command; with no session to add to (exit 3, a
// target not found) `rex new` makes one. 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
}
// rexArgs is how rex starts command in a new tab labelled label: the
// command in sh, as the .command file runs it, then the login shell, so
// the tab stays when the agent quits. Nothing is parsed by a shell on the
// way: the label and the script are arguments of their own.
func rexArgs(verb, command, label string) []string {
script := command + "\nexec \"${SHELL:-/bin/zsh}\" -l"
args := []string{verb}
if verb == "new" {
args = append(args, label) // the new session's label
}
args = append(args, "--label", label, "--", "/bin/sh", "-c", script)
return args
}
// 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, 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...).CombinedOutput()
}
// rexShow brings Rex forward, a var so a test opens nothing.
var rexShow = func() { proc.Command("open", "-b", rexBundleID).Run() }
// openInRex opens command in a new tab of Rex, through its CLI at bin.
func openInRex(bin, command, label string) error {
label = rexLabel(label)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
out, err := rexRun(ctx, bin, rexArgs("run", command, label)...)
if ee := (*exec.ExitError)(nil); errors.As(err, &ee) && ee.ExitCode() == 3 {
// no session to add a tab to: a session of its own
out, err = rexRun(ctx, bin, rexArgs("new", command, label)...)
}
if err != nil {
msg := strings.TrimSpace(string(out))
if ee := (*exec.ExitError)(nil); errors.As(err, &ee) && ee.ExitCode() == 4 {
return errors.New("rex couldn't reach the Rex server: open Rex and try again")
}
if msg != "" {
return fmt.Errorf("rex: %s", msg)
}
return fmt.Errorf("rex: %w", err)
}
rexShow()
return nil
}
+142
View File
@@ -0,0 +1,142 @@
package gui
import (
"context"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"testing"
"github.com/yetone/magpie/internal/proc"
)
var machO = []byte{0xcf, 0xfa, 0xed, 0xfe, 0, 0, 0, 0}
// The rex CLI counts only as a native program: Rex, the Perl deployment
// tool, puts a script named rex on PATH too (#4565). In the app it is
// found under Contents, the app's own Rex and a framework's passed over.
func TestFindRex(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Rex runs on macOS, Linux and FreeBSD")
}
dir := t.TempDir()
write := func(p string, b []byte, mode os.FileMode) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(p, b, mode); err != nil {
t.Fatal(err)
}
}
script := filepath.Join(dir, "perl", "rex")
write(script, []byte("#!/usr/bin/env perl\n"), 0o755)
native := filepath.Join(dir, "native", "rex")
write(native, machO, 0o755)
plain := filepath.Join(dir, "plain", "rex")
write(plain, machO, 0o644)
for p, want := range map[string]bool{script: false, native: true, plain: false, filepath.Join(dir, "none"): false} {
if got := nativeProgram(p); got != want {
t.Errorf("nativeProgram(%s) = %v, want %v", p, got, want)
}
}
app := filepath.Join(dir, "Rex Beta.app")
write(filepath.Join(app, "Contents", "MacOS", "Rex"), machO, 0o755)
write(filepath.Join(app, "Contents", "Frameworks", "X.framework", "rex"), machO, 0o755)
if got := rexInApp(app); got != "" {
t.Fatalf("rexInApp took %q: the app's own Rex or a framework's", got)
}
cli := filepath.Join(app, "Contents", "Resources", "bin", "rex")
write(cli, machO, 0o755)
if got := rexInApp(app); got != cli {
t.Fatalf("rexInApp = %q, want %q", got, cli)
}
// on PATH: the script is passed over for the one in the app
home := filepath.Join(dir, "home")
write(filepath.Join(home, "Applications", "Rex Beta.app", "Contents", "Resources", "bin", "rex"), machO, 0o755)
t.Setenv("HOME", home)
t.Setenv("PATH", filepath.Dir(script))
proc.Forget()
t.Cleanup(proc.Forget)
if got := lookRex(); !strings.HasPrefix(got, filepath.Join(home, "Applications")) && !strings.HasPrefix(got, "/Applications/") {
t.Fatalf("lookRex = %q with only Perl's rex on PATH, want the app's", got)
}
t.Setenv("PATH", filepath.Dir(native))
proc.Forget()
if got := lookRex(); got != native {
t.Fatalf("lookRex = %q, want the one on PATH %q", got, native)
}
}
// A session opens in a new Rex tab through `rex run`, its label and its
// script arguments of their own, never parsed by a shell on the way; with
// no session to add a tab to (exit 3) through `rex new`; with Rex's server
// not running (exit 4) it says to open Rex. The script runs the command,
// then the login shell, as the .command file does.
func TestOpenInRex(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Rex runs on macOS, Linux and FreeBSD")
}
wasRun, wasShow := rexRun, rexShow
t.Cleanup(func() { rexRun, rexShow = wasRun, wasShow })
shown := 0
rexShow = func() { shown++ }
exit := func(code string) error { return proc.Command("/bin/sh", "-c", "exit "+code).Run() }
var ran [][]string
codes := []string{}
rexRun = func(_ context.Context, bin string, args ...string) ([]byte, error) {
ran = append(ran, args)
if len(codes) > 0 {
c := codes[0]
codes = codes[1:]
return []byte("Error: no session"), exit(c)
}
return nil, nil
}
label := `it's "$(touch pwned)"`
if err := openInRex("/x/rex", "cd '/tmp' && claude", label); err != nil {
t.Fatal(err)
}
if len(ran) != 1 || ran[0][0] != "run" || shown != 1 {
t.Fatalf("ran %q shown %d, want one rex run and Rex shown", ran, shown)
}
i := slices.Index(ran[0], "--label")
if i < 0 || ran[0][i+1] != label || !slices.Equal(ran[0][len(ran[0])-4:len(ran[0])-1], []string{"--", "/bin/sh", "-c"}) {
t.Fatalf("rex run args %q", ran[0])
}
ran, codes, shown = nil, []string{"3"}, 0
if err := openInRex("/x/rex", "claude", "Claude Code"); err != nil {
t.Fatal(err)
}
if len(ran) != 2 || ran[1][0] != "new" || ran[1][1] != "Claude Code" || shown != 1 {
t.Fatalf("with no session: ran %q, want rex run then rex new", ran)
}
ran, codes, shown = nil, []string{"4"}, 0
if err := openInRex("/x/rex", "claude", ""); err == nil || !strings.Contains(err.Error(), "open Rex") || len(ran) != 1 || shown != 0 {
t.Fatalf("server not running: %v, ran %q, shown %d", err, ran, shown)
}
ran, codes = nil, []string{"1"}
if err := openInRex("/x/rex", "claude", ""); err == nil || !strings.Contains(err.Error(), "no session") {
t.Fatalf("rex failing: %v, want its output", err)
}
// the script, run as Rex runs it
dir := t.TempDir()
args := rexArgs("run", "cd "+shellQuote(dir)+" && echo ran > out", "x")
t.Setenv("SHELL", "/usr/bin/true")
if out, err := proc.Command(args[len(args)-3], args[len(args)-2:]...).CombinedOutput(); err != nil {
t.Fatalf("script: %v %s", err, out)
}
if b, _ := os.ReadFile(filepath.Join(dir, "out")); string(b) != "ran\n" {
t.Fatalf("the command didn't run in its folder: %q", b)
}
if got := rexLabel(" a\nlong " + strings.Repeat("x", 80)); !strings.HasPrefix(got, "a long x") || len([]rune(got)) != 60 || rexLabel("") != "magpie" {
t.Fatalf("rexLabel: %q", got)
}
}