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
3 changes: 3 additions & 0 deletions .github/workflows/apple.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@ concurrency:
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true

# 仓库公开后,fork 提的 PR 默认不在自托管 runner 上跑(避免陌生代码在本机执行);
# 只有源仓库自己分支的 PR、push 到 main、或手动触发才会实际执行 job。
jobs:
apple:
name: Apple
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
runs-on: [self-hosted, qc-macos]
timeout-minutes: 30
steps:
Expand Down
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@ concurrency:
# PR 只跑 ubuntu;push main 与手动触发跑 ubuntu + macOS。
# Windows 暂无本地 runner,全矩阵里已移除——Windows 验证(含 G2 Job Object 真机)
# 仍待 Actions 配额恢复或接入 Windows 主机后补。
# 仓库公开后,fork 提的 PR 默认不在自托管 runner 上跑(避免陌生代码在本机执行);
# 只有源仓库自己分支的 PR、push 到 main、或手动触发才会实际执行 job。
jobs:
rust:
name: Rust (${{ matrix.os }})
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
strategy:
fail-fast: false
matrix:
Expand Down Expand Up @@ -59,6 +62,7 @@ jobs:

gui:
name: GUI (${{ matrix.os }})
if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository
strategy:
fail-fast: false
matrix:
Expand Down
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,5 @@ DerivedData/
selfIdentity.plist
# third-party WebDriverAgent checkout used for real-device acceptance
/WebDriverAgent/
# Claude Code session scaffolding (launch.json, agent worktrees) — local only
/.claude/
2 changes: 2 additions & 0 deletions agents/ios-wda/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ macOS 26.5 host, go-ios 1.2.1.
| Capture vs tunnel ordering | starting **or** stopping the capture re-enumerates USB: every live `ios tunnel start --userspace` connection failed at that instant and the WDA runner died with `lost connection to testmanagerd`. Rule: capture first, then tunnel and WDA; after the capture stops, restart both |
| Side effects on the device | the status bar shows Apple's demo values (9:41, full battery, no carrier) while captured; iOS 26 asked for the device passcode once ("验证以访问 XCTest") when WDA was relaunched after a long idle |
| `wda/tap` re-timed (2026-09-16, three fresh sessions, home screen and Settings, capture on and off) | **0.81–1.49 s per tap**, `wda/dragfromtoforduration` 1.7–3.1 s, `pressButton home` 0.51 s. The **0.01 s** in the row above was a **404 on an invalidated session** (a tap against a dead session id answers in ~25 ms; the GUI's probe session had just been invalidated by a second `POST /session`), not a real tap. `waitForIdleTimeout` 0, `animationCoolOffTimeout` 0, `defaultActiveApplication` set, `snapshotMaxDepth` 1 and `wda/touchAndHold` change nothing: the time is XCTest event synthesis itself. ~1 s per gesture is the control-side floor |
| Gate 1 of P4.4 (2026-09-16, phone re-plugged first): probe `--serve` (CoreImage JPEG, quality 0.5) → existing proxy → GUI `<img>` in `LaunchMode::Attach` | probe: **58–60 fps capture on the home screen, JPEG encode 7.6–9.6 ms/frame, 50–100 KB/frame**; proxy took 54–60 parts/s; GUI label 58 fps. Render side (rAF + canvas pixel diff, changed frames per second): **50–56 in every second fully inside a 2 s home-screen drag**, median 32 across 8 drags (each 2 s of motion + 1.4 s idle). The Clock stopwatch page is not a valid motion source: the device sends only **30 fps** there (the app runs its display at 30 Hz) and the render count matched it 1:1. `requestAnimationFrame` stops entirely while the Mac is locked or the window is occluded, and the capture itself stalls to ~0.2 fps while the Mac is locked |
| Drag latency through the GUI's own session (2026-09-16) | `wda/dragfromtoforduration` with `duration` 2.0 returned after **3.4–3.5 s** each time (8 samples); the ~1.4 s overhead on top of the requested duration is the XCTest floor already seen for taps |
| Windows availability (desk research) | upstream gave up Windows; `chotgpt/quicktime_video_hack_windows` (C++ rewrite, MIT, commits to 2026-03) needs a replacement usbmuxd on port 37015 plus a libusb0 or filter driver that conflicts with Apple's driver |

Conclusion for engine selection: the stream is 2.5–3× the frame rate of the MJPEG path
Expand Down
197 changes: 164 additions & 33 deletions agents/ios-wda/tools/avprobe.swift
Original file line number Diff line number Diff line change
@@ -1,15 +1,40 @@
// avprobe: capture the iPhone screen via Apple's CoreMediaIO/AVFoundation path
// (the same USB "Valeria" interface qvh uses) and stamp every frame with the
// host wall clock plus a luma-difference score against the previous frame.
// (the same USB "Valeria" interface QuickTime Player uses).
//
// Two modes:
// avprobe <seconds> <frames.tsv> stamp every frame (wall clock, PTS, luma diff)
// avprobe --serve <port> [--quality q] JPEG-encode every frame and serve it as an
// MJPEG stream shaped like WDA's (HTTP/1.0,
// boundary --BoundaryString, Content-Length per
// part); prints "port=<n>" on stdout once bound.
//
// Never prints the device name or unique id. Run from Terminal.app: camera permission is
// granted per launching app and a probe started from an agent shell is denied silently.
import AVFoundation
import CoreImage
import CoreMediaIO
import Darwin
import Foundation

let args = CommandLine.arguments
let seconds = args.count > 1 ? Double(args[1]) ?? 30 : 30
let outPath = args.count > 2 ? args[2] : "frames.tsv"
func err(_ s: String) { FileHandle.standardError.write((s + "\n").data(using: .utf8)!) }

let args = CommandLine.arguments
var serveMode = false
var servePort: UInt16 = 0
var quality = 0.5
var seconds = 30.0
var outPath = "frames.tsv"
var i = 1
while i < args.count {
switch args[i] {
case "--serve": serveMode = true; servePort = UInt16(args[i + 1]) ?? 0; i += 2
case "--quality": quality = Double(args[i + 1]) ?? 0.5; i += 2
default:
if Double(args[i]) != nil { seconds = Double(args[i])! } else { outPath = args[i] }
i += 1
}
}

var prop = CMIOObjectPropertyAddress(
mSelector: CMIOObjectPropertySelector(kCMIOHardwarePropertyAllowScreenCaptureDevices),
mScope: CMIOObjectPropertyScope(kCMIOObjectPropertyScopeGlobal),
Expand All @@ -24,40 +49,70 @@ if auth == .notDetermined {
AVCaptureDevice.requestAccess(for: .video) { ok in err("requestAccess -> \(ok)"); sem.signal() }
_ = sem.wait(timeout: .now() + 120)
}
if AVCaptureDevice.authorizationStatus(for: .video) != .authorized {
err("capture_permission_denied"); exit(3)
}

func findScreenDevice() -> AVCaptureDevice? {
let ds = AVCaptureDevice.DiscoverySession(deviceTypes: [.external], mediaType: nil, position: .unspecified)
for d in ds.devices {
err("device: muxed=\(d.hasMediaType(.muxed)) video=\(d.hasMediaType(.video)) model=\(d.modelID)")
if d.hasMediaType(.muxed) { return d }
}
return nil
return ds.devices.first { $0.hasMediaType(.muxed) }
}

var device: AVCaptureDevice? = nil
for _ in 0..<40 {
device = findScreenDevice()
if device != nil { break }
RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.5))
}
guard let dev = device else { err("no muxed (screen) device found"); exit(2) }
err("using screen device model=\(dev.modelID)")
for f in dev.formats {
let dims = CMVideoFormatDescriptionGetDimensions(f.formatDescription)
let codec = CMFormatDescriptionGetMediaSubType(f.formatDescription)
let rates = f.videoSupportedFrameRateRanges.map { "\($0.minFrameRate)-\($0.maxFrameRate)" }
err("format: \(dims.width)x\(dims.height) subtype=\(String(format: "%08x", codec)) rates=\(rates)")
guard let dev = device else { err("capture_device_not_found"); exit(2) }
err("using an iOS screen device")

// MARK: - frame sinks

final class LatestFrame {
private let lock = NSCondition()
private var data = Data()
private var seq = 0
func publish(_ d: Data) { lock.lock(); data = d; seq += 1; lock.broadcast(); lock.unlock() }
/// Blocks until a frame newer than `after` exists; returns (seq, bytes).
func wait(after: Int) -> (Int, Data) {
lock.lock(); defer { lock.unlock() }
while seq <= after { lock.wait() }
return (seq, data)
}
}

final class Sink: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
var idx = 0
var prev: [UInt8]? = nil
let fh: FileHandle
init(fh: FileHandle) { self.fh = fh }
let fh: FileHandle?
let latest: LatestFrame?
let ci = CIContext(options: [.useSoftwareRenderer: false])
let cs = CGColorSpace(name: CGColorSpace.sRGB)!
var encodeNs: Int64 = 0
var encoded = 0
var lastReport = Date()
init(fh: FileHandle?, latest: LatestFrame?) { self.fh = fh; self.latest = latest }

func captureOutput(_ output: AVCaptureOutput, didOutput sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
let wall = Date().timeIntervalSince1970
let pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer).seconds
guard let pb = CMSampleBufferGetImageBuffer(sampleBuffer) else { return }
if let latest = latest {
let t0 = DispatchTime.now().uptimeNanoseconds
let image = CIImage(cvPixelBuffer: pb)
if let jpeg = ci.jpegRepresentation(of: image, colorSpace: cs, options: [kCGImageDestinationLossyCompressionQuality as CIImageRepresentationOption: quality]) {
latest.publish(jpeg)
encodeNs += Int64(DispatchTime.now().uptimeNanoseconds - t0)
encoded += 1
}
idx += 1
if Date().timeIntervalSince(lastReport) >= 5 {
let ms = encoded > 0 ? Double(encodeNs) / Double(encoded) / 1e6 : 0
err(String(format: "capture %.1f fps, jpeg encode %.1f ms/frame, last frame %d bytes", Double(idx) / Date().timeIntervalSince(lastReport), ms, latest.wait(after: -1).1.count))
idx = 0; encodeNs = 0; encoded = 0; lastReport = Date()
}
return
}
let pts = CMSampleBufferGetPresentationTimeStamp(sampleBuffer).seconds
CVPixelBufferLockBaseAddress(pb, .readOnly)
let w = CVPixelBufferGetWidthOfPlane(pb, 0), h = CVPixelBufferGetHeightOfPlane(pb, 0)
let stride = CVPixelBufferGetBytesPerRowOfPlane(pb, 0)
Expand All @@ -68,31 +123,107 @@ final class Sink: NSObject, AVCaptureVideoDataOutputSampleBufferDelegate {
CVPixelBufferUnlockBaseAddress(pb, .readOnly)
var diff = 0.0
if let p = prev, p.count == cur.count {
var acc = 0; for i in 0..<cur.count { acc += abs(Int(cur[i]) - Int(p[i])) }
var acc = 0; for k in 0..<cur.count { acc += abs(Int(cur[k]) - Int(p[k])) }
diff = Double(acc) / Double(cur.count)
}
prev = cur
fh.write(String(format: "%d\t%.6f\t%.6f\t%d\t%d\t%.3f\n", idx, wall, pts, w, h, diff).data(using: .utf8)!)
fh?.write(String(format: "%d\t%.6f\t%.6f\t%d\t%d\t%.3f\n", idx, wall, pts, w, h, diff).data(using: .utf8)!)
idx += 1
}
func captureOutput(_ output: AVCaptureOutput, didDrop sampleBuffer: CMSampleBuffer, from connection: AVCaptureConnection) {
fh.write("# dropped at \(Date().timeIntervalSince1970)\n".data(using: .utf8)!)
fh?.write("# dropped at \(Date().timeIntervalSince1970)\n".data(using: .utf8)!)
}
}

