feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+84
View File
@@ -0,0 +1,84 @@
package automationcli
import (
"fmt"
"strings"
)
// usageError is a command line the command does not take.
type usageError struct{ msg string }
func (e *usageError) Error() string { return e.msg }
func usagef(format string, args ...any) error {
return &usageError{fmt.Sprintf(format, args...)}
}
// args are a command's arguments: its positional ones and its flags.
type args struct {
pos []string
bools map[string]bool
vals map[string]string
}
// flagSpec lists the flags a command takes: true for a flag with a
// value, false for a switch.
type flagSpec map[string]bool
// aliases are the short spellings of flags.
var aliases = map[string]string{"i": "interactive"}
// parseArgs parses a command's arguments, with flags anywhere among them
// (press @e2 --settle), written -f, --f, --f=v or --f v. "--" ends the
// flags; a negative number, as wheel's -120, and "-" alone are
// positional.
func parseArgs(in []string, spec flagSpec) (*args, error) {
a := &args{bools: map[string]bool{}, vals: map[string]string{}}
for i := 0; i < len(in); i++ {
s := in[i]
if s == "--" {
a.pos = append(a.pos, in[i+1:]...)
break
}
if len(s) < 2 || s[0] != '-' || (s[1] >= '0' && s[1] <= '9') || s[1] == '.' {
a.pos = append(a.pos, s)
continue
}
name := strings.TrimLeft(s, "-")
val, hasVal := "", false
if k, v, ok := strings.Cut(name, "="); ok {
name, val, hasVal = k, v, true
}
if long, ok := aliases[name]; ok {
name = long
}
takesValue, ok := spec[name]
if !ok {
return nil, usagef("unknown flag %s", s)
}
switch {
case takesValue && !hasVal:
if i+1 >= len(in) {
return nil, usagef("flag --%s needs a value", name)
}
i++
a.vals[name] = in[i]
case takesValue:
a.vals[name] = val
case hasVal:
return nil, usagef("flag --%s takes no value", name)
default:
a.bools[name] = true
}
}
return a, nil
}
// want checks that the command got between min and max positional
// arguments, max -1 for any number.
func (a *args) want(min, max int, usage string) error {
if len(a.pos) < min || (max >= 0 && len(a.pos) > max) {
return usagef("usage: mygo-automation %s", usage)
}
return nil
}
+973
View File
@@ -0,0 +1,973 @@
// Package automationcli is mygo-automation, the command line client of
// plugins/automation's socket made for agents: compact snapshots of a
// window's elements with short refs, actions on them, and diffs of what
// the window shows once it settled. The command lives in
// plugins/automation/cmd/mygo-automation, which embeds its SKILL.md; the
// package is here so that internal/e2e can drive a real app with it.
package automationcli
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"maps"
"os"
"path/filepath"
"runtime/debug"
"slices"
"strconv"
"strings"
"time"
)
// Options are what the command takes besides its arguments.
type Options struct {
// Skill is the SKILL.md that skills prints.
Skill []byte
// Dir keeps the sessions' files; empty, it is mygo/automation in the
// user's cache directory.
Dir string
}
const usage = `usage: mygo-automation <command> [arguments] [--session name]
Run "mygo-automation skills" for the guide: commands, selectors, refs, --settle.
open [--socket path] attach a session to an app (default: $MYGO_AUTOMATION)
close end the session (the app keeps running)
windows | window <w> list windows | pick the one commands target
snapshot [-i] [--full] [--json]
diff what changed since the last snapshot or diff
press | focus <sel> fill <sel> <text> act <sel> <action> [args]
click <sel>|<x> <y> pointer move|down|up <sel>|<x> <y>
wheel <sel>|<x> <y> <dx> <dy>
type <text> key <key>... menu <label>...
eval <script>|- wait [<sel>] [--text s] [--gone]
screenshot <file.png> skills version
`
// defaultTimeout is how long --settle and wait wait unless --timeout says.
const defaultTimeout = 10 * time.Second
// Run runs a command line, without the program's name, and returns the
// exit status: 0, 1 when the command failed, 2 when it was used wrong.
func Run(argv []string, stdin io.Reader, stdout, stderr io.Writer, opts Options) int {
err := run(argv, stdin, stdout, stderr, opts)
if err == nil {
return 0
}
var ue *usageError
if errors.As(err, &ue) {
fmt.Fprintf(stderr, "error: %v\n", err)
return 2
}
fmt.Fprintf(stderr, "error: %v\n", err)
return 1
}
// command is a command of the CLI.
type command struct {
flags flagSpec
// noSession marks the commands that run without an open session.
noSession bool
run func(*cmd) error
}
// The flags commands share.
var (
windowFlag = flagSpec{"window": true}
actFlags = flagSpec{"window": true, "settle": false, "timeout": true}
)
func with(specs ...flagSpec) flagSpec {
out := flagSpec{}
for _, s := range specs {
for k, v := range s {
out[k] = v
}
}
return out
}
var commands map[string]*command
// Commands returns the names of the commands, sorted.
func Commands() []string {
return slices.Sorted(maps.Keys(commands))
}
func init() {
pointerFlags := flagSpec{"button": true, "clicks": true, "mods": true}
commands = map[string]*command{
"open": {flags: flagSpec{"socket": true}, noSession: true, run: (*cmd).open},
"close": {noSession: true, run: (*cmd).close},
"windows": {flags: flagSpec{"json": false}, run: (*cmd).windows},
"window": {run: (*cmd).window},
"snapshot": {flags: with(windowFlag, flagSpec{"interactive": false, "full": false, "json": false}), run: (*cmd).snapshot},
"diff": {flags: windowFlag, run: (*cmd).diff},
"press": {flags: actFlags, run: func(c *cmd) error { return c.action("press", "press <sel>") }},
"focus": {flags: actFlags, run: func(c *cmd) error { return c.action("focus", "focus <sel>") }},
"fill": {flags: actFlags, run: func(c *cmd) error { return c.action("setValue", "fill <sel> <text>") }},
"act": {flags: actFlags, run: (*cmd).act},
"click": {flags: with(actFlags, pointerFlags), run: (*cmd).click},
"pointer": {flags: with(actFlags, pointerFlags), run: (*cmd).pointer},
"wheel": {flags: with(actFlags, flagSpec{"precise": false, "mods": true}), run: (*cmd).wheel},
"type": {flags: actFlags, run: (*cmd).typeText},
"key": {flags: with(actFlags, flagSpec{"down": false, "up": false}), run: (*cmd).key},
"menu": {flags: actFlags, run: (*cmd).menu},
"eval": {flags: with(windowFlag, flagSpec{"json": false}), run: (*cmd).eval},
"wait": {flags: with(actFlags, flagSpec{"text": true, "gone": false}), run: (*cmd).wait},
"screenshot": {flags: windowFlag, run: (*cmd).screenshot},
"skills": {noSession: true, run: func(c *cmd) error { _, err := c.stdout.Write(c.opts.Skill); return err }},
"version": {noSession: true, run: func(c *cmd) error { fmt.Fprintln(c.stdout, Version()); return nil }},
}
}
// cmd is a command running.
type cmd struct {
stdin io.Reader
stdout, stderr io.Writer
opts Options
a *args
s *session
c *client
timeout time.Duration
}
func run(argv []string, stdin io.Reader, stdout, stderr io.Writer, opts Options) error {
if len(argv) == 0 || argv[0] == "help" || argv[0] == "-h" || argv[0] == "--help" {
io.WriteString(stdout, usage)
if len(argv) == 0 {
return usagef("no command")
}
return nil
}
name := argv[0]
cm, ok := commands[name]
if !ok {
return usagef("no command %q: run mygo-automation help", name)
}
a, err := parseArgs(argv[1:], with(cm.flags, flagSpec{"session": true}))
if err != nil {
return err
}
c := &cmd{stdin: stdin, stdout: stdout, stderr: stderr, opts: opts, a: a, timeout: defaultTimeout}
if v, ok := a.vals["timeout"]; ok {
if c.timeout, err = parseTimeout(v); err != nil {
return err
}
}
if cm.noSession {
return cm.run(c)
}
if c.s, err = c.loadSession(); err != nil {
return err
}
var deadline time.Time
if c.timeout > 0 {
// A request the app never answers, as from a main thread that
// hangs, fails rather than holding the agent forever.
deadline = time.Now().Add(c.timeout + 30*time.Second)
}
if c.c, err = dial(c.s.Socket, deadline); err != nil {
return err
}
defer c.c.Close()
return cm.run(c)
}
// parseTimeout reads a duration, as 5s or 500ms; a bare number is in
// milliseconds, as the protocol's.
func parseTimeout(v string) (time.Duration, error) {
if ms, err := strconv.Atoi(v); err == nil && ms >= 0 {
return time.Duration(ms) * time.Millisecond, nil
}
d, err := time.ParseDuration(v)
if err != nil || d < 0 {
return 0, usagef("--timeout %s: write a duration, as 5s or 500ms (0 waits forever)", v)
}
return d, nil
}
// Version is the version of MyGo the command was built from: the
// module's version when go install got it, as v0.8.0, the version an
// app's go.mod requires when installed from the app's module, or (devel).
func Version() string {
bi, ok := debug.ReadBuildInfo()
if !ok {
return "(devel)"
}
mods := append([]*debug.Module{&bi.Main}, bi.Deps...)
for _, m := range mods {
if m.Path != "github.com/egoist/mygo" || m.Version == "" {
continue
}
if m.Replace != nil {
return m.Version + " (replaced by " + m.Replace.Path + ")"
}
return m.Version
}
return "(devel)"
}
// sessionName is the session's name: --session, else
// $MYGO_AUTOMATION_SESSION, else default.
func (c *cmd) sessionName() string {
if v, ok := c.a.vals["session"]; ok {
return v
}
if v := os.Getenv("MYGO_AUTOMATION_SESSION"); v != "" {
return v
}
return "default"
}
func (c *cmd) dir() (string, error) {
if c.opts.Dir != "" {
return c.opts.Dir, nil
}
cache, err := os.UserCacheDir()
if err != nil {
return "", err
}
return filepath.Join(cache, "mygo", "automation"), nil
}
func (c *cmd) loadSession() (*session, error) {
dir, err := c.dir()
if err != nil {
return nil, err
}
return loadSession(dir, c.sessionName())
}
func (c *cmd) ok() error {
_, err := io.WriteString(c.stdout, "ok\n")
return err
}
// open attaches a session to the app listening on the socket.
func (c *cmd) open() error {
if err := c.a.want(0, 0, "open [--socket path] [--session name]"); err != nil {
return err
}
path := c.a.vals["socket"]
if path == "" {
path = os.Getenv("MYGO_AUTOMATION")
}
if path == "" {
return usagef("open needs --socket <path>: the path the app's MYGO_AUTOMATION names")
}
path, err := filepath.Abs(path)
if err != nil {
return err
}
dir, err := c.dir()
if err != nil {
return err
}
name := c.sessionName()
file, err := sessionPath(dir, name)
if err != nil {
return usagef("%v", err)
}
cl, err := dial(path, time.Now().Add(time.Minute))
if err != nil {
return err
}
defer cl.Close()
var res struct{ Windows []windowInfo }
if err := cl.call("windows", nil, &res); err != nil {
return err
}
s := &session{Socket: path, Next: 1, name: name, path: file}
if old, err := loadSession(dir, name); err == nil {
// Opening again forgets what windows showed, and its refs go
// stale rather than come back for other elements.
s.Next = max(old.Next, 1)
}
if err := s.save(); err != nil {
return err
}
fmt.Fprintf(c.stdout, "opened %s (session %s)\n", path, name)
for _, w := range res.Windows {
fmt.Fprintln(c.stdout, windowLine(w, false))
}
return nil
}
// close ends the session, leaving the app running.
func (c *cmd) close() error {
if err := c.a.want(0, 0, "close [--session name]"); err != nil {
return err
}
dir, err := c.dir()
if err != nil {
return err
}
name := c.sessionName()
path, err := sessionPath(dir, name)
if err != nil {
return usagef("%v", err)
}
if err := os.Remove(path); errors.Is(err, os.ErrNotExist) {
fmt.Fprintf(c.stdout, "no session %s\n", name)
return nil
} else if err != nil {
return err
}
fmt.Fprintf(c.stdout, "closed session %s\n", name)
return nil
}
func (c *cmd) windows() error {
if err := c.a.want(0, 0, "windows [--json]"); err != nil {
return err
}
raw, err := c.c.callRaw("windows", nil)
if err != nil {
return err
}
if c.a.bools["json"] {
return c.printJSON(raw)
}
var res struct{ Windows []windowInfo }
if err := json.Unmarshal(raw, &res); err != nil {
return err
}
if len(res.Windows) == 0 {
fmt.Fprintln(c.stdout, "(no windows)")
}
for _, w := range res.Windows {
fmt.Fprintln(c.stdout, windowLine(w, w.ID == c.s.Window))
}
return nil
}
// window picks the window that commands target unless they name one.
func (c *cmd) window() error {
if err := c.a.want(1, 1, "window <w1|auto>"); err != nil {
return err
}
id, err := parseWindow(c.a.pos[0])
if err != nil {
return err
}
var res struct{ Windows []windowInfo }
if err := c.c.call("windows", nil, &res); err != nil {
return err
}
if id == 0 {
c.s.Window = 0
fmt.Fprintln(c.stdout, "commands target the focused window")
return c.s.save()
}
for _, w := range res.Windows {
if w.ID == id {
c.s.Window = id
fmt.Fprintln(c.stdout, windowLine(w, true))
return c.s.save()
}
}
return &protoError{"no_window", fmt.Sprintf("no window %d: run windows", id)}
}
// parseWindow reads a window, as w2 or 2; auto or 0 is the focused one.
func parseWindow(s string) (int, error) {
if s == "auto" || s == "focused" {
return 0, nil
}
n, err := strconv.Atoi(strings.TrimPrefix(s, "w"))
if err != nil || n < 0 {
return 0, usagef("window %q: write w1, 1 or auto", s)
}
return n, nil
}
// targetWindow is the window a command without a ref targets: --window,
// else the session's, else 0 for the focused one.
func (c *cmd) targetWindow() (int, error) {
if v, ok := c.a.vals["window"]; ok {
return parseWindow(v)
}
return c.s.Window, nil
}
func (c *cmd) printJSON(raw json.RawMessage) error {
var b bytes.Buffer
if err := json.Compact(&b, raw); err != nil {
return err
}
b.WriteByte('\n')
_, err := c.stdout.Write(b.Bytes())
return err
}
// tree reads the elements of a window, saying how to read a page instead.
func (c *cmd) tree(window int) (*tree, json.RawMessage, error) {
raw, err := c.c.callRaw("tree", map[string]any{"window": window})
if err != nil {
var pe *protoError
if errors.As(err, &pe) && pe.Code == "unsupported" {
what, _, _ := strings.Cut(pe.Message, ":")
return nil, nil, &protoError{pe.Code, what + ", which has no elements here: read it with eval"}
}
if errors.As(err, &pe) && pe.Code == "no_window" && window != 0 {
c.s.forget(window)
c.s.save()
}
return nil, nil, err
}
t := &tree{}
if err := json.Unmarshal(raw, t); err != nil {
return nil, nil, err
}
return t, raw, nil
}
func (c *cmd) snapshot() error {
if err := c.a.want(0, 0, "snapshot [-i] [--full] [--json] [--window w]"); err != nil {
return err
}
window, err := c.targetWindow()
if err != nil {
return err
}
t, raw, err := c.tree(window)
if err != nil {
return err
}
c.s.observe(t)
if err := c.s.save(); err != nil {
return err
}
if c.a.bools["json"] {
return c.printJSON(raw)
}
writeSnapshot(c.stdout, c.s.Seen[strconv.Itoa(t.Window)], t.Announcements, c.a.bools["interactive"], c.a.bools["full"])
return nil
}
func (c *cmd) diff() error {
if err := c.a.want(0, 0, "diff [--window w]"); err != nil {
return err
}
window, err := c.targetWindow()
if err != nil {
return err
}
return c.printDiff(window)
}
// printDiff prints what changed in the window since the last snapshot or
// diff, and takes what it shows now.
func (c *cmd) printDiff(window int) error {
t, _, err := c.tree(window)
if err != nil {
var pe *protoError
if errors.As(err, &pe) && pe.Code == "unsupported" {
// A page settled; it has no elements to compare.
fmt.Fprintln(c.stdout, "ok (a web page: read it with eval)")
return nil
}
return err
}
before := c.s.observe(t)
if err := c.s.save(); err != nil {
return err
}
lines := diff(before, c.s.Seen[strconv.Itoa(t.Window)], 1)
if len(lines) == 0 {
fmt.Fprintln(c.stdout, "(no changes)")
}
for _, l := range lines {
fmt.Fprintln(c.stdout, l)
}
writeAnnouncements(c.stdout, t.Announcements)
return nil
}
// done ends an action on window: with --settle, it waits for the window
// to settle and prints the diff; otherwise it prints ok.
func (c *cmd) done(window int) error {
if !c.a.bools["settle"] {
return c.ok()
}
if err := c.idle(window); err != nil {
var pe *protoError
if !errors.As(err, &pe) || pe.Code != "timeout" {
return err
}
fmt.Fprintf(c.stderr, "warning: the window did not settle in %v; the diff may miss what comes after\n", c.timeout)
}
return c.printDiff(window)
}
// idle waits for the window to settle, for --timeout.
func (c *cmd) idle(window int) error {
return c.c.call("idle", map[string]any{"window": window, "timeout": c.timeout.Milliseconds()}, nil)
}
// target is an element a selector names.
type target struct {
window int
id string
// ref is the selector when it is a ref, for errors.
ref string
}
// resolve finds the element a selector names: @e7 (a ref), key=<key>
// (the app's key) or id=<digits> (an element ID, as --json shows).
func (c *cmd) resolve(sel string) (target, error) {
if n, ok := parseRef(sel); ok {
w, id, err := c.s.lookup(n)
if err != nil {
return target{}, err
}
return target{w, id, ref(n)}, nil
}
window, err := c.targetWindow()
if err != nil {
return target{}, err
}
if id, ok := strings.CutPrefix(sel, "id="); ok {
if _, err := strconv.ParseUint(id, 10, 64); err != nil {
return target{}, usagef("selector %q: an element ID is a string of digits", sel)
}
return target{window: window, id: id}, nil
}
k, ok := strings.CutPrefix(sel, "key=")
if !ok {
return target{}, usagef("selector %q: write a ref (@e7), key=<key> or id=<digits>", sel)
}
want := keyJSON(k)
t, _, err := c.tree(window)
if err != nil {
return target{}, err
}
var found []string
for _, n := range t.Nodes {
var got bytes.Buffer
if len(n.Key) > 0 && json.Compact(&got, n.Key) == nil && bytes.Equal(got.Bytes(), want) {
found = append(found, n.ID)
}
}
switch len(found) {
case 0:
return target{}, &protoError{"no_element", fmt.Sprintf("window %d shows no element with the key %s", t.Window, want)}
case 1:
return target{window: t.Window, id: found[0]}, nil
}
return target{}, &protoError{"invalid_request", fmt.Sprintf("%d elements of window %d have the key %s: use a ref", len(found), t.Window, want)}
}
// gone turns the app's answer that a ref's element or window is gone
// into a stale ref.
func gone(t target, err error) error {
var pe *protoError
if t.ref == "" || !errors.As(err, &pe) {
return err
}
switch pe.Code {
case "no_element":
return &staleError{t.ref, fmt.Sprintf("window %d no longer shows its element", t.window)}
case "no_window":
return &staleError{t.ref, fmt.Sprintf("its window %d closed", t.window)}
}
return err
}
// actOn performs an action of assistive technology on an element.
func (c *cmd) actOn(t target, action string, extra map[string]any) error {
p := map[string]any{"window": t.window, "id": t.id, "action": action}
for k, v := range extra {
p[k] = v
}
if err := c.c.call("act", p, nil); err != nil {
return gone(t, err)
}
return c.done(t.window)
}
// action runs press, focus and fill.
func (c *cmd) action(action, use string) error {
n := 1
if action == "setValue" {
n = 2
}
if err := c.a.want(n, n, use+" [--settle]"); err != nil {
return err
}
t, err := c.resolve(c.a.pos[0])
if err != nil {
return err
}
var extra map[string]any
if action == "setValue" {
extra = map[string]any{"text": c.a.pos[1]}
}
return c.actOn(t, action, extra)
}
// actions are the protocol's actions, which act takes.
var actions = []string{"press", "focus", "increment", "decrement", "setValue", "insertText", "selectText", "scrollIntoView", "expand", "collapse"}
func (c *cmd) act() error {
const use = "act <sel> <action> [<text> | <from> <to>] [--settle]"
if err := c.a.want(2, 4, use); err != nil {
return err
}
action := c.a.pos[1]
if !slices.Contains(actions, action) {
return usagef("no action %q: %s", action, strings.Join(actions, ", "))
}
extra := map[string]any{}
switch rest := c.a.pos[2:]; {
case action == "setValue" || action == "insertText":
if len(rest) != 1 {
return usagef("usage: mygo-automation act <sel> %s <text>", action)
}
extra["text"] = rest[0]
case action == "selectText":
if len(rest) != 2 {
return usagef("usage: mygo-automation act <sel> selectText <from> <to>")
}
for i, k := range []string{"from", "to"} {
n, err := strconv.Atoi(rest[i])
if err != nil || n < 0 {
return usagef("selectText takes rune offsets, not %q", rest[i])
}
extra[k] = n
}
case len(rest) > 0:
return usagef("action %s takes no arguments", action)
}
t, err := c.resolve(c.a.pos[0])
if err != nil {
return err
}
return c.actOn(t, action, extra)
}
// point reads where a pointer goes: an element's center, from pos[0], or
// x and y, from pos[0:2]. It returns the window, the point, and how many
// arguments it read.
func (c *cmd) point(pos []string) (window int, x, y float64, used int, t target, err error) {
if len(pos) >= 2 {
if x, err1 := strconv.ParseFloat(pos[0], 64); err1 == nil {
y, err2 := strconv.ParseFloat(pos[1], 64)
if err2 != nil {
return 0, 0, 0, 0, t, usagef("y %q is no number", pos[1])
}
window, err = c.targetWindow()
return window, x, y, 2, t, err
}
}
if len(pos) == 0 {
return 0, 0, 0, 0, t, usagef("a pointer needs a selector or x and y")
}
if t, err = c.resolve(pos[0]); err != nil {
return 0, 0, 0, 0, t, err
}
tr, _, err := c.tree(t.window)
if err != nil {
return 0, 0, 0, 0, t, gone(t, err)
}
for _, n := range tr.Nodes {
if n.ID == t.id {
b := n.Bounds
return tr.Window, b.X + b.Width/2, b.Y + b.Height/2, 1, t, nil
}
}
return 0, 0, 0, 0, t, gone(t, &protoError{"no_element", fmt.Sprintf("window %d shows no element %s", tr.Window, t.id)})
}
// pointerEvent makes an event of the pointer's flags.
func (c *cmd) pointerEvent(typ string, x, y float64) (inputEvent, error) {
ev := inputEvent{Type: typ, X: x, Y: y, Button: c.a.vals["button"]}
if v, ok := c.a.vals["clicks"]; ok {
n, err := strconv.Atoi(v)
if err != nil || n < 1 {
return ev, usagef("--clicks %q: 1 or more", v)
}
ev.Clicks = n
}
if v := c.a.vals["mods"]; v != "" {
ev.Mods = strings.Split(v, ",")
}
return ev, nil
}
// input sends events to a window, then ends as actions do.
func (c *cmd) input(window int, t target, evs ...inputEvent) error {
if err := c.c.call("input", map[string]any{"window": window, "events": evs}, nil); err != nil {
return gone(t, err)
}
return c.done(window)
}
func (c *cmd) click() error {
const use = "click <sel> | <x> <y> [--button left|right|middle] [--clicks n] [--mods shift,ctrl,alt,super,cmdOrCtrl] [--settle]"
if err := c.a.want(1, 2, use); err != nil {
return err
}
window, x, y, used, t, err := c.point(c.a.pos)
if err != nil {
return err
}
if used != len(c.a.pos) {
return usagef("usage: mygo-automation %s", use)
}
ev, err := c.pointerEvent("click", x, y)
if err != nil {
return err
}
return c.input(window, t, ev)
}
func (c *cmd) pointer() error {
const use = "pointer move|down|up <sel> | <x> <y> [--button b] [--clicks n] [--mods m] [--settle]"
if err := c.a.want(2, 3, use); err != nil {
return err
}
typ, ok := map[string]string{"move": "pointerMove", "down": "pointerDown", "up": "pointerUp"}[c.a.pos[0]]
if !ok {
return usagef("usage: mygo-automation %s", use)
}
window, x, y, used, t, err := c.point(c.a.pos[1:])
if err != nil {
return err
}
if used != len(c.a.pos)-1 {
return usagef("usage: mygo-automation %s", use)
}
ev, err := c.pointerEvent(typ, x, y)
if err != nil {
return err
}
return c.input(window, t, ev)
}
func (c *cmd) wheel() error {
const use = "wheel <sel> <dx> <dy> | <x> <y> <dx> <dy> [--precise] [--mods m] [--settle]"
if err := c.a.want(3, 4, use); err != nil {
return err
}
at := c.a.pos[:len(c.a.pos)-2]
window, x, y, used, t, err := c.point(at)
if err != nil {
return err
}
if used != len(at) {
return usagef("usage: mygo-automation %s", use)
}
var d [2]float64
for i, s := range c.a.pos[len(at):] {
if d[i], err = strconv.ParseFloat(s, 64); err != nil {
return usagef("wheel distance %q is no number", s)
}
}
ev := inputEvent{Type: "wheel", X: x, Y: y, DX: d[0], DY: d[1], Precise: c.a.bools["precise"]}
if v := c.a.vals["mods"]; v != "" {
ev.Mods = strings.Split(v, ",")
}
return c.input(window, t, ev)
}
func (c *cmd) typeText() error {
if err := c.a.want(1, 1, "type <text> [--settle]"); err != nil {
return err
}
window, err := c.targetWindow()
if err != nil {
return err
}
if c.a.pos[0] == "" {
return usagef("type needs text")
}
return c.input(window, target{}, inputEvent{Type: "text", Text: c.a.pos[0]})
}
func (c *cmd) key() error {
if err := c.a.want(1, -1, "key <key>... [--down|--up] [--settle], as key Enter or key CmdOrCtrl+A Backspace"); err != nil {
return err
}
typ := "key"
switch {
case c.a.bools["down"] && c.a.bools["up"]:
return usagef("key takes --down or --up, not both")
case c.a.bools["down"]:
typ = "keyDown"
case c.a.bools["up"]:
typ = "keyUp"
}
window, err := c.targetWindow()
if err != nil {
return err
}
evs := make([]inputEvent, len(c.a.pos))
for i, k := range c.a.pos {
evs[i] = inputEvent{Type: typ, Key: k}
}
return c.input(window, target{}, evs...)
}
func (c *cmd) menu() error {
if err := c.a.want(1, -1, "menu <label>... [--settle], as menu File \"New Window\""); err != nil {
return err
}
window, err := c.targetWindow()
if err != nil {
return err
}
if err := c.c.call("menu", map[string]any{"window": window, "path": c.a.pos}, nil); err != nil {
return err
}
return c.done(window)
}
func (c *cmd) eval() error {
if err := c.a.want(1, 1, "eval <script> | - [--json] [--window w]"); err != nil {
return err
}
script := c.a.pos[0]
if script == "-" {
b, err := io.ReadAll(c.stdin)
if err != nil {
return err
}
script = string(b)
}
window, err := c.targetWindow()
if err != nil {
return err
}
raw, err := c.c.callRaw("eval", map[string]any{"window": window, "script": script})
if err != nil {
var pe *protoError
if errors.As(err, &pe) && pe.Code == "unsupported" {
what, _, _ := strings.Cut(pe.Message, ":")
return &protoError{pe.Code, what + ": read it with snapshot (scripts reach only windows showing a web page, not web views inside native UI)"}
}
return err
}
var res struct{ Value json.RawMessage }
if err := json.Unmarshal(raw, &res); err != nil {
return err
}
if len(res.Value) == 0 {
res.Value = json.RawMessage("null")
}
var s string
if !c.a.bools["json"] && json.Unmarshal(res.Value, &s) == nil {
_, err := fmt.Fprintln(c.stdout, s)
return err
}
return c.printJSON(res.Value)
}
// pollEvery is how often wait reads the window again while what it
// waits for has not come.
const pollEvery = 50 * time.Millisecond
func (c *cmd) wait() error {
if err := c.a.want(0, 1, "wait [<sel>] [--text s] [--gone] [--timeout d] [--settle]"); err != nil {
return err
}
text, hasText := c.a.vals["text"]
if !hasText && len(c.a.pos) == 0 {
if c.a.bools["gone"] {
return usagef("wait --gone needs a selector or --text")
}
window, err := c.targetWindow()
if err != nil {
return err
}
if err := c.idle(window); err != nil {
return err
}
return c.done(window)
}
if hasText && len(c.a.pos) > 0 {
return usagef("wait takes a selector or --text, not both")
}
window, err := c.targetWindow()
if err != nil {
return err
}
// match tells whether the window shows what is waited for.
var match func(n *node) bool
var what string
if hasText {
what = "text " + strconv.Quote(text)
match = func(n *node) bool { return strings.Contains(n.Label, text) || strings.Contains(n.Value, text) }
} else {
sel := c.a.pos[0]
what = sel
if n, ok := parseRef(sel); ok {
w, id, err := c.s.lookup(n)
if err != nil {
return err
}
window = w
match = func(n *node) bool { return n.ID == id }
} else if id, ok := strings.CutPrefix(sel, "id="); ok {
match = func(n *node) bool { return n.ID == id }
} else if k, ok := strings.CutPrefix(sel, "key="); ok {
want := keyJSON(k)
match = func(n *node) bool {
var got bytes.Buffer
return len(n.Key) > 0 && json.Compact(&got, n.Key) == nil && bytes.Equal(got.Bytes(), want)
}
} else {
return usagef("selector %q: write a ref (@e7), key=<key> or id=<digits>", sel)
}
}
want := !c.a.bools["gone"]
start := time.Now()
for {
// Read the condition even while the window keeps drawing.
// Only --settle waits for idle, after the condition is met.
t, _, err := c.tree(window)
if err != nil {
return err
}
found := slices.ContainsFunc(t.Nodes, func(n node) bool { return match(&n) })
if found == want {
return c.done(window)
}
if c.timeout > 0 && time.Since(start) > c.timeout {
state := "does not show"
if !want {
state = "still shows"
}
return &protoError{"timeout", fmt.Sprintf("window %d %s %s after %v", t.Window, state, what, c.timeout)}
}
time.Sleep(pollEvery)
}
}
func (c *cmd) screenshot() error {
if err := c.a.want(1, 1, "screenshot <file.png> [--window w]"); err != nil {
return err
}
window, err := c.targetWindow()
if err != nil {
return err
}
var res struct {
PNG []byte
Width, Height int
}
if err := c.c.call("capture", map[string]any{"window": window}, &res); err != nil {
return err
}
path := c.a.pos[0]
if err := os.WriteFile(path, res.PNG, 0o644); err != nil {
return err
}
_, err = fmt.Fprintf(c.stdout, "%s %dx%d\n", path, res.Width, res.Height)
return err
}
+391
View File
@@ -0,0 +1,391 @@
package automationcli
import (
"bufio"
"bytes"
"encoding/json"
"net"
"os"
"path/filepath"
"slices"
"strings"
"sync"
"testing"
"github.com/egoist/mygo/internal/wait"
)
func TestParseArgs(t *testing.T) {
spec := flagSpec{"settle": false, "timeout": true, "interactive": false, "mods": true}
a, err := parseArgs([]string{"@e2", "--settle", "-i", "0", "-120", "--timeout=2s", "--mods", "shift,ctrl", "-.5", "-", "--", "--settle"}, spec)
if err != nil {
t.Fatal(err)
}
if !slices.Equal(a.pos, []string{"@e2", "0", "-120", "-.5", "-", "--settle"}) || !a.bools["settle"] || !a.bools["interactive"] || a.vals["timeout"] != "2s" || a.vals["mods"] != "shift,ctrl" {
t.Errorf("parsed %+v", a)
}
for _, bad := range [][]string{{"--nope"}, {"--timeout"}, {"--settle=1"}} {
if _, err := parseArgs(bad, spec); err == nil {
t.Errorf("%v parsed", bad)
}
}
}
// fakeApp answers the socket's requests as an app does, with a window of
// native UI (1) and one showing a page (2).
type fakeApp struct {
mu sync.Mutex
nodes []map[string]any
focus string
calls []string
// acted are the params of act and input requests.
acted []map[string]any
// idle can keep a request waiting while the app still draws.
idle func()
// trees are successive snapshots, as work changes what the app shows.
trees [][]map[string]any
}
func (f *fakeApp) answer(method string, p map[string]any) (any, *protoError) {
if method == "idle" && f.idle != nil {
f.idle()
}
f.mu.Lock()
defer f.mu.Unlock()
f.calls = append(f.calls, method)
window := 0
if w, ok := p["window"].(float64); ok {
window = int(w)
}
if window > 2 {
return nil, &protoError{"no_window", "no such window"}
}
page := window == 2
switch method {
case "windows":
return map[string]any{"windows": []map[string]any{
{"id": 1, "title": "Contacts", "kind": "content", "focused": true, "visible": true},
{"id": 2, "title": "Docs", "kind": "page", "url": "http://localhost/", "visible": true},
}}, nil
case "tree":
if page {
return nil, &protoError{"unsupported", "window 2 shows a web page: use eval"}
}
if len(f.trees) > 0 {
f.nodes, f.trees = f.trees[0], f.trees[1:]
}
return map[string]any{"window": 1, "focus": f.focus, "nodes": f.nodes}, nil
case "idle":
return map[string]any{}, nil
case "act":
f.acted = append(f.acted, p)
for _, n := range f.nodes {
if n["id"] == p["id"] {
if p["id"] == "11077037771207380721" && p["action"] == "press" && f.focus == "" {
// Add shows a text field.
f.nodes = append(f.nodes, map[string]any{"id": "42", "role": "textField", "label": "First name", "actions": []string{"focus", "setValue"}})
}
if p["action"] == "setValue" {
n["value"] = p["text"]
f.focus = n["id"].(string)
}
return map[string]any{}, nil
}
}
return nil, &protoError{"no_element", "window 1 shows no element " + p["id"].(string)}
case "input", "menu":
if page && method == "input" {
return nil, &protoError{"unsupported", "window 2 shows a web page: use eval"}
}
f.acted = append(f.acted, p)
return map[string]any{}, nil
case "eval":
if !page {
return nil, &protoError{"unsupported", "window 1 shows native UI, not a web page: use tree"}
}
if p["script"] == "document.title" {
return map[string]any{"value": "Docs"}, nil
}
return map[string]any{"value": map[string]any{"n": 1}}, nil
case "capture":
return map[string]any{"png": []byte("\x89PNG fake"), "width": 2, "height": 1}, nil
}
return nil, &protoError{"unknown_method", method}
}
// serve answers the socket's connections until the test ends.
func (f *fakeApp) serve(t *testing.T) string {
dir, err := os.MkdirTemp("", "mygo-automation")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { os.RemoveAll(dir) })
path := filepath.Join(dir, "app.sock")
l, err := net.Listen("unix", path)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { l.Close() })
go func() {
for {
c, err := l.Accept()
if err != nil {
return
}
go func() {
defer c.Close()
sc := bufio.NewScanner(c)
for sc.Scan() {
var req struct {
ID json.RawMessage
Method string
Params map[string]any
}
json.Unmarshal(sc.Bytes(), &req)
res, perr := f.answer(req.Method, req.Params)
line, _ := json.Marshal(map[string]any{"id": req.ID, "result": res, "error": perr})
if perr != nil {
line, _ = json.Marshal(map[string]any{"id": req.ID, "error": perr})
}
c.Write(append(line, '\n'))
}
}()
}
}()
return path
}
// cli runs the CLI's command lines in one directory of sessions.
type cli struct {
t *testing.T
dir string
}
// run runs a command line and returns its output and exit status.
func (c cli) run(args ...string) (string, int) {
c.t.Helper()
var out bytes.Buffer
code := Run(args, strings.NewReader("1 + 1"), &out, &out, Options{Dir: c.dir, Skill: []byte("---\nname: mygo-automation\n---\nguide\n")})
return out.String(), code
}
// must runs a command line that succeeds and checks its output.
func (c cli) must(want string, args ...string) {
c.t.Helper()
out, code := c.run(args...)
if code != 0 || out != want {
c.t.Errorf("mygo-automation %s: exit %d\n%s\nwant:\n%s", strings.Join(args, " "), code, out, want)
}
}
// fails runs a command line that fails, with an output that has want.
func (c cli) fails(code int, want string, args ...string) {
c.t.Helper()
out, got := c.run(args...)
if got != code || !strings.Contains(out, want) {
c.t.Errorf("mygo-automation %s: exit %d (want %d)\n%s\nwant it to say: %s", strings.Join(args, " "), got, code, out, want)
}
}
func TestCommands(t *testing.T) {
app := &fakeApp{nodes: []map[string]any{
{"id": "1", "role": "heading", "label": "Contacts"},
{"id": "11077037771207380721", "role": "button", "key": "add", "label": "Add", "states": []string{"focusable"}, "actions": []string{"press", "focus"}},
{"id": "3", "role": "list", "label": "People"},
{"id": "4", "parent": "3", "role": "listItem", "label": "Ada", "key": 7, "actions": []string{"press"}, "bounds": map[string]any{"x": 10, "y": 20, "width": 100, "height": 30}},
}}
path := app.serve(t)
c := cli{t, t.TempDir()}
c.fails(1, "no session \"default\": run mygo-automation open", "snapshot")
c.fails(2, "open needs --socket", "open")
c.must("opened "+path+" (session default)\nw1 [content] \"Contacts\" focused\nw2 [page] \"Docs\" url=http://localhost/\n", "open", "--socket", path)
c.must("@e2 [button] \"Add\" key=add\n@e4 [listItem] \"Ada\" key=7\n", "snapshot", "-i")
c.must("@e1 [heading] \"Contacts\"\n@e2 [button] \"Add\" key=add\n@e3 [list] \"People\"\n @e4 [listItem] \"Ada\" key=7\n", "snapshot")
// Acting, then what changed once the window settled, with the
// elements around the change and the new element's ref.
c.must("= @e4 [listItem] \"Ada\" key=7\n+ @e5 [textField] \"First name\"\n", "press", "@e2", "--settle")
c.must("= @e4 [listItem] \"Ada\" key=7\n- @e5 [textField] \"First name\"\n+ @e5 [textField] \"First name\" value=\"Ada\" focused\n", "fill", "@e5", "Ada", "--settle")
c.must("(no changes)\n", "diff")
c.must("ok\n", "press", "key=add")
if got := app.acted[len(app.acted)-1]; got["id"] != "11077037771207380721" || got["window"] != float64(1) {
t.Errorf("press key=add sent %v", got)
}
c.must("ok\n", "press", "key=7")
c.must("ok\n", "act", "@e5", "selectText", "0", "2")
if got := app.acted[len(app.acted)-1]; got["action"] != "selectText" || got["from"] != float64(0) || got["to"] != float64(2) {
t.Errorf("act selectText sent %v", got)
}
// Pointers go to an element's center, or to a point.
c.must("ok\n", "click", "@e4", "--button", "right", "--mods", "shift")
c.must("ok\n", "wheel", "@e4", "0", "-120", "--precise")
c.must("ok\n", "pointer", "down", "5", "6.5")
c.must("ok\n", "key", "CmdOrCtrl+A", "Backspace")
c.must("ok\n", "type", "Grace")
c.must("ok\n", "menu", "File", "New Window")
var events []any
for _, p := range app.acted[len(app.acted)-6:] {
if e, ok := p["events"].([]any); ok {
events = append(events, e...)
} else {
events = append(events, p["path"])
}
}
got, _ := json.Marshal(events)
want := `[{"button":"right","mods":["shift"],"type":"click","x":60,"y":35},{"dy":-120,"precise":true,"type":"wheel","x":60,"y":35},{"type":"pointerDown","x":5,"y":6.5},{"key":"CmdOrCtrl+A","type":"key"},{"key":"Backspace","type":"key"},{"text":"Grace","type":"text"},["File","New Window"]]`
if string(got) != want {
t.Errorf("events\n got %s\nwant %s", got, want)
}
// A ref whose element is gone is rejected, never given to another.
app.mu.Lock()
app.nodes = slices.Delete(app.nodes, 3, 4)
app.mu.Unlock()
c.fails(1, "stale ref @e4: window 1 no longer shows its element", "press", "@e4")
c.fails(1, "stale ref @e4: window 1 no longer shows its element", "click", "@e4")
c.must("= @e3 [list] \"People\"\n- @e4 [listItem] \"Ada\" key=7\n= @e5 [textField] \"First name\" value=\"Ada\" focused\n", "diff")
c.fails(1, "stale ref @e4: its element is gone", "press", "@e4")
c.fails(1, "stale ref @e9: no snapshot or diff", "press", "@e9")
c.fails(1, "no_element: window 1 shows no element with the key 7", "press", "key=7")
c.fails(2, `selector "Add"`, "press", "Add")
// Pages are read with eval; native UI is not.
c.must("w2 [page] \"Docs\" url=http://localhost/ selected\n", "window", "w2")
c.must("w1 [content] \"Contacts\" focused\nw2 [page] \"Docs\" url=http://localhost/ selected\n", "windows")
c.fails(1, "window 2 shows a web page, which has no elements here: read it with eval", "snapshot")
c.must("Docs\n", "eval", "document.title")
c.must("{\"n\":1}\n", "eval", "-")
c.must("\"Docs\"\n", "eval", "document.title", "--json")
c.must("ok (a web page: read it with eval)\n", "wait", "--settle")
c.fails(1, "window 1 shows native UI, not a web page: read it with snapshot", "eval", "1", "--window", "w1")
c.must("commands target the focused window\n", "window", "auto")
shot := filepath.Join(t.TempDir(), "shot.png")
c.must(shot+" 2x1\n", "screenshot", shot)
if b, err := os.ReadFile(shot); err != nil || string(b) != "\x89PNG fake" {
t.Errorf("the screenshot's file: %q, %v", b, err)
}
// Sessions keep refs of their own.
c.must("opened "+path+" (session b)\nw1 [content] \"Contacts\" focused\nw2 [page] \"Docs\" url=http://localhost/\n", "open", "--socket", path, "--session", "b")
c.must("@e1 [heading] \"Contacts\"\n@e2 [button] \"Add\" key=add\n@e3 [list] \"People\"\n@e4 [textField] \"First name\" value=\"Ada\" focused\n", "snapshot", "--session", "b")
c.fails(1, "stale ref @e4", "press", "@e4")
// Opening a session again makes its refs stale, never names others
// with them.
c.must("opened "+path+" (session b)\nw1 [content] \"Contacts\" focused\nw2 [page] \"Docs\" url=http://localhost/\n", "open", "--socket", path, "--session", "b")
c.fails(1, "stale ref @e1: its element is gone", "press", "@e1", "--session", "b")
c.must("@e6 [button] \"Add\" key=add\n@e8 [textField] \"First name\" value=\"Ada\" focused\n", "snapshot", "-i", "--session", "b")
c.must("---\nname: mygo-automation\n---\nguide\n", "skills")
c.must("closed session default\n", "close")
c.must("no session default\n", "close")
c.fails(1, "no session \"default\"", "snapshot")
c.fails(2, "no command \"nope\"", "nope")
}
func TestWaitText(t *testing.T) {
app := &fakeApp{nodes: []map[string]any{{"id": "1", "role": "text", "label": "Saving…"}}}
path := app.serve(t)
c := cli{t, t.TempDir()}
c.must("opened "+path+" (session default)\nw1 [content] \"Contacts\" focused\nw2 [page] \"Docs\" url=http://localhost/\n", "open", "--socket", path)
c.must("ok\n", "wait", "--text", "Saving")
c.fails(1, `timeout: window 1 does not show text "Saved" after 1ms`, "wait", "--text", "Saved", "--timeout", "1ms")
c.fails(1, `timeout: window 1 still shows text "Saving" after 1ms`, "wait", "--text", "Saving", "--gone", "--timeout", "1")
c.fails(2, "wait --gone needs", "wait", "--gone")
}
// A condition can be met while a window keeps drawing. Waiting for it
// must not need that drawing to stop, even with no timeout.
func TestWaitWhileDrawing(t *testing.T) {
ready := []map[string]any{{"id": "1", "role": "text", "label": "Ready", "key": "ready"}}
saving := []map[string]any{{"id": "1", "role": "text", "label": "Saving"}}
value := []map[string]any{{"id": "1", "role": "textField", "value": "Ready"}}
for _, tc := range []struct {
name string
args []string
trees [][]map[string]any
snapshot bool
code int
out string
}{
{"visible", []string{"--text", "Ready"}, [][]map[string]any{ready}, false, 0, "ok\n"},
{"no-timeout", []string{"--text", "Ready", "--timeout", "0"}, [][]map[string]any{ready}, false, 0, "ok\n"},
{"later", []string{"--text", "Ready", "--timeout", "0"}, [][]map[string]any{saving, ready}, false, 0, "ok\n"},
{"value", []string{"--text", "Ready", "--timeout", "0"}, [][]map[string]any{saving, value}, false, 0, "ok\n"},
{"key", []string{"key=ready", "--timeout", "0"}, [][]map[string]any{nil, ready}, false, 0, "ok\n"},
{"gone-text", []string{"--text", "Saving", "--gone", "--timeout", "0"}, [][]map[string]any{saving, ready}, false, 0, "ok\n"},
{"gone-id", []string{"id=1", "--gone", "--timeout", "0"}, [][]map[string]any{ready, nil}, false, 0, "ok\n"},
{"gone-ref", []string{"@e1", "--gone", "--timeout", "0"}, [][]map[string]any{ready, ready, nil}, true, 0, "ok\n"},
{"timeout", []string{"--text", "Ready", "--timeout", "1ms"}, [][]map[string]any{saving}, false, 1, "error: timeout: window 1 does not show text \"Ready\" after 1ms\n"},
} {
t.Run(tc.name, func(t *testing.T) {
app := &fakeApp{trees: tc.trees}
idle := make(chan struct{}, 1)
stopDrawing := make(chan struct{})
stop := sync.OnceFunc(func() { close(stopDrawing) })
defer stop()
app.idle = func() {
select {
case idle <- struct{}{}:
default:
}
<-stopDrawing
}
path := app.serve(t)
c := cli{t, t.TempDir()}
if out, code := c.run("open", "--socket", path); code != 0 {
t.Fatalf("open: exit %d: %s", code, out)
}
if tc.snapshot {
c.must("@e1 [text] \"Ready\" key=ready\n", "snapshot")
}
type result struct {
out string
code int
}
done := make(chan result, 1)
go func() {
out, code := c.run(append([]string{"wait"}, tc.args...)...)
done <- result{out, code}
}()
var got result
select {
case got = <-done:
case <-idle:
t.Error("condition wait needs the window to stop drawing")
stop()
got = wait.For(t, "the wait command to finish", done)
case <-wait.Context(t).Done():
t.Fatal("the wait command never finished or asked the app to settle")
}
if got.code != tc.code || got.out != tc.out {
t.Errorf("wait: exit %d: %s; want exit %d: %s", got.code, got.out, tc.code, tc.out)
}
})
}
}
func TestWaitSettles(t *testing.T) {
for _, condition := range []bool{false, true} {
app := &fakeApp{nodes: []map[string]any{{"id": "1", "role": "text", "label": "Ready"}}}
app.idle = func() {
app.mu.Lock()
defer app.mu.Unlock()
app.nodes = []map[string]any{{"id": "1", "role": "text", "label": "Settled"}}
}
path := app.serve(t)
c := cli{t, t.TempDir()}
if out, code := c.run("open", "--socket", path); code != 0 {
t.Fatalf("open: exit %d: %s", code, out)
}
if condition {
c.must("+ @e1 [text] \"Settled\"\n", "wait", "--text", "Ready", "--settle")
} else {
c.must("ok\n", "wait")
c.must("@e1 [text] \"Settled\"\n", "snapshot")
}
}
}
+162
View File
@@ -0,0 +1,162 @@
package automationcli
import (
"bufio"
"encoding/json"
"fmt"
"net"
"time"
)
// client sends requests to an app's socket, one at a time, as
// docs/plugins/automation.md describes.
type client struct {
conn net.Conn
r *bufio.Reader
n int
}
// dial connects to the socket at path. A request that the app does not
// answer by deadline fails, unless deadline is zero.
func dial(path string, deadline time.Time) (*client, error) {
conn, err := net.Dial("unix", path)
if err != nil {
return nil, fmt.Errorf("cannot reach the app at %s (did it quit? is MYGO_AUTOMATION set and the plugin imported?): %v", path, err)
}
conn.SetDeadline(deadline)
return &client{conn: conn, r: bufio.NewReader(conn)}, nil
}
func (c *client) Close() error { return c.conn.Close() }
// protoError is the error of an answer: a code from the protocol's table
// and its message.
type protoError struct {
Code string `json:"code"`
Message string `json:"message"`
}
func (e *protoError) Error() string { return e.Code + ": " + e.Message }
// call sends a request and decodes its result into result, unless nil.
// It returns the answer's error as a *protoError.
func (c *client) call(method string, params any, result any) error {
raw, err := c.callRaw(method, params)
if err != nil {
return err
}
if result != nil {
if err := json.Unmarshal(raw, result); err != nil {
return fmt.Errorf("%s: the app's answer: %v", method, err)
}
}
return nil
}
// callRaw sends a request and returns its result as the app wrote it.
func (c *client) callRaw(method string, params any) (json.RawMessage, error) {
c.n++
line, err := json.Marshal(map[string]any{"id": c.n, "method": method, "params": params})
if err != nil {
return nil, err
}
if _, err := c.conn.Write(append(line, '\n')); err != nil {
return nil, fmt.Errorf("%s: %v", method, err)
}
answer, err := c.r.ReadBytes('\n')
if err != nil {
return nil, fmt.Errorf("%s: the app did not answer: %v", method, err)
}
var res struct {
ID int `json:"id"`
Result json.RawMessage `json:"result"`
Error *protoError `json:"error"`
}
if err := json.Unmarshal(answer, &res); err != nil {
return nil, fmt.Errorf("%s: the app's answer: %v", method, err)
}
if res.Error != nil {
return nil, res.Error
}
if res.ID != c.n {
return nil, fmt.Errorf("%s: an answer to request %d, not %d", method, res.ID, c.n)
}
return res.Result, nil
}
// windowInfo is a window the windows method lists.
type windowInfo struct {
ID int `json:"id"`
Title string `json:"title"`
Kind string `json:"kind"`
URL string `json:"url,omitempty"`
Focused bool `json:"focused"`
Visible bool `json:"visible"`
}
type rect struct {
X float64 `json:"x"`
Y float64 `json:"y"`
Width float64 `json:"width"`
Height float64 `json:"height"`
}
// tree is the tree method's result.
type tree struct {
Window int `json:"window"`
Focus string `json:"focus,omitempty"`
Nodes []node `json:"nodes"`
Announcements []string `json:"announcements,omitempty"`
}
// node is an element of a tree, with the fields the protocol gives.
type node struct {
ID string `json:"id"`
Parent string `json:"parent,omitempty"`
Role string `json:"role"`
Key json.RawMessage `json:"key,omitempty"`
Label string `json:"label,omitempty"`
Value string `json:"value,omitempty"`
Placeholder string `json:"placeholder,omitempty"`
Description string `json:"description,omitempty"`
Shortcuts string `json:"keyShortcuts,omitempty"`
Bounds rect `json:"bounds"`
States []string `json:"states,omitempty"`
Actions []string `json:"actions,omitempty"`
Min *float64 `json:"min,omitempty"`
Max *float64 `json:"max,omitempty"`
Now *float64 `json:"now,omitempty"`
Step *float64 `json:"step,omitempty"`
Selection *[2]int `json:"selection,omitempty"`
Level int `json:"level,omitempty"`
PosInSet int `json:"posInSet,omitempty"`
SetSize int `json:"setSize,omitempty"`
RowCount int `json:"rowCount,omitempty"`
ColCount int `json:"colCount,omitempty"`
RowIndex int `json:"rowIndex,omitempty"`
ColIndex int `json:"colIndex,omitempty"`
RowSpan int `json:"rowSpan,omitempty"`
ColSpan int `json:"colSpan,omitempty"`
Current string `json:"current,omitempty"`
Complete string `json:"autoComplete,omitempty"`
WebView bool `json:"webView,omitempty"`
// RoleDescription and HasPopup are aria-roledescription and
// aria-haspopup.
RoleDescription string `json:"roleDescription,omitempty"`
HasPopup string `json:"hasPopup,omitempty"`
}
// inputEvent is an event of the input method.
type inputEvent struct {
Type string `json:"type"`
X float64 `json:"x,omitempty"`
Y float64 `json:"y,omitempty"`
Button string `json:"button,omitempty"`
Clicks int `json:"clicks,omitempty"`
DX float64 `json:"dx,omitempty"`
DY float64 `json:"dy,omitempty"`
Precise bool `json:"precise,omitempty"`
Key string `json:"key,omitempty"`
Mods []string `json:"mods,omitempty"`
Text string `json:"text,omitempty"`
}
+297
View File
@@ -0,0 +1,297 @@
package automationcli
import (
"bytes"
"encoding/json"
"fmt"
"io"
"regexp"
"strconv"
"strings"
)
// maxText is how many characters of a label or a value a line shows,
// unless full.
const maxText = 120
// line describes an element on a line, without its ref: its role, its
// label, value, key and key shortcuts, and its states, leaving out what
// it lacks. full adds what agents seldom need: placeholders under a
// label, descriptions, ranges, selections, levels, actions, bounds and
// the element's ID, and writes long text whole.
func line(n *node, focus string, full bool) string {
var b strings.Builder
b.WriteString("[" + n.Role + "]")
if n.Label != "" {
b.WriteString(" " + quote(n.Label, full))
}
if n.Value != "" {
b.WriteString(" value=" + quote(n.Value, full))
} else if n.Now != nil {
b.WriteString(" value=" + num(*n.Now))
}
if n.Placeholder != "" && (full || n.Label == "") {
b.WriteString(" placeholder=" + quote(n.Placeholder, full))
}
if len(n.Key) > 0 {
b.WriteString(" key=" + keyText(n.Key))
}
if n.Shortcuts != "" {
b.WriteString(" keyshortcuts=" + quote(n.Shortcuts, true))
}
for _, s := range n.States {
// Every control can take the focus: saying so is noise.
if s != "focusable" {
b.WriteString(" " + s)
}
}
if n.Current != "" {
b.WriteString(" current=" + n.Current)
}
if n.Complete != "" {
b.WriteString(" autocomplete=" + n.Complete)
}
if n.HasPopup != "" {
b.WriteString(" haspopup=" + n.HasPopup)
}
if n.RoleDescription != "" {
b.WriteString(" roledescription=" + quote(n.RoleDescription, full))
}
if n.ID == focus {
b.WriteString(" focused")
}
if n.WebView {
b.WriteString(" webview")
}
if !full {
return b.String()
}
if n.Description != "" {
b.WriteString(" description=" + quote(n.Description, true))
}
if n.Min != nil && n.Max != nil {
b.WriteString(" range=" + num(*n.Min) + ".." + num(*n.Max))
}
if n.Step != nil && *n.Step != 0 {
b.WriteString(" step=" + num(*n.Step))
}
if n.Selection != nil {
fmt.Fprintf(&b, " selection=%d,%d", n.Selection[0], n.Selection[1])
}
if n.Level != 0 {
fmt.Fprintf(&b, " level=%d", n.Level)
}
if n.SetSize != 0 {
fmt.Fprintf(&b, " item=%d/%d", n.PosInSet, n.SetSize)
}
// A table's or a grid's size and the place of a row or a cell in it,
// as the app gave them (aria-rowcount and the like), and the rows and
// columns a cell covers (aria-rowspan, aria-colspan).
for _, v := range [...]struct {
name string
n int
}{{"rowcount", n.RowCount}, {"colcount", n.ColCount}, {"rowindex", n.RowIndex}, {"colindex", n.ColIndex},
{"rowspan", n.RowSpan}, {"colspan", n.ColSpan}} {
if v.n != 0 {
fmt.Fprintf(&b, " %s=%d", v.name, v.n)
}
}
if len(n.Actions) > 0 {
b.WriteString(" actions=" + strings.Join(n.Actions, ","))
}
r := n.Bounds
fmt.Fprintf(&b, " bounds=%s,%s,%sx%s id=%s", num(r.X), num(r.Y), num(r.Width), num(r.Height), n.ID)
return b.String()
}
// quote quotes s, cut to maxText characters unless full.
func quote(s string, full bool) string {
if !full {
if r := []rune(s); len(r) > maxText {
return strconv.Quote(string(r[:maxText])+"…") + fmt.Sprintf(" (%d more)", len(r)-maxText)
}
}
return strconv.Quote(s)
}
func num(f float64) string { return strconv.FormatFloat(f, 'f', -1, 64) }
var bareKey = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_.:/-]*$`)
// keyText writes a key as selectors take it: a string that reads as no
// other value bare, other strings quoted, numbers and booleans as JSON
// writes them.
func keyText(k json.RawMessage) string {
var s string
if json.Unmarshal(k, &s) == nil && bareKey.MatchString(s) && s != "true" && s != "false" && s != "null" {
return s
}
var b bytes.Buffer
if json.Compact(&b, k) != nil {
return string(k)
}
return b.String()
}
// keyJSON is the JSON a key selector names: JSON as itself, as key=5,
// key=true or key="a b", anything else as a string.
func keyJSON(s string) []byte {
var v any
if json.Unmarshal([]byte(s), &v) == nil {
switch v.(type) {
case string, float64, bool:
var b bytes.Buffer
json.Compact(&b, []byte(s))
return b.Bytes()
}
}
b, _ := json.Marshal(s)
return b
}
// controls are the roles snapshot -i keeps even when they have no action
// now, as a disabled button.
var controls = map[string]bool{
"button": true, "link": true, "checkBox": true, "radio": true, "switch": true,
"slider": true, "textField": true, "popUpButton": true, "tab": true,
"menuButton": true, "toggleButton": true, "comboBox": true, "disclosure": true,
"stepper": true, "colorWell": true, "menuItem": true, "menuItemCheckBox": true,
"menuItemRadio": true, "treeItem": true,
}
// interactive tells whether snapshot -i shows n: controls, and elements
// with actions other than scrolling into view.
func interactive(n *node) bool {
if controls[n.Role] || n.WebView {
return true
}
for _, a := range n.Actions {
if a != "scrollIntoView" {
return true
}
}
return false
}
// writeSnapshot writes a window's elements, a line each, indented under
// the elements shown around them.
func writeSnapshot(w io.Writer, sn *seen, announcements []string, interactiveOnly, full bool) {
// inner is the depth of an element's children.
inner := make(map[string]int, len(sn.Nodes))
shown := 0
for i := range sn.Nodes {
n := &sn.Nodes[i]
depth := inner[n.Parent]
show := !interactiveOnly || interactive(n)
inner[n.ID] = depth
if !show {
continue
}
inner[n.ID] = depth + 1
shown++
fmt.Fprintf(w, "%s%s %s\n", strings.Repeat(" ", depth), ref(sn.Refs[n.ID]), line(n, sn.Focus, full))
}
switch {
case shown > 0:
case interactiveOnly && len(sn.Nodes) > 0:
fmt.Fprintln(w, "(no interactive elements: run snapshot without -i)")
default:
fmt.Fprintln(w, "(no elements)")
}
writeAnnouncements(w, announcements)
}
func writeAnnouncements(w io.Writer, announcements []string) {
for _, a := range announcements {
fmt.Fprintf(w, "announced %s\n", quote(a, false))
}
}
// windowLine describes a window on a line.
func windowLine(w windowInfo, selected bool) string {
var b strings.Builder
fmt.Fprintf(&b, "w%d [%s] %s", w.ID, w.Kind, quote(w.Title, false))
if w.URL != "" {
b.WriteString(" url=" + w.URL)
}
if w.Focused {
b.WriteString(" focused")
}
if !w.Visible {
b.WriteString(" hidden")
}
if selected {
b.WriteString(" selected")
}
return b.String()
}
// diffLine is a line of a diff: '+' an element added, '-' one gone or as
// it was, '=' one unchanged around them.
type diffLine struct {
op byte
ref int
text string
}
func (d diffLine) String() string { return string(d.op) + " " + ref(d.ref) + " " + d.text }
// diff compares what a window showed before with what it shows now, in
// the order of now, and keeps context unchanged elements around each
// change. An element whose line changed shows twice, as it was ('-') and
// as it is ('+'), with its ref; one gone shows with its ref, now stale.
func diff(before, now *seen, context int) []diffLine {
if before == nil {
before = &seen{}
}
at := make(map[string]int, len(before.Nodes))
for i, n := range before.Nodes {
if _, ok := at[n.ID]; !ok {
at[n.ID] = i
}
}
stays := make(map[string]bool, len(now.Nodes))
for _, n := range now.Nodes {
stays[n.ID] = true
}
var all []diffLine
next := 0
gone := func(upTo int) {
for ; next < upTo; next++ {
if n := &before.Nodes[next]; !stays[n.ID] {
all = append(all, diffLine{'-', before.Refs[n.ID], line(n, before.Focus, false)})
}
}
}
for i := range now.Nodes {
n := &now.Nodes[i]
r, text := now.Refs[n.ID], line(n, now.Focus, false)
p, ok := at[n.ID]
if !ok {
all = append(all, diffLine{'+', r, text})
continue
}
if p >= next {
gone(p)
next = p + 1
}
if was := line(&before.Nodes[p], before.Focus, false); was != text {
all = append(all, diffLine{'-', r, was}, diffLine{'+', r, text})
} else {
all = append(all, diffLine{'=', r, text})
}
}
gone(len(before.Nodes))
var out []diffLine
for i, d := range all {
keep := d.op != '='
for j := max(i-context, 0); !keep && j <= min(i+context, len(all)-1); j++ {
keep = all[j].op != '='
}
if keep {
out = append(out, d)
}
}
return out
}
+122
View File
@@ -0,0 +1,122 @@
package automationcli
import (
"encoding/json"
"strings"
"testing"
)
func f(v float64) *float64 { return &v }
func TestLine(t *testing.T) {
for _, c := range []struct {
n node
full bool
want string
}{
{node{ID: "1", Role: "text", Label: "Count: 0"}, false, `[text] "Count: 0"`},
{node{ID: "2", Role: "button", Label: "Add", Key: json.RawMessage(`"add"`), States: []string{"focusable", "disabled"}, Actions: []string{"press"}}, false, `[button] "Add" key=add disabled`},
// The focused element, a value, and a placeholder only under no label.
{node{ID: "3", Role: "textField", Label: "Name", Value: "Ada", Placeholder: "Your name"}, false, `[textField] "Name" value="Ada" focused`},
{node{ID: "4", Role: "textField", Placeholder: "Search"}, false, `[textField] placeholder="Search"`},
// Keys that read as other values, quoted; numbers as themselves.
{node{ID: "5", Role: "button", Key: json.RawMessage(`"true"`)}, false, `[button] key="true"`},
{node{ID: "5", Role: "button", Key: json.RawMessage(`"a b"`)}, false, `[button] key="a b"`},
{node{ID: "5", Role: "listItem", Key: json.RawMessage(`7`)}, false, `[listItem] key=7`},
// A slider's value, when it has no text for it.
{node{ID: "6", Role: "slider", Label: "Volume", Min: f(0), Max: f(1), Now: f(0.25), Step: f(0.05)}, false, `[slider] "Volume" value=0.25`},
{node{ID: "6", Role: "slider", Label: "Volume", Min: f(0), Max: f(1), Now: f(0.25), Step: f(0.05)}, true, `[slider] "Volume" value=0.25 range=0..1 step=0.05 bounds=0,0,0x0 id=6`},
{node{ID: "7", Role: "group", WebView: true}, false, `[group] webview`},
// What its suggestions complete, after its states.
{node{ID: "10", Role: "comboBox", Label: "City", States: []string{"focusable", "expanded"}, Complete: "list"}, false, `[comboBox] "City" expanded autocomplete=list`},
// The keys that press it, after its key.
{node{ID: "9", Role: "button", Label: "Redo", Key: json.RawMessage(`"redo"`), Shortcuts: "Ctrl+Shift+Z Ctrl+Y"}, false, `[button] "Redo" key=redo keyshortcuts="Ctrl+Shift+Z Ctrl+Y"`},
{
node{ID: "18446744073709551615", Role: "textField", Label: "Name", Value: "Ada", Placeholder: "Your name", Description: "Who", Selection: &[2]int{1, 3}, Actions: []string{"focus", "setValue"}, Bounds: rect{20, 90.5, 360, 32}},
true,
`[textField] "Name" value="Ada" placeholder="Your name" description="Who" selection=1,3 actions=focus,setValue bounds=20,90.5,360x32 id=18446744073709551615`,
},
{node{ID: "8", Role: "treeItem", Label: "src", Level: 2, PosInSet: 1, SetSize: 3, States: []string{"expandable", "expanded"}}, true, `[treeItem] "src" expandable expanded level=2 item=1/3 bounds=0,0,0x0 id=8`},
// A grid's size and a row's place in it, as the app gave them.
{node{ID: "10", Role: "grid", Label: "Sheet", RowCount: 10001, ColCount: 5, States: []string{"multiselectable"}}, true, `[grid] "Sheet" multiselectable rowcount=10001 colcount=5 bounds=0,0,0x0 id=10`},
{node{ID: "11", Role: "row", RowIndex: 4122}, true, `[row] rowindex=4122 bounds=0,0,0x0 id=11`},
{node{ID: "11", Role: "row", RowIndex: 4122}, false, `[row]`},
{node{ID: "12", Role: "cell", Label: "Total", ColSpan: 2}, true, `[cell] "Total" colspan=2 bounds=0,0,0x0 id=12`},
} {
if got := line(&c.n, "3", c.full); got != c.want {
t.Errorf("line(%+v, full %v)\n got %s\nwant %s", c.n, c.full, got, c.want)
}
}
}
func TestLongText(t *testing.T) {
long := strings.Repeat("é", maxText+30)
n := node{ID: "1", Role: "textField", Value: long}
want := `[textField] value="` + strings.Repeat("é", maxText) + `…" (30 more)`
if got := line(&n, "", false); got != want {
t.Errorf("got %s", got)
}
if got := line(&n, "", true); !strings.Contains(got, `value="`+long+`"`) {
t.Errorf("full cuts the text: %s", got)
}
// Lines stay lines.
n.Value = "a\nb"
if got := line(&n, "", false); got != `[textField] value="a\nb"` {
t.Errorf("got %s", got)
}
}
// TestKeys checks that a key, as lines write it, is a selector that
// names it.
func TestKeys(t *testing.T) {
for _, k := range []string{`"add"`, `"a b"`, `"true"`, `"5"`, `5`, `true`, `"row/1"`, `"null"`, `""`} {
text := keyText(json.RawMessage(k))
if got := string(keyJSON(text)); got != k {
t.Errorf("key %s writes %s, which selects %s", k, text, got)
}
}
}
func TestSnapshot(t *testing.T) {
sn := &seen{Focus: "4", Refs: map[string]int{"1": 1, "2": 2, "3": 3, "4": 4, "5": 5}, Nodes: []node{
{ID: "1", Role: "dialog", Label: "Settings"},
{ID: "2", Parent: "1", Role: "text", Label: "Theme"},
{ID: "3", Parent: "1", Role: "group"},
{ID: "4", Parent: "3", Role: "checkBox", Label: "Dark", States: []string{"focusable", "checked"}, Actions: []string{"press", "focus"}},
{ID: "5", Role: "button", Label: "Close", Actions: []string{"press"}},
}}
var b strings.Builder
writeSnapshot(&b, sn, []string{"Saved"}, false, false)
want := `@e1 [dialog] "Settings"
@e2 [text] "Theme"
@e3 [group]
@e4 [checkBox] "Dark" checked focused
@e5 [button] "Close"
announced "Saved"
`
if b.String() != want {
t.Errorf("snapshot:\n%s\nwant:\n%s", b.String(), want)
}
b.Reset()
writeSnapshot(&b, sn, nil, true, false)
want = `@e4 [checkBox] "Dark" checked focused
@e5 [button] "Close"
`
if b.String() != want {
t.Errorf("snapshot -i:\n%s\nwant:\n%s", b.String(), want)
}
b.Reset()
writeSnapshot(&b, &seen{Nodes: sn.Nodes[:3], Refs: sn.Refs}, nil, true, false)
if !strings.HasPrefix(b.String(), "(no interactive elements") {
t.Errorf("snapshot -i of no controls: %s", b.String())
}
}
func TestWindowLine(t *testing.T) {
if got := windowLine(windowInfo{ID: 2, Title: "Docs", Kind: "page", URL: "http://localhost:5173/", Visible: false}, true); got != `w2 [page] "Docs" url=http://localhost:5173/ hidden selected` {
t.Errorf("got %s", got)
}
if got := windowLine(windowInfo{ID: 1, Title: "Counter", Kind: "content", Focused: true, Visible: true}, false); got != `w1 [content] "Counter" focused` {
t.Errorf("got %s", got)
}
}
+174
View File
@@ -0,0 +1,174 @@
package automationcli
import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
)
// session is what a session keeps between commands, in a file of its own:
// the socket, the window commands target, and the elements of each window
// as the last snapshot or diff showed them, with their refs.
type session struct {
Socket string `json:"socket"`
// Window is the window commands target unless they name one, 0 for
// the focused window.
Window int `json:"window,omitempty"`
// Next is the number of the next ref. Numbers are never given twice
// in a session, so that a stale ref can't name another element.
Next int `json:"next"`
// Seen are the windows' elements as last shown, by window ID.
Seen map[string]*seen `json:"seen,omitempty"`
name, path string
}
// seen is a window's elements as a snapshot or a diff last showed them.
type seen struct {
Focus string `json:"focus,omitempty"`
Nodes []node `json:"nodes"`
// Refs are the elements' refs, by element ID.
Refs map[string]int `json:"refs"`
}
var sessionName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$`)
// sessionPath returns the file of the session name in dir.
func sessionPath(dir, name string) (string, error) {
if !sessionName.MatchString(name) {
return "", fmt.Errorf("session name %q: use letters, digits, '.', '_' and '-'", name)
}
return filepath.Join(dir, name+".json"), nil
}
// loadSession reads the session name, which open made.
func loadSession(dir, name string) (*session, error) {
path, err := sessionPath(dir, name)
if err != nil {
return nil, err
}
b, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return nil, fmt.Errorf("no session %q: run mygo-automation open --socket <path> first", name)
}
if err != nil {
return nil, err
}
s := &session{}
if err := json.Unmarshal(b, s); err != nil {
return nil, fmt.Errorf("session %q is damaged (%v): run mygo-automation open again", name, err)
}
s.name, s.path = name, path
return s, nil
}
// save writes the session, replacing its file at once so that a command
// killed halfway leaves the one before.
func (s *session) save() error {
if err := os.MkdirAll(filepath.Dir(s.path), 0o700); err != nil {
return err
}
b, err := json.Marshal(s)
if err != nil {
return err
}
f, err := os.CreateTemp(filepath.Dir(s.path), s.name+".*.tmp")
if err != nil {
return err
}
_, err = f.Write(b)
if cerr := f.Close(); err == nil {
err = cerr
}
if err == nil {
err = os.Rename(f.Name(), s.path)
}
if err != nil {
os.Remove(f.Name())
}
return err
}
// ref is how outputs name an element: @e and its number.
func ref(n int) string { return "@e" + strconv.Itoa(n) }
// parseRef returns the number of a ref, written @e7 or e7.
func parseRef(s string) (int, bool) {
s = strings.TrimPrefix(s, "@")
if !strings.HasPrefix(s, "e") {
return 0, false
}
n, err := strconv.Atoi(s[1:])
if err != nil || n <= 0 || strconv.Itoa(n) != s[1:] {
return 0, false
}
return n, true
}
// lookup returns the window and the element ID of ref number n. A ref
// lasts while its element is in what the last snapshot or diff of its
// window saw; it is stale once that showed the element gone.
func (s *session) lookup(n int) (window int, id string, err error) {
for w, sn := range s.Seen {
for id, r := range sn.Refs {
if r == n {
window, _ := strconv.Atoi(w)
return window, id, nil
}
}
}
if n < s.Next {
return 0, "", &staleError{ref(n), "its element is gone"}
}
return 0, "", &staleError{ref(n), "no snapshot or diff of this session gave it"}
}
// staleError rejects a ref that names no element now. The CLI never
// takes it for another element.
type staleError struct{ ref, why string }
func (e *staleError) Error() string {
return fmt.Sprintf("stale ref %s: %s; use a ref from the latest snapshot or diff (run snapshot)", e.ref, e.why)
}
// observe takes the elements of a window as they are now: elements seen
// before keep their refs, new ones get new refs and the refs of elements
// gone become stale. It returns what the window showed before, nil if
// nothing.
func (s *session) observe(t *tree) *seen {
if s.Seen == nil {
s.Seen = map[string]*seen{}
}
key := strconv.Itoa(t.Window)
old := s.Seen[key]
if s.Next < 1 {
s.Next = 1
}
now := &seen{Focus: t.Focus, Nodes: t.Nodes, Refs: make(map[string]int, len(t.Nodes))}
for _, n := range t.Nodes {
if _, ok := now.Refs[n.ID]; ok {
continue
}
if old != nil {
if r, ok := old.Refs[n.ID]; ok {
now.Refs[n.ID] = r
continue
}
}
now.Refs[n.ID] = s.Next
s.Next++
}
s.Seen[key] = now
return old
}
// forget drops what a window showed, as when it closed.
func (s *session) forget(window int) {
delete(s.Seen, strconv.Itoa(window))
}
+165
View File
@@ -0,0 +1,165 @@
package automationcli
import (
"errors"
"slices"
"strings"
"testing"
)
func nodes(spec ...string) []node {
var out []node
for _, s := range spec {
id, label, _ := strings.Cut(s, ":")
out = append(out, node{ID: id, Role: "text", Label: label})
}
return out
}
func diffText(lines []diffLine) []string {
var out []string
for _, l := range lines {
out = append(out, l.String())
}
return out
}
// TestRefs checks the life of refs: elements keep theirs while windows
// show them, new ones get new numbers, and the refs of elements gone are
// rejected, never given to another element.
func TestRefs(t *testing.T) {
s := &session{}
s.observe(&tree{Window: 1, Nodes: nodes("10:a", "11:b", "12:c")})
s.observe(&tree{Window: 2, Nodes: nodes("10:other window")})
want := func(n, window int, id string) {
t.Helper()
w, got, err := s.lookup(n)
if err != nil || w != window || got != id {
t.Errorf("%s: window %d, element %s, %v; want %d, %s", ref(n), w, got, err, window, id)
}
}
stale := func(n int, why string) {
t.Helper()
_, _, err := s.lookup(n)
var se *staleError
if !errors.As(err, &se) || !strings.Contains(err.Error(), why) {
t.Errorf("%s: %v, want stale: %s", ref(n), err, why)
}
}
want(1, 1, "10")
want(2, 1, "11")
want(3, 1, "12")
want(4, 2, "10")
stale(5, "no snapshot or diff")
// 11 goes, 13 comes; 12 moves before 10.
before := s.observe(&tree{Window: 1, Nodes: nodes("12:c", "10:a", "13:d")})
if before == nil || len(before.Nodes) != 3 {
t.Fatalf("observe returned %+v", before)
}
want(1, 1, "10")
want(3, 1, "12")
want(5, 1, "13")
stale(2, "gone")
want(4, 2, "10")
// 11 coming back is a new element to the session: the old ref stays
// stale, so that a ref read before never acts on what is there now.
s.observe(&tree{Window: 1, Nodes: nodes("11:b")})
want(6, 1, "11")
stale(2, "gone")
stale(1, "gone")
s.forget(2)
stale(4, "gone")
if s.Next != 7 {
t.Errorf("next ref %d", s.Next)
}
}
func TestParseRef(t *testing.T) {
for s, want := range map[string]int{"@e1": 1, "e12": 12, "@e0": 0, "@e": 0, "@x1": 0, "@e01": 0, "@e-1": 0, "e1a": 0, "key=a": 0} {
if n, ok := parseRef(s); n != want || ok != (want > 0) {
t.Errorf("parseRef(%q) = %d, %v", s, n, ok)
}
}
}
func TestSessionFile(t *testing.T) {
dir := t.TempDir()
if _, err := sessionPath(dir, "../x"); err == nil {
t.Error("a session name with a path")
}
if _, err := loadSession(dir, "a"); err == nil || !strings.Contains(err.Error(), "open") {
t.Errorf("loading no session: %v", err)
}
path, _ := sessionPath(dir, "a")
s := &session{Socket: "/tmp/app.sock", Window: 2, Next: 1, name: "a", path: path}
s.observe(&tree{Window: 2, Focus: "10", Nodes: nodes("10:a")})
if err := s.save(); err != nil {
t.Fatal(err)
}
// Another session keeps refs of its own.
other := &session{Socket: "/tmp/app.sock", Next: 1, name: "b"}
other.path, _ = sessionPath(dir, "b")
other.observe(&tree{Window: 2, Nodes: nodes("20:x", "10:a")})
if err := other.save(); err != nil {
t.Fatal(err)
}
got, err := loadSession(dir, "a")
if err != nil {
t.Fatal(err)
}
if got.Socket != s.Socket || got.Window != 2 || got.Next != 2 || got.Seen["2"].Focus != "10" {
t.Errorf("loaded %+v", got)
}
if w, id, err := got.lookup(1); w != 2 || id != "10" || err != nil {
t.Errorf("@e1 after loading: %d %s %v", w, id, err)
}
}
func TestDiff(t *testing.T) {
s := &session{}
s.observe(&tree{Window: 1, Nodes: nodes("1:title", "2:a", "3:b", "4:c", "5:d", "6:e", "7:f", "8:g")})
// b changes, e goes, x comes after f; focus moves to g.
before := s.observe(&tree{Window: 1, Focus: "8", Nodes: nodes("1:title", "2:a", "3:B", "4:c", "5:d", "7:f", "9:x", "8:g")})
got := diffText(diff(before, s.Seen["1"], 1))
want := []string{
`= @e2 [text] "a"`,
`- @e3 [text] "b"`,
`+ @e3 [text] "B"`,
`= @e4 [text] "c"`,
`= @e5 [text] "d"`,
`- @e6 [text] "e"`,
`= @e7 [text] "f"`,
`+ @e9 [text] "x"`,
`- @e8 [text] "g"`,
`+ @e8 [text] "g" focused`,
}
if !slices.Equal(got, want) {
t.Errorf("diff:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
}
// Nothing changed.
before = s.observe(&tree{Window: 1, Focus: "8", Nodes: nodes("1:title", "2:a", "3:B", "4:c", "5:d", "7:f", "9:x", "8:g")})
if got := diff(before, s.Seen["1"], 1); len(got) != 0 {
t.Errorf("diff of the same: %v", diffText(got))
}
// Moves alone change nothing; a window seen for the first time is all
// new.
before = s.observe(&tree{Window: 1, Focus: "8", Nodes: nodes("8:g", "1:title", "2:a", "3:B", "4:c", "5:d", "7:f", "9:x")})
if got := diff(before, s.Seen["1"], 1); len(got) != 0 {
t.Errorf("diff of a move: %v", diffText(got))
}
before = s.observe(&tree{Window: 3, Nodes: nodes("1:new")})
if got := diffText(diff(before, s.Seen["3"], 1)); !slices.Equal(got, []string{`+ @e10 [text] "new"`}) {
t.Errorf("diff of a new window: %v", got)
}
// Everything gone.
before = s.observe(&tree{Window: 3})
if got := diffText(diff(before, s.Seen["3"], 1)); !slices.Equal(got, []string{`- @e10 [text] "new"`}) {
t.Errorf("diff of an emptied window: %v", got)
}
}