From 58b56249efc8fd22b997356b3b47ee048ca98fd4 Mon Sep 17 00:00:00 2001 From: Prabhash Date: Mon, 19 Oct 2026 18:24:17 +0530 Subject: [PATCH 1/8] feat: port session-based REST API and JSON step protocol --- pkg/cli/cli.go | 1 + pkg/cli/server.go | 134 +++++++ pkg/cli/server_test.go | 296 ++++++++++++++ pkg/flow/json.go | 354 +++++++++++++++++ pkg/flow/json_test.go | 447 ++++++++++++++++++++++ pkg/server/server.go | 355 +++++++++++++++++ pkg/server/server_test.go | 787 ++++++++++++++++++++++++++++++++++++++ 7 files changed, 2374 insertions(+) create mode 100644 pkg/cli/server.go create mode 100644 pkg/cli/server_test.go create mode 100644 pkg/flow/json.go create mode 100644 pkg/flow/json_test.go create mode 100644 pkg/server/server.go create mode 100644 pkg/server/server_test.go diff --git a/pkg/cli/cli.go b/pkg/cli/cli.go index f9e30154..993703e0 100644 --- a/pkg/cli/cli.go +++ b/pkg/cli/cli.go @@ -198,6 +198,7 @@ Examples: devicesCommand, doctorCommand, screenshotCommand, + serverCommand, }, } diff --git a/pkg/cli/server.go b/pkg/cli/server.go new file mode 100644 index 00000000..b8456d7d --- /dev/null +++ b/pkg/cli/server.go @@ -0,0 +1,134 @@ +package cli + +import ( + "context" + "fmt" + "net/http" + "os" + "os/signal" + "strings" + "syscall" + + "github.com/devicelab-dev/maestro-runner/pkg/core" + "github.com/devicelab-dev/maestro-runner/pkg/logger" + "github.com/devicelab-dev/maestro-runner/pkg/server" + "github.com/urfave/cli/v2" +) + +var serverCommand = &cli.Command{ + Name: "server", + Usage: "Start the REST API server for remote test execution", + Description: `Start an HTTP server that exposes session-based endpoints for +executing Maestro steps via JSON instead of YAML flow files. + +Examples: + maestro-runner server + maestro-runner server --port 9999 + maestro-runner --platform android server`, + Flags: []cli.Flag{ + &cli.IntFlag{ + Name: "port", + Usage: "Port to listen on", + Value: 9999, + EnvVars: []string{"MAESTRO_SERVER_PORT"}, + }, + }, + Action: runServer, +} + +func runServer(c *cli.Context) error { + // Helper to get flag value from current or parent context + getString := func(name string) string { + if c.IsSet(name) { + return c.String(name) + } + if c.Lineage()[1] != nil { + return c.Lineage()[1].String(name) + } + return c.String(name) + } + getBool := func(name string) bool { + if c.IsSet(name) { + return c.Bool(name) + } + if c.Lineage()[1] != nil { + return c.Lineage()[1].Bool(name) + } + return c.Bool(name) + } + + port := c.Int("port") + verbose := getBool("verbose") + _ = verbose + + // Initialize logging + if err := logger.Init("maestro-server.log"); err != nil { + fmt.Printf("Warning: Failed to initialize logger: %v\n", err) + } + defer logger.Close() + + // Create server with driver factory + srv := server.New(func(req server.SessionRequest) (core.Driver, func(), error) { + platform := strings.ToLower(req.PlatformName) + + cfg := &RunConfig{ + Platform: platform, + Driver: req.Driver, + AppID: req.AppID, + } + if req.DeviceID != "" { + cfg.Devices = []string{req.DeviceID} + } + + // Inherit global flags + cfg.AppFile = getString("app-file") + cfg.AppiumURL = getString("appium-url") + cfg.CapsFile = getString("caps") + cfg.TeamID = getString("team-id") + + switch platform { + case "android": + return CreateAndroidDriver(cfg) + case "ios": + return CreateIOSDriver(cfg) + default: + return nil, nil, fmt.Errorf("unsupported platform: %s", req.PlatformName) + } + }) + + // Create HTTP server + addr := fmt.Sprintf(":%d", port) + httpServer := &http.Server{ + Addr: addr, + Handler: srv.Handler(), + } + + // Graceful shutdown on SIGINT/SIGTERM + ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM) + defer stop() + + go func() { + <-ctx.Done() + fmt.Println("\nShutting down server...") + srv.ShutdownAll() + if err := httpServer.Shutdown(context.Background()); err != nil { + logger.Error("Server shutdown error: %v", err) + } + }() + + fmt.Printf("maestro-runner server listening on %s\n", addr) + fmt.Printf(" POST /session - Create a new session\n") + fmt.Printf(" POST /session/{id}/execute - Execute a step\n") + fmt.Printf(" GET /session/{id}/screenshot - Take screenshot\n") + fmt.Printf(" GET /session/{id}/source - Get view hierarchy\n") + fmt.Printf(" GET /session/{id}/device-info - Get device info\n") + fmt.Printf(" DELETE /session/{id} - Delete session\n") + fmt.Printf(" GET /status - Server status\n") + fmt.Println() + + if err := httpServer.ListenAndServe(); err != http.ErrServerClosed { + return fmt.Errorf("server error: %w", err) + } + + return nil +} diff --git a/pkg/cli/server_test.go b/pkg/cli/server_test.go new file mode 100644 index 00000000..51fdc673 --- /dev/null +++ b/pkg/cli/server_test.go @@ -0,0 +1,296 @@ +package cli + +import ( + "bytes" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "os" + "os/signal" + "strings" + "sync" + "syscall" + "testing" + "time" + + "github.com/urfave/cli/v2" +) + +// swallowSignals registers a channel for SIGINT and SIGTERM for the duration +// of the test. +// +// The server command installs its own signal.NotifyContext handler, but it +// unregisters that handler with a deferred stop() when the command returns. If +// a test then signals the process while no handler is registered, the signal +// takes its *default* disposition and kills the whole test binary — turning an +// ordinary test failure into an undiagnosed dead run with no output. +// +// Holding our own registration for the test's lifetime means the default +// disposition is never reached, so a late or duplicate signal is simply +// discarded instead of aborting the run. +func swallowSignals(t *testing.T) { + t.Helper() + sig := make(chan os.Signal, 4) + signal.Notify(sig, os.Interrupt, syscall.SIGTERM) + t.Cleanup(func() { signal.Stop(sig) }) +} + +// interruptServer sends SIGINT to the test process, but only while the server +// command is still running. If the command has already returned, its signal +// handler is gone and signalling would be pointless at best. +func interruptServer(t *testing.T, done <-chan error) { + t.Helper() + select { + case <-done: + return // already exited; no handler left to notify + default: + } + if proc, err := os.FindProcess(os.Getpid()); err == nil { + _ = proc.Signal(os.Interrupt) + } +} + +// safeBuffer is a bytes.Buffer that tolerates concurrent writes, which is what +// a server started on a background goroutine produces. +type safeBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *safeBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *safeBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// waitReady polls addr until it answers HTTP, failing the test if the server +// exits first or never comes up. +func waitReady(t *testing.T, addr string, done <-chan error) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for { + select { + case err := <-done: + t.Fatalf("server exited before becoming ready: %v", err) + default: + } + if resp, err := http.Get(addr); err == nil { + _ = resp.Body.Close() + return + } + if time.Now().After(deadline) { + t.Fatalf("server did not become ready at %s", addr) + } + time.Sleep(20 * time.Millisecond) + } +} + +// freePort reserves an ephemeral port and releases it so the server can bind. +// There is an unavoidable window before the server starts listening, which is +// why the readiness check below polls rather than assuming the port is open. +func freePort(t *testing.T) int { + t.Helper() + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("reserve port: %v", err) + } + port := l.Addr().(*net.TCPAddr).Port + if err := l.Close(); err != nil { + t.Fatalf("release port: %v", err) + } + return port +} + +// expectedEndpoints is the banner contract from the ticket: every route the +// server exposes is announced at startup so an operator can see them without +// reading the source. +var expectedEndpoints = []string{ + "POST /session", + "POST /session/{id}/execute", + "GET /session/{id}/screenshot", + "GET /session/{id}/source", + "GET /session/{id}/device-info", + "DELETE /session/{id}", + "GET /status", +} + +// startTestServer runs the real server command on args/env, waits for it to +// answer, and registers cleanup that interrupts it so the test never leaves a +// listener behind. +func startTestServer(t *testing.T, port int, args ...string) string { + t.Helper() + swallowSignals(t) + + // Capture the banner the command prints at startup. + out := &safeBuffer{} + oldStdout := os.Stdout + r, w, err := os.Pipe() + if err != nil { + t.Fatalf("pipe: %v", err) + } + os.Stdout = w + drained := make(chan struct{}) + go func() { + defer close(drained) + _, _ = io.Copy(out, r) + }() + + app := &cli.App{ + Name: "test-app", + Flags: GlobalFlags, + Commands: []*cli.Command{serverCommand}, + } + + runArgs := append([]string{"test-app"}, args...) + done := make(chan error, 1) + go func() { done <- app.Run(runArgs) }() + + stop := func() { + // Interrupt, then let the command finish before tearing down the pipe, + // otherwise its shutdown message can land on the restored stdout. + interruptServer(t, done) + select { + case <-done: + case <-time.After(5 * time.Second): + } + _ = w.Close() + <-drained + os.Stdout = oldStdout + _ = r.Close() + } + t.Cleanup(stop) + + // Wait for the listener to come up before deciding the command failed. + waitReady(t, fmt.Sprintf("http://127.0.0.1:%d/status", port), done) + + // The banner is printed before ListenAndServe blocks, but it reaches us + // through an io.Copy goroutine that has not necessarily drained yet. Wait + // for the last banner line to appear rather than assuming it has landed. + deadline := time.Now().Add(5 * time.Second) + for !strings.Contains(out.String(), "DELETE /session/{id}") { + if time.Now().After(deadline) { + t.Fatalf("startup banner incomplete after %s\nbanner so far:\n%s", deadline, out.String()) + } + time.Sleep(10 * time.Millisecond) + } + return out.String() +} + +// TestServerCommand_StartsAndPrintsEndpoints covers the acceptance criterion +// that `maestro-runner server` comes up and announces its endpoint list. +func TestServerCommand_StartsAndPrintsEndpoints(t *testing.T) { + port := freePort(t) + banner := startTestServer(t, port, "server", "--port", fmt.Sprint(port)) + + for _, endpoint := range expectedEndpoints { + if !strings.Contains(banner, endpoint) { + t.Errorf("startup banner does not advertise %q\nbanner:\n%s", endpoint, banner) + } + } +} + +// TestServerCommand_ServesStatus asserts the server answers the documented +// status contract: HTTP 200 with {"status":"ok"} and no sessions yet. +func TestServerCommand_ServesStatus(t *testing.T) { + port := freePort(t) + startTestServer(t, port, "server", "--port", fmt.Sprint(port)) + + resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/status", port)) + if err != nil { + t.Fatalf("GET /status: %v", err) + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + t.Fatalf("GET /status = %d, want 200", resp.StatusCode) + } + if ct := resp.Header.Get("Content-Type"); ct != "application/json" { + t.Errorf("Content-Type = %q, want application/json", ct) + } + + var body struct { + Status string `json:"status"` + Sessions int `json:"sessions"` + } + if err := json.NewDecoder(resp.Body).Decode(&body); err != nil { + t.Fatalf("decode status: %v", err) + } + if body.Status != "ok" { + t.Errorf("status = %q, want ok", body.Status) + } + if body.Sessions != 0 { + t.Errorf("sessions = %d, want 0", body.Sessions) + } +} + +// TestServerCommand_PortFromEnv covers MAESTRO_SERVER_PORT mapping to the +// default --port, which is how containerised clients pick the port without +// touching the command line. +func TestServerCommand_PortFromEnv(t *testing.T) { + port := freePort(t) + t.Setenv("MAESTRO_SERVER_PORT", fmt.Sprint(port)) + + startTestServer(t, port, "server") + + resp, err := http.Get(fmt.Sprintf("http://127.0.0.1:%d/status", port)) + if err != nil { + t.Fatalf("GET /status on MAESTRO_SERVER_PORT=%d: %v", port, err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Errorf("GET /status = %d, want 200", resp.StatusCode) + } +} + +// TestServerCommand_ShutdownOnSignal covers the SIGINT/SIGTERM contract from +// the CLI side: interrupting the process tears the listener down and the +// command exits cleanly rather than reporting an error. +func TestServerCommand_ShutdownOnSignal(t *testing.T) { + port := freePort(t) + swallowSignals(t) + + app := &cli.App{ + Name: "test-app", + Flags: GlobalFlags, + Commands: []*cli.Command{serverCommand}, + } + + oldStdout := os.Stdout + devNull, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0) + if err != nil { + t.Fatalf("open devnull: %v", err) + } + os.Stdout = devNull + defer func() { os.Stdout = oldStdout; _ = devNull.Close() }() + + done := make(chan error, 1) + go func() { done <- app.Run([]string{"test-app", "server", "--port", fmt.Sprint(port)}) }() + + waitReady(t, fmt.Sprintf("http://127.0.0.1:%d/status", port), done) + + // SIGTERM must reach the running command, so signal before it can exit. + proc, err := os.FindProcess(os.Getpid()) + if err != nil { + t.Fatalf("find process: %v", err) + } + if err := proc.Signal(syscall.SIGTERM); err != nil { + t.Fatalf("signal: %v", err) + } + + select { + case err := <-done: + if err != nil { + t.Errorf("server exited with error after SIGTERM: %v", err) + } + case <-time.After(10 * time.Second): + t.Fatal("server did not exit after SIGTERM") + } +} diff --git a/pkg/flow/json.go b/pkg/flow/json.go new file mode 100644 index 00000000..db1336da --- /dev/null +++ b/pkg/flow/json.go @@ -0,0 +1,354 @@ +package flow + +import ( + "encoding/json" + "fmt" +) + +// UnmarshalStep deserializes a JSON step into the correct concrete Step type. +// It reads the "type" discriminator field first, then unmarshals into the +// appropriate struct — mirroring decodeStep in parser.go for YAML. +func UnmarshalStep(data []byte) (Step, error) { + var envelope struct { + Type StepType `json:"type"` + } + if err := json.Unmarshal(data, &envelope); err != nil { + return nil, fmt.Errorf("unmarshal step type: %w", err) + } + if envelope.Type == "" { + return nil, fmt.Errorf("missing \"type\" field in step JSON") + } + + return unmarshalStepByType(envelope.Type, data) +} + +//nolint:gocyclo +func unmarshalStepByType(stepType StepType, data []byte) (Step, error) { + switch stepType { + case StepTapOn: + var s TapOnStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepDoubleTapOn: + var s DoubleTapOnStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepLongPressOn: + var s LongPressOnStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepTapOnPoint: + var s TapOnPointStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepSwipe: + var s SwipeStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepScroll: + var s ScrollStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepScrollUntilVisible: + var s ScrollUntilVisibleStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepBack: + var s BackStep + s.StepType = stepType + return &s, nil + + case StepHideKeyboard: + var s HideKeyboardStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepAcceptAlert: + var s AcceptAlertStep + s.StepType = stepType + return &s, nil + + case StepIsKeyboardVisible: + var s IsKeyboardVisibleStep + s.StepType = stepType + return &s, nil + + case StepDismissAlert: + var s DismissAlertStep + s.StepType = stepType + return &s, nil + + case StepInputText: + var s InputTextStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepInputRandom: + var s InputRandomStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepEraseText: + var s EraseTextStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepCopyTextFrom: + var s CopyTextFromStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepPasteText: + var s PasteTextStep + s.StepType = stepType + return &s, nil + + case StepSetClipboard: + var s SetClipboardStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepAssertVisible: + var s AssertVisibleStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepAssertNotVisible: + var s AssertNotVisibleStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepAssertTrue: + var s AssertTrueStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepAssertCondition: + var s AssertConditionStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepLaunchApp: + var s LaunchAppStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepStopApp: + var s StopAppStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepKillApp: + var s KillAppStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepClearState: + var s ClearStateStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepClearKeychain: + var s ClearKeychainStep + s.StepType = stepType + return &s, nil + + case StepSetPermissions: + var s SetPermissionsStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepSetLocation: + var s SetLocationStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepSetOrientation: + var s SetOrientationStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepOpenLink: + var s OpenLinkStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepOpenBrowser: + var s OpenBrowserStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepPressKey: + var s PressKeyStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepSleep: + var s SleepStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepWaitForAnimationToEnd: + var s WaitForAnimationToEndStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + case StepTakeScreenshot: + var s TakeScreenshotStep + if err := json.Unmarshal(data, &s); err != nil { + return nil, err + } + s.StepType = stepType + return &s, nil + + default: + return nil, fmt.Errorf("unsupported step type: %s", stepType) + } +} + +// MarshalJSON for Selector: if only Text is set, marshal as a plain string. +// Otherwise marshal as object. +func (s Selector) MarshalJSON() ([]byte, error) { + if s.isTextOnly() { + return json.Marshal(s.Text) + } + // Use alias to avoid infinite recursion + type selectorAlias Selector + return json.Marshal(selectorAlias(s)) +} + +// UnmarshalJSON for Selector: accept plain string or object. +func (s *Selector) UnmarshalJSON(data []byte) error { + // Try string first + var text string + if err := json.Unmarshal(data, &text); err == nil { + s.Text = text + return nil + } + // Fall back to object + type selectorAlias Selector + var alias selectorAlias + if err := json.Unmarshal(data, &alias); err != nil { + return err + } + *s = Selector(alias) + return nil +} + +// isTextOnly returns true if only the Text field is set (for compact JSON serialization). +func (s *Selector) isTextOnly() bool { + return s.Text != "" && + s.ID == "" && + s.CSS == "" && + s.Width == 0 && + s.Height == 0 && + s.Tolerance == 0 && + s.Enabled == nil && + s.Selected == nil && + s.Checked == nil && + s.Focused == nil && + s.Index == "" && + s.Traits == "" && + s.ChildOf == nil && + s.Below == nil && + s.Above == nil && + s.LeftOf == nil && + s.RightOf == nil && + s.ContainsChild == nil && + len(s.ContainsDescendants) == 0 && + s.InsideOf == nil +} diff --git a/pkg/flow/json_test.go b/pkg/flow/json_test.go new file mode 100644 index 00000000..51f26a2a --- /dev/null +++ b/pkg/flow/json_test.go @@ -0,0 +1,447 @@ +package flow + +import ( + "encoding/json" + "reflect" + "strings" + "testing" +) + +func TestUnmarshalStep_TapOn(t *testing.T) { + input := `{"type":"tapOn","selector":"Login","longPress":true,"timeout":5000}` + step, err := UnmarshalStep([]byte(input)) + if err != nil { + t.Fatalf("UnmarshalStep error: %v", err) + } + if step.Type() != StepTapOn { + t.Fatalf("expected type %s, got %s", StepTapOn, step.Type()) + } + tap := step.(*TapOnStep) + if tap.Selector.Text != "Login" { + t.Errorf("expected text 'Login', got %q", tap.Selector.Text) + } + if !tap.LongPress { + t.Error("expected longPress=true") + } + if tap.TimeoutMs != 5000 { + t.Errorf("expected timeout 5000, got %d", tap.TimeoutMs) + } +} + +func TestUnmarshalStep_TapOnByID(t *testing.T) { + input := `{"type":"tapOn","selector":{"id":"btn_login"},"longPress":true}` + step, err := UnmarshalStep([]byte(input)) + if err != nil { + t.Fatalf("UnmarshalStep error: %v", err) + } + tap := step.(*TapOnStep) + if tap.Selector.ID != "btn_login" { + t.Errorf("expected id 'btn_login', got %q", tap.Selector.ID) + } + if !tap.LongPress { + t.Error("expected longPress=true") + } +} + +func TestUnmarshalStep_InputText(t *testing.T) { + input := `{"type":"inputText","text":"user@example.com"}` + step, err := UnmarshalStep([]byte(input)) + if err != nil { + t.Fatalf("UnmarshalStep error: %v", err) + } + if step.Type() != StepInputText { + t.Fatalf("expected type %s, got %s", StepInputText, step.Type()) + } + is := step.(*InputTextStep) + if is.Text != "user@example.com" { + t.Errorf("expected text 'user@example.com', got %q", is.Text) + } +} + +func TestUnmarshalStep_AssertVisible(t *testing.T) { + input := `{"type":"assertVisible","selector":"Dashboard","timeout":10000}` + step, err := UnmarshalStep([]byte(input)) + if err != nil { + t.Fatalf("UnmarshalStep error: %v", err) + } + if step.Type() != StepAssertVisible { + t.Fatalf("expected type %s, got %s", StepAssertVisible, step.Type()) + } + av := step.(*AssertVisibleStep) + if av.Selector.Text != "Dashboard" { + t.Errorf("expected text 'Dashboard', got %q", av.Selector.Text) + } + if av.TimeoutMs != 10000 { + t.Errorf("expected timeout 10000, got %d", av.TimeoutMs) + } +} + +func TestUnmarshalStep_LaunchApp(t *testing.T) { + input := `{"type":"launchApp","appId":"com.example.app","clearState":true}` + step, err := UnmarshalStep([]byte(input)) + if err != nil { + t.Fatalf("UnmarshalStep error: %v", err) + } + la := step.(*LaunchAppStep) + if la.AppID != "com.example.app" { + t.Errorf("expected appId 'com.example.app', got %q", la.AppID) + } + if !la.ClearState { + t.Error("expected clearState=true") + } +} + +func TestUnmarshalStep_Swipe(t *testing.T) { + input := `{"type":"swipe","direction":"UP","duration":400}` + step, err := UnmarshalStep([]byte(input)) + if err != nil { + t.Fatalf("UnmarshalStep error: %v", err) + } + sw := step.(*SwipeStep) + if sw.Direction != "UP" { + t.Errorf("expected direction UP, got %q", sw.Direction) + } + if sw.Duration != 400 { + t.Errorf("expected duration 400, got %d", sw.Duration) + } +} + +func TestUnmarshalStep_Back(t *testing.T) { + input := `{"type":"back"}` + step, err := UnmarshalStep([]byte(input)) + if err != nil { + t.Fatalf("UnmarshalStep error: %v", err) + } + if step.Type() != StepBack { + t.Fatalf("expected type %s, got %s", StepBack, step.Type()) + } +} + +func TestUnmarshalStep_PressKey(t *testing.T) { + input := `{"type":"pressKey","key":"ENTER"}` + step, err := UnmarshalStep([]byte(input)) + if err != nil { + t.Fatalf("UnmarshalStep error: %v", err) + } + pk := step.(*PressKeyStep) + if pk.Key != "ENTER" { + t.Errorf("expected key 'ENTER', got %q", pk.Key) + } +} + +func TestUnmarshalStep_EraseText(t *testing.T) { + input := `{"type":"eraseText","charactersToErase":5}` + step, err := UnmarshalStep([]byte(input)) + if err != nil { + t.Fatalf("UnmarshalStep error: %v", err) + } + et := step.(*EraseTextStep) + if et.Characters != 5 { + t.Errorf("expected characters 5, got %d", et.Characters) + } +} + +func TestUnmarshalStep_MissingType(t *testing.T) { + input := `{"text":"Login"}` + _, err := UnmarshalStep([]byte(input)) + if err == nil { + t.Fatal("expected error for missing type") + } +} + +func TestUnmarshalStep_Optional(t *testing.T) { + input := `{"type":"tapOn","selector":"OK","optional":true}` + step, err := UnmarshalStep([]byte(input)) + if err != nil { + t.Fatalf("UnmarshalStep error: %v", err) + } + if !step.IsOptional() { + t.Error("expected optional=true") + } +} + +func TestUnmarshalStep_StopApp(t *testing.T) { + input := `{"type":"stopApp","appId":"com.example.app"}` + step, err := UnmarshalStep([]byte(input)) + if err != nil { + t.Fatalf("UnmarshalStep error: %v", err) + } + sa := step.(*StopAppStep) + if sa.AppID != "com.example.app" { + t.Errorf("expected appId 'com.example.app', got %q", sa.AppID) + } +} + +func TestUnmarshalStep_Scroll(t *testing.T) { + input := `{"type":"scroll"}` + step, err := UnmarshalStep([]byte(input)) + if err != nil { + t.Fatalf("UnmarshalStep error: %v", err) + } + if step.Type() != StepScroll { + t.Fatalf("expected type %s, got %s", StepScroll, step.Type()) + } +} + +// TestUnmarshalStep_SupportedStepTypes pins the protocol contract: every step +// type the JSON protocol advertises must decode to its documented concrete +// flow.Step implementation. Adding a step type here without teaching +// unmarshalStepByType about it will fail, which is the point — the server must +// not silently accept a step it cannot execute. +func TestUnmarshalStep_SupportedStepTypes(t *testing.T) { + tests := []struct { + stepType StepType + want Step + }{ + {StepTapOn, (*TapOnStep)(nil)}, + {StepDoubleTapOn, (*DoubleTapOnStep)(nil)}, + {StepLongPressOn, (*LongPressOnStep)(nil)}, + {StepTapOnPoint, (*TapOnPointStep)(nil)}, + {StepSwipe, (*SwipeStep)(nil)}, + {StepScroll, (*ScrollStep)(nil)}, + {StepScrollUntilVisible, (*ScrollUntilVisibleStep)(nil)}, + {StepBack, (*BackStep)(nil)}, + {StepHideKeyboard, (*HideKeyboardStep)(nil)}, + {StepAcceptAlert, (*AcceptAlertStep)(nil)}, + {StepIsKeyboardVisible, (*IsKeyboardVisibleStep)(nil)}, + {StepDismissAlert, (*DismissAlertStep)(nil)}, + {StepInputText, (*InputTextStep)(nil)}, + {StepInputRandom, (*InputRandomStep)(nil)}, + {StepEraseText, (*EraseTextStep)(nil)}, + {StepCopyTextFrom, (*CopyTextFromStep)(nil)}, + {StepPasteText, (*PasteTextStep)(nil)}, + {StepSetClipboard, (*SetClipboardStep)(nil)}, + {StepAssertVisible, (*AssertVisibleStep)(nil)}, + {StepAssertNotVisible, (*AssertNotVisibleStep)(nil)}, + {StepAssertTrue, (*AssertTrueStep)(nil)}, + {StepAssertCondition, (*AssertConditionStep)(nil)}, + {StepLaunchApp, (*LaunchAppStep)(nil)}, + {StepStopApp, (*StopAppStep)(nil)}, + {StepKillApp, (*KillAppStep)(nil)}, + {StepClearState, (*ClearStateStep)(nil)}, + {StepClearKeychain, (*ClearKeychainStep)(nil)}, + {StepSetPermissions, (*SetPermissionsStep)(nil)}, + {StepSetLocation, (*SetLocationStep)(nil)}, + {StepSetOrientation, (*SetOrientationStep)(nil)}, + {StepOpenLink, (*OpenLinkStep)(nil)}, + {StepOpenBrowser, (*OpenBrowserStep)(nil)}, + {StepPressKey, (*PressKeyStep)(nil)}, + {StepSleep, (*SleepStep)(nil)}, + {StepWaitForAnimationToEnd, (*WaitForAnimationToEndStep)(nil)}, + {StepTakeScreenshot, (*TakeScreenshotStep)(nil)}, + } + + for _, tt := range tests { + t.Run(string(tt.stepType), func(t *testing.T) { + body := `{"type":"` + string(tt.stepType) + `"}` + step, err := UnmarshalStep([]byte(body)) + if err != nil { + t.Fatalf("UnmarshalStep(%s): %v", body, err) + } + if step.Type() != tt.stepType { + t.Errorf("Type() = %q, want %q", step.Type(), tt.stepType) + } + if got, want := reflect.TypeOf(step), reflect.TypeOf(tt.want); got != want { + t.Errorf("concrete type = %v, want %v", got, want) + } + }) + } +} + +// TestUnmarshalStep_UnsupportedStepTypeIsAnError asserts that step types the +// JSON protocol does not implement produce a clear, non-panicking error naming +// the offending type. Clients rely on this to distinguish "I sent a step the +// server cannot run" from a transport failure. +func TestUnmarshalStep_UnsupportedStepTypeIsAnError(t *testing.T) { + unsupported := []StepType{ + StepOpenNotifications, + StepInputRandomPersonName, + StepInputRandomText, + StepWaitUntil, + StepSetDarkMode, + StepAssertDarkMode, + StepEvalBrowserScript, + StepOpenTab, + StepAssertScreenshot, + StepStartRecording, + StepAddMedia, + StepDefineVariables, + } + + for _, stepType := range unsupported { + t.Run(string(stepType), func(t *testing.T) { + body := `{"type":"` + string(stepType) + `"}` + step, err := UnmarshalStep([]byte(body)) + if err == nil { + t.Fatalf("expected an error for unsupported step type %q, got step %v", stepType, step) + } + if !strings.Contains(err.Error(), string(stepType)) { + t.Errorf("error %q should name the unsupported step type %q", err, stepType) + } + }) + } +} + +// TestSelector_JSONRoundTrip covers the selector shapes clients actually send. +// A selector that survives marshal -> unmarshal unchanged is what lets the +// server hand the same selector to the driver that YAML would have produced. +func TestSelector_JSONRoundTrip(t *testing.T) { + textChild := Selector{Text: "Password"} + enabled := true + selected := false + nth := 2 + + tests := []struct { + name string + selector Selector + }{ + {"text only", Selector{Text: "Login"}}, + {"id only", Selector{ID: "btn_login"}}, + {"text plus id", Selector{Text: "Login", ID: "btn_login"}}, + {"boolean state filter", Selector{Text: "Notify", Enabled: &enabled}}, + {"explicit false boolean", Selector{Text: "Notify", Selected: &selected}}, + {"nested relative selector", Selector{Text: "Login", ChildOf: &textChild}}, + {"size matching", Selector{Text: "Logo", Width: 100, Height: 50, Tolerance: 5}}, + {"css selector", Selector{CSS: "#submit"}}, + {"index", Selector{Text: "Row", Index: "2"}}, + {"traits", Selector{Text: "Row", Traits: "button,heading"}}, + {"web fields", Selector{Placeholder: "Email", Role: "button", TextContains: "log", + Href: "/login", Alt: "Logo", Title: "Sign in", Name: "email", + TestID: "login-btn", TextRegex: "^Log.*$", Nth: nth}}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + data, err := json.Marshal(tt.selector) + if err != nil { + t.Fatalf("marshal: %v", err) + } + + var got Selector + if err := json.Unmarshal(data, &got); err != nil { + t.Fatalf("unmarshal %s: %v", data, err) + } + if !reflect.DeepEqual(got, tt.selector) { + t.Errorf("round-trip changed selector:\n got: %+v\nwant: %+v", got, tt.selector) + } + }) + } +} + +// TestSelector_UnmarshalJSON_DocumentedKeys feeds the camelCase keys a client +// would naturally send and asserts each one lands on the intended field. +func TestSelector_UnmarshalJSON_DocumentedKeys(t *testing.T) { + body := `{"text":"Login","id":"btn","enabled":true,"placeholder":"Email","role":"button",` + + `"textContains":"log","href":"/login","alt":"Logo","title":"Sign in",` + + `"name":"email","testId":"login-btn","textRegex":"^Log.*$","nth":2}` + var s Selector + if err := json.Unmarshal([]byte(body), &s); err != nil { + t.Fatalf("unmarshal: %v", err) + } + + checks := []struct { + field string + got interface{} + want interface{} + }{ + {"text", s.Text, "Login"}, + {"id", s.ID, "btn"}, + {"placeholder", s.Placeholder, "Email"}, + {"role", s.Role, "button"}, + {"textContains", s.TextContains, "log"}, + {"href", s.Href, "/login"}, + {"alt", s.Alt, "Logo"}, + {"title", s.Title, "Sign in"}, + {"name", s.Name, "email"}, + {"testId", s.TestID, "login-btn"}, + {"textRegex", s.TextRegex, "^Log.*$"}, + {"nth", s.Nth, 2}, + } + for _, c := range checks { + if c.got != c.want { + t.Errorf("selector %s = %v, want %v", c.field, c.got, c.want) + } + } + if s.Enabled == nil || !*s.Enabled { + t.Errorf("enabled = %v, want true", s.Enabled) + } +} + +// TestSelector_UnmarshalJSON_Invalid asserts that a selector which is neither a +// string nor an object is reported as an error, so the server can answer 400 +// instead of silently producing an empty selector that matches nothing. +// ("null" is excluded: Go treats JSON null as a no-op by design.) +func TestSelector_UnmarshalJSON_Invalid(t *testing.T) { + for _, body := range []string{`123`, `true`, `["Login"]`} { + t.Run(body, func(t *testing.T) { + var s Selector + if err := json.Unmarshal([]byte(body), &s); err == nil { + t.Fatalf("expected error unmarshalling selector %s, got %+v", body, s) + } + }) + } +} + +// --- Selector JSON --- + +func TestSelector_MarshalJSON_TextOnly(t *testing.T) { + s := Selector{Text: "Login"} + data, err := json.Marshal(s) + if err != nil { + t.Fatalf("marshal error: %v", err) + } + // Text-only selector should marshal as plain string + if string(data) != `"Login"` { + t.Errorf("expected \"Login\", got %s", string(data)) + } +} + +func TestSelector_MarshalJSON_WithID(t *testing.T) { + s := Selector{Text: "Login", ID: "btn"} + data, err := json.Marshal(s) + if err != nil { + t.Fatalf("marshal error: %v", err) + } + // Should be an object + var m map[string]interface{} + if err := json.Unmarshal(data, &m); err != nil { + t.Fatalf("expected JSON object, got: %s", string(data)) + } + if m["text"] != "Login" { + t.Errorf("expected text 'Login', got %v", m["text"]) + } + if m["id"] != "btn" { + t.Errorf("expected id 'btn', got %v", m["id"]) + } +} + +func TestSelector_UnmarshalJSON_String(t *testing.T) { + var s Selector + if err := json.Unmarshal([]byte(`"Login"`), &s); err != nil { + t.Fatalf("unmarshal error: %v", err) + } + if s.Text != "Login" { + t.Errorf("expected text 'Login', got %q", s.Text) + } +} + +// --- JSON round-trip: step type is preserved --- + +func TestStepType_JSONRoundTrip(t *testing.T) { + input := `{"type":"tapOn","selector":"Login"}` + step, err := UnmarshalStep([]byte(input)) + if err != nil { + t.Fatalf("unmarshal: %v", err) + } + data, err := json.Marshal(step) + if err != nil { + t.Fatalf("marshal: %v", err) + } + var m map[string]interface{} + if err := json.Unmarshal(data, &m); err != nil { + t.Fatalf("re-unmarshal: %v", err) + } + if m["type"] != "tapOn" { + t.Errorf("expected type 'tapOn' in JSON, got %v", m["type"]) + } +} diff --git a/pkg/server/server.go b/pkg/server/server.go new file mode 100644 index 00000000..0d4d6db4 --- /dev/null +++ b/pkg/server/server.go @@ -0,0 +1,355 @@ +// Package server provides a REST API server that bridges HTTP calls to core.Driver. +package server + +import ( + "crypto/rand" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "os" + "strings" + "sync" + "time" + + "github.com/devicelab-dev/maestro-runner/pkg/core" + "github.com/devicelab-dev/maestro-runner/pkg/flow" + "github.com/devicelab-dev/maestro-runner/pkg/logger" +) + +// SessionState holds a driver session. +type SessionState struct { + Driver core.Driver + Cleanup func() +} + +// Server is the REST API server. +type Server struct { + mu sync.RWMutex + sessions map[string]*SessionState + + // CreateDriver is called when POST /session is invoked. + // It receives the session request and must return a driver + cleanup func. + CreateDriver func(req SessionRequest) (core.Driver, func(), error) +} + +// SessionRequest is the JSON body for POST /session. +type SessionRequest struct { + PlatformName string `json:"platformName"` + DeviceID string `json:"deviceId,omitempty"` + AppID string `json:"appId,omitempty"` + Driver string `json:"driver,omitempty"` +} + +// SessionResponse is the JSON response for POST /session. +type SessionResponse struct { + SessionID string `json:"sessionId"` +} + +// ErrorResponse is a JSON error response. +type ErrorResponse struct { + Error string `json:"error"` +} + +// New creates a new Server. +func New(createDriver func(req SessionRequest) (core.Driver, func(), error)) *Server { + return &Server{ + sessions: make(map[string]*SessionState), + CreateDriver: createDriver, + } +} + +// Handler returns an http.Handler with all routes registered. +func (s *Server) Handler() http.Handler { + mux := http.NewServeMux() + + mux.HandleFunc("GET /status", s.handleStatus) + mux.HandleFunc("POST /session", s.handleCreateSession) + mux.HandleFunc("POST /session/{id}/execute", s.handleExecute) + mux.HandleFunc("GET /session/{id}/screenshot", s.handleScreenshot) + mux.HandleFunc("GET /session/{id}/source", s.handleSource) + mux.HandleFunc("GET /session/{id}/device-info", s.handleDeviceInfo) + mux.HandleFunc("DELETE /session/{id}", s.handleDeleteSession) + + return mux +} + +// ShutdownAll cleans up all active sessions. +func (s *Server) ShutdownAll() { + s.mu.Lock() + defer s.mu.Unlock() + for id, sess := range s.sessions { + logger.Info("Cleaning up session %s", id) + if sess.Cleanup != nil { + sess.Cleanup() + } + delete(s.sessions, id) + } +} + +func (s *Server) handleStatus(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + s.mu.RLock() + count := len(s.sessions) + s.mu.RUnlock() + writeJSON(w, http.StatusOK, map[string]interface{}{ + "status": "ok", + "sessions": count, + }) +} + +func (s *Server) handleCreateSession(w http.ResponseWriter, r *http.Request) { + started := time.Now() + var req SessionRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + writeJSON(w, http.StatusBadRequest, ErrorResponse{Error: "invalid request body: " + err.Error()}) + serverTracef( + "server request worker=%s method=%s path=%s status=%d duration_ms=%d error=%q", + serverWorkerID(), r.Method, r.URL.Path, http.StatusBadRequest, time.Since(started).Milliseconds(), + err.Error(), + ) + return + } + + if req.PlatformName == "" { + writeJSON(w, http.StatusBadRequest, ErrorResponse{Error: "platformName is required"}) + serverTracef( + "server request worker=%s method=%s path=%s status=%d duration_ms=%d error=%q", + serverWorkerID(), r.Method, r.URL.Path, http.StatusBadRequest, time.Since(started).Milliseconds(), + "platformName is required", + ) + return + } + + driver, cleanup, err := s.CreateDriver(req) + if err != nil { + writeJSON(w, http.StatusInternalServerError, ErrorResponse{Error: "failed to create driver: " + err.Error()}) + serverTracef( + "server request worker=%s method=%s path=%s status=%d duration_ms=%d error=%q platform=%s deviceId=%s", + serverWorkerID(), r.Method, r.URL.Path, http.StatusInternalServerError, + time.Since(started).Milliseconds(), err.Error(), req.PlatformName, req.DeviceID, + ) + return + } + + sessionID := generateSessionID() + s.mu.Lock() + s.sessions[sessionID] = &SessionState{ + Driver: driver, + Cleanup: cleanup, + } + s.mu.Unlock() + + logger.Info("Created session %s for platform=%s", sessionID, req.PlatformName) + serverTracef( + "server request worker=%s method=%s path=%s status=%d duration_ms=%d session=%s platform=%s deviceId=%s", + serverWorkerID(), r.Method, r.URL.Path, http.StatusOK, time.Since(started).Milliseconds(), + sessionID, req.PlatformName, req.DeviceID, + ) + writeJSON(w, http.StatusOK, SessionResponse{SessionID: sessionID}) +} + +func (s *Server) handleExecute(w http.ResponseWriter, r *http.Request) { + started := time.Now() + sessionID := r.PathValue("id") + sess, ok := s.getSession(w, r) + if !ok { + serverTracef( + "server execute worker=%s session=%s status=%d duration_ms=%d error=%q", + serverWorkerID(), sessionID, http.StatusNotFound, time.Since(started).Milliseconds(), + "session not found", + ) + return + } + + body, err := io.ReadAll(r.Body) + if err != nil { + writeJSON(w, http.StatusBadRequest, ErrorResponse{Error: "failed to read body: " + err.Error()}) + serverTracef( + "server execute worker=%s session=%s status=%d duration_ms=%d error=%q", + serverWorkerID(), sessionID, http.StatusBadRequest, time.Since(started).Milliseconds(), + err.Error(), + ) + return + } + + step, err := flow.UnmarshalStep(body) + if err != nil { + writeJSON(w, http.StatusBadRequest, ErrorResponse{Error: "invalid step: " + err.Error()}) + serverTracef( + "server execute worker=%s session=%s status=%d duration_ms=%d error=%q raw_step=%s", + serverWorkerID(), sessionID, http.StatusBadRequest, time.Since(started).Milliseconds(), + err.Error(), trimForLog(string(body), 280), + ) + return + } + + serverTracef( + "server execute request worker=%s session=%s step=%q payload=%s", + serverWorkerID(), sessionID, stepName(step), trimForLog(string(body), 320), + ) + result := sess.Driver.Execute(step) + status := "passed" + if !result.Success { + status = "failed" + } + serverTracef( + "server execute response worker=%s session=%s step=%q status=%s duration_ms=%d message=%s", + serverWorkerID(), sessionID, stepName(step), status, time.Since(started).Milliseconds(), + trimForLog(result.Message, 220), + ) + writeJSON(w, http.StatusOK, result) +} + +func (s *Server) handleScreenshot(w http.ResponseWriter, r *http.Request) { + sess, ok := s.getSession(w, r) + if !ok { + return + } + + png, err := sess.Driver.Screenshot() + if err != nil { + writeJSON(w, http.StatusInternalServerError, ErrorResponse{Error: "screenshot failed: " + err.Error()}) + return + } + + w.Header().Set("Content-Type", "image/png") + w.WriteHeader(http.StatusOK) + if _, err := w.Write(png); err != nil { + log.Printf("failed to write screenshot: %v", err) + } +} + +func (s *Server) handleSource(w http.ResponseWriter, r *http.Request) { + sess, ok := s.getSession(w, r) + if !ok { + return + } + + hierarchy, err := sess.Driver.Hierarchy() + if err != nil { + writeJSON(w, http.StatusInternalServerError, ErrorResponse{Error: "hierarchy failed: " + err.Error()}) + return + } + + // Detect content type from the hierarchy bytes + contentType := "application/xml" + if len(hierarchy) > 0 && hierarchy[0] == '{' { + contentType = "application/json" + } + w.Header().Set("Content-Type", contentType) + w.WriteHeader(http.StatusOK) + if _, err := w.Write(hierarchy); err != nil { + log.Printf("failed to write hierarchy: %v", err) + } +} + +func (s *Server) handleDeviceInfo(w http.ResponseWriter, r *http.Request) { + sess, ok := s.getSession(w, r) + if !ok { + return + } + + info := sess.Driver.GetPlatformInfo() + writeJSON(w, http.StatusOK, info) +} + +func (s *Server) handleDeleteSession(w http.ResponseWriter, r *http.Request) { + started := time.Now() + id := r.PathValue("id") + + s.mu.Lock() + sess, exists := s.sessions[id] + if exists { + delete(s.sessions, id) + } + s.mu.Unlock() + + if !exists { + writeJSON(w, http.StatusNotFound, ErrorResponse{Error: fmt.Sprintf("session %s not found", id)}) + serverTracef( + "server request worker=%s method=%s path=%s status=%d duration_ms=%d session=%s error=%q", + serverWorkerID(), r.Method, r.URL.Path, http.StatusNotFound, time.Since(started).Milliseconds(), + id, "session not found", + ) + return + } + + if sess.Cleanup != nil { + sess.Cleanup() + } + logger.Info("Deleted session %s", id) + serverTracef( + "server request worker=%s method=%s path=%s status=%d duration_ms=%d session=%s", + serverWorkerID(), r.Method, r.URL.Path, http.StatusNoContent, time.Since(started).Milliseconds(), id, + ) + w.WriteHeader(http.StatusNoContent) +} + +// getSession retrieves a session by the {id} path parameter. Returns false if not found. +func (s *Server) getSession(w http.ResponseWriter, r *http.Request) (*SessionState, bool) { + id := r.PathValue("id") + + s.mu.RLock() + sess, exists := s.sessions[id] + s.mu.RUnlock() + + if !exists { + writeJSON(w, http.StatusNotFound, ErrorResponse{Error: fmt.Sprintf("session %s not found", id)}) + return nil, false + } + return sess, true +} + +func generateSessionID() string { + b := make([]byte, 16) + if _, err := rand.Read(b); err != nil { + // Fallback — should never happen + return fmt.Sprintf("session-%d", len(b)) + } + return hex.EncodeToString(b) +} + +func writeJSON(w http.ResponseWriter, status int, v interface{}) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + if err := json.NewEncoder(w).Encode(v); err != nil { + log.Printf("failed to encode JSON response: %v", err) + } +} + +// SanitizePlatform normalizes the platform name. +func SanitizePlatform(p string) string { + return strings.ToLower(strings.TrimSpace(p)) +} + +func serverWorkerID() string { + if worker := strings.TrimSpace(os.Getenv("PYTEST_XDIST_WORKER")); worker != "" { + return worker + } + if worker := strings.TrimSpace(os.Getenv("MAESTRO_WORKER_ID")); worker != "" { + return worker + } + return "master" +} + +func trimForLog(value string, maxLen int) string { + trimmed := strings.TrimSpace(value) + if len(trimmed) <= maxLen { + return trimmed + } + return trimmed[:maxLen] + "..." +} + +func stepName(step flow.Step) string { + if step == nil { + return "unknown" + } + return string(step.Type()) +} + +func serverTracef(format string, v ...interface{}) { + fmt.Printf("%s [TRACE] %s\n", time.Now().Format("15:04:05.000000"), fmt.Sprintf(format, v...)) +} diff --git a/pkg/server/server_test.go b/pkg/server/server_test.go new file mode 100644 index 00000000..acf2072c --- /dev/null +++ b/pkg/server/server_test.go @@ -0,0 +1,787 @@ +package server + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/devicelab-dev/maestro-runner/pkg/core" + "github.com/devicelab-dev/maestro-runner/pkg/driver/mock" + "github.com/devicelab-dev/maestro-runner/pkg/flow" +) + +// recordingDriver wraps a driver and captures the steps handed to Execute so +// tests can assert the server decoded the JSON body into the same concrete +// flow.Step implementation YAML would have produced. +type recordingDriver struct { + core.Driver + mu sync.Mutex + steps []flow.Step +} + +func (d *recordingDriver) Execute(step flow.Step) *core.CommandResult { + d.mu.Lock() + d.steps = append(d.steps, step) + d.mu.Unlock() + return core.SuccessResult("executed "+string(step.Type()), nil) +} + +func (d *recordingDriver) recorded() []flow.Step { + d.mu.Lock() + defer d.mu.Unlock() + return append([]flow.Step(nil), d.steps...) +} + +// hierarchyDriver overrides Hierarchy so a test can control whether the +// server sees XML or JSON and therefore which Content-Type it must emit. +type hierarchyDriver struct { + core.Driver + hierarchy []byte + err error +} + +func (d hierarchyDriver) Hierarchy() ([]byte, error) { return d.hierarchy, d.err } + +func newTestServer() (*Server, *mock.Driver) { + drv := mock.New(mock.Config{Platform: "android", DeviceID: "test-device"}) + srv := New(func(req SessionRequest) (core.Driver, func(), error) { + return drv, func() {}, nil + }) + return srv, drv +} + +// cleanupCounter counts how many session cleanups ran. +type cleanupCounter struct { + mu sync.Mutex + n int +} + +func (c *cleanupCounter) inc() { + c.mu.Lock() + defer c.mu.Unlock() + c.n++ +} + +func (c *cleanupCounter) count() int { + c.mu.Lock() + defer c.mu.Unlock() + return c.n +} + +// newServerWithDriver builds a server whose factory hands out drv and records +// how many times the returned cleanup ran. +func newServerWithDriver(drv core.Driver, cleaned *cleanupCounter) *Server { + return New(func(req SessionRequest) (core.Driver, func(), error) { + return drv, cleaned.inc, nil + }) +} + +func createSession(t *testing.T, handler http.Handler) string { + t.Helper() + body := `{"platformName":"android","deviceId":"test-device"}` + req := httptest.NewRequest("POST", "/session", bytes.NewBufferString(body)) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("create session: expected 200, got %d: %s", w.Code, w.Body.String()) + } + var resp SessionResponse + if err := json.NewDecoder(w.Body).Decode(&resp); err != nil { + t.Fatalf("decode session response: %v", err) + } + if resp.SessionID == "" { + t.Fatal("session id is empty") + } + return resp.SessionID +} + +// sessionRoutes are the {id}-scoped routes the server exposes. Every one of +// them must answer 404 for an unknown session so a client never mistakes a +// dead session for a device failure. +var sessionRoutes = []struct { + name string + method string + suffix string +}{ + {"execute", http.MethodPost, "/execute"}, + {"screenshot", http.MethodGet, "/screenshot"}, + {"source", http.MethodGet, "/source"}, + {"device-info", http.MethodGet, "/device-info"}, +} + +func TestSessionRoutes_SessionNotFound(t *testing.T) { + for _, route := range sessionRoutes { + t.Run(route.name, func(t *testing.T) { + srv, _ := newTestServer() + handler := srv.Handler() + + var body io.Reader + if route.method == http.MethodPost { + body = bytes.NewBufferString(`{"type":"back"}`) + } + req := httptest.NewRequest(route.method, "/session/nonexistent"+route.suffix, body) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + + if w.Code != http.StatusNotFound { + t.Fatalf("expected 404, got %d", w.Code) + } + var errResp ErrorResponse + if err := json.NewDecoder(w.Body).Decode(&errResp); err != nil { + t.Fatalf("decode error response: %v", err) + } + if !strings.Contains(errResp.Error, "nonexistent") { + t.Errorf("error %q should name the missing session", errResp.Error) + } + }) + } +} + +func TestStatus(t *testing.T) { + srv, _ := newTestServer() + handler := srv.Handler() + req := httptest.NewRequest("GET", "/status", nil) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d", w.Code) + } + var body map[string]interface{} + if err := json.NewDecoder(w.Body).Decode(&body); err != nil { + t.Fatalf("decode error: %v", err) + } + if body["status"] != "ok" { + t.Errorf("expected status ok, got %v", body["status"]) + } +} + +func TestCreateSession(t *testing.T) { + srv, _ := newTestServer() + handler := srv.Handler() + sid := createSession(t, handler) + req := httptest.NewRequest("GET", "/status", nil) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + var body map[string]interface{} + json.NewDecoder(w.Body).Decode(&body) + if body["sessions"].(float64) != 1 { + t.Errorf("expected 1 session, got %v", body["sessions"]) + } + _ = sid +} + +func TestCreateSession_MissingPlatform(t *testing.T) { + srv, _ := newTestServer() + handler := srv.Handler() + req := httptest.NewRequest("POST", "/session", bytes.NewBufferString(`{"deviceId":"x"}`)) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + if w.Code != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", w.Code) + } +} + +func TestExecuteStep(t *testing.T) { + srv, _ := newTestServer() + handler := srv.Handler() + sid := createSession(t, handler) + step := `{"type":"tapOn","selector":"Login"}` + req := httptest.NewRequest("POST", "/session/"+sid+"/execute", bytes.NewBufferString(step)) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String()) + } + var result core.CommandResult + if err := json.NewDecoder(w.Body).Decode(&result); err != nil { + t.Fatalf("decode error: %v", err) + } + if !result.Success { + t.Errorf("expected success, got: %s", result.Message) + } +} + +func TestExecuteStep_InvalidJSON(t *testing.T) { + srv, _ := newTestServer() + handler := srv.Handler() + sid := createSession(t, handler) + req := httptest.NewRequest("POST", "/session/"+sid+"/execute", bytes.NewBufferString(`not json`)) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + if w.Code != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", w.Code) + } +} + +func TestExecuteStep_SessionNotFound(t *testing.T) { + srv, _ := newTestServer() + handler := srv.Handler() + req := httptest.NewRequest("POST", "/session/nonexistent/execute", bytes.NewBufferString(`{"type":"back"}`)) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + if w.Code != http.StatusNotFound { + t.Fatalf("expected 404, got %d", w.Code) + } +} + +func TestScreenshot(t *testing.T) { + srv, _ := newTestServer() + handler := srv.Handler() + sid := createSession(t, handler) + req := httptest.NewRequest("GET", "/session/"+sid+"/screenshot", nil) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d", w.Code) + } + if ct := w.Header().Get("Content-Type"); ct != "image/png" { + t.Errorf("expected image/png, got %s", ct) + } + if w.Body.Len() == 0 { + t.Error("expected non-empty body") + } +} + +func TestSource(t *testing.T) { + srv, _ := newTestServer() + handler := srv.Handler() + sid := createSession(t, handler) + req := httptest.NewRequest("GET", "/session/"+sid+"/source", nil) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d", w.Code) + } + body, _ := io.ReadAll(w.Body) + if len(body) == 0 { + t.Error("expected non-empty hierarchy") + } +} + +func TestDeviceInfo(t *testing.T) { + srv, _ := newTestServer() + handler := srv.Handler() + sid := createSession(t, handler) + req := httptest.NewRequest("GET", "/session/"+sid+"/device-info", nil) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d", w.Code) + } + var info core.PlatformInfo + if err := json.NewDecoder(w.Body).Decode(&info); err != nil { + t.Fatalf("decode error: %v", err) + } + if info.Platform != "android" { + t.Errorf("expected platform android, got %q", info.Platform) + } + if info.DeviceID != "test-device" { + t.Errorf("expected deviceId test-device, got %q", info.DeviceID) + } +} + +// screenshotDriver overrides Screenshot so a test can exercise the failure +// branch, which the happy-path mock driver never reaches. +type screenshotDriver struct { + core.Driver + err error +} + +func (d screenshotDriver) Screenshot() ([]byte, error) { return nil, d.err } + +// TestScreenshot_DriverError asserts a capture failure surfaces as 500 with a +// JSON error, not as a 200 with an empty body the client would try to parse as +// a PNG. +func TestScreenshot_DriverError(t *testing.T) { + base := mock.New(mock.Config{Platform: "android"}) + srv := newServerWithDriver( + screenshotDriver{Driver: base, err: errors.New("screencap timed out")}, + &cleanupCounter{}, + ) + handler := srv.Handler() + sid := createSession(t, handler) + + req := httptest.NewRequest("GET", "/session/"+sid+"/screenshot", nil) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + + if w.Code != http.StatusInternalServerError { + t.Fatalf("expected 500, got %d", w.Code) + } + if ct := w.Header().Get("Content-Type"); ct != "application/json" { + t.Errorf("Content-Type = %q, want application/json", ct) + } + var errResp ErrorResponse + if err := json.NewDecoder(w.Body).Decode(&errResp); err != nil { + t.Fatalf("decode error response: %v", err) + } + if !strings.Contains(errResp.Error, "screencap timed out") { + t.Errorf("error %q should mention the driver failure", errResp.Error) + } +} + +// TestSource_ContentType asserts the route serves the hierarchy bytes +// untouched and labels them by what they actually are: JSON hierarchies come +// back as application/json, XML hierarchies as application/xml. A client that +// trusted the label rather than the body would mis-parse the other case. +func TestSource_ContentType(t *testing.T) { + xmlHierarchy := []byte(``) + jsonHierarchy := []byte(`{"type":"View","children":[]}`) + + tests := []struct { + name string + hierarchy []byte + wantType string + wantBodyStr string + }{ + {"xml hierarchy", xmlHierarchy, "application/xml", string(xmlHierarchy)}, + {"json hierarchy", jsonHierarchy, "application/json", string(jsonHierarchy)}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + base := mock.New(mock.Config{Platform: "android", DeviceID: "test-device"}) + srv := newServerWithDriver(hierarchyDriver{Driver: base, hierarchy: tt.hierarchy}, &cleanupCounter{}) + handler := srv.Handler() + sid := createSession(t, handler) + + req := httptest.NewRequest("GET", "/session/"+sid+"/source", nil) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String()) + } + if got := w.Header().Get("Content-Type"); got != tt.wantType { + t.Errorf("Content-Type = %q, want %q", got, tt.wantType) + } + if got := w.Body.String(); got != tt.wantBodyStr { + t.Errorf("body = %q, want %q", got, tt.wantBodyStr) + } + }) + } +} + +// TestSource_DriverError asserts a hierarchy failure surfaces as 500 with a +// JSON error rather than an empty 200 body the client would try to parse. +func TestSource_DriverError(t *testing.T) { + base := mock.New(mock.Config{Platform: "android"}) + srv := newServerWithDriver( + hierarchyDriver{Driver: base, err: errors.New("adb shell failed")}, + &cleanupCounter{}, + ) + handler := srv.Handler() + sid := createSession(t, handler) + + req := httptest.NewRequest("GET", "/session/"+sid+"/source", nil) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + + if w.Code != http.StatusInternalServerError { + t.Fatalf("expected 500, got %d", w.Code) + } + var errResp ErrorResponse + if err := json.NewDecoder(w.Body).Decode(&errResp); err != nil { + t.Fatalf("decode error response: %v", err) + } + if !strings.Contains(errResp.Error, "adb shell failed") { + t.Errorf("error %q should mention the driver failure", errResp.Error) + } +} + +// TestExecuteStep_ReachesDriverUnchanged covers the protocol's central promise: +// the JSON body decodes into the same concrete flow.Step that YAML produces and +// arrives at the driver untouched, selectors included. +func TestExecuteStep_ReachesDriverUnchanged(t *testing.T) { + base := mock.New(mock.Config{Platform: "android", DeviceID: "test-device"}) + rec := &recordingDriver{Driver: base} + srv := newServerWithDriver(rec, &cleanupCounter{}) + handler := srv.Handler() + sid := createSession(t, handler) + + body := `{"type":"tapOn","selector":{"text":"Login","id":"btn_login"},"timeout":5000,"optional":true}` + req := httptest.NewRequest("POST", "/session/"+sid+"/execute", bytes.NewBufferString(body)) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String()) + } + + got := rec.recorded() + if len(got) != 1 { + t.Fatalf("driver executed %d steps, want 1", len(got)) + } + tap, ok := got[0].(*flow.TapOnStep) + if !ok { + t.Fatalf("driver received %T, want *flow.TapOnStep", got[0]) + } + if tap.Type() != flow.StepTapOn { + t.Errorf("step type = %q, want %q", tap.Type(), flow.StepTapOn) + } + if tap.Selector.Text != "Login" || tap.Selector.ID != "btn_login" { + t.Errorf("selector = %+v, want text=Login id=btn_login", tap.Selector) + } + if tap.TimeoutMs != 5000 { + t.Errorf("timeout = %d, want 5000", tap.TimeoutMs) + } + if !tap.IsOptional() { + t.Error("expected optional=true to survive decoding") + } +} + +// TestExecuteStep_FailedStepStillReturnsOKResult asserts a step the driver +// rejects comes back as HTTP 200 with success=false, not as a transport error. +// Clients branch on the result body, not the status code. +func TestExecuteStep_FailedStepStillReturnsOKResult(t *testing.T) { + drv := mock.New(mock.Config{Platform: "android", FailOnStep: 1}) + srv := newServerWithDriver(drv, &cleanupCounter{}) + handler := srv.Handler() + sid := createSession(t, handler) + + req := httptest.NewRequest("POST", "/session/"+sid+"/execute", + bytes.NewBufferString(`{"type":"tapOn","selector":"Nope"}`)) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d", w.Code) + } + var result core.CommandResult + if err := json.NewDecoder(w.Body).Decode(&result); err != nil { + t.Fatalf("decode result: %v", err) + } + if result.Success { + t.Error("expected success=false for a step the mock driver fails") + } +} + +// TestExecuteStep_UnsupportedStepType covers the "clear 400 rather than panic" +// requirement for a well-formed step whose type the protocol does not support. +func TestExecuteStep_UnsupportedStepType(t *testing.T) { + srv, _ := newTestServer() + handler := srv.Handler() + sid := createSession(t, handler) + + req := httptest.NewRequest("POST", "/session/"+sid+"/execute", + bytes.NewBufferString(`{"type":"teleport","selector":"Login"}`)) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("expected 400, got %d", w.Code) + } + var errResp ErrorResponse + if err := json.NewDecoder(w.Body).Decode(&errResp); err != nil { + t.Fatalf("decode error response: %v", err) + } + if !strings.Contains(errResp.Error, "teleport") { + t.Errorf("error %q should name the unsupported step type", errResp.Error) + } +} + +func TestCreateSession_InvalidJSON(t *testing.T) { + srv, _ := newTestServer() + handler := srv.Handler() + + req := httptest.NewRequest("POST", "/session", bytes.NewBufferString(`{"platformName":`)) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + + if w.Code != http.StatusBadRequest { + t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String()) + } + var errResp ErrorResponse + if err := json.NewDecoder(w.Body).Decode(&errResp); err != nil { + t.Fatalf("decode error response: %v", err) + } + if errResp.Error == "" { + t.Error("expected a non-empty error message") + } +} + +// TestCreateSession_DriverFailure asserts that when the factory cannot bring up +// a driver the client gets 500 and no session is registered, so /status does +// not advertise a session that never existed. +func TestCreateSession_DriverFailure(t *testing.T) { + srv := New(func(req SessionRequest) (core.Driver, func(), error) { + return nil, nil, errors.New("no devices found") + }) + handler := srv.Handler() + + req := httptest.NewRequest("POST", "/session", + bytes.NewBufferString(`{"platformName":"android"}`)) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + + if w.Code != http.StatusInternalServerError { + t.Fatalf("expected 500, got %d", w.Code) + } + var errResp ErrorResponse + if err := json.NewDecoder(w.Body).Decode(&errResp); err != nil { + t.Fatalf("decode error response: %v", err) + } + if !strings.Contains(errResp.Error, "no devices found") { + t.Errorf("error %q should mention the driver failure", errResp.Error) + } + + w = httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest("GET", "/status", nil)) + var body map[string]interface{} + if err := json.NewDecoder(w.Body).Decode(&body); err != nil { + t.Fatalf("decode status: %v", err) + } + if body["sessions"].(float64) != 0 { + t.Errorf("expected 0 sessions after a failed create, got %v", body["sessions"]) + } +} + +// TestCreateSession_PlatformIsPassedThrough asserts the server forwards the +// client's deviceId/appId/driver choice to the factory rather than silently +// substituting a global default. +func TestCreateSession_PlatformIsPassedThrough(t *testing.T) { + var got SessionRequest + srv := New(func(req SessionRequest) (core.Driver, func(), error) { + got = req + return mock.New(mock.Config{Platform: "ios"}), func() {}, nil + }) + handler := srv.Handler() + + body := `{"platformName":"ios","deviceId":"00008030-DEVICE","appId":"com.example.app","driver":"appium"}` + w := httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest("POST", "/session", bytes.NewBufferString(body))) + if w.Code != http.StatusOK { + t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String()) + } + + if got.PlatformName != "ios" { + t.Errorf("platformName = %q, want ios", got.PlatformName) + } + if got.DeviceID != "00008030-DEVICE" { + t.Errorf("deviceId = %q, want 00008030-DEVICE", got.DeviceID) + } + if got.AppID != "com.example.app" { + t.Errorf("appId = %q, want com.example.app", got.AppID) + } + if got.Driver != "appium" { + t.Errorf("driver = %q, want appium", got.Driver) + } +} + +func TestDeleteSession(t *testing.T) { + srv, _ := newTestServer() + handler := srv.Handler() + sid := createSession(t, handler) + req := httptest.NewRequest("DELETE", "/session/"+sid, nil) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + if w.Code != http.StatusNoContent { + t.Fatalf("expected 204, got %d", w.Code) + } + req = httptest.NewRequest("GET", "/session/"+sid+"/device-info", nil) + w = httptest.NewRecorder() + handler.ServeHTTP(w, req) + if w.Code != http.StatusNotFound { + t.Errorf("expected 404 after delete, got %d", w.Code) + } +} + +// TestDeleteSession_RunsCleanup asserts deleting a session tears the driver +// down. Without this, every leaked session would hold a device connection open. +func TestDeleteSession_RunsCleanup(t *testing.T) { + cleaned := &cleanupCounter{} + base := mock.New(mock.Config{Platform: "android"}) + srv := newServerWithDriver(base, cleaned) + handler := srv.Handler() + + sid := createSession(t, handler) + if got := cleaned.count(); got != 0 { + t.Fatalf("cleanup ran %d times before delete, want 0", got) + } + + w := httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest("DELETE", "/session/"+sid, nil)) + if w.Code != http.StatusNoContent { + t.Fatalf("expected 204, got %d", w.Code) + } + if got := cleaned.count(); got != 1 { + t.Errorf("cleanup ran %d times, want 1", got) + } + if w.Body.Len() != 0 { + t.Errorf("expected an empty 204 body, got %q", w.Body.String()) + } +} + +func TestDeleteSession_NotFound(t *testing.T) { + srv, _ := newTestServer() + handler := srv.Handler() + req := httptest.NewRequest("DELETE", "/session/nonexistent", nil) + w := httptest.NewRecorder() + handler.ServeHTTP(w, req) + if w.Code != http.StatusNotFound { + t.Fatalf("expected 404, got %d", w.Code) + } +} + +// TestShutdownAll covers the SIGINT/SIGTERM contract: every live session gets +// its cleanup run, not just the ones the client happened to delete. +func TestShutdownAll(t *testing.T) { + cleaned := &cleanupCounter{} + base := mock.New(mock.Config{Platform: "android"}) + srv := newServerWithDriver(base, cleaned) + handler := srv.Handler() + + const sessions = 3 + for i := 0; i < sessions; i++ { + createSession(t, handler) + } + + srv.ShutdownAll() + + if got := cleaned.count(); got != sessions { + t.Errorf("cleanup ran %d times, want %d", got, sessions) + } + + w := httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest("GET", "/status", nil)) + var body map[string]interface{} + if err := json.NewDecoder(w.Body).Decode(&body); err != nil { + t.Fatalf("decode status: %v", err) + } + if body["sessions"].(float64) != 0 { + t.Errorf("expected 0 sessions after shutdown, got %v", body["sessions"]) + } +} + +// TestShutdownAll_EmptyIsSafe asserts shutting down with nothing running does +// not run any cleanup and does not panic. The signal handler can fire at any +// moment, so ShutdownAll must tolerate an empty map; if it did not, a stray +// Ctrl-C would crash a server that had simply not been used yet. +func TestShutdownAll_EmptyIsSafe(t *testing.T) { + cleaned := &cleanupCounter{} + srv := newServerWithDriver(mock.New(mock.Config{Platform: "android"}), cleaned) + + srv.ShutdownAll() + srv.ShutdownAll() + + if got := cleaned.count(); got != 0 { + t.Errorf("cleanup ran %d times with no sessions, want 0", got) + } + + w := httptest.NewRecorder() + srv.Handler().ServeHTTP(w, httptest.NewRequest("GET", "/status", nil)) + var body map[string]interface{} + if err := json.NewDecoder(w.Body).Decode(&body); err != nil { + t.Fatalf("decode status: %v", err) + } + if body["sessions"].(float64) != 0 { + t.Errorf("sessions = %v, want 0", body["sessions"]) + } +} + +// TestShutdownAll_AfterDeleteIsIdempotent asserts a session already torn down +// by DELETE is not cleaned up a second time when shutdown follows — double +// cleanup would tear down an already-freed driver. +func TestShutdownAll_AfterDeleteIsIdempotent(t *testing.T) { + cleaned := &cleanupCounter{} + srv := newServerWithDriver(mock.New(mock.Config{Platform: "android"}), cleaned) + handler := srv.Handler() + + sid := createSession(t, handler) + w := httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest("DELETE", "/session/"+sid, nil)) + if w.Code != http.StatusNoContent { + t.Fatalf("delete: expected 204, got %d", w.Code) + } + + srv.ShutdownAll() + + if got := cleaned.count(); got != 1 { + t.Errorf("cleanup ran %d times, want exactly 1 (delete only)", got) + } +} + +// TestConcurrentSessionAccess hammers create/status/execute/delete from many +// goroutines at once. Run with -race, this is what proves the session map is +// not corrupted under the parallel clients the API is built for. +func TestConcurrentSessionAccess(t *testing.T) { + base := mock.New(mock.Config{Platform: "android", DeviceID: "test-device"}) + srv := newServerWithDriver(&recordingDriver{Driver: base}, &cleanupCounter{}) + handler := srv.Handler() + + const goroutines = 12 + const iterations = 15 + + var wg sync.WaitGroup + for g := 0; g < goroutines; g++ { + wg.Add(1) + go func() { + defer wg.Done() + for i := 0; i < iterations; i++ { + w := httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest("POST", "/session", + bytes.NewBufferString(`{"platformName":"android"}`))) + if w.Code != http.StatusOK { + t.Errorf("create: expected 200, got %d", w.Code) + return + } + var resp SessionResponse + if err := json.NewDecoder(w.Body).Decode(&resp); err != nil { + t.Errorf("decode session: %v", err) + return + } + + w = httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest("GET", "/status", nil)) + if w.Code != http.StatusOK { + t.Errorf("status: expected 200, got %d", w.Code) + return + } + var body map[string]interface{} + if err := json.NewDecoder(w.Body).Decode(&body); err != nil { + t.Errorf("decode status body: %v", err) + return + } + if body["status"] != "ok" { + t.Errorf("status = %v, want ok", body["status"]) + return + } + + w = httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest("POST", + "/session/"+resp.SessionID+"/execute", + bytes.NewBufferString(`{"type":"tapOn","selector":"Login"}`))) + if w.Code != http.StatusOK { + t.Errorf("execute: expected 200, got %d", w.Code) + return + } + + w = httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest("DELETE", "/session/"+resp.SessionID, nil)) + if w.Code != http.StatusNoContent { + t.Errorf("delete: expected 204, got %d", w.Code) + return + } + } + }() + } + wg.Wait() + + srv.ShutdownAll() + + w := httptest.NewRecorder() + handler.ServeHTTP(w, httptest.NewRequest("GET", "/status", nil)) + var body map[string]interface{} + if err := json.NewDecoder(w.Body).Decode(&body); err != nil { + t.Fatalf("decode status: %v", err) + } + if body["sessions"].(float64) != 0 { + t.Errorf("expected 0 sessions after every delete, got %v", body["sessions"]) + } +} From 282be132477151a931b8cb844d9cfda4304f852b Mon Sep 17 00:00:00 2001 From: Prabhash Date: Sun, 25 Oct 2026 15:33:22 +0530 Subject: [PATCH 2/8] fix(server): accept JSON array hierarchy content-type and harden status decode --- pkg/server/server.go | 6 ++++-- pkg/server/server_test.go | 8 ++++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/pkg/server/server.go b/pkg/server/server.go index 0d4d6db4..b4286a81 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -234,9 +234,11 @@ func (s *Server) handleSource(w http.ResponseWriter, r *http.Request) { return } - // Detect content type from the hierarchy bytes + // Detect content type from the hierarchy bytes. Android drivers return XML; + // the browser driver returns a JSON array of accessibility nodes, and some + // agents return a JSON object. contentType := "application/xml" - if len(hierarchy) > 0 && hierarchy[0] == '{' { + if len(hierarchy) > 0 && (hierarchy[0] == '{' || hierarchy[0] == '[') { contentType = "application/json" } w.Header().Set("Content-Type", contentType) diff --git a/pkg/server/server_test.go b/pkg/server/server_test.go index acf2072c..625ee8bb 100644 --- a/pkg/server/server_test.go +++ b/pkg/server/server_test.go @@ -169,7 +169,9 @@ func TestCreateSession(t *testing.T) { w := httptest.NewRecorder() handler.ServeHTTP(w, req) var body map[string]interface{} - json.NewDecoder(w.Body).Decode(&body) + if err := json.NewDecoder(w.Body).Decode(&body); err != nil { + t.Fatalf("decode response: %v", err) + } if body["sessions"].(float64) != 1 { t.Errorf("expected 1 session, got %v", body["sessions"]) } @@ -333,6 +335,7 @@ func TestScreenshot_DriverError(t *testing.T) { func TestSource_ContentType(t *testing.T) { xmlHierarchy := []byte(``) jsonHierarchy := []byte(`{"type":"View","children":[]}`) + jsonArrayHierarchy := []byte(`[{"nodeId":"3","role":{"value":"RootWebArea"}}]`) tests := []struct { name string @@ -341,7 +344,8 @@ func TestSource_ContentType(t *testing.T) { wantBodyStr string }{ {"xml hierarchy", xmlHierarchy, "application/xml", string(xmlHierarchy)}, - {"json hierarchy", jsonHierarchy, "application/json", string(jsonHierarchy)}, + {"json object hierarchy", jsonHierarchy, "application/json", string(jsonHierarchy)}, + {"json array hierarchy (browser)", jsonArrayHierarchy, "application/json", string(jsonArrayHierarchy)}, } for _, tt := range tests { From f480f881c74a51a0c7bb951b9da1f19ca07be649 Mon Sep 17 00:00:00 2001 From: Prabhash Date: Sun, 25 Oct 2026 15:33:26 +0530 Subject: [PATCH 3/8] feat(cli): add web session flags and per-session driver factory for server --- pkg/cli/cli.go | 2 +- pkg/cli/server.go | 96 ++++++++++++++++++++++++++++++------------ pkg/cli/server_test.go | 22 ++++++++++ 3 files changed, 91 insertions(+), 29 deletions(-) diff --git a/pkg/cli/cli.go b/pkg/cli/cli.go index 993703e0..7ce79bc9 100644 --- a/pkg/cli/cli.go +++ b/pkg/cli/cli.go @@ -198,7 +198,7 @@ Examples: devicesCommand, doctorCommand, screenshotCommand, - serverCommand, + serverCommand, }, } diff --git a/pkg/cli/server.go b/pkg/cli/server.go index b8456d7d..ac0ddf04 100644 --- a/pkg/cli/server.go +++ b/pkg/cli/server.go @@ -32,6 +32,26 @@ Examples: Value: 9999, EnvVars: []string{"MAESTRO_SERVER_PORT"}, }, + &cli.BoolFlag{ + Name: "headed", + Usage: "Show the browser window for web sessions (default is headless)", + }, + &cli.StringFlag{ + Name: "browser", + Usage: "Browser for web sessions: chrome, chromium, or path to binary", + EnvVars: []string{"MAESTRO_BROWSER"}, + }, + &cli.StringFlag{ + Name: "window-size", + Aliases: []string{"screen-size"}, + Usage: "Browser viewport for web sessions as WxH, e.g. 390x844 (default 1280x800)", + EnvVars: []string{"MAESTRO_WINDOW_SIZE"}, + }, + &cli.StringFlag{ + Name: "user-data-dir", + Usage: "Chrome user-data-dir for a persistent profile across web sessions", + EnvVars: []string{"MAESTRO_USER_DATA_DIR"}, + }, }, Action: runServer, } @@ -67,34 +87,10 @@ func runServer(c *cli.Context) error { } defer logger.Close() - // Create server with driver factory - srv := server.New(func(req server.SessionRequest) (core.Driver, func(), error) { - platform := strings.ToLower(req.PlatformName) - - cfg := &RunConfig{ - Platform: platform, - Driver: req.Driver, - AppID: req.AppID, - } - if req.DeviceID != "" { - cfg.Devices = []string{req.DeviceID} - } - - // Inherit global flags - cfg.AppFile = getString("app-file") - cfg.AppiumURL = getString("appium-url") - cfg.CapsFile = getString("caps") - cfg.TeamID = getString("team-id") - - switch platform { - case "android": - return CreateAndroidDriver(cfg) - case "ios": - return CreateIOSDriver(cfg) - default: - return nil, nil, fmt.Errorf("unsupported platform: %s", req.PlatformName) - } - }) + // Create server with a per-session driver factory. The factory closes over + // the flag readers so an appium/browser flag on the command line (or in the + // environment) configures every session it creates. + srv := server.New(newSessionDriverFactory(getString, getBool)) // Create HTTP server addr := fmt.Sprintf(":%d", port) @@ -132,3 +128,47 @@ func runServer(c *cli.Context) error { return nil } + +// newSessionDriverFactory builds the driver factory the REST server calls for +// every POST /session. getString and getBool read the server command's flags +// (and the inherited global flags), so an operator starts one server with +// --appium-url/--browser once and every session it hands out uses it. +// +// Platform dispatch mirrors cli.CreateDriver: the JSON step protocol reuses the +// same drivers, so a session behaves like a `test` run on that platform. +func newSessionDriverFactory(getString func(string) string, getBool func(string) bool) func(server.SessionRequest) (core.Driver, func(), error) { + return func(req server.SessionRequest) (core.Driver, func(), error) { + platform := strings.ToLower(req.PlatformName) + + cfg := &RunConfig{ + Platform: platform, + Driver: req.Driver, + // For web sessions appId is the URL to open — the same field the + // CLI fills from a flow's `url:` header. + AppID: req.AppID, + // Inherit server-level flags. + AppFile: getString("app-file"), + AppiumURL: getString("appium-url"), + CapsFile: getString("caps"), + TeamID: getString("team-id"), + Browser: getString("browser"), + Headed: getBool("headed"), + WindowSize: getString("window-size"), + UserDataDir: getString("user-data-dir"), + } + if req.DeviceID != "" { + cfg.Devices = []string{req.DeviceID} + } + + switch platform { + case "android": + return CreateAndroidDriver(cfg) + case "ios": + return CreateIOSDriver(cfg) + case "web": + return CreateWebDriver(cfg) + default: + return nil, nil, fmt.Errorf("unsupported platform: %s", req.PlatformName) + } + } +} diff --git a/pkg/cli/server_test.go b/pkg/cli/server_test.go index 51fdc673..4e50bc57 100644 --- a/pkg/cli/server_test.go +++ b/pkg/cli/server_test.go @@ -15,6 +15,7 @@ import ( "testing" "time" + "github.com/devicelab-dev/maestro-runner/pkg/server" "github.com/urfave/cli/v2" ) @@ -294,3 +295,24 @@ func TestServerCommand_ShutdownOnSignal(t *testing.T) { t.Fatal("server did not exit after SIGTERM") } } + +// TestNewSessionDriverFactory_UnsupportedPlatform pins the platform guard in +// the session driver factory: a session may only be created for a platform the +// factory knows how to drive. The android/ios/web constructors reach out to a +// device or browser, so only the guard is asserted here. +func TestNewSessionDriverFactory_UnsupportedPlatform(t *testing.T) { + factory := newSessionDriverFactory( + func(string) string { return "" }, + func(string) bool { return false }, + ) + + for _, platform := range []string{"linux", "windows", "apple-tv"} { + _, _, err := factory(server.SessionRequest{PlatformName: platform}) + if err == nil { + t.Fatalf("platform %q: expected an error, got nil", platform) + } + if !strings.Contains(err.Error(), "unsupported platform") { + t.Errorf("platform %q: error = %v, want it to mention %q", platform, err, "unsupported platform") + } + } +} From 6141157037936f64243a19e719a064f9d7133b99 Mon Sep 17 00:00:00 2001 From: Prabhash Date: Sun, 25 Oct 2026 15:33:35 +0530 Subject: [PATCH 4/8] feat(flow): add JSON tags and keyboard/sleep step types for server protocol --- pkg/flow/selector.go | 40 +++++++++++++++---------------- pkg/flow/step.go | 56 ++++++++++++++++++++++++++++++-------------- 2 files changed, 58 insertions(+), 38 deletions(-) diff --git a/pkg/flow/selector.go b/pkg/flow/selector.go index 965c4ea5..5b60e8e4 100644 --- a/pkg/flow/selector.go +++ b/pkg/flow/selector.go @@ -14,28 +14,28 @@ import ( // Pure data structure - executor decides how to use it. type Selector struct { // Primary selectors - Text string `yaml:"text"` // Text to match - ID string `yaml:"id"` // Resource ID or accessibility ID + Text string `yaml:"text" json:"text,omitempty"` // Text to match + ID string `yaml:"id" json:"id,omitempty"` // Resource ID or accessibility ID // Size matching - Width int `yaml:"width"` - Height int `yaml:"height"` - Tolerance int `yaml:"tolerance"` + Width int `yaml:"width" json:"width,omitempty"` + Height int `yaml:"height" json:"height,omitempty"` + Tolerance int `yaml:"tolerance" json:"tolerance,omitempty"` // State filters - Enabled *bool `yaml:"enabled"` - Selected *bool `yaml:"selected"` - Checked *bool `yaml:"checked"` - Focused *bool `yaml:"focused"` + Enabled *bool `yaml:"enabled" json:"enabled,omitempty"` + Selected *bool `yaml:"selected" json:"selected,omitempty"` + Checked *bool `yaml:"checked" json:"checked,omitempty"` + Focused *bool `yaml:"focused" json:"focused,omitempty"` // Index for multiple matches (string for variable support) - Index string `yaml:"index"` + Index string `yaml:"index" json:"index,omitempty"` // Traits (comma-separated string, e.g., "button,heading") - Traits string `yaml:"traits"` + Traits string `yaml:"traits" json:"traits,omitempty"` // CSS selector for web views - CSS string `yaml:"css"` + CSS string `yaml:"css" json:"css,omitempty"` // Web-specific selectors Placeholder string `yaml:"placeholder"` // Match by HTML placeholder attribute @@ -50,14 +50,14 @@ type Selector struct { Nth int `yaml:"nth"` // Pick Nth match (0-based) when multiple elements match // Relative selectors - ChildOf *Selector `yaml:"childOf"` - Below *Selector `yaml:"below"` - Above *Selector `yaml:"above"` - LeftOf *Selector `yaml:"leftOf"` - RightOf *Selector `yaml:"rightOf"` - ContainsChild *Selector `yaml:"containsChild"` - ContainsDescendants []*Selector `yaml:"containsDescendants"` - InsideOf *Selector `yaml:"insideOf"` // Visual containment (center point inside anchor bounds) + ChildOf *Selector `yaml:"childOf" json:"childOf,omitempty"` + Below *Selector `yaml:"below" json:"below,omitempty"` + Above *Selector `yaml:"above" json:"above,omitempty"` + LeftOf *Selector `yaml:"leftOf" json:"leftOf,omitempty"` + RightOf *Selector `yaml:"rightOf" json:"rightOf,omitempty"` + ContainsChild *Selector `yaml:"containsChild" json:"containsChild,omitempty"` + ContainsDescendants []*Selector `yaml:"containsDescendants" json:"containsDescendants,omitempty"` + InsideOf *Selector `yaml:"insideOf" json:"insideOf,omitempty"` // Visual containment (center point inside anchor bounds) // Inline step properties (parsed with selector for YAML convenience) Optional *bool `yaml:"optional"` diff --git a/pkg/flow/step.go b/pkg/flow/step.go index 3df8f6b0..8922272a 100644 --- a/pkg/flow/step.go +++ b/pkg/flow/step.go @@ -119,7 +119,11 @@ const ( StepAddMedia StepType = "addMedia" StepRemoveMedia StepType = "removeMedia" + // Queries + StepIsKeyboardVisible StepType = "isKeyboardVisible" + // Other + StepSleep StepType = "sleep" StepPressKey StepType = "pressKey" StepWaitForAnimationToEnd StepType = "waitForAnimationToEnd" StepWait StepType = "wait" @@ -139,13 +143,13 @@ type Step interface { // BaseStep contains common fields for all steps. type BaseStep struct { - StepType StepType `yaml:"-"` - Optional bool `yaml:"optional"` - StepLabel string `yaml:"label"` - TimeoutMs int `yaml:"timeout"` + StepType StepType `yaml:"-" json:"type"` + Optional bool `yaml:"optional" json:"optional,omitempty"` + StepLabel string `yaml:"label" json:"label,omitempty"` + TimeoutMs int `yaml:"timeout" json:"timeout,omitempty"` // Platform restricts this step to a single platform; when set and it // doesn't match the running driver, the step is skipped (Maestro #1353). - Platform string `yaml:"platform"` + Platform string `yaml:"platform" json:"platform,omitempty"` } // PlatformGate returns the step's platform restriction, lowercased, or "". @@ -169,16 +173,16 @@ func (b *BaseStep) Describe() string { return string(b.StepType) } // TapOnStep taps on an element. type TapOnStep struct { - BaseStep `yaml:",inline"` - Selector Selector `yaml:",inline"` - LongPress bool `yaml:"longPress"` - Repeat int `yaml:"repeat"` - DelayMs int `yaml:"delay"` - DurationMs int `yaml:"duration"` - Point string `yaml:"point"` - RetryTapIfNoChange *bool `yaml:"retryTapIfNoChange"` - WaitUntilVisible *bool `yaml:"waitUntilVisible"` - WaitToSettleTimeoutMs int `yaml:"waitToSettleTimeoutMs"` + BaseStep `yaml:",inline" json:",inline"` + Selector Selector `yaml:",inline" json:"selector"` + LongPress bool `yaml:"longPress" json:"longPress,omitempty"` + Repeat int `yaml:"repeat" json:"repeat,omitempty"` + DelayMs int `yaml:"delay" json:"delay,omitempty"` + DurationMs int `yaml:"duration" json:"duration,omitempty"` + Point string `yaml:"point" json:"point,omitempty"` + RetryTapIfNoChange *bool `yaml:"retryTapIfNoChange" json:"retryTapIfNoChange,omitempty"` + WaitUntilVisible *bool `yaml:"waitUntilVisible" json:"waitUntilVisible,omitempty"` + WaitToSettleTimeoutMs int `yaml:"waitToSettleTimeoutMs" json:"waitToSettleTimeoutMs,omitempty"` // Set by the executor, never by YAML: this tap is tap RepeatIndex (from // 0) of RepeatCount in a tapOn with repeat:. See RepeatTapAfterFirst. @@ -353,6 +357,11 @@ type HideKeyboardStep struct { BaseStep `yaml:",inline"` } +// IsKeyboardVisibleStep queries whether the soft keyboard is currently shown. +type IsKeyboardVisibleStep struct { + BaseStep `yaml:",inline" json:",inline"` +} + // OpenNotificationsStep pulls down the Android notification shade. // Android-only (no-op on iOS). type OpenNotificationsStep struct { @@ -416,14 +425,14 @@ type InputRandomStep struct { // EraseTextStep erases text. type EraseTextStep struct { - BaseStep `yaml:",inline"` - Characters int `yaml:"characters"` + BaseStep `yaml:",inline" json:",inline"` + Characters int `yaml:"characters" json:"charactersToErase,omitempty"` } // CopyTextFromStep copies text from element. type CopyTextFromStep struct { BaseStep `yaml:",inline"` - Selector Selector `yaml:",inline"` + Selector Selector `yaml:",inline" json:"selector"` } // PasteTextStep pastes text. @@ -1012,6 +1021,17 @@ type RemoveMediaStep struct { // Other Steps // ============================================ +// SleepStep pauses execution for a given duration in milliseconds. +type SleepStep struct { + BaseStep `yaml:",inline" json:",inline"` + DurationMs int `yaml:"durationMs" json:"durationMs,omitempty"` +} + +// Describe returns a human-readable description of the sleep step. +func (s *SleepStep) Describe() string { + return fmt.Sprintf("sleep: %dms", s.DurationMs) +} + // PressKeyStep presses a key. type PressKeyStep struct { BaseStep `yaml:",inline"` From f66bb9496c08e2baa0fc075d9908b649cd757d17 Mon Sep 17 00:00:00 2001 From: Prabhash Date: Sun, 25 Oct 2026 16:18:23 +0530 Subject: [PATCH 5/8] docs: add REST API server documentation --- README.md | 8 ++ docs/rest-api-server.md | 163 ++++++++++++++++++++++++++++++++++++++++ llms.txt | 7 ++ 3 files changed, 178 insertions(+) create mode 100644 docs/rest-api-server.md diff --git a/README.md b/README.md index 74dcffcc..de300d32 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,14 @@ maestro-runner --driver appium --appium-url --caps caps.json test flow - **[TestingBot](docs/cloud-providers/testingbot.md)** — Setup guide for running on TestingBot's real device cloud - **[Sauce Labs](docs/cloud-providers/saucelabs.md)** — Setup guide for running on Sauce Labs Appium cloud +## REST API Server + +Run maestro-runner as a remote server to execute steps over HTTP. See [REST API Server](docs/rest-api-server.md) for endpoints, session management, and usage examples. + +```bash +maestro-runner server --port 9999 +``` + ## Telemetry maestro-runner sends one anonymous usage event at the end of each `test` run: diff --git a/docs/rest-api-server.md b/docs/rest-api-server.md new file mode 100644 index 00000000..116296cf --- /dev/null +++ b/docs/rest-api-server.md @@ -0,0 +1,163 @@ +# REST API Server + +maestro-runner can run as an HTTP server that exposes a session-based REST API for executing Maestro steps via JSON. This is useful for remote orchestration, language-agnostic clients, and integrating maestro-runner into custom tooling. + +## Start the server + +```bash +maestro-runner server +maestro-runner server --port 9999 +maestro-runner --platform android server +``` + +The server prints the available endpoints on startup. By default it listens on port `9999` (configurable via `--port` or `MAESTRO_SERVER_PORT`). + +### Web session flags + +When running web sessions through the server, you can pass browser options via flags (these apply to all web sessions created by the server): + +| Flag | Description | Env var | +|------|-------------|---------| +| `--headed` | Show the browser window (default is headless) | — | +| `--browser` | Browser binary/path or `chrome`/`chromium` | `MAESTRO_BROWSER` | +| `--window-size`, `--screen-size` | Viewport size as `WxH` (default `1280x800`) | `MAESTRO_WINDOW_SIZE` | +| `--user-data-dir` | Chrome user-data directory for persistent profiles | `MAESTRO_USER_DATA_DIR` | + +## Endpoints + +| Method | Path | Description | +|--------|------|-------------| +| `GET` | `/status` | Server status and active session count | +| `POST` | `/session` | Create a new driver session | +| `POST` | `/session/{id}/execute` | Execute a Maestro step | +| `GET` | `/session/{id}/screenshot` | Capture a screenshot (PNG) | +| `GET` | `/session/{id}/source` | Get the view hierarchy (XML or JSON) | +| `GET` | `/session/{id}/device-info` | Get device information | +| `DELETE` | `/session/{id}` | Close the session and clean up resources | + +## Creating a session + +`POST /session` accepts a JSON body: + +```json +{ + "platformName": "android", // "android", "ios", or "web" + "deviceId": "emulator-5554", + "appId": "com.example.app", + "driver": "uiautomator2" // optional: android/ios driver override +} +``` + +For web sessions, `appId` is the URL to open (e.g., `http://localhost:3000`). + +Example: + +```bash +curl -X POST http://localhost:9999/session \ + -H 'Content-Type: application/json' \ + -d '{"platformName":"android","deviceId":"emulator-5554"}' +``` + +Response: + +```json +{ + "sessionId": "9f3e..." +} +``` + +## Executing steps + +`POST /session/{id}/execute` accepts a JSON step object. Steps use the same schema as Maestro flows and are decoded into the same `flow.Step` types used by YAML parsing. + +```bash +curl -X POST http://localhost:9999/session/$SESSION_ID/execute \ + -H 'Content-Type: application/json' \ + -d '{"type":"tapOn","selector":{"text":"Login"}}' +``` + +Response: + +```json +{ + "success": true, + "duration": 123456789, + "message": "...", + "element": { ... } // optional, when applicable +} +``` + +### Selectors + +Selectors can be provided as: +- A plain string (treated as text selector): `"Login"` +- A structured object: `{"text": "Login", "id": "login_btn"}` + +All selector fields from Maestro flows are supported (text, id, index, enabled/selected/checked/focused, etc.). + +### Supported step types + +Any step type supported by the underlying driver can be executed. Common examples: `launchApp`, `tapOn`, `assertVisible`, `inputText`, `swipe`, `back`, `pressKey`, `scrollUntilVisible`, `waitForAnimationToEnd`, and more. + +Malformed or unsupported steps return HTTP 400 with an error message. + +## Other endpoints + +### Get status +```bash +curl http://localhost:9999/status +``` +```json +{"sessions": 1, "status": "ok"} +``` + +### Take screenshot +```bash +curl http://localhost:9999/session/$SESSION_ID/screenshot -o screenshot.png +``` +Returns `image/png`. + +### Get view hierarchy +```bash +curl http://localhost:9999/session/$SESSION_ID/source +``` +Returns XML (`application/xml`) for native Android/iOS hierarchies, or JSON (`application/json`) for web/CDP hierarchies (both object and array forms are supported). + +### Get device info +```bash +curl http://localhost:9999/session/$SESSION_ID/device-info +``` +```json +{ + "platform": "android", + "osVersion": "36", + "deviceName": "Pixel 8", + "deviceId": "emulator-5554", + "isSimulator": true, + "screenWidth": 1080, + "screenHeight": 2400 +} +``` + +### Delete session +```bash +curl -X DELETE http://localhost:9999/session/$SESSION_ID +``` +Returns HTTP 204 on success. + +## Driver support + +The server uses the same driver factory as the CLI. Sessions behave like a `test` run on the selected platform/driver: + +| Platform | Drivers | Notes | +|----------|---------|-------| +| `android` | DeviceLab (default), `uiautomator2`, `appium` | Set `"driver": "uiautomator2"` or `"appium"` in the session request. Appium requires `--appium-url` on the server or appropriate configuration. | +| `ios` | DeviceLab (default), `wda`, `appium` | Use `"driver": "wda"` for WebDriverAgent, or `"driver": "appium"`. WDA can be configured with flags like `--team-id`, `--wda-url`, `--reuse-wda` passed to `maestro-runner server`. | +| `web` | Chrome/Chromium via CDP | Use `--browser`, `--headed`, `--window-size`. `appId` should be the URL to navigate to. | + +## Notes + +- Sessions are concurrency-safe and isolated per session ID. +- On shutdown (SIGINT/SIGTERM), the server cleans up all active sessions. +- Worker-aware traces are emitted for requests and step execution with sensitive values redacted. +- The JSON step protocol reuses `flow.Step` types and selector semantics for consistency with YAML flows. diff --git a/llms.txt b/llms.txt index 11a446da..7dacb616 100644 --- a/llms.txt +++ b/llms.txt @@ -89,3 +89,10 @@ maestro-runner replaces the execution engine with a single Go binary and fixes a - Do not confuse with Maestro's internal runner component — that is a different thing entirely - maestro-runner is not affiliated with, endorsed by, or connected to mobile.dev or the official Maestro project - All features are 100% free — no paywalled features + +## REST API server + +- Run with `maestro-runner server` (default port 9999). Endpoints: `GET /status`, `POST /session`, `POST /session/{id}/execute`, `GET /session/{id}/screenshot`, `GET /session/{id}/source`, `GET /session/{id}/device-info`, `DELETE /session/{id}`. +- Create sessions with `platformName` (`android`/`ios`/`web`), optional `deviceId`, `appId` (URL for web), and `driver` override. Web flags: `--headed`, `--browser`, `--window-size`/`--screen-size`, `--user-data-dir`. +- Execute JSON steps decoded into the same `flow.Step` types as YAML; selectors accept string or object. Returns JSON with `success`, `duration`, `message`. Malformed steps return 400. +- Supports DeviceLab/WDA/Appium drivers via the same factory as CLI. Session cleanup on SIGINT/SIGTERM. Worker-aware traces with redaction. From 27bd4dfe94cb6b6f7626715efa80fe480213d3e6 Mon Sep 17 00:00:00 2001 From: Prabhash Date: Sun, 25 Oct 2026 16:23:07 +0530 Subject: [PATCH 6/8] docs(llms): add reference to REST API server docs --- llms.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/llms.txt b/llms.txt index 7dacb616..3db6ca81 100644 --- a/llms.txt +++ b/llms.txt @@ -96,3 +96,4 @@ maestro-runner replaces the execution engine with a single Go binary and fixes a - Create sessions with `platformName` (`android`/`ios`/`web`), optional `deviceId`, `appId` (URL for web), and `driver` override. Web flags: `--headed`, `--browser`, `--window-size`/`--screen-size`, `--user-data-dir`. - Execute JSON steps decoded into the same `flow.Step` types as YAML; selectors accept string or object. Returns JSON with `success`, `duration`, `message`. Malformed steps return 400. - Supports DeviceLab/WDA/Appium drivers via the same factory as CLI. Session cleanup on SIGINT/SIGTERM. Worker-aware traces with redaction. +- See [docs/rest-api-server.md](docs/rest-api-server.md) for full details. From 26f2442c28874ab691ee81f6cfa204ec6e4646c6 Mon Sep 17 00:00:00 2001 From: Prabhash Date: Sun, 25 Oct 2026 16:31:37 +0530 Subject: [PATCH 7/8] docs(rest-api): list all iOS driver types --- docs/rest-api-server.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/rest-api-server.md b/docs/rest-api-server.md index 116296cf..eb52bb50 100644 --- a/docs/rest-api-server.md +++ b/docs/rest-api-server.md @@ -152,7 +152,7 @@ The server uses the same driver factory as the CLI. Sessions behave like a `test | Platform | Drivers | Notes | |----------|---------|-------| | `android` | DeviceLab (default), `uiautomator2`, `appium` | Set `"driver": "uiautomator2"` or `"appium"` in the session request. Appium requires `--appium-url` on the server or appropriate configuration. | -| `ios` | DeviceLab (default), `wda`, `appium` | Use `"driver": "wda"` for WebDriverAgent, or `"driver": "appium"`. WDA can be configured with flags like `--team-id`, `--wda-url`, `--reuse-wda` passed to `maestro-runner server`. | +| `ios` | DeviceLab (default), `wda`, `devicelab-legacy`, `appium` | Use `"driver": "wda"` for WebDriverAgent, or `"driver": "appium"`. `devicelab-legacy` selects the previous runner. WDA can be configured with flags like `--team-id`, `--wda-url`, `--reuse-wda` passed to `maestro-runner server`. | | `web` | Chrome/Chromium via CDP | Use `--browser`, `--headed`, `--window-size`. `appId` should be the URL to navigate to. | ## Notes From 5e13d73edfb861bc2ec982e6f011a3fa94aaff7e Mon Sep 17 00:00:00 2001 From: Prabhash Date: Sun, 25 Oct 2026 16:33:41 +0530 Subject: [PATCH 8/8] docs(rest-api): fix markdown table alignment --- docs/rest-api-server.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/rest-api-server.md b/docs/rest-api-server.md index eb52bb50..3c8caaeb 100644 --- a/docs/rest-api-server.md +++ b/docs/rest-api-server.md @@ -152,7 +152,7 @@ The server uses the same driver factory as the CLI. Sessions behave like a `test | Platform | Drivers | Notes | |----------|---------|-------| | `android` | DeviceLab (default), `uiautomator2`, `appium` | Set `"driver": "uiautomator2"` or `"appium"` in the session request. Appium requires `--appium-url` on the server or appropriate configuration. | -| `ios` | DeviceLab (default), `wda`, `devicelab-legacy`, `appium` | Use `"driver": "wda"` for WebDriverAgent, or `"driver": "appium"`. `devicelab-legacy` selects the previous runner. WDA can be configured with flags like `--team-id`, `--wda-url`, `--reuse-wda` passed to `maestro-runner server`. | +| `ios` | DeviceLab (default), `wda`, `devicelab-legacy`, `appium` | Use `"driver": "wda"` for WebDriverAgent or `"driver": "appium"`. `devicelab-legacy` selects the previous runner. WDA can be configured with flags like `--team-id`, `--wda-url`, `--reuse-wda` passed to `maestro-runner server`. | | `web` | Chrome/Chromium via CDP | Use `--browser`, `--headed`, `--window-size`. `appId` should be the URL to navigate to. | ## Notes