// MARK: - MJPEG server (WDA-shaped)

func serve(latest: LatestFrame, port: UInt16) {
let fd = socket(AF_INET, SOCK_STREAM, 0)
var one: Int32 = 1
setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, socklen_t(MemoryLayout<Int32>.size))
var addr = sockaddr_in()
addr.sin_family = sa_family_t(AF_INET)
addr.sin_port = port.bigEndian
addr.sin_addr.s_addr = inet_addr("127.0.0.1")
let bound = withUnsafePointer(to: &addr) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { bind(fd, $0, socklen_t(MemoryLayout<sockaddr_in>.size)) } }
guard bound == 0, listen(fd, 4) == 0 else { err("bind/listen failed: \(errno)"); exit(4) }
var bound_addr = sockaddr_in(); var len = socklen_t(MemoryLayout<sockaddr_in>.size)
withUnsafeMutablePointer(to: &bound_addr) { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { _ = getsockname(fd, $0, &len) } }
let actual = UInt16(bigEndian: bound_addr.sin_port)
print("port=\(actual)"); fflush(stdout)
while true {
let client = accept(fd, nil, nil)
if client < 0 { continue }
Thread.detachNewThread {
var nosig: Int32 = 1
setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &nosig, socklen_t(MemoryLayout<Int32>.size))
// Wait for the request line + headers (the proxy sends GET / HTTP/1.1 first).
var req = Data(); var buf = [UInt8](repeating: 0, count: 1024)
while req.range(of: Data("\r\n\r\n".utf8)) == nil {
let n = read(client, &buf, buf.count)
if n <= 0 { close(client); return }
req.append(buf, count: n)
if req.count > 8192 { close(client); return }
}
func send(_ d: Data) -> Bool {
var off = 0
while off < d.count {
let n = d.withUnsafeBytes { write(client, $0.baseAddress! + off, d.count - off) }
if n <= 0 { return false }
off += n
}
return true
}
let head = "HTTP/1.0 200 OK\r\nContent-Type: multipart/x-mixed-replace; boundary=--BoundaryString\r\n\r\n"
guard send(Data(head.utf8)) else { close(client); return }
var seq = -1

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Wait for a real frame before streaming

When a client connects immediately after the advertised port but before the first capture callback, LatestFrame still contains sequence 0 and empty data, so starting this cursor at -1 makes wait(after:) return immediately and emits a zero-length image/jpeg part. The Rust proxy republishes that invalid part as a phantom frame, and WebKit may reject or reconnect the stream before any real image arrives. Initialize the cursor to 0 or represent the no-frame state explicitly so the client blocks until the first JPEG is published.

Useful? React with 👍 / 👎.

var sent = 0
let started = Date()
while true {
let (s, frame) = latest.wait(after: seq)
seq = s
let part = "--BoundaryString\r\nContent-type: image/jpeg\r\nContent-Length: \(frame.count)\r\n\r\n"
guard send(Data(part.utf8)), send(frame), send(Data("\r\n".utf8)) else { break }
sent += 1
if sent % 250 == 0 { err(String(format: "client: %d parts sent, %.1f parts/s", sent, Double(sent) / Date().timeIntervalSince(started))) }
}
close(client)
err("client disconnected after \(sent) parts")
}
}
}

