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:
1 parent
2fb4a8ea79
commit
6c0ee61750
2538 files changed
+675779
-4792
No files matched your search
+35
@@ -0,0 +1,35 @@
|
||||
# automation
|
||||
|
||||
Drive a running [MyGo](https://github.com/egoist/mygo) app from another
|
||||
process, as end-to-end test runners and agents do: list its windows, read
|
||||
the elements of their native UI with the app's keys, act on them, send
|
||||
pointer, wheel, key and text input, choose menu items, evaluate scripts in
|
||||
pages, capture windows, and wait for them to settle. One protocol on
|
||||
macOS, Linux and Windows: newline-delimited JSON over a Unix domain
|
||||
socket that only the user can open.
|
||||
|
||||
```go
|
||||
//go:build e2e
|
||||
|
||||
package main
|
||||
|
||||
import _ "github.com/egoist/mygo/plugins/automation"
|
||||
```
|
||||
|
||||
```sh
|
||||
MYGO_AUTOMATION=/tmp/app.sock ./app
|
||||
echo '{"id": 1, "method": "windows"}' | socat - UNIX-CONNECT:/tmp/app.sock
|
||||
```
|
||||
|
||||
Agents drive it with `mygo-automation`, a command line client with
|
||||
compact snapshots, short refs and diffs once the UI settled, whose guide
|
||||
it prints:
|
||||
|
||||
```sh
|
||||
go install github.com/egoist/mygo/plugins/automation/cmd/mygo-automation
|
||||
mygo-automation skills
|
||||
```
|
||||
|
||||
It listens only when `MYGO_AUTOMATION` is set, and builds without the
|
||||
inspector (`-tags mygo_noinspector`, the release builds of `mygo build`)
|
||||
leave it out. See [the documentation](../../docs/plugins/automation.md).
|
||||
+314
@@ -0,0 +1,314 @@
|
||||
//go:build !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
"github.com/egoist/mygo/internal/surface"
|
||||
)
|
||||
|
||||
// init listens on the socket MYGO_AUTOMATION names, if any, before any
|
||||
// window opens, so that the content of every window of native UI comes to
|
||||
// the plugin as it attaches.
|
||||
func init() {
|
||||
if runtime.GOOS == "android" {
|
||||
// Android's host sets the environment after this package's init, as
|
||||
// the library has to load to run anything: the variable shows by the
|
||||
// time the app is ready, before any window opens.
|
||||
a := newApp()
|
||||
surface.Automate = a.attached
|
||||
mygo.App.WhenReady(func() {
|
||||
close(a.ready)
|
||||
if path := os.Getenv("MYGO_AUTOMATION"); path != "" {
|
||||
a.listen(path)
|
||||
}
|
||||
})
|
||||
return
|
||||
}
|
||||
path := os.Getenv("MYGO_AUTOMATION")
|
||||
if path == "" {
|
||||
return
|
||||
}
|
||||
a := newApp()
|
||||
if !a.listen(path) {
|
||||
return
|
||||
}
|
||||
surface.Automate = a.attached
|
||||
mygo.App.WhenReady(func() { close(a.ready) })
|
||||
}
|
||||
|
||||
func newApp() *app {
|
||||
return &app{ready: make(chan struct{}), targets: map[*mygo.Window]target{}}
|
||||
}
|
||||
|
||||
// listen serves requests on the socket at path, and reports whether it can.
|
||||
func (a *app) listen(path string) bool {
|
||||
l, err := listen(path)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "mygo: automation:", err)
|
||||
return false
|
||||
}
|
||||
mygo.App.OnQuit(func() { l.Close() })
|
||||
go serve(l, a)
|
||||
return true
|
||||
}
|
||||
|
||||
// app drives the running app's windows.
|
||||
type app struct {
|
||||
// ready is closed once the app has launched: requests wait for it.
|
||||
ready chan struct{}
|
||||
// targets are the windows of native UI, by window. Main thread only.
|
||||
targets map[*mygo.Window]target
|
||||
}
|
||||
|
||||
// target is a window of native UI: its connection to its content, and
|
||||
// the content.
|
||||
type target struct {
|
||||
conn *surface.Conn
|
||||
content surface.Automated
|
||||
}
|
||||
|
||||
// attached takes a window's content as it attaches (surface.Automate).
|
||||
// Main thread only.
|
||||
func (a *app) attached(conn *surface.Conn, content surface.Automated) {
|
||||
for w := range a.targets {
|
||||
if w.IsDestroyed() {
|
||||
delete(a.targets, w)
|
||||
}
|
||||
}
|
||||
if w, ok := conn.Window.(*mygo.Window); ok {
|
||||
a.targets[w] = target{conn, content}
|
||||
// A closed window's content goes, with what it showed (#1281).
|
||||
w.OnClosed(func() { delete(a.targets, w) })
|
||||
}
|
||||
}
|
||||
|
||||
var errQuit = errors.New("the app quit")
|
||||
|
||||
// onMain runs fn on the main thread, once the app has launched.
|
||||
func (a *app) onMain(fn func()) error {
|
||||
<-a.ready
|
||||
ran := false
|
||||
mygo.RunOnMain(func() {
|
||||
fn()
|
||||
ran = true
|
||||
})
|
||||
if !ran {
|
||||
return errQuit
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// window returns the window of the ID, or for 0 the focused window, else
|
||||
// the first.
|
||||
func (a *app) window(id int) (*mygo.Window, error) {
|
||||
<-a.ready
|
||||
if id != 0 {
|
||||
if w := mygo.WindowByID(id); w != nil && !w.IsDestroyed() {
|
||||
return w, nil
|
||||
}
|
||||
return nil, errorf(codeNoWindow, "no window %d", id)
|
||||
}
|
||||
if w := mygo.FocusedWindow(); w != nil {
|
||||
return w, nil
|
||||
}
|
||||
if ws := mygo.Windows(); len(ws) > 0 {
|
||||
return ws[0], nil
|
||||
}
|
||||
return nil, errorf(codeNoWindow, "the app has no window")
|
||||
}
|
||||
|
||||
// content runs fn on the main thread with the target of a window of
|
||||
// native UI.
|
||||
func (a *app) content(id int, fn func(w *mygo.Window, t target) error) error {
|
||||
w, err := a.window(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var ferr error
|
||||
if err := a.onMain(func() {
|
||||
t, ok := a.targets[w]
|
||||
switch {
|
||||
case w.IsDestroyed():
|
||||
ferr = errorf(codeNoWindow, "window %d closed", w.ID())
|
||||
case !ok:
|
||||
ferr = errorf(codeUnsupported, "window %d shows a web page: use eval", w.ID())
|
||||
default:
|
||||
ferr = fn(w, t)
|
||||
}
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
return ferr
|
||||
}
|
||||
|
||||
func (a *app) windows() ([]windowInfo, error) {
|
||||
var out []windowInfo
|
||||
err := a.onMain(func() {
|
||||
for _, w := range mygo.Windows() {
|
||||
if w.IsDestroyed() {
|
||||
continue
|
||||
}
|
||||
info := windowInfo{
|
||||
ID: w.ID(), Title: w.Title(), Kind: "page",
|
||||
Bounds: rectOf(w.Bounds()), ContentBounds: rectOf(w.ContentBounds()),
|
||||
Focused: w.IsFocused(), Visible: w.IsVisible(),
|
||||
}
|
||||
if _, ok := a.targets[w]; ok {
|
||||
info.Kind = "content"
|
||||
} else if p := w.Page(); p != nil {
|
||||
info.URL = p.URL()
|
||||
}
|
||||
out = append(out, info)
|
||||
}
|
||||
})
|
||||
return out, err
|
||||
}
|
||||
|
||||
func rectOf(r mygo.Rectangle) rect {
|
||||
return rect{float64(r.X), float64(r.Y), float64(r.Width), float64(r.Height)}
|
||||
}
|
||||
|
||||
// tree reads the elements the window shows: in a window out of sight, of
|
||||
// the frame waiting to build (Automated.Settle), built first.
|
||||
func (a *app) tree(id int) (window int, tree *platform.AccessTree, keys map[uint64]any, err error) {
|
||||
err = a.content(id, func(w *mygo.Window, t target) error {
|
||||
window = w.ID()
|
||||
t.content.Settle()
|
||||
tree, keys = t.content.AutomationTree()
|
||||
return nil
|
||||
})
|
||||
return window, tree, keys, err
|
||||
}
|
||||
|
||||
// act gives the content an action of assistive technology, as the
|
||||
// backend gives it those of the system's. In a window out of sight, the
|
||||
// frame that takes it builds at once (Automated.Settle).
|
||||
func (a *app) act(id int, ev platform.SurfaceEvent) error {
|
||||
return a.content(id, func(w *mygo.Window, t target) error {
|
||||
t.content.Settle()
|
||||
tree, _ := t.content.AutomationTree()
|
||||
for _, n := range tree.Nodes {
|
||||
if n.ID == ev.ID {
|
||||
t.conn.Event(ev)
|
||||
t.content.Settle()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errorf(codeNoElement, "window %d shows no element %d", w.ID(), ev.ID)
|
||||
})
|
||||
}
|
||||
|
||||
// input gives the content events, as the backend gives it the system's,
|
||||
// and in a window out of sight builds the frame that takes them.
|
||||
func (a *app) input(id int, evs []platform.SurfaceEvent) error {
|
||||
return a.content(id, func(w *mygo.Window, t target) error {
|
||||
for _, ev := range evs {
|
||||
t.conn.Event(ev)
|
||||
}
|
||||
t.content.Settle()
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (a *app) menu(id int, path []string) error {
|
||||
w, err := a.window(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var merr error
|
||||
if err := a.onMain(func() { merr = chooseMenuItem(w, path) }); err != nil {
|
||||
return err
|
||||
}
|
||||
if merr != nil {
|
||||
var e *Error
|
||||
if !errors.As(merr, &e) {
|
||||
merr = errorf(codeFailed, "%v", merr)
|
||||
}
|
||||
}
|
||||
return merr
|
||||
}
|
||||
|
||||
func (a *app) capture(id int) ([]byte, error) {
|
||||
w, err := a.window(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, err := w.CapturePage()
|
||||
if err != nil {
|
||||
return nil, errorf(codeFailed, "%v", err)
|
||||
}
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func (a *app) eval(id int, script string) (any, error) {
|
||||
w, err := a.window(id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p := w.Page()
|
||||
if p == nil {
|
||||
return nil, errorf(codeUnsupported, "window %d shows native UI, not a web page: use tree", w.ID())
|
||||
}
|
||||
v, err := p.Eval(script)
|
||||
if err != nil {
|
||||
return nil, errorf(codeFailed, "%v", err)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
// pollEvery is how often idle asks whether the window settled.
|
||||
const pollEvery = 5 * time.Millisecond
|
||||
|
||||
// idle returns once the window has drawn the frames it asked for: for a
|
||||
// window of native UI, once its content asks for no frame (as
|
||||
// ui.Tester.FramePending tells); for a page, once it has loaded and
|
||||
// answered a script.
|
||||
func (a *app) idle(id int, timeout time.Duration) error {
|
||||
w, err := a.window(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var deadline time.Time
|
||||
if timeout > 0 {
|
||||
deadline = time.Now().Add(timeout)
|
||||
}
|
||||
for {
|
||||
pending := false
|
||||
err := a.content(id, func(_ *mygo.Window, t target) error {
|
||||
t.content.Settle()
|
||||
pending = t.content.FramePending()
|
||||
return nil
|
||||
})
|
||||
var e *Error
|
||||
if errors.As(err, &e) && e.Code == codeUnsupported {
|
||||
// A page.
|
||||
p := w.Page()
|
||||
if p == nil {
|
||||
return errorf(codeNoWindow, "window %d closed", w.ID())
|
||||
}
|
||||
pending = p.IsLoading()
|
||||
if !pending {
|
||||
if _, err := p.Eval("true"); err != nil {
|
||||
return errorf(codeFailed, "%v", err)
|
||||
}
|
||||
}
|
||||
} else if err != nil {
|
||||
return err
|
||||
}
|
||||
if !pending {
|
||||
return nil
|
||||
}
|
||||
if !deadline.IsZero() && time.Now().After(deadline) {
|
||||
return errorf(codeTimeout, "window %d still draws after %v", w.ID(), timeout)
|
||||
}
|
||||
time.Sleep(pollEvery)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,304 @@
|
||||
---
|
||||
name: mygo-automation
|
||||
description: Drive a running MyGo app from the shell. Read the elements of its native UI as compact text with short refs, press, fill, click, type, send keys and wheel events, choose application menu items, evaluate scripts in windows showing a web page, wait for the UI to settle and read what changed, save screenshots.
|
||||
---
|
||||
|
||||
# mygo-automation
|
||||
|
||||
`mygo-automation` drives a running MyGo app through the socket of its
|
||||
automation plugin (`github.com/egoist/mygo/plugins/automation`). It is
|
||||
the guide of the version you run, as `mygo-automation version` tells. If
|
||||
the app's MyGo is another version, install the matching one (see
|
||||
"Installing").
|
||||
|
||||
The loop is: **snapshot → act with `--settle` → read the diff → act
|
||||
again**. Diffs carry the refs you act on next, so a new snapshot is
|
||||
seldom needed.
|
||||
|
||||
```sh
|
||||
mygo-automation open --socket /tmp/app.sock
|
||||
mygo-automation snapshot -i
|
||||
# @e2 [button] "Add" key=add
|
||||
# @e3 [textField] "Name" key=name
|
||||
mygo-automation press @e2 --settle
|
||||
# - @e1 [text] "Count: 0"
|
||||
# + @e1 [text] "Count: 1"
|
||||
# = @e2 [button] "Add" key=add
|
||||
mygo-automation fill @e3 "Ada" --settle
|
||||
mygo-automation screenshot /tmp/app.png
|
||||
mygo-automation close
|
||||
```
|
||||
|
||||
## The app
|
||||
|
||||
The app must link the plugin and be started with `MYGO_AUTOMATION`, the
|
||||
path of the socket it listens on. A file of the app's, kept out of its
|
||||
release by a build tag:
|
||||
|
||||
```go
|
||||
//go:build e2e
|
||||
|
||||
package main
|
||||
|
||||
import _ "github.com/egoist/mygo/plugins/automation"
|
||||
```
|
||||
|
||||
```sh
|
||||
go build -tags e2e -o /tmp/app . && MYGO_AUTOMATION=/tmp/app.sock /tmp/app &
|
||||
```
|
||||
|
||||
Any way of starting it works if the variable reaches it; `mygo dev`
|
||||
passes its environment to the app. Builds without the inspector
|
||||
(`-tags mygo_noinspector`, release builds of `mygo build` without
|
||||
`-debug`) leave the plugin out: they say so on standard error and never
|
||||
listen. The socket is the user's alone. Pick a path in a directory only
|
||||
the user can write to; nothing else is needed to connect, and there is
|
||||
no discovery: the path is the one you gave `MYGO_AUTOMATION`.
|
||||
|
||||
## Sessions
|
||||
|
||||
- `open [--socket <path>]` attaches a session to the app and lists its
|
||||
windows. Without `--socket` it takes `$MYGO_AUTOMATION`. Opening again
|
||||
keeps the session's name but forgets what it saw: every ref given
|
||||
before goes stale.
|
||||
- `close` ends the session and forgets its refs. **The app keeps
|
||||
running.** To quit it, choose its menu item (`menu <App> Quit`, when
|
||||
it has one) or end its process yourself.
|
||||
- Every command takes `--session <name>` (default:
|
||||
`$MYGO_AUTOMATION_SESSION`, else `default`), letters, digits, `.`,
|
||||
`_` and `-`. Sessions keep their socket, chosen window and refs apart,
|
||||
in files of their own in the user's cache directory
|
||||
(`mygo/automation/<name>.json`). Give each agent, or each app, a session
|
||||
of its own; run one command at a time in a session.
|
||||
|
||||
## Reading the UI
|
||||
|
||||
`snapshot` prints the elements of a window of native UI, one per line, a
|
||||
child indented under the element shown above it, in tree order:
|
||||
|
||||
```
|
||||
@e1 [dialog] "Settings"
|
||||
@e2 [checkBox] "Dark mode" key=dark checked focused
|
||||
@e3 [textField] "Name" value="Ada" key=name
|
||||
@e4 [slider] "Volume" value=0.25
|
||||
@e5 [button] "Save" disabled
|
||||
announced "Saved"
|
||||
```
|
||||
|
||||
A line is the element's ref, `[role]`, its label in quotes, then what
|
||||
it has of `value=`, `placeholder=` (when it has no label), `key=` (the
|
||||
app's own name for it), its states, `current=` (what it is the current
|
||||
one of, as the last crumb of a breadcrumb trail is the `page`),
|
||||
`autocomplete=` (what a field's suggestions complete as you type: `list`
|
||||
for a popup of them, `inline` for the text completed in place, or
|
||||
`both`), `haspopup=`, `roledescription=` and `focused`. Empty fields are left
|
||||
out, and so is `focusable`, which every control is. `webview` marks a web
|
||||
view inside native UI: its page has no elements here. `announced` lines
|
||||
are what the app announced to screen readers. Labels and values longer
|
||||
than 120 characters are cut, ending in `…" (N more)`.
|
||||
`keyshortcuts=` (after `key=`) is the keys the app says press or focus
|
||||
the element, as screen readers read them (`aria-keyshortcuts`): `"⌘K"`
|
||||
on macOS, `"Ctrl+K"` elsewhere, several separated by spaces.
|
||||
|
||||
- `-i` (`--interactive`) keeps controls and elements with actions:
|
||||
buttons, fields, check boxes, links, list items you can press, and so
|
||||
on. Elements left out still get refs, and diffs show them.
|
||||
- `--full` adds placeholders, descriptions, ranges (`range=0..1
|
||||
step=0.1`), text selections (`selection=3,3`, in characters), levels,
|
||||
positions in sets (`item=2/5`), the size of a table or a grid and
|
||||
the place of a row or a cell in it as the app gave them
|
||||
(`rowcount=10001 colcount=5`, `rowindex=4122 colindex=2`), the rows
|
||||
and columns a cell covers (`colspan=2`), actions, `bounds=x,y,wxh` and the full
|
||||
element ID (`id=…`), and writes long text whole.
|
||||
- `--json` prints the plugin's answer as it is (IDs, keys, bounds, all
|
||||
fields) on one line. It still takes the window's elements for later
|
||||
diffs and gives refs, which it does not print.
|
||||
- `--window <w>` reads another window (see "Windows and pages").
|
||||
|
||||
Roles are `group`, `text`, `heading`, `button`, `link`, `checkBox`,
|
||||
`radio`, `switch`, `slider`, `progress`, `meter`, `stepper`,
|
||||
`textField`, `comboBox`, `popUpButton`, `menuButton`, `toggleButton`,
|
||||
`image`, `list`, `listItem`, `table`, `grid`, `treeGrid`, `row`, `cell`, `columnHeader`,
|
||||
`tree`, `treeItem`, `tabList`, `tab`, `scroll`, `dialog`, `alertDialog`,
|
||||
`popup`, `tooltip`, `splitter`, `status`, `toolbar`, `radioGroup`,
|
||||
`disclosure`, `colorWell`, `menu`, `menuBar`, `menuItem`,
|
||||
`menuItemCheckBox`, `menuItemRadio`, `region`, `log`, `timer`, `alert`,
|
||||
`separator`, `rowHeader`, `search`, `article`, `navigation`, `deletion`,
|
||||
`insertion`, `tabPanel`, `main`, `banner`, `contentInfo` and
|
||||
`complementary`. States are `disabled`, `checked`,
|
||||
`mixed`, `selected`, `expanded`, `expandable`, `multiline`, `password`,
|
||||
`readOnly`, `selectable`, `multiselectable`, `offscreen`, `segment`,
|
||||
`search`, `invalid`, `sortAscending`, `sortDescending`, `sortOther`,
|
||||
`vertical`, `horizontal` and `busy`. `current=` is `true`, `page`, `step`, `location`,
|
||||
`date` or `time`; `haspopup=` the kind of popup the element opens
|
||||
(`menu`, `listbox`, `tree`, `grid` or `dialog`), and `roledescription=`
|
||||
what the app calls its role.
|
||||
Only what assistive technology reads is there: rows and columns that
|
||||
only lay out others have no line.
|
||||
|
||||
## Selectors
|
||||
|
||||
Commands that act on an element take one of:
|
||||
|
||||
| Selector | Names |
|
||||
| --- | --- |
|
||||
| `@e7` (or `e7`) | the element a snapshot or diff gave that ref, in its window |
|
||||
| `key=<key>` | the one element of the window whose key the app set (`Element.Key`, `Context.Key`) |
|
||||
| `id=<digits>` | the element with that ID, as `--full` and `--json` show |
|
||||
|
||||
Write keys as lines show them: `key=add`, `key=7` (a number), `key=true`
|
||||
(a boolean), `key='"7"'` or `key='"two words"'` (strings that need JSON's
|
||||
quotes, quoted again for the shell). A key two elements share is refused:
|
||||
use a ref. Prefer keys when the app gives them; they last across runs.
|
||||
|
||||
## Refs
|
||||
|
||||
- Refs come from `snapshot`, `diff` and `--settle`. Use the refs of the
|
||||
latest output for a window.
|
||||
- An element keeps its ref while the window shows it: after `press @e2
|
||||
--settle`, `@e2` still names the same button, printed or not.
|
||||
- New elements get new numbers. A ref is never given twice in a session,
|
||||
so it can't come to name another element.
|
||||
- A ref goes **stale** once a snapshot or diff of its window shows its
|
||||
element gone, or the app answers that it is gone. A stale ref is
|
||||
refused, never retargeted:
|
||||
`error: stale ref @e4: its element is gone; use a ref from the latest snapshot or diff (run snapshot)`.
|
||||
An element that comes back gets a new ref.
|
||||
- A ref carries its window: commands on it go there, whatever `window`
|
||||
or `--window` says.
|
||||
- `open` again, or `close`, ends every ref of the session.
|
||||
|
||||
## Acting
|
||||
|
||||
| Command | Does |
|
||||
| --- | --- |
|
||||
| `press <sel>` | presses, as assistive technology does: clicks a button, toggles a check box, opens a menu button |
|
||||
| `focus <sel>` | gives the element the keyboard focus |
|
||||
| `fill <sel> <text>` | replaces a text field's text (`""` empties it) |
|
||||
| `act <sel> <action> [args]` | any action: `press`, `focus`, `increment`, `decrement`, `setValue <text>`, `insertText <text>` (at the caret), `selectText <from> <to>` (characters), `scrollIntoView`, `expand`, `collapse` |
|
||||
| `click <sel>` or `click <x> <y>` | a pointer click at the element's center, or at a point; `--button left\|right\|middle`, `--clicks 2` for a double click, `--mods shift,ctrl,alt,super,cmdOrCtrl` |
|
||||
| `pointer move\|down\|up <sel>\|<x> <y>` | one pointer event, with the same flags, for drags and hovers |
|
||||
| `wheel <sel>\|<x> <y> <dx> <dy>` | scrolls by `dx`, `dy` DIPs (negative `dy` scrolls up); `--precise` as a touchpad, `--mods` |
|
||||
| `type <text>` | types text into the focused element, as the keyboard does |
|
||||
| `key <key>...` | presses and releases keys in order, written as menu accelerators: `Enter`, `Escape`, `Tab`, `Shift+Tab`, `Backspace`, `Delete`, `Up`, `PageDown`, `Home`, `F2`, `a`, `CmdOrCtrl+A`, `CmdOrCtrl+Shift+Z`; `--down` or `--up` sends only the press or the release |
|
||||
| `menu <label>...` | chooses an item of the application menu by the labels along its path: `menu File "New Window"` |
|
||||
|
||||
Points are in DIPs, from the top left corner of the window's content, as
|
||||
`bounds=` shows. Prefer `press` and `fill` to `click` and `type`: they
|
||||
need no coordinates and no focus. A key types no text: send text with
|
||||
`type`. A modifier alone (`key Shift`) is no key. Without `--settle`, an
|
||||
action prints `ok` once the app took it, which may be before it drew.
|
||||
|
||||
`press`, `focus`, `fill`, `act`, `click`, `pointer`, `wheel`, `type`,
|
||||
`key`, `menu` and `wait` take `--window <w>` (for coordinates, keys,
|
||||
text and menus), `--settle` and `--timeout <d>`.
|
||||
|
||||
## Settle and diff
|
||||
|
||||
`--settle` waits until the window has drawn every frame it asked for (the
|
||||
plugin's `idle`), for `--timeout` (default `10s`; `500ms`, a number of
|
||||
milliseconds, or `0` to wait as long as it takes), then prints what
|
||||
changed since the last snapshot or diff of that window, and takes what it
|
||||
shows now for the next diff:
|
||||
|
||||
```
|
||||
= @e2 [button] "Add" key=add
|
||||
- @e3 [textField] "Name" key=name
|
||||
+ @e3 [textField] "Name" value="Ada" key=name focused
|
||||
+ @e4 [text] "Hello, Ada"
|
||||
- @e9 [dialog] "Unsaved changes"
|
||||
```
|
||||
|
||||
- `+` an element that came, with its new ref, or an element as it is now.
|
||||
- `-` an element that went, with its now stale ref, or an element as it
|
||||
was before: a changed element shows as `-` then `+`, with one ref.
|
||||
- `=` an unchanged element next to a change, for context, with its ref.
|
||||
- `(no changes)` when nothing changed. Moves and bounds are not changes.
|
||||
|
||||
A window that never settles, as one with a spinner, warns on standard
|
||||
error after `--timeout` and prints the diff anyway. `diff` prints the
|
||||
same without acting or waiting. An action on a ref diffs the ref's
|
||||
window. One that names no window (`type`, `key`, `menu`, points) while
|
||||
the session targets the focused window diffs the window focused once it
|
||||
settled: a window it opened comes as `+` lines.
|
||||
|
||||
## Waiting
|
||||
|
||||
- `wait` waits for the window to settle (`--timeout`, as above).
|
||||
- `wait <sel>` waits until the window shows the element; `wait --text
|
||||
<s>` until an element's label or value contains `s` (case sensitive).
|
||||
These check the condition while the window keeps drawing; `--settle`
|
||||
waits for it to settle after the condition is met.
|
||||
- `--gone` waits until it no longer shows it, as a dialog closing.
|
||||
- It prints `ok`, or with `--settle` the diff. After `--timeout` it fails
|
||||
with `timeout`. Never sleep: wait for what you expect.
|
||||
|
||||
## Windows and pages
|
||||
|
||||
- `windows` lists the windows: `w1 [content] "Title" focused`; `[content]`
|
||||
shows native UI, `[page]` a web page, with its `url=`; `hidden` and
|
||||
`selected` mark windows not shown and the one the session targets.
|
||||
`--json` prints the plugin's answer.
|
||||
- `window <w>` makes commands target window `w` (`w2` or `2`) unless they
|
||||
name one with `--window`; `window auto` goes back to the focused window,
|
||||
the default, else the first.
|
||||
- Native UI windows have elements: `snapshot`, selectors, `press`, input.
|
||||
- Page windows have none: `snapshot` and input fail with `unsupported`.
|
||||
Read and drive them with `eval <script>`, which prints a string as it
|
||||
is and other values as JSON (`--json`: always JSON); `eval -` reads the
|
||||
script from standard input. An expression's value is printed, promises
|
||||
awaited, or what statements `return`.
|
||||
- A web view inside native UI is one `webview` element: neither
|
||||
`snapshot` nor `eval` reaches its page.
|
||||
|
||||
## Screenshots
|
||||
|
||||
`screenshot <file.png> [--window <w>]` saves the window as a PNG file and
|
||||
prints `<file> <width>x<height>` in device pixels. It never prints the
|
||||
image. Take one only when text does not tell you enough.
|
||||
|
||||
## Output and errors
|
||||
|
||||
Output goes to standard output; errors go to standard error as
|
||||
`error: <message>`, with exit status 1, or 2 for a command line used
|
||||
wrong. Errors from the app start with its code:
|
||||
|
||||
| Error | Means | Do |
|
||||
| --- | --- | --- |
|
||||
| `no session "<name>"` | no `open` for this session | `open --socket <path>` |
|
||||
| `cannot reach the app at <path>` | nothing listens: the app quit, never set `MYGO_AUTOMATION`, or lacks the plugin | start the app, then `open` |
|
||||
| `stale ref @eN` | the ref's element or window is gone | `snapshot`, use a ref it gives |
|
||||
| `no_window` | no window has that ID, or the app has none | `windows` |
|
||||
| `no_element` | the window shows no such element or key | `snapshot` |
|
||||
| `unsupported` | the window cannot do it, as `snapshot` of a page or `eval` in native UI | use the other one |
|
||||
| `timeout` | `wait` did not see what it waited for, or the window never settled | look at a `snapshot`; raise `--timeout` |
|
||||
| `invalid_request` | a value the app can't use, as an unknown key name | fix the command |
|
||||
| `failed` | the app could not do it, as a script that threw, or a menu item it lacks | read the message |
|
||||
|
||||
## Limits
|
||||
|
||||
- Context menus, and the menus of the Dock and of tray icons, can't be
|
||||
chosen: don't open a context menu with `click --button right`.
|
||||
- Settling waits for frames asked for, not for timers the app set
|
||||
(`Context.After`) or work it does in the background: use `wait <sel>`
|
||||
or `wait --text` for those.
|
||||
- On Linux and Windows, `menu` chooses from the window's menu bar, which
|
||||
shows the application menu.
|
||||
- The command does not start or quit the app.
|
||||
|
||||
## Installing
|
||||
|
||||
```sh
|
||||
# In the app's module directory: the version of MyGo its go.mod requires.
|
||||
go install github.com/egoist/mygo/plugins/automation/cmd/mygo-automation
|
||||
# Anywhere else: name that version, which this prints in the app's module.
|
||||
go list -m github.com/egoist/mygo
|
||||
go install github.com/egoist/mygo/plugins/automation/cmd/mygo-automation@vX.Y.Z
|
||||
```
|
||||
|
||||
`version` prints the version of MyGo the command was built from (as
|
||||
`v0.8.0`; `(devel)` or a pseudo-version for a build from a checkout), and
|
||||
`skills` prints this guide. `go install` puts `mygo-automation` in
|
||||
`$(go env GOBIN)`, else
|
||||
`$(go env GOPATH)/bin`. Upgrading the app's MyGo does not upgrade the
|
||||
installed command: install it again, and this guide comes with it.
|
||||
@@ -0,0 +1,26 @@
|
||||
// Command mygo-automation drives a running MyGo app through
|
||||
// plugins/automation's socket, made for AI coding agents: compact text
|
||||
// snapshots of a window's elements with short refs (@e1), actions on
|
||||
// them, and diffs of what the window shows once it settled.
|
||||
//
|
||||
// go install github.com/egoist/mygo/plugins/automation/cmd/mygo-automation
|
||||
// mygo-automation skills
|
||||
//
|
||||
// skills prints the guide, SKILL.md, embedded in the command so that it
|
||||
// matches the commands of the version installed. See
|
||||
// docs/plugins/automation.md.
|
||||
package main
|
||||
|
||||
import (
|
||||
_ "embed"
|
||||
"os"
|
||||
|
||||
"github.com/egoist/mygo/internal/automationcli"
|
||||
)
|
||||
|
||||
//go:embed SKILL.md
|
||||
var skill []byte
|
||||
|
||||
func main() {
|
||||
os.Exit(automationcli.Run(os.Args[1:], os.Stdin, os.Stdout, os.Stderr, automationcli.Options{Skill: skill}))
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/egoist/mygo/internal/automationcli"
|
||||
)
|
||||
|
||||
// TestSkills checks that skills prints SKILL.md as it is, and that the
|
||||
// guide tells of every command.
|
||||
func TestSkills(t *testing.T) {
|
||||
var out, errs bytes.Buffer
|
||||
if code := automationcli.Run([]string{"skills"}, nil, &out, &errs, automationcli.Options{Skill: skill}); code != 0 || errs.Len() > 0 {
|
||||
t.Fatalf("skills: exit %d: %s", code, errs.String())
|
||||
}
|
||||
file, err := os.ReadFile("SKILL.md")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(out.Bytes(), file) {
|
||||
t.Error("skills does not print SKILL.md as it is")
|
||||
}
|
||||
if !bytes.HasPrefix(file, []byte("---\nname: mygo-automation\ndescription: ")) {
|
||||
t.Error("SKILL.md lacks its front matter")
|
||||
}
|
||||
for _, name := range automationcli.Commands() {
|
||||
if !strings.Contains(string(file), "`"+name+" ") && !strings.Contains(string(file), "`"+name+"`") {
|
||||
t.Errorf("SKILL.md does not tell of %s", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
// Package automation lets another process drive a running app, as an
|
||||
// end-to-end test runner or an agent does: list its windows, read what
|
||||
// their native UI shows as elements, act on them, send pointer, wheel,
|
||||
// key and text input, choose items of the application menu, evaluate
|
||||
// scripts in pages, capture windows as PNG images, and wait for them to
|
||||
// settle.
|
||||
//
|
||||
// An app opts in by importing the package, as a file built for tests
|
||||
// does:
|
||||
//
|
||||
// //go:build e2e
|
||||
//
|
||||
// package main
|
||||
//
|
||||
// import _ "github.com/egoist/mygo/plugins/automation"
|
||||
//
|
||||
// Then it listens only when the environment variable MYGO_AUTOMATION names
|
||||
// the path of a Unix domain socket, which only the user can open, and
|
||||
// answers JSON requests on it, one per line:
|
||||
//
|
||||
// MYGO_AUTOMATION=/tmp/app.sock ./app
|
||||
//
|
||||
// Builds without the inspector of native UI (-tags mygo_noinspector, as
|
||||
// mygo build makes for release) leave the plugin out: it never listens
|
||||
// there. See docs/plugins/automation.md for the protocol, and for
|
||||
// mygo-automation (cmd/mygo-automation), its command line client for
|
||||
// agents.
|
||||
package automation
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
//go:build !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// listen listens on the Unix domain socket at path, which only the user
|
||||
// can open. A socket left there by an app that ended without closing it
|
||||
// is removed; one that an app listens on, or a file that is no socket, is
|
||||
// left alone.
|
||||
//
|
||||
// A path that starts with @ is in Android's abstract namespace, where an
|
||||
// app's files are out of adb's reach:
|
||||
//
|
||||
// adb forward tcp:9000 localabstract:mygo
|
||||
func listen(path string) (net.Listener, error) {
|
||||
if strings.HasPrefix(path, "@") {
|
||||
return net.Listen("unix", path)
|
||||
}
|
||||
// A phone on a cable, whose files no socket of this computer reaches: anyone
|
||||
// on its networks can reach the port too, so use it where you trust those,
|
||||
// with a build that isn't a release, which has no plugin.
|
||||
if addr, ok := strings.CutPrefix(path, "tcp:"); ok {
|
||||
return net.Listen("tcp", addr)
|
||||
}
|
||||
if fi, err := os.Lstat(path); err == nil {
|
||||
if fi.Mode().Type() != os.ModeSocket {
|
||||
return nil, fmt.Errorf("%s exists and is not a socket", path)
|
||||
}
|
||||
if c, err := net.Dial("unix", path); err == nil {
|
||||
c.Close()
|
||||
return nil, fmt.Errorf("another app listens on %s", path)
|
||||
}
|
||||
if err := os.Remove(path); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return listenPrivate(path)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//go:build !unix && !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import "net"
|
||||
|
||||
// listenPrivate listens on the socket. On Windows, a socket's file has no
|
||||
// mode: it takes the access control list of its directory, which is the
|
||||
// user's alone in the user's profile and temporary directory.
|
||||
func listenPrivate(path string) (net.Listener, error) { return net.Listen("unix", path) }
|
||||
@@ -0,0 +1,27 @@
|
||||
//go:build unix && !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"net"
|
||||
"os"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// listenPrivate makes the socket readable and writable by the user alone,
|
||||
// from the start: with the umask that leaves the others out while the
|
||||
// socket is made, which runs in init, before goroutines of the app make
|
||||
// files, and with its mode after.
|
||||
func listenPrivate(path string) (net.Listener, error) {
|
||||
old := syscall.Umask(0o177)
|
||||
l, err := net.Listen("unix", path)
|
||||
syscall.Umask(old)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := os.Chmod(path, 0o600); err != nil {
|
||||
l.Close()
|
||||
return nil, err
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build darwin && !ios && !mygo_noinspector && !ios
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/internal/darwin"
|
||||
)
|
||||
|
||||
// chooseMenuItem chooses an item of the application menu by the titles
|
||||
// along its path, as the menu bar does. Main thread only.
|
||||
func chooseMenuItem(_ *mygo.Window, path []string) error {
|
||||
return darwin.TestPerformMenuItem(path...)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build linux && !android && (amd64 || arm64) && !mygo_noinspector && !android
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/internal/linux"
|
||||
)
|
||||
|
||||
// chooseMenuItem chooses an item of the window's menu bar, which shows
|
||||
// the application menu, by the labels along its path. Main thread only.
|
||||
func chooseMenuItem(w *mygo.Window, path []string) error {
|
||||
return linux.TestActivateMenuItem(w.NativeHandle(), path...)
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
//go:build !(darwin && !ios) && !(linux && !android && (amd64 || arm64)) && !(windows && (amd64 || arm64)) && !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import "github.com/egoist/mygo"
|
||||
|
||||
// chooseMenuItem has no menus to choose from on other platforms.
|
||||
func chooseMenuItem(*mygo.Window, []string) error {
|
||||
return errorf(codeUnsupported, "this platform has no menus to choose from")
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//go:build windows && (amd64 || arm64) && !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"github.com/egoist/mygo"
|
||||
"github.com/egoist/mygo/internal/windows"
|
||||
)
|
||||
|
||||
// chooseMenuItem chooses an item of the window's menu bar, which shows
|
||||
// the application menu, by the labels along its path. Main thread only.
|
||||
func chooseMenuItem(w *mygo.Window, path []string) error {
|
||||
return windows.TestActivateMenuItem(w.NativeHandle(), path...)
|
||||
}
|
||||
+239
@@ -0,0 +1,239 @@
|
||||
//go:build !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/egoist/mygo/internal/accelerator"
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// roleNames are the names of platform.AccessRole's roles, in their order.
|
||||
var roleNames = [...]string{
|
||||
"group", "text", "button", "link", "checkBox", "radio", "switch", "slider",
|
||||
"progress", "textField", "image", "list", "scroll", "dialog", "popup",
|
||||
"tooltip", "popUpButton", "tabList", "tab", "splitter", "status", "table",
|
||||
"row", "cell", "columnHeader", "tree", "treeItem", "listItem", "menuButton",
|
||||
"toolbar", "radioGroup", "toggleButton", "comboBox", "disclosure", "meter",
|
||||
"stepper", "colorWell", "alertDialog", "menu", "menuBar", "menuItem",
|
||||
"menuItemCheckBox", "menuItemRadio", "heading", "region", "log", "timer",
|
||||
"alert", "separator", "rowHeader", "search", "article",
|
||||
"navigation", "grid", "treeGrid", "deletion", "insertion", "tabPanel",
|
||||
"main", "banner", "contentInfo", "complementary",
|
||||
}
|
||||
|
||||
func roleName(r platform.AccessRole) string {
|
||||
if int(r) < len(roleNames) {
|
||||
return roleNames[r]
|
||||
}
|
||||
return "role" + strconv.Itoa(int(r))
|
||||
}
|
||||
|
||||
// stateNames are the names of platform.AccessStates' bits, from the
|
||||
// lowest.
|
||||
var stateNames = [...]string{
|
||||
"focusable", "disabled", "checked", "mixed", "selected", "expanded",
|
||||
"multiline", "password", "readOnly", "selectable", "offscreen",
|
||||
"multiselectable", "segment", "search", "invalid", "sortAscending",
|
||||
"sortDescending", "expandable", "vertical", "busy", "sortOther",
|
||||
"horizontal",
|
||||
}
|
||||
|
||||
// actionNames are the names of platform.AccessActions' bits, from the
|
||||
// lowest.
|
||||
var actionNames = [...]string{
|
||||
"press", "focus", "increment", "decrement", "setValue", "scrollIntoView", "expand",
|
||||
}
|
||||
|
||||
// names returns the names of the bits set in bits.
|
||||
func names(bits uint64, of []string) []string {
|
||||
var out []string
|
||||
for i, name := range of {
|
||||
if bits&(1<<i) != 0 {
|
||||
out = append(out, name)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// actionKinds are the actions act takes, by name.
|
||||
var actionKinds = map[string]platform.AccessActionKind{
|
||||
"press": platform.AccessPress,
|
||||
"focus": platform.AccessFocus,
|
||||
"increment": platform.AccessIncrement,
|
||||
"decrement": platform.AccessDecrement,
|
||||
"setValue": platform.AccessSetValue,
|
||||
"scrollIntoView": platform.AccessScrollIntoView,
|
||||
"expand": platform.AccessExpand,
|
||||
"collapse": platform.AccessCollapse,
|
||||
"selectText": platform.AccessSelectText,
|
||||
"insertText": platform.AccessInsertText,
|
||||
}
|
||||
|
||||
// inputEvent is an event of an input request.
|
||||
type inputEvent struct {
|
||||
// Type is pointerMove, pointerDown, pointerUp, click, wheel, keyDown,
|
||||
// keyUp, key or text.
|
||||
Type string `json:"type"`
|
||||
X float64 `json:"x"`
|
||||
Y float64 `json:"y"`
|
||||
// Button is left (the default), right or middle; Clicks counts quick
|
||||
// successive presses, 1 unless set.
|
||||
Button string `json:"button"`
|
||||
Clicks int `json:"clicks"`
|
||||
// DX and DY are a wheel's distances in DIPs, Precise marks a
|
||||
// touchpad's.
|
||||
DX float64 `json:"dx"`
|
||||
DY float64 `json:"dy"`
|
||||
Precise bool `json:"precise"`
|
||||
// Key is a key with its modifiers as menus' accelerators write them,
|
||||
// as "Enter" or "CmdOrCtrl+Shift+Z".
|
||||
Key string `json:"key"`
|
||||
// Mods are the modifiers held during a pointer or wheel event: shift,
|
||||
// ctrl, alt, super or cmdOrCtrl.
|
||||
Mods []string `json:"mods"`
|
||||
Text string `json:"text"`
|
||||
// Touch marks pointer events as a finger's, on a phone: they pan and fling
|
||||
// what scrolls, rather than press as a mouse's.
|
||||
Touch bool `json:"touch"`
|
||||
}
|
||||
|
||||
// surfaceEvents returns the events of the surface that evs make, as the
|
||||
// backend's would.
|
||||
func surfaceEvents(evs []inputEvent) ([]platform.SurfaceEvent, error) {
|
||||
var out []platform.SurfaceEvent
|
||||
for i, e := range evs {
|
||||
mods, err := modifiers(e.Mods)
|
||||
if err != nil {
|
||||
return nil, errorf(codeInvalid, "event %d: %v", i, err)
|
||||
}
|
||||
button := 0
|
||||
switch e.Button {
|
||||
case "", "left":
|
||||
case "right":
|
||||
button = 1
|
||||
case "middle":
|
||||
button = 2
|
||||
default:
|
||||
return nil, errorf(codeInvalid, "event %d: no button %q: left, right or middle", i, e.Button)
|
||||
}
|
||||
clicks := max(e.Clicks, 1)
|
||||
at := platform.SurfaceEvent{X: e.X, Y: e.Y, Mods: mods, Touch: e.Touch}
|
||||
pointer := func(kind platform.SurfaceEventKind, clicks int) platform.SurfaceEvent {
|
||||
ev := at
|
||||
ev.Kind, ev.Button, ev.Clicks = kind, button, clicks
|
||||
return ev
|
||||
}
|
||||
switch e.Type {
|
||||
case "pointerMove":
|
||||
out = append(out, pointer(platform.PointerMove, 0))
|
||||
case "pointerDown":
|
||||
out = append(out, pointer(platform.PointerDown, clicks))
|
||||
case "pointerUp":
|
||||
out = append(out, pointer(platform.PointerUp, clicks))
|
||||
if e.Touch {
|
||||
// A finger is gone as it lifts, as phones tell.
|
||||
out = append(out, platform.SurfaceEvent{Kind: platform.PointerLeave, Touch: true})
|
||||
}
|
||||
case "click":
|
||||
// A double click is two presses, the second counting 2.
|
||||
out = append(out, pointer(platform.PointerMove, 0))
|
||||
for n := 1; n <= clicks; n++ {
|
||||
out = append(out, pointer(platform.PointerDown, n), pointer(platform.PointerUp, n))
|
||||
}
|
||||
case "wheel":
|
||||
ev := pointer(platform.PointerScroll, 0)
|
||||
ev.DX, ev.DY, ev.Precise = e.DX, e.DY, e.Precise
|
||||
out = append(out, ev)
|
||||
case "keyDown", "keyUp", "key":
|
||||
k, mods, err := parseKey(e.Key)
|
||||
if err != nil {
|
||||
return nil, errorf(codeInvalid, "event %d: %v", i, err)
|
||||
}
|
||||
ev := platform.SurfaceEvent{Key: k, PhysicalKey: k, Mods: mods}
|
||||
if e.Type != "keyUp" {
|
||||
ev.Kind = platform.KeyPressed
|
||||
out = append(out, ev)
|
||||
}
|
||||
if e.Type != "keyDown" {
|
||||
ev.Kind = platform.KeyReleased
|
||||
out = append(out, ev)
|
||||
}
|
||||
case "text":
|
||||
if e.Text == "" {
|
||||
return nil, errorf(codeInvalid, "event %d: text has no text", i)
|
||||
}
|
||||
out = append(out, platform.SurfaceEvent{Kind: platform.TextInput, Text: e.Text})
|
||||
default:
|
||||
return nil, errorf(codeInvalid, "event %d: no event type %q", i, e.Type)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// modifiers returns the modifiers of names.
|
||||
func modifiers(list []string) (platform.Modifiers, error) {
|
||||
var mods platform.Modifiers
|
||||
for _, name := range list {
|
||||
switch strings.ToLower(name) {
|
||||
case "shift":
|
||||
mods |= platform.ModShift
|
||||
case "ctrl", "control":
|
||||
mods |= platform.ModCtrl
|
||||
case "alt", "option":
|
||||
mods |= platform.ModAlt
|
||||
case "super", "cmd", "command", "meta":
|
||||
mods |= platform.ModSuper
|
||||
case "cmdorctrl":
|
||||
if runtime.GOOS == "darwin" {
|
||||
mods |= platform.ModSuper
|
||||
} else {
|
||||
mods |= platform.ModCtrl
|
||||
}
|
||||
default:
|
||||
return 0, fmt.Errorf("no modifier %q", name)
|
||||
}
|
||||
}
|
||||
return mods, nil
|
||||
}
|
||||
|
||||
// namedKeys are the keys of accelerators that have a key of native UI,
|
||||
// by accelerator.Accelerator's names.
|
||||
var namedKeys = map[string]platform.Key{
|
||||
"Enter": platform.KeyEnter, "Escape": platform.KeyEscape, "Backspace": platform.KeyBackspace,
|
||||
"Tab": platform.KeyTab, "Space": platform.KeySpace, "Delete": platform.KeyDelete,
|
||||
"Insert": platform.KeyInsert, "Home": platform.KeyHome, "End": platform.KeyEnd,
|
||||
"PageUp": platform.KeyPageUp, "PageDown": platform.KeyPageDown, "Left": platform.KeyLeft,
|
||||
"Right": platform.KeyRight, "Up": platform.KeyUp, "Down": platform.KeyDown,
|
||||
}
|
||||
|
||||
// parseKey returns the key and the modifiers of an accelerator.
|
||||
func parseKey(s string) (platform.Key, platform.Modifiers, error) {
|
||||
a, err := accelerator.Parse(s, runtime.GOOS)
|
||||
if err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
var mods platform.Modifiers
|
||||
for _, m := range []struct {
|
||||
a accelerator.Modifiers
|
||||
p platform.Modifiers
|
||||
}{{accelerator.Super, platform.ModSuper}, {accelerator.Ctrl, platform.ModCtrl}, {accelerator.Alt, platform.ModAlt}, {accelerator.Shift, platform.ModShift}} {
|
||||
if a.Has(m.a) {
|
||||
mods |= m.p
|
||||
}
|
||||
}
|
||||
k := namedKeys[a.Key]
|
||||
if r := []rune(a.Key); len(r) == 1 {
|
||||
k = platform.KeyForRune(r[0])
|
||||
} else if n, err := strconv.Atoi(strings.TrimPrefix(a.Key, "F")); err == nil && a.Key[0] == 'F' && n >= 1 && n <= 12 {
|
||||
k = platform.KeyF1 + platform.Key(n-1)
|
||||
}
|
||||
if k == platform.KeyUnknown {
|
||||
return 0, 0, fmt.Errorf("native UI has no key %q", a.Key)
|
||||
}
|
||||
return k, mods, nil
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
//go:build mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import "os"
|
||||
|
||||
// Builds without the inspector leave the plugin out, as they are the
|
||||
// app's release: it says so rather than leave a test runner waiting.
|
||||
func init() {
|
||||
if os.Getenv("MYGO_AUTOMATION") != "" {
|
||||
os.Stderr.WriteString("mygo: MYGO_AUTOMATION is ignored: this build leaves automation out (mygo_noinspector)\n")
|
||||
}
|
||||
}
|
||||
+515
@@ -0,0 +1,515 @@
|
||||
//go:build !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"image/png"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// maxLine is the longest request a line may hold, as a script to
|
||||
// evaluate.
|
||||
const maxLine = 16 << 20
|
||||
|
||||
// request is a line a client sends.
|
||||
type request struct {
|
||||
// ID is any JSON value, which the response repeats.
|
||||
ID json.RawMessage `json:"id"`
|
||||
Method string `json:"method"`
|
||||
Params json.RawMessage `json:"params"`
|
||||
}
|
||||
|
||||
// response is the line that answers a request: its Result, or its Error.
|
||||
type response struct {
|
||||
ID json.RawMessage `json:"id"`
|
||||
Result any `json:"result,omitempty"`
|
||||
Error *Error `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// Error is a request's failure, with a code clients test and a message
|
||||
// people read.
|
||||
type Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
}
|
||||
|
||||
func (e *Error) Error() string { return e.Code + ": " + e.Message }
|
||||
|
||||
// The codes of Error.
|
||||
const (
|
||||
// codeParse: the line is not a JSON object.
|
||||
codeParse = "parse_error"
|
||||
// codeInvalid: the request lacks a method, or its params are not the
|
||||
// method's.
|
||||
codeInvalid = "invalid_request"
|
||||
// codeUnknownMethod: no such method.
|
||||
codeUnknownMethod = "unknown_method"
|
||||
// codeNoWindow: no window has the ID, or the app has none.
|
||||
codeNoWindow = "no_window"
|
||||
// codeNoElement: no element of the window's last frame has the ID or
|
||||
// the key.
|
||||
codeNoElement = "no_element"
|
||||
// codeUnsupported: the window or the platform cannot do it, as
|
||||
// reading the elements of a page.
|
||||
codeUnsupported = "unsupported"
|
||||
// codeTimeout: the window did not settle in the time idle allowed.
|
||||
codeTimeout = "timeout"
|
||||
// codeFailed: the app could not do it, as a script that threw.
|
||||
codeFailed = "failed"
|
||||
)
|
||||
|
||||
func errorf(code, format string, args ...any) *Error {
|
||||
return &Error{Code: code, Message: fmt.Sprintf(format, args...)}
|
||||
}
|
||||
|
||||
// driver is what requests do in the app. Window 0 is the default window:
|
||||
// the focused one, else the first. Methods are called from the goroutines
|
||||
// of connections, and hop to the main thread for what they touch.
|
||||
type driver interface {
|
||||
windows() ([]windowInfo, error)
|
||||
tree(window int) (int, *platform.AccessTree, map[uint64]any, error)
|
||||
act(window int, ev platform.SurfaceEvent) error
|
||||
input(window int, evs []platform.SurfaceEvent) error
|
||||
menu(window int, path []string) error
|
||||
capture(window int) ([]byte, error)
|
||||
eval(window int, script string) (any, error)
|
||||
idle(window int, timeout time.Duration) error
|
||||
}
|
||||
|
||||
// serve answers the connections of l until it closes.
|
||||
func serve(l net.Listener, d driver) {
|
||||
for {
|
||||
c, err := l.Accept()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
go serveConn(c, d)
|
||||
}
|
||||
}
|
||||
|
||||
// serveConn answers the requests of a connection in order, each once the
|
||||
// one before it is answered, until the client closes it.
|
||||
func serveConn(c io.ReadWriteCloser, d driver) {
|
||||
defer c.Close()
|
||||
sc := bufio.NewScanner(c)
|
||||
sc.Buffer(make([]byte, 0, 64<<10), maxLine)
|
||||
enc := json.NewEncoder(c)
|
||||
enc.SetEscapeHTML(false)
|
||||
for sc.Scan() {
|
||||
line := bytes.TrimSpace(sc.Bytes())
|
||||
if len(line) == 0 {
|
||||
continue
|
||||
}
|
||||
if enc.Encode(handle(d, line)) != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if errors.Is(sc.Err(), bufio.ErrTooLong) {
|
||||
enc.Encode(response{Error: errorf(codeParse, "a request is longer than %d bytes", maxLine)})
|
||||
}
|
||||
}
|
||||
|
||||
// handle answers a line.
|
||||
func handle(d driver, line []byte) response {
|
||||
var req request
|
||||
if err := json.Unmarshal(line, &req); err != nil {
|
||||
return response{Error: errorf(codeParse, "%v", err)}
|
||||
}
|
||||
res := response{ID: req.ID}
|
||||
v, err := call(d, req)
|
||||
if err != nil {
|
||||
var e *Error
|
||||
if !errors.As(err, &e) {
|
||||
e = &Error{Code: codeFailed, Message: err.Error()}
|
||||
}
|
||||
res.Error = e
|
||||
return res
|
||||
}
|
||||
res.Result = v
|
||||
return res
|
||||
}
|
||||
|
||||
// done is the result of requests that answer nothing but success.
|
||||
type done struct{}
|
||||
|
||||
// call performs a request.
|
||||
func call(d driver, req request) (any, error) {
|
||||
switch req.Method {
|
||||
case "":
|
||||
return nil, errorf(codeInvalid, "the request has no method")
|
||||
case "windows":
|
||||
if err := params(req, &struct{}{}); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ws, err := d.windows()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return windowsResult{Windows: ws}, nil
|
||||
case "tree":
|
||||
var p windowParams
|
||||
if err := params(req, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
w, t, keys, err := d.tree(p.Window)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return treeJSON(w, t, keys), nil
|
||||
case "act":
|
||||
var p actParams
|
||||
if err := params(req, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return act(d, p)
|
||||
case "input":
|
||||
var p inputParams
|
||||
if err := params(req, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
evs, err := surfaceEvents(p.Events)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return done{}, d.input(p.Window, evs)
|
||||
case "menu":
|
||||
var p menuParams
|
||||
if err := params(req, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(p.Path) == 0 {
|
||||
return nil, errorf(codeInvalid, "menu needs the path of the item, as [\"File\", \"New\"]")
|
||||
}
|
||||
return done{}, d.menu(p.Window, p.Path)
|
||||
case "capture":
|
||||
var p windowParams
|
||||
if err := params(req, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, err := d.capture(p.Window)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
r := captureResult{PNG: b}
|
||||
if c, err := png.DecodeConfig(bytes.NewReader(b)); err == nil {
|
||||
r.Width, r.Height = c.Width, c.Height
|
||||
}
|
||||
return r, nil
|
||||
case "eval":
|
||||
var p evalParams
|
||||
if err := params(req, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v, err := d.eval(p.Window, p.Script)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return evalResult{Value: v}, nil
|
||||
case "idle":
|
||||
var p idleParams
|
||||
if err := params(req, &p); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if p.Timeout < 0 {
|
||||
return nil, errorf(codeInvalid, "timeout is negative")
|
||||
}
|
||||
return done{}, d.idle(p.Window, time.Duration(p.Timeout)*time.Millisecond)
|
||||
}
|
||||
return nil, errorf(codeUnknownMethod, "no method %q", req.Method)
|
||||
}
|
||||
|
||||
// params decodes the params of a request into p, refusing fields the
|
||||
// method does not take.
|
||||
func params(req request, p any) error {
|
||||
raw := bytes.TrimSpace(req.Params)
|
||||
if len(raw) == 0 || bytes.Equal(raw, []byte("null")) {
|
||||
return nil
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(p); err != nil {
|
||||
return errorf(codeInvalid, "params of %s: %v", req.Method, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type windowParams struct {
|
||||
Window int `json:"window"`
|
||||
}
|
||||
|
||||
type actParams struct {
|
||||
Window int `json:"window"`
|
||||
ID nodeID `json:"id"`
|
||||
// Key finds the element by its key instead of ID.
|
||||
Key json.RawMessage `json:"key"`
|
||||
Action string `json:"action"`
|
||||
// Text is setValue's and insertText's; From and To are selectText's.
|
||||
Text string `json:"text"`
|
||||
From int `json:"from"`
|
||||
To int `json:"to"`
|
||||
}
|
||||
|
||||
type inputParams struct {
|
||||
Window int `json:"window"`
|
||||
Events []inputEvent `json:"events"`
|
||||
}
|
||||
|
||||
type menuParams struct {
|
||||
Window int `json:"window"`
|
||||
Path []string `json:"path"`
|
||||
}
|
||||
|
||||
type evalParams struct {
|
||||
Window int `json:"window"`
|
||||
Script string `json:"script"`
|
||||
}
|
||||
|
||||
type idleParams struct {
|
||||
Window int `json:"window"`
|
||||
// Timeout is in milliseconds, 0 for none.
|
||||
Timeout int `json:"timeout"`
|
||||
}
|
||||
|
||||
type windowsResult struct {
|
||||
Windows []windowInfo `json:"windows"`
|
||||
}
|
||||
|
||||
// windowInfo describes a window.
|
||||
type windowInfo struct {
|
||||
ID int `json:"id"`
|
||||
Title string `json:"title"`
|
||||
// Kind is "content" for a window of native UI, "page" for a web page.
|
||||
Kind string `json:"kind"`
|
||||
// URL is a page's.
|
||||
URL string `json:"url,omitempty"`
|
||||
Bounds rect `json:"bounds"`
|
||||
ContentBounds rect `json:"contentBounds"`
|
||||
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"`
|
||||
}
|
||||
|
||||
type captureResult struct {
|
||||
// PNG is encoded in base64, as encoding/json does []byte; Width and
|
||||
// Height are its size in pixels.
|
||||
PNG []byte `json:"png"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
}
|
||||
|
||||
type evalResult struct {
|
||||
Value any `json:"value"`
|
||||
}
|
||||
|
||||
// nodeID is the ID of an element. It goes as a string of its decimal
|
||||
// digits, which JavaScript's numbers would round, and comes as one or as
|
||||
// a number.
|
||||
type nodeID uint64
|
||||
|
||||
func (id nodeID) MarshalJSON() ([]byte, error) {
|
||||
return strconv.AppendQuote(nil, strconv.FormatUint(uint64(id), 10)), nil
|
||||
}
|
||||
|
||||
func (id *nodeID) UnmarshalJSON(b []byte) error {
|
||||
s := string(b)
|
||||
if u, err := strconv.Unquote(s); err == nil {
|
||||
s = u
|
||||
}
|
||||
n, err := strconv.ParseUint(s, 10, 64)
|
||||
if err != nil {
|
||||
return fmt.Errorf("an element ID is a string of digits, not %s", b)
|
||||
}
|
||||
*id = nodeID(n)
|
||||
return nil
|
||||
}
|
||||
|
||||
// act performs an action of assistive technology on the element of the
|
||||
// ID or the key.
|
||||
func act(d driver, p actParams) (any, error) {
|
||||
kind, ok := actionKinds[p.Action]
|
||||
if !ok {
|
||||
return nil, errorf(codeInvalid, "no action %q", p.Action)
|
||||
}
|
||||
hasKey := len(bytes.TrimSpace(p.Key)) > 0
|
||||
switch {
|
||||
case p.ID == 0 && !hasKey:
|
||||
return nil, errorf(codeInvalid, "act needs the id or the key of an element")
|
||||
case p.ID != 0 && hasKey:
|
||||
return nil, errorf(codeInvalid, "act takes an id or a key, not both")
|
||||
}
|
||||
id := uint64(p.ID)
|
||||
if hasKey {
|
||||
var want bytes.Buffer
|
||||
if err := json.Compact(&want, p.Key); err != nil {
|
||||
return nil, errorf(codeInvalid, "key: %v", err)
|
||||
}
|
||||
_, t, keys, err := d.tree(p.Window)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
n := 0
|
||||
for _, node := range t.Nodes {
|
||||
k, ok := keys[node.ID]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if b, err := json.Marshal(keyJSON(k)); err == nil && bytes.Equal(b, want.Bytes()) {
|
||||
id = node.ID
|
||||
n++
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case n == 0:
|
||||
return nil, errorf(codeNoElement, "no element has the key %s", want.Bytes())
|
||||
case n > 1:
|
||||
return nil, errorf(codeInvalid, "%d elements have the key %s: act on one by its id", n, want.Bytes())
|
||||
}
|
||||
}
|
||||
ev := platform.SurfaceEvent{Kind: platform.AccessAction, ID: id, Action: kind, Text: p.Text, From: p.From, To: p.To}
|
||||
return done{}, d.act(p.Window, ev)
|
||||
}
|
||||
|
||||
// treeJSON is the tree request's answer: the elements of window's last
|
||||
// frame.
|
||||
func treeJSON(window int, t *platform.AccessTree, keys map[uint64]any) treeResult {
|
||||
r := treeResult{Window: window, Focus: nodeID(t.Focus), Nodes: make([]nodeJSON, 0, len(t.Nodes)), Announcements: t.Announcements}
|
||||
for _, n := range t.Nodes {
|
||||
j := nodeJSON{
|
||||
ID: nodeID(n.ID), Role: roleName(n.Role), Label: n.Label, Value: n.Value,
|
||||
Placeholder: n.Placeholder, Description: n.Description, KeyShortcuts: n.KeyShortcuts,
|
||||
Bounds: rect{n.Bounds.X, n.Bounds.Y, n.Bounds.W, n.Bounds.H},
|
||||
States: names(uint64(n.States), stateNames[:]),
|
||||
Actions: names(uint64(n.Actions), actionNames[:]),
|
||||
Level: n.Level, PosInSet: n.PosInSet, SetSize: n.SetSize,
|
||||
RowCount: n.RowCount, ColCount: n.ColCount, RowIndex: n.RowIndex, ColIndex: n.ColIndex,
|
||||
RowSpan: n.RowSpan, ColSpan: n.ColSpan,
|
||||
Current: n.Current.String(), AutoComplete: n.AutoComplete.String(), WebView: n.WebView != nil,
|
||||
RoleDescription: n.RoleDescription, HasPopup: n.HasPopup.String(),
|
||||
}
|
||||
for _, c := range n.Controls {
|
||||
j.Controls = append(j.Controls, nodeID(c))
|
||||
}
|
||||
for _, d := range n.DescribedBy {
|
||||
j.DescribedBy = append(j.DescribedBy, nodeID(d))
|
||||
}
|
||||
if n.States&platform.AccessInvalid != 0 {
|
||||
for _, m := range n.ErrorMessage {
|
||||
j.ErrorMessage = append(j.ErrorMessage, nodeID(m))
|
||||
}
|
||||
}
|
||||
if n.Parent >= 0 && n.Parent < len(t.Nodes) {
|
||||
j.Parent = nodeID(t.Nodes[n.Parent].ID)
|
||||
}
|
||||
if k, ok := keys[n.ID]; ok {
|
||||
j.Key = keyJSON(k)
|
||||
}
|
||||
if n.Role.Ranged() {
|
||||
j.Min, j.Max, j.Now, j.Step = &n.Min, &n.Max, &n.Now, &n.Step
|
||||
}
|
||||
if n.Role == platform.RoleTextField || n.Role == platform.RoleComboBox {
|
||||
j.Selection = &[2]int{n.SelStart, n.SelEnd}
|
||||
}
|
||||
r.Nodes = append(r.Nodes, j)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
type treeResult struct {
|
||||
Window int `json:"window"`
|
||||
// Focus is the element with the keyboard focus.
|
||||
Focus nodeID `json:"focus,omitempty"`
|
||||
Nodes []nodeJSON `json:"nodes"`
|
||||
Announcements []string `json:"announcements,omitempty"`
|
||||
}
|
||||
|
||||
// nodeJSON is an element, as assistive technology reads it.
|
||||
type nodeJSON struct {
|
||||
ID nodeID `json:"id"`
|
||||
// Parent is omitted for the elements at the top.
|
||||
Parent nodeID `json:"parent,omitempty"`
|
||||
Role string `json:"role"`
|
||||
// Key is the key the app gave the element (ui's Key).
|
||||
Key any `json:"key,omitempty"`
|
||||
Label string `json:"label,omitempty"`
|
||||
Value string `json:"value,omitempty"`
|
||||
Placeholder string `json:"placeholder,omitempty"`
|
||||
Description string `json:"description,omitempty"`
|
||||
Bounds rect `json:"bounds"`
|
||||
States []string `json:"states,omitempty"`
|
||||
Actions []string `json:"actions,omitempty"`
|
||||
// Min, Max, Now and Step are those of a slider, a progress bar, a
|
||||
// meter or a stepper.
|
||||
Min *float64 `json:"min,omitempty"`
|
||||
Max *float64 `json:"max,omitempty"`
|
||||
Now *float64 `json:"now,omitempty"`
|
||||
Step *float64 `json:"step,omitempty"`
|
||||
// KeyShortcuts are the keys that press or focus the element, as
|
||||
// ARIA's aria-keyshortcuts, as the platform's menus write them
|
||||
// ("⌘K" on macOS, "Ctrl+K" elsewhere), separated by spaces.
|
||||
KeyShortcuts string `json:"keyShortcuts,omitempty"`
|
||||
// Selection is a text field's, in runes.
|
||||
Selection *[2]int `json:"selection,omitempty"`
|
||||
Level int `json:"level,omitempty"`
|
||||
PosInSet int `json:"posInSet,omitempty"`
|
||||
SetSize int `json:"setSize,omitempty"`
|
||||
// RowCount and ColCount are how many rows and columns a table or a
|
||||
// grid has, and RowIndex and ColIndex the place of a row or a cell
|
||||
// among them, from 1, as the app gave them (aria-rowcount,
|
||||
// aria-colcount, aria-rowindex, aria-colindex).
|
||||
RowCount int `json:"rowCount,omitempty"`
|
||||
ColCount int `json:"colCount,omitempty"`
|
||||
RowIndex int `json:"rowIndex,omitempty"`
|
||||
ColIndex int `json:"colIndex,omitempty"`
|
||||
// RowSpan and ColSpan are how many rows and columns a cell covers,
|
||||
// when more than one (aria-rowspan, aria-colspan).
|
||||
RowSpan int `json:"rowSpan,omitempty"`
|
||||
ColSpan int `json:"colSpan,omitempty"`
|
||||
// Current is the item the element is the current one of, as ARIA's
|
||||
// aria-current: true, page, step, location, date or time.
|
||||
Current string `json:"current,omitempty"`
|
||||
// AutoComplete is what the suggestions of a text field or a combo
|
||||
// box complete as the user types, as ARIA's aria-autocomplete:
|
||||
// inline, list or both.
|
||||
AutoComplete string `json:"autoComplete,omitempty"`
|
||||
// RoleDescription is what the app calls the element's role, as
|
||||
// ARIA's aria-roledescription; HasPopup the kind of popup it opens,
|
||||
// as aria-haspopup: menu, listbox, tree, grid or dialog; Controls the
|
||||
// elements it controls, as aria-controls.
|
||||
RoleDescription string `json:"roleDescription,omitempty"`
|
||||
HasPopup string `json:"hasPopup,omitempty"`
|
||||
Controls []nodeID `json:"controls,omitempty"`
|
||||
// DescribedBy are the elements whose text describes the element, as
|
||||
// ARIA's aria-describedby, and ErrorMessage those holding its error
|
||||
// while it is invalid, as aria-errormessage.
|
||||
DescribedBy []nodeID `json:"describedBy,omitempty"`
|
||||
ErrorMessage []nodeID `json:"errorMessage,omitempty"`
|
||||
// WebView marks the node of a web view's page, whose elements the
|
||||
// tree leaves out.
|
||||
WebView bool `json:"webView,omitempty"`
|
||||
}
|
||||
|
||||
// keyJSON is how a key goes in JSON: strings, booleans and integers as
|
||||
// themselves, other keys as fmt prints them.
|
||||
func keyJSON(k any) any {
|
||||
switch k := k.(type) {
|
||||
case string, bool, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64, uintptr:
|
||||
return k
|
||||
}
|
||||
return fmt.Sprint(k)
|
||||
}
|
||||
@@ -0,0 +1,451 @@
|
||||
//go:build !mygo_noinspector
|
||||
|
||||
package automation
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"image"
|
||||
"image/png"
|
||||
"net"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/egoist/mygo/internal/platform"
|
||||
)
|
||||
|
||||
// fakeDriver records what requests ask of the app.
|
||||
type fakeDriver struct {
|
||||
access *platform.AccessTree
|
||||
keys map[uint64]any
|
||||
acted []platform.SurfaceEvent
|
||||
sent []platform.SurfaceEvent
|
||||
menus [][]string
|
||||
png []byte
|
||||
evalFn func(string) (any, error)
|
||||
waited time.Duration
|
||||
}
|
||||
|
||||
func (d *fakeDriver) windows() ([]windowInfo, error) {
|
||||
return []windowInfo{{ID: 1, Title: "Counter", Kind: "content", Bounds: rect{10, 20, 300, 200}, Focused: true, Visible: true}}, nil
|
||||
}
|
||||
|
||||
func (d *fakeDriver) tree(window int) (int, *platform.AccessTree, map[uint64]any, error) {
|
||||
if window > 1 {
|
||||
return 0, nil, nil, errorf(codeNoWindow, "no window %d", window)
|
||||
}
|
||||
return 1, d.access, d.keys, nil
|
||||
}
|
||||
|
||||
func (d *fakeDriver) act(window int, ev platform.SurfaceEvent) error {
|
||||
d.acted = append(d.acted, ev)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *fakeDriver) input(window int, evs []platform.SurfaceEvent) error {
|
||||
d.sent = append(d.sent, evs...)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *fakeDriver) menu(window int, path []string) error {
|
||||
d.menus = append(d.menus, path)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d *fakeDriver) capture(window int) ([]byte, error) { return d.png, nil }
|
||||
|
||||
func (d *fakeDriver) eval(window int, script string) (any, error) { return d.evalFn(script) }
|
||||
|
||||
func (d *fakeDriver) idle(window int, timeout time.Duration) error {
|
||||
d.waited = timeout
|
||||
return nil
|
||||
}
|
||||
|
||||
// do answers line, as JSON.
|
||||
func do(t *testing.T, d driver, line string) map[string]any {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(handle(d, []byte(line)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var m map[string]any
|
||||
if err := json.Unmarshal(b, &m); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// errCode returns the code of the error of a response, "" for none.
|
||||
func errCode(m map[string]any) string {
|
||||
e, _ := m["error"].(map[string]any)
|
||||
code, _ := e["code"].(string)
|
||||
return code
|
||||
}
|
||||
|
||||
func TestRequestErrors(t *testing.T) {
|
||||
d := &fakeDriver{}
|
||||
for _, c := range []struct{ line, code string }{
|
||||
{`not json`, codeParse},
|
||||
{`[1, 2]`, codeParse},
|
||||
{`{"id": 1}`, codeInvalid},
|
||||
{`{"id": 1, "method": "fly"}`, codeUnknownMethod},
|
||||
{`{"id": 1, "method": "tree", "params": {"window": 1, "windwo": 2}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "tree", "params": {"window": "one"}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "tree", "params": {"window": 7}}`, codeNoWindow},
|
||||
{`{"id": 1, "method": "windows", "params": {"window": 1}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "menu", "params": {"path": []}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "idle", "params": {"timeout": -1}}`, codeInvalid},
|
||||
} {
|
||||
m := do(t, d, c.line)
|
||||
if got := errCode(m); got != c.code {
|
||||
t.Errorf("%s: error %v, want %s", c.line, m["error"], c.code)
|
||||
}
|
||||
if _, ok := m["result"]; ok {
|
||||
t.Errorf("%s: a result with the error: %v", c.line, m)
|
||||
}
|
||||
}
|
||||
// The ID comes back as it went, or null when the line has none.
|
||||
if m := do(t, d, `{"id": "a-7", "method": "fly"}`); m["id"] != "a-7" {
|
||||
t.Errorf("id %v", m["id"])
|
||||
}
|
||||
if b, _ := json.Marshal(handle(d, []byte("{"))); !bytes.Contains(b, []byte(`"id":null`)) {
|
||||
t.Errorf("an unreadable line's answer: %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWindowsRequest(t *testing.T) {
|
||||
m := do(t, &fakeDriver{}, `{"id": 1, "method": "windows"}`)
|
||||
ws := m["result"].(map[string]any)["windows"].([]any)
|
||||
w := ws[0].(map[string]any)
|
||||
if w["id"] != 1.0 || w["kind"] != "content" || w["focused"] != true || w["bounds"].(map[string]any)["width"] != 300.0 {
|
||||
t.Errorf("windows: %v", ws)
|
||||
}
|
||||
}
|
||||
|
||||
// testTree is a window's tree: a button in a group, and a text field.
|
||||
func testTree() (*platform.AccessTree, map[uint64]any) {
|
||||
t := &platform.AccessTree{Focus: 1 << 60, Nodes: []platform.AccessNode{
|
||||
{ID: 7, Parent: -1, Role: platform.RoleGroup},
|
||||
{ID: 1 << 60, Parent: 0, Role: platform.RoleButton, Label: "Add", KeyShortcuts: "Ctrl+N",
|
||||
States: platform.AccessFocusable, Actions: platform.ActionPress | platform.ActionFocus,
|
||||
Bounds: platform.RectF{X: 1, Y: 2, W: 30, H: 20}},
|
||||
{ID: 9, Parent: 0, Role: platform.RoleTextField, Value: "hey", SelStart: 3, SelEnd: 3, AutoComplete: platform.AutoCompleteList},
|
||||
{ID: 11, Parent: 0, Role: platform.RoleSlider, Min: 0, Max: 10, Now: 4},
|
||||
}}
|
||||
return t, map[uint64]any{1 << 60: "add", 9: 42}
|
||||
}
|
||||
|
||||
func TestTreeRequest(t *testing.T) {
|
||||
tree, keys := testTree()
|
||||
m := do(t, &fakeDriver{access: tree, keys: keys}, `{"id": 1, "method": "tree"}`)
|
||||
r := m["result"].(map[string]any)
|
||||
if r["window"] != 1.0 || r["focus"] != "1152921504606846976" {
|
||||
t.Errorf("tree: %v", r)
|
||||
}
|
||||
nodes := r["nodes"].([]any)
|
||||
group, button, field, slider := nodes[0].(map[string]any), nodes[1].(map[string]any), nodes[2].(map[string]any), nodes[3].(map[string]any)
|
||||
if _, ok := group["parent"]; ok || group["role"] != "group" {
|
||||
t.Errorf("group: %v", group)
|
||||
}
|
||||
// IDs go as strings, which JavaScript's numbers would round.
|
||||
if button["id"] != "1152921504606846976" || button["parent"] != "7" || button["role"] != "button" || button["key"] != "add" || button["label"] != "Add" || button["keyShortcuts"] != "Ctrl+N" {
|
||||
t.Errorf("button: %v", button)
|
||||
}
|
||||
if !slices.Equal(button["states"].([]any), []any{"focusable"}) || !slices.Equal(button["actions"].([]any), []any{"press", "focus"}) {
|
||||
t.Errorf("button's states and actions: %v %v", button["states"], button["actions"])
|
||||
}
|
||||
if b := button["bounds"].(map[string]any); b["x"] != 1.0 || b["height"] != 20.0 {
|
||||
t.Errorf("button's bounds: %v", b)
|
||||
}
|
||||
if field["key"] != 42.0 || field["value"] != "hey" || !slices.Equal(field["selection"].([]any), []any{3.0, 3.0}) || field["autoComplete"] != "list" {
|
||||
t.Errorf("text field: %v", field)
|
||||
}
|
||||
if slider["max"] != 10.0 || slider["now"] != 4.0 || slider["min"] != 0.0 {
|
||||
t.Errorf("slider: %v", slider)
|
||||
}
|
||||
if _, ok := field["keyShortcuts"]; ok {
|
||||
t.Errorf("a text field with key shortcuts: %v", field)
|
||||
}
|
||||
if _, ok := button["autoComplete"]; ok {
|
||||
t.Errorf("a button with suggestions: %v", button)
|
||||
}
|
||||
if _, ok := button["min"]; ok {
|
||||
t.Errorf("a button with a range: %v", button)
|
||||
}
|
||||
}
|
||||
|
||||
// A grid gives its size and its rows and cells their places, as the app
|
||||
// gave them, and the columns a cell covers, and says it chooses several
|
||||
// rows.
|
||||
func TestTreeGrid(t *testing.T) {
|
||||
tree := &platform.AccessTree{Nodes: []platform.AccessNode{
|
||||
{ID: 1, Parent: -1, Role: platform.RoleGrid, Label: "Sheet", RowCount: 10001, ColCount: 5, States: platform.AccessSelectable | platform.AccessMultiselectable},
|
||||
{ID: 2, Parent: 0, Role: platform.RoleRow, RowIndex: 4122},
|
||||
{ID: 3, Parent: 1, Role: platform.RoleCell, Label: "B4121", ColIndex: 2, ColSpan: 2},
|
||||
}}
|
||||
m := do(t, &fakeDriver{access: tree}, `{"id": 1, "method": "tree"}`)
|
||||
nodes := m["result"].(map[string]any)["nodes"].([]any)
|
||||
grid, row, cell := nodes[0].(map[string]any), nodes[1].(map[string]any), nodes[2].(map[string]any)
|
||||
if grid["role"] != "grid" || grid["rowCount"] != 10001.0 || grid["colCount"] != 5.0 || !slices.Contains(grid["states"].([]any), "multiselectable") {
|
||||
t.Errorf("grid: %v", grid)
|
||||
}
|
||||
if row["rowIndex"] != 4122.0 || cell["colIndex"] != 2.0 || cell["colSpan"] != 2.0 {
|
||||
t.Errorf("row %v, cell %v", row, cell)
|
||||
}
|
||||
if _, ok := cell["rowIndex"]; ok {
|
||||
t.Errorf("a cell with a row index of its own: %v", cell)
|
||||
}
|
||||
if _, ok := cell["rowSpan"]; ok {
|
||||
t.Errorf("a cell covering one row with a row span: %v", cell)
|
||||
}
|
||||
}
|
||||
|
||||
func TestActRequest(t *testing.T) {
|
||||
tree, keys := testTree()
|
||||
d := &fakeDriver{access: tree, keys: keys}
|
||||
for _, line := range []string{
|
||||
`{"id": 1, "method": "act", "params": {"id": "1152921504606846976", "action": "press"}}`,
|
||||
`{"id": 2, "method": "act", "params": {"key": "add", "action": "press"}}`,
|
||||
`{"id": 3, "method": "act", "params": {"key": 42, "action": "setValue", "text": "hi"}}`,
|
||||
`{"id": 4, "method": "act", "params": {"id": 9, "action": "selectText", "from": 1, "to": 2}}`,
|
||||
} {
|
||||
if m := do(t, d, line); m["error"] != nil {
|
||||
t.Fatalf("%s: %v", line, m["error"])
|
||||
}
|
||||
}
|
||||
want := []platform.SurfaceEvent{
|
||||
{Kind: platform.AccessAction, ID: 1 << 60, Action: platform.AccessPress},
|
||||
{Kind: platform.AccessAction, ID: 1 << 60, Action: platform.AccessPress},
|
||||
{Kind: platform.AccessAction, ID: 9, Action: platform.AccessSetValue, Text: "hi"},
|
||||
{Kind: platform.AccessAction, ID: 9, Action: platform.AccessSelectText, From: 1, To: 2},
|
||||
}
|
||||
if len(d.acted) != len(want) {
|
||||
t.Fatalf("acted %+v", d.acted)
|
||||
}
|
||||
for i := range want {
|
||||
if a, w := d.acted[i], want[i]; a.Kind != w.Kind || a.ID != w.ID || a.Action != w.Action || a.Text != w.Text || a.From != w.From || a.To != w.To {
|
||||
t.Errorf("action %d: %+v, want %+v", i, a, w)
|
||||
}
|
||||
}
|
||||
|
||||
keys[11] = "add" // two elements have it now
|
||||
for _, c := range []struct{ line, code string }{
|
||||
{`{"id": 1, "method": "act", "params": {"action": "press"}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "act", "params": {"id": "7", "key": "add", "action": "press"}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "act", "params": {"id": "7", "action": "smash"}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "act", "params": {"id": "seven", "action": "press"}}`, codeInvalid},
|
||||
{`{"id": 1, "method": "act", "params": {"key": "remove", "action": "press"}}`, codeNoElement},
|
||||
{`{"id": 1, "method": "act", "params": {"key": "add", "action": "press"}}`, codeInvalid},
|
||||
} {
|
||||
if m := do(t, d, c.line); errCode(m) != c.code {
|
||||
t.Errorf("%s: error %v, want %s", c.line, m["error"], c.code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInputRequest(t *testing.T) {
|
||||
d := &fakeDriver{}
|
||||
m := do(t, d, `{"id": 1, "method": "input", "params": {"events": [
|
||||
{"type": "click", "x": 5, "y": 6, "clicks": 2},
|
||||
{"type": "pointerDown", "x": 1, "y": 2, "button": "right", "mods": ["shift"]},
|
||||
{"type": "wheel", "x": 1, "y": 2, "dy": 40, "precise": true},
|
||||
{"type": "key", "key": "Ctrl+Shift+Z"},
|
||||
{"type": "keyDown", "key": "Enter"},
|
||||
{"type": "keyUp", "key": "F5"},
|
||||
{"type": "text", "text": "héllo"}
|
||||
]}}`)
|
||||
if m["error"] != nil {
|
||||
t.Fatal(m["error"])
|
||||
}
|
||||
type ev struct {
|
||||
kind platform.SurfaceEventKind
|
||||
x, dy float64
|
||||
button, click int
|
||||
key platform.Key
|
||||
mods platform.Modifiers
|
||||
text string
|
||||
}
|
||||
var got []ev
|
||||
for _, e := range d.sent {
|
||||
got = append(got, ev{e.Kind, e.X, e.DY, e.Button, e.Clicks, e.Key, e.Mods, e.Text})
|
||||
}
|
||||
want := []ev{
|
||||
{kind: platform.PointerMove, x: 5},
|
||||
{kind: platform.PointerDown, x: 5, click: 1}, {kind: platform.PointerUp, x: 5, click: 1},
|
||||
{kind: platform.PointerDown, x: 5, click: 2}, {kind: platform.PointerUp, x: 5, click: 2},
|
||||
{kind: platform.PointerDown, x: 1, button: 1, click: 1, mods: platform.ModShift},
|
||||
{kind: platform.PointerScroll, x: 1, dy: 40},
|
||||
{kind: platform.KeyPressed, key: platform.KeyZ, mods: platform.ModCtrl | platform.ModShift},
|
||||
{kind: platform.KeyReleased, key: platform.KeyZ, mods: platform.ModCtrl | platform.ModShift},
|
||||
{kind: platform.KeyPressed, key: platform.KeyEnter},
|
||||
{kind: platform.KeyReleased, key: platform.KeyF5},
|
||||
{kind: platform.TextInput, text: "héllo"},
|
||||
}
|
||||
if !slices.Equal(got, want) {
|
||||
t.Errorf("events:\n%+v\nwant\n%+v", got, want)
|
||||
}
|
||||
if !d.sent[6].Precise || d.sent[7].PhysicalKey != platform.KeyZ {
|
||||
t.Errorf("wheel %+v, key %+v", d.sent[6], d.sent[7])
|
||||
}
|
||||
|
||||
for _, events := range []string{
|
||||
`[{"type": "hover"}]`,
|
||||
`[{"type": "key", "key": "Hyper+A"}]`,
|
||||
`[{"type": "key", "key": "VolumeUp"}]`,
|
||||
`[{"type": "click", "button": "fourth"}]`,
|
||||
`[{"type": "click", "mods": ["fn"]}]`,
|
||||
`[{"type": "text"}]`,
|
||||
} {
|
||||
n := len(d.sent)
|
||||
if m := do(t, d, `{"id": 1, "method": "input", "params": {"events": `+events+`}}`); errCode(m) != codeInvalid {
|
||||
t.Errorf("%s: error %v", events, m["error"])
|
||||
}
|
||||
if len(d.sent) != n {
|
||||
t.Errorf("%s: sent events before failing", events)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMenuCaptureEvalIdle(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
png.Encode(&buf, image.NewRGBA(image.Rect(0, 0, 3, 2)))
|
||||
d := &fakeDriver{png: buf.Bytes(), evalFn: func(s string) (any, error) {
|
||||
if s == "throw 1" {
|
||||
return nil, errors.New("Uncaught 1")
|
||||
}
|
||||
return map[string]any{"title": "E2E"}, nil
|
||||
}}
|
||||
if m := do(t, d, `{"id": 1, "method": "menu", "params": {"path": ["File", "New"]}}`); m["error"] != nil || !slices.Equal(d.menus[0], []string{"File", "New"}) {
|
||||
t.Errorf("menu: %v %v", m, d.menus)
|
||||
}
|
||||
m := do(t, d, `{"id": 1, "method": "capture"}`)
|
||||
r := m["result"].(map[string]any)
|
||||
if r["png"] == nil || r["width"] != 3.0 || r["height"] != 2.0 {
|
||||
t.Errorf("capture: %v", r)
|
||||
}
|
||||
var cr captureResult
|
||||
b, _ := json.Marshal(m["result"])
|
||||
if json.Unmarshal(b, &cr) != nil || !bytes.Equal(cr.PNG, buf.Bytes()) {
|
||||
t.Errorf("the PNG did not come back whole")
|
||||
}
|
||||
if m := do(t, d, `{"id": 1, "method": "eval", "params": {"script": "({title: document.title})"}}`); m["result"].(map[string]any)["value"].(map[string]any)["title"] != "E2E" {
|
||||
t.Errorf("eval: %v", m)
|
||||
}
|
||||
if m := do(t, d, `{"id": 1, "method": "eval", "params": {"script": "throw 1"}}`); errCode(m) != codeFailed {
|
||||
t.Errorf("eval that throws: %v", m)
|
||||
}
|
||||
if m := do(t, d, `{"id": 1, "method": "idle", "params": {"timeout": 1500}}`); m["error"] != nil || d.waited != 1500*time.Millisecond {
|
||||
t.Errorf("idle: %v, waited %v", m, d.waited)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNames(t *testing.T) {
|
||||
if len(roleNames) != int(platform.RoleComplementary)+1 {
|
||||
t.Errorf("%d role names for %d roles", len(roleNames), platform.RoleComplementary+1)
|
||||
}
|
||||
if platform.AccessStates(1)<<(len(stateNames)-1) != platform.AccessHorizontal {
|
||||
t.Errorf("%d state names", len(stateNames))
|
||||
}
|
||||
if platform.AccessActions(1)<<(len(actionNames)-1) != platform.ActionExpand {
|
||||
t.Errorf("%d action names", len(actionNames))
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, n := range roleNames {
|
||||
if seen[n] {
|
||||
t.Errorf("role name %q twice", n)
|
||||
}
|
||||
seen[n] = true
|
||||
}
|
||||
if len(actionKinds) != int(platform.AccessInsertText)+1 {
|
||||
t.Errorf("%d actions for %d", len(actionKinds), platform.AccessInsertText+1)
|
||||
}
|
||||
}
|
||||
|
||||
// socketPath returns a path for a socket, short enough for macOS's limit
|
||||
// of 104 bytes.
|
||||
func socketPath(t *testing.T) string {
|
||||
dir, err := os.MkdirTemp("", "mygo-automation")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(dir) })
|
||||
return filepath.Join(dir, "s")
|
||||
}
|
||||
|
||||
func TestServe(t *testing.T) {
|
||||
path := socketPath(t)
|
||||
l, err := listen(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer l.Close()
|
||||
if runtime.GOOS != "windows" {
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil || fi.Mode().Perm() != 0o600 {
|
||||
t.Errorf("socket's mode %v, %v", fi.Mode(), err)
|
||||
}
|
||||
}
|
||||
tree, keys := testTree()
|
||||
go serve(l, &fakeDriver{access: tree, keys: keys})
|
||||
|
||||
c, err := net.Dial("unix", path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer c.Close()
|
||||
// Requests answered in order, each on a line of its own.
|
||||
if _, err := c.Write([]byte("{\"id\": 1, \"method\": \"tree\"}\n\n{\"id\": 2, \"method\": \"nope\"}\n")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r := bufio.NewReader(c)
|
||||
for i, want := range []string{`"id":1,"result":{"window":1,`, `"id":2,"error":{"code":"unknown_method"`} {
|
||||
line, err := r.ReadString('\n')
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(line, want) {
|
||||
t.Errorf("response %d: %s", i+1, line)
|
||||
}
|
||||
}
|
||||
|
||||
// Another app's socket is left alone, as is a file that is no socket.
|
||||
if l2, err := listen(path); err == nil {
|
||||
l2.Close()
|
||||
t.Error("listened on a socket another app listens on")
|
||||
}
|
||||
file := filepath.Join(filepath.Dir(path), "f")
|
||||
os.WriteFile(file, nil, 0o600)
|
||||
if l2, err := listen(file); err == nil {
|
||||
l2.Close()
|
||||
t.Error("listened in place of a file")
|
||||
}
|
||||
}
|
||||
|
||||
// TestStaleSocket listens where an app that ended left its socket.
|
||||
func TestStaleSocket(t *testing.T) {
|
||||
path := socketPath(t)
|
||||
l, err := listen(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l.(*net.UnixListener).SetUnlinkOnClose(false)
|
||||
l.Close()
|
||||
if _, err := os.Lstat(path); err != nil {
|
||||
t.Fatal("no socket left: ", err)
|
||||
}
|
||||
l, err = listen(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
l.Close()
|
||||
if _, err := os.Lstat(path); !os.IsNotExist(err) {
|
||||
t.Errorf("the socket stays once closed: %v", err)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user