CtrlProxy Swift-6 rewrite — status¶
CtrlProxy is the only implementation of ios/control-proxy and runs under Swift 6 strict
concurrency. See README.md for runner structure and diagnostics.
Current state¶
- The wire protocol is frozen: the TypeScript MCP server in
src/speaks it, so byte/shape parity is the contract and internals are free. Wire-contract tests anchor ontest/fixtures/ios-ctrlproxy-request-snapshots.jsonand a reference-freeJSONGoldenhelper (decode→sorted-encode is idempotent and preserves every input wire field). - Package:
Package.swifttools 6.3, iOS 17 / macOS 15, all targets.swiftLanguageMode(.v6). XcodeGen’sCtrlProxyUITeststarget compiles the sources directly (Swift 6, strict concurrencycomplete, iOS 17). Fakes live inCtrlProxyTestSupport, not the shipped product. - The server runs inside the XCUITest runner. The TS layer (
IOSCtrlProxyManager,IosCtrlProxyBuilder,IosCtrlProxyProcessClient, process-recovery command-shape matchers) andscripts/ios/ctrl-proxy-*.shdepend on the target, runner app, xctest bundle and-only-testing:CtrlProxyUITests/CtrlProxyUITests/testRunServiceidentifier. - Known flake:
WebSocketServerTests.testFragmentedCommandReassemblesEndToEnd(RealSocketClientloopback timing); passes in isolation. - Not covered by tests: a Phase-2 loopback smoke test (
127.0.0.1), extra connection scenarios (frames/ping/close/fragmentation/HTTP, scripted-ByteChannelharness) as iOS UI tests, and a fullmanual-testlive-client pass.
Build and gate¶
cd ios/control-proxy # or pass --package-path; from the repo root `swift test`
# resolves a different package (ios/auto-mobile-sdk)
swift build -Xswiftc -warnings-as-errors
swift test -Xswiftc -warnings-as-errors
CI runs scripts/ios/swift-test.sh (the same -warnings-as-errors invocation), which is the real
gate. The host build never compiles the iOS-only @MainActor/XCUITest bodies (they sit
behind #if canImport(XCTest) && os(iOS)). Xcode keeps SDK-inferred main-actor
violations non-promotable even with SWIFT_TREAT_WARNINGS_AS_ERRORS, so iOS strict-concurrency
warnings are only caught by an iOS-simulator build-for-testing.
Runtime caveat: validate on the iOS 26.5 simulator runtime, not the 27.0 beta. On the
beta the host app never reaches its fixture view controller (XCUITest “Unable to monitor
event loop”). The xcodebuild teardown then hangs ~10 min. name=iPhone 17 is ambiguous across
runtimes, so pin the 26.5 device UDID (xcrun simctl list devices). Run a single on-device test with
xcodebuild test-without-building -xctestrun <...>.xctestrun -destination 'platform=iOS Simulator,id=<udid>' -only-testing:CtrlProxyUITests/HierarchyIntegrationTests.
Never run testRunService (it waits forever). HierarchyIntegrationTests is
XCTSkipUnless-guarded on the fixture appearing, so it skips rather than fails on the beta.
Concurrency archetypes¶
- iOS 17 floor rules out
Synchronization.Mutex(iOS 18). Use actors,OSAllocatedUnfairLock(iOS 16+), or GCD queue-confinement. - Queue-confinement:
final class ... @unchecked Sendable+ private serialDispatchQueue+dispatchPrecondition(.onQueue(queue)); public API funnels throughqueue.sync/async. Used byWebSocketServer,WebSocketConnection,NWByteChannel,OSLogReader(the last must be queue-confined:OSLogStoreis notSendable, so it cannot live in anOSAllocatedUnfairLock<State: Sendable>). - Lock-confined
Sendable(OSAllocatedUnfairLock<State>, no@unchecked) where a synchronous cross-thread path cannotawait:SdkEventBuffer,ConnectionRegistry, the server’s upgraded-client set,SdkHierarchyCache,FrameContext,RotationChangeMonitor,PerfProvider’s pool. SdkHierarchyCacheis a lock, not an actor. Its write path (POST /sdk-events→SdkHierarchyExtractor→update→ refresh broadcast) runs synchronously and in order on the connection’s serial queue. An actor is reachable from that closure only via a detachedTask, which would reorder cache updates across rapid POSTs (caching a stale hierarchy) and move JSON decode off the serial queue. A single-withLocktransactionalreconcile(read→compare→clear) closes the lost-update race instead.CommandHandleris aSendablePOD router, not@MainActor, or its blocking SDK HTTP/DB calls would freeze XCUITest and starve/health(#5374).handleisasync -> any WebSocketResponsePayload(Sendable & Encodable). Itawaits the@MainActorUI collaborators and async SDK clients and calls lock-confined ones synchronously.encodeResponsekeeps theWebSocketResponse/HierarchyUpdateResponsedowncasts forperfTiminginjection.- Command dispatch is a serial
Taskchain:commandTail(anOSAllocatedUnfairLock<Task<Void, Never>?>) andawait previous?.valuepreserve per-command ordering (#5374) without a blocking queue hop. They free the accept queue immediately.WebSocketServer.handleMessagebrackets decode→handle→flush→encode inperf.withScope. - Coders are fresh-per-call (
.sortedKeys), removing the shared mutableJSONEncoder. ObjCExceptionCatchersurvives: Swift still cannot catch XCUITestNSExceptions; the guard (catchingObjCException) sits inside the@MainActorbody.- Perf call tree is a
@TaskLocal, not thread-local, so an operation never nests under an in-flight one on another thread (#3635). With@MainActorElementLocator, one hierarchy request spans the command queue and the main actor within one task, so a thread-local would split the tree at that hop. A@TaskLocalbound per operation bywithScopepropagates across theawait; outside a scope the calls are safe no-ops. The scope is@unchecked Sendable, justified by single-task-serial mutation. Completed roots are snapshotted to immutablePerfTimingbefore entering the pool, andflush()drains the whole pool so command and polling timings report together. Injectedany PerfTracking; the coordinator owns the one instance (no singleton). performContextCheckedGesture= oneMainActor.runturn inside a FRESHperf.withScope. Frame-context validation and the gesture run in one turn (atomic, no suspension between the generation read and the gesture). The fresh scope makes a gesture-nestedtrack(setText.byResourceId,pressButton, …) its own root under a synthetictotal, which is the on-wire tree shape; a plainMainActor.runwould nest it under the handler. A trackless gesture leaves the scope empty.CtrlProxycoordinator is@MainActor. It owns the single instances and injects the server’s immutable@Sendableseams at construction (onSdkEventBatch,drainLogEvents,onClientPresenceChangedfor client-gated samplers, #5477). Those closures are built beforeselfexists and fire off the main actor, so they capture aWeakCoordinator(@unchecked Sendable, written once duringinit, read only insideTask { @MainActor }).XCUIDeviceRotationSamplerandDeviceOrientationChangeSignalreach main-actor UIKit/XCUITest state from host-compiled nonisolated protocols viaMainActor.assumeIsolated(call-graph provably main; the signal’sdeinitis unreachable, a process-lifetimestatic let).VoiceOverToggling.setVoiceOveris@MainActor. The runner has notearDownWithErroroverride (it trips region isolation); each test stops its service viadefer.ElementLocator’s iOSinit(application:perf:)isinternal: apublicinit cannot expose the internalPerfTracking, an error the host#elsestub hides.
Conventions¶
- One type per file (except tightly related helpers or a shape + its sub-shapes).