FileManager.default.createFile(atPath: outPath, contents: nil)
let fh = FileHandle(forWritingAtPath: outPath)!
// MARK: - session

let latest: LatestFrame? = serveMode ? LatestFrame() : nil
var fh: FileHandle? = nil
if !serveMode {
FileManager.default.createFile(atPath: outPath, contents: nil)
fh = FileHandle(forWritingAtPath: outPath)
}
let session = AVCaptureSession()
let input = try AVCaptureDeviceInput(device: dev)
session.addInput(input)
let out = AVCaptureVideoDataOutput()
out.alwaysDiscardsLateVideoFrames = false
out.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange]
let sink = Sink(fh: fh)
out.alwaysDiscardsLateVideoFrames = serveMode
out.videoSettings = [kCVPixelBufferPixelFormatTypeKey as String: serveMode ? kCVPixelFormatType_32BGRA : kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange]
let sink = Sink(fh: fh, latest: latest)
out.setSampleBufferDelegate(sink, queue: DispatchQueue(label: "sink"))
session.addOutput(out)
fh.write("# start wall=\(Date().timeIntervalSince1970)\n".data(using: .utf8)!)
fh?.write("# start wall=\(Date().timeIntervalSince1970)\n".data(using: .utf8)!)
session.startRunning()
RunLoop.main.run(until: Date(timeIntervalSinceNow: seconds))
session.stopRunning()
err("done: \(sink.idx) frames")

