fix(sample-app): make it standalone, no repo_root assumptions (#8)

* fix(cli): fall back to node_modules for @uatu/spec resolution

Drop the hard failure when the uatu source tree is not reachable from
the spec file. Users integrating uatu in their own app have @uatu/spec
installed via npm; esbuild now resolves it from node_modules.

* build(gradle): drop :sample-app include from root settings

The sample now has its own Gradle project in examples/sample-app/android.

* build(sample-app): vendor gradle wrapper

Users running the sample build the APK via ./gradlew from inside the
sample-app's own android/ directory, no repo-root wrapper required.

* build(sample-app): make gradle project standalone

Drop the project(':sdk-android') dependency in favor of the Maven
Central coordinate io.github.priyanshujain:sdk-android. The sample now
owns its settings.gradle.kts and gradle.properties, so it builds
without any pieces of the uatu source tree.

* chore(sample-app): declare @uatu/spec npm dependency

Mirrors what a downstream user would put in their own package.json.
Uses file: for pre-release development; becomes a normal semver pin
once @uatu/spec ships to npm.

* docs(sample-app): rewrite justfile and add README

Justfile drops repo_root; all recipes run against the local gradle
wrapper and uatu from PATH. README is scoped to what a user needs to
run the sample against their own device.

* docs(manual): update sample install steps to standalone layout

./gradlew :sample-app:installDebug no longer exists; the sample owns
its own wrapper under android/.

* feat(sdk): log when Uatu.start succeeds

Silent SDK start makes the "SDK didn't connect" failure mode
impossible to debug. One INFO line at start time is enough.

* fix(sidecar): launch via am start -W instead of monkey

monkey -p <pkg> -c LAUNCHER 1 is unreliable on API 36+: it reports no
error but silently fails to start the activity, so the SDK never runs
and the CLI times out on the SDK-accept handshake.

Resolve the launcher activity via `cmd package resolve-activity
--brief` and launch it with `am start -W -n`. -W makes the call block
until the activity is up, which also makes the subsequent SDK
accept timing deterministic.

* feat(cli): auto-resolve Android device; boot AVD if none connected

--avd becomes optional. Resolution order:
 - use any already-connected adb device;
 - else if --avd names an existing AVD, boot it and wait for boot;
 - else if --avd is missing or names no AVD, error with a clear message.

Falls back to $ANDROID_HOME/emulator/emulator when the binary is not on
PATH, so a standard Android SDK install works without extra shell setup.

* docs(sample-app): AVD is optional; document both paths

just test runs against any connected device. If none, pass AVD=<name>
to have uatu boot the emulator for you.

* feat(cli): auto-discover Android SDK; auto-pick the lone AVD

adb and emulator are looked up via PATH, then $ANDROID_HOME,
$ANDROID_SDK_ROOT, ~/Library/Android/sdk, ~/Android/Sdk, and the
Homebrew cask path. The discovered platform-tools directory is
prepended to the sidecar's PATH so its adb subprocess calls work too.

When --avd isn't passed and no device is connected, the CLI picks the
sole local AVD and boots it. Multiple AVDs → error listing them.

* build(make): add `make install` that go-installs uatu onto PATH

Puts `uatu` into $GOBIN (or $GOPATH/bin) so the sample and any local
dev flow can call it without PATH= prefixes.

* docs(sample-app): zero-config just test; dotenv-load for persistence

Drop the expectation that users prefix commands with PATH=, ANDROID_HOME=,
or AVD=. `just test` now works as-is; optional knobs can be pinned in a
.env file alongside the justfile.

* fix(sample-app): auto-detect ANDROID_HOME for Gradle tasks

The Go CLI finds the SDK itself, but AGP still needs ANDROID_HOME to
resolve `sdk.dir`. The justfile now resolves it from env or canonical
install paths before invoking ./gradlew, so `just install` works out
of the box on a standard Android SDK setup.

* gitignore runs directory for sample app
This commit is contained in:
pj authored and GitHub committed 2026-04-18 15:31:47 +07:00
1 parent bf733f4f93
commit 6b1c17328c
26 files changed
+1098 -65

No files matched your search

+235
View File
@@ -0,0 +1,235 @@
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"time"
)
// ensureDevice makes sure an Android device is ready for adb commands.
// Resolution order:
// - if an adb device is already online, use it;
// - else if avdName is set, validate and boot it;
// - else if exactly one AVD exists locally, boot it;
// - else fail with a helpful message listing the available AVDs.
func ensureDevice(ctx context.Context, avdName string, stdout io.Writer) error {
devices, err := listAdbDevices(ctx)
if err != nil {
return fmt.Errorf("list adb devices: %w", err)
}
if len(devices) > 0 {
fmt.Fprintf(stdout, "using connected device: %s\n", devices[0])
return nil
}
avds, err := listAVDs(ctx)
if err != nil {
return fmt.Errorf("list AVDs: %w", err)
}
target, err := pickAVD(avdName, avds)
if err != nil {
return err
}
fmt.Fprintf(stdout, "booting AVD %q...\n", target)
if err := bootAVD(ctx, target); err != nil {
return fmt.Errorf("boot AVD %q: %w", target, err)
}
if err := waitForBoot(ctx, 180*time.Second); err != nil {
return fmt.Errorf("wait for AVD boot: %w", err)
}
fmt.Fprintf(stdout, "AVD %q ready\n", target)
return nil
}
func pickAVD(requested string, available []string) (string, error) {
if requested != "" {
if !slices.Contains(available, requested) {
return "", fmt.Errorf("AVD %q does not exist (available: %s)", requested, strings.Join(available, ", "))
}
return requested, nil
}
switch len(available) {
case 0:
return "", fmt.Errorf("no android device connected and no AVD found; create one in Android Studio or `avdmanager create avd`")
case 1:
return available[0], nil
default:
return "", fmt.Errorf("no android device connected and multiple AVDs available (%s); pick one with --avd", strings.Join(available, ", "))
}
}
func listAdbDevices(ctx context.Context) ([]string, error) {
adb, err := adbBinary()
if err != nil {
return nil, err
}
output, err := exec.CommandContext(ctx, adb, "devices").Output()
if err != nil {
return nil, err
}
return parseAdbDevices(string(output)), nil
}
func parseAdbDevices(output string) []string {
var serials []string
scanner := bufio.NewScanner(strings.NewReader(output))
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "List of devices") {
continue
}
fields := strings.Fields(line)
if len(fields) >= 2 && fields[1] == "device" {
serials = append(serials, fields[0])
}
}
return serials
}
func listAVDs(ctx context.Context) ([]string, error) {
emulator, err := emulatorBinary()
if err != nil {
return nil, err
}
output, err := exec.CommandContext(ctx, emulator, "-list-avds").Output()
if err != nil {
return nil, err
}
return parseAVDList(string(output)), nil
}
func adbBinary() (string, error) { return findAndroidTool("adb", "platform-tools") }
func emulatorBinary() (string, error) { return findAndroidTool("emulator", "emulator") }
// findAndroidTool locates a binary from the Android SDK. It checks PATH,
// then $ANDROID_HOME/<subdir>/<name> and $ANDROID_SDK_ROOT/<subdir>/<name>,
// then the canonical install locations used by Android Studio and Homebrew.
// Returns a descriptive error when nothing works, so the user knows to set
// $ANDROID_HOME instead of getting a raw "executable file not found".
func findAndroidTool(name, subdir string) (string, error) {
if path, err := exec.LookPath(name); err == nil {
return path, nil
}
var tried []string
for _, root := range androidSDKCandidates() {
candidate := filepath.Join(root, subdir, name)
if info, err := os.Stat(candidate); err == nil && !info.IsDir() {
return candidate, nil
}
tried = append(tried, candidate)
}
return "", fmt.Errorf("could not locate %q: not on PATH and not under any known Android SDK root (set $ANDROID_HOME to point at your SDK; tried %v)", name, tried)
}
func androidSDKCandidates() []string {
var roots []string
seen := map[string]bool{}
addRoot := func(path string) {
if path == "" || seen[path] {
return
}
seen[path] = true
roots = append(roots, path)
}
addRoot(os.Getenv("ANDROID_HOME"))
addRoot(os.Getenv("ANDROID_SDK_ROOT"))
if home, err := os.UserHomeDir(); err == nil {
addRoot(filepath.Join(home, "Library", "Android", "sdk"))
addRoot(filepath.Join(home, "Android", "Sdk"))
}
addRoot("/opt/homebrew/share/android-commandlinetools")
addRoot("/usr/local/share/android-commandlinetools")
return roots
}
func parseAVDList(output string) []string {
var avds []string
scanner := bufio.NewScanner(strings.NewReader(output))
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" || strings.HasPrefix(line, "INFO") {
continue
}
avds = append(avds, line)
}
return avds
}
func bootAVD(_ context.Context, name string) error {
emulator, err := emulatorBinary()
if err != nil {
return err
}
command := exec.Command(emulator, "-avd", name, "-no-snapshot-save", "-no-audio", "-no-boot-anim")
if err := command.Start(); err != nil {
return err
}
go func() { _ = command.Wait() }()
return nil
}
func waitForBoot(ctx context.Context, timeout time.Duration) error {
deadline, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
ticker := time.NewTicker(2 * time.Second)
defer ticker.Stop()
for {
if completed, _ := bootCompleted(deadline); completed {
return nil
}
select {
case <-deadline.Done():
return deadline.Err()
case <-ticker.C:
}
}
}
// envWithAndroidPlatformTools returns env with the directory containing adb
// prepended to PATH, so child processes (the sidecar) can invoke adb even
// when the user hasn't set up their shell PATH.
func envWithAndroidPlatformTools(env []string) []string {
adb, err := adbBinary()
if err != nil {
return env
}
adbDir := filepath.Dir(adb)
result := make([]string, 0, len(env))
found := false
for _, entry := range env {
if current, ok := strings.CutPrefix(entry, "PATH="); ok {
if !pathContains(current, adbDir) {
entry = "PATH=" + adbDir + string(os.PathListSeparator) + current
}
found = true
}
result = append(result, entry)
}
if !found {
result = append(result, "PATH="+adbDir)
}
return result
}
func pathContains(path, directory string) bool {
return slices.Contains(strings.Split(path, string(os.PathListSeparator)), directory)
}
func bootCompleted(ctx context.Context) (bool, error) {
adb, err := adbBinary()
if err != nil {
return false, err
}
output, err := exec.CommandContext(ctx, adb, "shell", "getprop", "sys.boot_completed").Output()
if err != nil {
return false, err
}
return strings.TrimSpace(string(output)) == "1", nil
}
+93
View File
@@ -0,0 +1,93 @@
package main
import (
"reflect"
"testing"
)
func TestParseAdbDevices_OnlineOnly(t *testing.T) {
output := `List of devices attached
emulator-5554 device
emulator-5556 offline
physical-abc device
`
got := parseAdbDevices(output)
want := []string{"emulator-5554", "physical-abc"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v, want %v", got, want)
}
}
func TestParseAdbDevices_Empty(t *testing.T) {
output := "List of devices attached\n\n"
got := parseAdbDevices(output)
if len(got) != 0 {
t.Fatalf("got %v, want empty", got)
}
}
func TestParseAVDList_DropsInfoLines(t *testing.T) {
output := `INFO | Storing crashdata in: /tmp/x
Medium_Phone_API_36.0
uatu_test
`
got := parseAVDList(output)
want := []string{"Medium_Phone_API_36.0", "uatu_test"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v, want %v", got, want)
}
}
func TestPickAVD_ExplicitName(t *testing.T) {
got, err := pickAVD("Pixel_7", []string{"Pixel_7", "uatu_test"})
if err != nil {
t.Fatal(err)
}
if got != "Pixel_7" {
t.Fatalf("got %q, want Pixel_7", got)
}
}
func TestPickAVD_ExplicitMissing(t *testing.T) {
_, err := pickAVD("Nope", []string{"Pixel_7"})
if err == nil {
t.Fatal("expected error")
}
}
func TestPickAVD_SingleAvailable(t *testing.T) {
got, err := pickAVD("", []string{"uatu_test"})
if err != nil {
t.Fatal(err)
}
if got != "uatu_test" {
t.Fatalf("got %q, want uatu_test", got)
}
}
func TestPickAVD_AmbiguousWithoutHint(t *testing.T) {
_, err := pickAVD("", []string{"a", "b"})
if err == nil {
t.Fatal("expected error when multiple AVDs and no --avd")
}
}
func TestPickAVD_NoneAvailable(t *testing.T) {
_, err := pickAVD("", nil)
if err == nil {
t.Fatal("expected error when no AVDs exist")
}
}
func TestPathContains(t *testing.T) {
path := "/usr/bin:/opt/tools:/usr/local/bin"
if !pathContains(path, "/opt/tools") {
t.Error("expected /opt/tools in PATH")
}
if pathContains(path, "/nope") {
t.Error("did not expect /nope in PATH")
}
}
+1 -4
View File
@@ -46,7 +46,7 @@ func parseTestArgs(args []string, stderr io.Writer) (testOptions, error) {
flagSet.StringVar(&options.bundleID, "bundle-id", "", "target app bundle ID (required)")
flagSet.StringVar(&options.launcherActivity, "launcher-activity", "", "optional <pkg>/<activity> to launch (overrides default resolution)")
flagSet.StringVar(&options.platform, "platform", "android", "target platform: android (ios deferred)")
flagSet.StringVar(&options.avd, "avd", "", "Android AVD name (required on android)")
flagSet.StringVar(&options.avd, "avd", "", "Android AVD name to boot if no device is connected")
flagSet.DurationVar(&options.duration, "duration", 5*time.Minute, "total test duration")
flagSet.Int64Var(&options.seed, "seed", 0, "RNG seed (0 = random)")
flagSet.StringVar(&options.output, "output", "./runs", "output directory for traces")
@@ -59,9 +59,6 @@ func parseTestArgs(args []string, stderr io.Writer) (testOptions, error) {
if options.bundleID == "" {
return testOptions{}, errors.New("--bundle-id is required")
}
if options.platform == "android" && options.avd == "" {
return testOptions{}, errors.New("--avd is required on android")
}
if options.platform != "android" {
return testOptions{}, fmt.Errorf("unsupported platform: %q (only android in v0.1)", options.platform)
}
+22 -10
View File
@@ -66,10 +66,13 @@ func TestParseTestArgs_RequiresBundleID(t *testing.T) {
}
}
func TestParseTestArgs_RequiresAVDOnAndroid(t *testing.T) {
_, err := parseTestArgs([]string{"--spec", "s.ts", "--bundle-id", "com.example"}, io.Discard)
if err == nil || !strings.Contains(err.Error(), "--avd") {
t.Fatalf("expected missing --avd error, got %v", err)
func TestParseTestArgs_AVDIsOptional(t *testing.T) {
options, err := parseTestArgs([]string{"--spec", "s.ts", "--bundle-id", "com.example"}, io.Discard)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if options.avd != "" {
t.Fatalf("avd default: got %q, want empty", options.avd)
}
}
@@ -129,16 +132,25 @@ func TestRun_Doctor(t *testing.T) {
}
}
func TestRun_TestSubcommand_ReportsBundleErrorForMissingSpec(t *testing.T) {
// Without a real spec file the pipeline should fail at the bundle step
// rather than panicking — proves the flag wiring reaches the runner.
func TestRun_TestSubcommand_PipelineErrors(t *testing.T) {
// Without a real spec, a real device, or a bootable AVD the pipeline
// must surface a specific error rather than panicking — proves the flag
// wiring reaches the runner.
err := run([]string{
"uatu", "test",
"--spec", "definitely-missing-spec.ts",
"--bundle-id", "com.example",
"--avd", "Pixel_5_API_33",
"--avd", "definitely-missing-avd",
}, io.Discard, io.Discard)
if err == nil || !strings.Contains(err.Error(), "bundle") {
t.Errorf("expected bundle error, got %v", err)
if err == nil {
t.Fatal("expected error, got nil")
}
message := err.Error()
ok := strings.Contains(message, "bundle") ||
strings.Contains(message, "device") ||
strings.Contains(message, "AVD") ||
strings.Contains(message, "emulator")
if !ok {
t.Errorf("expected pipeline error (bundle/device/AVD/emulator), got %v", err)
}
}
+27 -12
View File
@@ -28,9 +28,14 @@ const (
)
func runTestPipeline(ctx context.Context, options testOptions, stdout io.Writer) error {
specApiPath, err := resolveSpecAPIPath(options.spec)
if err != nil {
return err
if options.platform == "android" {
if err := ensureDevice(ctx, options.avd, stdout); err != nil {
return err
}
}
aliases := map[string]string{}
if specApiPath := resolveSpecAPIPath(options.spec); specApiPath != "" {
aliases["@uatu/spec"] = specApiPath
}
bundle, err := bundler.Bundle(bundler.Options{
EntryFile: options.spec,
@@ -38,7 +43,7 @@ func runTestPipeline(ctx context.Context, options testOptions, stdout io.Writer)
"UATU_TEST_PHONE": os.Getenv("UATU_TEST_PHONE"),
"UATU_TEST_OTP": os.Getenv("UATU_TEST_OTP"),
},
Aliases: map[string]string{"@uatu/spec": specApiPath},
Aliases: aliases,
})
if err != nil {
return fmt.Errorf("bundle spec: %w", err)
@@ -62,6 +67,7 @@ func runTestPipeline(ctx context.Context, options testOptions, stdout io.Writer)
)
sidecarCommand.Stdout = stdout
sidecarCommand.Stderr = stdout
sidecarCommand.Env = envWithAndroidPlatformTools(os.Environ())
if err := sidecarCommand.Start(); err != nil {
return fmt.Errorf("spawn sidecar: %w", err)
}
@@ -193,10 +199,11 @@ func runTestPipeline(ctx context.Context, options testOptions, stdout io.Writer)
return nil
}
// resolveSpecAPIPath finds pkg/spec-api/src/index.ts relative to the spec
// file or the current working directory so the bundler can resolve
// `@uatu/spec` imports.
func resolveSpecAPIPath(specPath string) (string, error) {
// resolveSpecAPIPath returns the path to pkg/spec-api/src/index.ts inside
// a uatu source checkout, searched upward from the spec file and the cwd.
// Returns "" when not found, in which case esbuild resolves @uatu/spec via
// node_modules the way a downstream user's project would.
func resolveSpecAPIPath(specPath string) string {
candidates := []string{}
if absoluteSpec, err := filepath.Abs(specPath); err == nil {
directory := filepath.Dir(absoluteSpec)
@@ -214,10 +221,10 @@ func resolveSpecAPIPath(specPath string) (string, error) {
}
for _, candidate := range candidates {
if _, err := os.Stat(candidate); err == nil {
return candidate, nil
return candidate
}
}
return "", fmt.Errorf("could not locate pkg/spec-api/src/index.ts (searched %d paths)", len(candidates))
return ""
}
func pickFreePort() (int, error) {
@@ -230,10 +237,18 @@ func pickFreePort() (int, error) {
}
func adbReverse(socket string, port int) error {
command := exec.Command("adb", "reverse", "localabstract:"+socket, fmt.Sprintf("tcp:%d", port))
adb, err := adbBinary()
if err != nil {
return err
}
command := exec.Command(adb, "reverse", "localabstract:"+socket, fmt.Sprintf("tcp:%d", port))
return command.Run()
}
func adbReverseRemove(socket string) error {
return exec.Command("adb", "reverse", "--remove", "localabstract:"+socket).Run()
adb, err := adbBinary()
if err != nil {
return err
}
return exec.Command(adb, "reverse", "--remove", "localabstract:"+socket).Run()
}
+52
View File
@@ -0,0 +1,52 @@
package main
import (
"os"
"path/filepath"
"testing"
)
func TestResolveSpecAPIPath_FindsUpwardSibling(t *testing.T) {
root := t.TempDir()
apiPath := filepath.Join(root, "pkg", "spec-api", "src", "index.ts")
if err := os.MkdirAll(filepath.Dir(apiPath), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(apiPath, []byte("export {}"), 0o644); err != nil {
t.Fatal(err)
}
specPath := filepath.Join(root, "examples", "app", "spec.ts")
if err := os.MkdirAll(filepath.Dir(specPath), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(specPath, []byte(""), 0o644); err != nil {
t.Fatal(err)
}
got := resolveSpecAPIPath(specPath)
if got != apiPath {
t.Fatalf("got %q, want %q", got, apiPath)
}
}
func TestResolveSpecAPIPath_ReturnsEmptyWhenMissing(t *testing.T) {
root := t.TempDir()
specPath := filepath.Join(root, "spec.ts")
if err := os.WriteFile(specPath, []byte(""), 0o644); err != nil {
t.Fatal(err)
}
cwd, err := os.Getwd()
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { _ = os.Chdir(cwd) })
if err := os.Chdir(root); err != nil {
t.Fatal(err)
}
got := resolveSpecAPIPath(specPath)
if got != "" {
t.Fatalf("got %q, want empty (no uatu source tree reachable)", got)
}
}