Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
86 changes: 17 additions & 69 deletions internal/dev/flutter.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,15 @@ package dev
import (
"bufio"
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"

"github.com/MobAI-App/ios-builder/internal/config"
"github.com/MobAI-App/ios-builder/internal/hotreload"
"github.com/MobAI-App/ios-builder/internal/mobai"
)

Expand Down Expand Up @@ -82,7 +79,6 @@ func (h *FlutterHandler) Stop() {
}

func (h *FlutterHandler) findDebugURL(ctx context.Context, debugOutput <-chan mobai.DebugOutput) (string, <-chan mobai.DebugOutput, error) {
re := regexp.MustCompile(`(?:Observatory|Dart VM service)[^h]*(http://[^\s]+)`)
timeout := time.After(30 * time.Second)

for {
Expand All @@ -98,9 +94,9 @@ func (h *FlutterHandler) findDebugURL(ctx context.Context, debugOutput <-chan mo
if output.Type == "error" {
return "", nil, fmt.Errorf("debug error: %s", output.Message)
}
if m := re.FindStringSubmatch(output.Data); len(m) >= 2 {
fmt.Printf("Found debug service: %s\n", m[1])
return m[1], debugOutput, nil
if u := hotreload.VMServiceURL(output.Data); u != "" {
fmt.Printf("Found debug service: %s\n", u)
return u, debugOutput, nil
}
}
}
Expand Down Expand Up @@ -186,7 +182,7 @@ func (h *FlutterHandler) startFileWatcher(ctx context.Context) {
watchCtx, cancel := context.WithCancel(ctx)
h.cancelWatch = cancel

cfg := FileWatcherConfig{
cfg := hotreload.FileWatcherConfig{
Dirs: h.watchConfig.Dirs,
Patterns: h.watchConfig.Patterns,
Ignore: h.watchConfig.Ignore,
Expand All @@ -197,11 +193,11 @@ func (h *FlutterHandler) startFileWatcher(ctx context.Context) {
},
}

if needsPolling(cfg.Dirs) {
if hotreload.NeedsPolling(cfg.Dirs) {
fmt.Println("\n[builder] WSL2 detected, using polling watcher for Windows filesystem")
h.watcher = NewPollingWatcher(&cfg)
h.watcher = hotreload.NewPollingWatcher(&cfg)
} else {
w, err := NewFileWatcher(&cfg)
w, err := hotreload.NewFileWatcher(&cfg)
if err != nil {
fmt.Printf("\n[builder] Warning: failed to start file watcher: %v\n", err)
return
Expand All @@ -220,66 +216,18 @@ func (h *FlutterHandler) startFileWatcher(ctx context.Context) {

// EnsureCustomDevice ensures Flutter custom_devices.json has mobai-ios configured.
func EnsureCustomDevice(mobaiURL string) error {
if err := exec.Command("flutter", "config", "--enable-custom-devices").Run(); err != nil {
return fmt.Errorf("failed to enable custom devices - run 'flutter config --enable-custom-devices' manually first: %w", err)
}

var configPath string
if runtime.GOOS == "windows" {
appData := os.Getenv("APPDATA")
if appData == "" {
return fmt.Errorf("APPDATA environment variable not set")
}
configPath = filepath.Join(appData, ".flutter_custom_devices.json")
} else {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("get home dir: %w", err)
}
flutterDir := filepath.Join(homeDir, ".config", "flutter")
if err := os.MkdirAll(flutterDir, 0755); err != nil {
return fmt.Errorf("create flutter config dir: %w", err)
}
configPath = filepath.Join(flutterDir, "custom_devices.json")
}

execPath, err := os.Executable()
if err != nil {
return fmt.Errorf("get executable path: %w", err)
}

pingCmd := []string{execPath, "mobai", "--url", mobaiURL, "ping"}
installCmd := []string{execPath, "mobai", "--url", mobaiURL, "install", "${localPath}"}
runDebugCmd := []string{execPath, "mobai", "--url", mobaiURL, "run-debug", "${appName}"}
forwardCmd := []string{execPath, "mobai", "--url", mobaiURL, "forward", "${devicePort}", "${hostPort}"}

config := map[string]any{
"custom-devices": []any{
map[string]any{
"id": "mobai-ios",
"label": "MobAI iOS Device",
"sdkNameAndVersion": "iOS (via MobAI)",
"platform": nil,
"enabled": true,
"ping": pingCmd,
"pingSuccessRegex": "success",
"install": installCmd,
"uninstall": []string{"echo", "uninstall not supported"},
"runDebug": runDebugCmd,
"forwardPort": forwardCmd,
"forwardPortSuccessRegex": "forwarded",
},
},
}

output, err := json.MarshalIndent(config, "", " ")
if err != nil {
return fmt.Errorf("marshal config: %w", err)
}

if err := os.WriteFile(configPath, output, 0644); err != nil {
return fmt.Errorf("write config: %w", err)
}

return nil
return hotreload.WriteCustomDevice(&hotreload.CustomDevice{
Ping: []string{execPath, "mobai", "--url", mobaiURL, "ping"},
PingSuccessRegex: "success",
Install: []string{execPath, "mobai", "--url", mobaiURL, "install", "${localPath}"},
Uninstall: []string{"echo", "uninstall not supported"},
RunDebug: []string{execPath, "mobai", "--url", mobaiURL, "run-debug", "${appName}"},
ForwardPort: []string{execPath, "mobai", "--url", mobaiURL, "forward", "${devicePort}", "${hostPort}"},
ForwardPortSuccessRegex: "forwarded",
})
}
37 changes: 4 additions & 33 deletions internal/dev/reactnative.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"strings"
"time"

"github.com/MobAI-App/ios-builder/internal/hotreload"
"github.com/MobAI-App/ios-builder/internal/mobai"
)

Expand Down Expand Up @@ -63,7 +64,7 @@ func (h *ReactNativeHandler) Setup(ctx context.Context) error {

// Attach monitors app output for React Native development.
func (h *ReactNativeHandler) Attach(ctx context.Context, deviceID string, debugOutput <-chan mobai.DebugOutput) error {
ip := getLocalIP()
ip := hotreload.LocalIP()

fmt.Println()
fmt.Printf("Metro bundler: http://%s:%d\n", ip, h.metroPort)
Expand Down Expand Up @@ -105,14 +106,12 @@ func (h *ReactNativeHandler) Attach(ctx context.Context, deviceID string, debugO
// DebugConfig returns launch arguments to configure Metro connection.
// React Native reads RCT_jsLocation from NSUserDefaults, which can be set via launch arguments.
func (h *ReactNativeHandler) DebugConfig() *mobai.DebugConfig {
ip := getLocalIP()
ip := hotreload.LocalIP()

fmt.Printf("Detected host IP: %s\n", ip)

jsLocation := fmt.Sprintf("%s:%d", ip, h.metroPort)

return &mobai.DebugConfig{
Arguments: []string{"-RCT_jsLocation", jsLocation},
Arguments: hotreload.MetroLaunchArguments(ip, h.metroPort),
}
}

Expand Down Expand Up @@ -193,31 +192,3 @@ func getWorkingDir() string {
}
return wd
}

func getLocalIP() string {
if isWSL() {
cmd := exec.Command("powershell.exe", "-NoProfile", "-Command",
`Get-NetIPAddress -AddressFamily IPv4 | Where-Object { ($_.IPAddress -notlike "169.*") -and ($_.IPAddress -notlike "127.*") -and ($_.IPAddress -notlike "172.*") } | Select-Object -First 1 -ExpandProperty IPAddress`)
output, err := cmd.Output()
if err != nil {
return "localhost"
}
ip := strings.TrimSpace(string(output))
if ip == "" {
return "localhost"
}
return ip
}

conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
return "localhost"
}
defer func() { _ = conn.Close() }()

localAddr, ok := conn.LocalAddr().(*net.UDPAddr)
if !ok {
return "localhost"
}
return localAddr.IP.String()
}
99 changes: 99 additions & 0 deletions internal/hotreload/customdevice.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
package hotreload

import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
)

// CustomDeviceID is the Flutter device id of the MobAI iOS custom device:
// flutter attach -d mobai-ios.
const CustomDeviceID = "mobai-ios"

// CustomDevice is the commands Flutter's custom device runs for the MobAI
// iOS device. Flutter fills in ${localPath}, ${appName}, ${devicePort} and
// ${hostPort}; each success regex must match a line of the command's output.
// Flutter keeps the forward command running for the life of the forward and
// takes its exit as a failed forward.
type CustomDevice struct {
Ping []string
PingSuccessRegex string
Install []string
Uninstall []string
RunDebug []string
ForwardPort []string
ForwardPortSuccessRegex string
}

// WriteCustomDevice turns on Flutter's custom devices and writes d as the
// mobai-ios device to Flutter's custom_devices.json.
func WriteCustomDevice(d *CustomDevice) error {
if err := exec.Command("flutter", "config", "--enable-custom-devices").Run(); err != nil {
return fmt.Errorf("failed to enable custom devices - run 'flutter config --enable-custom-devices' manually first: %w", err)
}

var configPath string
if runtime.GOOS == "windows" {
appData := os.Getenv("APPDATA")
if appData == "" {
return fmt.Errorf("APPDATA environment variable not set")
}
configPath = filepath.Join(appData, ".flutter_custom_devices.json")
} else {
homeDir, err := os.UserHomeDir()
if err != nil {
return fmt.Errorf("get home dir: %w", err)
}
flutterDir := filepath.Join(homeDir, ".config", "flutter")
if err := os.MkdirAll(flutterDir, 0755); err != nil {
return fmt.Errorf("create flutter config dir: %w", err)
}
configPath = filepath.Join(flutterDir, "custom_devices.json")
}

config := map[string]any{
"custom-devices": []any{
map[string]any{
"id": CustomDeviceID,
"label": "MobAI iOS Device",
"sdkNameAndVersion": "iOS (via MobAI)",
"platform": nil,
"enabled": true,
"ping": d.Ping,
"pingSuccessRegex": d.PingSuccessRegex,
"install": d.Install,
"uninstall": d.Uninstall,
"runDebug": d.RunDebug,
"forwardPort": d.ForwardPort,
"forwardPortSuccessRegex": d.ForwardPortSuccessRegex,
},
},
}

output, err := json.MarshalIndent(config, "", " ")
if err != nil {
return fmt.Errorf("marshal config: %w", err)
}

if err := os.WriteFile(configPath, output, 0644); err != nil {
return fmt.Errorf("write config: %w", err)
}

return nil
}

// vmServiceRE finds the Dart VM service URL a debug build prints at launch.
var vmServiceRE = regexp.MustCompile(`(?:Observatory|Dart VM service)[^h]*(http://[^\s]+)`)

// VMServiceURL returns the Dart VM service URL in a line of a Flutter debug
// build's output, or "".
func VMServiceURL(line string) string {
if m := vmServiceRE.FindStringSubmatch(line); len(m) >= 2 {
return m[1]
}
return ""
}
19 changes: 19 additions & 0 deletions internal/hotreload/customdevice_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package hotreload

import "testing"

func TestVMServiceURL(t *testing.T) {
tests := []struct {
line string
want string
}{
{"flutter: The Dart VM service is listening on http://127.0.0.1:52361/kKx2tUbXYuM=/", "http://127.0.0.1:52361/kKx2tUbXYuM=/"},
{"Observatory listening on http://127.0.0.1:1024/abc=/\n", "http://127.0.0.1:1024/abc=/"},
{"flutter: hello", ""},
}
for _, tt := range tests {
if got := VMServiceURL(tt.line); got != tt.want {
t.Errorf("VMServiceURL(%q) = %q, want %q", tt.line, got, tt.want)
}
}
}
46 changes: 46 additions & 0 deletions internal/hotreload/metro.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package hotreload

import (
"fmt"
"net"
"os/exec"
"strings"
)

// MetroLaunchArguments are the launch arguments that point a React Native
// debug build at the Metro bundler on host:port. React Native reads
// RCT_jsLocation from NSUserDefaults, which launch arguments set.
func MetroLaunchArguments(host string, port int) []string {
return []string{"-RCT_jsLocation", fmt.Sprintf("%s:%d", host, port)}
}

// LocalIP is this machine's address on the local network, the one a phone on
// the same Wi-Fi reaches it at; under WSL, the Windows host's. "localhost"
// when there is none.
func LocalIP() string {
if isWSL2() {
cmd := exec.Command("powershell.exe", "-NoProfile", "-Command",
`Get-NetIPAddress -AddressFamily IPv4 | Where-Object { ($_.IPAddress -notlike "169.*") -and ($_.IPAddress -notlike "127.*") -and ($_.IPAddress -notlike "172.*") } | Select-Object -First 1 -ExpandProperty IPAddress`)
output, err := cmd.Output()
if err != nil {
return "localhost"
}
ip := strings.TrimSpace(string(output))
if ip == "" {
return "localhost"
}
return ip
}

conn, err := net.Dial("udp", "8.8.8.8:80")
if err != nil {
return "localhost"
}
defer func() { _ = conn.Close() }()

localAddr, ok := conn.LocalAddr().(*net.UDPAddr)
if !ok {
return "localhost"
}
return localAddr.IP.String()
}
Loading
Loading