signal(SIGINT) { _ in exit(0) }
signal(SIGTERM) { _ in exit(0) }
if serveMode {
// Exit when stdin closes (the supervisor's pipe), so a killed parent takes us down.
Thread.detachNewThread {
while let _ = readLine() {}
err("stdin closed, exiting"); exit(0)
}
serve(latest: latest!, port: servePort)
} else {
RunLoop.main.run(until: Date(timeIntervalSinceNow: seconds))
session.stopRunning()
err("done: \(sink.idx) frames")
}
37 changes: 32 additions & 5 deletions crates/quadcontrol-gui/src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -714,6 +714,17 @@ fn ios_launch_allowed() -> Result<(), String> {
Ok(())
}

/// P4.4 门 1 专用:debug 构建且 macOS 开发路径已放行时,
/// `QUADCONTROL_IOS_ATTACH=<http_port>:<mjpeg_port>` 让 GUI 接到手工起好的链路上。
fn dev_attach_ports() -> Option<(u16, u16)> {
if !cfg!(debug_assertions) || !cfg!(target_os = "macos") || ios_launch_allowed().is_err() {
return None;
}
let raw = std::env::var("QUADCONTROL_IOS_ATTACH").ok()?;
let (http, mjpeg) = raw.split_once(':')?;
Some((http.trim().parse().ok()?, mjpeg.trim().parse().ok()?))
}

