Files
magpie/internal/gui/terminal_rex_test.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

434 lines
13 KiB
Go

package gui
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"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)
}
}
// fakeRex models the rex CLI as Rex's server answered it (snapshot
// 0.0.1793420730, run from outside Rex): a session target is a full ID or
// a label, any case; one matching nothing or more than one exits 3, and so
// does run with no -s unless there is exactly one session. `rex new` takes
// no --label (exit 2). down makes every call exit 4.
type fakeRex struct {
t *testing.T
sessions []fakeRexSession
ran [][]string
down bool
seq int
bin string // the last rex run
}
type fakeRexSession struct {
id, label string
windows []string // each tab's label
ids []string // each tab's window ID
}
func (f *fakeRex) fail(code int, msg string) ([]byte, error) {
err := proc.Command("/bin/sh", "-c", fmt.Sprintf("exit %d", code)).Run()
ee := err.(*exec.ExitError)
ee.Stderr = []byte(msg)
return nil, ee
}
func (f *fakeRex) target(s string) (int, string) {
var hit []int
for i, x := range f.sessions {
if x.id == s {
return i, ""
}
}
for i, x := range f.sessions {
if strings.EqualFold(x.label, s) {
hit = append(hit, i)
}
}
switch len(hit) {
case 0:
return -1, fmt.Sprintf("Error: session target %q not found", s)
case 1:
return hit[0], ""
}
return -1, fmt.Sprintf("Error: session target %q is ambiguous", s)
}
func (f *fakeRex) run(_ context.Context, bin string, args ...string) ([]byte, error) {
f.ran, f.bin = append(f.ran, args), bin
if f.down {
return f.fail(4, "Error: server unreachable")
}
flags, rest := map[string]string{}, []string{}
for i := 1; i < len(args); i++ {
a := args[i]
if a == "--" {
rest = append(rest, args[i+1:]...)
break
}
if !strings.HasPrefix(a, "-") {
rest = append(rest, a)
continue
}
k, v, eq := strings.Cut(strings.TrimLeft(a, "-"), "=")
if !eq && k != "json" && i+1 < len(args) {
i++
v = args[i]
}
flags[k] = v
}
switch args[0] {
case "ls":
var b strings.Builder
b.WriteString(`{"sessions":[`)
for i, x := range f.sessions {
if i > 0 {
b.WriteString(",")
}
fmt.Fprintf(&b, `{"session_id":%q,"label":%q}`, x.id, x.label)
}
b.WriteString("]}")
return []byte(b.String()), nil
case "new":
if _, ok := flags["label"]; ok {
return f.fail(2, "Error: unknown flag: --label")
}
f.seq++
x := fakeRexSession{id: fmt.Sprintf("session:%04d", f.seq), label: rest[0]}
w := flags["window"]
if w == "" {
w = "Window 1"
}
x.windows, x.ids = []string{w}, []string{fmt.Sprintf("window:%04d", f.seq)}
f.sessions = append(f.sessions, x)
return []byte(x.id + "\n"), nil
case "run":
i := -1
if s, ok := flags["s"]; ok {
var msg string
if i, msg = f.target(s); i < 0 {
return f.fail(3, msg)
}
} else if len(f.sessions) == 1 {
i = 0
} else if len(f.sessions) == 0 {
return f.fail(3, "Error: session target default not found: no sessions")
} else {
return f.fail(3, "Error: session target default is ambiguous: multiple sessions are available")
}
f.seq++
w := fmt.Sprintf("window:%04d", f.seq)
f.sessions[i].windows = append(f.sessions[i].windows, "Window "+w[7:])
f.sessions[i].ids = append(f.sessions[i].ids, w)
return []byte(fmt.Sprintf(`{"window_id":%q,"block_ids":["block:%04d"],"revision":2}`, w, f.seq)), nil
case "window":
i, msg := f.target(flags["s"])
if args[1] != "rename" || len(rest) != 3 || i < 0 {
return f.fail(3, msg)
}
j := slices.Index(f.sessions[i].ids, rest[1])
if j < 0 {
return f.fail(3, "Error: window target not found")
}
f.sessions[i].windows[j] = rest[2]
return nil, nil
}
f.t.Fatalf("fake rex: %q", args)
return nil, nil
}
func (f *fakeRex) use(t *testing.T) {
wasRun, wasShow := rexRun, rexShow
t.Cleanup(func() { rexRun, rexShow = wasRun, wasShow })
rexRun, rexShow = f.run, func() {}
}
// A session opens in a tab of a Rex session of magpie's own, labelled
// magpie, whether Rex has no session, one or several (StringKe, #4565: run
// with no -s exits 3 for none and for several alike, and `rex new` has no
// --label). The tab is named for the session; the label and the script
// stay arguments of their own, never parsed by a shell on the way. With
// Rex's server not running (exit 4) it says to open Rex.
func TestOpenInRex(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("Rex runs on macOS, Linux and FreeBSD")
}
label := `it's "$(touch pwned)"`
for _, tc := range []struct {
name string
sessions []fakeRexSession
}{
{"no session", nil},
{"one session", []fakeRexSession{{id: "session:a1", label: "work"}}},
{"two sessions", []fakeRexSession{{id: "session:a1", label: "okcall"}, {id: "session:a2", label: "cswap"}}},
{"magpie's and two more", []fakeRexSession{{id: "session:a1", label: "okcall"}, {id: "session:a2", label: "Magpie"}, {id: "session:a3", label: "cswap"}}},
{"two named magpie", []fakeRexSession{{id: "session:a1", label: "MAGPIE"}, {id: "session:a2", label: "magpie"}}},
} {
t.Run(tc.name, func(t *testing.T) {
f := &fakeRex{t: t, sessions: slices.Clone(tc.sessions)}
f.use(t)
for range 2 {
if err := openInRex("/x/rex", "cd '/tmp' && claude", label); err != nil {
t.Fatalf("%v; ran %q", err, f.ran)
}
}
var mine []fakeRexSession
for _, s := range f.sessions {
if strings.EqualFold(s.label, "magpie") {
mine = append(mine, s)
}
}
own := 0
for _, s := range tc.sessions {
if strings.EqualFold(s.label, "magpie") {
own++
}
}
if own == 0 && (len(mine) != 1 || mine[0].label != "magpie") {
t.Fatalf("sessions %+v, want one session labelled magpie made", f.sessions)
}
if want := len(tc.sessions) + max(0, 1-own); len(f.sessions) != want {
t.Fatalf("sessions %+v, want %d: magpie's made once, then used", f.sessions, want)
}
tabs := 0
for _, s := range f.sessions {
for _, w := range s.windows {
if w == label {
tabs++
}
}
}
if tabs != 2 {
t.Fatalf("sessions %+v, want two tabs named %q", f.sessions, label)
}
for _, a := range f.ran {
if a[0] == "run" && !slices.Contains(a, "--label="+label) || a[0] == "new" && !slices.Contains(a, "--window="+label) {
t.Fatalf("rex %q: the label not an argument of its own", a)
}
if i := slices.Index(a, "--"); (a[0] == "run" || a[0] == "new") && (i < 0 || !slices.Equal(a[i:i+3], []string{"--", "/bin/sh", "-c"})) {
t.Fatalf("rex %q: not the script in sh", a)
}
}
})
}
// the session ended between the list and the run: a new one
f := &fakeRex{t: t, sessions: []fakeRexSession{{id: "session:a1", label: "magpie"}}}
f.use(t)
wasRun := rexRun
rexRun = func(ctx context.Context, bin string, args ...string) ([]byte, error) {
if args[0] == "run" {
f.sessions = nil
}
return wasRun(ctx, bin, args...)
}
if err := openInRex("/x/rex", "claude", "Claude Code"); err != nil {
t.Fatal(err)
}
if len(f.sessions) != 1 || f.sessions[0].windows[0] != "Claude Code" {
t.Fatalf("sessions %+v, want a new magpie session", f.sessions)
}
f = &fakeRex{t: t, down: true}
f.use(t)
if err := openInRex("/x/rex", "claude", ""); err == nil || !strings.Contains(err.Error(), "open Rex") || len(f.ran) != 1 {
t.Fatalf("server not running: %v, ran %q", err, f.ran)
}
f = &fakeRex{t: t}
f.use(t)
rexRun = func(context.Context, string, ...string) ([]byte, error) { return f.fail(1, "Error: boom") }
if err := openInRex("/x/rex", "claude", ""); err == nil || !strings.Contains(err.Error(), "boom") {
t.Fatalf("rex failing: %v, want its output", err)
}
// the script, run as Rex runs it
dir := t.TempDir()
args := rexScript("cd " + shellQuote(dir) + " && echo ran > out")
t.Setenv("SHELL", "/usr/bin/true")
if out, err := proc.Command(args[1], 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)
}
}
// The same against the real rex, when MAGPIE_TEST_REX names one: a server
// of the test's own (rex starts one for the socket in XDG_RUNTIME_DIR),
// with no session, one and two of others, then magpie's among them.
func TestOpenInRexReal(t *testing.T) {
bin := os.Getenv("MAGPIE_TEST_REX")
if bin == "" {
t.Skip("MAGPIE_TEST_REX names no rex program")
}
run, err := os.MkdirTemp("/tmp", "rx") // a socket path's room is short
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(run) })
t.Setenv("HOME", t.TempDir())
t.Setenv("XDG_RUNTIME_DIR", run)
t.Setenv("SHELL", "/bin/sh")
for _, k := range []string{"REX_SESSION", "REX_BLOCK", "REX_SERVER", "REX_CLIENT"} {
t.Setenv(k, "")
os.Unsetenv(k)
}
wasShow := rexShow
t.Cleanup(func() { rexShow = wasShow })
rexShow = func() {}
rex := func(args ...string) []byte {
t.Helper()
out, err := rexRun(context.Background(), bin, args...)
if err != nil {
t.Fatalf("rex %q: %v", args, rexError(err))
}
return out
}
t.Cleanup(func() {
ids, _ := rexRun(context.Background(), bin, "ls", "-q", "--short=false")
if f := strings.Fields(string(ids)); len(f) > 0 {
rexRun(context.Background(), bin, append([]string{"kill"}, f...)...)
}
rexRun(context.Background(), bin, "server", "stop")
})
type session struct {
ID string `json:"session_id"`
Label string `json:"label"`
}
list := func() []session {
var l struct{ Sessions []session }
if err := json.Unmarshal(rex("ls", "--json"), &l); err != nil {
t.Fatal(err)
}
return l.Sessions
}
tabs := func(id string) []string {
var w struct {
Windows []struct{ Label string }
}
if err := json.Unmarshal(rex("window", "ls", "-s", id, "--json"), &w); err != nil {
t.Fatal(err)
}
var l []string
for _, x := range w.Windows {
l = append(l, x.Label)
}
return l
}
mine := func() string {
t.Helper()
id := ""
for _, s := range list() {
if s.Label == "magpie" {
if id != "" {
t.Fatalf("two magpie sessions: %+v", list())
}
id = s.ID
}
}
if id == "" {
t.Fatalf("no magpie session: %+v", list())
}
return id
}
open := func(label string) {
t.Helper()
if err := openInRex(bin, "sleep 120", label); err != nil {
t.Fatalf("with sessions %+v: %v", list(), err)
}
}
open(`it's "$(touch pwned)"`) // no session
if got := tabs(mine()); !slices.Equal(got, []string{`it's "$(touch pwned)"`}) {
t.Fatalf("no session: tabs %q", got)
}
rex("kill", mine())
rex("new", "work", "--", "sleep", "120")
open("one") // one of another's
if got := tabs(mine()); !slices.Equal(got, []string{"one"}) {
t.Fatalf("one session: tabs %q", got)
}
rex("kill", mine())
rex("new", "notes", "--", "sleep", "120")
open("two") // two of others'
if got := tabs(mine()); !slices.Equal(got, []string{"two"}) {
t.Fatalf("two sessions: tabs %q", got)
}
open("-three") // magpie's among them: a tab added to it
if got := tabs(mine()); !slices.Equal(got, []string{"two", "-three"}) || len(list()) != 3 {
t.Fatalf("magpie's and two: tabs %q, sessions %+v", got, list())
}
}