fn wda_ids_from_env() -> WdaIds {
let read = |name: &str, fallback: &str| {
std::env::var(name)
Expand Down Expand Up @@ -764,6 +775,15 @@ async fn ios_dev_wda_enabled() -> Result<bool, String> {
Ok(cfg!(target_os = "macos") && ios_launch_allowed().is_ok())
}

/// P4.4 门 1 专用:前端渲染侧帧率,只打到本进程 stderr(debug 构建)。
#[tauri::command]
async fn ios_dev_render_fps(fps: u32, note: String) -> Result<(), String> {
if cfg!(debug_assertions) {
eprintln!("ios render fps: {fps} {note}");
}
Ok(())
}

#[tauri::command]
async fn start_ios_session(
store: tauri::State<'_, IosSessionStore>,
Expand All @@ -789,15 +809,21 @@ async fn start_ios_session(
*session = Some(IosSlot::Starting);
store.next_id.fetch_add(1, Ordering::Relaxed)
};
// GUI 只起完整链路;`LaunchMode::Attach` 只存在于库与其测试里(方案 §三)。
let options = IosLaunchOptions::new(
device_id,
LaunchMode::Launch {
// GUI 默认只起完整链路。`LaunchMode::Attach` 只在 debug 构建 + macOS 开发路径下
// 由 `QUADCONTROL_IOS_ATTACH=<http_port>:<mjpeg_port>` 放行,用于 P4.4 门 1:
// 手工起好采集探针与 WDA 链路,GUI 只接画面(IOS_MAC_STREAM_PLAN §四)。
let mode = match dev_attach_ports() {
Some((http_port, mjpeg_port)) => LaunchMode::Attach {
http_port,
mjpeg_port,
},
None => LaunchMode::Launch {
ios: quadcontrol_ios::resolve_ios(None),
wda: wda_ids_from_env(),
env: Vec::new(),
},
);
};
let options = IosLaunchOptions::new(device_id, mode);
// `spawn_supervised` 会跑 `ios version` 与端口探测(阻塞),不能占着 async
// 运行时,也不能在持锁期间做。
let spawned = tauri::async_runtime::spawn_blocking(move || {
Expand Down Expand Up @@ -1978,6 +2004,7 @@ pub fn run() {
sessions,
host_platform,
ios_dev_wda_enabled,
ios_dev_render_fps,
start_ios_session,
stop_ios_session,
ios_session_status,
Expand Down
2 changes: 1 addition & 1 deletion crates/quadcontrol-gui/src/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ <h2>
<div id="ios-stage-column" class="ios-stage-column">
<div id="ios-stage" class="ios-stage">
<!-- draggable=false:`<img>` 默认可拖,原生拖放会打断滑动手势(pointercancel)。 -->
<img id="ios-stream" class="ios-stream" alt="" draggable="false" />
<img id="ios-stream" class="ios-stream" alt="" draggable="false" crossorigin="anonymous" />
<div id="ios-stage-placeholder" class="ios-stage-placeholder">
<svg class="icon mirror-phone" aria-hidden="true"><use href="#icon-smartphone"></use></svg>
<span data-i18n="iosStageHint"></span>
Expand Down
Loading
Loading