Let an AI model use a real iPhone with a $7 ESP32: AirPlay eyes, USB HID hands, any OpenAI-compatible vision model. No Mac, no developer account, no jailbreak.
ios: ESP32 Agent app, the agent now runs on the phone
Henryf911d841c0f6
diff --git a/ios/.gitignore b/ios/.gitignorenew file mode 100644index 0000000..c8ce5d0--- /dev/null+++ b/ios/.gitignore@@ -0,0 +1,6 @@+Config/Local.xcconfig+build/+DerivedData/+*.xcodeproj/xcuserdata/+*.xcodeproj/project.xcworkspace/xcuserdata/+build-sim/diff --git a/ios/AgentActivity/AgentActivity.entitlements b/ios/AgentActivity/AgentActivity.entitlementsnew file mode 100644index 0000000..4011d3e--- /dev/null+++ b/ios/AgentActivity/AgentActivity.entitlements@@ -0,0 +1,10 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.security.application-groups</key>+ <array>+ <string>group.$(IA_BUNDLE_ID)</string>+ </array>+</dict>+</plist>diff --git a/ios/AgentActivity/AgentActivityWidget.swift b/ios/AgentActivity/AgentActivityWidget.swiftnew file mode 100644index 0000000..6c19748--- /dev/null+++ b/ios/AgentActivity/AgentActivityWidget.swift@@ -0,0 +1,183 @@+import ActivityKit+import AppIntents+import SwiftUI+import WidgetKit++@main+struct AgentActivityBundle: WidgetBundle {+ var body: some Widget {+ AgentLiveActivity()+ AgentStatusWidget()+ RunLastIntentControl()+ StopAgentControl()+ }+}++/// The Live Activity and Dynamic Island: running (eyes, "3/12", current step, Stop), needs help+/// (Continue / Skip / Stop) and recording a demonstration (red dot, timer, Stop).+struct AgentLiveActivity: Widget {+ var body: some WidgetConfiguration {+ ActivityConfiguration(for: AgentActivityAttributes.self) { context in+ LockScreenView(context: context)+ .activityBackgroundTint(Color.black.opacity(0.85))+ .activitySystemActionForegroundColor(.white)+ .widgetURL(AgentActivityAttributes.url(run: context.attributes.runID))+ } dynamicIsland: { context in+ let s = context.state+ return DynamicIsland {+ DynamicIslandExpandedRegion(.leading) {+ Eyes(state: s).frame(width: 44, height: 44).padding(.leading, 4)+ }+ DynamicIslandExpandedRegion(.trailing) {+ Counter(state: s).font(.headline).padding(.trailing, 4)+ }+ DynamicIslandExpandedRegion(.center) {+ Text(verbatim: context.attributes.task).font(.headline).lineLimit(1)+ }+ DynamicIslandExpandedRegion(.bottom) {+ VStack(alignment: .leading, spacing: 8) {+ Says(state: s, full: true).font(.subheadline.weight(.semibold))+ if s.line != s.labelFull {+ Text(verbatim: s.line).font(.footnote).foregroundStyle(.secondary).lineLimit(2)+ }+ if s.phase == .running {+ ProgressView(value: Double(min(s.step, s.limit)), total: Double(max(s.limit, 1))).tint(.white)+ }+ if !s.finished { Buttons(state: s) }+ }+ }+ } compactLeading: {+ if s.phase == .recording {+ Image(systemName: "record.circle.fill").foregroundStyle(.red)+ } else {+ Eyes(state: s).frame(width: 24, height: 24)+ }+ } compactTrailing: {+ if s.phase == .recording && !s.finished {+ Counter(state: s).font(.caption).frame(maxWidth: 44)+ } else {+ Says(state: s, full: false).font(.caption2.weight(.semibold)).frame(maxWidth: 92, alignment: .trailing)+ }+ } minimal: {+ if s.phase == .recording {+ Image(systemName: "record.circle.fill").foregroundStyle(.red)+ } else {+ Eyes(state: s).frame(width: 22, height: 22)+ }+ }+ .widgetURL(AgentActivityAttributes.url(run: context.attributes.runID))+ .keylineTint(s.phase == .help ? .orange : s.phase == .recording ? .red : .white)+ }+ }+}++/// "3/12" while running, the elapsed time while recording.+private struct Counter: View {+ let state: AgentActivityAttributes.ContentState+ var body: some View {+ if state.phase == .recording && !state.finished {+ Text(timerInterval: state.since...Date.distantFuture, countsDown: false)+ .monospacedDigit().foregroundStyle(.red).multilineTextAlignment(.trailing)+ } else {+ Text(verbatim: "\(state.step)/\(state.limit)").monospacedDigit().foregroundStyle(.secondary)+ }+ }+}++private struct Buttons: View {+ let state: AgentActivityAttributes.ContentState+ var body: some View {+ HStack(spacing: 8) {+ switch state.phase {+ case .help:+ Button(intent: ContinueAgentIntent()) { Label("Continue", systemImage: "play.fill").frame(maxWidth: .infinity) }+ .tint(.green)+ Button(intent: SkipStepIntent()) { Label("Skip", systemImage: "forward.fill").frame(maxWidth: .infinity) }+ .tint(.gray)+ Button(intent: StopAgentIntent()) { Image(systemName: "stop.fill") }.tint(.red)+ case .recording:+ Button(intent: StopRecordingIntent()) {+ Label("Stop Recording", systemImage: "stop.fill").frame(maxWidth: .infinity)+ }+ .tint(.red)+ case .running:+ Button(intent: StopAgentIntent()) { Label("Stop", systemImage: "stop.fill").frame(maxWidth: .infinity) }+ .tint(.red)+ }+ }+ .buttonStyle(.borderedProminent)+ }+}++/// The character's face without the USB tab. Widgets do not animate on their own, but a change of `look`+/// between two updates springs: the app sends a new gaze every ~2 s while it waits (darting eyes) and the+/// gesture's target before the pointer moves.+private struct Eyes: View {+ let state: AgentActivityAttributes.ContentState+ var body: some View {+ AgentFace(mood: state.mood, look: state.look, lookRange: 2.4, animated: false, showsTab: false)+ .animation(.spring(response: 0.3, dampingFraction: 0.65), value: state.look)+ }+}++/// What the character says ("Thinking…", "Tapping Clock", "Done!"), colored by how things stand.+private struct Says: View {+ let state: AgentActivityAttributes.ContentState+ let full: Bool+ var body: some View {+ let text = full ? state.labelFull : state.label+ Text(verbatim: text.isEmpty ? state.line : text)+ .lineLimit(1)+ .minimumScaleFactor(0.75)+ .foregroundStyle(color)+ .contentTransition(.opacity)+ .animation(.easeOut(duration: 0.25), value: text)+ }++ private var color: Color {+ if state.phase == .help { return .orange }+ if state.finished { return state.mood == .success ? .green : state.mood == .failure ? .orange : .secondary }+ return .white+ }+}++private struct LockScreenView: View {+ let context: ActivityViewContext<AgentActivityAttributes>++ var body: some View {+ let s = context.state+ HStack(alignment: .top, spacing: 14) {+ if s.phase == .recording && !s.finished {+ Image(systemName: "record.circle.fill").font(.system(size: 40)).foregroundStyle(.red).frame(width: 52)+ } else {+ Eyes(state: s).frame(width: 52, height: 52)+ }+ VStack(alignment: .leading, spacing: 6) {+ if let name = context.attributes.name {+ Text(verbatim: name).font(.caption.weight(.semibold)).foregroundStyle(.secondary)+ }+ HStack {+ Text(verbatim: context.attributes.task).font(.headline).lineLimit(1)+ Spacer()+ Counter(state: s).font(.subheadline)+ }+ if !s.finished && !s.labelFull.isEmpty {+ Says(state: s, full: true).font(.subheadline.weight(.semibold))+ }+ Text(verbatim: s.line).font(.subheadline).foregroundStyle(.secondary).lineLimit(2)+ if s.finished {+ Label(s.mood == .success ? "Done · tap to review" : "Ended · tap to review",+ systemImage: s.mood == .success ? "checkmark.circle.fill" : "play.circle")+ .font(.footnote.weight(.semibold))+ } else {+ if s.phase == .running {+ ProgressView(value: Double(min(s.step, s.limit)), total: Double(max(s.limit, 1))).tint(.white)+ }+ Buttons(state: s).controlSize(.small)+ }+ }+ }+ .foregroundStyle(.white)+ .padding(16)+ }+}diff --git a/ios/AgentActivity/HomeWidgets.swift b/ios/AgentActivity/HomeWidgets.swiftnew file mode 100644index 0000000..012f0b2--- /dev/null+++ b/ios/AgentActivity/HomeWidgets.swift@@ -0,0 +1,177 @@+import AppIntents+import SwiftUI+import WidgetKit++struct AgentEntry: TimelineEntry {+ let date: Date+ let snapshot: AgentSnapshot? // nil: the app hasn't written one yet+}++struct AgentProvider: TimelineProvider {+ func placeholder(in context: Context) -> AgentEntry { AgentEntry(date: .now, snapshot: .preview) }++ func getSnapshot(in context: Context, completion: @escaping (AgentEntry) -> Void) {+ completion(AgentEntry(date: .now, snapshot: context.isPreview ? SharedState.load() ?? .preview : SharedState.load()))+ }++ func getTimeline(in context: Context, completion: @escaping (Timeline<AgentEntry>) -> Void) {+ // The app reloads the timelines when its state changes.+ completion(Timeline(entries: [AgentEntry(date: .now, snapshot: SharedState.load())], policy: .never))+ }+}++/// Home Screen (small: the character and its status; medium: plus up to four saved intents as buttons)+/// and Lock Screen (circular: the character; rectangular: the last run).+struct AgentStatusWidget: Widget {+ var body: some WidgetConfiguration {+ StaticConfiguration(kind: SharedState.kind, provider: AgentProvider()) { entry in+ AgentWidgetView(entry: entry)+ .containerBackground(.fill.tertiary, for: .widget)+ }+ .configurationDisplayName("ESP32 Agent")+ .description("See whether the agent is ready and run your saved intents.")+ .supportedFamilies([.systemSmall, .systemMedium, .accessoryCircular, .accessoryRectangular])+ }+}++struct AgentWidgetView: View {+ let entry: AgentEntry+ @Environment(\.widgetFamily) private var family++ private var snap: AgentSnapshot { entry.snapshot ?? AgentSnapshot(status: .needsSetup) }++ var body: some View {+ switch family {+ case .accessoryCircular: circular+ case .accessoryRectangular: rectangular+ case .systemMedium: medium+ default: small+ }+ }++ private var statusText: Text {+ if entry.snapshot == nil { return Text("Open the app") }+ switch snap.status {+ case .ready: return Text("Ready")+ case .running: return Text("Running · step \(snap.step)")+ case .offline: return Text("Board offline")+ case .needsSetup: return Text("Needs setup")+ }+ }++ private var face: some View {+ AgentFace(mood: snap.mood, animated: false, reacts: false)+ }++ private var small: some View {+ VStack(alignment: .leading, spacing: 6) {+ face.frame(width: 52, height: 58)+ Spacer(minLength: 0)+ Text(verbatim: "ESP32 Agent").font(.caption).foregroundStyle(.secondary)+ statusText.font(.headline).lineLimit(1).minimumScaleFactor(0.8)+ if snap.status == .running {+ Text(verbatim: snap.task).font(.caption2).foregroundStyle(.secondary).lineLimit(2)+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)+ }++ private var medium: some View {+ HStack(spacing: 12) {+ VStack(alignment: .leading, spacing: 6) {+ face.frame(width: 52, height: 58)+ Spacer(minLength: 0)+ statusText.font(.subheadline.weight(.semibold)).lineLimit(2).minimumScaleFactor(0.8)+ }+ .frame(width: 96, alignment: .leading)+ if snap.intents.isEmpty {+ Text("Save an intent in the app to run it from here.")+ .font(.footnote).foregroundStyle(.secondary).frame(maxWidth: .infinity)+ } else {+ VStack(spacing: 6) {+ ForEach(snap.intents.prefix(4)) { item in+ Button(intent: RunSavedIntentIntent(intent: SavedIntentEntity(item))) {+ Label { Text(verbatim: item.name).lineLimit(1) } icon: { Image(systemName: item.symbol) }+ .font(.caption.weight(.medium))+ .frame(maxWidth: .infinity, alignment: .leading)+ }+ .buttonStyle(.bordered)+ .tint(.primary)+ .disabled(snap.status == .running)+ }+ }+ }+ }+ }++ private var circular: some View {+ ZStack {+ AccessoryWidgetBackground()+ face.padding(8)+ }+ .widgetAccentable()+ }++ private var rectangular: some View {+ VStack(alignment: .leading, spacing: 1) {+ if snap.status == .running {+ Label { Text("Step \(snap.step)") } icon: { Image(systemName: "play.fill") }.font(.headline)+ Text(verbatim: snap.task).font(.caption).lineLimit(2)+ } else if let run = snap.lastRun {+ Label { Text(run.ok ? "Done" : "Not finished") } icon: {+ Image(systemName: run.ok ? "checkmark.circle.fill" : "xmark.circle.fill")+ }+ .font(.headline)+ Text(verbatim: run.task).font(.caption).lineLimit(1)+ Text(run.date, style: .relative).font(.caption2).foregroundStyle(.secondary)+ } else {+ Text(verbatim: "ESP32 Agent").font(.headline)+ statusText.font(.caption)+ }+ }+ .frame(maxWidth: .infinity, alignment: .leading)+ }+}++/// Control Center: run the last intent; stop the agent.+struct RunLastIntentControl: ControlWidget {+ var body: some ControlWidgetConfiguration {+ StaticControlConfiguration(kind: "RunLastIntent") {+ ControlWidgetButton(action: RunLastIntentIntent()) {+ Label("Run Last Intent", systemImage: "bolt.fill")+ }+ }+ .displayName("Run Last Intent")+ .description("Runs the saved intent you ran last on ESP32 Agent.")+ }+}++struct StopAgentControl: ControlWidget {+ var body: some ControlWidgetConfiguration {+ StaticControlConfiguration(kind: "StopAgent") {+ ControlWidgetButton(action: StopAgentIntent()) {+ Label("Stop ESP32 Agent", systemImage: "stop.fill")+ }+ }+ .displayName("Stop ESP32 Agent")+ .description("Stops the running task and lets go of the screen.")+ }+}++#Preview("Small", as: .systemSmall) {+ AgentStatusWidget()+} timeline: {+ AgentEntry(date: .now, snapshot: .preview)+}++#Preview("Medium", as: .systemMedium) {+ AgentStatusWidget()+} timeline: {+ AgentEntry(date: .now, snapshot: .preview)+}++#Preview("Lock Screen", as: .accessoryRectangular) {+ AgentStatusWidget()+} timeline: {+ AgentEntry(date: .now, snapshot: .preview)+}diff --git a/ios/AgentActivity/Info.plist b/ios/AgentActivity/Info.plistnew file mode 100644index 0000000..472b7fb--- /dev/null+++ b/ios/AgentActivity/Info.plist@@ -0,0 +1,36 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>en</string>+ <key>CFBundleDisplayName</key>+ <string>ESP32 Agent</string>+ <key>CFBundleExecutable</key>+ <string>$(EXECUTABLE_NAME)</string>+ <key>CFBundleIdentifier</key>+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleLocalizations</key>+ <array>+ <string>en</string>+ <string>zh-Hans</string>+ </array>+ <key>CFBundleName</key>+ <string>$(PRODUCT_NAME)</string>+ <key>CFBundlePackageType</key>+ <string>XPC!</string>+ <key>CFBundleShortVersionString</key>+ <string>1.0</string>+ <key>CFBundleVersion</key>+ <string>1</string>+ <key>IAAppGroup</key>+ <string>group.$(IA_BUNDLE_ID)</string>+ <key>NSExtension</key>+ <dict>+ <key>NSExtensionPointIdentifier</key>+ <string>com.apple.widgetkit-extension</string>+ </dict>+</dict>+</plist>diff --git a/ios/AgentActivity/Localizable.xcstrings b/ios/AgentActivity/Localizable.xcstringsnew file mode 100644index 0000000..d554827--- /dev/null+++ b/ios/AgentActivity/Localizable.xcstrings@@ -0,0 +1,452 @@+{+ "sourceLanguage" : "en",+ "strings" : {+ "Board offline" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "板子离线"+ }+ }+ }+ },+ "Continue" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "继续"+ }+ }+ }+ },+ "Daily 7 AM alarm" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "每天 7 点闹钟"+ }+ }+ }+ },+ "Done" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "完成"+ }+ }+ }+ },+ "Done · tap to review" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "完成 · 轻点复盘"+ }+ }+ }+ },+ "Draw a smiley" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "画个笑脸"+ }+ }+ }+ },+ "Ended · tap to review" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已结束 · 轻点复盘"+ }+ }+ }+ },+ "Intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "意图"+ }+ }+ }+ },+ "Needs setup" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "需要设置"+ }+ }+ }+ },+ "Not finished" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未完成"+ }+ }+ }+ },+ "Note: hello" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "备忘录:hello"+ }+ }+ }+ },+ "Open ESP32 Agent once, then try again." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请先打开一次 ESP32 Agent,然后再试。"+ }+ }+ }+ },+ "Open the app" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打开 App"+ }+ }+ }+ },+ "Ready" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "就绪"+ }+ }+ }+ },+ "Run ${intent}" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行${intent}"+ }+ }+ }+ },+ "Run Last Intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行上次的意图"+ }+ }+ }+ },+ "Run a Saved Intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行已保存的意图"+ }+ }+ }+ },+ "Running · step %lld" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行中 · 第 %lld 步"+ }+ }+ }+ },+ "Runs one of your saved intents on ESP32 Agent." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "在 ESP32 Agent 上运行一个已保存的意图。"+ }+ }+ }+ },+ "Runs the saved intent you ran last on ESP32 Agent." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "在 ESP32 Agent 上运行你上次运行的意图。"+ }+ }+ }+ },+ "Save an intent in the app to run it from here." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "在 App 中保存意图后,可在这里运行。"+ }+ }+ }+ },+ "Saved Intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已保存的意图"+ }+ }+ }+ },+ "See whether the agent is ready and run your saved intents." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "查看 Agent 是否就绪,并运行已保存的意图。"+ }+ }+ }+ },+ "Skip" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "跳过"+ }+ }+ }+ },+ "Skip step" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "跳过这步"+ }+ }+ }+ },+ "Smiley drawn" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "笑脸画好了"+ }+ }+ }+ },+ "Step %lld" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "第 %lld 步"+ }+ }+ }+ },+ "Stop" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "停止"+ }+ }+ }+ },+ "Stop Recording" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "停止录制"+ }+ }+ }+ },+ "Stop ESP32 Agent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "停止 ESP32 Agent"+ }+ }+ }+ },+ "Stop recording" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "停止录制"+ }+ }+ }+ },+ "Stop the agent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "停止 agent"+ }+ }+ }+ },+ "Stops the running task and lets go of the screen." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "停止正在运行的任务并松开屏幕。"+ }+ }+ }+ },+ "Wi-Fi settings" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Wi-Fi 设置"+ }+ }+ }+ },+ "acting" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "动手中"+ }+ }+ }+ },+ "content" : {+ "extractionState" : "manual",+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "惬意"+ }+ }+ }+ },+ "dizzy" : {+ "extractionState" : "manual",+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "晕乎乎"+ }+ }+ }+ },+ "failure" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "失败"+ }+ }+ }+ },+ "ESP32 Agent" : {+ "shouldTranslate" : false+ },+ "idle" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "空闲"+ }+ }+ }+ },+ "listening" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "在听"+ }+ }+ }+ },+ "sleeping" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "睡觉"+ }+ }+ }+ },+ "success" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "成功"+ }+ }+ }+ },+ "thinking" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "思考中"+ }+ }+ }+ },+ "wink" : {+ "extractionState" : "manual",+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "眨眼"+ }+ }+ }+ }+ },+ "version" : "1.0"+}diff --git a/ios/Branding/logo-source.png b/ios/Branding/logo-source.pngnew file mode 100644index 0000000..7afc694Binary files /dev/null and b/ios/Branding/logo-source.png differdiff --git a/ios/Config/Local.xcconfig.example b/ios/Config/Local.xcconfig.examplenew file mode 100644index 0000000..1b33003--- /dev/null+++ b/ios/Config/Local.xcconfig.example@@ -0,0 +1,15 @@+// Copy to Local.xcconfig (git-ignored) and fill in. Everything here is optional except your team.+DEVELOPMENT_TEAM = ABCDE12345++// Your own bundle ID; the widget is <id>.activity and the App Group group.<id>.+IA_BUNDLE_ID = com.example.esp32agent++// One-tap hotspot join, Live Activity group and time-sensitive alerts need these capabilities+// (Hotspot Configuration needs a paid developer account). Leave empty to build without them.+IA_ENTITLEMENTS = IPhoneAgent/IPhoneAgent.entitlements+IA_WIDGET_ENTITLEMENTS = AgentActivity/AgentActivity.entitlements++// Optional model preset for your own builds (never commit a key).+IA_PRESET_BASE_URL =+IA_PRESET_MODEL =+IA_PRESET_KEY =diff --git a/ios/Config/Shared.xcconfig b/ios/Config/Shared.xcconfignew file mode 100644index 0000000..efba909--- /dev/null+++ b/ios/Config/Shared.xcconfig@@ -0,0 +1,20 @@+// Signing: put your team in Config/Local.xcconfig (gitignored), e.g.+// DEVELOPMENT_TEAM = ABCDE12345++// Set // Bundle ID of the app; the widget extension and tests append a suffix, the App Group is group.<this>.+// Set your own in Local.xcconfig.+IA_BUNDLE_ID = com.example.esp32agent++IA_ENTITLEMENTS = IPhoneAgent/IPhoneAgent.entitlements in Local.xcconfig+// once Xcode is signed in, to enable one-tap joining of the board's hotspot.+IA_ENTITLEMENTS =+// Also set IA_WIDGET_ENTITLEMENTS = AgentActivity/AgentActivity.entitlements so the widgets share the App Group.+IA_WIDGET_ENTITLEMENTS =++// Optional LLM preset for your own builds, set in Local.xcconfig (write "//" as "/$()/"):+// IA_PRESET_BASE_URL = https:/$()/example.com/v1+IA_PRESET_BASE_URL =+IA_PRESET_MODEL =+IA_PRESET_KEY =++#include? "Local.xcconfig"diff --git a/ios/IPhoneAgent.xcodeproj/project.pbxproj b/ios/IPhoneAgent.xcodeproj/project.pbxprojnew file mode 100644index 0000000..f087f8c--- /dev/null+++ b/ios/IPhoneAgent.xcodeproj/project.pbxproj@@ -0,0 +1,985 @@+// !$*UTF8*$!+{+ archiveVersion = 1;+ classes = {+ };+ objectVersion = 77;+ objects = {++/* Begin PBXBuildFile section */+ 006434261FDDF11EA3BF16E6 /* DebugEntry.swift in Sources */ = {isa = PBXBuildFile; fileRef = 41B8435B1585E5ECE113AC49 /* DebugEntry.swift */; };+ 041DFAB6BE68032D48592AC2 /* HomeParts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 406D13832E556B804F6F3887 /* HomeParts.swift */; };+ 0638DE7546BE2E3578EAE3D6 /* StoreTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0884D2AF849046D0FA2E62C1 /* StoreTests.swift */; };+ 079927568C3047DA5C2F105E /* Recovery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8AE108AA4534D13B7AC12079 /* Recovery.swift */; };+ 0A553429560D1697C678A682 /* AboutView.swift in Sources */ = {isa = PBXBuildFile; fileRef = E948F0EBC262C7ABF8E413E5 /* AboutView.swift */; };+ 0B7AB0B39C3257BD2E395DC2 /* Theme.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2418164D156C7D2934CA5312 /* Theme.swift */; };+ 173BD54931BD69B83D7F6FD3 /* CalibrationToast.swift in Sources */ = {isa = PBXBuildFile; fileRef = E2E3712143A195602610004B /* CalibrationToast.swift */; };+ 180133912100FC228377AE9A /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = F960AA3F536A5DF20F8E908A /* Assets.xcassets */; };+ 189667BD260B5751915C28AF /* OnboardingPages.swift in Sources */ = {isa = PBXBuildFile; fileRef = 22464AAA35416D0351B8063C /* OnboardingPages.swift */; };+ 1BBB78AF1CD2B329778F6E01 /* AutoCalibrator.swift in Sources */ = {isa = PBXBuildFile; fileRef = 65736EFE5D5C4AF40EDC5F92 /* AutoCalibrator.swift */; };+ 1DBE4EFF0FB05C1390236410 /* IntentDetailView.swift in Sources */ = {isa = PBXBuildFile; fileRef = D222722DF7856F9253B9784E /* IntentDetailView.swift */; };+ 1DE8E596908DD14C90E40761 /* RunsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 915FC0D291F09BE0A0439D9C /* RunsView.swift */; };+ 2013DD86239B8EE1396CB82B /* AgentShortcuts.swift in Sources */ = {isa = PBXBuildFile; fileRef = B260480A536241A2B9043EE1 /* AgentShortcuts.swift */; };+ 24645B70C28410D8E96A9D92 /* RunRecovery.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4BBF99F934AC45DB1B8B9324 /* RunRecovery.swift */; };+ 2671E23FE56D69B0CEAB4EF6 /* Actions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 458E8069AA8BE0B721C9AD7A /* Actions.swift */; };+ 28166EA554E9D943A62AF961 /* Stores.swift in Sources */ = {isa = PBXBuildFile; fileRef = 35D21F22B2928E33B4036328 /* Stores.swift */; };+ 28CC6521C0BE74701079D0E1 /* AgentActivity.swift in Sources */ = {isa = PBXBuildFile; fileRef = B155ADD97189D634A809EDE9 /* AgentActivity.swift */; };+ 2A48924EF6EF7A39D5A05E21 /* ReviewMedia.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43CF0FDDD155E930C9AC80D8 /* ReviewMedia.swift */; };+ 2CF6A30C3D72E05EEBC6FFED /* IslandTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A54BC007EE5C64A13CDEE9EE /* IslandTests.swift */; };+ 3607786AAF7296B3414B6F08 /* VisionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1887982FE1A729487269296E /* VisionTests.swift */; };+ 419FA08397BAF31F91A62633 /* DebugLog.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0B88A1538529C9674B323370 /* DebugLog.swift */; };+ 42A1AE0EA1AC18461ED8F33B /* RecoveryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8F2E6CFBDF20832FF9626D99 /* RecoveryTests.swift */; };+ 48100361D2ECFE7E36F83F9D /* LLMTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F071F3E4D7B82DE70AE75A81 /* LLMTests.swift */; };+ 4A2BFED999CA010867968893 /* H264Decoder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 607F9EBBC39E74507B73F751 /* H264Decoder.swift */; };+ 4C33F19F733F62B5A131BE9E /* TouchCalibration.swift in Sources */ = {isa = PBXBuildFile; fileRef = C70A2F48B5948F180DF1450C /* TouchCalibration.swift */; };+ 4C9AF1D3470474D2AB745D00 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3E74E2758C4170812147466F /* SettingsView.swift */; };+ 4CA70811574C401EB0012355 /* Notifier.swift in Sources */ = {isa = PBXBuildFile; fileRef = 05DA6345A40715C8BD2AED6C /* Notifier.swift */; };+ 5529FEF43DA98563B4BCFEC1 /* AgentFace.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7314ABD64EC1106422C685E /* AgentFace.swift */; };+ 57716E1B9BBB6026600DAD4C /* AgentSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EC8ECB7FF0B63991E8AEFFB /* AgentSnapshot.swift */; };+ 58405C052C5CE287759E2AA4 /* ProbeFit.swift in Sources */ = {isa = PBXBuildFile; fileRef = 435B39A7D499300AADA2D16C /* ProbeFit.swift */; };+ 5D657D39BD5F6808ED60EDEA /* DemoRecorder.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5962900FEB08728899160DD1 /* DemoRecorder.swift */; };+ 5EC81FBCFE439052A8F26EA2 /* Pointer.swift in Sources */ = {isa = PBXBuildFile; fileRef = A5CC3BCF7F90AF60B075DD96 /* Pointer.swift */; };+ 607B1520E654F13F1F304F4D /* DeviceTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 23A9A9D917B2B2FC534E7DBA /* DeviceTests.swift */; };+ 63B0CAE819339D8FC103AC8B /* VideoFeed.swift in Sources */ = {isa = PBXBuildFile; fileRef = D9615E8664A5DC600B1B97E0 /* VideoFeed.swift */; };+ 63CB6644E6517C6B12F3E0AB /* Localizable.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = 1C25AC81D9FBF6073FDD1851 /* Localizable.xcstrings */; };+ 66CADEEED2A075ECD5070131 /* BoardCommands.swift in Sources */ = {isa = PBXBuildFile; fileRef = 02C2C2C9EBE006E896050646 /* BoardCommands.swift */; };+ 6787B6280DD3923D995F8611 /* AgentIntents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0278B11885CA8C4A96C96531 /* AgentIntents.swift */; };+ 6CDEB83B98075E73AEA52F13 /* ShareTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = AA04712864CA08DA02B08369 /* ShareTests.swift */; };+ 72E72D656EFE51EB73F94A5C /* PrivacyViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8C498727CAF51C5A955A8A10 /* PrivacyViews.swift */; };+ 74222DFADC00836F21E19FEA /* AgentIntents.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0278B11885CA8C4A96C96531 /* AgentIntents.swift */; };+ 796CF6A9427314B483BBA14B /* HomeWidgets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A091027B026D22579AA4972 /* HomeWidgets.swift */; };+ 7A0635EEEE8295BBA54B9DD9 /* ReviewSheets.swift in Sources */ = {isa = PBXBuildFile; fileRef = 9419B84DE8B4B7CD816AF19B /* ReviewSheets.swift */; };+ 7B684FAA8B218BB9798F9EC3 /* Metrics.swift in Sources */ = {isa = PBXBuildFile; fileRef = B9719A5EC1DD7C5033CC8DF5 /* Metrics.swift */; };+ 7B925E867DA328C9A682CDE0 /* AgentLoop.swift in Sources */ = {isa = PBXBuildFile; fileRef = 17DBD3270E7E91B39C3C7438 /* AgentLoop.swift */; };+ 7BBA01EDC5514C6EC77AE6E2 /* IPhoneAgentApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 953BF9D5FB798BA1F3CEC832 /* IPhoneAgentApp.swift */; };+ 7D859BE4F1E945FE96CD8C61 /* AgentTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCDFF66F3082E46B88130ABC /* AgentTests.swift */; };+ 7F412478410DC75BC26A0D5C /* ModelSettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3B94481DB51BD93A2900698F /* ModelSettingsView.swift */; };+ 80EA74A9A970F441C661524C /* StepText.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2169FBFC7A60B9FC1FF1E724 /* StepText.swift */; };+ 812925C7EC9F24F99DC06037 /* AppPresence.swift in Sources */ = {isa = PBXBuildFile; fileRef = 25891E89F3EF8CFF37935661 /* AppPresence.swift */; };+ 84CA12989B5CB62129C3419B /* Localizable.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = E37B39FEB9A7A965ED4A86B3 /* Localizable.xcstrings */; };+ 85678CC068CF3297ECF345DF /* InfoPlist.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = E7721FA5F1DD53610AD0B737 /* InfoPlist.xcstrings */; };+ 8738C1055CD8FE6AFD6B9204 /* OnboardingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 99381FBF82EA7EB76556866E /* OnboardingView.swift */; };+ 87BA6110B7AD061157A0995C /* ReviewModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = AF7D99C79D12EBD49F30723F /* ReviewModel.swift */; };+ 8A11B8068D97194AA3C9723B /* CalibrationViews.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1828194EBD7CDB8FEFF8643 /* CalibrationViews.swift */; };+ 8D154D84FE2D6E532A27E095 /* Vision.swift in Sources */ = {isa = PBXBuildFile; fileRef = E1FF376927D9503ABF677854 /* Vision.swift */; };+ 8F45E1F46FB046780AC0838F /* Redactor.swift in Sources */ = {isa = PBXBuildFile; fileRef = 541D1A2837E5F270700EAF55 /* Redactor.swift */; };+ 8FCFB9340A6E3F74CE629FBF /* VideoTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 44E6D0770452B562B5CA484E /* VideoTests.swift */; };+ 90594045D55F83E5EEE53574 /* ReviewTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 794E46A6A28E406A3D606661 /* ReviewTests.swift */; };+ 948C0D1F80207A8E5874D943 /* HomeView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6DCAEE3FDF94357F8875E473 /* HomeView.swift */; };+ 962068E4EB7D31C8E1E0A9F2 /* PromptTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F775C2B833B33E951A629957 /* PromptTests.swift */; };+ 96C08C1CFEECA69484811137 /* StatusChips.swift in Sources */ = {isa = PBXBuildFile; fileRef = 96BDA430E0C54DC956DE9366 /* StatusChips.swift */; };+ 99D64CF9B896616382FC8A0E /* AgentActivity.appex in Embed Foundation Extensions */ = {isa = PBXBuildFile; fileRef = A11E0FF01881451EBB3D18FF /* AgentActivity.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };+ 9BA8ABE4398546618D6AE675 /* DiagnosticsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2F3122E7A1DB53F3BFCCFD06 /* DiagnosticsView.swift */; };+ 9CB0E6A2FE92EF5422B95377 /* AgentSnapshot.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3EC8ECB7FF0B63991E8AEFFB /* AgentSnapshot.swift */; };+ A0DECAC4E4DBADB432942A83 /* IntentBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = 5538B879586D04FB7F15C7E5 /* IntentBridge.swift */; };+ A177729443FE818CD754FD64 /* StepFrame.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8E64CF4B18DBAB014C7E9314 /* StepFrame.swift */; };+ A271DC80F0EB0BA42FD7D022 /* PokeableFace.swift in Sources */ = {isa = PBXBuildFile; fileRef = A409B3696F547E712B4D4D14 /* PokeableFace.swift */; };+ A42DB537742861FF668DB34A /* JSON.swift in Sources */ = {isa = PBXBuildFile; fileRef = FCC7FAA4989F36E7F9B4C021 /* JSON.swift */; };+ A5A1640A615256B576F9A055 /* RunSession.swift in Sources */ = {isa = PBXBuildFile; fileRef = 38FB6FEBD55DCBE8EED6834C /* RunSession.swift */; };+ ABEF22E60573E04FACD0E4A9 /* AgentFace.swift in Sources */ = {isa = PBXBuildFile; fileRef = A7314ABD64EC1106422C685E /* AgentFace.swift */; };+ AD702230192ADBF827044490 /* LiveActivity.swift in Sources */ = {isa = PBXBuildFile; fileRef = 27A03E1A122C50B8ED88AC91 /* LiveActivity.swift */; };+ B356EECAFE045249704E63FD /* MockMode.swift in Sources */ = {isa = PBXBuildFile; fileRef = 13664BFD54E7827E0E53B7F6 /* MockMode.swift */; };+ B86BD0431A675EC2681E03A7 /* AgentActivityWidget.swift in Sources */ = {isa = PBXBuildFile; fileRef = 86452ED01E883A6E57BB13E4 /* AgentActivityWidget.swift */; };+ B9B15030A9EEC21B4512533B /* HotspotJoin.swift in Sources */ = {isa = PBXBuildFile; fileRef = C12C6B350F7AFD555CE0B8EA /* HotspotJoin.swift */; };+ BB3C60862112DB87D3555158 /* LLMClient.swift in Sources */ = {isa = PBXBuildFile; fileRef = DCDA925D0FFD42810895573C /* LLMClient.swift */; };+ BD09EA4793C0B09297190CD9 /* BoardProtocol.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0DFECC30B2ADEB1BB69072EC /* BoardProtocol.swift */; };+ C4F3ADB5189E27B999BDDF83 /* TouchProbe.swift in Sources */ = {isa = PBXBuildFile; fileRef = C5099810C37BB0AD66EDC8C8 /* TouchProbe.swift */; };+ CED032EC090264C33AD7D1D1 /* Prompts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 8B2B975DEE7BC511DC51441F /* Prompts.swift */; };+ CFDC07BA9E09D3446164B1B9 /* OnboardingDemos.swift in Sources */ = {isa = PBXBuildFile; fileRef = D17A722B1C48BF8FBF8B4222 /* OnboardingDemos.swift */; };+ D04078EE246F6B5EB38D64B5 /* prompts in Resources */ = {isa = PBXBuildFile; fileRef = 769290C5E01DE7CA97412DDA /* prompts */; };+ D48CF75915F3D1FFE18ADC3A /* BoardLink.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33107099A7483949F03FBDB6 /* BoardLink.swift */; };+ D5D197473F9BD99FD38F6231 /* AppShortcuts.xcstrings in Resources */ = {isa = PBXBuildFile; fileRef = 6EC7C29EBD2DA1A602B0BED2 /* AppShortcuts.xcstrings */; };+ DD9700301BED070734BD4F87 /* TraceStore.swift in Sources */ = {isa = PBXBuildFile; fileRef = 226739C44752297294C75671 /* TraceStore.swift */; };+ DDC8DB5DA64D75338F3A52DF /* AppModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 43A1CAA88BC5B551B872615F /* AppModel.swift */; };+ E86B4A3177FC9F0A5D846C2F /* Settings.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDB8774D34E5E3FEF5C7A1E6 /* Settings.swift */; };+ E8FA336F818FBAB651C32BEE /* AgentActivity.swift in Sources */ = {isa = PBXBuildFile; fileRef = B155ADD97189D634A809EDE9 /* AgentActivity.swift */; };+ EF83C4DFA24497FDB0BF123E /* mock-frame.jpg in Resources */ = {isa = PBXBuildFile; fileRef = F0918D2C621FD17EDD51AF5E /* mock-frame.jpg */; };+ F0989DBA8FA72168CA371221 /* IslandStatus.swift in Sources */ = {isa = PBXBuildFile; fileRef = CFB37456C763ADFEF9E577A2 /* IslandStatus.swift */; };+ F2D091FC47717266EFF75FBA /* ReviewView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 31BF05E92BF9DC3156F81ED6 /* ReviewView.swift */; };+ F2FFDB2986493F65EB6A9738 /* LogUploader.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4D9FABC284798F9949C1A8EF /* LogUploader.swift */; };+ F3DE9777E0FAD414E17465BC /* VideoAssembler.swift in Sources */ = {isa = PBXBuildFile; fileRef = CD4270DF66937405FC86B145 /* VideoAssembler.swift */; };+ F6301B26DAF28C96D09F6D8E /* RunShare.swift in Sources */ = {isa = PBXBuildFile; fileRef = B1B84B4F1C81E697ACB30630 /* RunShare.swift */; };+ F77EB884A6AE61AC290911D9 /* AssistiveTouchSpots.swift in Sources */ = {isa = PBXBuildFile; fileRef = D317C60AA727B6A20A589DAC /* AssistiveTouchSpots.swift */; };+/* End PBXBuildFile section */++/* Begin PBXContainerItemProxy section */+ 7554F08B663A589FB7FAF693 /* PBXContainerItemProxy */ = {+ isa = PBXContainerItemProxy;+ containerPortal = A87BF3B3154BD2A36E9E8546 /* Project object */;+ proxyType = 1;+ remoteGlobalIDString = 5983F0E1632FA0FDDDEAB3FC;+ remoteInfo = IPhoneAgent;+ };+ A1F8805FC5601538374FA630 /* PBXContainerItemProxy */ = {+ isa = PBXContainerItemProxy;+ containerPortal = A87BF3B3154BD2A36E9E8546 /* Project object */;+ proxyType = 1;+ remoteGlobalIDString = 6DB9E3E8534E6FC1BF6E382C;+ remoteInfo = AgentActivity;+ };+/* End PBXContainerItemProxy section */++/* Begin PBXCopyFilesBuildPhase section */+ 51D918A1DE20665371F6629D /* Embed Foundation Extensions */ = {+ isa = PBXCopyFilesBuildPhase;+ buildActionMask = 2147483647;+ dstPath = "";+ dstSubfolderSpec = 13;+ files = (+ 99D64CF9B896616382FC8A0E /* AgentActivity.appex in Embed Foundation Extensions */,+ );+ name = "Embed Foundation Extensions";+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXCopyFilesBuildPhase section */++/* Begin PBXFileReference section */+ 0278B11885CA8C4A96C96531 /* AgentIntents.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentIntents.swift; sourceTree = "<group>"; };+ 02C2C2C9EBE006E896050646 /* BoardCommands.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BoardCommands.swift; sourceTree = "<group>"; };+ 05DA6345A40715C8BD2AED6C /* Notifier.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Notifier.swift; sourceTree = "<group>"; };+ 0884D2AF849046D0FA2E62C1 /* StoreTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StoreTests.swift; sourceTree = "<group>"; };+ 0B88A1538529C9674B323370 /* DebugLog.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DebugLog.swift; sourceTree = "<group>"; };+ 0DFECC30B2ADEB1BB69072EC /* BoardProtocol.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BoardProtocol.swift; sourceTree = "<group>"; };+ 13664BFD54E7827E0E53B7F6 /* MockMode.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MockMode.swift; sourceTree = "<group>"; };+ 16165E2AD13D29F06CBFA5B0 /* AgentActivity.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = AgentActivity.entitlements; sourceTree = "<group>"; };+ 17DBD3270E7E91B39C3C7438 /* AgentLoop.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentLoop.swift; sourceTree = "<group>"; };+ 1887982FE1A729487269296E /* VisionTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VisionTests.swift; sourceTree = "<group>"; };+ 1C25AC81D9FBF6073FDD1851 /* Localizable.xcstrings */ = {isa = PBXFileReference; lastKnownFileType = text.json.xcstrings; path = Localizable.xcstrings; sourceTree = "<group>"; };+ 2169FBFC7A60B9FC1FF1E724 /* StepText.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StepText.swift; sourceTree = "<group>"; };+ 22464AAA35416D0351B8063C /* OnboardingPages.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnboardingPages.swift; sourceTree = "<group>"; };+ 226739C44752297294C75671 /* TraceStore.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TraceStore.swift; sourceTree = "<group>"; };+ 23A9A9D917B2B2FC534E7DBA /* DeviceTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DeviceTests.swift; sourceTree = "<group>"; };+ 2418164D156C7D2934CA5312 /* Theme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Theme.swift; sourceTree = "<group>"; };+ 24A4292E1153548AEB53299E /* IPhoneAgentTests.xctest */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.cfbundle; path = IPhoneAgentTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };+ 25891E89F3EF8CFF37935661 /* AppPresence.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppPresence.swift; sourceTree = "<group>"; };+ 27A03E1A122C50B8ED88AC91 /* LiveActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LiveActivity.swift; sourceTree = "<group>"; };+ 2F3122E7A1DB53F3BFCCFD06 /* DiagnosticsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DiagnosticsView.swift; sourceTree = "<group>"; };+ 31BF05E92BF9DC3156F81ED6 /* ReviewView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReviewView.swift; sourceTree = "<group>"; };+ 33107099A7483949F03FBDB6 /* BoardLink.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BoardLink.swift; sourceTree = "<group>"; };+ 35D21F22B2928E33B4036328 /* Stores.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Stores.swift; sourceTree = "<group>"; };+ 38FB6FEBD55DCBE8EED6834C /* RunSession.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunSession.swift; sourceTree = "<group>"; };+ 3A091027B026D22579AA4972 /* HomeWidgets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeWidgets.swift; sourceTree = "<group>"; };+ 3B94481DB51BD93A2900698F /* ModelSettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelSettingsView.swift; sourceTree = "<group>"; };+ 3E74E2758C4170812147466F /* SettingsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SettingsView.swift; sourceTree = "<group>"; };+ 3EC8ECB7FF0B63991E8AEFFB /* AgentSnapshot.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentSnapshot.swift; sourceTree = "<group>"; };+ 406D13832E556B804F6F3887 /* HomeParts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeParts.swift; sourceTree = "<group>"; };+ 41B8435B1585E5ECE113AC49 /* DebugEntry.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DebugEntry.swift; sourceTree = "<group>"; };+ 435B39A7D499300AADA2D16C /* ProbeFit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProbeFit.swift; sourceTree = "<group>"; };+ 43A1CAA88BC5B551B872615F /* AppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppModel.swift; sourceTree = "<group>"; };+ 43CF0FDDD155E930C9AC80D8 /* ReviewMedia.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReviewMedia.swift; sourceTree = "<group>"; };+ 44E6D0770452B562B5CA484E /* VideoTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VideoTests.swift; sourceTree = "<group>"; };+ 458E8069AA8BE0B721C9AD7A /* Actions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Actions.swift; sourceTree = "<group>"; };+ 45B51ED9B63507FA8E2D2A52 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };+ 4BBF99F934AC45DB1B8B9324 /* RunRecovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunRecovery.swift; sourceTree = "<group>"; };+ 4D9FABC284798F9949C1A8EF /* LogUploader.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LogUploader.swift; sourceTree = "<group>"; };+ 541D1A2837E5F270700EAF55 /* Redactor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Redactor.swift; sourceTree = "<group>"; };+ 5538B879586D04FB7F15C7E5 /* IntentBridge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IntentBridge.swift; sourceTree = "<group>"; };+ 5754C9233BF0BA12F8EB78D7 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist; path = Info.plist; sourceTree = "<group>"; };+ 5962900FEB08728899160DD1 /* DemoRecorder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DemoRecorder.swift; sourceTree = "<group>"; };+ 607F9EBBC39E74507B73F751 /* H264Decoder.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = H264Decoder.swift; sourceTree = "<group>"; };+ 65736EFE5D5C4AF40EDC5F92 /* AutoCalibrator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutoCalibrator.swift; sourceTree = "<group>"; };+ 6DCAEE3FDF94357F8875E473 /* HomeView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HomeView.swift; sourceTree = "<group>"; };+ 6EC7C29EBD2DA1A602B0BED2 /* AppShortcuts.xcstrings */ = {isa = PBXFileReference; lastKnownFileType = text.json.xcstrings; path = AppShortcuts.xcstrings; sourceTree = "<group>"; };+ 769290C5E01DE7CA97412DDA /* prompts */ = {isa = PBXFileReference; lastKnownFileType = folder; name = prompts; path = ../prompts; sourceTree = SOURCE_ROOT; };+ 794E46A6A28E406A3D606661 /* ReviewTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReviewTests.swift; sourceTree = "<group>"; };+ 86452ED01E883A6E57BB13E4 /* AgentActivityWidget.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentActivityWidget.swift; sourceTree = "<group>"; };+ 8AE108AA4534D13B7AC12079 /* Recovery.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Recovery.swift; sourceTree = "<group>"; };+ 8B2B975DEE7BC511DC51441F /* Prompts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Prompts.swift; sourceTree = "<group>"; };+ 8C498727CAF51C5A955A8A10 /* PrivacyViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PrivacyViews.swift; sourceTree = "<group>"; };+ 8E64CF4B18DBAB014C7E9314 /* StepFrame.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StepFrame.swift; sourceTree = "<group>"; };+ 8F2E6CFBDF20832FF9626D99 /* RecoveryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecoveryTests.swift; sourceTree = "<group>"; };+ 915FC0D291F09BE0A0439D9C /* RunsView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunsView.swift; sourceTree = "<group>"; };+ 9419B84DE8B4B7CD816AF19B /* ReviewSheets.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReviewSheets.swift; sourceTree = "<group>"; };+ 953BF9D5FB798BA1F3CEC832 /* IPhoneAgentApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IPhoneAgentApp.swift; sourceTree = "<group>"; };+ 96BDA430E0C54DC956DE9366 /* StatusChips.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StatusChips.swift; sourceTree = "<group>"; };+ 98111895572CDFBCBA4C5268 /* Shared.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Shared.xcconfig; sourceTree = "<group>"; };+ 98425438C4A7C1EB827CDD2C /* IPhoneAgent.app */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = wrapper.application; path = IPhoneAgent.app; sourceTree = BUILT_PRODUCTS_DIR; };+ 99381FBF82EA7EB76556866E /* OnboardingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnboardingView.swift; sourceTree = "<group>"; };+ A11E0FF01881451EBB3D18FF /* AgentActivity.appex */ = {isa = PBXFileReference; includeInIndex = 0; lastKnownFileType = "wrapper.app-extension"; path = AgentActivity.appex; sourceTree = BUILT_PRODUCTS_DIR; };+ A409B3696F547E712B4D4D14 /* PokeableFace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PokeableFace.swift; sourceTree = "<group>"; };+ A54BC007EE5C64A13CDEE9EE /* IslandTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandTests.swift; sourceTree = "<group>"; };+ A5CC3BCF7F90AF60B075DD96 /* Pointer.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Pointer.swift; sourceTree = "<group>"; };+ A7314ABD64EC1106422C685E /* AgentFace.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentFace.swift; sourceTree = "<group>"; };+ AA04712864CA08DA02B08369 /* ShareTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShareTests.swift; sourceTree = "<group>"; };+ AF7D99C79D12EBD49F30723F /* ReviewModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ReviewModel.swift; sourceTree = "<group>"; };+ B155ADD97189D634A809EDE9 /* AgentActivity.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentActivity.swift; sourceTree = "<group>"; };+ B1B84B4F1C81E697ACB30630 /* RunShare.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RunShare.swift; sourceTree = "<group>"; };+ B260480A536241A2B9043EE1 /* AgentShortcuts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentShortcuts.swift; sourceTree = "<group>"; };+ B9719A5EC1DD7C5033CC8DF5 /* Metrics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Metrics.swift; sourceTree = "<group>"; };+ C12C6B350F7AFD555CE0B8EA /* HotspotJoin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HotspotJoin.swift; sourceTree = "<group>"; };+ C5099810C37BB0AD66EDC8C8 /* TouchProbe.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TouchProbe.swift; sourceTree = "<group>"; };+ C70A2F48B5948F180DF1450C /* TouchCalibration.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TouchCalibration.swift; sourceTree = "<group>"; };+ CD4270DF66937405FC86B145 /* VideoAssembler.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VideoAssembler.swift; sourceTree = "<group>"; };+ CFB37456C763ADFEF9E577A2 /* IslandStatus.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IslandStatus.swift; sourceTree = "<group>"; };+ D17A722B1C48BF8FBF8B4222 /* OnboardingDemos.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = OnboardingDemos.swift; sourceTree = "<group>"; };+ D222722DF7856F9253B9784E /* IntentDetailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IntentDetailView.swift; sourceTree = "<group>"; };+ D317C60AA727B6A20A589DAC /* AssistiveTouchSpots.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AssistiveTouchSpots.swift; sourceTree = "<group>"; };+ D9615E8664A5DC600B1B97E0 /* VideoFeed.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = VideoFeed.swift; sourceTree = "<group>"; };+ DA2DCFC32B990B166DF9C1C6 /* IPhoneAgent.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = IPhoneAgent.entitlements; sourceTree = "<group>"; };+ DCDA925D0FFD42810895573C /* LLMClient.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LLMClient.swift; sourceTree = "<group>"; };+ DCDFF66F3082E46B88130ABC /* AgentTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AgentTests.swift; sourceTree = "<group>"; };+ E1828194EBD7CDB8FEFF8643 /* CalibrationViews.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CalibrationViews.swift; sourceTree = "<group>"; };+ E1FF376927D9503ABF677854 /* Vision.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Vision.swift; sourceTree = "<group>"; };+ E2E3712143A195602610004B /* CalibrationToast.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CalibrationToast.swift; sourceTree = "<group>"; };+ E37B39FEB9A7A965ED4A86B3 /* Localizable.xcstrings */ = {isa = PBXFileReference; lastKnownFileType = text.json.xcstrings; path = Localizable.xcstrings; sourceTree = "<group>"; };+ E7721FA5F1DD53610AD0B737 /* InfoPlist.xcstrings */ = {isa = PBXFileReference; lastKnownFileType = text.json.xcstrings; path = InfoPlist.xcstrings; sourceTree = "<group>"; };+ E948F0EBC262C7ABF8E413E5 /* AboutView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AboutView.swift; sourceTree = "<group>"; };+ EDB8774D34E5E3FEF5C7A1E6 /* Settings.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Settings.swift; sourceTree = "<group>"; };+ F071F3E4D7B82DE70AE75A81 /* LLMTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LLMTests.swift; sourceTree = "<group>"; };+ F0918D2C621FD17EDD51AF5E /* mock-frame.jpg */ = {isa = PBXFileReference; lastKnownFileType = image.jpeg; path = "mock-frame.jpg"; sourceTree = "<group>"; };+ F775C2B833B33E951A629957 /* PromptTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PromptTests.swift; sourceTree = "<group>"; };+ F960AA3F536A5DF20F8E908A /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };+ FCC7FAA4989F36E7F9B4C021 /* JSON.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = JSON.swift; sourceTree = "<group>"; };+/* End PBXFileReference section */++/* Begin PBXGroup section */+ 0753133D3A6ABA1AE76560A5 /* Agent */ = {+ isa = PBXGroup;+ children = (+ 458E8069AA8BE0B721C9AD7A /* Actions.swift */,+ 17DBD3270E7E91B39C3C7438 /* AgentLoop.swift */,+ D317C60AA727B6A20A589DAC /* AssistiveTouchSpots.swift */,+ FCC7FAA4989F36E7F9B4C021 /* JSON.swift */,+ A5CC3BCF7F90AF60B075DD96 /* Pointer.swift */,+ 435B39A7D499300AADA2D16C /* ProbeFit.swift */,+ 8B2B975DEE7BC511DC51441F /* Prompts.swift */,+ 8AE108AA4534D13B7AC12079 /* Recovery.swift */,+ 2169FBFC7A60B9FC1FF1E724 /* StepText.swift */,+ E1FF376927D9503ABF677854 /* Vision.swift */,+ );+ path = Agent;+ sourceTree = "<group>";+ };+ 08845C942DD375164EDA5202 /* Shared */ = {+ isa = PBXGroup;+ children = (+ B155ADD97189D634A809EDE9 /* AgentActivity.swift */,+ A7314ABD64EC1106422C685E /* AgentFace.swift */,+ 0278B11885CA8C4A96C96531 /* AgentIntents.swift */,+ 3EC8ECB7FF0B63991E8AEFFB /* AgentSnapshot.swift */,+ );+ path = Shared;+ sourceTree = "<group>";+ };+ 1EA48D564DC11DC29CADDB20 /* Video */ = {+ isa = PBXGroup;+ children = (+ 607F9EBBC39E74507B73F751 /* H264Decoder.swift */,+ CD4270DF66937405FC86B145 /* VideoAssembler.swift */,+ D9615E8664A5DC600B1B97E0 /* VideoFeed.swift */,+ );+ path = Video;+ sourceTree = "<group>";+ };+ 2E129AC3427FD8596CDD739B = {+ isa = PBXGroup;+ children = (+ 769290C5E01DE7CA97412DDA /* prompts */,+ 6B89A631EB4E7F210263D373 /* AgentActivity */,+ 3BFB1D3C3353300444555F3F /* Config */,+ 69ABF23BB7D5C10E752A0434 /* IPhoneAgent */,+ 3C577534E113D39F4ACCDA56 /* IPhoneAgentTests */,+ 08845C942DD375164EDA5202 /* Shared */,+ E2CB2956C0FAB159A2518364 /* Products */,+ );+ sourceTree = "<group>";+ };+ 3BFB1D3C3353300444555F3F /* Config */ = {+ isa = PBXGroup;+ children = (+ 98111895572CDFBCBA4C5268 /* Shared.xcconfig */,+ );+ path = Config;+ sourceTree = "<group>";+ };+ 3C577534E113D39F4ACCDA56 /* IPhoneAgentTests */ = {+ isa = PBXGroup;+ children = (+ DCDFF66F3082E46B88130ABC /* AgentTests.swift */,+ 23A9A9D917B2B2FC534E7DBA /* DeviceTests.swift */,+ A54BC007EE5C64A13CDEE9EE /* IslandTests.swift */,+ F071F3E4D7B82DE70AE75A81 /* LLMTests.swift */,+ F775C2B833B33E951A629957 /* PromptTests.swift */,+ 8F2E6CFBDF20832FF9626D99 /* RecoveryTests.swift */,+ 794E46A6A28E406A3D606661 /* ReviewTests.swift */,+ AA04712864CA08DA02B08369 /* ShareTests.swift */,+ 0884D2AF849046D0FA2E62C1 /* StoreTests.swift */,+ 44E6D0770452B562B5CA484E /* VideoTests.swift */,+ 1887982FE1A729487269296E /* VisionTests.swift */,+ );+ path = IPhoneAgentTests;+ sourceTree = "<group>";+ };+ 587F0A7B34E5140D82A4CAAC /* UI */ = {+ isa = PBXGroup;+ children = (+ E948F0EBC262C7ABF8E413E5 /* AboutView.swift */,+ E2E3712143A195602610004B /* CalibrationToast.swift */,+ E1828194EBD7CDB8FEFF8643 /* CalibrationViews.swift */,+ 2F3122E7A1DB53F3BFCCFD06 /* DiagnosticsView.swift */,+ 406D13832E556B804F6F3887 /* HomeParts.swift */,+ 6DCAEE3FDF94357F8875E473 /* HomeView.swift */,+ D222722DF7856F9253B9784E /* IntentDetailView.swift */,+ 3B94481DB51BD93A2900698F /* ModelSettingsView.swift */,+ D17A722B1C48BF8FBF8B4222 /* OnboardingDemos.swift */,+ 22464AAA35416D0351B8063C /* OnboardingPages.swift */,+ 99381FBF82EA7EB76556866E /* OnboardingView.swift */,+ A409B3696F547E712B4D4D14 /* PokeableFace.swift */,+ 8C498727CAF51C5A955A8A10 /* PrivacyViews.swift */,+ 915FC0D291F09BE0A0439D9C /* RunsView.swift */,+ 3E74E2758C4170812147466F /* SettingsView.swift */,+ 96BDA430E0C54DC956DE9366 /* StatusChips.swift */,+ 2418164D156C7D2934CA5312 /* Theme.swift */,+ );+ path = UI;+ sourceTree = "<group>";+ };+ 69ABF23BB7D5C10E752A0434 /* IPhoneAgent */ = {+ isa = PBXGroup;+ children = (+ 6EC7C29EBD2DA1A602B0BED2 /* AppShortcuts.xcstrings */,+ F960AA3F536A5DF20F8E908A /* Assets.xcassets */,+ 5754C9233BF0BA12F8EB78D7 /* Info.plist */,+ E7721FA5F1DD53610AD0B737 /* InfoPlist.xcstrings */,+ DA2DCFC32B990B166DF9C1C6 /* IPhoneAgent.entitlements */,+ 1C25AC81D9FBF6073FDD1851 /* Localizable.xcstrings */,+ 0753133D3A6ABA1AE76560A5 /* Agent */,+ 7CA15ABF933E415D7A5C913F /* App */,+ 8DC40723EB5CCA5BC6501702 /* Board */,+ DF6BCFAD193E805D67205DCA /* Mock */,+ A30003CF353570FD93F44FB3 /* Review */,+ 84CF32A0010E6F1E5085D90E /* Services */,+ 587F0A7B34E5140D82A4CAAC /* UI */,+ 1EA48D564DC11DC29CADDB20 /* Video */,+ );+ path = IPhoneAgent;+ sourceTree = "<group>";+ };+ 6B89A631EB4E7F210263D373 /* AgentActivity */ = {+ isa = PBXGroup;+ children = (+ 16165E2AD13D29F06CBFA5B0 /* AgentActivity.entitlements */,+ 86452ED01E883A6E57BB13E4 /* AgentActivityWidget.swift */,+ 3A091027B026D22579AA4972 /* HomeWidgets.swift */,+ 45B51ED9B63507FA8E2D2A52 /* Info.plist */,+ E37B39FEB9A7A965ED4A86B3 /* Localizable.xcstrings */,+ );+ path = AgentActivity;+ sourceTree = "<group>";+ };+ 7CA15ABF933E415D7A5C913F /* App */ = {+ isa = PBXGroup;+ children = (+ B260480A536241A2B9043EE1 /* AgentShortcuts.swift */,+ 43A1CAA88BC5B551B872615F /* AppModel.swift */,+ 25891E89F3EF8CFF37935661 /* AppPresence.swift */,+ 65736EFE5D5C4AF40EDC5F92 /* AutoCalibrator.swift */,+ 41B8435B1585E5ECE113AC49 /* DebugEntry.swift */,+ 5962900FEB08728899160DD1 /* DemoRecorder.swift */,+ C12C6B350F7AFD555CE0B8EA /* HotspotJoin.swift */,+ 5538B879586D04FB7F15C7E5 /* IntentBridge.swift */,+ 953BF9D5FB798BA1F3CEC832 /* IPhoneAgentApp.swift */,+ CFB37456C763ADFEF9E577A2 /* IslandStatus.swift */,+ 27A03E1A122C50B8ED88AC91 /* LiveActivity.swift */,+ 4BBF99F934AC45DB1B8B9324 /* RunRecovery.swift */,+ 38FB6FEBD55DCBE8EED6834C /* RunSession.swift */,+ C70A2F48B5948F180DF1450C /* TouchCalibration.swift */,+ C5099810C37BB0AD66EDC8C8 /* TouchProbe.swift */,+ );+ path = App;+ sourceTree = "<group>";+ };+ 84CF32A0010E6F1E5085D90E /* Services */ = {+ isa = PBXGroup;+ children = (+ 0B88A1538529C9674B323370 /* DebugLog.swift */,+ DCDA925D0FFD42810895573C /* LLMClient.swift */,+ 4D9FABC284798F9949C1A8EF /* LogUploader.swift */,+ B9719A5EC1DD7C5033CC8DF5 /* Metrics.swift */,+ 05DA6345A40715C8BD2AED6C /* Notifier.swift */,+ 541D1A2837E5F270700EAF55 /* Redactor.swift */,+ B1B84B4F1C81E697ACB30630 /* RunShare.swift */,+ EDB8774D34E5E3FEF5C7A1E6 /* Settings.swift */,+ 35D21F22B2928E33B4036328 /* Stores.swift */,+ 226739C44752297294C75671 /* TraceStore.swift */,+ );+ path = Services;+ sourceTree = "<group>";+ };+ 8DC40723EB5CCA5BC6501702 /* Board */ = {+ isa = PBXGroup;+ children = (+ 02C2C2C9EBE006E896050646 /* BoardCommands.swift */,+ 33107099A7483949F03FBDB6 /* BoardLink.swift */,+ 0DFECC30B2ADEB1BB69072EC /* BoardProtocol.swift */,+ );+ path = Board;+ sourceTree = "<group>";+ };+ A30003CF353570FD93F44FB3 /* Review */ = {+ isa = PBXGroup;+ children = (+ 43CF0FDDD155E930C9AC80D8 /* ReviewMedia.swift */,+ AF7D99C79D12EBD49F30723F /* ReviewModel.swift */,+ 9419B84DE8B4B7CD816AF19B /* ReviewSheets.swift */,+ 31BF05E92BF9DC3156F81ED6 /* ReviewView.swift */,+ 8E64CF4B18DBAB014C7E9314 /* StepFrame.swift */,+ );+ path = Review;+ sourceTree = "<group>";+ };+ DF6BCFAD193E805D67205DCA /* Mock */ = {+ isa = PBXGroup;+ children = (+ F0918D2C621FD17EDD51AF5E /* mock-frame.jpg */,+ 13664BFD54E7827E0E53B7F6 /* MockMode.swift */,+ );+ path = Mock;+ sourceTree = "<group>";+ };+ E2CB2956C0FAB159A2518364 /* Products */ = {+ isa = PBXGroup;+ children = (+ A11E0FF01881451EBB3D18FF /* AgentActivity.appex */,+ 98425438C4A7C1EB827CDD2C /* IPhoneAgent.app */,+ 24A4292E1153548AEB53299E /* IPhoneAgentTests.xctest */,+ );+ name = Products;+ sourceTree = "<group>";+ };+/* End PBXGroup section */++/* Begin PBXNativeTarget section */+ 18572F489CB05524CA0AD23E /* IPhoneAgentTests */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = 8DD62507E8662534B1BD2721 /* Build configuration list for PBXNativeTarget "IPhoneAgentTests" */;+ buildPhases = (+ B02D1E21CE897BD46B00BFF2 /* Sources */,+ );+ buildRules = (+ );+ dependencies = (+ 7455C39275576460C09D45CB /* PBXTargetDependency */,+ );+ name = IPhoneAgentTests;+ packageProductDependencies = (+ );+ productName = IPhoneAgentTests;+ productReference = 24A4292E1153548AEB53299E /* IPhoneAgentTests.xctest */;+ productType = "com.apple.product-type.bundle.unit-test";+ };+ 5983F0E1632FA0FDDDEAB3FC /* IPhoneAgent */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = E829CB2B6C7DD210C0DEDC25 /* Build configuration list for PBXNativeTarget "IPhoneAgent" */;+ buildPhases = (+ F1224053C142E1A541220796 /* Sources */,+ 43117A04F8604C83490CF3E3 /* Resources */,+ 51D918A1DE20665371F6629D /* Embed Foundation Extensions */,+ );+ buildRules = (+ );+ dependencies = (+ D2EE8688804B4066368D13F0 /* PBXTargetDependency */,+ );+ name = IPhoneAgent;+ packageProductDependencies = (+ );+ productName = IPhoneAgent;+ productReference = 98425438C4A7C1EB827CDD2C /* IPhoneAgent.app */;+ productType = "com.apple.product-type.application";+ };+ 6DB9E3E8534E6FC1BF6E382C /* AgentActivity */ = {+ isa = PBXNativeTarget;+ buildConfigurationList = 2E54A25279D231D9DFC2760D /* Build configuration list for PBXNativeTarget "AgentActivity" */;+ buildPhases = (+ 06DCF8A537797EFF26DB9DAA /* Sources */,+ F9CE9155A87828D94D4331F3 /* Resources */,+ );+ buildRules = (+ );+ dependencies = (+ );+ name = AgentActivity;+ packageProductDependencies = (+ );+ productName = AgentActivity;+ productReference = A11E0FF01881451EBB3D18FF /* AgentActivity.appex */;+ productType = "com.apple.product-type.app-extension";+ };+/* End PBXNativeTarget section */++/* Begin PBXProject section */+ A87BF3B3154BD2A36E9E8546 /* Project object */ = {+ isa = PBXProject;+ attributes = {+ BuildIndependentTargetsInParallel = YES;+ LastUpgradeCheck = 1430;+ TargetAttributes = {+ 18572F489CB05524CA0AD23E = {+ ProvisioningStyle = Automatic;+ };+ 5983F0E1632FA0FDDDEAB3FC = {+ ProvisioningStyle = Automatic;+ };+ 6DB9E3E8534E6FC1BF6E382C = {+ ProvisioningStyle = Automatic;+ };+ };+ };+ buildConfigurationList = 06049FB4DD69300CA63BABD4 /* Build configuration list for PBXProject "IPhoneAgent" */;+ developmentRegion = en;+ hasScannedForEncodings = 0;+ knownRegions = (+ Base,+ en,+ "zh-Hans",+ );+ mainGroup = 2E129AC3427FD8596CDD739B;+ minimizedProjectReferenceProxies = 1;+ preferredProjectObjectVersion = 77;+ productRefGroup = E2CB2956C0FAB159A2518364 /* Products */;+ projectDirPath = "";+ projectRoot = "";+ targets = (+ 5983F0E1632FA0FDDDEAB3FC /* IPhoneAgent */,+ 6DB9E3E8534E6FC1BF6E382C /* AgentActivity */,+ 18572F489CB05524CA0AD23E /* IPhoneAgentTests */,+ );+ };+/* End PBXProject section */++/* Begin PBXResourcesBuildPhase section */+ 43117A04F8604C83490CF3E3 /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ D5D197473F9BD99FD38F6231 /* AppShortcuts.xcstrings in Resources */,+ 180133912100FC228377AE9A /* Assets.xcassets in Resources */,+ 85678CC068CF3297ECF345DF /* InfoPlist.xcstrings in Resources */,+ 63CB6644E6517C6B12F3E0AB /* Localizable.xcstrings in Resources */,+ EF83C4DFA24497FDB0BF123E /* mock-frame.jpg in Resources */,+ D04078EE246F6B5EB38D64B5 /* prompts in Resources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ F9CE9155A87828D94D4331F3 /* Resources */ = {+ isa = PBXResourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 84CA12989B5CB62129C3419B /* Localizable.xcstrings in Resources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXResourcesBuildPhase section */++/* Begin PBXSourcesBuildPhase section */+ 06DCF8A537797EFF26DB9DAA /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 28CC6521C0BE74701079D0E1 /* AgentActivity.swift in Sources */,+ B86BD0431A675EC2681E03A7 /* AgentActivityWidget.swift in Sources */,+ 5529FEF43DA98563B4BCFEC1 /* AgentFace.swift in Sources */,+ 6787B6280DD3923D995F8611 /* AgentIntents.swift in Sources */,+ 9CB0E6A2FE92EF5422B95377 /* AgentSnapshot.swift in Sources */,+ 796CF6A9427314B483BBA14B /* HomeWidgets.swift in Sources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ B02D1E21CE897BD46B00BFF2 /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 7D859BE4F1E945FE96CD8C61 /* AgentTests.swift in Sources */,+ 607B1520E654F13F1F304F4D /* DeviceTests.swift in Sources */,+ 2CF6A30C3D72E05EEBC6FFED /* IslandTests.swift in Sources */,+ 48100361D2ECFE7E36F83F9D /* LLMTests.swift in Sources */,+ 962068E4EB7D31C8E1E0A9F2 /* PromptTests.swift in Sources */,+ 42A1AE0EA1AC18461ED8F33B /* RecoveryTests.swift in Sources */,+ 90594045D55F83E5EEE53574 /* ReviewTests.swift in Sources */,+ 6CDEB83B98075E73AEA52F13 /* ShareTests.swift in Sources */,+ 0638DE7546BE2E3578EAE3D6 /* StoreTests.swift in Sources */,+ 8FCFB9340A6E3F74CE629FBF /* VideoTests.swift in Sources */,+ 3607786AAF7296B3414B6F08 /* VisionTests.swift in Sources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+ F1224053C142E1A541220796 /* Sources */ = {+ isa = PBXSourcesBuildPhase;+ buildActionMask = 2147483647;+ files = (+ 0A553429560D1697C678A682 /* AboutView.swift in Sources */,+ 2671E23FE56D69B0CEAB4EF6 /* Actions.swift in Sources */,+ E8FA336F818FBAB651C32BEE /* AgentActivity.swift in Sources */,+ ABEF22E60573E04FACD0E4A9 /* AgentFace.swift in Sources */,+ 74222DFADC00836F21E19FEA /* AgentIntents.swift in Sources */,+ 7B925E867DA328C9A682CDE0 /* AgentLoop.swift in Sources */,+ 2013DD86239B8EE1396CB82B /* AgentShortcuts.swift in Sources */,+ 57716E1B9BBB6026600DAD4C /* AgentSnapshot.swift in Sources */,+ DDC8DB5DA64D75338F3A52DF /* AppModel.swift in Sources */,+ 812925C7EC9F24F99DC06037 /* AppPresence.swift in Sources */,+ F77EB884A6AE61AC290911D9 /* AssistiveTouchSpots.swift in Sources */,+ 1BBB78AF1CD2B329778F6E01 /* AutoCalibrator.swift in Sources */,+ 66CADEEED2A075ECD5070131 /* BoardCommands.swift in Sources */,+ D48CF75915F3D1FFE18ADC3A /* BoardLink.swift in Sources */,+ BD09EA4793C0B09297190CD9 /* BoardProtocol.swift in Sources */,+ 173BD54931BD69B83D7F6FD3 /* CalibrationToast.swift in Sources */,+ 8A11B8068D97194AA3C9723B /* CalibrationViews.swift in Sources */,+ 006434261FDDF11EA3BF16E6 /* DebugEntry.swift in Sources */,+ 419FA08397BAF31F91A62633 /* DebugLog.swift in Sources */,+ 5D657D39BD5F6808ED60EDEA /* DemoRecorder.swift in Sources */,+ 9BA8ABE4398546618D6AE675 /* DiagnosticsView.swift in Sources */,+ 4A2BFED999CA010867968893 /* H264Decoder.swift in Sources */,+ 041DFAB6BE68032D48592AC2 /* HomeParts.swift in Sources */,+ 948C0D1F80207A8E5874D943 /* HomeView.swift in Sources */,+ B9B15030A9EEC21B4512533B /* HotspotJoin.swift in Sources */,+ 7BBA01EDC5514C6EC77AE6E2 /* IPhoneAgentApp.swift in Sources */,+ A0DECAC4E4DBADB432942A83 /* IntentBridge.swift in Sources */,+ 1DBE4EFF0FB05C1390236410 /* IntentDetailView.swift in Sources */,+ F0989DBA8FA72168CA371221 /* IslandStatus.swift in Sources */,+ A42DB537742861FF668DB34A /* JSON.swift in Sources */,+ BB3C60862112DB87D3555158 /* LLMClient.swift in Sources */,+ AD702230192ADBF827044490 /* LiveActivity.swift in Sources */,+ F2FFDB2986493F65EB6A9738 /* LogUploader.swift in Sources */,+ 7B684FAA8B218BB9798F9EC3 /* Metrics.swift in Sources */,+ B356EECAFE045249704E63FD /* MockMode.swift in Sources */,+ 7F412478410DC75BC26A0D5C /* ModelSettingsView.swift in Sources */,+ 4CA70811574C401EB0012355 /* Notifier.swift in Sources */,+ CFDC07BA9E09D3446164B1B9 /* OnboardingDemos.swift in Sources */,+ 189667BD260B5751915C28AF /* OnboardingPages.swift in Sources */,+ 8738C1055CD8FE6AFD6B9204 /* OnboardingView.swift in Sources */,+ 5EC81FBCFE439052A8F26EA2 /* Pointer.swift in Sources */,+ A271DC80F0EB0BA42FD7D022 /* PokeableFace.swift in Sources */,+ 72E72D656EFE51EB73F94A5C /* PrivacyViews.swift in Sources */,+ 58405C052C5CE287759E2AA4 /* ProbeFit.swift in Sources */,+ CED032EC090264C33AD7D1D1 /* Prompts.swift in Sources */,+ 079927568C3047DA5C2F105E /* Recovery.swift in Sources */,+ 8F45E1F46FB046780AC0838F /* Redactor.swift in Sources */,+ 2A48924EF6EF7A39D5A05E21 /* ReviewMedia.swift in Sources */,+ 87BA6110B7AD061157A0995C /* ReviewModel.swift in Sources */,+ 7A0635EEEE8295BBA54B9DD9 /* ReviewSheets.swift in Sources */,+ F2D091FC47717266EFF75FBA /* ReviewView.swift in Sources */,+ 24645B70C28410D8E96A9D92 /* RunRecovery.swift in Sources */,+ A5A1640A615256B576F9A055 /* RunSession.swift in Sources */,+ F6301B26DAF28C96D09F6D8E /* RunShare.swift in Sources */,+ 1DE8E596908DD14C90E40761 /* RunsView.swift in Sources */,+ E86B4A3177FC9F0A5D846C2F /* Settings.swift in Sources */,+ 4C9AF1D3470474D2AB745D00 /* SettingsView.swift in Sources */,+ 96C08C1CFEECA69484811137 /* StatusChips.swift in Sources */,+ A177729443FE818CD754FD64 /* StepFrame.swift in Sources */,+ 80EA74A9A970F441C661524C /* StepText.swift in Sources */,+ 28166EA554E9D943A62AF961 /* Stores.swift in Sources */,+ 0B7AB0B39C3257BD2E395DC2 /* Theme.swift in Sources */,+ 4C33F19F733F62B5A131BE9E /* TouchCalibration.swift in Sources */,+ C4F3ADB5189E27B999BDDF83 /* TouchProbe.swift in Sources */,+ DD9700301BED070734BD4F87 /* TraceStore.swift in Sources */,+ F3DE9777E0FAD414E17465BC /* VideoAssembler.swift in Sources */,+ 63B0CAE819339D8FC103AC8B /* VideoFeed.swift in Sources */,+ 8D154D84FE2D6E532A27E095 /* Vision.swift in Sources */,+ );+ runOnlyForDeploymentPostprocessing = 0;+ };+/* End PBXSourcesBuildPhase section */++/* Begin PBXTargetDependency section */+ 7455C39275576460C09D45CB /* PBXTargetDependency */ = {+ isa = PBXTargetDependency;+ target = 5983F0E1632FA0FDDDEAB3FC /* IPhoneAgent */;+ targetProxy = 7554F08B663A589FB7FAF693 /* PBXContainerItemProxy */;+ };+ D2EE8688804B4066368D13F0 /* PBXTargetDependency */ = {+ isa = PBXTargetDependency;+ target = 6DB9E3E8534E6FC1BF6E382C /* AgentActivity */;+ targetProxy = A1F8805FC5601538374FA630 /* PBXContainerItemProxy */;+ };+/* End PBXTargetDependency section */++/* Begin XCBuildConfiguration section */+ 1828451D6D5172A2262E25F2 /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ CODE_SIGN_ENTITLEMENTS = "$(IA_WIDGET_ENTITLEMENTS)";+ GENERATE_INFOPLIST_FILE = NO;+ INFOPLIST_FILE = AgentActivity/Info.plist;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ "@executable_path/../../Frameworks",+ );+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;+ PRODUCT_BUNDLE_IDENTIFIER = "$(IA_BUNDLE_ID).activity";+ PRODUCT_NAME = AgentActivity;+ SDKROOT = iphoneos;+ SKIP_INSTALL = YES;+ SWIFT_EMIT_LOC_STRINGS = YES;+ TARGETED_DEVICE_FAMILY = "1,2";+ };+ name = Release;+ };+ 279C9C9C0E8A091798D611ED /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_ENTITLEMENTS = "$(IA_ENTITLEMENTS)";+ CODE_SIGN_IDENTITY = "iPhone Developer";+ GENERATE_INFOPLIST_FILE = NO;+ INFOPLIST_FILE = IPhoneAgent/Info.plist;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ );+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;+ PRODUCT_BUNDLE_IDENTIFIER = "$(IA_BUNDLE_ID)";+ PRODUCT_NAME = IPhoneAgent;+ SDKROOT = iphoneos;+ SWIFT_EMIT_LOC_STRINGS = YES;+ TARGETED_DEVICE_FAMILY = "1,2";+ };+ name = Debug;+ };+ 2FE3963DC8F82D28318FBB47 /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ BUNDLE_LOADER = "$(TEST_HOST)";+ GENERATE_INFOPLIST_FILE = YES;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ "@loader_path/Frameworks",+ );+ PRODUCT_BUNDLE_IDENTIFIER = "$(IA_BUNDLE_ID).tests";+ SDKROOT = iphoneos;+ TARGETED_DEVICE_FAMILY = "1,2";+ TEST_HOST = "$(BUILT_PRODUCTS_DIR)/IPhoneAgent.app/IPhoneAgent";+ };+ name = Release;+ };+ 9211D4AD6677A1CC9066E7CC /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ BUNDLE_LOADER = "$(TEST_HOST)";+ GENERATE_INFOPLIST_FILE = YES;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ "@loader_path/Frameworks",+ );+ PRODUCT_BUNDLE_IDENTIFIER = "$(IA_BUNDLE_ID).tests";+ SDKROOT = iphoneos;+ TARGETED_DEVICE_FAMILY = "1,2";+ TEST_HOST = "$(BUILT_PRODUCTS_DIR)/IPhoneAgent.app/IPhoneAgent";+ };+ name = Debug;+ };+ A6B069D64E88C7CBEF6BACAF /* Debug */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ CODE_SIGN_ENTITLEMENTS = "$(IA_WIDGET_ENTITLEMENTS)";+ GENERATE_INFOPLIST_FILE = NO;+ INFOPLIST_FILE = AgentActivity/Info.plist;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ "@executable_path/../../Frameworks",+ );+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;+ PRODUCT_BUNDLE_IDENTIFIER = "$(IA_BUNDLE_ID).activity";+ PRODUCT_NAME = AgentActivity;+ SDKROOT = iphoneos;+ SKIP_INSTALL = YES;+ SWIFT_EMIT_LOC_STRINGS = YES;+ TARGETED_DEVICE_FAMILY = "1,2";+ };+ name = Debug;+ };+ BC923BBCAD113743DF8FC255 /* Release */ = {+ isa = XCBuildConfiguration;+ buildSettings = {+ ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;+ CODE_SIGN_ENTITLEMENTS = "$(IA_ENTITLEMENTS)";+ CODE_SIGN_IDENTITY = "iPhone Developer";+ GENERATE_INFOPLIST_FILE = NO;+ INFOPLIST_FILE = IPhoneAgent/Info.plist;+ LD_RUNPATH_SEARCH_PATHS = (+ "$(inherited)",+ "@executable_path/Frameworks",+ );+ LOCALIZATION_PREFERS_STRING_CATALOGS = YES;+ PRODUCT_BUNDLE_IDENTIFIER = "$(IA_BUNDLE_ID)";+ PRODUCT_NAME = IPhoneAgent;+ SDKROOT = iphoneos;+ SWIFT_EMIT_LOC_STRINGS = YES;+ TARGETED_DEVICE_FAMILY = "1,2";+ };+ name = Release;+ };+ C91432F6930E64A0403C1076 /* Release */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 98111895572CDFBCBA4C5268 /* Shared.xcconfig */;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";+ CLANG_CXX_LIBRARY = "libc++";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_ENABLE_OBJC_WEAK = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ CODE_SIGN_STYLE = Automatic;+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";+ ENABLE_NS_ASSERTIONS = NO;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ GCC_C_LANGUAGE_STANDARD = gnu11;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ IPHONEOS_DEPLOYMENT_TARGET = 18.0;+ MTL_ENABLE_DEBUG_INFO = NO;+ MTL_FAST_MATH = YES;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SDKROOT = iphoneos;+ SWIFT_COMPILATION_MODE = wholemodule;+ SWIFT_OPTIMIZATION_LEVEL = "-O";+ SWIFT_VERSION = 5.0;+ TARGETED_DEVICE_FAMILY = 1;+ };+ name = Release;+ };+ D1BDC4E2B01698A65B6D5FDB /* Debug */ = {+ isa = XCBuildConfiguration;+ baseConfigurationReference = 98111895572CDFBCBA4C5268 /* Shared.xcconfig */;+ buildSettings = {+ ALWAYS_SEARCH_USER_PATHS = NO;+ CLANG_ANALYZER_NONNULL = YES;+ CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;+ CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";+ CLANG_CXX_LIBRARY = "libc++";+ CLANG_ENABLE_MODULES = YES;+ CLANG_ENABLE_OBJC_ARC = YES;+ CLANG_ENABLE_OBJC_WEAK = YES;+ CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;+ CLANG_WARN_BOOL_CONVERSION = YES;+ CLANG_WARN_COMMA = YES;+ CLANG_WARN_CONSTANT_CONVERSION = YES;+ CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;+ CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;+ CLANG_WARN_DOCUMENTATION_COMMENTS = YES;+ CLANG_WARN_EMPTY_BODY = YES;+ CLANG_WARN_ENUM_CONVERSION = YES;+ CLANG_WARN_INFINITE_RECURSION = YES;+ CLANG_WARN_INT_CONVERSION = YES;+ CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;+ CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;+ CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;+ CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;+ CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;+ CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;+ CLANG_WARN_STRICT_PROTOTYPES = YES;+ CLANG_WARN_SUSPICIOUS_MOVE = YES;+ CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;+ CLANG_WARN_UNREACHABLE_CODE = YES;+ CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;+ CODE_SIGN_STYLE = Automatic;+ COPY_PHASE_STRIP = NO;+ DEBUG_INFORMATION_FORMAT = dwarf;+ ENABLE_STRICT_OBJC_MSGSEND = YES;+ ENABLE_TESTABILITY = YES;+ GCC_C_LANGUAGE_STANDARD = gnu11;+ GCC_DYNAMIC_NO_PIC = NO;+ GCC_NO_COMMON_BLOCKS = YES;+ GCC_OPTIMIZATION_LEVEL = 0;+ GCC_PREPROCESSOR_DEFINITIONS = (+ "$(inherited)",+ "DEBUG=1",+ );+ GCC_WARN_64_TO_32_BIT_CONVERSION = YES;+ GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;+ GCC_WARN_UNDECLARED_SELECTOR = YES;+ GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;+ GCC_WARN_UNUSED_FUNCTION = YES;+ GCC_WARN_UNUSED_VARIABLE = YES;+ IPHONEOS_DEPLOYMENT_TARGET = 18.0;+ MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;+ MTL_FAST_MATH = YES;+ ONLY_ACTIVE_ARCH = YES;+ PRODUCT_NAME = "$(TARGET_NAME)";+ SDKROOT = iphoneos;+ SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;+ SWIFT_OPTIMIZATION_LEVEL = "-Onone";+ SWIFT_VERSION = 5.0;+ TARGETED_DEVICE_FAMILY = 1;+ };+ name = Debug;+ };+/* End XCBuildConfiguration section */++/* Begin XCConfigurationList section */+ 06049FB4DD69300CA63BABD4 /* Build configuration list for PBXProject "IPhoneAgent" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ D1BDC4E2B01698A65B6D5FDB /* Debug */,+ C91432F6930E64A0403C1076 /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Debug;+ };+ 2E54A25279D231D9DFC2760D /* Build configuration list for PBXNativeTarget "AgentActivity" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ A6B069D64E88C7CBEF6BACAF /* Debug */,+ 1828451D6D5172A2262E25F2 /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Debug;+ };+ 8DD62507E8662534B1BD2721 /* Build configuration list for PBXNativeTarget "IPhoneAgentTests" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 9211D4AD6677A1CC9066E7CC /* Debug */,+ 2FE3963DC8F82D28318FBB47 /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Debug;+ };+ E829CB2B6C7DD210C0DEDC25 /* Build configuration list for PBXNativeTarget "IPhoneAgent" */ = {+ isa = XCConfigurationList;+ buildConfigurations = (+ 279C9C9C0E8A091798D611ED /* Debug */,+ BC923BBCAD113743DF8FC255 /* Release */,+ );+ defaultConfigurationIsVisible = 0;+ defaultConfigurationName = Debug;+ };+/* End XCConfigurationList section */+ };+ rootObject = A87BF3B3154BD2A36E9E8546 /* Project object */;+}diff --git a/ios/IPhoneAgent.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/IPhoneAgent.xcodeproj/project.xcworkspace/contents.xcworkspacedatanew file mode 100644index 0000000..919434a--- /dev/null+++ b/ios/IPhoneAgent.xcodeproj/project.xcworkspace/contents.xcworkspacedata@@ -0,0 +1,7 @@+<?xml version="1.0" encoding="UTF-8"?>+<Workspace+ version = "1.0">+ <FileRef+ location = "self:">+ </FileRef>+</Workspace>diff --git a/ios/IPhoneAgent.xcodeproj/xcshareddata/xcschemes/IPhoneAgent.xcscheme b/ios/IPhoneAgent.xcodeproj/xcshareddata/xcschemes/IPhoneAgent.xcschemenew file mode 100644index 0000000..9a0ad91--- /dev/null+++ b/ios/IPhoneAgent.xcodeproj/xcshareddata/xcschemes/IPhoneAgent.xcscheme@@ -0,0 +1,116 @@+<?xml version="1.0" encoding="UTF-8"?>+<Scheme+ LastUpgradeVersion = "1430"+ version = "1.7">+ <BuildAction+ parallelizeBuildables = "YES"+ buildImplicitDependencies = "YES"+ runPostActionsOnFailure = "NO">+ <BuildActionEntries>+ <BuildActionEntry+ buildForTesting = "YES"+ buildForRunning = "YES"+ buildForProfiling = "YES"+ buildForArchiving = "YES"+ buildForAnalyzing = "YES">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "5983F0E1632FA0FDDDEAB3FC"+ BuildableName = "IPhoneAgent.app"+ BlueprintName = "IPhoneAgent"+ ReferencedContainer = "container:IPhoneAgent.xcodeproj">+ </BuildableReference>+ </BuildActionEntry>+ <BuildActionEntry+ buildForTesting = "YES"+ buildForRunning = "NO"+ buildForProfiling = "NO"+ buildForArchiving = "NO"+ buildForAnalyzing = "NO">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "18572F489CB05524CA0AD23E"+ BuildableName = "IPhoneAgentTests.xctest"+ BlueprintName = "IPhoneAgentTests"+ ReferencedContainer = "container:IPhoneAgent.xcodeproj">+ </BuildableReference>+ </BuildActionEntry>+ </BuildActionEntries>+ </BuildAction>+ <TestAction+ buildConfiguration = "Debug"+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"+ shouldUseLaunchSchemeArgsEnv = "YES"+ onlyGenerateCoverageForSpecifiedTargets = "NO">+ <MacroExpansion>+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "5983F0E1632FA0FDDDEAB3FC"+ BuildableName = "IPhoneAgent.app"+ BlueprintName = "IPhoneAgent"+ ReferencedContainer = "container:IPhoneAgent.xcodeproj">+ </BuildableReference>+ </MacroExpansion>+ <Testables>+ <TestableReference+ skipped = "NO"+ parallelizable = "NO">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "18572F489CB05524CA0AD23E"+ BuildableName = "IPhoneAgentTests.xctest"+ BlueprintName = "IPhoneAgentTests"+ ReferencedContainer = "container:IPhoneAgent.xcodeproj">+ </BuildableReference>+ </TestableReference>+ </Testables>+ <CommandLineArguments>+ </CommandLineArguments>+ </TestAction>+ <LaunchAction+ buildConfiguration = "Debug"+ selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"+ selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"+ launchStyle = "0"+ useCustomWorkingDirectory = "NO"+ ignoresPersistentStateOnLaunch = "NO"+ debugDocumentVersioning = "YES"+ debugServiceExtension = "internal"+ allowLocationSimulation = "YES">+ <BuildableProductRunnable+ runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "5983F0E1632FA0FDDDEAB3FC"+ BuildableName = "IPhoneAgent.app"+ BlueprintName = "IPhoneAgent"+ ReferencedContainer = "container:IPhoneAgent.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </LaunchAction>+ <ProfileAction+ buildConfiguration = "Release"+ shouldUseLaunchSchemeArgsEnv = "YES"+ savedToolIdentifier = ""+ useCustomWorkingDirectory = "NO"+ debugDocumentVersioning = "YES">+ <BuildableProductRunnable+ runnableDebuggingMode = "0">+ <BuildableReference+ BuildableIdentifier = "primary"+ BlueprintIdentifier = "5983F0E1632FA0FDDDEAB3FC"+ BuildableName = "IPhoneAgent.app"+ BlueprintName = "IPhoneAgent"+ ReferencedContainer = "container:IPhoneAgent.xcodeproj">+ </BuildableReference>+ </BuildableProductRunnable>+ </ProfileAction>+ <AnalyzeAction+ buildConfiguration = "Debug">+ </AnalyzeAction>+ <ArchiveAction+ buildConfiguration = "Release"+ revealArchiveInOrganizer = "YES">+ </ArchiveAction>+</Scheme>diff --git a/ios/IPhoneAgent/Agent/Actions.swift b/ios/IPhoneAgent/Agent/Actions.swiftnew file mode 100644index 0000000..1f94681--- /dev/null+++ b/ios/IPhoneAgent/Agent/Actions.swift@@ -0,0 +1,135 @@+import Foundation++/// Parsing of the model's replies; a line-for-line port of agent.py (parse_command, parse_actions, parse_plan).+enum Actions {+ struct ParseError: LocalizedError {+ let message: String+ var errorDescription: String? { message }+ }++ /// Bookkeeping keys that are not part of the action itself.+ static let meta: Set<String> = ["t", "thought", "thought_zh", "think_s", "act_s", "shot", "_shot", "changed"]++ /// action name -> argument names; numeric arguments are 0-1000 screen coordinates+ static let actions: [String: [String]] = [+ "tap": ["x", "y"], "swipe": ["x1", "y1", "x2", "y2"], "circle": ["x", "y", "r"], "path": ["points"],+ "type": ["text"], "key": ["combo"], "done": ["answer"], "fail": ["reason"],+ "home": [], "back": [], "wait": [], "replan": [],+ ]+ static let textArgs: Set<String> = ["text", "combo", "answer", "reason"]++ /// One DO line, e.g. "tap 152 362" -> {"action": "tap", "x": 152, "y": 362}.+ static func parseCommand(_ line: String) throws -> JObject {+ let (head, rest) = partition(line.trimmingCharacters(in: .whitespacesAndNewlines))+ let name = head.lowercased()+ guard let keys = actions[name] else { throw ParseError(message: "unknown action: \(line.prefix(100))") }+ if let first = keys.first, textArgs.contains(first) {+ let text = rest.trimmingCharacters(in: .whitespacesAndNewlines).trimmingCharacters(in: CharacterSet(charactersIn: "\""))+ return ["action": .str(name), first: .str(text)]+ }+ let numbers = matches(#"-?\d+(?:\.\d+)?"#, in: rest).compactMap { Double($0) }.map { Int($0) }+ if keys == ["points"] {+ guard numbers.count >= 4, numbers.count % 2 == 0 else {+ throw ParseError(message: "path needs 2+ x y pairs: \(line.prefix(100))")+ }+ let points = stride(from: 0, to: numbers.count, by: 2).prefix(20)+ .map { JValue.arr([.int(numbers[$0]), .int(numbers[$0 + 1])]) }+ return ["action": .str(name), "points": .arr(Array(points))]+ }+ guard numbers.count == keys.count else {+ throw ParseError(message: "\(name) needs \(keys.count) numbers: \(line.prefix(100))")+ }+ var action: JObject = ["action": .str(name)]+ for (k, n) in zip(keys, numbers) { action[k] = .int(n) }+ if name == "tap" && rest.lowercased().contains("precise") { action["precise"] = .bool(true) }+ return action+ }++ /// Parse a THINK / DO… reply (an optional ZH line is kept); the thought goes on the first action.+ static func parseActions(_ text: String) throws -> [JObject] {+ let thought = firstGroup(#"^\s*THINK\s*[::]\s*(.*?)\s*$"#, in: text, multiline: true)+ let zh = firstGroup(#"^\s*ZH\s*[::]\s*(.*?)\s*$"#, in: text, multiline: true)+ var acts = try allGroups(#"^\s*DO\s*[::]\s*(.*?)\s*$"#, in: text).map(parseCommand).prefix(6).map { $0 }+ guard !acts.isEmpty else { throw ParseError(message: "no DO line in reply: \(text.prefix(200))") }+ acts[0] = JObject([("thought", .str(thought ?? "")), ("thought_zh", .str(zh ?? ""))]).merging(acts[0])+ return acts+ }++ /// Split an optional EN: / ZH: plan reply; a plain reply is used for both.+ static func parsePlan(_ text: String) -> (String, String) {+ let re = try! NSRegularExpression(pattern: #"EN\s*[::](.*?)ZH\s*[::](.*)"#,+ options: [.dotMatchesLineSeparators, .caseInsensitive])+ let ns = text as NSString+ if let m = re.firstMatch(in: text, range: NSRange(location: 0, length: ns.length)) {+ return (trim(ns.substring(with: m.range(at: 1))), trim(ns.substring(with: m.range(at: 2))))+ }+ return (trim(text), trim(text))+ }++ /// The action itself, without thoughts, timings and other bookkeeping.+ static func key(_ step: JObject) -> JObject { step.without(meta) }++ // MARK: - helpers++ private static func trim(_ s: String) -> String { s.trimmingCharacters(in: .whitespacesAndNewlines) }++ private static func partition(_ s: String) -> (String, String) {+ guard let i = s.firstIndex(of: " ") else { return (s, "") }+ return (String(s[..<i]), String(s[s.index(after: i)...]))+ }++ private static func regex(_ p: String, multiline: Bool) -> NSRegularExpression {+ try! NSRegularExpression(pattern: p, options: multiline ? [.anchorsMatchLines, .caseInsensitive] : [])+ }++ private static func matches(_ p: String, in s: String) -> [String] {+ let ns = s as NSString+ return regex(p, multiline: false).matches(in: s, range: NSRange(location: 0, length: ns.length))+ .map { ns.substring(with: $0.range) }+ }++ private static func firstGroup(_ p: String, in s: String, multiline: Bool) -> String? {+ let ns = s as NSString+ guard let m = regex(p, multiline: multiline).firstMatch(in: s, range: NSRange(location: 0, length: ns.length))+ else { return nil }+ return ns.substring(with: m.range(at: 1))+ }++ private static func allGroups(_ p: String, in s: String) -> [String] {+ let ns = s as NSString+ return regex(p, multiline: true).matches(in: s, range: NSRange(location: 0, length: ns.length))+ .map { ns.substring(with: $0.range(at: 1)) }+ }+}++/// Screen points (fractions) the pointer passes through for one action.+func pointerPath(_ act: JObject) -> [CGPoint] {+ func n(_ k: String) -> Double { act[k]?.double ?? 0 }+ func f(_ x: Double, _ y: Double) -> CGPoint { CGPoint(x: x / 1000, y: y / 1000) }+ switch act["action"]?.str {+ case "tap": return [f(n("x"), n("y"))]+ case "swipe": return [f(n("x1"), n("y1")), f(n("x2"), n("y2"))]+ case "path": return points(act).map { f($0.x, $0.y) }+ case "circle": return [f(n("x") + n("r"), n("y"))]+ case "home": return [CGPoint(x: 0.5, y: 0.995), CGPoint(x: 0.5, y: 0.6)]+ case "back": return [CGPoint(x: 0.005, y: 0.45), CGPoint(x: 0.6, y: 0.45)]+ default: return []+ }+}++/// The [[x, y], …] points of a path action, in 0-1000 units.+func points(_ act: JObject) -> [CGPoint] {+ guard case .arr(let items)? = act["points"] else { return [] }+ return items.compactMap {+ guard case .arr(let p) = $0, p.count == 2, let x = p[0].double, let y = p[1].double else { return nil }+ return CGPoint(x: x, y: y)+ }+}++/// Points around a circle; r is a fraction of the width, aspect = width / height.+func circle(_ x: Double, _ y: Double, _ r: Double, aspect: Double, n: Int = 24) -> [CGPoint] {+ (0...n).map { i in+ let a = 2 * Double.pi * Double(i) / Double(n)+ return CGPoint(x: x + r * cos(a), y: y + r * aspect * sin(a))+ }+}diff --git a/ios/IPhoneAgent/Agent/AgentLoop.swift b/ios/IPhoneAgent/Agent/AgentLoop.swiftnew file mode 100644index 0000000..e9b1064--- /dev/null+++ b/ios/IPhoneAgent/Agent/AgentLoop.swift@@ -0,0 +1,368 @@+import Foundation++/// The screen feed is gone; acting now would be guessing.+struct BlindError: LocalizedError {+ var reason = "lost the phone screen: reconnect Screen Mirroring"+ var errorDescription: String? { reason }+}++/// What AgentLoop does on the phone (Pointer, or a fake in tests).+@MainActor protocol Gestures: AnyObject {+ var device: HIDDevice { get }+ func tap(_ x: Double, _ y: Double, aim: Bool) async throws+ func swipe(_ x1: Double, _ y1: Double, _ x2: Double, _ y2: Double, hold: Bool) async throws+ func drag(_ points: [CGPoint], hold: Bool) async throws+ func type(_ text: String) async throws+ func key(_ combo: String) async throws+ func goHome() async throws+ func goBack() async throws+ func reset() async throws+}++extension Pointer: Gestures {}++/// See-think-act loop: a planner model writes the plan, an actor model picks each step. Port of agent.py.+@MainActor final class AgentLoop: ObservableObject {+ struct Planned {+ var act: JObject+ var shot: Data? // every action of one reply is drawn on the same screenshot+ }++ let phone: Gestures?+ let screen: ScreenSource?+ var actor: ChatModel?, planner: ChatModel?+ let trace: TraceStore?+ let maxSteps: Int, maxFailures: Int+ var metrics: Metrics?++ @Published private(set) var task = ""+ @Published private(set) var plan = ""+ @Published var steps: [JObject] = []+ @Published private(set) var shots: [Int: Data] = [:] // step index -> screenshot the model decided on+ @Published private(set) var running = false+ private var pointerAt = CGPoint.zero // last pointer position (screen fractions)+ /// When the last gesture ended: the model never decides on a frame from before it.+ private(set) var lastActed = 0.0+ /// Awaited before every look and every gesture (the app holds the run while its own UI is in front).+ var gate: (() async throws -> Void)?+ static let maxTokens = ["planner": 1500, "actor": 1000]+ private var job: Task<Void, Never>?+ var onFinish: (() -> Void)?+ /// Paused for the board to come back (a line for the UI), or nil when going on.+ /// Recovery from a lost link: the link state (from the app), each stage as it changes (nil = live again),+ /// and what to redo once live (stream on, fresh frame, release, re-home).+ var link: (() -> Recovery.Link)?+ var onRecover: ((Recovery.Stage?) -> Void)?+ var restore: (() async throws -> Void)?+ var recoveryLimit = Recovery.limit+ var onStep: (() -> Void)?+ /// What the agent is busy with between steps, for the Dynamic Island (looking, thinking, about to act).+ var onDoing: ((Doing) -> Void)?+ enum Doing { case looking, thinking, acting(JObject) }+ /// Hints from a saved intent's checklist, appended to the actor's system prompt (empty = the original prompt).+ var hints: [String] = []+ /// "Needs your help": asked when the actor gives up or errors repeat; nil = end the run as before.+ var onHelp: ((String) async -> HelpChoice)?+ private var helpAsked = 0+ enum HelpChoice { case resume, skip, stop }++ init(phone: Gestures?, screen: ScreenSource?, actor: ChatModel?, planner: ChatModel?, trace: TraceStore?,+ maxSteps: Int = 40, maxFailures: Int = 3) {+ self.phone = phone; self.screen = screen; self.actor = actor; self.planner = planner+ self.trace = trace; self.maxSteps = maxSteps; self.maxFailures = maxFailures+ }++ /// traceStarted: the caller already opened the run's trace folder (so a failed start is logged too).+ func start(_ task: String, traceStarted: Bool = false) throws {+ if running { throw DeviceError(message: "agent already running") }+ guard screen?.live == true else { throw DeviceError(message: "no phone screen: start Screen Mirroring first") }+ self.task = task; plan = ""; steps = []; shots = [:]+ pointerAt = .zero+ lastActed = 0+ helpAsked = 0+ if !traceStarted { trace?.start(task: task) }+ running = true+ job = Task { [weak self] in+ await self?.run()+ self?.running = false+ self?.onFinish?()+ }+ }++ func stop() {+ if let job { job.cancel() } else { running = false } // a shown (demo) run has no job+ }++ func clear() throws {+ if running { throw DeviceError(message: "stop the agent first") }+ task = ""; plan = ""; steps = []; shots = [:]+ }++ private func record(_ shot: Data? = nil, _ step: JObject) {+ if let shot { shots[steps.count] = shot }+ steps.append(JObject([("t", .num(now())), ("shot", .bool(shot != nil))]).merging(step))+ trace?.write(kind: "step", step)+ onStep?()+ }++ /// The board or mirroring went away mid-run: pause ("waiting for the board") until the screen is live+ /// again, up to `reconnectWait` s, instead of failing the run.+ /// The screen is gone (board, hotspot or mirroring lost): pause the run until it is back, in stages.+ /// Returns how many seconds it took, or nil if the screen was there all along. Never ends the run for a+ /// lost link before Recovery.limit.+ func waitForScreen(poll: Double = 0.5) async throws -> Double? {+ guard let screen, !screen.live else { return nil }+ var recovery = Recovery(at: now(), limit: recoveryLimit)+ var shown: Recovery.Stage?+ defer { if shown != nil { onRecover?(nil) } }+ while true {+ try Task.checkCancellation()+ let state = link?() ?? Recovery.Link(connected: phone?.device.connected ?? true, sta: nil,+ ap: screen.live ? "streaming" : nil, frameAt: screen.live ? now() : 0)+ switch recovery.next(state, at: now()) {+ case .live where screen.live:+ try await restore?()+ await screen.settled()+ return now() - recovery.started+ case .live: break+ case .wait(let stage):+ if stage != shown { shown = stage; onRecover?(stage) }+ case .giveUp(let reason):+ throw BlindError(reason: reason)+ }+ try await Task.sleep(nanoseconds: UInt64(poll * 1e9))+ }+ }++ private func ask(_ role: String, _ llm: ChatModel, _ system: String, _ prompt: String,+ temperature: Double = 0) async throws -> (String, Double, Data?) {+ try await gate?()+ var prompt = prompt+ if let lost = try await waitForScreen() {+ record(nil, ["action": .str("reconnected"), "reason": .str(String(format: "connection lost for %.0f s and restored", lost))])+ prompt += "\n\nNote: the connection was lost and restored; re-check the screen before acting."+ try await gate?() // the user may have opened this app while it was paused+ }+ guard let screen, screen.live else { throw BlindError() } // never let the model act blind+ let frame = screen.frame, started = now()+ onDoing?(.thinking)+ let reply = try await llm.chat(system: system, text: prompt, image: frame, maxTokens: Self.maxTokens[role] ?? 1000,+ temperature: temperature)+ let seconds = ((now() - started) * 100).rounded() / 100+ metrics?.llm(first: reply.firstToken, total: reply.total)+ var rec: JObject = ["role": .str(role), "model": .str(llm.model), "prompt": .str(prompt),+ "reply": .str(reply.text), "seconds": .num(seconds)]+ if let first = reply.firstToken { rec["first_token_s"] = .num((first * 100).rounded() / 100) }+ if lastActed > 0 { rec["frame_after_action_s"] = .num(((screen.capturedAt - lastActed) * 100).rounded() / 100) }+ trace?.write(frame, kind: "llm", rec.merging(reply.diagnostics))+ return (reply.text, seconds, frame)+ }++ func run() async {+ var failures = 0+ do {+ try await replan()+ for _ in 0..<maxSteps {+ do {+ if try await step() {+ guard steps.last?["action"]?.str == "fail", try await askForHelp() else { return finish() }+ continue+ }+ failures = 0+ } catch let e where e is BlindError || e is CancellationError || Task.isCancelled {+ throw e+ } catch { // a bad reply or a dropped link: recover, don't crash+ record(nil, ["action": .str("hiccup"), "reason": .str(String(error.localizedDescription.prefix(300)))])+ let linkLost = error is DeviceError && screen?.live == false // the next look waits for it (waitForScreen)+ failures += linkLost ? 0 : 1 // a lost link is not the agent's fault+ if failures >= maxFailures {+ record(nil, ["action": .str("fail"), "reason": .str("\(failures) errors in a row")])+ guard try await askForHelp() else { return finish() }+ failures = 0+ continue+ }+ await screen?.settled()+ try await replan(stuck: true)+ }+ }+ record(nil, ["action": .str("fail"), "reason": .str("step limit reached")])+ } catch let e where e is CancellationError || Task.isCancelled {+ record(nil, ["action": .str("stopped")])+ } catch let e as BlindError {+ record(nil, ["action": .str("fail"), "reason": .str(e.reason)])+ } catch { // e.g. the planner itself is unreachable+ record(nil, ["action": .str("error"), "reason": .str(String(describing: error))])+ }+ finish()+ }++ /// Pauses for the user (at most twice a run). True = go on from the current screen with a new plan.+ private func askForHelp() async throws -> Bool {+ guard let onHelp, helpAsked < 2 else { return false }+ helpAsked += 1+ let reason = steps.last?["reason"]?.str ?? ""+ record(nil, ["action": .str("help"), "reason": .str(reason)])+ let choice = await onHelp(reason)+ try Task.checkCancellation()+ switch choice {+ case .stop:+ record(nil, ["action": .str("stopped")])+ return false+ case .resume:+ record(nil, ["action": .str("takeover"), "reason": .str("the user did this part by hand: \(reason)")])+ case .skip:+ record(nil, ["action": .str("skipped"), "reason": .str("the user asked to skip this step: \(reason)")])+ }+ await screen?.settled()+ try await replan(stuck: true)+ return true+ }++ /// The actor's system prompt: the original, plus an intent's checklist as hints.+ var actorPrompt: String {+ let base = Prompts.actor + "\n" + AssistiveTouchSpots.rule+ return hints.isEmpty ? base : base + "\n\nHints for this task:\n" + hints.map { "- " + $0 }.joined(separator: "\n")+ }++ private func finish() {+ if let metrics { trace?.writeMetrics(metrics.snapshot()) }+ }++ /// One see-think-act round (one or more actions). Returns true when the task is over.+ func step() async throws -> Bool {+ var timing = Metrics.Step()+ let acts = try await nextActions()+ timing.llmMs = (acts[0].act["think_s"]?.double ?? 0) * 1000+ let seen = acts[0].shot+ var spots = [pointerAt] // where the pointer was and goes: pointer moves are not screen changes+ let stuck = repeating(acts[0].act)+ defer { metrics?.step(timing) }+ for (i, planned) in acts.enumerated() {+ var act = planned.act+ let name = act["action"]?.str ?? ""+ if name == "replan" || stuck {+ record(planned.shot, act)+ try await replan(stuck: stuck)+ return false+ }+ if name != "done" && name != "fail" {+ try await gate?()+ onDoing?(.acting(act)) // the thought (on the first act) names the target+ let started = now()+ try await perform(act)+ lastActed = now()+ let s = lastActed - started+ timing.hidMs += s * 1000+ act["act_s"] = .num((s * 100).rounded() / 100)+ spots += pointerPath(act)+ pointerAt = spots.last!+ }+ record(planned.shot, act)+ if name == "done" || name == "fail" { return true }+ let following = i < acts.count - 1 ? acts[i + 1].act["action"]?.str : nil+ if name == "tap" && (following == "type" || following == "key") { // a missed tap never opened the field+ timing.frameMs += await settle()+ if !Vision.changed(seen, screen?.frame, ignore: spots) {+ steps[steps.count - 1]["changed"] = .bool(false)+ return false // skip the rest; the actor looks again+ }+ }+ }+ timing.frameMs += await settle()+ // feedback for the next round+ steps[steps.count - 1]["changed"] = .bool(Vision.changed(seen, screen?.frame, ignore: spots))+ return false+ }++ private func settle() async -> Double {+ let started = now()+ onDoing?(.looking)+ await screen?.afterAction(since: lastActed)+ return (now() - started) * 1000+ }++ /// The previous round changed nothing on screen, so a tap may have landed off target.+ private var missed: Bool { steps.last?["changed"] == .bool(false) }++ /// True when the actor picks the same action as its last limit-1 moves and the last one did nothing.+ /// Repeating a move that still changes the screen (e.g. scrolling down a long list) is progress, not a loop.+ func repeating(_ act: JObject, limit: Int = 3) -> Bool {+ let moves = steps.filter { $0["plan"] == nil }.suffix(limit - 1)+ return moves.count == limit - 1 && moves.allSatisfy { Actions.key($0) == Actions.key(act) }+ && moves.last?["changed"] != .bool(true)+ }++ func replan(stuck: Bool = false) async throws {+ guard let planner else { throw LLMError(message: "no planner model") }+ var prompt = "Goal: \(task)"+ if stuck {+ let last = steps.last ?? JObject()+ prompt += "\n\nThe previous plan got stuck (last event: \(pyStr(last["action"])) \(last["reason"]?.str ?? "")):"+ + "\n\(plan)\nLook at the current screen and plan from here, another way if needed."+ }+ let (reply, seconds, frame) = try await ask("planner", planner, Prompts.plannerApp + "\n" + AssistiveTouchSpots.rule, prompt)+ let (en, zh) = Actions.parsePlan(reply)+ plan = en+ record(frame, ["action": .str(stuck ? "replan (stuck)" : "plan"), "plan": .str(en), "plan_zh": .str(zh),+ "think_s": .num(seconds)])+ }++ func nextActions() async throws -> [Planned] {+ guard let actor else { throw LLMError(message: "no actor model") }+ // actions and their effect only: echoing earlier thoughts makes the model repeat them instead of looking+ let hidden: Set<String> = ["t", "plan", "plan_zh", "think_s", "act_s", "shot", "thought", "thought_zh", "changed"]+ let history = steps.suffix(8).filter { $0["plan"] == nil }.map { s -> String in+ let effect = s["changed"] == .bool(true) ? " -> screen changed"+ : s["changed"] == .bool(false) ? " -> screen did NOT change" : ""+ return String(PyJSON.dumps(s.without(hidden)).prefix(300)) + effect+ }.joined(separator: "\n")+ var prompt = "Goal: \(task)\n\nPlan:\n\(plan)\n\nRecent actions:\n\(history.isEmpty ? "(none)" : history)\n\nNext action?"+ var reply = ""+ for attempt in 0..<3 { // retry unparseable replies, a little less deterministically+ let (text, seconds, frame) = try await ask("actor", actor, actorPrompt, prompt, temperature: 0.4 * Double(attempt))+ reply = text+ var acts: [JObject]+ do { acts = try Actions.parseActions(text) } catch { continue }+ if missed, let last = steps.last, Actions.key(acts[0]) == Actions.key(last) { // same move that did nothing+ prompt += "\n\nYou just proposed \(PyJSON.dumps(Actions.key(acts[0]))) again, but it changed nothing last "+ + "time. Choose a different action (another position, a shorter swipe, or another way)."+ continue+ }+ acts[0]["think_s"] = .num(seconds)+ return acts.map { Planned(act: $0, shot: frame) }+ }+ throw Actions.ParseError(message: "actor gave no valid action: \(reply.prefix(200))")+ }++ private func perform(_ a: JObject) async throws {+ guard let phone else { throw DeviceError(message: "no phone") }+ func p(_ k: String) -> Double { (a[k]?.double ?? 0) / 1000 }+ switch a["action"]?.str {+ case "tap": try await phone.tap(p("x"), p("y"), aim: a["precise"]?.bool ?? false || missed)+ case "swipe": try await phone.swipe(p("x1"), p("y1"), p("x2"), p("y2"), hold: true)+ case "path": try await phone.drag(points(a).map { CGPoint(x: $0.x / 1000, y: $0.y / 1000) }, hold: true)+ case "circle": try await phone.drag(circle(p("x"), p("y"), p("r"), aspect: screen?.aspect ?? 9 / 19.5), hold: true)+ case "type": try await phone.type(a["text"]?.str ?? "")+ case "key": try await phone.key(a["combo"]?.str ?? "")+ case "home": try await phone.goHome()+ case "back": try await phone.goBack()+ case "wait": break+ case let other: throw Actions.ParseError(message: "unknown action \(other ?? "nil")")+ }+ }++ /// Show a run without running it (demo data).+ func showMock(task: String, plan: String, steps: [JObject], running: Bool) {+ self.task = task+ self.plan = plan+ self.steps = steps+ self.running = running+ }++ /// Python's str() of a value in an f-string (None for a missing key).+ private func pyStr(_ v: JValue?) -> String {+ guard let v else { return "None" }+ if case .str(let s) = v { return s }+ return PyJSON.dumps(v)+ }+}diff --git a/ios/IPhoneAgent/Agent/AssistiveTouchSpots.swift b/ios/IPhoneAgent/Agent/AssistiveTouchSpots.swiftnew file mode 100644index 0000000..8da45c6--- /dev/null+++ b/ios/IPhoneAgent/Agent/AssistiveTouchSpots.swift@@ -0,0 +1,33 @@+import Foundation++/// Where calibration clicks went missing: the AssistiveTouch floating button swallows clicks, so a probe+/// that never reaches the app most likely hit it. The last few spots (screen fractions) are kept and shown+/// to the models so they keep away from it.+enum AssistiveTouchSpots {+ private static let key = "atButtonSpots"+ private static let limit = 3++ static var all: [(x: Double, y: Double)] {+ let raw = UserDefaults.standard.array(forKey: key) as? [[Double]] ?? []+ return raw.compactMap { $0.count == 2 ? ($0[0], $0[1]) : nil }+ }++ static func remember(x: Double, y: Double) {+ var raw = UserDefaults.standard.array(forKey: key) as? [[Double]] ?? []+ raw.removeAll { abs($0[0] - x) < 0.08 && abs($0[1] - y) < 0.08 }+ raw.append([x, y])+ UserDefaults.standard.set(Array(raw.suffix(limit)), forKey: key)+ DebugLog.write(String(format: "AssistiveTouch spot remembered at (%.2f, %.2f); known: %d", x, y, raw.suffix(limit).count))+ }++ /// The prompt rule, with the remembered spots in the models' 0–1000 coordinates.+ static var rule: String {+ var text = """+Never tap the AssistiveTouch floating button (a small translucent round button at a screen edge). \+If an AssistiveTouch menu panel is visible, close it by tapping outside it.+"""+ let spots = all.map { "(\(Int($0.x * 1000)), \(Int($0.y * 1000)))" }+ if !spots.isEmpty { text += " It was last seen near " + spots.joined(separator: ", ") + "; keep away from there." }+ return text+ }+}diff --git a/ios/IPhoneAgent/Agent/JSON.swift b/ios/IPhoneAgent/Agent/JSON.swiftnew file mode 100644index 0000000..d52d808--- /dev/null+++ b/ios/IPhoneAgent/Agent/JSON.swift@@ -0,0 +1,102 @@+import Foundation++/// A JSON value. Agent steps are ordered objects, like the Python dicts they replace, so the history+/// sent to the model reads exactly as before (`json.dumps` key order and spacing).+enum JValue: Equatable {+ case int(Int), num(Double), str(String), bool(Bool), arr([JValue]), obj(JObject), null++ var int: Int? { if case .int(let v) = self { return v }; return nil }+ var str: String? { if case .str(let v) = self { return v }; return nil }+ var bool: Bool? { if case .bool(let v) = self { return v }; return nil }+ var double: Double? {+ switch self { case .int(let v): return Double(v); case .num(let v): return v; default: return nil }+ }+}++/// An insertion-ordered JSON object; equality ignores order, like Python dicts.+struct JObject: Equatable, ExpressibleByDictionaryLiteral {+ private(set) var pairs: [(String, JValue)] = []++ init(_ pairs: [(String, JValue)] = []) { pairs.forEach { self[$0.0] = $0.1 } }+ init(dictionaryLiteral elements: (String, JValue)...) { self.init(elements) }++ var keys: [String] { pairs.map(\.0) }++ subscript(key: String) -> JValue? {+ get { pairs.first { $0.0 == key }?.1 }+ set {+ let i = pairs.firstIndex { $0.0 == key }+ switch (i, newValue) {+ case let (i?, v?): pairs[i].1 = v+ case let (nil, v?): pairs.append((key, v))+ case let (i?, nil): pairs.remove(at: i)+ case (nil, nil): break+ }+ }+ }++ /// `{**a, **b}`: b's keys win, a's order first.+ func merging(_ other: JObject) -> JObject {+ var out = self+ other.pairs.forEach { out[$0.0] = $0.1 }+ return out+ }++ func without(_ hidden: Set<String>) -> JObject { JObject(pairs.filter { !hidden.contains($0.0) }) }++ static func == (a: JObject, b: JObject) -> Bool {+ a.pairs.count == b.pairs.count && a.pairs.allSatisfy { b[$0.0] == $0.1 }+ }+}++/// Python's `json.dumps` output format (", " and ": " separators).+enum PyJSON {+ static func dumps(_ v: JValue, ascii: Bool = true) -> String {+ switch v {+ case .int(let i): return String(i)+ case .num(let d): return d == d.rounded() && abs(d) < 1e15 ? String(format: "%.1f", d) : String(d)+ case .bool(let b): return b ? "true" : "false"+ case .null: return "null"+ case .str(let s): return quote(s, ascii: ascii)+ case .arr(let a): return "[" + a.map { dumps($0, ascii: ascii) }.joined(separator: ", ") + "]"+ case .obj(let o): return dumps(o, ascii: ascii)+ }+ }++ static func dumps(_ o: JObject, ascii: Bool = true) -> String {+ "{" + o.pairs.map { quote($0.0, ascii: ascii) + ": " + dumps($0.1, ascii: ascii) }.joined(separator: ", ") + "}"+ }++ private static func quote(_ s: String, ascii: Bool) -> String {+ var out = "\""+ for u in s.unicodeScalars {+ switch u {+ case "\"": out += "\\\""+ case "\\": out += "\\\\"+ case "\n": out += "\\n"+ case "\r": out += "\\r"+ case "\t": out += "\\t"+ default:+ if u.value < 0x20 || (ascii && u.value > 0x7e) {+ for unit in String(u).utf16 { out += String(format: "\\u%04x", unit) }+ } else {+ out.unicodeScalars.append(u)+ }+ }+ }+ return out + "\""+ }++ /// Convert a Foundation JSON object (from JSONSerialization) into a JValue.+ static func from(_ any: Any?) -> JValue {+ switch any {+ case let n as NSNumber where CFGetTypeID(n) == CFBooleanGetTypeID(): return .bool(n.boolValue)+ case let n as NSNumber: return n.doubleValue == n.doubleValue.rounded() && !"\(n)".contains(".")+ ? .int(n.intValue) : .num(n.doubleValue)+ case let s as String: return .str(s)+ case let a as [Any]: return .arr(a.map(from))+ case let d as [String: Any]: return .obj(JObject(d.keys.sorted().map { ($0, from(d[$0])) }))+ default: return .null+ }+ }+}diff --git a/ios/IPhoneAgent/Agent/Pointer.swift b/ios/IPhoneAgent/Agent/Pointer.swiftnew file mode 100644index 0000000..45e4a3b--- /dev/null+++ b/ios/IPhoneAgent/Agent/Pointer.swift@@ -0,0 +1,312 @@+import Foundation++/// Touch-like gestures on the phone, built from relative mouse moves. Port of phone.py.+///+/// The pointer is relative, so the app tracks where it is (in mouse units) and moves from there; every few+/// gestures it slams it into the top-left corner (`home`) again to cancel drift. Coordinates are fractions of+/// the screen (0..1, origin top-left), so they work for any frame size.+@MainActor final class Pointer: ObservableObject {+ static let calibrationMove = 200 // mouse units moved diagonally for a manual (one point) calibration+ static let calibrationStops = [150, 350] // automatic calibration finds the pointer at these distances+ static let rehomeEvery = 10 // gestures between re-homing+ static let hold = 0.25 // s to rest before lifting, so iOS adds no momentum+ static let tapGap = 0.15 // s to stay still after a click, so iOS sees a finished tap+ static let nudge = 12 // mouse units the pointer is wiggled by to find it on screen+ static let aimTolerance = 0.008 // screen fraction; a bigger miss is corrected before pressing+ static let maxMiss = 0.06 // bigger misses are still corrected, but not learned from++ struct Span: Codable, Equatable { var w: Int, h: Int }+ private struct Saved: Codable { var w: Int, h: Int, seen: [String: [[Double]]]?, quality: Double?, aspect: Double? }++ let device: HIDDevice+ weak var screen: ScreenSource?+ private let file: URL+ @Published private(set) var span: Span? // mouse units needed to cross the full screen width / height+ private var pos: (Int, Int)? // pointer position in mouse units; nil = unknown+ private var moves = 0+ private var link = 0 // device.links when the pointer was last homed+ /// where the pointer really landed (seen on screen) for the fraction we aimed at, per axis; a line fit+ /// through them corrects every later move, so taps get better as the agent works+ private(set) var seen: [String: [(Double, Double)]] = ["x": [], "y": []]+ @Published private(set) var quality: Double? // pointer error at the last check, fraction of the screen+ private(set) var aspect: Double? // frame width / height when calibrated+ var log: (String) -> Void = { print($0) }+ /// The device screen's width / height (iPhone or iPad), stored with a calibration.+ var screenAspect: () -> Double = { 9 / 19.5 }+ /// Last-resort pointer finder on a frame (the vision model), when the pixel diff finds nothing.+ var locate: ((Data) async -> CGPoint?)?++ init(device: HIDDevice, calibrationFile: URL, screen: ScreenSource? = nil) {+ self.device = device+ self.file = calibrationFile+ self.screen = screen+ if let data = try? Data(contentsOf: calibrationFile), let saved = try? JSONDecoder().decode(Saved.self, from: data) {+ span = Span(w: saved.w, h: saved.h)+ (quality, aspect) = (saved.quality, saved.aspect)+ for axis in ["x", "y"] {+ seen[axis] = (saved.seen?[axis] ?? []).filter { $0.count == 2 }.map { ($0[0], $0[1]) }.suffix(12)+ }+ }+ }++ var calibrated: Bool { span != nil }++ private func remember(_ axis: String, _ sample: (Double, Double)) {+ seen[axis] = Array((seen[axis, default: []] + [sample]).suffix(12)) // deque(maxlen=12)+ }++ /// Find the pointer on screen at two known distances from the corner and fit the mapping from both.+ /// Returns true when it calibrated itself; otherwise the user taps the pointer (finishCalibration).+ /// `progress` gets 0 (homing), then 1, 2 (each probe).+ func startCalibration(progress: ((Int) -> Void)? = nil) async throws -> Bool {+ pos = nil+ progress?(0)+ try await device.send("home")+ var found: [(Int, Double, Double)] = []+ for (i, units) in Self.calibrationStops.enumerated() {+ progress?(i + 1)+ let step = units - (found.last?.0 ?? 0)+ try await device.send("move \(step) \(step)")+ guard let screen, screen.live, let p = try await findPointer() else { break }+ found.append((units, p.x, p.y))+ }+ if found.count < 2 {+ log("calibration: pointer not found on screen, waiting for a tap")+ if found.isEmpty {+ try await device.send("home")+ try await device.send("move \(Self.calibrationMove) \(Self.calibrationMove)")+ }+ return false+ }+ let (u1, x1, y1) = found[0], (u2, x2, y2) = found[1]+ let s = Span(w: Int((Double(u2 - u1) / (x2 - x1)).rounded(.toNearestOrEven)), h: Int((Double(u2 - u1) / (y2 - y1)).rounded(.toNearestOrEven)))+ span = s+ (quality, aspect) = (nil, screenAspect())+ seen = ["x": [], "y": []]+ for (units, x, y) in found { // where each stop landed, so moves are corrected for the offset too+ remember("x", (Double(units) / Double(s.w), x))+ remember("y", (Double(units) / Double(s.h), y))+ }+ save()+ log("calibration: span \(s.w) x \(s.h)")+ return true+ }++ /// Wiggle the pointer and find it anywhere on screen (the span may still be unknown).+ private func findPointer() async throws -> CGPoint? {+ guard let screen else { return nil }+ await screen.settled(quiet: 0.2, least: 0.3, most: 1.5)+ let before = screen.frame, sent = now()+ try await device.send("move \(Self.nudge) 0")+ var after = await screen.fresh(since: sent, timeout: 1.0)+ if after != nil {+ await screen.settled(quiet: 0.15, least: 0.1, most: 0.6)+ after = screen.frame+ }+ try await device.send("move -\(Self.nudge) 0")+ guard let before, let after else { return nil }+ let pixel = Vision.pointer(before, after, near: CGPoint(x: 0.5, y: 0.5), shift: 0.025, reach: CGPoint(x: 0.5, y: 0.5))+ var found = pixel+ if found == nil { found = await locate?(after) }+ guard let p = found else { return nil }+ if pixel == nil { log(String(format: "calibration: vision model found the pointer at (%.3f, %.3f)", p.x, p.y)) }+ return 0.03 < p.x && p.x < 0.97 && 0.03 < p.y && p.y < 0.97 ? p : nil+ }++ /// x, y: where the pointer ended up after startCalibration() (one point, picked by the user).+ func finishCalibration(x: Double, y: Double) {+ (quality, aspect) = (nil, screenAspect())+ span = Span(w: Int((Double(Self.calibrationMove) / x).rounded(.toNearestOrEven)), h: Int((Double(Self.calibrationMove) / y).rounded(.toNearestOrEven)))+ seen = ["x": [], "y": []]+ save()+ }++ /// Touch-probe result: per-axis lines landed = a * units + b fitted from taps the app caught itself.+ /// The span is 1/a; every probe becomes a landing sample, so `fix` also corrects the offset b.+ func applyProbe(x: ProbeFit.Line, y: ProbeFit.Line, samples: [(ux: Double, uy: Double, fx: Double, fy: Double)]) {+ let s = Span(w: Int((1 / x.a).rounded()), h: Int((1 / y.a).rounded()))+ span = s+ (quality, aspect) = (max(x.rms, y.rms), screenAspect())+ seen = ["x": [], "y": []]+ for p in samples {+ remember("x", (p.ux / Double(s.w), p.fx))+ remember("y", (p.uy / Double(s.h), p.fy))+ }+ pos = nil+ save()+ log(String(format: "calibration: touch probe span %d x %d, offset %.3f / %.3f, residual %.2f%%",+ s.w, s.h, x.b, y.b, max(x.rms, y.rms) * 100))+ }++ /// A measured check (e.g. a probe tap) as the current accuracy.+ func setQuality(_ q: Double) {+ quality = q+ save()+ }++ /// Calibration plus the observed landings, so the correction survives a restart.+ private func save() {+ guard let span else { return }+ let saved = Saved(w: span.w, h: span.h, seen: seen.mapValues { $0.map { [$0.0, $0.1] } }, quality: quality,+ aspect: aspect)+ try? JSONEncoder().encode(saved).write(to: file)+ }++ func point(_ x: Double, _ y: Double, aim: Bool = false) async throws {+ guard calibrated else { throw DeviceError(message: "pointer not calibrated") }+ try await moveTo(dx(x), dy(y))+ if aim && screen != nil { try await self.aim(x, y) }+ }++ /// Closed loop: find the real pointer on screen, fix a miss, and learn the error for later moves.+ private func aim(_ x: Double, _ y: Double) async throws {+ guard let span, let found = try await measure(x, y, model: false) else {+ log(String(format: "aim (%.3f, %.3f): pointer not found", x, y))+ return+ }+ let fx = Double(found.x), fy = Double(found.y)+ if max(abs(fx - x), abs(fy - y)) <= Self.maxMiss { // learn from normal drift only, never a stray reading+ remember("x", (fix(x, "x"), fx))+ remember("y", (fix(y, "y"), fy))+ save()+ }+ if abs(fx - x) <= Self.aimTolerance && abs(fy - y) <= Self.aimTolerance { return }+ let mx = Int(((x - fx) * Double(span.w)).rounded(.toNearestOrEven)), my = Int(((y - fy) * Double(span.h)).rounded(.toNearestOrEven))+ try await device.send("move \(mx) \(my)") // fix this miss right away+ if let p = pos { pos = (p.0 + mx, p.1 + my) }+ }++ /// Wiggle the pointer and find it on screen, near the target first, then anywhere. model: ask the vision+ /// model when the pixels don't show it (~20 s, rarely right); a tap's aim never waits for that.+ private func measure(_ x: Double, _ y: Double, model: Bool = true) async throws -> CGPoint? {+ guard let screen, let span else { return nil }+ let nudge = x < 0.9 ? Self.nudge : -Self.nudge // stay clear of the screen edge+ await screen.settled(quiet: 0.15, least: 0.1, most: 0.6) // pointer at rest+ let before = screen.frame, sent = now()+ try await device.send("move \(nudge) 0")+ var after = await screen.fresh(since: sent, timeout: 1.2)+ if after != nil {+ await screen.settled(quiet: 0.1, least: 0.05, most: 0.4)+ after = screen.frame+ }+ try await device.send("move \(-nudge) 0")+ let shift = Double(nudge) / Double(span.w)+ guard let before, let after else { return nil }+ if let p = Vision.pointer(before, after, near: CGPoint(x: x, y: y), shift: shift)+ ?? Vision.pointer(before, after, near: CGPoint(x: 0.5, y: 0.5), shift: shift, reach: CGPoint(x: 0.5, y: 0.5)) {+ return p+ }+ return model ? await locate?(after) : nil+ }++ /// Calibration check without tapping: move to a known point and measure the miss (fraction of the screen).+ /// nil when the pointer could not be found.+ func verify(x: Double = 0.5, y: Double = 0.62) async throws -> Double? {+ try await point(x, y)+ guard let found = try await measure(x, y) else { return nil }+ let error = max(abs(Double(found.x) - x), abs(Double(found.y) - y))+ quality = error+ save()+ return error+ }++ /// How far the learned correction has moved targets away from the plain calibration (fraction of the screen).+ var drift: Double {+ [0.2, 0.8].flatMap { t in ["x", "y"].map { abs(fix(t, $0) - t) } }.max() ?? 0+ }++ /// Demo data: pretend a calibration with this quality.+ func mockCalibrated(quality: Double) {+ span = span ?? Span(w: 400, h: 860)+ self.quality = quality+ }++ /// The fraction to aim at so the pointer lands on t, from the line through the observed landings.+ func fix(_ t: Double, _ axis: String) -> Double {+ let pts = seen[axis] ?? []+ guard pts.count >= 2 else { return t }+ let n = Double(pts.count)+ let mc = pts.map(\.0).reduce(0, +) / n, mf = pts.map(\.1).reduce(0, +) / n+ let variance = pts.map { pow($0.0 - mc, 2) }.reduce(0, +)+ var a = variance > 1e-4 ? pts.map { ($0.0 - mc) * ($0.1 - mf) }.reduce(0, +) / variance : 1.0 // landed = a*aimed + b+ a = 0.85 < a && a < 1.15 ? a : 1.0+ let b = mf - a * mc+ return abs(b) < 0.1 ? (t - b) / a : t+ }++ private func moveTo(_ tx: Int, _ ty: Int, rehome: Bool = true) async throws {+ if link != device.links { // new link: a dropped gesture may have left the button down+ try await device.send("release")+ (pos, link) = (nil, device.links)+ }+ if pos == nil || (rehome && moves >= Self.rehomeEvery) {+ try await device.send("home")+ (pos, moves) = ((0, 0), 0)+ }+ let (x, y) = pos!+ pos = nil // unknown until the move succeeds+ try await device.send("move \(tx - x) \(ty - y)")+ (pos, moves) = ((tx, ty), moves + 1)+ }++ /// Let go of the button and re-home the pointer, whatever state a gesture left.+ func reset() async throws {+ pos = nil+ try await device.send("release")+ try await device.send("home")+ (pos, moves) = ((0, 0), 0)+ }++ /// aim: find the pointer on screen first (slower); worth it when a tap just missed.+ func tap(_ x: Double, _ y: Double, aim: Bool = false) async throws {+ try await point(x, y, aim: aim)+ try await device.send("click")+ try await Task.sleep(nanoseconds: UInt64(Self.tapGap * 1e9))+ }++ func swipe(_ x1: Double, _ y1: Double, _ x2: Double, _ y2: Double, hold: Bool = true) async throws {+ try await drag([CGPoint(x: x1, y: y1), CGPoint(x: x2, y: y2)], hold: hold)+ }++ /// Press at the first point, move through the rest, release: one continuous stroke. hold rests at the end+ /// first, so lists and pickers stop exactly there; system gestures (home, back) need the flick.+ func drag(_ points: [CGPoint], hold: Bool = true) async throws {+ try await point(Double(points[0].x), Double(points[0].y))+ try await device.send("press")+ do {+ for p in points.dropFirst() {+ try await moveTo(dx(Double(p.x)), dy(Double(p.y)), rehome: false) // never home mid-drag+ }+ if hold { try await Task.sleep(nanoseconds: UInt64(Self.hold * 1e9)) }+ } catch {+ _ = try? await device.send("release")+ throw error+ }+ try await device.send("release")+ }++ func scroll(_ x: Double, _ y: Double, lines: Int) async throws {+ try await point(x, y)+ try await device.send("scroll \(lines) 0")+ }++ func type(_ text: String) async throws { try await device.send("type \(text)") }+ func key(_ combo: String) async throws { try await device.send("key \(combo)") }+ /// The board's consumer-control Home key ("AC Home"), which iOS treats like a keyboard's home key. Boards+ /// without it (older firmware) answer an error: then Cmd+H and the flick up from the home bar (a flick, not+ /// a rest: resting opens the app switcher).+ func goHome() async throws {+ if (try? await device.send("homescreen")) != nil { return }+ try await key("cmd+h")+ try await Task.sleep(nanoseconds: 350_000_000)+ try await swipe(0.5, 0.995, 0.5, 0.45, hold: false)+ pos = nil // starting at the screen's edge may have clamped the pointer: re-home before the next move+ }+ func goBack() async throws {+ try await swipe(0.005, 0.45, 0.6, 0.45, hold: false)+ pos = nil+ }++ private func dx(_ x: Double) -> Int { Int((min(max(fix(x, "x"), 0), 1) * Double(span!.w)).rounded(.toNearestOrEven)) }+ private func dy(_ y: Double) -> Int { Int((min(max(fix(y, "y"), 0), 1) * Double(span!.h)).rounded(.toNearestOrEven)) }+}diff --git a/ios/IPhoneAgent/Agent/ProbeFit.swift b/ios/IPhoneAgent/Agent/ProbeFit.swiftnew file mode 100644index 0000000..61f35f8--- /dev/null+++ b/ios/IPhoneAgent/Agent/ProbeFit.swift@@ -0,0 +1,48 @@+import UIKit++/// Least-squares line through touch-probe samples: landed = a * units + b, per axis.+enum ProbeFit {+ struct Line: Equatable {+ var a: Double, b: Double+ var rms: Double // residual, fraction of the screen++ /// Mouse units (from home) that land on screen fraction f.+ func units(for f: Double) -> Int { Int(((f - b) / a).rounded()) }+ }++ /// samples: (mouse units from home, landed screen fraction). Nil with fewer than two distinct points.+ static func line(_ samples: [(Double, Double)]) -> Line? {+ let n = Double(samples.count)+ guard samples.count >= 2 else { return nil }+ let mu = samples.map(\.0).reduce(0, +) / n, mf = samples.map(\.1).reduce(0, +) / n+ let variance = samples.map { pow($0.0 - mu, 2) }.reduce(0, +)+ guard variance > 1e-6 else { return nil }+ let a = samples.map { ($0.0 - mu) * ($0.1 - mf) }.reduce(0, +) / variance+ guard a > 0 else { return nil }+ let b = mf - a * mu+ let rms = sqrt(samples.map { pow($0.1 - (a * $0.0 + b), 2) }.reduce(0, +) / n)+ return Line(a: a, b: b, rms: rms)+ }++ /// One sample and no offset: the line through home (0, 0).+ static func throughHome(_ s: (Double, Double)) -> Line? {+ s.0 > 0 && s.1 > 0 ? Line(a: s.1 / s.0, b: 0, rms: 0) : nil+ }++ /// A tap at the very edge may be the pointer stuck there: useless for a fit.+ static func usable(_ f: Double) -> Bool { 0.02 < f && f < 0.98 }+}++/// This device's screen, read at runtime (iPhone or iPad, current interface orientation).+@MainActor enum DeviceScreen {+ static var scene: UIWindowScene? {+ let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }+ return scenes.first { $0.activationState == .foregroundActive } ?? scenes.first+ }++ /// Points.+ static var size: CGSize { scene?.screen.bounds.size ?? CGSize(width: 390, height: 844) }+ static var scale: CGFloat { scene?.screen.scale ?? 3 }+ static var aspect: Double { size.height > 0 ? size.width / size.height : 9 / 19.5 }+ static var foreground: Bool { UIApplication.shared.applicationState == .active }+}diff --git a/ios/IPhoneAgent/Agent/Prompts.swift b/ios/IPhoneAgent/Agent/Prompts.swiftnew file mode 100644index 0000000..4951998--- /dev/null+++ b/ios/IPhoneAgent/Agent/Prompts.swift@@ -0,0 +1,21 @@+import Foundation++/// The model prompts, kept as plain text in the repository's `prompts/` folder (bundled with the app) so they+/// can be read and tuned without touching Swift. actor/planner = the shared rules + the app-only rules.+enum Prompts {+ static let planner = load("planner")+ static let actorServer = load("actor")+ static let appRules = load("app-rules")++ static let actor = actorServer + "\n" + appRules+ static let plannerApp = planner + "\n" + appRules++ /// One file from the bundled prompts folder, without the file's final newline.+ static func load(_ name: String) -> String {+ guard let url = Bundle.main.url(forResource: name, withExtension: "md", subdirectory: "prompts"),+ let text = try? String(contentsOf: url, encoding: .utf8) else {+ fatalError("prompts/\(name).md is missing from the app bundle")+ }+ return text.hasSuffix("\n") ? String(text.dropLast()) : text+ }+}diff --git a/ios/IPhoneAgent/Agent/Recovery.swift b/ios/IPhoneAgent/Agent/Recovery.swiftnew file mode 100644index 0000000..d21cf53--- /dev/null+++ b/ios/IPhoneAgent/Agent/Recovery.swift@@ -0,0 +1,101 @@+import Foundation++/// Self-healing after a lost link: which part is missing (board, hotspot, mirroring), when to ask the user,+/// and when to give up. Pure: the caller polls it with the link state and the time.+struct Recovery {+ /// What the app sees of the link right now.+ struct Link: Equatable {+ var connected: Bool // BLE link to the board is up+ var sta: Int? // phones joined to the board's hotspot (nil = unknown)+ var ap: String? // idle | connected | streaming+ var frameAt: Double // when the newest decoded frame arrived+ }++ enum Part: Equatable { case board, hotspot, mirroring }++ struct Stage: Equatable {+ var part: Part+ var ask: Bool // waited long enough: the user has to do something+ }++ enum Next: Equatable {+ case wait(Stage)+ case live+ case giveUp(String)+ }++ /// How long each part may come back by itself before the user is asked; then the whole limit.+ static let quiet: [Part: Double] = [.board: 30, .hotspot: 30, .mirroring: 20]+ static let limit = 300.0++ let started: Double+ let limit: Double+ private(set) var stage: Stage?+ private var partSince = 0.0++ init(at t: Double, limit: Double = Self.limit) { started = t; self.limit = limit }++ /// Live once the board is back, mirroring streams and a frame newer than the loss has been decoded.+ mutating func next(_ l: Link, at t: Double) -> Next {+ let part: Part? = !l.connected ? .board+ : l.sta == 0 ? .hotspot+ : l.ap != "streaming" || l.frameAt <= started ? .mirroring+ : nil+ guard let part else { stage = nil; return .live }+ if part != stage?.part { partSince = t }+ stage = Stage(part: part, ask: t - partSince >= Self.quiet[part]!)+ if t - started >= limit { return .giveUp(Self.reason(part)) }+ return .wait(stage!)+ }++ static func reason(_ part: Part) -> String {+ switch part {+ case .board: return String(localized: "the board did not come back in 5 minutes")+ case .hotspot: return String(localized: "the iPhone did not rejoin the board's Wi-Fi in 5 minutes")+ case .mirroring: return String(localized: "Screen Mirroring did not come back in 5 minutes")+ }+ }+}++extension Recovery.Stage {+ /// For the log: "recover: …".+ var logLine: String {+ switch (part, ask) {+ case (.board, false): return "BLE link lost; reconnecting"+ case (.board, true): return "board still gone; asked the user to check it"+ case (.hotspot, false): return "board up, iPhone not on its hotspot (sta 0); waiting for iOS to rejoin"+ case (.hotspot, true): return "iPhone still off the hotspot; asked the user to join it"+ case (.mirroring, false): return "board and hotspot up, no mirrored frame; waiting for iOS to resume mirroring"+ case (.mirroring, true): return "mirroring still off; asked the user to start it"+ }+ }++ /// Dynamic Island label: compact and full.+ var status: IslandStatus {+ switch (part, ask) {+ case (.board, _):+ return IslandStatus(short: String(localized: "Reconnecting…"), full: String(localized: "Reconnecting…"), look: nil)+ case (.hotspot, false):+ return IslandStatus(short: String(localized: "Joining Wi-Fi…"), full: String(localized: "Rejoining the board's Wi-Fi…"), look: nil)+ case (.hotspot, true):+ return IslandStatus(short: String(localized: "Join Wi-Fi"), full: String(localized: "Join the board's Wi-Fi to continue"), look: nil)+ case (.mirroring, false):+ return IslandStatus(short: String(localized: "Mirroring…"), full: String(localized: "Waiting for mirroring…"), look: nil)+ case (.mirroring, true):+ return IslandStatus(short: String(localized: "Start Mirroring"),+ full: String(localized: "Tap Screen Mirroring → ESP32 Agent to continue"), look: nil)+ }+ }++ /// One sentence for the Live Activity line, the in-app banner and the notification body.+ var line: String {+ switch (part, ask) {+ case (.board, false): return String(localized: "Lost the board. Reconnecting…")+ case (.board, true): return String(localized: "The board is still gone. Check that it is plugged in; the run goes on when it is back.")+ case (.hotspot, false): return String(localized: "The board restarted. Waiting for the iPhone to rejoin its Wi-Fi…")+ case (.hotspot, true): return String(localized: "Join the board's Wi-Fi in Settings › Wi-Fi; the run goes on when it is back.")+ case (.mirroring, false): return String(localized: "Board is back. Waiting for Screen Mirroring to resume…")+ case (.mirroring, true): return String(localized: "Open Control Center, tap Screen Mirroring → ESP32 Agent; the run goes on from here.")+ }+ }+}diff --git a/ios/IPhoneAgent/Agent/StepText.swift b/ios/IPhoneAgent/Agent/StepText.swiftnew file mode 100644index 0000000..16a24a0--- /dev/null+++ b/ios/IPhoneAgent/Agent/StepText.swift@@ -0,0 +1,85 @@+import Foundation++/// Human words for a recorded step, for the replay player, the Live Activity and Home.+enum StepText {+ static func title(_ s: JObject) -> String {+ let n = { (k: String) in s[k]?.int ?? Int(s[k]?.double ?? 0) }+ switch s["action"]?.str {+ case "plan": return String(localized: "Made a plan")+ case "replan (stuck)", "replan": return String(localized: "Made a new plan")+ case "tap": return String(localized: "Tap at \(n("x")), \(n("y"))")+ case "swipe": return String(localized: "Swipe")+ case "path": return String(localized: "Draw a path")+ case "circle": return String(localized: "Draw a circle")+ case "type": return String(localized: "Type “\(s["text"]?.str ?? "")”")+ case "key": return String(localized: "Press \(s["combo"]?.str ?? "")")+ case "home": return String(localized: "Go to the Home Screen")+ case "back": return String(localized: "Go back")+ case "wait": return String(localized: "Wait")+ case "done": return String(localized: "Done")+ case "fail": return String(localized: "Gave up")+ case "stopped": return String(localized: "Stopped")+ case "hiccup": return String(localized: "Hiccup, retrying")+ case "reconnected": return String(localized: "Reconnected")+ case "error": return String(localized: "Error")+ case "help": return String(localized: "Asked for your help")+ case "takeover": return String(localized: "You took over")+ case "skipped": return String(localized: "Skipped")+ case "note": return String(localized: "Note")+ default: return s["action"]?.str ?? ""+ }+ }++ /// The model's own words if it gave any, else the action.+ static func line(_ s: JObject) -> String {+ if let t = s["thought"]?.str, !t.isEmpty { return t }+ if let a = s["answer"]?.str ?? s["reason"]?.str, !a.isEmpty { return "\(title(s)): \(a)" }+ return title(s)+ }++ static func symbol(_ name: String?) -> String {+ switch name {+ case "plan", "replan (stuck)": return "list.bullet.clipboard"+ case "tap": return "hand.tap"+ case "swipe", "path", "circle": return "hand.draw"+ case "type": return "keyboard"+ case "key": return "command"+ case "home": return "house"+ case "back": return "chevron.backward"+ case "wait": return "hourglass"+ case "done": return "checkmark.circle.fill"+ case "stopped": return "stop.circle"+ case "help", "takeover": return "hand.raised"+ case "skipped": return "forward"+ case "note": return "text.bubble"+ case "reconnected": return "arrow.triangle.2.circlepath"+ default: return "exclamationmark.triangle"+ }+ }++ static let notMoves: Set<String> = ["plan", "replan (stuck)", "hiccup", "stopped", "error", "fail", "done", "help",+ "takeover", "skipped", "note", "reconnected"]+}++/// How a run ended.+enum Outcome {+ case running, done, failed, stopped++ init(last: String?, running: Bool) {+ if running { self = .running; return }+ switch last {+ case "done": self = .done+ case "stopped": self = .stopped+ default: self = .failed+ }+ }++ var mood: Mood {+ switch self {+ case .running: return .thinking+ case .done: return .success+ case .failed: return .failure+ case .stopped: return .idle+ }+ }+}diff --git a/ios/IPhoneAgent/Agent/Vision.swift b/ios/IPhoneAgent/Agent/Vision.swiftnew file mode 100644index 0000000..e9c0ed8--- /dev/null+++ b/ios/IPhoneAgent/Agent/Vision.swift@@ -0,0 +1,95 @@+import CoreGraphics+import Foundation+import ImageIO++/// Small image checks on screen frames: did the screen change, and where is the pointer. Port of vision.py.+enum Vision {+ /// Top share of the frame never compared: the status bar, where the Dynamic Island shows our Live Activity.+ static let topMask = 0.06++ /// A grayscale bitmap (PIL "L" weights), row-major.+ struct Gray {+ let w: Int, h: Int+ let px: [UInt8]+ }++ static func image(_ jpeg: Data) -> CGImage? {+ guard let src = CGImageSourceCreateWithData(jpeg as CFData, nil) else { return nil }+ return CGImageSourceCreateImageAtIndex(src, 0, nil)+ }++ /// The image drawn at w x h (bilinear-ish scaling), converted to gray like PIL's convert("L").+ static func gray(_ img: CGImage, _ w: Int, _ h: Int) -> Gray {+ var rgba = [UInt8](repeating: 0, count: w * h * 4)+ rgba.withUnsafeMutableBytes { buf in+ let ctx = CGContext(data: buf.baseAddress, width: w, height: h, bitsPerComponent: 8, bytesPerRow: w * 4,+ space: CGColorSpaceCreateDeviceRGB(),+ bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!+ ctx.interpolationQuality = .medium+ ctx.draw(img, in: CGRect(x: 0, y: 0, width: w, height: h))+ }+ var px = [UInt8](repeating: 0, count: w * h)+ for i in 0..<(w * h) {+ let r = Int(rgba[i * 4]), g = Int(rgba[i * 4 + 1]), b = Int(rgba[i * 4 + 2])+ px[i] = UInt8((r * 299 + g * 587 + b * 114 + 500) / 1000)+ }+ return Gray(w: w, h: h, px: px)+ }++ /// True when the screen content changed, including small things such as a checkmark.+ ///+ /// `ignore` lists screen points (fractions) where the pointer was or went: those spots are masked, so pointer+ /// moves never count. The status bar (clock) is ignored too.+ static func changed(_ before: Data?, _ after: Data?, ignore: [CGPoint] = [], threshold: Double = 1.0) -> Bool {+ guard let before, let after, let a = image(before), let b = image(after) else { return true }+ if a.width != b.width || a.height != b.height { return true }+ let sa = gray(a, 32, 64), sb = gray(b, 32, 64)+ let total = zip(sa.px, sb.px).reduce(0) { $0 + abs(Int($1.0) - Int($1.1)) }+ if Double(total) / Double(sa.px.count) > threshold { return true } // a big change: new screen, scrolled list+ let w = a.width / 2, h = a.height / 2 // fine pass for small changes, at half resolution+ let fa = gray(a, w, h), fb = gray(b, w, h)+ let masks = ignore.map { (Double($0.x) * Double(w), Double($0.y) * Double(h)) }+ let r2 = pow(0.05 * Double(w), 2)+ var hits = 0+ for i in 0..<(w * h) where abs(Int(fa.px[i]) - Int(fb.px[i])) > 25 {+ let x = Double(i % w), y = Double(i / w)+ if y > topMask * Double(h) && masks.allSatisfy({ pow(x - $0.0, 2) + pow(y - $0.1, 2) > r2 }) {+ hits += 1+ }+ }+ return hits >= 6+ }++ /// Where the pointer is in `before`, given it moved right by `shift` (fraction of width) in `after`.+ ///+ /// Only the pointer moved between the two frames, so the changed pixels within `reach` of `near` are the+ /// pointer at both spots; their centroid sits shift/2 to the right of the first one. nil if unclear.+ static func pointer(_ before: Data, _ after: Data, near: CGPoint, shift: Double,+ reach: CGPoint = CGPoint(x: 0.12, y: 0.08)) -> CGPoint? {+ guard let ia = image(before), let ib = image(after), ia.width == ib.width, ia.height == ib.height else {+ return nil+ }+ let w = ia.width, h = ia.height+ let a = gray(ia, w, h), b = gray(ib, w, h)+ let nx = Double(near.x), ny = Double(near.y), rx = Double(reach.x), ry = Double(reach.y)+ let left = max(0, Int((nx - rx) * Double(w)))+ let top = max(Int(0.05 * Double(h)), Int((ny - ry) * Double(h))) // skip the status bar+ let right = min(w, Int((nx + rx) * Double(w))), bottom = min(h, Int((ny + ry) * Double(h)))+ guard right > left, bottom > top else { return nil }+ var hits: [(Int, Int)] = []+ for y in top..<bottom {+ for x in left..<right where abs(Int(a.px[y * w + x]) - Int(b.px[y * w + x])) > 30 {+ hits.append((x - left, y - top))+ }+ }+ let area = (right - left) * (bottom - top)+ guard hits.count >= 15, hits.count <= area / 4 else { return nil } // nothing moved, or more than a pointer+ let xs = hits.map(\.0), ys = hits.map(\.1)+ if Double(xs.max()! - xs.min()!) > 0.15 * Double(w) || Double(ys.max()! - ys.min()!) > 0.07 * Double(h) {+ return nil // not one compact spot+ }+ let cx = Double(xs.reduce(0, +)) / Double(hits.count) + Double(left)+ let cy = Double(ys.reduce(0, +)) / Double(hits.count) + Double(top)+ return CGPoint(x: cx / Double(w) - shift / 2, y: cy / Double(h))+ }+}diff --git a/ios/IPhoneAgent/App/AgentShortcuts.swift b/ios/IPhoneAgent/App/AgentShortcuts.swiftnew file mode 100644index 0000000..65ed093--- /dev/null+++ b/ios/IPhoneAgent/App/AgentShortcuts.swift@@ -0,0 +1,82 @@+import AppIntents+import SwiftUI++/// "Ask ESP32 Agent to …": runs a typed task. A LiveActivityIntent so it runs in the app process in the+/// background (the run itself happens on the Home Screen) and may start the Live Activity.+struct RunTaskIntent: LiveActivityIntent {+ static let title: LocalizedStringResource = "Run a Task"+ static let description = IntentDescription("Asks ESP32 Agent to do a task on this iPhone, like \"Open Settings and go to Wi-Fi\".")++ @Parameter(title: "Task", requestValueDialog: "What should I do?") var task: String++ static var parameterSummary: some ParameterSummary { Summary("Ask ESP32 Agent to \(\.$task)") }++ func perform() async throws -> some IntentResult & ProvidesDialog {+ let line = await AgentRequests.handle?(.runTask(task)) ?? AgentRequests.unavailable+ return .result(dialog: "\(line)")+ }+}++/// Calibration catches taps on this app's own screen, so it opens the app.+struct CalibrateIntent: AppIntent {+ static let title: LocalizedStringResource = "Calibrate the Pointer"+ static let description = IntentDescription("Opens ESP32 Agent and calibrates the pointer.")+ static let openAppWhenRun = true++ @MainActor+ func perform() async throws -> some IntentResult & ProvidesDialog {+ let line = await AgentRequests.handle?(.calibrate) ?? AgentRequests.unavailable+ return .result(dialog: "\(line)")+ }+}++struct GetStatusIntent: AppIntent {+ static let title: LocalizedStringResource = "Get Status"+ static let description = IntentDescription("Tells whether the board, Screen Mirroring, calibration and the model are ready.")++ @MainActor+ func perform() async throws -> some IntentResult & ProvidesDialog & ShowsSnippetView {+ let line = await AgentRequests.handle?(.status) ?? AgentRequests.unavailable+ let snapshot = SharedState.load()+ return .result(dialog: "\(line)", view: StatusSnippet(mood: snapshot?.mood ?? .sleeping, lines: AppModel.shared.statusLines))+ }+}++struct StatusSnippet: View {+ let mood: Mood+ let lines: [String]++ var body: some View {+ HStack(alignment: .top, spacing: 14) {+ AgentFace(mood: mood, animated: false, reacts: false).frame(width: 44, height: 50)+ VStack(alignment: .leading, spacing: 4) {+ ForEach(lines, id: \.self) { Text(verbatim: $0).font(.subheadline) }+ }+ Spacer(minLength: 0)+ }+ .padding()+ }+}++struct AgentShortcuts: AppShortcutsProvider {+ static var appShortcuts: [AppShortcut] {+ AppShortcut(intent: RunSavedIntentIntent(), phrases: [+ "Run \(.applicationName) intent \(\.$intent)",+ "Run \(\.$intent) with \(.applicationName)",+ ], shortTitle: "Run Intent", systemImageName: "bolt.fill")+ AppShortcut(intent: RunTaskIntent(), phrases: [+ "Ask \(.applicationName) to do something",+ "Give \(.applicationName) a task",+ ], shortTitle: "Run a Task", systemImageName: "text.bubble")+ AppShortcut(intent: StopAgentIntent(), phrases: [+ "Stop \(.applicationName)",+ ], shortTitle: "Stop", systemImageName: "stop.fill")+ AppShortcut(intent: GetStatusIntent(), phrases: [+ "\(.applicationName) status",+ "Is \(.applicationName) ready",+ ], shortTitle: "Status", systemImageName: "checkmark.circle")+ AppShortcut(intent: CalibrateIntent(), phrases: [+ "Calibrate \(.applicationName)",+ ], shortTitle: "Calibrate", systemImageName: "scope")+ }+}diff --git a/ios/IPhoneAgent/App/AppModel.swift b/ios/IPhoneAgent/App/AppModel.swiftnew file mode 100644index 0000000..e81861f--- /dev/null+++ b/ios/IPhoneAgent/App/AppModel.swift@@ -0,0 +1,263 @@+import Combine+import Foundation+import UIKit++/// Wires the board, the screen feed, the pointer, the agent and the metrics together.+@MainActor final class AppModel: ObservableObject {+ /// One per process: the UI, App Intents (also when iOS launches the app in the background) and widgets use it.+ static let shared = AppModel()++ struct LogLine: Identifiable {+ let id = UUID()+ let time = Date()+ let text: String+ }++ let settings = Settings()+ let board = BoardLink(mock: MockMode.on)+ let feed = VideoFeed()+ let metrics = Metrics()+ let traces = MockMode.on+ ? TraceStore(root: FileManager.default.temporaryDirectory.appendingPathComponent("demo-traces"))+ : TraceStore()+ let intents = IntentStore()+ private(set) lazy var runs = RunStore(traces: traces)+ let pointer: Pointer+ let agent: AgentLoop+ @Published private(set) var log: [LogLine] = []+ @Published var modelOK: Bool? // last LLM ping result+ @Published var hotspotSSID: String?+ @Published var otherWiFi: String? // the phone is on this network, not the board's+ /// The character's mood during and right after a run; nil = resting (idle or sleeping, see `mood`).+ @Published var runMood: Mood?+ @Published var tab = AppTab.agent+ /// Setup page to show (onboarding, or a Home status chip deep link); nil = hidden.+ @Published var setupPage: SetupPage?+ /// The review editor on screen (after a run, a recording, or editing an intent).+ @Published var review: ReviewDraft?+ /// Paused for the user: why (nil = not paused), and whether they are doing it by hand right now.+ @Published var help: String?+ @Published var recovering: Recovery.Stage? // the run is paused for a lost link (board, hotspot, mirroring)+ var recoverySince = Date()+ @Published var takingOver = false+ @Published var departing = false // the character's take-off before a run+ /// A banner on Home: the app could not leave by itself (swipe up), or the run waits while the app is in front.+ @Published var homeHint: String?+ var resumeAsked = 0.0 // when Continue was tapped in the app+ let live = LiveActivityController()+ let notifier = Notifier()+ private(set) lazy var recorder = DemoRecorder(app: self)+ var mockJob: Task<Void, Never>?+ @Published var mockMirroring = false+ var moodReset: Task<Void, Never>?+ var helpWait: CheckedContinuation<AgentLoop.HelpChoice, Never>?+ var currentIntent: SavedTask?+ var lastTask = ""+ var runStarted = Date()+ var videoSink: AnyCancellable?+ var videoDir: URL?+ private(set) lazy var calibrator = AutoCalibrator(app: self)+ let probe = TouchProbe()+ private var lastStatus = ""+ private var lastTick = now()+ private var lastStreamLog = 0.0+ private var timers: [Task<Void, Never>] = []+ var backgroundTask: UIBackgroundTaskIdentifier = .invalid+ var lastWidgetReload = 0.0++ init() {+ let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]+ try? FileManager.default.createDirectory(at: support, withIntermediateDirectories: true)+ pointer = Pointer(device: board.commands, calibrationFile: support.appendingPathComponent("calibration.json"),+ screen: feed)+ agent = AgentLoop(phone: pointer, screen: feed, actor: nil, planner: nil, trace: traces)+ agent.metrics = metrics+ feed.device = board.commands+ feed.metrics = metrics++ let say: (String) -> Void = { [weak self] in self?.say($0) }+ board.log = say+ board.commands.log = say+ pointer.log = say+ pointer.screenAspect = { DeviceScreen.aspect }+ pointer.locate = { [weak self] jpeg in await self?.locatePointer(jpeg) }+ DebugLog.relay = { [weak self] line in+ MainActor.assumeIsolated { if !MockMode.on { self?.board.commands.relayLog(line) } }+ }+ board.commands.onAppCommand = { [weak self] line in self?.handleAppCommand(line) }+ DebugLog.write("app launched \(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") ?? "")"+ + " (\(Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") ?? ""))")+ board.onVideo = { [weak self] in self?.feed.receive($0) }+ board.onStatus = { [weak self] s in+ self?.feed.mirroring = s.ap == "streaming"+ if let up = s.up { self?.feed.boardClock(ms: up) }+ self?.metrics.status(s)+ self?.logStatus(s)+ }+ board.onLinkUp = { [weak self] in+ guard let self else { return }+ feed.resetStream()+ metrics.mtu = board.mtu+ if agent.running && !MockMode.on && FrameMode.current == .stream { // the board forgot `stream on`: the paused run needs the screen back+ Task { [weak self] in+ do { try await self?.feed.stream(true); DebugLog.write("recover: BLE back, stream on again") } catch {+ DebugLog.write("recover: stream on after reconnect failed: \(error.localizedDescription)")+ }+ }+ }+ }+ board.onLinkDown = { [weak self] in self?.feed.linkLost() }+ board.commands.onTimeout = { [weak self] command in await self?.commandTimedOut(command) }+ DebugLog.write("frame mode: \(FrameMode.current.rawValue)")+ board.commands.onTiming = { [weak self] name, ms in self?.metrics.hidMs[name] = ms }+ agent.onFinish = { [weak self] in self?.agentFinished() }+ agent.onStep = { [weak self] in self?.stepped() }+ agent.onDoing = { [weak self] d in self?.doing(d) }+ agent.onHelp = { [weak self] reason in await self?.needsHelp(reason) ?? .stop }+ agent.gate = { [weak self] in try await self?.holdWhileInFront() }+ AgentControl.handle = { [weak self] command in await self?.control(command) }+ AgentRequests.handle = { [weak self] request in await self?.handle(request) ?? AgentRequests.unavailable }+ notifier.onAction = { [weak self] action, run in self?.notificationAction(action, run: run) }+ wireRecovery()++ timers.append(Task { [weak self] in await self?.board.commands.keepAwake(screenLive: { self?.feed.live ?? false }) })+ timers.append(Task { [weak self] in+ while !Task.isCancelled {+ try? await Task.sleep(nanoseconds: 1_000_000_000)+ self?.tick()+ }+ })+ let center = NotificationCenter.default+ center.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] _ in+ MainActor.assumeIsolated { self?.metrics.enteredBackground(); DebugLog.write("app: background") }+ }+ center.addObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] _ in+ MainActor.assumeIsolated { self?.metrics.enteredForeground(); DebugLog.write("app: foreground") }+ }+ if MockMode.on { startMock() }+ runs.reload()+ handleLaunchArguments()+ publishWidget()+ }++ /// Every second: metrics; a suspension note; the stream's numbers every 10 s while a run goes.+ private func tick() {+ let before = metrics.suspensions, gap = now() - lastTick+ metrics.tick()+ lastTick = now()+ publishWidget()+ if metrics.suspensions > before { DebugLog.write(String(format: "app: resumed after %.0f s suspended", gap)) }+ if agent.running, now() - lastStreamLog >= 10 {+ lastStreamLog = now()+ let s = board.status+ DebugLog.write(String(format: "stream: decoded %.1f fps, BLE in %.0f kbps (board %.0f kbps out, AirPlay %.0f kbps %.1f fps), frame age %.1f s, drops %d",+ metrics.fps, metrics.bleKbps, s?.ble?.kbps ?? 0, s?.kbps ?? 0, s?.fps ?? 0,+ feed.updated > 0 ? now() - feed.updated : -1, metrics.drops))+ }+ }++ /// A command timed out: video may be starving the board's control traffic. Stop the stream and run+ /// snap-per-step for the rest of this run (the next run streams again).+ private func commandTimedOut(_ command: String) async {+ DebugLog.write("cmd timeout on '\(command.prefix(30))': stream off, snap-per-step for this run")+ FrameMode.fallback = .snap+ if feed.streamOn { _ = try? await feed.stream(false) }+ }++ func setFrameMode(_ mode: FrameMode) {+ FrameMode.current = mode+ say("frame mode: \(mode.rawValue)")+ if mode == .stream && agent.running { Task { try? await feed.stream(true) } }+ if mode == .snap && feed.streamOn { Task { try? await feed.stream(false) } }+ }++ /// The run paused for the board (line) or goes on (nil).+ /// Board status changes go to the debug log (not every identical notify).+ private func logStatus(_ s: BoardStatus) {+ let line = "board status: ap \(s.ap ?? "-") usb \(s.usb ?? "-") sta \(s.sta.map(String.init) ?? "-")"+ + " screen \(s.w.map(String.init) ?? "-")x\(s.h.map(String.init) ?? "-") rst \(s.rst ?? "-")"+ guard line != lastStatus else { return }+ lastStatus = line+ DebugLog.write(line)+ if let up = s.up, up < 30_000 { // a link drop that is really the board rebooting (crash, brownout, ...)+ DebugLog.write("board: booted \(up / 1000) s ago (reset: \(s.rst ?? "?"), heap \((s.heap ?? 0) / 1024) KB)")+ }+ }++ /// The character's mood right now.+ var mood: Mood { runMood ?? (board.connected ? .idle : .sleeping) }++ /// The model endpoint is filled in (demo data simulates one).+ var modelReady: Bool { MockMode.on || settings.isConfigured }++ func say(_ text: String) {+ log = Array((log + [LogLine(text: text)]).suffix(200))+ DebugLog.write(text)+ }++ // MARK: - setup and diagnostics++ /// The one-tap join of the board's Wi-Fi (state machine in HotspotJoin.swift).+ @Published var join = JoinState.idle+ var joinTask: Task<Void, Never>?++ /// Set when one-tap join failed: the user joins in Settings with the shown password.+ @Published var manualHotspot: NetConfig?++ func bench(kb: Int = 256) async {+ do {+ let reply = try await board.commands.send("bench \(kb)")+ let ms = Double(reply.split(separator: " ").first ?? "") ?? 0+ metrics.benchKbps = ms > 0 ? Double(kb) * 8 * 1024 / ms : nil+ say(String(format: "BLE bench: %d KB in %.0f ms", kb, ms))+ } catch {+ say("bench: \(error.localizedDescription)")+ }+ }++ func snapTest() async {+ do { say(String(format: "snap -> decoded in %.0f ms", try await feed.snap())) } catch {+ say("snap: \(error.localizedDescription)")+ }+ }++ func pingLLM() async {+ if MockMode.on {+ try? await Task.sleep(nanoseconds: 900_000_000)+ modelOK = true+ return say("LLM ok (demo data)")+ }+ let started = now()+ do {+ let client = try await settings.client("actor")+ let r = try await client.chat(system: "Reply with OK.", text: "ping", image: nil, maxTokens: 600, temperature: 0)+ metrics.llmPingMs = (now() - started) * 1000+ metrics.llm(first: r.firstToken, total: r.total)+ modelOK = true+ say(String(format: "LLM ok in %.0f ms: %@", metrics.llmPingMs ?? 0, String(r.text.prefix(40))))+ } catch {+ modelOK = false+ say("LLM: \(error.localizedDescription)")+ }+ }++ /// Ping the LLM every 2 s for `seconds` (switch to another app meanwhile) and report what survived.+ func backgroundTest(seconds: Double = 600) async {+ let id = UIApplication.shared.beginBackgroundTask(withName: "bgtest")+ defer { UIApplication.shared.endBackgroundTask(id) }+ guard let client = try? await settings.client("actor") else { return say("background test: no model") }+ let started = now()+ var ok = 0, failed = 0, decodedBefore = metrics.decodeErrors+ say("background test: \(Int(seconds)) s, switch to another app now")+ try? await feed.stream(true)+ while now() - started < seconds && !Task.isCancelled {+ do { _ = try await client.chat(system: "Reply with OK.", text: "ping", image: nil, maxTokens: 600, temperature: 0); ok += 1 }+ catch { failed += 1 }+ try? await Task.sleep(nanoseconds: 2_000_000_000)+ }+ try? await feed.stream(false)+ decodedBefore = metrics.decodeErrors - decodedBefore+ say("background test: LLM \(ok) ok / \(failed) failed, decode errors \(decodedBefore), "+ + "suspensions \(metrics.suspensions), background alive \(Int(metrics.backgroundAlive)) s")+ }+}diff --git a/ios/IPhoneAgent/App/AppPresence.swift b/ios/IPhoneAgent/App/AppPresence.swiftnew file mode 100644index 0000000..f7b5c6c--- /dev/null+++ b/ios/IPhoneAgent/App/AppPresence.swift@@ -0,0 +1,69 @@+import Foundation+import UIKit++/// The agent works on the phone this app runs on, so the app must be out of the way: Start sends it to the+/// Home Screen (and checks that iOS really put it in the background), and a run holds while it is in front.+extension AppModel {++ private var inBackground: Bool { UIApplication.shared.applicationState == .background }++ /// Leaves our own app without touching the screen: iOS's own suspend (as the Home gesture does),+ /// then the board's Cmd+H and home flick as fallbacks. The model is never asked to do this.+ func leaveApp() async -> Bool {+ for method in ["suspend", "cmd+h", "home swipe"] {+ if inBackground { return true }+ do {+ switch method {+ case "suspend": await MainActor.run { _ = UIApplication.shared.perform(NSSelectorFromString("suspend")) }+ case "cmd+h": try await pointer.key("cmd+h")+ default: try await pointer.goHome()+ }+ } catch {+ DebugLog.write("leave app: \(method) failed: \(error.localizedDescription)")+ continue+ }+ if await waitForBackground(2) { DebugLog.write("leave app: in background after \(method)"); return true }+ DebugLog.write("leave app: still in front after \(method)")+ }+ return false+ }++ /// Neither way worked: ask the user to swipe up, and wait for it (bounded).+ func askUserToLeave() async -> Bool {+ homeHint = String(localized: "Swipe up to go to the Home Screen, and I'll start.")+ defer { homeHint = nil }+ return await waitForBackground(30)+ }++ /// Before each look and gesture of a run. If the agent itself brought the app to the front (it tapped our+ /// Live Activity, a notification or an intent), or Continue was just tapped here, send the app away at once;+ /// if the user opened it, wait until they leave. The model never sees or taps this app's own screens.+ func holdWhileInFront() async throws {+ guard UIApplication.shared.applicationState == .active, agent.running, !MockMode.on else { return }+ let ours = now() - agent.lastActed < 3 || now() - resumeAsked < 5+ DebugLog.write("run: ESP32 Agent is in front (\(ours ? "after an agent action" : "opened by the user")); holding")+ let since = now()+ var away = false+ if ours { away = await leaveApp() }+ if !away {+ homeHint = String(localized: "Paused while you're here. Go to the Home Screen and I'll go on.")+ defer { homeHint = nil }+ while !inBackground {+ try Task.checkCancellation()+ try await Task.sleep(nanoseconds: 300_000_000)+ }+ }+ _ = await feed.fresh(since: since, timeout: 3) // a frame of the screen that is in front now+ await feed.settled()+ DebugLog.write("run: app in background again, going on")+ }++ private func waitForBackground(_ seconds: Double) async -> Bool {+ let deadline = now() + seconds+ while !inBackground {+ if now() > deadline { return false }+ try? await Task.sleep(nanoseconds: 100_000_000)+ }+ return true+ }+}diff --git a/ios/IPhoneAgent/App/AutoCalibrator.swift b/ios/IPhoneAgent/App/AutoCalibrator.swiftnew file mode 100644index 0000000..4074b71--- /dev/null+++ b/ios/IPhoneAgent/App/AutoCalibrator.swift@@ -0,0 +1,221 @@+import Foundation+import UIKit++/// Calibrates the pointer like a 3D printer's auto bed levelling, on the calibration board: a white+/// full-screen grid (CalibrationBoard) over the app. The board homes the pointer, clicks at known mouse+/// distances and the app catches the taps (TouchProbe), then fits mouse units → screen per axis. When no tap+/// arrives it falls back to finding the pointer in the mirrored video (pixel diff, then the vision model).+/// If both fail the board offers Try Again and "Tap the pointer yourself" (manual needs the grid behind it).+/// It never starts by itself: when calibration is needed and the mouse and mirroring are up, the Agent page+/// shows a Calibrate button; a run calibrates first if needed; Settings › Calibration starts it too.+@MainActor final class AutoCalibrator: ObservableObject {+ enum Phase: Equatable {+ case idle, homing, probeA, probeB, verifying, done, needsTap, failed++ /// 1...4 while working.+ var step: Int? {+ switch self {+ case .homing: return 1+ case .probeA: return 2+ case .probeB: return 3+ case .verifying: return 4+ default: return nil+ }+ }+ }++ struct Progress: Equatable { var done: Int, total: Int }++ static let tolerance = 0.015 // fraction of the screen; a bigger miss calibrates again++ @Published var phase = Phase.idle+ @Published var reason = "" // why the last run started+ @Published var progress: Progress? // probe clicks+ /// Why the last run failed, in words for the board (e.g. clicks not reaching the screen).+ @Published var problem: String?+ /// The calibration board is up.+ @Published private(set) var boardOpen = false+ /// The small success toast ("Pointer calibrated ±0.6%").+ @Published var toast = false+ unowned let app: AppModel+ var link = -1 // board link the pointer was last calibrated on+ private var hide: Task<Void, Never>?+ private var current: Task<Void, Never>?++ init(app: AppModel) { self.app = app }++ var busy: Bool { phase.step != nil }++ /// The mouse is up (board connected, USB HID mounted).+ var boardReady: Bool { app.board.connected && app.board.status?.usb == "ok" }+ var mirroring: Bool { app.board.status?.ap == "streaming" }++ /// Calibration is due: never done, the screen shape changed, or the learned correction drifted.+ var needed: Bool {+ let p = app.pointer+ guard p.calibrated else { return true }+ if let aspect = p.aspect, abs(aspect - DeviceScreen.aspect) > 0.02 { return true }+ return p.drift > Self.tolerance+ }++ /// Show the Calibrate button: due, and everything it needs is up.+ var offer: Bool { (needed || MockMode.on && !app.pointer.calibrated) && (MockMode.on || boardReady && mirroring) && !busy && !boardOpen }++ /// Open the board and calibrate automatically (Calibrate button, Settings, debug entry).+ func calibrate(why: String = String(localized: "requested")) {+ guard !busy else { return }+ Task { await run(why: why) }+ }++ /// Before a run: calibrate if needed and wait for it. True when the pointer is calibrated.+ func ensureCalibrated() async -> Bool {+ while busy { try? await Task.sleep(nanoseconds: 200_000_000) }+ if !app.pointer.calibrated && boardReady { await run(why: String(localized: "before a run")) }+ return app.pointer.calibrated+ }++ /// One automatic calibration, on the board when the app is in front.+ func run(why: String) async {+ reason = why+ problem = nil+ progress = nil+ toast = false+ if DeviceScreen.foreground { openBoard() }+ let job = Task { await runOnce() }+ current = job+ await job.value+ current = nil+ }++ private func openBoard() {+ boardOpen = true+ app.probe.begin()+ }++ private func closeBoard() {+ boardOpen = false+ app.probe.end()+ }++ /// The board's Back button: stop whatever runs and close the board.+ func cancel() {+ current?.cancel()+ if busy || phase == .needsTap { app.say("calibration: cancelled") }+ progress = nil+ phase = app.pointer.calibrated ? .done : .idle+ closeBoard()+ Task { _ = try? await app.pointer.reset() }+ }++ private func runOnce() async {+ if MockMode.on { return await mockRun() }+ app.say("calibration: \(reason)")+ var noTaps = false+ if boardOpen {+ do {+ switch try await touchCalibrate(full: true) {+ case .done(let error): return finished(error)+ case .noTaps: noTaps = true+ case .failed(let why): app.say("calibration: touch probe failed: \(why)")+ }+ } catch {+ if Task.isCancelled { return }+ app.say("calibration: touch probe: \(error.localizedDescription)")+ }+ }+ if Task.isCancelled { return }+ progress = nil+ await videoCalibrate(noTaps: noTaps)+ }++ /// The fallback: find the pointer in the mirrored video.+ private func videoCalibrate(noTaps: Bool) async {+ let diagnosis = noTaps ? Self.noTapsText : nil+ guard mirroring else { return failed(diagnosis ?? String(localized: "Mirroring is off, so the pointer can't be seen.")) }+ guard FrameMode.current == .stream else { // the video finder needs the live stream+ app.say("calibration: video fallback skipped in snap mode")+ return failed(diagnosis ?? String(localized: "Pointer not found on screen."))+ }+ do {+ try await app.feed.stream(true)+ defer { if !app.agent.running { Task { try? await app.feed.stream(false) } } }+ let ok = try await app.pointer.startCalibration { [weak self] i in+ self?.phase = [.homing, .probeA, .probeB][min(i, 2)]+ }+ if Task.isCancelled { return }+ guard ok else { return failed(diagnosis ?? String(localized: "Pointer not found on screen.")) }+ phase = .verifying+ guard let error = try await app.pointer.verify() else {+ return failed(diagnosis ?? String(localized: "Check point not found."))+ }+ finished(error)+ } catch {+ if !Task.isCancelled { failed(diagnosis ?? error.localizedDescription) }+ }+ }++ static var noTapsText: String {+ String(localized: "Clicks aren't reaching the screen — is AssistiveTouch on and the board plugged into this iPhone?")+ }++ func finished(_ error: Double) {+ link = app.board.commands.links+ progress = nil+ problem = nil+ phase = .done+ app.say(String(format: "calibration: ±%.1f%%", error * 100))+ closeBoard()+ toast = true+ hide?.cancel()+ hide = Task { [weak self] in+ try? await Task.sleep(nanoseconds: 2_500_000_000)+ guard !Task.isCancelled else { return }+ self?.toast = false+ }+ }++ /// The board stays up with the problem, Try Again and "Tap the pointer yourself".+ private func failed(_ why: String) {+ progress = nil+ problem = why+ phase = .failed+ app.say("calibration failed: \(why)")+ }++ // MARK: - manual, on the board++ /// "Tap the pointer yourself": park the pointer at a known spot, then the next tap on the board is where it is.+ func startManual() {+ guard boardOpen else { return }+ problem = nil+ phase = .needsTap+ current?.cancel()+ current = Task {+ do {+ try await app.pointer.reset()+ try await app.board.commands.send("move \(Pointer.calibrationMove) \(Pointer.calibrationMove)")+ } catch {+ return failed(error.localizedDescription)+ }+ let since = now()+ while !Task.isCancelled && phase == .needsTap {+ if let p = await app.probe.tap(since: since, timeout: 1) {+ app.say(String(format: "calibration: tapped the pointer at (%.3f, %.3f)", p.x, p.y))+ app.pointer.finishCalibration(x: p.x, y: p.y)+ return finished(app.pointer.quality ?? 0.01)+ }+ }+ }+ }++ private func mockRun() async {+ for (i, p) in [Phase.homing, .probeA, .probeB, .verifying].enumerated() {+ phase = p+ progress = Progress(done: i * 2, total: 8)+ try? await Task.sleep(nanoseconds: 700_000_000)+ if Task.isCancelled { return }+ }+ app.pointer.mockCalibrated(quality: 0.006)+ finished(0.006)+ }+}diff --git a/ios/IPhoneAgent/App/DebugEntry.swift b/ios/IPhoneAgent/App/DebugEntry.swiftnew file mode 100644index 0000000..52c8ac3--- /dev/null+++ b/ios/IPhoneAgent/App/DebugEntry.swift@@ -0,0 +1,129 @@+import Foundation++/// Drive the app without touching the phone, for development:+/// iphoneagent://run?task=<urlencoded> iphoneagent://calibrate iphoneagent://stop+/// iphoneagent://bench?kb=256 iphoneagent://snap+/// or launch arguments: -run "<task>", -calibrate, -bench 256, -snap+/// (e.g. `xcrun devicectl device process launch --device <id> <bundle id> -run "Open Clock"`).+/// Commands that need the board wait up to 30 s for it (and mirroring, for a run) before giving up.+extension AppModel {+ /// True when the URL was a debug command (iphoneagent://run/<id> from the Live Activity is not).+ @discardableResult+ func handleDebug(_ url: URL) -> Bool {+ guard url.scheme == "iphoneagent", let host = url.host else { return false }+ let query = URLComponents(url: url, resolvingAgainstBaseURL: false)?.queryItems ?? []+ func arg(_ name: String) -> String? { query.first { $0.name == name }?.value }+ switch host {+ case "run":+ guard let task = arg("task"), !task.isEmpty else { return false }+ debugCommand("run", task: task)+ case "calibrate", "stop", "snap":+ debugCommand(host)+ case "status":+ say(statusSummary)+ case "bench":+ debugCommand("bench", kb: Int(arg("kb") ?? "") ?? 256)+ default:+ return false+ }+ return true+ }++ /// A line from the Mac harness, relayed by the board: "run <task>", "calibrate", "stop", "bench <kb>",+ /// "snap" or "status".+ func handleAppCommand(_ line: String) {+ let parts = line.split(separator: " ", maxSplits: 1).map(String.init)+ let name = parts.first ?? "", rest = parts.count > 1 ? parts[1] : ""+ switch name {+ case "run" where !rest.isEmpty: debugCommand("run", task: rest)+ case "calibrate", "stop", "snap": debugCommand(name)+ case "bench": debugCommand("bench", kb: Int(rest) ?? 256)+ case "status": say(statusSummary)+ case "log": relayHistory(Int(rest) ?? 50)+ case "mode":+ if let mode = FrameMode(rawValue: rest) { setFrameMode(mode) } else { say("frame mode: \(FrameMode.current.rawValue)") }+ default: say("debug: unknown app command \"\(line.prefix(40))\"")+ }+ }++ /// "app log <n>": the last n debug.log lines to the harness, paced under the relay's rate limit; a line+ /// is retried while the link is busy.+ func relayHistory(_ n: Int) {+ let lines = DebugLog.tail(min(n, 2000))+ Task { [weak self] in+ for line in lines {+ for _ in 0..<20 {+ guard let self, self.board.connected else { return }+ if self.board.commands.relayLog("hist " + line) { break }+ try? await Task.sleep(nanoseconds: 60_000_000)+ }+ try? await Task.sleep(nanoseconds: 110_000_000)+ }+ }+ }++ /// One line: board, mirroring, calibration, model and run.+ var statusSummary: String {+ let s = board.status+ let boardText = board.connected ? "connected usb \(s?.usb ?? "-") ap \(s?.ap ?? "-") sta \(s?.sta.map(String.init) ?? "-")"+ : "not connected"+ let mirror = feed.live ? String(format: "live %.2f", feed.aspect) : "off"+ let cal = pointer.span.map { "\($0.w)x\($0.h) " + (pointer.quality.map { String(format: "±%.1f%%", $0 * 100) } ?? "?") }+ ?? "none"+ let model = settings.isConfigured ? (settings.currentModel ?? "auto") : "not set"+ let run = agent.running ? "running step \(agent.steps.count)" : "idle"+ return "status: frames \(FrameMode.current.rawValue); board \(boardText); mirroring \(mirror); calibration \(cal) (\(calibrator.phase)); "+ + "model \(model); run \(run); screen \(Int(DeviceScreen.size.width))x\(Int(DeviceScreen.size.height))"+ }++ /// Launch arguments, once at startup.+ func handleLaunchArguments(_ args: [String] = ProcessInfo.processInfo.arguments) {+ func value(after flag: String) -> String? {+ guard let i = args.firstIndex(of: flag), i + 1 < args.count else { return nil }+ return args[i + 1]+ }+ if let task = value(after: "-run") { debugCommand("run", task: task) }+ if args.contains("-calibrate") { debugCommand("calibrate") }+ if args.contains("-bench") { debugCommand("bench", kb: Int(value(after: "-bench") ?? "") ?? 256) }+ if args.contains("-snap") { debugCommand("snap") }+ }++ private func debugCommand(_ name: String, task: String = "", kb: Int = 256) {+ say("debug: \(name)\(task.isEmpty ? "" : " \"\(task)\"")\(name == "bench" ? " \(kb) KB" : "")")+ Task { [weak self] in+ guard let self else { return }+ switch name {+ case "stop":+ await stopAgent()+ case "run":+ guard await waitReady(mirroring: true) else { return say("debug: run not started, board/mirroring not ready in 30 s") }+ guard !agent.running else { return say("debug: a run is already going") }+ tab = .agent+ await run(task)+ case "calibrate":+ guard await waitReady(mirroring: false) else { return say("debug: board not ready in 30 s") }+ calibrator.calibrate()+ case "bench":+ guard await waitReady(mirroring: false) else { return say("debug: board not ready in 30 s") }+ await bench(kb: kb)+ case "snap":+ guard await waitReady(mirroring: true) else { return say("debug: mirroring not ready in 30 s") }+ await snapTest()+ default:+ break+ }+ }+ }++ /// Board connected (and USB up), plus mirroring streaming when asked; waits up to `timeout` s.+ func waitReady(mirroring: Bool, timeout: Double = 30) async -> Bool {+ if MockMode.on { return true }+ let deadline = now() + timeout+ while now() < deadline {+ let s = board.status+ if board.connected && s?.usb == "ok" && (!mirroring || s?.ap == "streaming") { return true }+ try? await Task.sleep(nanoseconds: 500_000_000)+ }+ return false+ }+}diff --git a/ios/IPhoneAgent/App/DemoRecorder.swift b/ios/IPhoneAgent/App/DemoRecorder.swiftnew file mode 100644index 0000000..5e2353b--- /dev/null+++ b/ios/IPhoneAgent/App/DemoRecorder.swift@@ -0,0 +1,160 @@+import Foundation+import UIKit++/// "Record me doing it": while the user does the task by hand, keep a keyframe each time the mirrored screen+/// changes and settles. On stop, the model infers the steps from the keyframes (fingers are invisible to the+/// board, so it guesses from before/after) and the draft opens in the review editor, unsure steps in yellow.+@MainActor final class DemoRecorder: ObservableObject {+ @Published private(set) var recording = false+ @Published private(set) var inferring = false+ @Published private(set) var keyframes = 0+ @Published private(set) var started = Date()+ @Published var error: String?+ private unowned let app: AppModel+ private var folder: URL?+ private var loop: Task<Void, Never>?+ static let maxFrames = 12++ init(app: AppModel) { self.app = app }++ static var root: URL {+ FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("recordings")+ }++ func start() {+ guard !recording, !app.agent.running else { return }+ let f = DateFormatter()+ f.dateFormat = "yyyyMMdd-HHmmss"+ f.locale = Locale(identifier: "en_US_POSIX")+ let dir = Self.root.appendingPathComponent(f.string(from: Date()))+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ folder = dir+ keyframes = 0+ error = nil+ started = Date()+ recording = true+ app.live.start(task: String(localized: "Recording a demonstration"), runID: "rec-" + dir.lastPathComponent,+ limit: 0, phase: .recording)+ app.runMood = .listening+ loop = Task { [weak self] in await self?.capture() }+ }++ private func capture() async {+ if MockMode.on {+ while recording && !Task.isCancelled {+ save(AppModel.mockFrame)+ try? await Task.sleep(nanoseconds: 1_500_000_000)+ }+ return+ }+ try? await app.feed.stream(true)+ var last: Data?+ while recording && !Task.isCancelled {+ try? await Task.sleep(nanoseconds: 400_000_000)+ guard let frame = app.feed.frame, Vision.changed(last, frame) else { continue }+ await app.feed.settled() // keep the screen after the change, not mid-animation+ last = app.feed.frame ?? frame+ save(last)+ }+ }++ private func save(_ jpeg: Data?) {+ guard let jpeg, let folder else { return }+ keyframes += 1+ try? jpeg.write(to: folder.appendingPathComponent(String(format: "k%03d.jpg", keyframes)))+ app.live.update(mood: .listening, step: keyframes,+ line: String(localized: "\(keyframes) screens captured. Stop when you're done."), phase: .recording)+ }++ func cancel() {+ loop?.cancel()+ recording = false+ app.live.end(nil)+ app.runMood = nil+ if let folder { try? FileManager.default.removeItem(at: folder) }+ }++ /// Stop and turn the keyframes into an intent draft in the review editor.+ func stop() async {+ guard recording, let folder else { return }+ loop?.cancel()+ recording = false+ if !MockMode.on { try? await app.feed.stream(false) }+ app.live.end((.thinking, String(localized: "Working out the steps…")))+ inferring = true+ let bg = UIApplication.shared.beginBackgroundTask(withName: "infer") // stopped from the Dynamic Island+ defer { inferring = false; app.runMood = nil; UIApplication.shared.endBackgroundTask(bg) }+ let frames = (1...max(keyframes, 1)).map { folder.appendingPathComponent(String(format: "k%03d.jpg", $0)) }+ .filter { FileManager.default.fileExists(atPath: $0.path) }+ guard !frames.isEmpty else { error = String(localized: "No screen changes were captured."); return }+ let picked = Self.sample(frames, Self.maxFrames)+ do {+ let reply = MockMode.on ? try await Self.mockReply() : try await infer(picked)+ let draft = Self.draft(reply, frames: picked, folder: folder)+ draft.saveEdits()+ app.notifier.post(.done, title: String(localized: "Intent draft ready"),+ body: String(localized: "\(draft.steps.count) steps. Check the yellow ones."),+ run: "rec-" + folder.lastPathComponent)+ app.review = draft+ } catch {+ self.error = error.localizedDescription+ }+ }++ private func infer(_ frames: [URL]) async throws -> String {+ let images = frames.compactMap { try? Data(contentsOf: $0) }+ let r = try await app.settings.client("planner").chat(system: Self.inferPrompt, text:+ "These are \(images.count) keyframes in order (frame 1 first). Infer the steps.",+ images: images, maxTokens: 1200, temperature: 0)+ return r.text+ }++ static func sample(_ frames: [URL], _ n: Int) -> [URL] {+ guard frames.count > n else { return frames }+ return (0..<n).map { frames[$0 * (frames.count - 1) / (n - 1)] }+ }++ static let inferPrompt = """+ You watch keyframes of a person using an iPhone, in order. Fingers are not visible: infer each action \+ from how the screen changed between two frames. Coordinates are 0-1000 of the screen width and height. \+ Reply in this format only:+ NAME: <short name for the task>+ PROMPT: <one instruction that would make an AI agent repeat this task>+ STEP <frame number the action was done on>: <command> | sure or unsure+ Commands: tap X Y, swipe X1 Y1 X2 Y2, type "text", home, back, wait.+ """++ /// Parses the model's reply into a draft (unparseable or "unsure" steps are marked uncertain).+ static func draft(_ reply: String, frames: [URL], folder: URL) -> ReviewDraft {+ var name = "", prompt = "", steps: [DraftStep] = []+ for raw in reply.split(separator: "\n") {+ let line = raw.trimmingCharacters(in: .whitespaces)+ if line.uppercased().hasPrefix("NAME:") { name = String(line.dropFirst(5)).trimmingCharacters(in: .whitespaces) }+ if line.uppercased().hasPrefix("PROMPT:") { prompt = String(line.dropFirst(7)).trimmingCharacters(in: .whitespaces) }+ guard line.uppercased().hasPrefix("STEP"), let colon = line.firstIndex(of: ":") else { continue }+ let n = Int(line[line.index(line.startIndex, offsetBy: 4)..<colon].trimmingCharacters(in: .whitespaces)) ?? 1+ let parts = line[line.index(after: colon)...].split(separator: "|", maxSplits: 1)+ let command = parts.first.map(String.init) ?? ""+ let sure = parts.count > 1 && parts[1].lowercased().contains("unsure") == false+ let action = (try? Actions.parseCommand(command)) ?? ["action": .str("note"), "text": .str(command)]+ steps.append(DraftStep(action: action, frame: frames[max(0, min(frames.count - 1, n - 1))],+ uncertain: !sure || action["action"]?.str == "note"))+ }+ return ReviewDraft(source: .recording, folder: folder, runID: nil, outcome: nil, steps: steps, name: name,+ prompt: prompt, icon: "record.circle")+ }++ private static func mockReply() async throws -> String {+ try await Task.sleep(nanoseconds: 1_500_000_000)+ return """+ NAME: Daily 7 AM alarm+ PROMPT: Open Clock, add an alarm for 7:00 AM that repeats every day, then save it+ STEP 1: tap 500 814 | sure+ STEP 2: type "Clock" | sure+ STEP 3: tap 152 212 | sure+ STEP 4: tap 905 88 | unsure+ STEP 5: swipe 397 300 397 200 | unsure+ STEP 6: tap 150 395 | sure+ """+ }+}diff --git a/ios/IPhoneAgent/App/HotspotJoin.swift b/ios/IPhoneAgent/App/HotspotJoin.swiftnew file mode 100644index 0000000..95d05a6--- /dev/null+++ b/ios/IPhoneAgent/App/HotspotJoin.swift@@ -0,0 +1,103 @@+import Foundation+import NetworkExtension++/// Joining the board's Wi-Fi: idle → joining (the system prompt) → verifying (≤ 10 s) → joined, or+/// failed(reason) with Try Again and the manual fallback. A new start cancels the old task, so a re-tap+/// always restarts cleanly and the spinner never sticks.+enum JoinState: Equatable {+ case idle, joining, verifying, joined+ case failed(String)++ var busy: Bool { self == .joining || self == .verifying }+}++extension AppModel {+ /// Start (or restart) the join. `auto`: the page appeared; skipped once it was tried or is done.+ func startJoin(auto: Bool = false) {+ if auto && join != .idle { return }+ joinTask?.cancel()+ joinTask = Task { [weak self] in await self?.runJoin() }+ }++ private func runJoin() async {+ if MockMode.on {+ join = .joining+ try? await Task.sleep(nanoseconds: 800_000_000)+ hotspotSSID = board.net?.ssid ?? "ESP32Agent-7C3E"+ join = .joined+ return mockStartMirroring()+ }+ join = .joining+ let net: NetConfig+ do { net = try await board.readNet() } catch {+ say("hotspot: could not read the board's Wi-Fi: \(error.localizedDescription)")+ join = .failed(String(localized: "Couldn't read the board's Wi-Fi. Is the board connected?"))+ return+ }+ guard !Task.isCancelled else { return }+ let ssid = net.ssid ?? "?"+ if await onBoardWiFi(ssid) { // already there: iOS would show no prompt+ say("hotspot: already on \(ssid)")+ return joined(ssid)+ }+ say("hotspot: NEHotspotConfigurationManager.apply(\(ssid), password \(net.pass?.count ?? 0) chars, joinOnce false)")+ let started = now()+ do {+ try await Hotspot.join(net)+ say(String(format: "hotspot: apply → ok after %.1f s", now() - started))+ } catch let e as NSError {+ say(String(format: "hotspot: apply → %@ after %.1f s", Hotspot.describe(e), now() - started))+ guard !Task.isCancelled else { return }+ if Hotspot.userDenied(e) {+ join = .failed(String(localized: "Join was cancelled."))+ } else {+ manualHotspot = net+ join = .failed(String(localized: "iOS couldn't join automatically. Join by hand with the password below."))+ }+ return+ }+ // apply() can succeed (or show no prompt) without the phone really joining: confirm for up to 10 s.+ join = .verifying+ for _ in 0..<20 {+ guard !Task.isCancelled else { return }+ if await onBoardWiFi(ssid) { return joined(ssid) }+ try? await Task.sleep(nanoseconds: 500_000_000)+ }+ let current = await Hotspot.currentSSID()+ say("hotspot: applied, but after 10 s the phone is on \(current ?? "no readable network"), not \(ssid)")+ manualHotspot = net+ join = .failed(String(localized: "The iPhone didn't switch to the board's Wi-Fi. Join by hand with the password below."))+ }++ private func joined(_ ssid: String) {+ manualHotspot = nil+ hotspotSSID = ssid+ join = .joined+ say("hotspot: joined \(ssid)")+ }++ /// On the board's network: the current SSID matches, or the board counts a client.+ private func onBoardWiFi(_ ssid: String) async -> Bool {+ if await Hotspot.currentSSID() == ssid { return true }+ return board.connected && (board.status?.sta ?? 0) > 0+ }++ /// Poll while the See page is up (and when the app comes back): the user may have joined in Settings.+ func refreshHotspot() async {+ guard !MockMode.on else { return }+ let current = await Hotspot.currentSSID()+ let ours = board.net?.ssid+ let on = current != nil && (current == ours || (ours == nil && (current?.hasPrefix("ESP32Agent") == true || current?.hasPrefix("iPhoneAgent") == true)))+ let other = on ? nil : current+ if otherWiFi != other { otherWiFi = other }+ if on, hotspotSSID != current {+ hotspotSSID = current+ if !join.busy { join = .joined }+ DebugLog.write("hotspot: detected on \(current ?? "")")+ } else if !on, current != nil, hotspotSSID != nil || join == .joined {+ hotspotSSID = nil // on another network: not joined, whatever was true before+ if join == .joined { join = .idle }+ DebugLog.write("hotspot: on another network, not the board's")+ }+ }+}diff --git a/ios/IPhoneAgent/App/IPhoneAgentApp.swift b/ios/IPhoneAgent/App/IPhoneAgentApp.swiftnew file mode 100644index 0000000..9944359--- /dev/null+++ b/ios/IPhoneAgent/App/IPhoneAgentApp.swift@@ -0,0 +1,74 @@+import SwiftUI++@main+struct IPhoneAgentApp: App {+ @StateObject private var app = AppModel.shared++ init() { _ = AppModel.shared } // also on a background launch for an App Intent, which shows no scene++ var body: some Scene {+ WindowGroup {+ RootView(app: app, settings: app.settings)+ }+ }+}++enum AppTab: Hashable { case agent, runs, settings }++/// The setup screens; Home's status chips open the one that fixes a problem.+enum SetupPage: Int, CaseIterable, Identifiable {+ case welcome, connect, see, act, brain+ var id: Int { rawValue }+}++struct RootView: View {+ @ObservedObject var app: AppModel+ @ObservedObject var settings: Settings+ @AppStorage(RunShare.askedKey) private var privacyAsked = false+ @State private var consent = false++ var body: some View {+ TabView(selection: $app.tab) {+ HomeView(app: app, board: app.board, feed: app.feed, agent: app.agent, settings: settings,+ intents: app.intents, recorder: app.recorder)+ .tabItem { Label("Agent", systemImage: "face.smiling") }+ .tag(AppTab.agent)+ RunsView(app: app, runs: app.runs, agent: app.agent)+ .tabItem { Label("Runs", systemImage: "play.rectangle.on.rectangle") }+ .tag(AppTab.runs)+ SettingsView(app: app, settings: settings, board: app.board)+ .tabItem { Label("Settings", systemImage: "gearshape") }+ .tag(AppTab.settings)+ }+ .fullScreenCover(item: $app.review) { draft in ReviewView(draft: draft, app: app) }+ .background {+ Color.clear.fullScreenCover(item: $app.setupPage) { page in+ OnboardingView(app: app, board: app.board, feed: app.feed, settings: settings, calibrator: app.calibrator,+ pointer: app.pointer, start: page)+ .id(page) // a fresh setup (its own page state) for every start page, e.g. "Run setup again"+ }+ }+ .background { Color.clear.sheet(isPresented: $consent, onDismiss: setUp) { ConsentSheet() } }+ .onAppear {+ if privacyAsked { setUp() } else { consent = true } // what is kept, before setup+ app.probe.install(CalibrationOverlay(calibrator: app.calibrator, probe: app.probe, pointer: app.pointer))+ }+ .onOpenURL { url in+ if url.isFileURL && url.pathExtension.lowercased() == "zip" { // a shared run archive+ do { try app.importRuns(url) } catch { app.say("import: \(error.localizedDescription)") }+ return+ }+ if app.handleDebug(url) { return } // iphoneagent://run?task=…, calibrate, stop, bench, snap+ // iphoneagent://run/<id> from the Live Activity+ guard url.scheme == "iphoneagent", url.host == "run" else { return }+ let id = url.lastPathComponent+ if id.hasPrefix("rec-") { return } // a recording: its draft opens by itself+ if app.agent.running { app.tab = .agent } else { app.openReview(run: id) }+ }+ }++ private func setUp() {+ privacyAsked = true+ if !settings.onboarded && app.setupPage == nil { app.setupPage = .welcome }+ }+}diff --git a/ios/IPhoneAgent/App/IntentBridge.swift b/ios/IPhoneAgent/App/IntentBridge.swiftnew file mode 100644index 0000000..87fd7e9--- /dev/null+++ b/ios/IPhoneAgent/App/IntentBridge.swift@@ -0,0 +1,99 @@+import AppIntents+import Foundation+import WidgetKit++/// Siri, Shortcuts, widgets and controls → the app; and the app's state → the widgets (App Group snapshot).+extension AppModel {+ func handle(_ request: AgentRequest) async -> String {+ DebugLog.write("intent: \(request)")+ switch request {+ case .runTask(let task):+ return await runFromIntent(task, intent: nil)+ case .runSaved(let id):+ let saved = id.flatMap { intents.item($0) } ?? intents.item(widgetSnapshot?.lastIntent) ?? intents.items.first+ guard let saved else { return String(localized: "There are no saved intents yet.") }+ return await runFromIntent(saved.prompt, intent: saved)+ case .status:+ return statusLines.joined(separator: "\n")+ case .calibrate:+ guard MockMode.on || board.connected else { return String(localized: "The board isn't connected.") }+ calibrator.calibrate()+ return String(localized: "Calibrating the pointer…")+ }+ }++ /// Checks what a run needs before starting it from outside the app (no screen to fix things on).+ private func runFromIntent(_ task: String, intent: SavedTask?) async -> String {+ let task = task.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !task.isEmpty else { return String(localized: "The task is empty.") }+ if agent.running { return String(localized: "Already running: \(agent.task)") }+ if !MockMode.on {+ guard settings.isConfigured else { return String(localized: "Set up the model in Settings first.") }+ guard pointer.calibrated else { return String(localized: "Calibrate the pointer in ESP32 Agent first.") }+ guard await waitReady(mirroring: true, timeout: 20) else {+ return String(localized: "The board or Screen Mirroring isn't ready. Connect the board and start Screen Mirroring.")+ }+ }+ await run(task, intent: intent)+ publishWidget()+ if agent.running { return String(localized: "Started: \(task)") }+ return String(localized: "Could not start: \(log.last?.text ?? "")")+ }++ /// Board, mirroring, calibration, model and run, for Siri and the status snippet.+ var statusLines: [String] {+ let s = board.status+ var lines: [String] = []+ if MockMode.on { lines.append(String(localized: "Demo data is on.")) }+ lines.append(board.connected ? String(localized: "Board connected") : String(localized: "Board not connected"))+ lines.append(feed.live || s?.ap == "streaming" ? String(localized: "Screen Mirroring on")+ : String(localized: "Screen Mirroring off"))+ if pointer.calibrated {+ lines.append(pointer.quality.map { String(localized: "Calibrated, \(CalibrationText.percent($0))") }+ ?? String(localized: "Calibrated"))+ } else {+ lines.append(String(localized: "Not calibrated"))+ }+ lines.append(settings.isConfigured || MockMode.on+ ? String(localized: "Model: \(MockMode.on ? "Demo" : settings.currentModel ?? String(localized: "Automatic"))")+ : String(localized: "Model not set up"))+ lines.append(agent.running ? String(localized: "Running step \(moveCount): \(agent.task)") : String(localized: "Not running"))+ return lines+ }++ var widgetSnapshot: AgentSnapshot? { SharedState.load() }++ /// Writes the snapshot when it changed and reloads the widgets: at once for a new state, at most every+ /// 30 s for a step count alone (background reloads are budgeted).+ func publishWidget() {+ var snap = AgentSnapshot(status: .ready)+ if agent.running {+ snap.status = .running+ } else if !modelReady || !(MockMode.on || pointer.calibrated) || (!MockMode.on && board.pairedID == nil) {+ snap.status = .needsSetup+ } else if !MockMode.on && !board.connected {+ snap.status = .offline+ }+ snap.step = agent.running ? moveCount : 0+ snap.task = agent.running ? agent.task : ""+ snap.intents = intents.items.map { .init(id: $0.id, name: $0.name, prompt: $0.prompt, symbol: $0.symbol) }+ let old = widgetSnapshot+ snap.lastIntent = currentIntent?.id ?? old?.lastIntent+ if !agent.running, let last = runs.runs.first(where: { !$0.id.hasPrefix("rec-") }), let step = last.steps.last {+ snap.lastRun = .init(task: last.task, ok: last.outcome == .done,+ line: step.action["answer"]?.str ?? step.action["reason"]?.str ?? "", date: last.date)+ } else {+ snap.lastRun = old?.lastRun+ }+ snap.demo = MockMode.on+ guard snap != old else { return }+ var quiet = old ?? snap+ quiet.step = snap.step+ let stepOnly = old != nil && quiet == snap+ if stepOnly && now() - lastWidgetReload < 30 { return }+ SharedState.save(snap)+ lastWidgetReload = now()+ WidgetCenter.shared.reloadAllTimelines()+ if old?.intents != snap.intents { AgentShortcuts.updateAppShortcutParameters() }+ }+}diff --git a/ios/IPhoneAgent/App/IslandStatus.swift b/ios/IPhoneAgent/App/IslandStatus.swiftnew file mode 100644index 0000000..801e7e2--- /dev/null+++ b/ios/IPhoneAgent/App/IslandStatus.swift@@ -0,0 +1,100 @@+import Foundation++/// What the character says in the Dynamic Island, first person: "Thinking…", "Tapping Clock", "Typing 0800",+/// "Done!". `short` fits the compact island (≤ ~16 characters), `full` is for the expanded island and the+/// Lock Screen. `look` is where the eyes go (-1...1 from the center, e.g. toward a tap); nil while it waits,+/// when the eyes dart around on their own.+struct IslandStatus: Equatable {+ var short: String+ var full: String+ var look: CGPoint?++ var waits: Bool { look == nil }++ static let compactLimit = 16++ static var looking: Self {+ Self(short: String(localized: "Looking…"), full: String(localized: "Looking at the screen…"), look: nil)+ }++ static var thinking: Self {+ Self(short: String(localized: "Thinking…"), full: String(localized: "Thinking…"), look: nil)+ }++ static var help: Self {+ Self(short: String(localized: "Need help"), full: String(localized: "Need your help"), look: .zero)+ }++ static var yourTurn: Self {+ Self(short: String(localized: "Your turn"), full: String(localized: "Your turn"), look: CGPoint(x: 0, y: 0.6))+ }++ /// The end of a run, from its outcome's mood.+ static func ended(_ mood: Mood) -> Self {+ switch mood {+ case .success: return Self(short: String(localized: "Done!"), full: String(localized: "Done!"), look: .zero)+ case .failure: return Self(short: String(localized: "Didn't finish"), full: String(localized: "Didn't finish"), look: .zero)+ default: return Self(short: String(localized: "Stopped"), full: String(localized: "Stopped"), look: .zero)+ }+ }++ /// About to do `act` (its thought, if any, names the target: "… so I tap the Clock app").+ static func acting(_ act: JObject) -> Self {+ let look = gaze(act)+ func say(_ verb: (String) -> String, _ bare: String, _ what: String?) -> Self {+ guard let what, !what.isEmpty else { return Self(short: bare, full: bare, look: look) }+ let room = compactLimit - verb("").count+ return Self(short: verb(clip(what, room)), full: verb(clip(what, 28)), look: look)+ }+ switch act["action"]?.str {+ case "tap":+ return say({ String(localized: "Tapping \($0)") }, String(localized: "Tapping…"), target(act["thought"]?.str ?? ""))+ case "type":+ return say({ String(localized: "Typing \($0)") }, String(localized: "Typing…"), act["text"]?.str)+ case "key":+ return say({ String(localized: "Pressing \($0)") }, String(localized: "Pressing a key…"), act["combo"]?.str)+ case "swipe":+ return Self(short: String(localized: "Swiping…"), full: String(localized: "Swiping…"), look: look)+ case "path", "circle":+ return Self(short: String(localized: "Drawing…"), full: String(localized: "Drawing…"), look: look)+ case "home":+ return Self(short: String(localized: "Going home"), full: String(localized: "Going to the Home Screen"), look: look)+ case "back":+ return Self(short: String(localized: "Going back"), full: String(localized: "Going back"), look: look)+ default:+ return Self(short: String(localized: "Waiting…"), full: String(localized: "Waiting…"), look: look)+ }+ }++ /// Where the pointer is going, relative to the screen center; typing looks down at the keyboard.+ static func gaze(_ act: JObject) -> CGPoint {+ if ["type", "key"].contains(act["action"]?.str ?? "") { return CGPoint(x: 0, y: 0.7) }+ guard let p = pointerPath(act).last else { return .zero }+ func clamp(_ v: Double) -> Double { min(1, max(-1, (v - 0.5) * 2)) }+ return CGPoint(x: clamp(p.x), y: clamp(p.y))+ }++ /// The thing a thought says it taps: a quoted name ("Save", “Repeat”), else the words after the last+ /// "tap / open / press / select …" ("so I tap the Clock app" → "Clock"). Nil for "it", "here" and the like.+ static func target(_ thought: String) -> String? {+ if let quoted = lastMatch(#"[“"‘]([^“”"‘’]{1,24})[”"’]"#, in: thought) { return quoted }+ let verb = #"\b(?:tap|tapping|open|opening|press|select|choose|hit)\s+(?:on\s+)?(?:the\s+)?"#+ let stop = #"(?=\s+(?:app|icon|button|tab|field|row|toggle|option|pill|key|link|result|to|so|and|in|at|on|again)\b|[.,;:!]|$)"#+ guard let name = lastMatch(verb + #"([^.,;:!]{1,24}?)"# + stop, in: thought, options: .caseInsensitive) else { return nil }+ let pronouns: Set<String> = ["it", "this", "that", "them", "here", "there", "one", "a", "an"]+ return pronouns.contains(name.lowercased()) ? nil : name+ }++ private static func clip(_ s: String, _ n: Int) -> String {+ let s = s.trimmingCharacters(in: .whitespacesAndNewlines)+ return s.count <= n ? s : String(s.prefix(max(1, n - 1))) + "…"+ }++ private static func lastMatch(_ pattern: String, in s: String, options: NSRegularExpression.Options = []) -> String? {+ guard let re = try? NSRegularExpression(pattern: pattern, options: options) else { return nil }+ let ns = s as NSString+ guard let m = re.matches(in: s, range: NSRange(location: 0, length: ns.length)).last else { return nil }+ let found = ns.substring(with: m.range(at: 1)).trimmingCharacters(in: .whitespaces)+ return found.isEmpty ? nil : found+ }+}diff --git a/ios/IPhoneAgent/App/LiveActivity.swift b/ios/IPhoneAgent/App/LiveActivity.swiftnew file mode 100644index 0000000..5eb422c--- /dev/null+++ b/ios/IPhoneAgent/App/LiveActivity.swift@@ -0,0 +1,154 @@+import ActivityKit+import Foundation++/// Starts, updates and ends the Live Activity of a run or a recording. While the agent works the app is in+/// the background, so this is the user's view of the run; the app updates it whenever BLE wakes it.+///+/// The island's eyes: Live Activity views cannot run their own animations, but a change between two updates+/// animates (the widget springs `look`). So while the agent waits for a frame or the model, a loop here sends a+/// new random gaze every 1.4-2.2 s (the eyes dart), and before a gesture the gaze points at its target.+/// Updates go through a token bucket (burst 2, then 1 per second), so the system never sees more than ~1/s.+@MainActor final class LiveActivityController {+ typealias State = AgentActivityAttributes.ContentState+ private var activity: Activity<AgentActivityAttributes>?+ private var last: State? // the newest state (sent or waiting for a token)+ private var sent: State?+ private var tokens = 2.0, refilled = 0.0+ private var flush: Task<Void, Never>?+ private var darting: Task<Void, Never>?++ func start(task: String, runID: String, limit: Int, phase: AgentActivityAttributes.Phase = .running) {+ end(nil)+ guard ActivityAuthorizationInfo().areActivitiesEnabled else { return DebugLog.write("Live Activity: disabled in Settings") }+ let line = phase == .recording ? String(localized: "Do the task yourself. I'm watching.")+ : String(localized: "Reading the screen…")+ let status = phase == .recording+ ? IslandStatus(short: String(localized: "Watching you"), full: String(localized: "Watching you"), look: CGPoint(x: 0, y: 0.6))+ : IslandStatus.looking+ var state = State(mood: phase == .recording ? .listening : .thinking, step: 0, limit: limit, line: line,+ phase: phase, since: Date())+ apply(status, to: &state)+ do {+ activity = try Activity.request(attributes: AgentActivityAttributes(task: task, runID: runID, name: Settings.storedAgentName),+ content: .init(state: state, staleDate: nil))+ last = state+ sent = state+ tokens = 1+ refilled = now()+ DebugLog.write("Live Activity: started (\(phase.rawValue)) run \(runID)")+ if status.waits { startDarting() }+ } catch {+ activity = nil+ DebugLog.write("Live Activity: start failed: \(error.localizedDescription)")+ }+ }++ /// Step counter, the model's words, the mood; `status` also changes what the character says and where it looks.+ func update(mood: Mood, step: Int, line: String, phase: AgentActivityAttributes.Phase? = nil, status: IslandStatus? = nil) {+ guard var state = last else { return }+ state.mood = mood+ state.step = step+ state.line = line+ if let phase { state.phase = phase }+ if let status { apply(status, to: &state) }+ push(state)+ }++ /// What the character is doing now: looking / thinking (the eyes dart) or a gesture (the eyes go to its target).+ func show(_ status: IslandStatus, mood: Mood? = nil) {+ guard var state = last, !state.finished else { return }+ apply(status, to: &state)+ if let mood { state.mood = mood }+ push(state)+ }++ /// Shows the outcome for a while, then the system removes it. Tapping it opens the review.+ func end(_ outcome: (mood: Mood, line: String)?) {+ stopDarting()+ flush?.cancel()+ flush = nil+ guard let activity else { return }+ var state = last ?? State(mood: .idle, step: 0, limit: 0, line: "")+ if let outcome {+ state.mood = outcome.mood+ state.line = outcome.line+ if state.phase != .recording { apply(.ended(outcome.mood), to: &state) }+ }+ state.finished = true+ DebugLog.write("Live Activity: ended" + (outcome.map { " (\($0.mood.rawValue))" } ?? ""))+ self.activity = nil+ last = nil+ sent = nil+ Task {+ await activity.end(.init(state: state, staleDate: nil),+ dismissalPolicy: outcome == nil ? .immediate : .after(.now + 15 * 60))+ }+ }++ // MARK: - status and eyes++ private func apply(_ status: IslandStatus, to state: inout State) {+ state.label = status.short+ state.labelFull = status.full+ if let look = status.look {+ state.lookX = look.x+ state.lookY = look.y+ }+ if status.waits { startDarting() } else { stopDarting() }+ }++ /// While waiting: glance somewhere else every 1.4-2.2 s, mostly sideways, never twice at the same spot.+ private func startDarting() {+ guard darting == nil else { return }+ darting = Task { [weak self] in+ while !Task.isCancelled {+ try? await Task.sleep(nanoseconds: UInt64.random(in: 1_400_000_000...2_200_000_000))+ guard !Task.isCancelled, let self, var state = self.last, !state.finished else { return }+ var x = state.lookX+ while abs(x - state.lookX) < 0.5 { x = [-0.9, -0.55, 0, 0.55, 0.9].randomElement()! }+ state.lookX = x+ state.lookY = Double.random(in: -0.35...0.15)+ self.push(state)+ }+ }+ }++ private func stopDarting() {+ darting?.cancel()+ darting = nil+ }++ // MARK: - rate limit++ /// Sends now if a token is left, else once one refills (the newest state wins).+ private func push(_ state: State) {+ guard activity != nil, state != last || state != sent else { return }+ last = state+ guard flush == nil else { return } // a send is already scheduled; it picks up `last`+ refill()+ if tokens >= 1 { return send() }+ let wait = (1 - tokens) * Self.perSecond+ flush = Task { [weak self] in+ try? await Task.sleep(nanoseconds: UInt64(wait * 1_000_000_000))+ guard !Task.isCancelled, let self else { return }+ self.flush = nil+ self.refill()+ self.send()+ }+ }++ private static let perSecond = 1.0, burst = 2.0++ private func refill() {+ let t = now()+ tokens = min(Self.burst, tokens + (t - refilled) / Self.perSecond)+ refilled = t+ }++ private func send() {+ guard let activity, let state = last, state != sent else { return }+ tokens -= 1+ sent = state+ Task { await activity.update(.init(state: state, staleDate: nil)) }+ }+}diff --git a/ios/IPhoneAgent/App/RunRecovery.swift b/ios/IPhoneAgent/App/RunRecovery.swiftnew file mode 100644index 0000000..5d3d0c6--- /dev/null+++ b/ios/IPhoneAgent/App/RunRecovery.swift@@ -0,0 +1,61 @@+import Foundation++/// Self-healing runs: a lost board, hotspot or mirroring pauses the run (AgentLoop.waitForScreen); this side+/// reports each stage (log, Live Activity, in-app banner, a notification when the user has to act) and+/// restores the board's state once the screen is live again.+extension AppModel {++ func wireRecovery() {+ agent.link = { [unowned self] in+ Recovery.Link(connected: board.connected, sta: board.status?.sta, ap: board.status?.ap,+ frameAt: FrameMode.current == .snap ? now() : feed.updated) // snap mode: restore snaps a fresh one+ }+ agent.onRecover = { [weak self] stage in self?.recover(stage) }+ agent.restore = { [weak self] in try await self?.restoreRun() }+ }++ func recover(_ stage: Recovery.Stage?) {+ let was = recovering+ recovering = stage+ guard let stage else {+ notifier.clearLinkAsks()+ runMood = .thinking+ return+ }+ if was == nil { recoverySince = Date() }+ if stage.part != .board, was == nil || was?.part == .board, let up = board.status?.up, up < 60_000 {+ DebugLog.write("recover: board rebooted \(up / 1000) s ago (reset: \(board.status?.rst ?? "?"))")+ }+ DebugLog.write("recover: \(stage.logLine)")+ runMood = .listening+ live.update(mood: .listening, step: moveCount, line: stage.line, phase: .running, status: stage.status)+ if stage.ask { notifier.post(kind(stage.part), title: title(stage.part), body: stage.line, run: runID) }+ }++ /// Live again: the board may have rebooted (stream off, button state unknown) and the screen moved on.+ func restoreRun() async throws {+ DebugLog.write(String(format: "recover: live again after %.0f s", Date().timeIntervalSince(recoverySince)))+ if FrameMode.current == .stream && !feed.streamOn { try await feed.stream(true) }+ DebugLog.write("recover: fresh frame (" + (try await feed.currentFrame()) + ")")+ try await pointer.reset() // a gesture cut off mid-way may have left the button down+ DebugLog.write("recover: button released, pointer re-homed; going on from step \(moveCount)")+ live.update(mood: .thinking, step: moveCount, line: String(localized: "Back online. Going on from here…"),+ phase: .running, status: .looking)+ }++ private func kind(_ part: Recovery.Part) -> Notifier.Kind {+ switch part {+ case .board: return .board+ case .hotspot: return .wifi+ case .mirroring: return .mirroring+ }+ }++ private func title(_ part: Recovery.Part) -> String {+ switch part {+ case .board: return String(localized: "Board disconnected")+ case .hotspot: return String(localized: "iPhone left the board's Wi-Fi")+ case .mirroring: return String(localized: "Start Screen Mirroring to continue")+ }+ }+}diff --git a/ios/IPhoneAgent/App/RunSession.swift b/ios/IPhoneAgent/App/RunSession.swiftnew file mode 100644index 0000000..f57fe85--- /dev/null+++ b/ios/IPhoneAgent/App/RunSession.swift@@ -0,0 +1,300 @@+import Combine+import Foundation+import UIKit++/// Working mode: Start → the character takes off → the phone goes to the Home Screen and the agent runs, with+/// the Live Activity as its UI, a low-fps video of the mirror stream, "needs your help" pauses, notifications,+/// and the review editor at the end.+extension AppModel {++ var moveCount: Int { agent.steps.filter { !StepText.notMoves.contains($0["action"]?.str ?? "") }.count }+ var runID: String { traces.dir?.lastPathComponent ?? "" }++ /// Start a task (or a saved intent: its checklist goes to the actor as hints).+ func run(_ task: String, intent: SavedTask? = nil) async {+ guard !agent.running, !recorder.recording else { return }+ currentIntent = intent+ lastTask = task+ agent.hints = intent?.checklist ?? []+ departing = true+ try? await Task.sleep(nanoseconds: 800_000_000) // "See you later" (DepartureOverlay)+ departing = false+ await startAgent(task)+ }++ func startAgent(_ task: String) async {+ if MockMode.on { return mockRun(task) }+ guard settings.isConfigured else {+ say(String(localized: "Set up the model in Settings first."))+ return+ }+ guard await calibrator.ensureCalibrated() else {+ say(String(localized: "The pointer isn't calibrated yet."))+ return+ }+ do {+ agent.actor = try await settings.client("actor")+ agent.planner = try await settings.client("planner")+ } catch {+ say("LLM: \(error.localizedDescription)")+ return+ }+ // Start is tapped in this app, so: Live Activity, go Home, let the screen settle, THEN the first+ // frame for the planner. Each sub-step is timed in the log.+ let t0 = now()+ func mark(_ what: String) { DebugLog.write(String(format: "start: %@ (+%.0f ms)", what, (now() - t0) * 1000)) }+ traces.start(task: task) // the run folder exists from here: a failed start keeps its log and video+ startVideo()+ FrameMode.fallback = nil // each run starts in the chosen mode+ let snapMode = FrameMode.current == .snap+ do {+ if snapMode {+ if feed.streamOn { try await feed.stream(false) }+ mark("snap-per-step mode (stream off)")+ } else {+ try await feed.stream(true) // the agent waits for the screen to settle: it needs every change+ mark("stream on")+ }+ backgroundTask = UIApplication.shared.beginBackgroundTask(withName: "agent") { [weak self] in+ self?.say("iOS is ending background time; BLE status keeps the run going")+ self?.endBackgroundTask()+ }+ live.start(task: task, runID: runID, limit: agent.maxSteps)+ mark("Live Activity started")+ let left = now()+ var away = await leaveApp()+ if !away { away = await askUserToLeave() }+ guard away else { // never let the agent start on its own app+ throw DeviceError(message: String(localized: "ESP32 Agent is still on screen"))+ }+ mark("app in background")+ if !snapMode {+ let changed = await feed.fresh(since: left, timeout: 3) != nil+ await feed.settled()+ mark(changed ? "screen changed and settled" : "no screen change seen in 3 s; settled")+ }+ mark("first frame: " + (try await feed.currentFrame()))+ try agent.start(task, traceStarted: true)+ mark("agent started")+ say("started: \(task)")+ began(task, early: true)+ } catch {+ say("cannot start: \(error.localizedDescription)")+ traces.write(feed.frame, kind: "step", ["action": .str("error"),+ "reason": .str("cannot start: \(error.localizedDescription)")])+ videoSink = nil+ saveVideoFrame(feed.frame)+ videoDir = nil+ live.end((.failure, String(localized: "Could not start")))+ endBackgroundTask()+ runs.reload()+ }+ }++ /// Emergency stop: cancel the agent and release the mouse button.+ func stopAgent() async {+ answerHelp(.stop)+ mockJob?.cancel()+ agent.stop()+ try? await Task.sleep(nanoseconds: 100_000_000) // let a gesture in flight finish its own release+ if board.connected && !MockMode.on {+ do { try await pointer.reset() } catch { say("release failed: \(error.localizedDescription)") }+ }+ }++ /// A run began: the character thinks, the Live Activity appears, the video starts.+ /// early: the Live Activity and the video were started before the agent (a real run's start sequence).+ func began(_ task: String, early: Bool = false) {+ moodReset?.cancel()+ runMood = .thinking+ runStarted = Date()+ if !early {+ live.start(task: task, runID: runID, limit: agent.maxSteps)+ if !MockMode.on { startVideo() } // always: the review needs it, even for a run that stops at once+ }+ runs.reload()+ }++ /// After each recorded step: a short "acting" hop, then back to thinking while the model looks again.+ func stepped() {+ runs.reload()+ guard agent.running, let last = agent.steps.last, help == nil else { return }+ let moved = !StepText.notMoves.contains(last["action"]?.str ?? "")+ runMood = moved ? .acting : .thinking+ live.update(mood: runMood ?? .thinking, step: moveCount, line: StepText.line(last), phase: .running)+ if moved {+ moodReset?.cancel()+ moodReset = Task { [weak self] in+ try? await Task.sleep(nanoseconds: 700_000_000)+ guard !Task.isCancelled, self?.agent.running == true, self?.help == nil else { return }+ self?.runMood = .thinking+ }+ }+ }++ /// Between steps: what the character says in the Dynamic Island and where its eyes go.+ func doing(_ d: AgentLoop.Doing) {+ guard agent.running, help == nil else { return }+ switch d {+ case .looking: live.show(.looking, mood: .thinking)+ case .thinking: live.show(.thinking, mood: .thinking)+ case .acting(let act): live.show(.acting(act), mood: .acting)+ }+ }++ /// The run ended: outcome on the character, Live Activity and a notification; then the review opens.+ func ended() {+ videoSink = nil+ saveVideoFrame(feed.frame) // the last screen too, however the run ended+ videoDir = nil+ help = nil+ takingOver = false+ recovering = nil+ notifier.clearHelp()+ notifier.clearLinkAsks()+ let last = agent.steps.last+ let outcome = Outcome(last: last?["action"]?.str, running: false)+ let seconds = Date().timeIntervalSince(runStarted)+ runMood = outcome.mood+ live.end((outcome.mood, last.map(StepText.line) ?? ""))+ runs.reload()+ let summary = String(localized: "\(moveCount) steps · \(seconds.durationText)")+ switch outcome {+ case .done:+ Haptics.success()+ let answer = last?["answer"]?.str ?? agent.task+ notifier.post(.done, title: String(localized: "Done: \(answer)"), body: summary, run: runID)+ case .failed:+ let why = last?["reason"]?.str ?? ""+ notifier.post(.failed, title: String(localized: "Not finished: \(why)"), body: summary, run: runID)+ default: break+ }+ if let intent = currentIntent {+ intents.record(intent.id, RunStat(run: runID, ok: outcome == .done, seconds: seconds))+ }+ if outcome != .stopped || UIApplication.shared.applicationState == .active { openReview(run: runID) }+ moodReset?.cancel()+ moodReset = Task { [weak self] in+ try? await Task.sleep(nanoseconds: 5_000_000_000)+ guard !Task.isCancelled, self?.agent.running == false else { return }+ self?.runMood = nil+ }+ }++ func agentFinished() {+ ended()+ if let last = agent.steps.last { say("finished: \(last["action"]?.str ?? "") \(last["reason"]?.str ?? last["answer"]?.str ?? "")") }+ Task { try? await feed.stream(false) }+ endBackgroundTask()+ }++ func endBackgroundTask() {+ if backgroundTask != .invalid { UIApplication.shared.endBackgroundTask(backgroundTask) }+ backgroundTask = .invalid+ }++ // MARK: - review++ /// Opens the review editor for a run (with its intent, if it ran one).+ func openReview(run id: String) {+ runs.reload()+ guard let run = runs.run(id) else { return }+ let intent = intents.items.first { $0.refRun == id || $0.runs.contains { $0.run == id } }+ review = ReviewDraft(run: run, intent: intent)+ }++ /// The model rewrites the prompt and checklist from the trace and the user's corrections.+ func optimize(_ draft: ReviewDraft) async throws -> (prompt: String, hints: [String]) {+ if MockMode.on {+ try await Task.sleep(nanoseconds: 1_400_000_000)+ return (String(localized: "Open Clock › Alarms, tap +, type 0700 for the time, set Repeat to every day, then tap Save"),+ [String(localized: "Type the time instead of scrolling the wheel"),+ String(localized: "The + button is at the top right of Alarms"),+ String(localized: "Check all seven days under Repeat, then tap Back")])+ }+ let reply = try await settings.client("planner").chat(system: ReviewDraft.optimizerPrompt,+ text: draft.optimizerInput(), image: nil,+ maxTokens: 800, temperature: 0.2)+ guard let result = ReviewDraft.parseOptimized(reply.text) else {+ throw LLMError(message: String(localized: "The model gave no improved prompt."))+ }+ return result+ }++ // MARK: - needs your help++ /// The agent is stuck: pause, tell the user (Live Activity + notification) and wait for their choice.+ func needsHelp(_ reason: String) async -> AgentLoop.HelpChoice {+ help = reason.isEmpty ? String(localized: "I'm stuck on this step.") : reason+ runMood = .failure+ let line = String(localized: "Needs your help: \(help ?? "")")+ live.update(mood: .failure, step: moveCount, line: line, phase: .help, status: .help)+ notifier.post(.help, title: String(localized: "Needs your help"), body: help ?? "", run: runID)+ return await withCheckedContinuation { helpWait = $0 }+ }++ func answerHelp(_ choice: AgentLoop.HelpChoice) {+ guard let wait = helpWait else { return }+ resumeAsked = now() // Continue tapped in this app: the run sends it away before looking again+ helpWait = nil+ help = nil+ takingOver = false+ notifier.clearHelp()+ runMood = choice == .stop ? .idle : .thinking+ live.update(mood: runMood ?? .thinking, step: moveCount, line: String(localized: "Going on from here…"), phase: .running,+ status: .looking)+ wait.resume(returning: choice)+ }++ /// The user does the step by hand, then taps Continue.+ func takeOver() {+ guard help != nil else { return }+ takingOver = true+ live.update(mood: .listening, step: moveCount, line: String(localized: "Your turn. Tap Continue when you're done."),+ phase: .help, status: .yourTurn)+ notifier.post(.takeover, title: String(localized: "Your turn"),+ body: String(localized: "Do the step yourself, then tap Continue."), run: runID)+ }++ /// Live Activity buttons.+ func control(_ command: AgentCommand) async {+ switch command {+ case .stop: await stopAgent()+ case .resume: answerHelp(.resume)+ case .skip: answerHelp(.skip)+ case .takeOver: takeOver()+ case .stopRecording: await recorder.stop()+ }+ }++ /// Notification actions; tapping the notification itself opens the review.+ func notificationAction(_ action: Notifier.Action?, run: String) {+ switch action {+ case .stop?: Task { await stopAgent() }+ case .resume?: answerHelp(.resume)+ case .skip?: answerHelp(.skip)+ case .takeOver?: takeOver()+ case .retry?: Task { await self.run(lastTask, intent: currentIntent) }+ case .review?, nil:+ if agent.running { tab = .agent } else if !run.hasPrefix("rec-") && review == nil { openReview(run: run) }+ }+ }++ // MARK: - recording the run++ /// Saves the mirror stream at ~2 fps into the run folder (video/<ms>.jpg), for the review's video view.+ private func startVideo() {+ guard let dir = traces.dir?.appendingPathComponent("video") else { return }+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ videoDir = dir+ videoSink = feed.$frame.compactMap { $0 }+ .throttle(for: .milliseconds(500), scheduler: RunLoop.main, latest: true)+ .sink { [weak self] jpeg in self?.saveVideoFrame(jpeg) }+ }++ /// Each frame is written at once, so a run that stops or fails early still has its video.+ func saveVideoFrame(_ jpeg: Data?) {+ guard let jpeg, let dir = videoDir else { return }+ try? jpeg.write(to: dir.appendingPathComponent("\(Int(Date().timeIntervalSince1970 * 1000)).jpg"))+ }+}diff --git a/ios/IPhoneAgent/App/TouchCalibration.swift b/ios/IPhoneAgent/App/TouchCalibration.swiftnew file mode 100644index 0000000..b2c2e23--- /dev/null+++ b/ios/IPhoneAgent/App/TouchCalibration.swift@@ -0,0 +1,153 @@+import UIKit++/// Touch-probe calibration, like levelling a 3D printer bed: home the pointer, click at known mouse+/// distances and catch where each click lands on this app's own screen. Stage 1 clicks twice on the+/// diagonal for a rough fit; stage 2 clicks near the four corners (25% / 75%) and the centre, all from home,+/// and fits mouse units → screen fraction per axis by least squares; stage 3 taps a check point.+extension AutoCalibrator {+ enum TouchResult { case done(Double), noTaps, failed(String) }++ static let roughStops = [150, 350]+ static let targets: [(Double, Double)] = [(0.25, 0.25), (0.75, 0.25), (0.5, 0.5), (0.25, 0.75), (0.75, 0.75)]+ static let check = (x: 0.5, y: 0.62)+ static let tapTimeout = 3.0++ func touchCalibrate(full: Bool) async throws -> TouchResult {+ let probe = app.probe, device = app.board.commands, pointer = app.pointer+ var total = full ? Self.roughStops.count + Self.targets.count + 1 : 1+ var clicks = 0, hits = 0+ phase = .homing+ try await pointer.reset()++ /// Home, move by (ux, uy), click and wait for the tap. Every probe starts from home, like the agent's moves.+ func click(_ ux: Int, _ uy: Int) async throws -> CGPoint? {+ try await device.send("home")+ try await device.send("move \(ux) \(uy)")+ let sent = now()+ try await device.send("click")+ let p = await probe.tap(since: sent, timeout: Self.tapTimeout)+ clicks += 1+ progress = Progress(done: clicks, total: total)+ if let p {+ hits += 1+ UIImpactFeedbackGenerator(style: .light).impactOccurred()+ app.say(String(format: "probe %d: move %d %d → (%.3f, %.3f) = %.0f, %.0f px", clicks, ux, uy, p.x, p.y,+ p.x * DeviceScreen.size.width * DeviceScreen.scale,+ p.y * DeviceScreen.size.height * DeviceScreen.scale))+ } else {+ app.say("probe \(clicks): move \(ux) \(uy) → no tap within \(Int(Self.tapTimeout)) s")+ }+ return p+ }++ /// A click that never reached the app probably hit the AssistiveTouch button and opened its menu:+ /// remember the spot and close the menu (esc, then a click on an empty area, which the probe swallows).+ func missed(at fx: Double, _ fy: Double, empty: (Int, Int)?) async {+ AssistiveTouchSpots.remember(x: fx, y: fy)+ _ = try? await device.send("key esc")+ if let (ex, ey) = empty {+ _ = try? await device.send("home")+ _ = try? await device.send("move \(ex) \(ey)")+ _ = try? await device.send("click")+ }+ try? await Task.sleep(nanoseconds: 500_000_000)+ }++ if !full { // quick check after a reconnect: one tap at the check point+ phase = .verifying+ guard pointer.calibrated else { return .failed("not calibrated") }+ try await pointer.point(Self.check.x, Self.check.y)+ let sent = now()+ try await device.send("click")+ guard let p = await probe.tap(since: sent, timeout: Self.tapTimeout) else { return .noTaps }+ let error = max(abs(p.x - Self.check.x), abs(p.y - Self.check.y))+ app.say(String(format: "probe check: ±%.1f%%", error * 100))+ if error <= Self.tolerance {+ pointer.setQuality(error)+ return .done(error)+ }+ return try await touchCalibrate(full: true)+ }++ var samples: [(ux: Double, uy: Double, fx: Double, fy: Double)] = []+ func record(_ ux: Int, _ uy: Int, _ p: CGPoint?) {+ if let p { samples.append((Double(ux), Double(uy), p.x, p.y)) }+ }+ func lines() -> (ProbeFit.Line, ProbeFit.Line)? {+ let xs = samples.filter { ProbeFit.usable($0.fx) }.map { ($0.ux, $0.fx) }+ let ys = samples.filter { ProbeFit.usable($0.fy) }.map { ($0.uy, $0.fy) }+ guard let x = ProbeFit.line(xs) ?? xs.first.flatMap(ProbeFit.throughHome),+ let y = ProbeFit.line(ys) ?? ys.first.flatMap(ProbeFit.throughHome) else { return nil }+ return (x, y)+ }++ // stage 1: rough, on the diagonal+ phase = .probeA+ for u in Self.roughStops {+ let p = try await click(u, u)+ if p == nil && hits == 0 { return .noTaps }+ if p == nil { _ = try? await device.send("key esc") } // no fit yet to place the spot or an empty click+ record(u, u, p)+ }+ guard let rough = lines() else { return .failed("probe taps stuck at the screen edge") }++ // stage 2: corners and centre+ phase = .probeB+ let empty = (rough.0.units(for: 0.5), rough.1.units(for: 0.12))+ for (fx, fy) in Self.targets {+ let ux = rough.0.units(for: fx), uy = rough.1.units(for: fy)+ guard ux > 0, uy > 0 else { continue }+ if let p = try await click(ux, uy) { record(ux, uy, p); continue }+ await missed(at: fx, fy, empty: empty)+ // replace the probe with one a little closer to the centre+ let rx = fx + (0.5 - fx) * 0.4, ry = fy + (0.5 - fy) * 0.4+ guard rx != fx || ry != fy else { continue }+ let vx = rough.0.units(for: rx), vy = rough.1.units(for: ry)+ total += 1+ app.say(String(format: "probe replaced: (%.2f, %.2f) → (%.2f, %.2f)", fx, fy, rx, ry))+ if let p = try await click(vx, vy) { record(vx, vy, p) } else { await missed(at: rx, ry, empty: empty) }+ }+ guard samples.count >= 4, let (lx, ly) = lines() else {+ return .failed("only \(samples.count) of \(clicks) probe clicks arrived")+ }+ app.say(String(format: "probe fit: x = %.5f·u %+.3f, y = %.5f·u %+.3f, residual %.2f%% / %.2f%% (%@)",+ lx.a, lx.b, ly.a, ly.b, lx.rms * 100, ly.rms * 100,+ "\(Int(DeviceScreen.size.width))×\(Int(DeviceScreen.size.height)) pt @\(Int(DeviceScreen.scale))x"))+ pointer.applyProbe(x: lx, y: ly, samples: samples)++ // stage 3: check with the agent's own move+ phase = .verifying+ try await pointer.point(Self.check.x, Self.check.y)+ let sent = now()+ try await device.send("click")+ clicks += 1+ progress = Progress(done: clicks, total: total)+ guard let p = await probe.tap(since: sent, timeout: Self.tapTimeout) else { return .done(max(lx.rms, ly.rms)) }+ let error = max(abs(p.x - Self.check.x), abs(p.y - Self.check.y))+ pointer.setQuality(error)+ app.say(String(format: "probe check at (%.2f, %.2f): landed (%.3f, %.3f), ±%.1f%%", Self.check.x, Self.check.y,+ p.x, p.y, error * 100))+ return .done(error)+ }+}++extension AppModel {+ /// Ask the vision model where the pointer is on a mirrored frame (fallback for calibration).+ func locatePointer(_ jpeg: Data) async -> CGPoint? {+ guard !MockMode.on, settings.isConfigured, let client = try? await settings.client("actor") else { return nil }+ let system = "You find the mouse pointer on iPhone/iPad screenshots. The AssistiveTouch pointer is a small "+ + "round dark grey translucent dot. During calibration the screen is white with a grid: thin lines every "+ + "10% labelled 100-900 along the top and left edges, and coloured squares in the corners. Reply with JSON only: {\"x\": <0-1000>, \"y\": <0-1000>} for its centre, "+ + "relative to the screenshot (x left->right, y top->bottom), or {\"x\": null, \"y\": null} if there is none."+ guard let r = try? await client.chat(system: system, text: "Where is the pointer?", image: jpeg, maxTokens: 200,+ temperature: 0),+ let start = r.text.firstIndex(of: "{"), let end = r.text.lastIndex(of: "}"),+ let json = try? JSONSerialization.jsonObject(with: Data(r.text[start...end].utf8)) as? [String: Any],+ let x = (json["x"] as? NSNumber)?.doubleValue, let y = (json["y"] as? NSNumber)?.doubleValue,+ (0...1000).contains(x), (0...1000).contains(y) else {+ say("calibration: vision model did not find the pointer")+ return nil+ }+ return CGPoint(x: x / 1000, y: y / 1000)+ }+}diff --git a/ios/IPhoneAgent/App/TouchProbe.swift b/ios/IPhoneAgent/App/TouchProbe.swiftnew file mode 100644index 0000000..6f0fa8d--- /dev/null+++ b/ios/IPhoneAgent/App/TouchProbe.swift@@ -0,0 +1,110 @@+import SwiftUI+import UIKit++/// Catches the board's clicks on this app's own screen during calibration. While `capturing`, the+/// calibration board (white, gridded, above sheets and covers too) swallows every touch except its Back+/// button, so a probe click never presses a control underneath; otherwise only the toast takes touches.+@MainActor final class TouchProbe: ObservableObject {+ @Published private(set) var capturing = false+ /// Recent hits (screen fractions) for the faint flash on the grid.+ @Published private(set) var flashes: [CGPoint] = []+ private var taps: [(time: Double, at: CGPoint)] = []+ private var window: OverlayWindow?++ /// Show the overlay window over this scene (once; a no-op until a scene exists).+ func install<Content: View>(_ content: Content) {+ guard window == nil, let scene = DeviceScreen.scene else { return }+ let w = OverlayWindow(windowScene: scene)+ w.windowLevel = .alert + 1+ let host = UIHostingController(rootView: content)+ host.view.backgroundColor = .clear+ w.rootViewController = host+ w.catcher.onTouch = { [weak self] p, size in self?.touched(p, in: size) }+ w.isHidden = false+ window = w+ }++ /// Where the toast is (window coordinates); only that area takes touches when not capturing.+ func setInteractive(_ rect: CGRect) { window?.interactive = rect }+ /// The calibration board's buttons: the only places that take touches while capturing.+ func setButtonArea(_ id: String, _ rect: CGRect?) { window?.buttons[id] = rect }++ func begin() {+ taps = []+ flashes = []+ capturing = true+ window?.capturing = true+ }++ func end() {+ capturing = false+ window?.capturing = false+ Task { [weak self] in+ try? await Task.sleep(nanoseconds: 600_000_000)+ self?.flashes = []+ }+ }++ private func touched(_ p: CGPoint, in size: CGSize) {+ guard capturing, size.width > 0, size.height > 0 else { return }+ let f = CGPoint(x: p.x / size.width, y: p.y / size.height)+ taps.append((now(), f))+ flashes = Array((flashes + [f]).suffix(12))+ }++ /// The first tap after `since` (a click just sent), waiting up to `timeout` s.+ func tap(since: Double, timeout: Double = 3) async -> CGPoint? {+ let deadline = now() + timeout+ while now() < deadline && !Task.isCancelled {+ if let hit = taps.first(where: { $0.time >= since }) {+ taps.removeAll { $0.time <= hit.time }+ return hit.at+ }+ try? await Task.sleep(nanoseconds: 20_000_000)+ }+ return nil+ }+}++/// Passes touches through, except on the toast; while capturing, everything lands on the catcher.+final class OverlayWindow: UIWindow {+ let catcher = TouchCatcher()+ var capturing = false+ var interactive = CGRect.zero+ var buttons: [String: CGRect] = [:]++ override init(windowScene: UIWindowScene) {+ super.init(windowScene: windowScene)+ backgroundColor = .clear+ catcher.frame = bounds+ catcher.autoresizingMask = [.flexibleWidth, .flexibleHeight]+ addSubview(catcher)+ }++ required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }++ override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {+ if capturing {+ return buttons.values.contains { $0.contains(point) } ? super.hitTest(point, with: event) : catcher+ }+ guard interactive.contains(point) else { return nil }+ return super.hitTest(point, with: event)+ }+}++/// Reports where each touch begins, in screen points with the screen's size (an iPad app in Split View+/// is smaller than the screen the pointer moves on).+final class TouchCatcher: UIView {+ var onTouch: ((CGPoint, CGSize) -> Void)?++ override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {+ for t in touches {+ let p = t.location(in: self)+ if let screen = window?.windowScene?.screen {+ onTouch?(convert(p, to: screen.coordinateSpace), screen.bounds.size)+ } else {+ onTouch?(p, bounds.size)+ }+ }+ }+}diff --git a/ios/IPhoneAgent/AppShortcuts.xcstrings b/ios/IPhoneAgent/AppShortcuts.xcstringsnew file mode 100644index 0000000..4d58ac8--- /dev/null+++ b/ios/IPhoneAgent/AppShortcuts.xcstrings@@ -0,0 +1,86 @@+{+ "sourceLanguage" : "en",+ "strings" : {+ "${applicationName} status" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "${applicationName}状态"+ }+ }+ }+ },+ "Ask ${applicationName} to do something" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "让${applicationName}做件事"+ }+ }+ }+ },+ "Calibrate ${applicationName}" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "校准${applicationName}"+ }+ }+ }+ },+ "Give ${applicationName} a task" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "给${applicationName}一个任务"+ }+ }+ }+ },+ "Is ${applicationName} ready" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "${applicationName}准备好了吗"+ }+ }+ }+ },+ "Run ${applicationName} intent ${intent}" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "用${applicationName}运行${intent}"+ }+ }+ }+ },+ "Run ${intent} with ${applicationName}" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "让${applicationName}运行${intent}"+ }+ }+ }+ },+ "Stop ${applicationName}" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "停止${applicationName}"+ }+ }+ }+ }+ },+ "version" : "1.0"+}diff --git a/ios/IPhoneAgent/Assets.xcassets/AccentColor.colorset/Contents.json b/ios/IPhoneAgent/Assets.xcassets/AccentColor.colorset/Contents.jsonnew file mode 100644index 0000000..d464cbd--- /dev/null+++ b/ios/IPhoneAgent/Assets.xcassets/AccentColor.colorset/Contents.json@@ -0,0 +1,38 @@+{+ "colors": [+ {+ "idiom": "universal",+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0xB8",+ "green": "0x66",+ "blue": "0x0A",+ "alpha": "1.000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0xC7",+ "green": "0x74",+ "blue": "0x1A",+ "alpha": "1.000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}\ No newline at end of filediff --git a/ios/IPhoneAgent/Assets.xcassets/AppIcon.appiconset/AppIcon.png b/ios/IPhoneAgent/Assets.xcassets/AppIcon.appiconset/AppIcon.pngnew file mode 100644index 0000000..4a92685Binary files /dev/null and b/ios/IPhoneAgent/Assets.xcassets/AppIcon.appiconset/AppIcon.png differdiff --git a/ios/IPhoneAgent/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/IPhoneAgent/Assets.xcassets/AppIcon.appiconset/Contents.jsonnew file mode 100644index 0000000..0fe6aaf--- /dev/null+++ b/ios/IPhoneAgent/Assets.xcassets/AppIcon.appiconset/Contents.json@@ -0,0 +1,14 @@+{+ "images": [+ {+ "filename": "AppIcon.png",+ "idiom": "universal",+ "platform": "ios",+ "size": "1024x1024"+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}\ No newline at end of filediff --git a/ios/IPhoneAgent/Assets.xcassets/Contents.json b/ios/IPhoneAgent/Assets.xcassets/Contents.jsonnew file mode 100644index 0000000..c47b5f2--- /dev/null+++ b/ios/IPhoneAgent/Assets.xcassets/Contents.json@@ -0,0 +1,6 @@+{+ "info": {+ "author": "xcode",+ "version": 1+ }+}\ No newline at end of filediff --git a/ios/IPhoneAgent/Assets.xcassets/DiscordLogo.imageset/Contents.json b/ios/IPhoneAgent/Assets.xcassets/DiscordLogo.imageset/Contents.jsonnew file mode 100644index 0000000..be4e650--- /dev/null+++ b/ios/IPhoneAgent/Assets.xcassets/DiscordLogo.imageset/Contents.json@@ -0,0 +1,5 @@+{+ "images" : [ { "filename" : "DiscordLogo.svg", "idiom" : "universal" } ],+ "info" : { "author" : "xcode", "version" : 1 },+ "properties" : { "preserves-vector-representation" : true, "template-rendering-intent" : "template" }+}diff --git a/ios/IPhoneAgent/Assets.xcassets/DiscordLogo.imageset/DiscordLogo.svg b/ios/IPhoneAgent/Assets.xcassets/DiscordLogo.imageset/DiscordLogo.svgnew file mode 100644index 0000000..b82ef0b--- /dev/null+++ b/ios/IPhoneAgent/Assets.xcassets/DiscordLogo.imageset/DiscordLogo.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="#000" d="M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z"/></svg>diff --git a/ios/IPhoneAgent/Assets.xcassets/GitHubMark.imageset/Contents.json b/ios/IPhoneAgent/Assets.xcassets/GitHubMark.imageset/Contents.jsonnew file mode 100644index 0000000..b78dcd4--- /dev/null+++ b/ios/IPhoneAgent/Assets.xcassets/GitHubMark.imageset/Contents.json@@ -0,0 +1,5 @@+{+ "images" : [ { "filename" : "GitHubMark.svg", "idiom" : "universal" } ],+ "info" : { "author" : "xcode", "version" : 1 },+ "properties" : { "preserves-vector-representation" : true, "template-rendering-intent" : "template" }+}diff --git a/ios/IPhoneAgent/Assets.xcassets/GitHubMark.imageset/GitHubMark.svg b/ios/IPhoneAgent/Assets.xcassets/GitHubMark.imageset/GitHubMark.svgnew file mode 100644index 0000000..2a112bd--- /dev/null+++ b/ios/IPhoneAgent/Assets.xcassets/GitHubMark.imageset/GitHubMark.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="#000" d="M12 .297c-6.63 0-12 5.373-12 12 0 5.303 3.438 9.8 8.205 11.385.6.113.82-.258.82-.577 0-.285-.01-1.04-.015-2.04-3.338.724-4.042-1.61-4.042-1.61C4.422 18.07 3.633 17.7 3.633 17.7c-1.087-.744.084-.729.084-.729 1.205.084 1.838 1.236 1.838 1.236 1.07 1.835 2.809 1.305 3.495.998.108-.776.417-1.305.76-1.605-2.665-.3-5.466-1.332-5.466-5.93 0-1.31.465-2.38 1.235-3.22-.135-.303-.54-1.523.105-3.176 0 0 1.005-.322 3.3 1.23.96-.267 1.98-.399 3-.405 1.02.006 2.04.138 3 .405 2.28-1.552 3.285-1.23 3.285-1.23.645 1.653.24 2.873.12 3.176.765.84 1.23 1.91 1.23 3.22 0 4.61-2.805 5.625-5.475 5.92.42.36.81 1.096.81 2.22 0 1.606-.015 2.896-.015 3.286 0 .315.21.69.825.57C20.565 22.092 24 17.592 24 12.297c0-6.627-5.373-12-12-12"/></svg>diff --git a/ios/IPhoneAgent/Assets.xcassets/LaunchBackground.colorset/Contents.json b/ios/IPhoneAgent/Assets.xcassets/LaunchBackground.colorset/Contents.jsonnew file mode 100644index 0000000..3fd65d8--- /dev/null+++ b/ios/IPhoneAgent/Assets.xcassets/LaunchBackground.colorset/Contents.json@@ -0,0 +1,38 @@+{+ "colors": [+ {+ "idiom": "universal",+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0xFF",+ "green": "0xFF",+ "blue": "0xFF",+ "alpha": "1.000"+ }+ }+ },+ {+ "idiom": "universal",+ "appearances": [+ {+ "appearance": "luminosity",+ "value": "dark"+ }+ ],+ "color": {+ "color-space": "srgb",+ "components": {+ "red": "0x00",+ "green": "0x00",+ "blue": "0x00",+ "alpha": "1.000"+ }+ }+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}\ No newline at end of filediff --git a/ios/IPhoneAgent/Assets.xcassets/LaunchLogo.imageset/Contents.json b/ios/IPhoneAgent/Assets.xcassets/LaunchLogo.imageset/Contents.jsonnew file mode 100644index 0000000..97a5c2d--- /dev/null+++ b/ios/IPhoneAgent/Assets.xcassets/LaunchLogo.imageset/Contents.json@@ -0,0 +1,4 @@+{+ "images" : [ { "filename" : "LaunchLogo.png", "idiom" : "universal", "scale" : "3x" } ],+ "info" : { "author" : "xcode", "version" : 1 }+}diff --git a/ios/IPhoneAgent/Assets.xcassets/LaunchLogo.imageset/LaunchLogo.png b/ios/IPhoneAgent/Assets.xcassets/LaunchLogo.imageset/LaunchLogo.pngnew file mode 100644index 0000000..bd422e8Binary files /dev/null and b/ios/IPhoneAgent/Assets.xcassets/LaunchLogo.imageset/LaunchLogo.png differdiff --git a/ios/IPhoneAgent/Assets.xcassets/Logo.imageset/Contents.json b/ios/IPhoneAgent/Assets.xcassets/Logo.imageset/Contents.jsonnew file mode 100644index 0000000..76b8930--- /dev/null+++ b/ios/IPhoneAgent/Assets.xcassets/Logo.imageset/Contents.json@@ -0,0 +1,12 @@+{+ "images": [+ {+ "filename": "Logo.png",+ "idiom": "universal"+ }+ ],+ "info": {+ "author": "xcode",+ "version": 1+ }+}\ No newline at end of filediff --git a/ios/IPhoneAgent/Assets.xcassets/Logo.imageset/Logo.png b/ios/IPhoneAgent/Assets.xcassets/Logo.imageset/Logo.pngnew file mode 100644index 0000000..bd422e8Binary files /dev/null and b/ios/IPhoneAgent/Assets.xcassets/Logo.imageset/Logo.png differdiff --git a/ios/IPhoneAgent/Assets.xcassets/XLogo.imageset/Contents.json b/ios/IPhoneAgent/Assets.xcassets/XLogo.imageset/Contents.jsonnew file mode 100644index 0000000..1bdefb0--- /dev/null+++ b/ios/IPhoneAgent/Assets.xcassets/XLogo.imageset/Contents.json@@ -0,0 +1,5 @@+{+ "images" : [ { "filename" : "XLogo.svg", "idiom" : "universal" } ],+ "info" : { "author" : "xcode", "version" : 1 },+ "properties" : { "preserves-vector-representation" : true, "template-rendering-intent" : "template" }+}diff --git a/ios/IPhoneAgent/Assets.xcassets/XLogo.imageset/XLogo.svg b/ios/IPhoneAgent/Assets.xcassets/XLogo.imageset/XLogo.svgnew file mode 100644index 0000000..293e2f2--- /dev/null+++ b/ios/IPhoneAgent/Assets.xcassets/XLogo.imageset/XLogo.svg@@ -0,0 +1 @@+<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="#000" d="M18.901 1.153h3.68l-8.04 9.19L24 22.846h-7.406l-5.8-7.584-6.638 7.584H.474l8.6-9.83L0 1.154h7.594l5.243 6.932ZM17.61 20.644h2.039L6.486 3.24H4.298Z"/></svg>diff --git a/ios/IPhoneAgent/Board/BoardCommands.swift b/ios/IPhoneAgent/Board/BoardCommands.swiftnew file mode 100644index 0000000..d54256c--- /dev/null+++ b/ios/IPhoneAgent/Board/BoardCommands.swift@@ -0,0 +1,232 @@+import Foundation++/// The board did not answer in time; the link is still up (a disconnect throws DeviceError instead).+struct BoardTimeout: LocalizedError {+ let command: String+ let seconds: Double+ var errorDescription: String? { String(format: "the board did not answer '%@' within %.0f s", command, seconds) }+}++struct DeviceError: LocalizedError {+ let message: String+ var errorDescription: String? { message }+}++/// Where command lines go: the BLE link, or a fake board in tests.+@MainActor protocol BoardTransport: AnyObject {+ var isConnected: Bool { get }+ func write(_ line: String) throws+ /// Fire-and-forget: write only if the link can take it right now; false = dropped.+ func writeIfIdle(_ line: String) -> Bool+ /// Bytes one write can carry without a response.+ var maxWrite: Int { get }+ /// Drop the link after a timeout; the transport reconnects on its own (like the old TCP close).+ func dropLink()+}++extension BoardTransport {+ func writeIfIdle(_ line: String) -> Bool { (try? write(line)) != nil }+ var maxWrite: Int { 180 }+}++/// What gestures need from the board (CommandChannel, or a fake in tests).+@MainActor protocol HIDDevice: AnyObject {+ var links: Int { get }+ var connected: Bool { get }+ @discardableResult func send(_ command: String) async throws -> String+ func waitConnected(_ timeout: TimeInterval) async -> Bool+}++/// A FIFO async mutex for main-actor code.+@MainActor final class AsyncLock {+ private var busy = false+ private var waiters: [CheckedContinuation<Void, Never>] = []++ func lock() async {+ if !busy { busy = true; return }+ await withCheckedContinuation { waiters.append($0) }+ }++ func unlock() {+ if waiters.isEmpty { busy = false } else { waiters.removeFirst().resume() }+ }+}++/// Sends the board commands one at a time and matches replies by request id. Port of device.py.+@MainActor final class CommandChannel: HIDDevice {+ weak var transport: BoardTransport?+ private(set) var links = 0 // bumped on every (re)connect, so gestures know to release and re-home+ private let lock = AsyncLock()+ /// The board serves two centrals (this app and a Mac harness) and notifies replies to both: start our ids+ /// far from the harness's small ones, and drop replies to ids we did not send.+ private var nextID = Int.random(in: 100_000...800_000)+ private var logTimes: [Double] = []+ /// "app <command>" lines relayed from the Mac harness.+ var onAppCommand: ((String) -> Void)?+ private var pending: [Int: CheckedContinuation<BoardReply, Error>] = [:]+ private var last = 0.0, beat = 0.0+ var onTiming: ((String, Double) -> Void)? // command name, ms++ init(transport: BoardTransport? = nil) { self.transport = transport }++ var connected: Bool { transport?.isConnected ?? false }++ /// The transport (re)connected and subscribed.+ func linkUp() {+ links += 1+ last = now(); beat = last // fresh link: nothing to keep awake yet+ }++ /// The link dropped: fail everything in flight.+ func linkDown() {+ let waiting = pending+ pending = [:]+ waiting.values.forEach { $0.resume(throwing: DeviceError(message: "board disconnected")) }+ }++ func handleReply(_ line: String) {+ let text = line.trimmingCharacters(in: .whitespacesAndNewlines)+ if text.hasPrefix("app ") { return onAppCommand?(String(text.dropFirst(4))) ?? () }+ if text.hasPrefix("log ") { return } // our own log lines, relayed to the harness+ guard let reply = BoardReply.parse(line), let c = pending.removeValue(forKey: reply.id) else { return }+ c.resume(returning: reply)+ }++ func waitConnected(_ timeout: TimeInterval) async -> Bool {+ let deadline = now() + timeout+ while !connected && now() < deadline { try? await Task.sleep(nanoseconds: 200_000_000) }+ return connected+ }++ /// Seconds the board may take: replies need up to ~2 s at p99, moves are paced (10 units per 8 ms),+ /// typing is per character.+ nonisolated static func timeout(_ command: String) -> Double {+ let parts = command.split(separator: " ", maxSplits: 1).map(String.init)+ let name = parts.first ?? "", arg = parts.count > 1 ? parts[1] : ""+ switch name {+ case "move": return 5 + Double(arg.split(separator: " ").compactMap { Int($0) }.map(abs).max() ?? 0) / 10 * 0.012+ case "type": return 5 + 0.1 * Double(arg.count)+ case "ping": return 8 // an idle check: tolerate a hiccup rather than drop a healthy board+ case "snap": return 15 // a whole GOP over BLE+ case "bench": return 5 + (Double(arg) ?? 0) / 10 // KB at >= 80 kbps+ default: return 5+ }+ }++ /// Called once when a command times out (e.g. video starving control traffic): the app turns the+ /// stream off, then the command is retried once.+ var onTimeout: ((String) async -> Void)?++ /// Send one command; returns the text after "ok" (e.g. bench's ms). Throws DeviceError on err/timeout.+ @discardableResult+ func send(_ command: String) async throws -> String {+ do {+ return try await send(command, timeout: nil)+ } catch let e as BoardTimeout {+ guard command != "ping", !command.hasPrefix("stream"), let onTimeout else { throw e }+ await onTimeout(command)+ DebugLog.write("cmd retry after timeout: \(command.prefix(40))")+ return try await send(command, timeout: nil)+ }+ }++ /// A timeout is the board being slow (e.g. a snap while it also streams), not a lost link: it throws+ /// BoardTimeout and keeps the connection; only a real CoreBluetooth disconnect fails as link lost.+ @discardableResult+ func send(_ command: String, timeout custom: Double?) async throws -> String {+ guard connected, let transport else { throw DeviceError(message: "board not connected") }+ let timeout = custom ?? Self.timeout(command)+ let name = String(command.split(separator: " ").first ?? "")+ await lock.lock()+ defer { lock.unlock() }+ let started = now()+ let id = nextID+ nextID += 1+ let reply: BoardReply+ do {+ reply = try await withTaskCancellationHandler {+ try await withCheckedThrowingContinuation { (c: CheckedContinuation<BoardReply, Error>) in+ pending[id] = c+ do { try transport.write("\(id) \(command)") } catch {+ pending[id] = nil+ c.resume(throwing: error)+ return+ }+ Task { @MainActor [weak self] in+ try? await Task.sleep(nanoseconds: UInt64(timeout * 1e9))+ self?.fail(id, DeviceError(message: "timeout"))+ }+ }+ } onCancel: {+ Task { @MainActor [weak self] in self?.fail(id, CancellationError()) }+ }+ } catch is CancellationError {+ throw CancellationError()+ } catch {+ let ms = (now() - started) * 1000+ if (error as? DeviceError)?.message == "timeout" {+ if name != "ping" { DebugLog.write(String(format: "cmd #%d %@ → timeout after %.0f ms", id, String(command.prefix(40)), ms)) }+ throw BoardTimeout(command: String(command.prefix(30)), seconds: timeout)+ }+ DebugLog.write(String(format: "cmd #%d %@ → link lost after %.0f ms: %@", id, String(command.prefix(40)), ms,+ error.localizedDescription))+ throw DeviceError(message: "board link lost during '\(command.prefix(30))': \(error.localizedDescription)")+ }+ beat = now() // last reply of any kind+ if command != "ping" {+ last = beat // last real command: the phone's idle time+ onTiming?(String(command.split(separator: " ").first ?? ""), (now() - started) * 1000)+ }+ if name != "ping" {+ DebugLog.write(String(format: "cmd #%d %@ → %@ %@ (%.0f ms)", id, String(command.prefix(40)),+ reply.ok ? "ok" : "err", String(reply.text.prefix(60)), (now() - started) * 1000))+ }+ guard reply.ok else { throw DeviceError(message: "err " + reply.text) }+ return reply.text+ }++ /// Send a debug-log line to the Mac harness through the board (`log <text>`): fire-and-forget, at most+ /// 10 a second, truncated to one write, dropped when the link is busy.+ @discardableResult+ func relayLog(_ text: String) -> Bool {+ guard connected, let transport else { return false }+ let t = now()+ logTimes = logTimes.filter { t - $0 < 1 }+ guard logTimes.count < 10 else { return false }+ let prefix = "\(nextID) log "+ nextID += 1+ var body = text.replacingOccurrences(of: "\n", with: " ")+ while prefix.utf8.count + body.utf8.count > transport.maxWrite && !body.isEmpty { body.removeLast() }+ guard transport.writeIfIdle(prefix + body) else { return false }+ logTimes.append(t)+ return true+ }++ private func fail(_ id: Int, _ error: Error) {+ pending.removeValue(forKey: id)?.resume(throwing: error)+ }++ /// While idle: ping every few seconds, so a board that went away shows as gone within seconds, and nudge+ /// the pointer now and then so the phone does not auto-lock. Runs until cancelled.+ func keepAwake(idle: Double = 25, heartbeat: Double = 2, screenLive: @escaping () -> Bool) async {+ while !Task.isCancelled {+ try? await Task.sleep(nanoseconds: UInt64(heartbeat * 1e9))+ if !connected || now() - beat < heartbeat { continue }+ do {+ // nudge only a phone that is awake and mirroring: there is nothing to keep awake otherwise+ if now() - last > idle && screenLive() {+ try await send("move 1 0")+ try await send("move -1 0")+ } else {+ try await send("ping")+ }+ } catch {+ log("board gone: \(error.localizedDescription)")+ }+ }+ }++ var log: (String) -> Void = { print($0) }+}++func now() -> Double { Date().timeIntervalSince1970 }diff --git a/ios/IPhoneAgent/Board/BoardLink.swift b/ios/IPhoneAgent/Board/BoardLink.swiftnew file mode 100644index 0000000..8861717--- /dev/null+++ b/ios/IPhoneAgent/Board/BoardLink.swift@@ -0,0 +1,370 @@+import CoreBluetooth+import Foundation++/// CoreBluetooth central for the board: scan, connect (bonding happens on the first `net` read), command+/// writes, status / reply / video notifies. Reconnects on its own; restores state when iOS relaunches the app.+@MainActor final class BoardLink: NSObject, ObservableObject, BoardTransport {+ struct Found: Identifiable, Equatable {+ let id: UUID+ let name: String+ let rssi: Int+ }++ @Published private(set) var state: CBManagerState = .unknown+ @Published private(set) var found: [Found] = []+ @Published private(set) var scanning = false+ @Published private(set) var connected = false // subscribed and ready for commands+ @Published private(set) var linking = false // connected over the air, pairing / subscribing+ @Published private(set) var pairedID: UUID?+ @Published private(set) var name = ""+ @Published private(set) var status: BoardStatus?+ @Published private(set) var net: NetConfig?+ @Published private(set) var lastError = ""++ let commands = CommandChannel()+ var onVideo: ((Data) -> Void)?+ var onStatus: ((BoardStatus) -> Void)?+ var onLinkUp: (() -> Void)?+ var onLinkDown: (() -> Void)?+ private var lastNotify = 0.0 // last notification of any kind, to tell a supervision timeout from a peer drop+ private var readySince = 0.0+ var log: (String) -> Void = { print($0) }++ private var central: CBCentralManager!+ private var peripheral: CBPeripheral?+ private var chars: [CBUUID: CBCharacteristic] = [:]+ private var subscribed = Set<CBUUID>()+ private var netWaiters: [CheckedContinuation<NetConfig, Error>] = []+ private static let pairedKey = "pairedBoard"+ private var statusReads: Task<Void, Never>?+ let mock: Bool // demo data: no Bluetooth, every command answers ok (MockMode)++ init(mock: Bool = false) {+ self.mock = mock+ super.init()+ pairedID = UserDefaults.standard.string(forKey: Self.pairedKey).flatMap(UUID.init)+ commands.transport = self+ if mock { return }+ central = CBCentralManager(delegate: self, queue: .main, options: [+ CBCentralManagerOptionRestoreIdentifierKey: "iphone-agent-central",+ CBCentralManagerOptionShowPowerAlertKey: true,+ ])+ }++ var isConnected: Bool { connected }+ var mtu: Int { peripheral.map { $0.maximumWriteValueLength(for: .withoutResponse) + 3 } ?? 0 }++ // MARK: - scan / pair++ func scan() {+ guard state == .poweredOn, !mock else { return }+ found = []+ scanning = true+ central.scanForPeripherals(withServices: [BoardUUID.service], options: nil)+ }++ func stopScan() {+ central?.stopScan()+ scanning = false+ }++ /// Connect to a board and remember it; reading `net` then triggers the iOS pairing prompt.+ func pair(_ id: UUID) {+ if mock { return mockPair(id) }+ stopScan()+ pairedID = id+ UserDefaults.standard.set(id.uuidString, forKey: Self.pairedKey)+ reconnect()+ }++ /// Ask the board to erase its bonds, then forget it here. iOS keeps its own bond: the user removes+ /// "ESP32 Agent" in Settings > Bluetooth (apps cannot do that).+ func unpair() async {+ _ = try? await commands.send("unpair")+ forget()+ }++ /// Forget the board in the app only.+ func forget() {+ if let peripheral { central?.cancelPeripheralConnection(peripheral) }+ peripheral = nil+ pairedID = nil+ UserDefaults.standard.removeObject(forKey: Self.pairedKey)+ setDisconnected()+ }++ private func reconnect() {+ guard state == .poweredOn, !mock, let id = pairedID else { return }+ if peripheral?.identifier != id {+ peripheral = central.retrievePeripherals(withIdentifiers: [id]).first+ }+ guard let peripheral else { // iOS does not know it (yet): find it by scanning, then connect+ lastError = "board not found; scanning"+ if !scanning { scan() }+ return+ }+ peripheral.delegate = self+ name = peripheral.name ?? name+ central.connect(peripheral, options: nil) // no timeout: completes whenever the board shows up+ }++ // MARK: - net++ /// Read the network config (the first read pairs the phone with the board).+ func readNet() async throws -> NetConfig {+ guard let peripheral, let c = chars[BoardUUID.net] else { throw DeviceError(message: "board not connected") }+ return try await withCheckedThrowingContinuation { cont in+ netWaiters.append(cont)+ peripheral.readValue(for: c)+ }+ }++ func writeNet(_ config: NetConfig) throws {+ guard let peripheral, let c = chars[BoardUUID.net] else { throw DeviceError(message: "board not connected") }+ peripheral.writeValue(try JSONEncoder().encode(config), for: c, type: .withResponse)+ }++ // MARK: - BoardTransport++ func write(_ line: String) throws {+ if mock, connected { return mockReply(line) }+ guard let peripheral, let c = chars[BoardUUID.cmd], connected else {+ throw DeviceError(message: "board not connected")+ }+ let data = Data(line.utf8)+ let fast = data.count <= peripheral.maximumWriteValueLength(for: .withoutResponse)+ && c.properties.contains(.writeWithoutResponse) && peripheral.canSendWriteWithoutResponse+ peripheral.writeValue(data, for: c, type: fast ? .withoutResponse : .withResponse) // long writes need a response+ }++ var maxWrite: Int { peripheral?.maximumWriteValueLength(for: .withoutResponse) ?? 20 }++ func writeIfIdle(_ line: String) -> Bool {+ guard !mock, let peripheral, let c = chars[BoardUUID.cmd], connected,+ c.properties.contains(.writeWithoutResponse), peripheral.canSendWriteWithoutResponse else { return false }+ let data = Data(line.utf8)+ guard data.count <= peripheral.maximumWriteValueLength(for: .withoutResponse) else { return false }+ peripheral.writeValue(data, for: c, type: .withoutResponse)+ return true+ }++ func dropLink() {+ guard let peripheral, !mock else { return }+ central.cancelPeripheralConnection(peripheral) // didDisconnect reconnects+ }++ // MARK: - demo data++ /// Demo onboarding: Bluetooth is on and one board is nearby, not paired yet.+ func mockFound() {+ state = .poweredOn+ pairedID = nil+ found = [Found(id: UUID(), name: "ESP32 Agent 7C3E", rssi: -58)]+ }++ private func mockPair(_ id: UUID) {+ scanning = true+ Task { @MainActor in+ try? await Task.sleep(nanoseconds: 1_200_000_000)+ scanning = false+ mockConnect(name: "ESP32 Agent 7C3E",+ net: NetConfig(mode: "ap", ssid: "ESP32Agent-7C3E", pass: "demo-pass", ip: "192.168.4.1"))+ }+ }++ /// Pretend a board is paired and connected (MockMode).+ func mockConnect(name: String, net: NetConfig) {+ state = .poweredOn+ self.name = name+ self.net = net+ pairedID = pairedID ?? UUID()+ found = [Found(id: UUID(), name: "ESP32 Agent 7C3E", rssi: -71)]+ connected = true+ commands.linkUp()+ onLinkUp?()+ }++ func mockStatus(_ s: BoardStatus) {+ status = s+ onStatus?(s)+ }++ private func mockReply(_ line: String) {+ let parts = line.split(separator: " ").map(String.init)+ let extra = parts.count > 1 && parts[1] == "bench" ? " 6400" : ""+ Task { @MainActor in+ try? await Task.sleep(nanoseconds: 40_000_000)+ commands.handleReply("\(parts[0]) ok" + extra)+ }+ }++ /// Notifies may be shortened on a small MTU; read the full status every 5 s and merge it. The board notifies+ /// its status every second, so 5 s of silence (while this loop kept running) means it was unplugged: drop the+ /// link now instead of waiting for the Bluetooth timeout; the pending connect picks it up when it is back.+ private func startFullStatusReads() {+ statusReads?.cancel()+ statusReads = Task { [weak self] in+ var tick = 0, lastTick = now()+ while !Task.isCancelled {+ guard let self, self.connected, let p = self.peripheral, let c = self.chars[BoardUUID.status] else { return }+ if tick % 5 == 0 { p.readValue(for: c) }+ if now() - lastTick < 2 && now() - self.lastNotify > 5 {+ DebugLog.write(String(format: "BLE: no notification for %.0f s; dropping the link", now() - self.lastNotify))+ return self.dropLink()+ }+ tick += 1+ lastTick = now()+ try? await Task.sleep(nanoseconds: 1_000_000_000)+ }+ }+ }++ private func setDisconnected() {+ statusReads?.cancel()+ let was = connected+ connected = false+ linking = false+ chars = [:]+ subscribed = []+ commands.linkDown()+ netWaiters.forEach { $0.resume(throwing: DeviceError(message: "board disconnected")) }+ netWaiters = []+ if was {+ log("board disconnected")+ onLinkDown?()+ }+ }+}++extension BoardLink: CBCentralManagerDelegate {+ nonisolated func centralManagerDidUpdateState(_ central: CBCentralManager) {+ MainActor.assumeIsolated {+ state = central.state+ if central.state == .poweredOn { reconnect() } else { setDisconnected() }+ }+ }++ nonisolated func centralManager(_ central: CBCentralManager, willRestoreState dict: [String: Any]) {+ MainActor.assumeIsolated {+ if let restored = (dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral])?.first {+ peripheral = restored+ restored.delegate = self+ log("restored board link after relaunch")+ }+ }+ }++ nonisolated func centralManager(_ central: CBCentralManager, didDiscover p: CBPeripheral,+ advertisementData: [String: Any], rssi: NSNumber) {+ MainActor.assumeIsolated {+ let name = advertisementData[CBAdvertisementDataLocalNameKey] as? String ?? p.name ?? "ESP32 Agent"+ let item = Found(id: p.identifier, name: name, rssi: rssi.intValue)+ if let i = found.firstIndex(where: { $0.id == item.id }) { found[i] = item } else { found.append(item) }+ if p.identifier == pairedID && !connected && !linking { // the paired board is back: connect at once+ stopScan()+ peripheral = p+ reconnect()+ }+ }+ }++ nonisolated func centralManager(_ central: CBCentralManager, didConnect p: CBPeripheral) {+ MainActor.assumeIsolated {+ name = p.name ?? name+ linking = true+ log("board connected, discovering")+ p.discoverServices([BoardUUID.service])+ }+ }++ nonisolated func centralManager(_ central: CBCentralManager, didFailToConnect p: CBPeripheral, error: Error?) {+ MainActor.assumeIsolated {+ lastError = error?.localizedDescription ?? "connect failed"+ let e = error as NSError?+ DebugLog.write("BLE connect failed: \(e?.domain ?? "-") \(e?.code ?? 0): \(lastError)")+ reconnect()+ }+ }++ nonisolated func centralManager(_ central: CBCentralManager, didDisconnectPeripheral p: CBPeripheral,+ error: Error?) {+ MainActor.assumeIsolated {+ let e = error as NSError?+ DebugLog.write(String(format: "BLE disconnect: %@ %d: %@; last notification %.1f s ago; link up %.0f s",+ e?.domain ?? "no error", e?.code ?? 0, e?.localizedDescription ?? "-",+ lastNotify > 0 ? now() - lastNotify : -1, readySince > 0 ? now() - readySince : -1))+ setDisconnected()+ if let error { lastError = error.localizedDescription }+ reconnect() // pending connect: iOS completes it when the board is back, even in background+ }+ }+}++extension BoardLink: CBPeripheralDelegate {+ nonisolated func peripheral(_ p: CBPeripheral, didDiscoverServices error: Error?) {+ MainActor.assumeIsolated {+ guard let service = p.services?.first(where: { $0.uuid == BoardUUID.service }) else {+ lastError = "board service missing"+ return+ }+ p.discoverCharacteristics(BoardUUID.all, for: service)+ }+ }++ nonisolated func peripheral(_ p: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {+ MainActor.assumeIsolated {+ for c in service.characteristics ?? [] {+ chars[c.uuid] = c+ if [BoardUUID.reply, BoardUUID.status, BoardUUID.video].contains(c.uuid) { p.setNotifyValue(true, for: c) }+ }+ }+ }++ nonisolated func peripheral(_ p: CBPeripheral, didUpdateNotificationStateFor c: CBCharacteristic, error: Error?) {+ MainActor.assumeIsolated {+ if let error { lastError = "subscribe \(c.uuid): \(error.localizedDescription)"; return }+ subscribed.insert(c.uuid)+ if !connected && subscribed.isSuperset(of: [BoardUUID.reply, BoardUUID.status, BoardUUID.video]) {+ connected = true+ linking = false+ startFullStatusReads()+ commands.linkUp()+ readySince = now()+ lastNotify = now()+ onLinkUp?()+ log("board ready (MTU \(mtu))")+ }+ }+ }++ nonisolated func peripheral(_ p: CBPeripheral, didUpdateValueFor c: CBCharacteristic, error: Error?) {+ MainActor.assumeIsolated {+ lastNotify = now()+ if c.uuid == BoardUUID.net {+ let waiters = netWaiters+ netWaiters = []+ if let error {+ waiters.forEach { $0.resume(throwing: error) }+ } else if let v = c.value, let config = try? JSONDecoder().decode(NetConfig.self, from: v) {+ net = config+ waiters.forEach { $0.resume(returning: config) }+ } else {+ waiters.forEach { $0.resume(throwing: DeviceError(message: "bad net config")) }+ }+ return+ }+ guard error == nil, let v = c.value else { return }+ switch c.uuid {+ case BoardUUID.video: onVideo?(v)+ case BoardUUID.reply: commands.handleReply(String(decoding: v, as: UTF8.self))+ case BoardUUID.status:+ if let s = BoardStatus.decode(v) {+ let merged = status?.merged(with: s) ?? s+ status = merged+ onStatus?(merged)+ }+ default: break+ }+ }+ }+}diff --git a/ios/IPhoneAgent/Board/BoardProtocol.swift b/ios/IPhoneAgent/Board/BoardProtocol.swiftnew file mode 100644index 0000000..ad23de9--- /dev/null+++ b/ios/IPhoneAgent/Board/BoardProtocol.swift@@ -0,0 +1,70 @@+import CoreBluetooth+import Foundation++/// GATT layout and message formats from docs/ble-protocol.md.+enum BoardUUID {+ static func make(_ suffix: String) -> CBUUID { CBUUID(string: "6e400001-a9e8-4b1b-9c39-6d6f8a3c" + suffix) }+ static let service = make("0000")+ static let cmd = make("0001")+ static let reply = make("0002")+ static let status = make("0003")+ static let video = make("0004")+ static let net = make("0005")+ static let all = [cmd, reply, status, video, net]+}++/// The 1 s JSON heartbeat on `status`.+struct BoardStatus: Codable, Equatable {+ struct BLE: Codable, Equatable {+ var mtu: Int?, phy: Int?, kbps: Double?, drop: Int?+ }+ var up: Int?+ var rst: String?+ var heap: Int?+ var psram: Int?+ var usb: String? // ok | asleep | off+ var net: String? // ap | sta | none+ var ip: String?+ var sta: Int?+ var ap: String? // idle | connected | streaming+ var w: Int?, h: Int?+ var kbps: Double?, fps: Double?, idr: Int?, gop: Int?+ var ble: BLE?++ static func decode(_ data: Data) -> BoardStatus? { try? JSONDecoder().decode(BoardStatus.self, from: data) }++ /// A small MTU makes the board notify a reduced object (up, usb, net, ap, ble.mtu); a `status` read returns+ /// the full one. Newer fields win, missing ones keep their last value.+ func merged(with n: BoardStatus) -> BoardStatus {+ var m = n+ m.up = n.up ?? up; m.rst = n.rst ?? rst; m.heap = n.heap ?? heap; m.psram = n.psram ?? psram+ m.usb = n.usb ?? usb; m.net = n.net ?? net; m.ip = n.ip ?? ip; m.sta = n.sta ?? sta; m.ap = n.ap ?? ap+ m.w = n.w ?? w; m.h = n.h ?? h; m.kbps = n.kbps ?? kbps; m.fps = n.fps ?? fps; m.idr = n.idr ?? idr+ m.gop = n.gop ?? gop+ let a = ble ?? BLE(), b = n.ble ?? BLE()+ m.ble = BLE(mtu: b.mtu ?? a.mtu, phy: b.phy ?? a.phy, kbps: b.kbps ?? a.kbps, drop: b.drop ?? a.drop)+ return m+ }+}++/// The `net` characteristic: SoftAP credentials (read) or Wi-Fi mode (write).+struct NetConfig: Codable, Equatable {+ var mode: String+ var ssid: String?+ var pass: String?+ var ip: String?+}++/// A `reply` notify: `<id> ok [extra]` or `<id> err <reason>`.+struct BoardReply: Equatable {+ let id: Int+ let ok: Bool+ let text: String // extra after "ok", or the error reason++ static func parse(_ line: String) -> BoardReply? {+ let parts = line.trimmingCharacters(in: .whitespacesAndNewlines).split(separator: " ", maxSplits: 2)+ .map(String.init)+ guard parts.count >= 2, let id = Int(parts[0]), parts[1] == "ok" || parts[1] == "err" else { return nil }+ return BoardReply(id: id, ok: parts[1] == "ok", text: parts.count > 2 ? parts[2] : "")+ }+}diff --git a/ios/IPhoneAgent/IPhoneAgent.entitlements b/ios/IPhoneAgent/IPhoneAgent.entitlementsnew file mode 100644index 0000000..e3ff101--- /dev/null+++ b/ios/IPhoneAgent/IPhoneAgent.entitlements@@ -0,0 +1,16 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>com.apple.security.application-groups</key>+ <array>+ <string>group.$(IA_BUNDLE_ID)</string>+ </array>+ <key>com.apple.developer.networking.HotspotConfiguration</key>+ <true/>+ <key>com.apple.developer.networking.wifi-info</key>+ <true/>+ <key>com.apple.developer.usernotifications.time-sensitive</key>+ <true/>+</dict>+</plist>diff --git a/ios/IPhoneAgent/Info.plist b/ios/IPhoneAgent/Info.plistnew file mode 100644index 0000000..4461e0b--- /dev/null+++ b/ios/IPhoneAgent/Info.plist@@ -0,0 +1,86 @@+<?xml version="1.0" encoding="UTF-8"?>+<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">+<plist version="1.0">+<dict>+ <key>CFBundleDevelopmentRegion</key>+ <string>en</string>+ <key>CFBundleDisplayName</key>+ <string>ESP32 Agent</string>+ <key>CFBundleDocumentTypes</key>+ <array>+ <dict>+ <key>CFBundleTypeName</key>+ <string>ESP32 Agent runs</string>+ <key>LSHandlerRank</key>+ <string>Alternate</string>+ <key>LSItemContentTypes</key>+ <array>+ <string>public.zip-archive</string>+ </array>+ </dict>+ </array>+ <key>CFBundleExecutable</key>+ <string>$(EXECUTABLE_NAME)</string>+ <key>CFBundleIdentifier</key>+ <string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>+ <key>CFBundleInfoDictionaryVersion</key>+ <string>6.0</string>+ <key>CFBundleLocalizations</key>+ <array>+ <string>en</string>+ <string>zh-Hans</string>+ </array>+ <key>CFBundleName</key>+ <string>$(PRODUCT_NAME)</string>+ <key>CFBundlePackageType</key>+ <string>APPL</string>+ <key>CFBundleShortVersionString</key>+ <string>1.0</string>+ <key>CFBundleURLTypes</key>+ <array>+ <dict>+ <key>CFBundleURLName</key>+ <string>$(IA_BUNDLE_ID)</string>+ <key>CFBundleURLSchemes</key>+ <array>+ <string>iphoneagent</string>+ </array>+ </dict>+ </array>+ <key>CFBundleVersion</key>+ <string>1</string>+ <key>IAAppGroup</key>+ <string>group.$(IA_BUNDLE_ID)</string>+ <key>IAPresetBaseURL</key>+ <string>$(IA_PRESET_BASE_URL)</string>+ <key>IAPresetKey</key>+ <string>$(IA_PRESET_KEY)</string>+ <key>IAPresetModel</key>+ <string>$(IA_PRESET_MODEL)</string>+ <key>LSSupportsOpeningDocumentsInPlace</key>+ <true/>+ <key>NSBluetoothAlwaysUsageDescription</key>+ <string>ESP32 Agent talks to its USB board over Bluetooth to see the screen and move the pointer.</string>+ <key>NSSupportsLiveActivities</key>+ <true/>+ <key>UIBackgroundModes</key>+ <array>+ <string>bluetooth-central</string>+ </array>+ <key>UIFileSharingEnabled</key>+ <true/>+ <key>UILaunchScreen</key>+ <dict>+ <key>UIColorName</key>+ <string>LaunchBackground</string>+ <key>UIImageName</key>+ <string>LaunchLogo</string>+ </dict>+ <key>UIRequiresFullScreen</key>+ <true/>+ <key>UISupportedInterfaceOrientations</key>+ <array>+ <string>UIInterfaceOrientationPortrait</string>+ </array>+</dict>+</plist>diff --git a/ios/IPhoneAgent/InfoPlist.xcstrings b/ios/IPhoneAgent/InfoPlist.xcstringsnew file mode 100644index 0000000..f8def48--- /dev/null+++ b/ios/IPhoneAgent/InfoPlist.xcstrings@@ -0,0 +1,38 @@+{+ "sourceLanguage" : "en",+ "version" : "1.0",+ "strings" : {+ "CFBundleDisplayName" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "ESP32 Agent"+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "ESP32 Agent"+ }+ }+ }+ },+ "NSBluetoothAlwaysUsageDescription" : {+ "localizations" : {+ "en" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "ESP32 Agent talks to its USB board over Bluetooth to see the screen and move the pointer."+ }+ },+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "ESP32 Agent 通过蓝牙与 USB 开发板通信,用来查看屏幕和移动指针。"+ }+ }+ }+ }+ }+}diff --git a/ios/IPhoneAgent/Localizable.xcstrings b/ios/IPhoneAgent/Localizable.xcstringsnew file mode 100644index 0000000..4721256--- /dev/null+++ b/ios/IPhoneAgent/Localizable.xcstrings@@ -0,0 +1,5033 @@+{+ "sourceLanguage" : "en",+ "strings" : {+ "" : {+ "shouldTranslate" : false+ },+ " " : {+ "shouldTranslate" : false,+ "extractionState" : "stale"+ },+ "${applicationName} status" : {},+ "%@" : {},+ "%lld runs, %@, redacted" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%lld 个运行,%@,已脱敏"+ }+ }+ }+ },+ "%lld screens" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%lld 个画面"+ }+ }+ }+ },+ "%lld screens captured. Stop when you're done." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已抓取 %lld 个画面。做完后点停止。"+ }+ }+ }+ },+ "%lld steps" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%lld 步"+ }+ }+ }+ },+ "%lld steps · %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "%lld 步 · %@"+ }+ }+ }+ },+ "%lld steps. Check the yellow ones." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "共 %lld 步。请确认标黄的步骤。"+ }+ }+ }+ },+ "A .zip with steps, metrics, screenshots, video frames and debug.log, redacted before it is written." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "一个 .zip,包含步骤、指标、截图、视频帧和 debug.log,写入前已脱敏。"+ }+ }+ }+ },+ "A zip of debug.log and every run (steps, model replies, screenshots, video). Your API key is never in it." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "包含 debug.log 和每次运行(步骤、模型回复、截图、视频)的压缩包。不会包含你的 API 密钥。"+ }+ }+ }+ },+ "API key" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "API 密钥"+ }+ }+ }+ },+ "API key (optional)" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "API 密钥(可选)"+ }+ }+ }+ },+ "About" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "关于"+ }+ }+ }+ },+ "Accept" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "接受"+ }+ }+ }+ },+ "Accessibility" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "辅助功能"+ }+ }+ }+ },+ "Accuracy %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "精度 %@"+ }+ }+ }+ },+ "Acknowledgements" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "致谢"+ }+ }+ }+ },+ "Actions" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "操作"+ }+ }+ }+ },+ "Actor model" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "执行模型"+ }+ }+ }+ },+ "Add Hint" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "添加要点"+ }+ }+ }+ },+ "Add a step at the end" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "在末尾添加一步"+ }+ }+ }+ },+ "Advanced" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "高级"+ }+ }+ }+ },+ "After" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "优化后"+ }+ }+ }+ },+ "Agent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "助手"+ }+ }+ }+ },+ "AirPlay fps" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "AirPlay 帧率"+ }+ }+ }+ },+ "AirPlay kbps" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "AirPlay 码率 kbps"+ }+ }+ }+ },+ "Airplane Mode" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "飞行模式"+ }+ }+ }+ },+ "Alive in background" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "后台存活时长"+ }+ }+ }+ },+ "Almost there. Tap an orange item to finish setup." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "快好了。点橙色的项目完成设置。"+ }+ }+ }+ },+ "Already running: %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在运行:%@"+ }+ }+ }+ },+ "Any OpenAI-compatible vision model works. The key stays in this iPhone's Keychain." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "任何兼容 OpenAI 的视觉模型都可以。密钥只保存在这台 iPhone 的钥匙串里。"+ }+ }+ }+ },+ "App-side video kbps" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "App 端视频 kbps"+ }+ }+ }+ },+ "Ask ${applicationName} to do something" : {},+ "Ask ESP32 Agent to ${task}" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "让 ESP32 Agent ${task}"+ }+ }+ }+ },+ "Asked for your help" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请求你帮忙"+ }+ }+ }+ },+ "Asks ESP32 Agent to do a task on this iPhone, like \"Open Settings and go to Wi-Fi\"." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "让 ESP32 Agent 在这台 iPhone 上完成一个任务,比如“打开设置并进入无线局域网”。"+ }+ }+ }+ },+ "AssistiveTouch" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "辅助触控"+ }+ }+ }+ },+ "Author on X" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "作者 X"+ }+ }+ }+ },+ "Auto" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "自动"+ }+ }+ }+ },+ "Automatic" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "自动"+ }+ }+ }+ },+ "Automatic (first: %@)" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "自动(第一个:%@)"+ }+ }+ }+ },+ "Average time" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "平均用时"+ }+ }+ }+ },+ "BLE" : {+ "shouldTranslate" : false+ },+ "BLE bench (256 KB)" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "蓝牙测速(256 KB)"+ }+ }+ }+ },+ "Back" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "返回"+ }+ }+ }+ },+ "Back 5 seconds" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "后退 5 秒"+ }+ }+ }+ },+ "Background" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "后台"+ }+ }+ }+ },+ "Background test (10 min)" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "后台测试(10 分钟)"+ }+ }+ }+ },+ "Base URL" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "接口地址"+ }+ }+ }+ },+ "Before" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "优化前"+ }+ }+ }+ },+ "Bench kbps" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "测速 kbps"+ }+ }+ }+ },+ "Bluetooth" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "蓝牙"+ }+ }+ }+ },+ "Bluetooth Pairing Request" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "蓝牙配对请求"+ }+ }+ }+ },+ "Bluetooth is not allowed for ESP32 Agent." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "ESP32 Agent 没有蓝牙权限。"+ }+ }+ }+ },+ "Board" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "开发板"+ }+ }+ }+ },+ "Board BLE kbps" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "开发板蓝牙 kbps"+ }+ }+ }+ },+ "Board connected" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "板子已连接"+ }+ }+ }+ },+ "Board disconnected" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "小板已断开"+ }+ }+ }+ },+ "Board metrics" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "板子指标"+ }+ }+ }+ },+ "Board not connected" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "板子未连接"+ }+ }+ }+ },+ "Calibrate" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "校准"+ }+ }+ }+ },+ "Calibrate ${applicationName}" : {},+ "Calibrate before first use" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "首次使用前请先校准"+ }+ }+ }+ },+ "Calibrate the Pointer" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "校准指针"+ }+ }+ }+ },+ "Calibrate the pointer" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "校准指针"+ }+ }+ }+ },+ "Calibrate the pointer in ESP32 Agent first." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请先在 ESP32 Agent 中校准指针。"+ }+ }+ }+ },+ "Calibrated" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已校准"+ }+ }+ }+ },+ "Calibrated, %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已校准,%@"+ }+ }+ }+ },+ "Calibrates the pointer on a grid; takes a few seconds." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "在网格上校准指针,需要几秒钟。"+ }+ }+ }+ },+ "Calibrating" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "校准中"+ }+ }+ }+ },+ "Calibrating pointer…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在校准指针…"+ }+ }+ }+ },+ "Calibrating pointer… %lld/%lld" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在校准指针… %lld/%lld"+ }+ }+ }+ },+ "Calibrating the pointer…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在校准指针…"+ }+ }+ }+ },+ "Calibrating…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在校准…"+ }+ }+ }+ },+ "Calibration" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "校准"+ }+ }+ }+ },+ "Calibration didn't work" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "校准没有成功"+ }+ }+ }+ },+ "Cancel" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "取消"+ }+ }+ }+ },+ "Cellular" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "蜂窝网络"+ }+ }+ }+ },+ "Change" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "更改"+ }+ }+ }+ },+ "Check all seven days under Repeat, then tap Back" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "在“重复”里勾选全部七天,然后点返回"+ }+ }+ }+ },+ "Check point not found." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "没有找到检查点。"+ }+ }+ }+ },+ "Check that the board is plugged in. The run waits for it." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请检查小板是否插好。运行会等它回来。"+ }+ }+ }+ },+ "Checking the connection…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在检查连接…"+ }+ }+ }+ },+ "Checking…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在检查…"+ }+ }+ }+ },+ "Checklist" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "要点清单"+ }+ }+ }+ },+ "Choose the board's network" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "选择小板的网络"+ }+ }+ }+ },+ "Choose “ESP32 Agent”" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "选择“ESP32 Agent”"+ }+ }+ }+ },+ "Clear the Point" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "清除标记点"+ }+ }+ }+ },+ "Clicks aren't reaching the screen — is AssistiveTouch on and the board plugged into this iPhone?" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "点击没有到达屏幕——辅助触控是否已打开?板子是否插在这台 iPhone 上?"+ }+ }+ }+ },+ "Close" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "关闭"+ }+ }+ }+ },+ "Coming soon" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "即将推出"+ }+ }+ }+ },+ "Community" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "社区"+ }+ }+ }+ },+ "Connect the board" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "连接小板"+ }+ }+ }+ },+ "Connect the board to the USB-C port. I'll find it over Bluetooth; tap Pair when iOS asks." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "把小板插到 USB-C 口。我会通过蓝牙找到它;iOS 询问时点“配对”。"+ }+ }+ }+ },+ "Connected" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已连接"+ }+ }+ }+ },+ "Connected to %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已连接 %@"+ }+ }+ }+ },+ "Connected. Try this first:" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已连接。先试试这个:"+ }+ }+ }+ },+ "Connecting can take a few seconds — be patient." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "连接需要几秒钟,请耐心等待。"+ }+ }+ },+ "extractionState" : "stale"+ },+ "Connecting…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在连接…"+ }+ }+ }+ },+ "Contacts" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "通讯录"+ }+ }+ }+ },+ "Continue" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "继续"+ }+ }+ }+ },+ "Copied" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已复制"+ }+ }+ }+ },+ "Copy" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "复制"+ }+ }+ }+ },+ "Copy Password & Open Settings" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "拷贝密码并打开设置"+ }+ }+ }+ },+ "Copy Wi-Fi Password" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "拷贝 Wi-Fi 密码"+ }+ }+ }+ },+ "Correct" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "对"+ }+ }+ }+ },+ "Could not import" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "无法导入"+ }+ }+ }+ },+ "Could not load the model list: %@ Type a model id instead." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "无法获取模型列表:%@ 请直接输入模型 ID。"+ }+ }+ }+ },+ "Could not optimize" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "无法优化"+ }+ }+ }+ },+ "Could not reach the model. Check the URL and key." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "无法连接模型。请检查 URL 和密钥。"+ }+ }+ }+ },+ "Could not start" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "无法开始"+ }+ }+ }+ },+ "Could not start: %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "无法开始:%@"+ }+ }+ }+ },+ "Couldn't read the board's Wi-Fi. Is the board connected?" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "读取不到板子的 Wi-Fi。板子连上了吗?"+ }+ }+ }+ },+ "Daily 7 AM alarm" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "每天 7 点闹钟"+ }+ }+ }+ },+ "Decode" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "解码"+ }+ }+ }+ },+ "Decode errors (bg)" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "解码错误(后台)"+ }+ }+ }+ },+ "Decoded fps" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "解码帧率"+ }+ }+ }+ },+ "Delete" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "删除"+ }+ }+ }+ },+ "Delete Intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "删除意图"+ }+ }+ }+ },+ "Delete step" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "删除这一步"+ }+ }+ }+ },+ "Delete this intent?" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "删除这个意图?"+ }+ }+ }+ },+ "Demo data" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "演示数据"+ }+ }+ }+ },+ "Demo data fakes a board, a finished run and the whole setup, to try the app without hardware. Takes effect after you quit and reopen the app." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "演示数据会模拟小板、一次完成的运行和整个设置流程,无需硬件即可试用。退出并重新打开 App 后生效。"+ }+ }+ }+ },+ "Demo data is on." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "演示数据已开启。"+ }+ }+ }+ },+ "Demo data simulates the model." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "演示数据会模拟模型。"+ }+ }+ }+ },+ "Demonstration" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "示范录制"+ }+ }+ }+ },+ "Demonstration · check the yellow steps" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "示范录制 · 请确认标黄的步骤"+ }+ }+ }+ },+ "Describe what should happen after this step." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "描述这一步之后应该做什么。"+ }+ }+ }+ },+ "Device model and iOS version" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "设备型号和 iOS 版本"+ }+ }+ }+ },+ "Diagnostics" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "诊断"+ }+ }+ }+ },+ "Didn't finish" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "没做完"+ }+ }+ }+ },+ "Disclaimer" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "免责声明"+ }+ }+ }+ },+ "Display" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "显示与亮度"+ }+ }+ }+ },+ "Do the step yourself, then tap Continue." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请你自己完成这一步,然后点“继续”。"+ }+ }+ }+ },+ "Do the task yourself. I watch the mirrored screen and write the steps down." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "你自己做一遍。我看着镜像画面,把步骤记下来。"+ }+ }+ }+ },+ "Do the task yourself. I'm watching." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "你来做一遍,我在看。"+ }+ }+ }+ },+ "Done" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "完成"+ }+ }+ }+ },+ "Done!" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "搞定!"+ }+ }+ }+ },+ "Done! Open Runs to replay what I did." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "完成了!去“记录”回放我做了什么。"+ }+ }+ }+ },+ "Done: %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "完成:%@"+ }+ }+ }+ },+ "Draw a circle" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "画一个圆"+ }+ }+ }+ },+ "Draw a path" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "画一条路径"+ }+ }+ }+ },+ "Draw a smiley" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "画个笑脸"+ }+ }+ }+ },+ "Drawing…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "画一画…"+ }+ }+ }+ },+ "Drops (app / board)" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "丢包(App / 开发板)"+ }+ }+ }+ },+ "Edit" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "编辑"+ }+ }+ }+ },+ "Edit as task" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "编辑为任务"+ }+ }+ }+ },+ "Error" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "错误"+ }+ }+ }+ },+ "Espressif's frameworks for the board firmware." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "乐鑫的框架,用于小板固件。"+ }+ }+ }+ },+ "Every run is recorded here step by step, so you can replay what I did." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "每次运行都会一步步记录在这里,方便你回放我做了什么。"+ }+ }+ }+ },+ "Every run keeps a low-frame-rate video of the mirrored screen, next to the step screenshots, for the review." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "每次运行都会保存一段低帧率的镜像屏幕视频,与步骤截图一起用于复盘。"+ }+ }+ }+ },+ "Examples" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "示例"+ }+ }+ }+ },+ "Export all logs" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "导出全部日志"+ }+ }+ }+ },+ "Export run data" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "导出运行数据"+ }+ }+ }+ },+ "Export trace" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "导出 trace"+ }+ }+ }+ },+ "Export traces" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "导出运行记录"+ }+ }+ }+ },+ "Extra body JSON" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "额外请求参数 JSON"+ }+ }+ }+ },+ "Face ID" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "面容 ID"+ }+ }+ }+ },+ "Failed" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "失败"+ }+ }+ }+ },+ "Fix" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "修正"+ }+ }+ }+ },+ "Forget in This App" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "在本 App 中忘记"+ }+ }+ }+ },+ "Forward 5 seconds" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "前进 5 秒"+ }+ }+ }+ },+ "Found %@" : {},+ "GOP buffered" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已缓存 GOP"+ }+ }+ }+ },+ "Gave up" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "放弃了"+ }+ }+ }+ },+ "General" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "通用"+ }+ }+ }+ },+ "Get Started" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "开始"+ }+ }+ }+ },+ "Get Status" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "获取状态"+ }+ }+ }+ },+ "Get notified?" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "要接收通知吗?"+ }+ }+ }+ },+ "Give Me a Brain" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "给我一个大脑"+ }+ }+ }+ },+ "Given to the agent as hints every time this intent runs." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "每次运行这个意图时都会作为提示交给 agent。"+ }+ }+ }+ },+ "Go back" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "返回"+ }+ }+ }+ },+ "Go to the Home Screen" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "回到主屏幕"+ }+ }+ }+ },+ "Go to the Home Screen and do the task. Stop here or in the Dynamic Island." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "回到主屏幕完成任务。在这里或灵动岛里停止。"+ }+ }+ }+ },+ "Going back" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "返回"+ }+ }+ }+ },+ "Going home" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "回主屏幕"+ }+ }+ }+ },+ "Going on from here…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "从这里继续…"+ }+ }+ }+ },+ "Going to the Home Screen" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "回主屏幕"+ }+ }+ }+ },+ "HID %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "HID %@"+ }+ }+ },+ "shouldTranslate" : false+ },+ "Hands off the screen for a few seconds." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "几秒钟内请不要触碰屏幕。"+ }+ }+ }+ },+ "Haptic Touch" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "触感触控"+ }+ }+ }+ },+ "Heap" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "堆内存"+ }+ }+ }+ },+ "Hi, I'm %@. Tell me what to do on this iPhone." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "你好,我是 %@。告诉我要在这台 iPhone 上做什么。"+ }+ }+ }+ },+ "Hi, I'm ESP32 Agent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "你好,我是 ESP32 Agent"+ }+ }+ }+ },+ "Hiccup, retrying" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "出了点小问题,重试中"+ }+ }+ }+ },+ "Hint" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "要点"+ }+ }+ }+ },+ "Home" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "归位"+ }+ }+ }+ },+ "I need your help with one step." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "有一步需要你帮忙。"+ }+ }+ }+ },+ "I understand and accept" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "我已了解并同意"+ }+ }+ }+ },+ "I'll connect as soon as it's plugged in." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "一插上我就会自动连接。"+ }+ }+ }+ },+ "I'll tell you when a run is done or needs your help, since you won't see this app while I work." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "我工作时你看不到这个 App,所以运行完成或需要你帮忙时我会通知你。"+ }+ }+ }+ },+ "I'm already on the board's Wi-Fi" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "我已连上开发板的 Wi-Fi"+ }+ }+ }+ },+ "I'm reading the steps and your fixes to write a clearer intent." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "我在看这些步骤和你的修正,写一个更清楚的意图。"+ }+ }+ }+ },+ "I'm stuck on this step." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "我卡在这一步了。"+ }+ }+ }+ },+ "I'm watching. Do the task, then stop the recording." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "我在看。做完任务后停止录制。"+ }+ }+ }+ },+ "IDR interval (board / app)" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "关键帧间隔(开发板 / App)"+ }+ }+ }+ },+ "Import run" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "导入运行"+ }+ }+ }+ },+ "Imported" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已导入"+ }+ }+ }+ },+ "Insert" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "插入"+ }+ }+ }+ },+ "Insert a step" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "插入一步"+ }+ }+ }+ },+ "Instruction" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "指令"+ }+ }+ }+ },+ "Intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "意图"+ }+ }+ }+ },+ "Intent deleted" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "意图已删除"+ }+ }+ }+ },+ "Intent draft ready" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "意图草稿已生成"+ }+ }+ }+ },+ "Internet uses cellular data while on the board's Wi-Fi." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "连接板子的 Wi-Fi 时,上网走蜂窝数据。"+ }+ }+ }+ },+ "It's the grey dot, near the top left." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "就是左上方附近的灰色圆点。"+ }+ }+ }+ },+ "Join" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "加入"+ }+ }+ }+ },+ "Join the Board's Wi-Fi" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "加入小板的 Wi-Fi"+ }+ }+ }+ },+ "Join the Discord" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "加入 Discord 社区"+ }+ }+ }+ },+ "Join the board's Wi-Fi" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "加入开发板的 Wi-Fi"+ }+ }+ }+ },+ "Join was cancelled." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已取消加入。"+ }+ }+ }+ },+ "Joining usually takes up to 10 seconds — hang tight." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "加入一般 10 秒内完成,请稍等。"+ }+ }+ }+ },+ "Joining…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在加入…"+ }+ }+ }+ },+ "Keep Editing" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "继续编辑"+ }+ }+ }+ },+ "Keep run data for sharing" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "保留运行数据以便分享"+ }+ }+ }+ },+ "Keep the last run as a reference and reuse it with one tap." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "把上次运行留作参考,以后一键复用。"+ }+ }+ }+ },+ "Keep the screen unlocked: locking stops mirroring." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "保持屏幕解锁:锁屏会中断镜像。"+ }+ }+ }+ },+ "Kept on this iPhone" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "保存在这台 iPhone 上"+ }+ }+ }+ },+ "LLM first token / total" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "模型首字 / 总耗时"+ }+ }+ }+ },+ "LLM ping" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "模型连通测试"+ }+ }+ }+ },+ "Language" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "语言"+ }+ }+ }+ },+ "Last run" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "上次运行"+ }+ }+ }+ },+ "Last step frame / LLM / HID" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "上一步 取帧 / 模型 / HID"+ }+ }+ }+ },+ "Later" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "稍后"+ }+ }+ }+ },+ "Learning from %lld corrections…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在从 %lld 处修正中学习…"+ }+ }+ }+ },+ "Let Me See the Screen" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "让我看见屏幕"+ }+ }+ }+ },+ "Let Me Use the Pointer" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "让我能动手"+ }+ }+ }+ },+ "Lets you export redacted runs from Settings › Privacy to share with the community. You can change this anytime." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "可以在 设置 › 隐私 中导出脱敏后的运行数据分享给社区。随时可以更改。"+ }+ }+ }+ },+ "Logs" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "日志"+ }+ }+ }+ },+ "Looking at the screen…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "我看看…"+ }+ }+ }+ },+ "Looking for the board…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在寻找小板…"+ }+ }+ }+ },+ "Looking…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "我看看…"+ }+ }+ }+ },+ "MTU (app / board)" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "MTU(App / 开发板)"+ }+ }+ }+ },+ "Made a new plan" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "重新做了计划"+ }+ }+ }+ },+ "Made a plan" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "做了计划"+ }+ }+ }+ },+ "Mirroring" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "镜像"+ }+ }+ }+ },+ "Mirroring is off, so the pointer can't be seen." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "屏幕镜像未开启,看不到指针。"+ }+ }+ }+ },+ "Model" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "模型"+ }+ }+ }+ },+ "Model not set up" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "模型未设置"+ }+ }+ }+ },+ "Model replies" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "模型回复"+ }+ }+ }+ },+ "Model: %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "模型:%@"+ }+ }+ }+ },+ "More" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "更多"+ }+ }+ }+ },+ "Mouse" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "鼠标"+ }+ }+ }+ },+ "Mouse connected" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "鼠标已连接"+ }+ }+ }+ },+ "My intents" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "我的意图"+ }+ }+ }+ },+ "Name" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "名称"+ }+ }+ }+ },+ "Nearby" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "附近"+ }+ }+ }+ },+ "Need help" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "需要帮忙"+ }+ }+ }+ },+ "Need your help" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "需要你帮忙"+ }+ }+ }+ },+ "Needs setup" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "需要设置"+ }+ }+ }+ },+ "Needs your help" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "需要你帮一下"+ }+ }+ }+ },+ "Needs your help: %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "需要你帮一下:%@"+ }+ }+ }+ },+ "Network" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "网络"+ }+ }+ }+ },+ "Never collected" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "从不收集"+ }+ }+ }+ },+ "New Intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "新建意图"+ }+ }+ }+ },+ "New intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "新建意图"+ }+ }+ }+ },+ "Next step" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "下一步"+ }+ }+ }+ },+ "No runs in this file." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "这个文件里没有运行数据。"+ }+ }+ }+ },+ "No runs yet" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "还没有运行记录"+ }+ }+ }+ },+ "No screen changes were captured." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "没有抓到画面变化。"+ }+ }+ }+ },+ "No video for this run." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "这次运行没有录像。"+ }+ }+ }+ },+ "Not Now" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "以后再说"+ }+ }+ }+ },+ "Not calibrated" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未校准"+ }+ }+ }+ },+ "Not connected" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未连接"+ }+ }+ }+ },+ "Not connected — plug the board into USB-C" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未连接——请把板子插到 USB-C 口"+ }+ }+ }+ },+ "Not finished: %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "没完成:%@"+ }+ }+ }+ },+ "Not paired" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未配对"+ }+ }+ }+ },+ "Not running" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未在运行"+ }+ }+ }+ },+ "Not set up" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未设置"+ }+ }+ }+ },+ "Note" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "备注"+ }+ }+ }+ },+ "Note: hello" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "备忘录:hello"+ }+ }+ }+ },+ "Nothing is uploaded. An export is redacted: secrets and IP addresses removed, typed text hidden, the top of every screenshot blacked out." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "不会上传任何内容。导出内容会脱敏:去掉密钥和 IP 地址,隐藏输入的文字,并涂黑每张截图的顶部。"+ }+ }+ }+ },+ "Nothing logged yet." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "暂无日志。"+ }+ }+ }+ },+ "Notifications" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "通知"+ }+ }+ }+ },+ "Now" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "进行中"+ }+ }+ }+ },+ "Now swipe down from the top-right corner and tap **Screen Mirroring → ESP32 Agent**." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "现在从右上角向下轻扫,然后轻点 **屏幕镜像 → ESP32 Agent**。"+ }+ }+ }+ },+ "OK" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "好"+ }+ }+ }+ },+ "Office" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "办公室"+ }+ }+ }+ },+ "Open Clock › Alarms, tap +, type 0700 for the time, set Repeat to every day, then tap Save" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打开 时钟 › 闹钟,点 +,输入 0700 作为时间,把重复设为每天,然后点存储"+ }+ }+ }+ },+ "Open Notes and write \"hello\"" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打开备忘录写 hello"+ }+ }+ }+ },+ "Open Settings" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打开设置"+ }+ }+ }+ },+ "Open Settings and go to Wi-Fi" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打开设置,进入 Wi-Fi"+ }+ }+ }+ },+ "Open Settings › Wi-Fi" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打开 设置 › 无线局域网"+ }+ }+ }+ },+ "Open Whiteboard and draw a smiley face" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打开白板画一个笑脸"+ }+ }+ }+ },+ "Open ESP32 Agent once, then try again." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请先打开一次 ESP32 Agent,然后再试。"+ }+ }+ }+ },+ "Open source. No data leaves this iPhone except the requests to the model endpoint you set up." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "开源软件。除了发往你设置的模型接口的请求,没有数据离开这台 iPhone。"+ }+ }+ }+ },+ "OpenAI-compatible API" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "OpenAI 兼容 API"+ }+ }+ }+ },+ "Opens ESP32 Agent and calibrates the pointer." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打开 ESP32 Agent 并校准指针。"+ }+ }+ }+ },+ "Opens the replay" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打开回放"+ }+ }+ }+ },+ "Optimize with AI" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "让 AI 优化"+ }+ }+ }+ },+ "PHY" : {+ "shouldTranslate" : false+ },+ "PSRAM" : {+ "shouldTranslate" : false+ },+ "Pair" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "配对"+ }+ }+ }+ },+ "Pairing… tap Pair when iOS asks" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "配对中… iOS 询问时点“配对”"+ }+ }+ }+ },+ "Password" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "密码"+ }+ }+ }+ },+ "Paste the password, then Join" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "粘贴密码,然后加入"+ }+ }+ }+ },+ "Pause" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "暂停"+ }+ }+ }+ },+ "Paused while you're here. Go to the Home Screen and I'll go on." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "你在这里时我先暂停。回到主屏幕我就继续。"+ }+ }+ }+ },+ "Per-step screenshots" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "每一步的截图"+ }+ }+ }+ },+ "Planner model" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "规划模型"+ }+ }+ }+ },+ "Play" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "播放"+ }+ }+ }+ },+ "Playback speed" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "播放速度"+ }+ }+ }+ },+ "Plug Me In" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "把我插上"+ }+ }+ }+ },+ "Plug me into the USB-C port to wake me up." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "把我插到 USB-C 口,我就醒了。"+ }+ }+ }+ },+ "Plug the board into the USB-C port" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "把小板插到 USB-C 口"+ }+ }+ }+ },+ "Pointer" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "指针"+ }+ }+ }+ },+ "Pointer Devices" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "指针设备"+ }+ }+ }+ },+ "Pointer calibrated" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "指针已校准"+ }+ }+ }+ },+ "Pointer calibrated %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "指针已校准 %@"+ }+ }+ }+ },+ "Pointer not found on screen." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "屏幕上没有找到指针。"+ }+ }+ }+ },+ "Poke" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "戳一戳"+ }+ }+ }+ },+ "Prepare Export" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "准备导出"+ }+ }+ }+ },+ "Press %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "按 %@"+ }+ }+ }+ },+ "Pressing %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "按 %@"+ }+ }+ }+ },+ "Pressing a key…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "按一下键…"+ }+ }+ }+ },+ "Previous step" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "上一步"+ }+ }+ }+ },+ "Privacy" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "隐私与安全性"+ }+ }+ }+ },+ "Re-run from here" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "从这一步重跑"+ }+ }+ }+ },+ "Reading the screen…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在看屏幕…"+ }+ }+ }+ },+ "Ready" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "就绪"+ }+ }+ }+ },+ "Recommended: calibrate before first use." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "建议:首次使用前先校准。"+ }+ }+ }+ },+ "Record an intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "录制意图"+ }+ }+ }+ },+ "Record me doing it" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "我来做一遍"+ }+ }+ }+ },+ "Recording" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "录制中"+ }+ }+ }+ },+ "Recording a demonstration" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在录制示范"+ }+ }+ }+ },+ "Recording needs Screen Mirroring. Your fingers are not visible to the board, so I guess each step from the screen and mark the unsure ones yellow." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "录制需要屏幕镜像。小板看不到你的手指,所以我根据画面推断每一步,不确定的会标黄。"+ }+ }+ }+ },+ "Reference run" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "参考运行"+ }+ }+ }+ },+ "Refresh Model List" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "刷新模型列表"+ }+ }+ }+ },+ "Rename %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "重命名 %@"+ }+ }+ }+ },+ "Rename Agent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "重命名助手"+ }+ }+ }+ },+ "Reset reason" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "重启原因"+ }+ }+ }+ },+ "Resolution" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "分辨率"+ }+ }+ }+ },+ "Retry" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "重试"+ }+ }+ }+ },+ "Review" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "查看复盘"+ }+ }+ }+ },+ "Review Last Run" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "复盘上次运行"+ }+ }+ }+ },+ "Run" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行"+ }+ }+ }+ },+ "Run ${applicationName} intent ${intent}" : {},+ "Run ${intent}" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行${intent}"+ }+ }+ }+ },+ "Run %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行 %@"+ }+ }+ }+ },+ "Run Intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行意图"+ }+ }+ }+ },+ "Run Last Intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行上次的意图"+ }+ }+ }+ },+ "Run a Saved Intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行已保存的意图"+ }+ }+ }+ },+ "Run a Task" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行任务"+ }+ }+ }+ },+ "Run it again later with one tap." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "以后一键再次运行。"+ }+ }+ }+ },+ "Run it once to get steps you can review and fix here." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行一次后,这里就会有可以复盘和修正的步骤。"+ }+ }+ }+ },+ "Run setup again" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "重新运行设置向导"+ }+ }+ }+ },+ "Running" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行中"+ }+ }+ }+ },+ "Running step %lld: %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在运行第 %lld 步:%@"+ }+ }+ }+ },+ "Runs" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "记录"+ }+ }+ }+ },+ "Runs one of your saved intents on ESP32 Agent." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "在 ESP32 Agent 上运行一个已保存的意图。"+ }+ }+ }+ },+ "Runs the saved intent you ran last on ESP32 Agent." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "在 ESP32 Agent 上运行你上次运行的意图。"+ }+ }+ }+ },+ "Same as Model" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "与“模型”相同"+ }+ }+ }+ },+ "Save" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "保存"+ }+ }+ }+ },+ "Save Intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "保存意图"+ }+ }+ }+ },+ "Save as Intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "存为意图"+ }+ }+ }+ },+ "Save as intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "存为意图"+ }+ }+ }+ },+ "Save last run as intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "把上次运行存为意图"+ }+ }+ }+ },+ "Saved Intent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已保存的意图"+ }+ }+ }+ },+ "Scan for Boards" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "扫描小板"+ }+ }+ }+ },+ "Scanning…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在扫描…"+ }+ }+ }+ },+ "Screen Mirroring" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "屏幕镜像"+ }+ }+ }+ },+ "Screen Mirroring goes to the board over its own Wi-Fi." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "屏幕镜像通过小板自己的 Wi-Fi 传给小板。"+ }+ }+ }+ },+ "Screen Mirroring off" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "屏幕镜像已关闭"+ }+ }+ }+ },+ "Screen Mirroring on" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "屏幕镜像已开启"+ }+ }+ }+ },+ "Screen Mirroring stopped" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "屏幕镜像已中断"+ }+ }+ }+ },+ "See you later!" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "回头见!"+ }+ }+ }+ },+ "Set an alarm for 7:00 AM that repeats every day (check all days under Repeat), then save it" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "设置早上 7:00 的闹钟,在「重复」里把每一天都勾上,然后保存"+ }+ }+ }+ },+ "Set up the model" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "设置模型"+ }+ }+ }+ },+ "Set up the model in Settings first." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请先在设置里配置模型。"+ }+ }+ }+ },+ "Settings" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "设置"+ }+ }+ }+ },+ "Settings › Accessibility" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "设置 › 辅助功能"+ }+ }+ }+ },+ "Several boards nearby. Choose yours:" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "附近有多块小板,选择你的:"+ }+ }+ }+ },+ "Share" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "分享"+ }+ }+ }+ },+ "Share debug log" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "分享调试日志"+ }+ }+ }+ },+ "Shown on the Agent tab, in greetings and in the Live Activity." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "显示在助手标签页、问候语和实时活动中。"+ }+ }+ }+ },+ "Skip Step" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "跳过这步"+ }+ }+ }+ },+ "Skip step" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "跳过这步"+ }+ }+ }+ },+ "Skipped" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已跳过"+ }+ }+ }+ },+ "Smiley drawn" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "笑脸画好了"+ }+ }+ }+ },+ "Snap -> decoded" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "取帧 → 解码完成"+ }+ }+ }+ },+ "Snap latency" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "取帧延迟"+ }+ }+ }+ },+ "Speed" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "速度"+ }+ }+ }+ },+ "Start" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "开始"+ }+ }+ }+ },+ "Start Screen Mirroring" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "开启屏幕镜像"+ }+ }+ }+ },+ "Start Using ESP32 Agent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "开始使用 ESP32 Agent"+ }+ }+ }+ },+ "Start from this step: %@. The steps before it are already done." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "从这一步开始:%@。之前的步骤已经完成。"+ }+ }+ }+ },+ "Start it again from Control Center so I can see the screen." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请从控制中心重新打开,让我能看见屏幕。"+ }+ }+ }+ },+ "Started: %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已开始:%@"+ }+ }+ }+ },+ "Starting" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在开始"+ }+ }+ }+ },+ "Status" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "状态"+ }+ }+ }+ },+ "Status age" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "状态更新间隔"+ }+ }+ }+ },+ "Step %lld of %lld" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "第 %lld 步,共 %lld 步"+ }+ }+ }+ },+ "Step %lld of 4" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "第 %lld 步,共 4 步"+ }+ }+ }+ },+ "Step %lld of up to %lld" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "第 %lld 步,最多 %lld 步"+ }+ }+ }+ },+ "Steps" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "步骤"+ }+ }+ }+ },+ "Stop" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "停止"+ }+ }+ }+ },+ "Stop ${applicationName}" : {},+ "Stop Recording" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "停止录制"+ }+ }+ }+ },+ "Stop recording" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "停止录制"+ }+ }+ }+ },+ "Stop the agent" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "停止 agent"+ }+ }+ }+ },+ "Stopped" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "已停止"+ }+ }+ }+ },+ "Stops the running task and lets go of the screen." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "停止正在运行的任务并松开屏幕。"+ }+ }+ }+ },+ "Success rate" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "成功率"+ }+ }+ }+ },+ "Suspensions" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "被挂起次数"+ }+ }+ }+ },+ "Swipe" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "滑动"+ }+ }+ }+ },+ "Swipe down from the top-right corner" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "从右上角向下轻扫"+ }+ }+ }+ },+ "Swipe up to go to the Home Screen, and I'll start." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请向上轻扫回到主屏幕,我就开始。"+ }+ }+ }+ },+ "Swiping…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "滑一下…"+ }+ }+ }+ },+ "Take Over" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "接管"+ }+ }+ }+ },+ "Take over" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "接管"+ }+ }+ }+ },+ "Tap Pair when iOS asks" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "iOS 询问时点“配对”"+ }+ }+ }+ },+ "Tap Screen Mirroring" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "点“屏幕镜像”"+ }+ }+ }+ },+ "Tap at %lld, %lld" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "点击 %lld, %lld"+ }+ }+ }+ },+ "Tap exactly where the pointer is" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "请准确轻点指针所在的位置"+ }+ }+ }+ },+ "Tap the pointer yourself" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "自己轻点指针"+ }+ }+ }+ },+ "Tap to Wake" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "轻点唤醒"+ }+ }+ }+ },+ "Tap where it should have tapped. The green target marks it." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "点出它本该点击的位置,绿色准星会标出来。"+ }+ }+ }+ },+ "Tap ▶ to run, tap the row for details. Swipe left to delete." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "点 ▶ 运行,点整行查看详情,左滑删除。"+ }+ }+ }+ },+ "Tapping %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "点一下 %@"+ }+ }+ }+ },+ "Tapping…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "点一下…"+ }+ }+ }+ },+ "Task" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "任务"+ }+ }+ }+ },+ "Tell me a task and I'll do it on this iPhone: I see the screen through Screen Mirroring and tap with a USB mouse." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "告诉我一个任务,我会在这台 iPhone 上完成:通过屏幕镜像看屏幕,用 USB 鼠标点击。"+ }+ }+ }+ },+ "Tells whether the board, Screen Mirroring, calibration and the model are ready." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "告诉你板子、屏幕镜像、校准和模型是否就绪。"+ }+ }+ }+ },+ "Test Connection" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "测试连接"+ }+ }+ }+ },+ "Testing…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "测试中…"+ }+ }+ }+ },+ "Tests" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "测试"+ }+ }+ }+ },+ "That did not work out. The replay shows where I got stuck." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "没成功。回放里能看到我卡在了哪里。"+ }+ }+ }+ },+ "The + button is at the top right of Alarms" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "+ 按钮在“闹钟”页右上角"+ }+ }+ }+ },+ "The board is a USB mouse. iOS shows its pointer only with AssistiveTouch on. Then I calibrate on a grid, like a 3D printer levelling its bed." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "板子是一个 USB 鼠标。只有打开辅助触控,iOS 才会显示它的指针。然后我会在网格上校准,就像 3D 打印机调平热床。"+ }+ }+ }+ },+ "The board isn't connected." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "板子未连接。"+ }+ }+ }+ },+ "The board or Screen Mirroring isn't ready. Connect the board and start Screen Mirroring." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "板子或屏幕镜像还没准备好。请连接板子并开启屏幕镜像。"+ }+ }+ }+ },+ "The board's AirPlay receiver is ported from UxPlay." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "小板的 AirPlay 接收端移植自 UxPlay。"+ }+ }+ }+ },+ "The board's Bluetooth LE stack." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "小板的低功耗蓝牙协议栈。"+ }+ }+ }+ },+ "The board's USB mouse and keyboard." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "小板的 USB 鼠标和键盘。"+ }+ }+ }+ },+ "The endpoint lists no models." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "该接口没有列出任何模型。"+ }+ }+ }+ },+ "The iPhone didn't switch to the board's Wi-Fi. Join by hand with the password below." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "iPhone 没有切换到板子的 Wi-Fi。请用下面的密码手动加入。"+ }+ }+ }+ },+ "The model gave no improved prompt." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "模型没有给出改进的指令。"+ }+ }+ }+ },+ "The pointer isn't calibrated yet." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "指针还没有校准。"+ }+ }+ }+ },+ "The task is empty." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "任务为空。"+ }+ }+ }+ },+ "There are no saved intents yet." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "还没有已保存的意图。"+ }+ }+ }+ },+ "Thinking…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "想一想…"+ }+ }+ }+ },+ "This is not a run archive." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "这不是运行数据压缩包。"+ }+ }+ }+ },+ "Timeline" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "时间轴"+ }+ }+ }+ },+ "Timings" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "耗时"+ }+ }+ }+ },+ "Tip: in AssistiveTouch › Pointer Devices, set Tracking Speed to the middle and turn Pointer Animations off." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "提示:在 辅助触控 › 指针设备 中,把跟踪速度调到中间,并关闭指针动画。"+ }+ }+ }+ },+ "Token parameter" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Token 参数"+ }+ }+ }+ },+ "Touch" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "触控"+ }+ }+ }+ },+ "Try Again" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "重试"+ }+ }+ }+ },+ "Turn AssistiveTouch on" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "打开辅助触控"+ }+ }+ }+ },+ "Turn on Bluetooth in Control Center." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "在控制中心打开蓝牙。"+ }+ }+ }+ },+ "Type the time instead of scrolling the wheel" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "时间用输入,不要滑动滚轮"+ }+ }+ }+ },+ "Type “%@”" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "输入“%@”"+ }+ }+ }+ },+ "Typing %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "输入 %@"+ }+ }+ }+ },+ "Typing…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "输入中…"+ }+ }+ }+ },+ "USB" : {+ "shouldTranslate" : false+ },+ "Understand the risks" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "了解风险"+ }+ }+ }+ },+ "Unpair Board" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "解除配对"+ }+ }+ }+ },+ "Unpair erases the bonds on the board. iOS keeps its own: also tap (i) next to \"ESP32 Agent\" in Settings › Bluetooth and choose Forget This Device." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "解除配对会清除小板上的绑定。iOS 会保留自己的绑定:还需在 设置 › 蓝牙 中点“ESP32 Agent”旁的 (i),选择“忽略此设备”。"+ }+ }+ }+ },+ "Unsure" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "不确定"+ }+ }+ }+ },+ "Untitled run" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "未命名的运行"+ }+ }+ }+ },+ "Uptime" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行时长"+ }+ }+ }+ },+ "Version %@" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "版本 %@"+ }+ }+ }+ },+ "Video" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "视频"+ }+ }+ }+ },+ "Video position" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "视频位置"+ }+ }+ }+ },+ "View" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "视图"+ }+ }+ }+ },+ "View source on GitHub" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "在 GitHub 上查看源码"+ }+ }+ }+ },+ "Voice Control" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "语音控制"+ }+ }+ }+ },+ "Wait" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "等待"+ }+ }+ }+ },+ "Waiting for Screen Mirroring…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在等待屏幕镜像…"+ }+ }+ }+ },+ "Waiting for mirroring…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在等待镜像…"+ }+ }+ }+ },+ "Waiting for the board…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在等待板子…"+ }+ }+ }+ },+ "Waiting for the mouse…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在等待鼠标…"+ }+ }+ }+ },+ "Waiting…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "等一下…"+ }+ }+ }+ },+ "Watching you" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "我看着你做"+ }+ }+ }+ },+ "What should I do on this iPhone?" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "要我在这台 iPhone 上做什么?"+ }+ }+ }+ },+ "What should I do?" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "要我做什么?"+ }+ }+ }+ },+ "What should the agent do?" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "agent 应该做什么?"+ }+ }+ }+ },+ "While joined, the internet goes over cellular data. Switch back in Settings › Wi-Fi when you are done." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "加入后,上网会走蜂窝数据。用完后在 设置 › 无线局域网 里切回。"+ }+ }+ }+ },+ "Wi-Fi" : {+ "shouldTranslate" : false+ },+ "Wi-Fi password" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Wi-Fi 密码"+ }+ }+ }+ },+ "Wi-Fi settings" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "Wi-Fi 设置"+ }+ }+ }+ },+ "Working on it. Watch the Dynamic Island, or stop me anytime." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在做。看灵动岛,或随时让我停下。"+ }+ }+ }+ },+ "Working out the steps from %lld screens…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在从 %lld 个画面推断步骤…"+ }+ }+ }+ },+ "Working out the steps…" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "正在推断步骤…"+ }+ }+ }+ },+ "Wrong" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "不对"+ }+ }+ }+ },+ "You took over" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "你接管了"+ }+ }+ }+ },+ "Your Data" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "你的数据"+ }+ }+ }+ },+ "Your key stays in this iPhone's Keychain and is only sent to this endpoint." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "密钥仅保存在这台 iPhone 的钥匙串中,只会发送给此端点。"+ }+ }+ }+ },+ "Your turn" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "轮到你了"+ }+ }+ }+ },+ "Your turn. Tap Continue when you're done." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "轮到你了。做完后点“继续”。"+ }+ }+ }+ },+ "acting" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "动手中"+ }+ }+ },+ "extractionState" : "stale"+ },+ "before a run" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "运行前"+ }+ }+ }+ },+ "content" : {+ "extractionState" : "stale",+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "惬意"+ }+ }+ }+ },+ "dizzy" : {+ "extractionState" : "stale",+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "晕乎乎"+ }+ }+ }+ },+ "e.g. Morning alarm" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "例如:早上闹钟"+ }+ }+ }+ },+ "e.g. Tap Save at the top right" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "例如:点右上角的存储"+ }+ }+ }+ },+ "e.g. Tap the + at the top right" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "例如:应该点右上角的 +"+ }+ }+ }+ },+ "failure" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "失败"+ }+ }+ },+ "extractionState" : "stale"+ },+ "first setup" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "首次设置"+ }+ }+ }+ },+ "iOS couldn't join automatically. Join by hand with the password below." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "iOS 无法自动加入。请用下面的密码手动加入。"+ }+ }+ }+ },+ "ESP32 Agent" : {+ "shouldTranslate" : false+ },+ "ESP32 Agent follows your iPhone's language. To change it just for this app, open Settings › ESP32 Agent › Language." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "ESP32 Agent 跟随 iPhone 的语言。只想改这个 App 的语言,请打开 设置 › ESP32 Agent › 语言。"+ }+ }+ }+ },+ "ESP32 Agent is experimental software that controls this iPhone on its own. It can tap the wrong thing, send messages, change settings, buy things or delete data. Watch it while it runs and stop it if anything looks wrong. Screenshots of your screen are sent to the model endpoint you choose. You use it at your own risk; the authors accept no liability for any loss or damage." : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "ESP32 Agent 是实验性软件,会自行操作这台 iPhone。它可能点错、发出消息、修改设置、购买东西或删除数据。运行时请看着它,发现不对立即停止。屏幕截图会发送到你选择的模型接口。使用风险由你自行承担;作者不对任何损失负责。"+ }+ }+ }+ },+ "ESP32 Agent is still on screen" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "ESP32 Agent 仍在屏幕上"+ }+ }+ }+ },+ "idle" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "空闲"+ }+ }+ },+ "extractionState" : "stale"+ },+ "listening" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "在听"+ }+ }+ },+ "extractionState" : "stale"+ },+ "requested" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "手动请求"+ }+ }+ }+ },+ "sleeping" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "睡觉"+ }+ }+ },+ "extractionState" : "stale"+ },+ "success" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "成功"+ }+ }+ },+ "extractionState" : "stale"+ },+ "thinking" : {+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "思考中"+ }+ }+ },+ "extractionState" : "stale"+ },+ "wink" : {+ "extractionState" : "stale",+ "localizations" : {+ "zh-Hans" : {+ "stringUnit" : {+ "state" : "translated",+ "value" : "眨眼"+ }+ }+ }+ },+ "••••••••" : {+ "shouldTranslate" : false+ }+ },+ "version" : "1.0"+}diff --git a/ios/IPhoneAgent/Mock/MockMode.swift b/ios/IPhoneAgent/Mock/MockMode.swiftnew file mode 100644index 0000000..b0f1a2b--- /dev/null+++ b/ios/IPhoneAgent/Mock/MockMode.swift@@ -0,0 +1,193 @@+import Foundation++/// Demo data for looking at the UI without a board: launch with `-mock`, or turn on Settings > Demo data+/// (takes effect on the next launch). Walks the whole setup (board found → paired → mirroring → calibrated),+/// has one finished run to replay, and Start plays a fake run with a Live Activity. Nothing reaches a phone.+enum MockMode {+ static let key = "demoData"+ /// Read once at launch, so turning the switch on mid-session never mixes real and fake state.+ static let on: Bool = ProcessInfo.processInfo.arguments.contains("-mock") || UserDefaults.standard.bool(forKey: key)+}++extension AppModel {+ func startMock() {+ writeMockRun()+ if settings.onboarded {+ mockReady()+ } else {+ board.mockFound()+ }++ Task { [weak self] in+ var up = 812_000, n = 0+ while !Task.isCancelled {+ guard let self else { return }+ n += 1+ up += 1000+ if self.settings.onboarded && !self.board.connected { self.mockReady() } // setup skipped with "Later"+ if self.board.connected {+ if self.mockMirroring && self.feed.frame == nil { self.showMockFrame() }+ self.board.mockStatus(Self.status(up: up, n: n, mirroring: self.mockMirroring))+ }+ self.metrics.videoBytes(Int.random(in: 38_000...46_000))+ for _ in 0..<5 { self.metrics.frameDecoded(ms: Double.random(in: 3.5...6)) }+ if n % 2 == 0 { self.metrics.idrSeen() }+ if n % 4 == 0 { self.metrics.snapLatency(Double.random(in: 420...690)) }+ if n % 3 == 0 {+ self.metrics.llm(first: Double.random(in: 0.35...0.6), total: Double.random(in: 1.2...2.1))+ self.metrics.step(Metrics.Step(frameMs: .random(in: 300...520), llmMs: .random(in: 1200...2100),+ hidMs: .random(in: 250...700)))+ self.metrics.hidMs = ["move": .random(in: 18...40), "click": .random(in: 9...16)]+ }+ try? await Task.sleep(nanoseconds: 1_000_000_000)+ }+ }+ }++ /// Demo data after setup: everything is ready, whatever was skipped.+ func mockReady() {+ if !board.connected {+ board.mockConnect(name: "ESP32 Agent 7C3E",+ net: NetConfig(mode: "ap", ssid: "ESP32Agent-7C3E", pass: nil, ip: "192.168.4.1"))+ }+ hotspotSSID = "ESP32Agent-7C3E"+ mockMirroring = true+ modelOK = true+ if feed.frame == nil { showMockFrame() }+ board.mockStatus(Self.status(up: 812_000, n: 0, mirroring: true))+ if !pointer.calibrated { pointer.mockCalibrated(quality: 0.006) }+ }++ /// Demo: Screen Mirroring "starts" a moment after the hotspot is joined.+ func mockStartMirroring() {+ Task { [weak self] in+ try? await Task.sleep(nanoseconds: 2_500_000_000)+ self?.mockMirroring = true+ }+ }++ private func showMockFrame() {+ if let jpeg = Self.mockFrame { feed.show(jpeg, width: 480, height: 1075) }+ }++ static var mockFrame: Data? {+ Bundle.main.url(forResource: "mock-frame", withExtension: "jpg").flatMap { try? Data(contentsOf: $0) }+ }++ /// Plays the demo steps as a run: trace and video on disk, Live Activity, one "needs your help" pause,+ /// notifications, then the review.+ func mockRun(_ task: String) {+ guard !agent.running else { return }+ traces.start(task: task)+ agent.showMock(task: task, plan: "", steps: [], running: true)+ began(task)+ let video = traces.dir?.appendingPathComponent("video")+ if let video { try? FileManager.default.createDirectory(at: video, withIntermediateDirectories: true) }+ mockJob = Task { [weak self] in+ var shown: [JObject] = []+ for (i, step) in (Self.mockSteps + [["action": .str("done"), "answer": .str("The alarm is saved.")]]).enumerated() {+ self?.doing(.thinking) // the island's eyes dart while the "model" thinks, then look at the target+ try? await Task.sleep(nanoseconds: 2_400_000_000)+ guard let self, !Task.isCancelled, self.agent.running else { break }+ if i == 6 { // a demo of the help pause+ let fail: JObject = ["action": .str("fail"), "reason": .str("A passcode prompt appeared.")]+ self.traces.write(kind: "step", fail)+ shown.append(fail)+ self.agent.showMock(task: task, plan: Self.mockPlan, steps: shown, running: true)+ let choice = await self.needsHelp("A passcode prompt appeared.")+ let rec: JObject = ["action": .str(choice == .stop ? "stopped" : choice == .skip ? "skipped" : "takeover")]+ self.traces.write(kind: "step", rec)+ shown.append(rec)+ if choice == .stop { break }+ }+ if !StepText.notMoves.contains(step["action"]?.str ?? "") {+ self.doing(.acting(step))+ try? await Task.sleep(nanoseconds: 900_000_000)+ }+ guard !Task.isCancelled, self.agent.running else { break }+ self.traces.write(Self.mockFrame, kind: "llm", ["role": .str("actor"), "seconds": .num(1.3)])+ self.traces.write(kind: "step", step.merging(["think_s": .num(1.3), "act_s": .num(0.4)]))+ if let video, let frame = Self.mockFrame {+ try? frame.write(to: video.appendingPathComponent("\(Int(Date().timeIntervalSince1970 * 1000)).jpg"))+ }+ shown.append(JObject([("t", .num(now()))]).merging(step))+ self.agent.showMock(task: task, plan: Self.mockPlan, steps: shown, running: true)+ self.stepped()+ }+ guard let self else { return }+ if (Task.isCancelled || !self.agent.running) && shown.last?["action"]?.str != "stopped" {+ self.traces.write(kind: "step", ["action": .str("stopped")])+ shown.append(["action": .str("stopped")])+ }+ self.agent.showMock(task: task, plan: Self.mockPlan, steps: shown, running: false)+ self.ended()+ }+ }++ /// One finished run in the demo traces folder, so Runs and the replay player have something to show.+ private func writeMockRun() {+ let id = "20261015-071500"+ let dir = traces.root.appendingPathComponent(id)+ guard !FileManager.default.fileExists(atPath: dir.path), let frame = Self.mockFrame else { return }+ try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)+ var lines: [String] = [], n = 0, t = 1_760_483_700.0+ func add(_ kind: String, _ rec: JObject, shot: Bool = false) {+ n += 1+ t += kind == "step" ? 1.6 : 0.9+ var line = JObject([("n", .int(n)), ("t", .num(t)), ("kind", .str(kind))]).merging(rec)+ if shot {+ let name = String(format: "%03d.jpg", n)+ try? frame.write(to: dir.appendingPathComponent(name))+ line["frame"] = .str(name)+ let video = dir.appendingPathComponent("video")+ try? FileManager.default.createDirectory(at: video, withIntermediateDirectories: true)+ try? frame.write(to: video.appendingPathComponent("\(Int(t * 1000)).jpg"))+ }+ lines.append(PyJSON.dumps(line, ascii: false))+ }+ add("task", ["task": .str(IntentStore.examples[0].prompt)])+ for step in Self.mockSteps + [["thought": .str("Every day is checked and the alarm is saved."),+ "action": .str("done"), "answer": .str("The 7:00 AM alarm repeats every day.")]] {+ add("llm", ["role": .str("actor"), "seconds": .num(1.4)], shot: true)+ add("step", step.merging(["think_s": .num(1.4), "act_s": .num(0.5)]))+ }+ try? (lines.joined(separator: "\n") + "\n").write(to: dir.appendingPathComponent("steps.jsonl"),+ atomically: true, encoding: .utf8)+ }++ private static func status(up: Int, n: Int, mirroring: Bool) -> BoardStatus {+ BoardStatus(up: up, rst: "power-on", heap: 81_234 - n % 7 * 120, psram: 6_200_000, usb: "ok",+ net: "ap", ip: "192.168.4.1", sta: 1, ap: mirroring ? "streaming" : "idle", w: 480, h: 1040,+ kbps: Double.random(in: 150...230), fps: Double.random(in: 4.4...5), idr: 2000,+ gop: 42_000 + n % 5 * 3000,+ ble: .init(mtu: 247, phy: 2, kbps: Double.random(in: 320...380), drop: n / 30))+ }++ static let mockPlan = """+ 1. Open the Clock app with Search.+ 2. Go to the Alarms tab and tap +.+ 3. Set the time to 7:00 AM.+ 4. Tap Repeat and check every day.+ 5. Go back and tap Save.+ """++ static let mockSteps: [JObject] = [+ ["action": .str("plan"), "plan": .str(mockPlan)],+ ["thought": .str("I am on the home screen. I tap the Search pill to find Clock."), "action": .str("tap"),+ "x": .int(500), "y": .int(814), "changed": .bool(true)],+ ["action": .str("type"), "text": .str("Clock"), "changed": .bool(true)],+ ["thought": .str("Clock is the top result, so I open it."), "action": .str("tap"), "x": .int(152),+ "y": .int(212), "changed": .bool(true)],+ ["thought": .str("The Alarms tab is open. I tap + to add an alarm."), "action": .str("tap"), "x": .int(905),+ "y": .int(88), "precise": .bool(true), "changed": .bool(true)],+ ["thought": .str("I scroll the hour wheel to 7."), "action": .str("swipe"), "x1": .int(397), "y1": .int(300),+ "x2": .int(397), "y2": .int(200), "changed": .bool(true)],+ ["action": .str("type"), "text": .str("0700"), "changed": .bool(true)],+ ["thought": .str("The time is 07:00. I open Repeat."), "action": .str("tap"), "x": .int(150), "y": .int(395),+ "changed": .bool(true)],+ ["thought": .str("I check every day from Sunday to Saturday."), "action": .str("tap"), "x": .int(210),+ "y": .int(204), "changed": .bool(true)],+ ["action": .str("tap"), "x": .int(210), "y": .int(260), "changed": .bool(true)],+ ["action": .str("tap"), "x": .int(210), "y": .int(315), "changed": .bool(false)],+ ]+}diff --git a/ios/IPhoneAgent/Mock/mock-frame.jpg b/ios/IPhoneAgent/Mock/mock-frame.jpgnew file mode 100644index 0000000..d01a91aBinary files /dev/null and b/ios/IPhoneAgent/Mock/mock-frame.jpg differdiff --git a/ios/IPhoneAgent/Review/ReviewMedia.swift b/ios/IPhoneAgent/Review/ReviewMedia.swiftnew file mode 100644index 0000000..da02089--- /dev/null+++ b/ios/IPhoneAgent/Review/ReviewMedia.swift@@ -0,0 +1,116 @@+import SwiftUI++/// The timeline: a tick per step (green done, red ✗ or problems, yellow unsure, gray plans), filled up to the+/// current step. Drag or tap anywhere on it to jump; VoiceOver adjusts it step by step.+struct ReviewTimeline: View {+ let steps: [DraftStep]+ @Binding var index: Int+ @Binding var playing: Bool++ var body: some View {+ GeometryReader { g in+ let n = max(steps.count, 1)+ let w = g.size.width+ let x = { (i: Int) in n > 1 ? w * CGFloat(i) / CGFloat(n - 1) : w / 2 }+ ZStack(alignment: .leading) {+ Capsule().fill(Color(uiColor: .tertiarySystemFill)).frame(height: 4)+ Capsule().fill(Color.accentColor).frame(width: x(index), height: 4)+ ForEach(Array(steps.enumerated()), id: \.element.id) { i, s in+ Capsule().fill(tint(s, i))+ .frame(width: s.verdict == false ? 5 : 3, height: i == index ? 18 : s.verdict == false ? 14 : 10)+ .position(x: x(i), y: g.size.height / 2)+ }+ Circle().fill(.white).shadow(color: .black.opacity(0.25), radius: 3, y: 1)+ .frame(width: 18, height: 18)+ .position(x: x(index), y: g.size.height / 2)+ }+ .contentShape(Rectangle())+ .gesture(DragGesture(minimumDistance: 0).onChanged { v in+ playing = false+ let i = max(0, min(n - 1, Int(((v.location.x / max(w, 1)) * CGFloat(n - 1)).rounded())))+ if i != index { index = i }+ })+ }+ .frame(height: 32)+ .animation(.spring(response: 0.3, dampingFraction: 0.85), value: index)+ .accessibilityElement()+ .accessibilityLabel(Text("Timeline"))+ .accessibilityValue(Text("Step \(index + 1) of \(steps.count)"))+ .accessibilityAdjustableAction { d in+ playing = false+ index = d == .increment ? min(steps.count - 1, index + 1) : max(0, index - 1)+ }+ }++ private func tint(_ s: DraftStep, _ i: Int) -> Color {+ if s.verdict == false { return Palette.stop }+ if s.uncertain { return .yellow }+ switch s.name {+ case "done": return Palette.ok+ case "fail", "error", "hiccup", "help": return Palette.stop+ case "plan", "replan (stuck)", "stopped", "takeover", "skipped": return Color(uiColor: .systemGray2)+ default: return i <= index ? Color.accentColor : Color(uiColor: .systemGray3)+ }+ }+}++/// The run's low-fps video (frames of the mirror stream), continuous in real time: the frame at `time`+/// (seconds since 1970), with the step running at that moment as a caption. No step screenshots, no overlays.+struct RunVideoView: View {+ let frames: [(url: URL, t: Double)]+ let time: Double+ let caption: String?++ private var current: URL? {+ (frames.last { $0.t <= time } ?? frames.first)?.url+ }++ var body: some View {+ Group {+ if let url = current, let img = UIImage(contentsOfFile: url.path) {+ Image(uiImage: img).resizable().aspectRatio(img.size, contentMode: .fit)+ .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous))+ .overlay(alignment: .bottom) {+ if let caption {+ Text(verbatim: caption).font(.caption.weight(.semibold)).lineLimit(1)+ .padding(.horizontal, 10).padding(.vertical, 5)+ .background(Capsule().fill(.black.opacity(0.6))).foregroundStyle(.white).padding(10)+ }+ }+ } else {+ Text("No video for this run.").foregroundStyle(.secondary)+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .padding(.horizontal, Space.l)+ .padding(.vertical, Space.s)+ }+}++/// The video's scrubber, in seconds (elapsed / total), not steps.+struct VideoScrubber: View {+ let start: Double, end: Double+ @Binding var time: Double+ @Binding var playing: Bool++ var body: some View {+ VStack(spacing: 0) {+ Slider(value: Binding(get: { min(max(time - start, 0), end - start) },+ set: { playing = false; time = start + $0 }),+ in: 0...max(end - start, 0.1))+ HStack {+ Text(verbatim: Self.clock(time - start))+ Spacer()+ Text(verbatim: Self.clock(end - start))+ }+ .font(.caption.monospacedDigit()).foregroundStyle(.secondary)+ }+ .accessibilityElement(children: .combine)+ .accessibilityLabel(Text("Video position"))+ }++ static func clock(_ s: Double) -> String {+ let n = max(0, Int(s.rounded(.down)))+ return String(format: "%d:%02d", n / 60, n % 60)+ }+}diff --git a/ios/IPhoneAgent/Review/ReviewModel.swift b/ios/IPhoneAgent/Review/ReviewModel.swiftnew file mode 100644index 0000000..c12b745--- /dev/null+++ b/ios/IPhoneAgent/Review/ReviewModel.swift@@ -0,0 +1,199 @@+import Foundation++/// One step in the review editor: what was done, on which screenshot, and the user's verdict and fix.+struct DraftStep: Identifiable, Equatable {+ var id = UUID()+ var action: JObject+ var frame: URL?+ var t: Double?+ var verdict: Bool? // true ✓, false ✗, nil = not judged+ var fix: CGPoint? // the right spot, 0-1000 screen units+ var note = "" // "should tap the + at the top right"+ var uncertain = false // inferred from a demonstration and not sure+ var inserted = false // added by the user++ var name: String { action["action"]?.str ?? "" }+ var isMove: Bool { !StepText.notMoves.contains(name) }+}++/// The review editor's document: a run, a demonstration or an intent, the steps with the user's+/// corrections, and the intent being made (name, icon, prompt, checklist). Saved next to its trace.+@MainActor final class ReviewDraft: ObservableObject, Identifiable {+ enum Source { case run, recording, intent }++ let id = UUID()+ let source: Source+ let folder: URL?+ let runID: String?+ let outcome: Outcome?+ @Published var steps: [DraftStep]+ @Published var name: String+ @Published var icon: String+ @Published var prompt: String+ @Published var hints: [String]+ @Published var intentID: UUID?+ /// Open the Save sheet right away (Record › Save last run as intent).+ var showSaveOnOpen = false++ init(source: Source, folder: URL?, runID: String?, outcome: Outcome?, steps: [DraftStep], name: String,+ prompt: String, hints: [String] = [], icon: String = "bolt.fill", intentID: UUID? = nil) {+ self.source = source; self.folder = folder; self.runID = runID; self.outcome = outcome+ self.steps = steps; self.name = name; self.prompt = prompt; self.hints = hints; self.icon = icon+ self.intentID = intentID+ loadEdits()+ }++ /// A finished run; the intent it ran for (if any) fills the name, prompt and checklist.+ convenience init(run: Run, intent: SavedTask? = nil) {+ let steps = run.steps.map { DraftStep(action: $0.action, frame: $0.frame, t: $0.t) }+ self.init(source: intent == nil ? .run : .intent, folder: run.folder, runID: run.id, outcome: run.outcome,+ steps: steps, name: intent?.name ?? "", prompt: intent?.prompt ?? run.task,+ hints: intent?.checklist ?? [], icon: intent?.symbol ?? "bolt.fill", intentID: intent?.id)+ }++ /// An intent without a reference run: only its words to edit.+ convenience init(intent: SavedTask) {+ self.init(source: .intent, folder: nil, runID: nil, outcome: nil, steps: [], name: intent.name,+ prompt: intent.prompt, hints: intent.checklist, icon: intent.symbol, intentID: intent.id)+ }++ /// An imported run: replay only, no edits or intents.+ var readOnly: Bool { folder.map(RunShare.isImported) ?? false }++ var title: String {+ switch source {+ case .run: return prompt+ case .recording: return name.isEmpty ? String(localized: "Demonstration") : name+ case .intent: return name+ }+ }++ // MARK: - editing++ func index(_ id: UUID) -> Int? { steps.firstIndex { $0.id == id } }++ func mark(_ id: UUID, _ ok: Bool?) {+ guard let i = index(id) else { return }+ steps[i].verdict = steps[i].verdict == ok ? nil : ok+ steps[i].uncertain = false+ saveEdits()+ }++ func setFix(_ id: UUID, point: CGPoint?, note: String) {+ guard let i = index(id) else { return }+ steps[i].fix = point+ steps[i].note = note+ if point != nil || !note.isEmpty { steps[i].verdict = false }+ steps[i].uncertain = false+ saveEdits()+ }++ func delete(_ id: UUID) {+ steps.removeAll { $0.id == id }+ saveEdits()+ }++ /// A step written by the user ("then tap Save"), shown on the previous screenshot.+ func insert(after id: UUID?, text: String) {+ let at = id.flatMap(index).map { $0 + 1 } ?? steps.count+ let frame = at > 0 ? steps[at - 1].frame : nil+ steps.insert(DraftStep(action: ["action": .str("note"), "text": .str(text)], frame: frame, inserted: true), at: at)+ saveEdits()+ }++ var corrections: Int { steps.filter { $0.verdict == false || $0.inserted || !$0.note.isEmpty }.count }++ // MARK: - intent++ func intent(existing: SavedTask?) -> SavedTask {+ var item = existing ?? SavedTask(name: "", prompt: "")+ item.name = name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ? String(prompt.prefix(30)) : name+ item.prompt = prompt+ item.icon = icon+ item.hints = hints.filter { !$0.trimmingCharacters(in: .whitespaces).isEmpty }+ item.refRun = runID ?? item.refRun+ return item+ }++ // MARK: - AI optimization++ static let optimizerPrompt = """+ You improve saved tasks for an AI agent that operates an iPhone with a mouse pointer. You get the task, \+ the steps of one run or of a human demonstration, and the user's corrections. Write a clearer instruction \+ and a short checklist of concrete hints that would make the next run succeed (for example "Type the time \+ instead of scrolling the wheel"). Keep the user's language. Reply in this format only:+ PROMPT: <one clear instruction>+ HINTS:+ - <hint>+ (at most 6 hints)+ """++ /// The trace and the corrections, as text for the model.+ func optimizerInput() -> String {+ var lines = ["Task: \(prompt)"]+ if !hints.isEmpty { lines.append("Current hints:\n" + hints.map { "- " + $0 }.joined(separator: "\n")) }+ if let outcome { lines.append("Run outcome: \(outcome)") }+ lines.append("Steps:")+ for (i, s) in steps.enumerated() {+ var line = "\(i + 1). " + PyJSON.dumps(Actions.key(s.action).without(["plan", "plan_zh"]), ascii: false)+ if let t = s.action["thought"]?.str { line += " (thought: \(t.prefix(200)))" }+ if s.inserted { line += " [ADDED BY USER]" }+ if s.verdict == true { line += " [USER: correct]" }+ if s.verdict == false { line += " [USER: wrong]" }+ if let p = s.fix { line += " [USER: the right spot is \(Int(p.x)) \(Int(p.y))]" }+ if !s.note.isEmpty { line += " [USER NOTE: \(s.note)]" }+ if s.action["changed"]?.bool == false { line += " (screen did not change)" }+ lines.append(line)+ }+ return lines.joined(separator: "\n")+ }++ /// PROMPT: … / HINTS: - … ; nil if the reply has no prompt.+ static func parseOptimized(_ reply: String) -> (prompt: String, hints: [String])? {+ var prompt = "", hints: [String] = [], inHints = false+ for raw in reply.split(separator: "\n") {+ let line = raw.trimmingCharacters(in: .whitespaces)+ if line.uppercased().hasPrefix("PROMPT:") {+ prompt = String(line.dropFirst(7)).trimmingCharacters(in: .whitespaces)+ inHints = false+ } else if line.uppercased().hasPrefix("HINTS:") {+ inHints = true+ } else if inHints, line.hasPrefix("-") || line.hasPrefix("•") {+ hints.append(String(line.dropFirst()).trimmingCharacters(in: .whitespaces))+ }+ }+ return prompt.isEmpty ? nil : (prompt, Array(hints.prefix(6)))+ }++ // MARK: - persistence (review.json next to the trace)++ private struct Edits: Codable {+ struct Step: Codable { var action: String; var frame: String?; var t: Double?; var verdict: Bool?+ var fix: CGPoint?; var note: String; var uncertain: Bool; var inserted: Bool }+ var steps: [Step]+ var name: String, prompt: String, hints: [String], icon: String+ }++ private var editsURL: URL? { folder?.appendingPathComponent("review.json") }++ func saveEdits() {+ guard let editsURL else { return }+ let e = Edits(steps: steps.map {+ .init(action: PyJSON.dumps($0.action, ascii: false), frame: $0.frame?.lastPathComponent, t: $0.t,+ verdict: $0.verdict, fix: $0.fix, note: $0.note, uncertain: $0.uncertain, inserted: $0.inserted)+ }, name: name, prompt: prompt, hints: hints, icon: icon)+ try? JSONEncoder().encode(e).write(to: editsURL)+ }++ private func loadEdits() {+ guard let editsURL, let folder, let data = try? Data(contentsOf: editsURL),+ let e = try? JSONDecoder().decode(Edits.self, from: data) else { return }+ steps = e.steps.compactMap { s in+ guard let any = try? JSONSerialization.jsonObject(with: Data(s.action.utf8)),+ case .obj(let action) = PyJSON.from(any) else { return nil }+ return DraftStep(action: action, frame: s.frame.map { folder.appendingPathComponent($0) }, t: s.t,+ verdict: s.verdict, fix: s.fix, note: s.note, uncertain: s.uncertain, inserted: s.inserted)+ }+ if intentID == nil { name = e.name; prompt = e.prompt; hints = e.hints; icon = e.icon }+ }+}diff --git a/ios/IPhoneAgent/Review/ReviewSheets.swift b/ios/IPhoneAgent/Review/ReviewSheets.swiftnew file mode 100644index 0000000..c989380--- /dev/null+++ b/ios/IPhoneAgent/Review/ReviewSheets.swift@@ -0,0 +1,219 @@+import SwiftUI++/// Fix a step: tap where it should have tapped on its screenshot, or write what should have happened.+struct FixSheet: View {+ @ObservedObject var draft: ReviewDraft+ let step: DraftStep+ @Environment(\.dismiss) private var dismiss+ @State private var point: CGPoint?+ @State private var note = ""++ var body: some View {+ NavigationStack {+ Form {+ Section {+ if let url = step.frame, let img = UIImage(contentsOfFile: url.path) {+ GeometryReader { g in+ Image(uiImage: img).resizable().scaledToFit()+ .frame(width: g.size.width, height: g.size.height)+ .overlay { ActionOverlay(action: step.action) }+ .overlay { if let point { FixMarker(point: point) } }+ .contentShape(Rectangle())+ .onTapGesture { p in+ point = CGPoint(x: (p.x / g.size.width * 1000).rounded(),+ y: (p.y / g.size.height * 1000).rounded())+ Haptics.tick()+ }+ }+ .aspectRatio(img.size, contentMode: .fit)+ .frame(maxHeight: 420)+ .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))+ .listRowInsets(EdgeInsets(top: Space.m, leading: Space.m, bottom: Space.m, trailing: Space.m))+ }+ } footer: {+ Text("Tap where it should have tapped. The green target marks it.")+ }+ Section("Note") {+ TextField("e.g. Tap the + at the top right", text: $note, axis: .vertical).lineLimit(2...4)+ }+ if point != nil {+ Section { Button("Clear the Point", role: .destructive) { point = nil } }+ }+ }+ .navigationTitle(Text(verbatim: StepText.title(step.action)))+ .navigationBarTitleDisplayMode(.inline)+ .toolbar {+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+ ToolbarItem(placement: .confirmationAction) {+ Button("Save") {+ draft.setFix(step.id, point: point, note: note.trimmingCharacters(in: .whitespacesAndNewlines))+ Haptics.success()+ dismiss()+ }+ .fontWeight(.semibold)+ }+ }+ .onAppear { point = step.fix; note = step.note }+ }+ }+}++/// The model's improved prompt and checklist next to the current ones; accept or keep editing.+struct OptimizeSheet: View {+ @ObservedObject var draft: ReviewDraft+ @ObservedObject var app: AppModel+ @Environment(\.dismiss) private var dismiss+ @State private var result: (prompt: String, hints: [String])?+ @State private var failure: String?++ var body: some View {+ NavigationStack {+ Group {+ if let result {+ List {+ Section("Before") { words(draft.prompt, draft.hints, muted: true) }+ Section("After") { words(result.prompt, result.hints, muted: false) }+ }+ } else if let failure {+ ContentUnavailableView {+ Label("Could not optimize", systemImage: "exclamationmark.triangle")+ } description: { Text(verbatim: failure) } actions: {+ Button("Try Again") { Task { await run() } }+ }+ } else {+ VStack(spacing: Space.l) {+ AgentFace(mood: .thinking).frame(width: 96, height: 108)+ Text("Learning from \(draft.corrections) corrections…").font(.headline)+ Text("I'm reading the steps and your fixes to write a clearer intent.")+ .font(.subheadline).foregroundStyle(.secondary).multilineTextAlignment(.center)+ }+ .padding(Space.xl)+ .frame(maxHeight: .infinity)+ }+ }+ .navigationTitle("Optimize with AI")+ .navigationBarTitleDisplayMode(.inline)+ .toolbar {+ ToolbarItem(placement: .cancellationAction) { Button("Keep Editing") { dismiss() } }+ ToolbarItem(placement: .confirmationAction) {+ Button("Accept") {+ if let result { draft.prompt = result.prompt; draft.hints = result.hints; draft.saveEdits() }+ Haptics.success()+ dismiss()+ }+ .fontWeight(.semibold)+ .disabled(result == nil)+ }+ }+ .task { await run() }+ }+ }++ private func run() async {+ failure = nil+ do { result = try await app.optimize(draft) } catch { failure = error.localizedDescription }+ }++ private func words(_ prompt: String, _ hints: [String], muted: Bool) -> some View {+ VStack(alignment: .leading, spacing: Space.s) {+ Text(verbatim: prompt).font(.body).foregroundStyle(muted ? .secondary : .primary)+ ForEach(hints, id: \.self) { h in+ Label { Text(verbatim: h) } icon: { Image(systemName: "checkmark.circle") }+ .font(.subheadline).foregroundStyle(muted ? .secondary : .primary)+ }+ }+ .padding(.vertical, Space.xs)+ }+}++/// Save as intent: name, icon, prompt, checklist and the reference run.+struct SaveIntentSheet: View {+ @ObservedObject var draft: ReviewDraft+ @ObservedObject var intents: IntentStore+ var saved: () -> Void = {}+ @Environment(\.dismiss) private var dismiss+ static let icons = ["bolt.fill", "alarm.fill", "message.fill", "note.text", "gearshape.fill", "cart.fill",+ "music.note", "map.fill", "camera.fill", "envelope.fill", "paintbrush.fill", "star.fill"]++ var body: some View {+ NavigationStack {+ Form {+ Section {+ TextField("Name", text: $draft.name, prompt: Text("e.g. Morning alarm"))+ LazyVGrid(columns: Array(repeating: GridItem(.flexible()), count: 6), spacing: Space.m) {+ ForEach(Self.icons, id: \.self) { icon in+ Button { draft.icon = icon; Haptics.tick() } label: {+ SettingsIcon(symbol: icon, color: draft.icon == icon ? .accentColor : Color(uiColor: .systemGray3))+ }+ .buttonStyle(.plain)+ .accessibilityLabel(Text(verbatim: icon))+ .accessibilityAddTraits(draft.icon == icon ? .isSelected : [])+ }+ }+ .padding(.vertical, Space.xs)+ }+ Section("Instruction") {+ TextField("What should the agent do?", text: $draft.prompt, axis: .vertical).lineLimit(2...6)+ }+ ChecklistSection(hints: $draft.hints)+ if let run = draft.runID {+ Section("Reference run") { Label { Text(verbatim: run) } icon: { Image(systemName: "play.rectangle") } }+ }+ }+ .navigationTitle(draft.intentID == nil ? "Save as Intent" : "Save Intent")+ .navigationBarTitleDisplayMode(.inline)+ .toolbar {+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+ ToolbarItem(placement: .confirmationAction) {+ Button("Save") {+ let item = draft.intent(existing: intents.item(draft.intentID))+ intents.upsert(item)+ draft.intentID = item.id+ draft.saveEdits()+ Haptics.success()+ dismiss()+ saved()+ }+ .fontWeight(.semibold)+ .disabled(draft.prompt.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)+ }+ }+ }+ }+}++/// The checklist: one hint per row, add and swipe to delete.+struct ChecklistSection: View {+ @Binding var hints: [String]++ var body: some View {+ Section {+ ForEach(hints.indices, id: \.self) { i in+ TextField("Hint", text: Binding(get: { hints[safe: i] ?? "" }, set: { if hints.indices.contains(i) { hints[i] = $0 } }))+ }+ .onDelete { hints.remove(atOffsets: $0) }+ Button { hints.append("") } label: { Label("Add Hint", systemImage: "plus.circle.fill") }+ } header: {+ Text("Checklist")+ } footer: {+ Text("Given to the agent as hints every time this intent runs.")+ }+ }+}++/// An intent with no recorded steps yet: just its words.+struct IntentWordsView: View {+ @ObservedObject var draft: ReviewDraft++ var body: some View {+ Form {+ Section("Instruction") {+ TextField("What should the agent do?", text: $draft.prompt, axis: .vertical).lineLimit(2...8)+ }+ ChecklistSection(hints: $draft.hints)+ Section {+ Text("Run it once to get steps you can review and fix here.").foregroundStyle(.secondary)+ }+ }+ }+}diff --git a/ios/IPhoneAgent/Review/ReviewView.swift b/ios/IPhoneAgent/Review/ReviewView.swiftnew file mode 100644index 0000000..bc33bd0--- /dev/null+++ b/ios/IPhoneAgent/Review/ReviewView.swift@@ -0,0 +1,349 @@+import SwiftUI++/// Review and editor, one screen for a finished run, a demonstration and an intent: media on top (step+/// screenshots with overlays, or the run video), the timeline below, and per step ✓ / ✗, Fix, Insert after,+/// Delete and Re-run from here. "Optimize with AI" and "Save as Intent" are pinned at the bottom.+struct ReviewView: View {+ @ObservedObject var draft: ReviewDraft+ @ObservedObject var app: AppModel+ @Environment(\.dismiss) private var dismiss+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @State private var index = 0+ @State private var playing = false+ @State private var speed = 1.0+ @State private var showVideo = false+ @State private var videoTime = 0.0+ @State private var expanded = false+ @State private var fixing: DraftStep?+ @State private var inserting = false+ @State private var insertText = ""+ @State private var saving = false+ @State private var optimizing = false+ @State private var shareURL: URL?++ private var steps: [DraftStep] { draft.steps }+ private var step: DraftStep? { steps.indices.contains(index) ? steps[index] : nil }+ @State private var video: [(url: URL, t: Double)] = []++ var body: some View {+ VStack(spacing: 0) {+ topBar+ if steps.isEmpty {+ IntentWordsView(draft: draft)+ } else {+ if !video.isEmpty {+ Picker("View", selection: $showVideo) {+ Text("Steps").tag(false)+ Text("Video").tag(true)+ }+ .pickerStyle(.segmented)+ .padding(.horizontal, Space.xl)+ .padding(.bottom, Space.xs)+ }+ if showVideo && !video.isEmpty { // continuous video, scrubbed in seconds+ RunVideoView(frames: video, time: videoTime, caption: step.map { StepText.title($0.action) })+ VideoScrubber(start: video[0].t, end: video[video.count - 1].t, time: $videoTime, playing: $playing)+ .padding(.horizontal, Space.xl)+ controls+ } else { // one screenshot per step, with its action drawn on it+ media+ stepCard+ ReviewTimeline(steps: steps, index: $index, playing: $playing).padding(.horizontal, Space.xl)+ controls+ }+ }+ }+ .background(Color(uiColor: .systemBackground).ignoresSafeArea())+ .safeAreaInset(edge: .bottom) { if !draft.readOnly { bottomBar } }+ .task(id: [playing, showVideo]) { await autoplay() }+ .onChange(of: showVideo) { playing = false }+ .onChange(of: videoTime) { _, t in // the step follows the video+ guard showVideo, let i = steps.lastIndex(where: { ($0.t ?? 0) <= t }), i != index else { return }+ index = i+ }+ .onChange(of: index) { _, i in+ Haptics.tick()+ if !playing, let t = steps[safe: i]?.t { videoTime = t }+ }+ .onAppear {+ video = draft.runID.flatMap { app.runs.run($0) }?.video ?? []+ videoTime = steps.first?.t ?? 0+ if let firstUnsure = steps.firstIndex(where: \.uncertain) { index = firstUnsure }+ if draft.showSaveOnOpen { saving = true; draft.showSaveOnOpen = false }+ }+ .sheet(item: $fixing) { s in FixSheet(draft: draft, step: s) }+ .sheet(isPresented: $saving) { SaveIntentSheet(draft: draft, intents: app.intents) { dismiss() } }+ .sheet(isPresented: $optimizing) { OptimizeSheet(draft: draft, app: app) }+ .sheet(item: $shareURL) { ShareSheet(items: [$0]) }+ .alert("Insert a step", isPresented: $inserting) {+ TextField("e.g. Tap Save at the top right", text: $insertText)+ Button("Insert") {+ draft.insert(after: step?.id, text: insertText)+ index = min(index + 1, steps.count - 1)+ }+ Button("Cancel", role: .cancel) {}+ } message: {+ Text("Describe what should happen after this step.")+ }+ }++ // MARK: - top++ private var topBar: some View {+ HStack(spacing: Space.m) {+ Button { dismiss() } label: {+ Image(systemName: "xmark.circle.fill").font(.system(size: 32)).symbolRenderingMode(.hierarchical)+ .frame(width: 44, height: 44).contentShape(Rectangle())+ }+ .tint(.secondary)+ .accessibilityLabel(Text("Close"))+ VStack(alignment: .leading, spacing: 2) {+ Text(verbatim: draft.title).font(.headline).lineLimit(1)+ subtitle.font(.caption)+ }+ Spacer()+ Menu {+ if let folder = draft.folder {+ Button { shareURL = try? TraceStore.zip(folder) } label: {+ Label("Export trace", systemImage: "square.and.arrow.up")+ }+ }+ Button { inserting = true; insertText = "" } label: { Label("Add a step at the end", systemImage: "plus") }+ } label: {+ Image(systemName: "ellipsis.circle").font(.title2)+ }+ }+ .padding(.horizontal, Space.l)+ .padding(.vertical, Space.s)+ }++ @ViewBuilder private var subtitle: some View {+ switch draft.source {+ case .recording: Label("Demonstration · check the yellow steps", systemImage: "record.circle").foregroundStyle(.secondary)+ case .intent: Label("Intent", systemImage: draft.icon).foregroundStyle(.secondary)+ case .run:+ if draft.readOnly { Label("Imported", systemImage: "square.and.arrow.down").foregroundStyle(.secondary) }+ else if let o = draft.outcome { OutcomeLabel(outcome: o) }+ }+ }++ // MARK: - media and step++ private var media: some View {+ TabView(selection: $index) {+ ForEach(Array(steps.enumerated()), id: \.element.id) { i, s in+ StepFrame(step: s, active: i == index).tag(i).padding(.horizontal, Space.l)+ }+ }+ .tabViewStyle(.page(indexDisplayMode: .never))+ }++ @ViewBuilder private var stepCard: some View {+ if let step {+ VStack(alignment: .leading, spacing: Space.s) {+ HStack(spacing: Space.s) {+ Image(systemName: StepText.symbol(step.name)).foregroundStyle(.secondary)+ Text(verbatim: StepText.title(step.action)).font(.headline).lineLimit(1)+ if step.uncertain {+ Text("Unsure").font(.caption2.weight(.bold)).padding(.horizontal, 6).padding(.vertical, 2)+ .background(Capsule().fill(Color.yellow.opacity(0.35)))+ }+ Spacer()+ if !draft.readOnly { verdictButtons(step) }+ }+ if let thought = step.action["thought"]?.str ?? step.action["plan"]?.str ?? step.action["reason"]?.str {+ Text(verbatim: thought).font(.subheadline).foregroundStyle(.secondary).lineLimit(expanded ? nil : 2)+ .onTapGesture { withAnimation(.spring(response: 0.35, dampingFraction: 0.85)) { expanded.toggle() } }+ }+ if !step.note.isEmpty {+ Label { Text(verbatim: step.note) } icon: { Image(systemName: "pencil.line") }+ .font(.subheadline).foregroundStyle(Palette.ok)+ }+ if expanded { StepDetails(step: step) }+ if !draft.readOnly { stepActions(step) }+ }+ .padding(Space.l)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 14, style: .continuous).fill(Palette.surface))+ .padding(.horizontal, Space.l)+ .padding(.vertical, Space.s)+ }+ }++ private func verdictButtons(_ step: DraftStep) -> some View {+ HStack(spacing: Space.s) {+ Button { draft.mark(step.id, true); Haptics.tick() } label: {+ Image(systemName: step.verdict == true ? "checkmark.circle.fill" : "checkmark.circle")+ .foregroundStyle(step.verdict == true ? Palette.ok : .secondary)+ }+ .accessibilityLabel(Text("Correct"))+ Button { draft.mark(step.id, false); Haptics.tick() } label: {+ Image(systemName: step.verdict == false ? "xmark.circle.fill" : "xmark.circle")+ .foregroundStyle(step.verdict == false ? Palette.stop : .secondary)+ }+ .accessibilityLabel(Text("Wrong"))+ }+ .font(.title2)+ .buttonStyle(.plain)+ }++ private func stepActions(_ step: DraftStep) -> some View {+ HStack(spacing: Space.s) {+ Button { fixing = step } label: { Label("Fix", systemImage: "scope") }+ Button { inserting = true; insertText = "" } label: { Label("Insert", systemImage: "plus") }+ Spacer()+ Menu {+ if draft.source != .recording {+ Button { rerun(from: step) } label: { Label("Re-run from here", systemImage: "arrow.clockwise") }+ }+ Button(role: .destructive) {+ draft.delete(step.id)+ index = min(index, max(0, steps.count - 1))+ } label: { Label("Delete step", systemImage: "trash") }+ } label: {+ Image(systemName: "ellipsis").frame(width: 32, height: 28)+ }+ .accessibilityLabel(Text("More"))+ }+ .font(.subheadline.weight(.semibold))+ .buttonStyle(.bordered)+ .controlSize(.small)+ }++ // MARK: - playback++ private var controls: some View {+ HStack {+ Menu {+ Picker("Speed", selection: $speed) {+ Text(verbatim: "0.5×").tag(0.5)+ Text(verbatim: "1×").tag(1.0)+ Text(verbatim: "2×").tag(2.0)+ }+ } label: {+ Text(verbatim: speed == 0.5 ? "0.5×" : speed == 2 ? "2×" : "1×")+ .font(.subheadline.weight(.semibold).monospacedDigit())+ .frame(width: 52, height: 32)+ .background(Capsule().fill(Palette.surface))+ }+ .accessibilityLabel(Text("Playback speed"))+ Spacer()+ if videoMode {+ Button { seek(-5) } label: { Image(systemName: "gobackward.5") }.accessibilityLabel(Text("Back 5 seconds"))+ } else {+ Button { go(-1) } label: { Image(systemName: "backward.end.fill") }+ .disabled(index == 0).accessibilityLabel(Text("Previous step"))+ }+ Button {+ if videoMode {+ if videoTime >= video[video.count - 1].t { videoTime = video[0].t }+ } else if index >= steps.count - 1 { index = 0 }+ playing.toggle()+ } label: {+ Image(systemName: playing ? "pause.circle.fill" : "play.circle.fill").font(.system(size: 44))+ }+ .padding(.horizontal, Space.m)+ .accessibilityLabel(Text(playing ? "Pause" : "Play"))+ if videoMode {+ Button { seek(5) } label: { Image(systemName: "goforward.5") }.accessibilityLabel(Text("Forward 5 seconds"))+ } else {+ Button { go(1) } label: { Image(systemName: "forward.end.fill") }+ .disabled(index >= steps.count - 1).accessibilityLabel(Text("Next step"))+ }+ Spacer()+ Text(verbatim: "\(index + 1)/\(steps.count)")+ .font(.subheadline.monospacedDigit()).foregroundStyle(.secondary).frame(width: 52)+ }+ .font(.title3)+ .padding(.horizontal, Space.xl)+ .padding(.bottom, Space.xs)+ }++ private func go(_ d: Int) {+ playing = false+ withAnimation(.spring(response: 0.4, dampingFraction: 0.9)) { index = max(0, min(steps.count - 1, index + d)) }+ }++ private var videoMode: Bool { showVideo && !video.isEmpty }++ private func seek(_ seconds: Double) {+ playing = false+ videoTime = min(max(videoTime + seconds, video[0].t), video[video.count - 1].t)+ }++ private func autoplay() async {+ if videoMode { return await playVideo() }+ while playing && !Task.isCancelled {+ try? await Task.sleep(nanoseconds: UInt64(1_200_000_000 / speed))+ guard playing, !Task.isCancelled else { return }+ if index >= steps.count - 1 { playing = false; return }+ withAnimation(reduceMotion ? .none : .spring(response: 0.45, dampingFraction: 0.9)) { index += 1 }+ }+ }++ /// Video view: a clock runs at real time (times the speed); the frame and the step follow it.+ private func playVideo() async {+ guard let end = video.last?.t else { return }+ var last = now()+ while playing && !Task.isCancelled && videoTime < end {+ try? await Task.sleep(nanoseconds: 66_000_000) // ~15 fps of clock; frames change at their own times+ guard playing else { return }+ videoTime = min(end, videoTime + (now() - last) * speed)+ last = now()+ }+ playing = false+ }++ // MARK: - bottom++ private var bottomBar: some View {+ BottomBar {+ HStack(spacing: Space.m) {+ Button { optimizing = true } label: { Label("Optimize with AI", systemImage: "sparkles") }+ .buttonStyle(BigButton(tint: Color(uiColor: .systemIndigo)))+ Button { saving = true } label: {+ Label(draft.intentID == nil ? "Save as Intent" : "Save Intent", systemImage: "bookmark.fill")+ }+ .buttonStyle(BigButton())+ }+ }+ }++ private func rerun(from step: DraftStep) {+ let intent = app.intents.item(draft.intentID)+ let task = draft.prompt + "\n\n" + String(localized: "Start from this step: \(StepText.title(step.action)). The steps before it are already done.")+ dismiss()+ Task { await app.run(task, intent: intent) }+ }+}++/// THINK / DO / CHANGED / TIME of one step.+struct StepDetails: View {+ let step: DraftStep++ var body: some View {+ VStack(alignment: .leading, spacing: Space.xs) {+ Divider().padding(.vertical, Space.xs)+ if let t = step.action["thought"]?.str { row("THINK", t) }+ row("DO", PyJSON.dumps(Actions.key(step.action).without(["plan", "plan_zh"]), ascii: false))+ if let c = step.action["changed"]?.bool { row("CHANGED", c ? "yes" : "no") }+ let think = step.action["think_s"]?.double, act = step.action["act_s"]?.double+ if think != nil || act != nil {+ row("TIME", [think.map { String(format: "model %.1f s", $0) }, act.map { String(format: "action %.1f s", $0) }]+ .compactMap { $0 }.joined(separator: " · "))+ }+ }+ }++ private func row(_ key: String, _ value: String) -> some View {+ HStack(alignment: .firstTextBaseline, spacing: Space.s) {+ Text(verbatim: key).font(.caption2.weight(.bold).monospaced()).foregroundStyle(.secondary)+ .frame(width: 58, alignment: .leading)+ Text(verbatim: value).font(.caption.monospaced()).textSelection(.enabled)+ }+ }+}++extension Array {+ subscript(safe i: Int) -> Element? { indices.contains(i) ? self[i] : nil }+}diff --git a/ios/IPhoneAgent/Review/StepFrame.swift b/ios/IPhoneAgent/Review/StepFrame.swiftnew file mode 100644index 0000000..f400c98--- /dev/null+++ b/ios/IPhoneAgent/Review/StepFrame.swift@@ -0,0 +1,229 @@+import SwiftUI++/// One review page: the screenshot the model decided on, with its action drawn on top (tap ripple, swipe+/// trail, typed-text bubble) and the user's fix (a green target). Coordinates are 0-1000 screen units.+struct StepFrame: View {+ let step: DraftStep+ var active = true+ private var moves: Bool { step.isMove || step.name == "note" }++ var body: some View {+ Group {+ if let url = step.frame, let img = UIImage(contentsOfFile: url.path) {+ Image(uiImage: img)+ .resizable()+ .aspectRatio(img.size, contentMode: .fit)+ .overlay { if moves { ActionOverlay(action: step.action, active: active) } }+ .overlay { if let fix = step.fix { FixMarker(point: fix) } }+ .overlay {+ if step.verdict == false {+ RoundedRectangle(cornerRadius: 18, style: .continuous).stroke(Palette.stop, lineWidth: 3)+ } else if step.uncertain {+ RoundedRectangle(cornerRadius: 18, style: .continuous).stroke(Color.yellow, lineWidth: 3)+ }+ }+ .overlay(alignment: .bottom) { if moves { bubble } }+ .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous))+ .overlay(RoundedRectangle(cornerRadius: 18, style: .continuous).stroke(Color(uiColor: .separator), lineWidth: 0.5))+ .shadow(color: .black.opacity(0.12), radius: 10, y: 4)+ } else {+ RoundedRectangle(cornerRadius: 18, style: .continuous).fill(Color(uiColor: .tertiarySystemFill))+ .aspectRatio(9 / 19.5, contentMode: .fit)+ .overlay(Image(systemName: StepText.symbol(step.name)).font(.largeTitle).foregroundStyle(.secondary))+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .padding(.vertical, Space.s)+ .accessibilityElement()+ .accessibilityLabel(Text(verbatim: StepText.title(step.action)))+ }++ /// Typed text, keys and navigation shown as a bubble near the bottom.+ @ViewBuilder private var bubble: some View {+ let a = step.action+ switch step.name {+ case "type": Bubble(symbol: "keyboard", text: a["text"]?.str ?? "")+ case "key": Bubble(symbol: "command", text: a["combo"]?.str ?? "")+ case "home": Bubble(symbol: "house.fill", text: String(localized: "Home"))+ case "back": Bubble(symbol: "chevron.backward", text: String(localized: "Back"))+ case "wait": Bubble(symbol: "hourglass", text: String(localized: "Wait"))+ case "note": Bubble(symbol: "text.bubble", text: a["text"]?.str ?? "")+ default: EmptyView()+ }+ }+}++private struct Bubble: View {+ let symbol: String+ let text: String++ var body: some View {+ Label { Text(verbatim: text).lineLimit(2) } icon: { Image(systemName: symbol) }+ .font(.callout.weight(.semibold))+ .foregroundStyle(.white)+ .padding(.horizontal, Space.l)+ .padding(.vertical, Space.s)+ .background(Capsule().fill(Color.black.opacity(0.75)))+ .padding(.bottom, Space.xl)+ .transition(.scale(scale: 0.8).combined(with: .opacity))+ }+}++/// Taps, swipes, paths and circles drawn in the image's own coordinate space.+struct ActionOverlay: View {+ let action: JObject+ var active = true+ @State private var t: CGFloat = 0+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ var body: some View {+ GeometryReader { g in+ let size = g.size+ let p = { (x: Double, y: Double) in CGPoint(x: x / 1000 * size.width, y: y / 1000 * size.height) }+ let n = { (k: String) in action[k]?.double ?? 0 }+ switch action["action"]?.str {+ case "tap":+ Ripple(t: t).position(p(n("x"), n("y")))+ case "swipe":+ Trail(points: [p(n("x1"), n("y1")), p(n("x2"), n("y2"))], t: t)+ case "path":+ Trail(points: points(action).map { p($0.x, $0.y) }, t: t)+ case "circle":+ let r = n("r") / 1000 * size.width+ Circle().trim(from: 0, to: t)+ .stroke(ink, style: StrokeStyle(lineWidth: 5, lineCap: .round))+ .frame(width: r * 2, height: r * 2)+ .position(p(n("x"), n("y")))+ .shadow(color: .black.opacity(0.4), radius: 2)+ default:+ EmptyView()+ }+ }+ .allowsHitTesting(false)+ .onAppear { if active { play() } }+ .onChange(of: active) { _, on in if on { play() } }+ }++ /// Draws the action in each time its step comes up.+ private func play() {+ guard !reduceMotion else { t = 1; return }+ t = 0+ withAnimation(.easeOut(duration: 0.6).delay(0.1)) { t = 1 }+ }+}++/// Action marks are red: they must stand out on any screenshot, whatever the accent colour.+private let ink = Color.red++/// A tap: three rings pulsing out from a solid red ring, and a pointing hand that keeps pressing the spot.+private struct Ripple: View {+ let t: CGFloat+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ var body: some View {+ TimelineView(.animation(paused: reduceMotion)) { tl in+ let time = tl.date.timeIntervalSinceReferenceDate+ ZStack {+ ForEach(0..<3, id: \.self) { i in // staggered pulses, one every 0.4 s+ let p = CGFloat((time / 1.2 + Double(i) / 3).truncatingRemainder(dividingBy: 1))+ Circle().stroke(ink, lineWidth: 3)+ .frame(width: 30, height: 30)+ .scaleEffect(1 + 1.4 * p)+ .opacity(Double(1 - p) * Double(t))+ }+ Circle().stroke(Color.white, lineWidth: 7).frame(width: 30, height: 30)+ Circle().stroke(ink, lineWidth: 4).frame(width: 30, height: 30)+ Circle().fill(ink).frame(width: 8, height: 8)+ Hand(press: reduceMotion ? 0 : CGFloat(max(0, sin(time * 2 * .pi / 1.2))))+ .offset(x: 4, y: 26)+ .opacity(min(1, 2 * t))+ }+ .shadow(color: .black.opacity(0.35), radius: 3)+ }+ }+}++/// 👆 with its fingertip at the anchor; press 0-1 nudges it in and shrinks it a little, like tapping.+private struct Hand: View {+ var press: CGFloat = 0++ var body: some View {+ Text(verbatim: "👆").font(.system(size: 34))+ .scaleEffect(1 - 0.08 * press, anchor: .top)+ .offset(y: -4 * press)+ }+}++/// A swipe or drag: the path drawn in (red on a white edge), a ring where the finger starts, an arrowhead+/// where it ends, and a hand that keeps sliding along it.+private struct Trail: View {+ let points: [CGPoint]+ let t: CGFloat+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ var body: some View {+ TimelineView(.animation(paused: reduceMotion)) { tl in+ let loop = CGFloat((tl.date.timeIntervalSinceReferenceDate / 1.6).truncatingRemainder(dividingBy: 1))+ ZStack {+ path.trim(from: 0, to: t)+ .stroke(Color.white, style: StrokeStyle(lineWidth: 10, lineCap: .round, lineJoin: .round))+ path.trim(from: 0, to: t)+ .stroke(ink, style: StrokeStyle(lineWidth: 6, lineCap: .round, lineJoin: .round))+ if let first = points.first {+ Circle().fill(Color.white).frame(width: 18, height: 18)+ .overlay(Circle().stroke(ink, lineWidth: 4))+ .position(first)+ }+ if points.count >= 2, let last = points.last {+ let prev = points[points.count - 2]+ Image(systemName: "arrowtriangle.up.fill")+ .font(.system(size: 18))+ .foregroundStyle(ink)+ .rotationEffect(.radians(atan2(last.y - prev.y, last.x - prev.x) + .pi / 2))+ .position(last)+ .opacity(Double(t))+ Hand()+ .position(at(reduceMotion ? 1 : min(t, loop)))+ .offset(x: 4, y: 26)+ .opacity(Double(t))+ }+ }+ .shadow(color: .black.opacity(0.4), radius: 2)+ }+ }++ private var path: Path {+ Path { path in+ guard let first = points.first else { return }+ path.move(to: first)+ points.dropFirst().forEach { path.addLine(to: $0) }+ }+ }++ /// The point a fraction f of the way along the polyline.+ private func at(_ f: CGFloat) -> CGPoint {+ let segs = zip(points, points.dropFirst()).map { ($0, $1, hypot($1.x - $0.x, $1.y - $0.y)) }+ var left = f * segs.reduce(0) { $0 + $1.2 }+ for (a, b, len) in segs {+ if left <= len, len > 0 { return CGPoint(x: a.x + (b.x - a.x) * left / len, y: a.y + (b.y - a.y) * left / len) }+ left -= len+ }+ return points.last ?? .zero+ }+}++/// Where the user says the tap should have gone.+struct FixMarker: View {+ let point: CGPoint++ var body: some View {+ GeometryReader { g in+ Image(systemName: "scope")+ .font(.system(size: 30, weight: .bold))+ .foregroundStyle(Palette.ok)+ .shadow(color: .black.opacity(0.4), radius: 2)+ .position(x: point.x / 1000 * g.size.width, y: point.y / 1000 * g.size.height)+ }+ .allowsHitTesting(false)+ }+}diff --git a/ios/IPhoneAgent/Services/DebugLog.swift b/ios/IPhoneAgent/Services/DebugLog.swiftnew file mode 100644index 0000000..b3ee1e2--- /dev/null+++ b/ios/IPhoneAgent/Services/DebugLog.swift@@ -0,0 +1,58 @@+import Foundation++/// A rolling text log in Documents/debug.log (pull it with `devicectl device copy from … appDataContainer`+/// or share it from About › Logs). One timestamped line per event; at 2 MB it rolls to debug.1.log.+/// Secrets are redacted before writing.+enum DebugLog {+ static let url = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]+ .appendingPathComponent("debug.log")+ private static let old = url.deletingLastPathComponent().appendingPathComponent("debug.1.log")+ private static let limit = 2_000_000+ private static let queue = DispatchQueue(label: "debug-log")+ nonisolated(unsafe) private static var secrets: [String] = []+ private static let lock = NSLock()+ /// Each (redacted) line also goes here, on the caller's thread (the app relays it to the Mac harness).+ nonisolated(unsafe) static var relay: ((String) -> Void)?+ private static let stamp: ISO8601DateFormatter = {+ let f = ISO8601DateFormatter()+ f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]+ return f+ }()++ /// Strings never to write (e.g. the API key); replaced by "‹redacted›".+ static func redact(_ values: [String]) {+ let keep = values.filter { $0.count >= 6 }+ lock.lock(); secrets = keep; lock.unlock()+ }++ /// The last n lines of debug.log (after pending writes).+ static func tail(_ n: Int) -> [String] {+ queue.sync {+ guard let text = try? String(contentsOf: url, encoding: .utf8) else { return [] }+ return Array(text.split(separator: "\n").suffix(max(0, n)).map(String.init))+ }+ }++ static func write(_ text: String) {+ let time = Date()+ lock.lock(); let hidden = secrets; lock.unlock()+ var line = text+ for s in hidden { line = line.replacingOccurrences(of: s, with: "‹redacted›") }+ relay?(line)+ queue.async {+ let data = Data("\(stamp.string(from: time)) \(line)\n".utf8)+ let fm = FileManager.default+ if let size = (try? fm.attributesOfItem(atPath: url.path)[.size]) as? Int, size > limit {+ try? fm.removeItem(at: old)+ try? fm.moveItem(at: url, to: old)+ }+ if let h = try? FileHandle(forWritingTo: url) {+ h.seekToEndOfFile()+ h.write(data)+ try? h.close()+ } else {+ try? data.write(to: url)+ }+ }+ }+}diff --git a/ios/IPhoneAgent/Services/LLMClient.swift b/ios/IPhoneAgent/Services/LLMClient.swiftnew file mode 100644index 0000000..41ccb34--- /dev/null+++ b/ios/IPhoneAgent/Services/LLMClient.swift@@ -0,0 +1,216 @@+import Foundation++struct ChatResult {+ var text: String+ var firstToken: Double? // seconds until the first streamed token+ var total: Double+ var finishReason: String? // "stop", "length" (max tokens hit), …+ var usage: [String: Int] = [:] // prompt_tokens, completion_tokens, … when the server sends them+ var reasoningChars = 0 // reasoning_content the model wrote (not part of `text`)+ var rawChars = 0 // content before trimming+ var retried = false // the first reply was empty++ /// For the trace and the debug log: why a reply came back empty or cut.+ var diagnostics: JObject {+ var d: JObject = ["finish_reason": .str(finishReason ?? "-"), "reasoning_chars": .int(reasoningChars),+ "raw_chars": .int(rawChars)]+ if !usage.isEmpty { d["usage"] = .obj(JObject(usage.sorted { $0.key < $1.key }.map { ($0.key, .int($0.value)) })) }+ if retried { d["retried_empty"] = .bool(true) }+ if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && reasoningChars > 0 {+ d["note"] = .str("empty content, reasoning only")+ }+ return d+ }+}++/// A chat model the agent can ask (LLMClient, or a fake in tests).+@MainActor protocol ChatModel: AnyObject {+ var model: String { get }+ func chat(system: String, text: String, image: Data?, maxTokens: Int, temperature: Double) async throws -> ChatResult+}++struct LLMError: LocalizedError {+ let message: String+ var errorDescription: String? { message }+}++/// Client for any OpenAI-compatible chat endpoint (vision models). Port of llm.py, with streaming:+/// Cloudflare cuts requests that send nothing for ~100 s, so replies are streamed (SSE). A server that+/// ignores `stream` and answers with plain JSON works too.+@MainActor final class LLMClient: ChatModel {+ static let tokenParams = ["max_tokens", "max_completion_tokens"]++ let model: String+ let baseURL: URL+ private let apiKey: String+ private let extra: [String: Any]+ private(set) var tokenParam: String+ private var auto: Bool+ private let session: URLSession++ init(baseURL: String, model: String, apiKey: String = "", extra: [String: Any] = [:],+ tokenParam: String = "auto", session: URLSession? = nil) {+ var trimmed = baseURL+ while trimmed.hasSuffix("/") { trimmed.removeLast() }+ self.baseURL = URL(string: trimmed) ?? URL(string: "http://invalid")!+ self.model = model+ self.apiKey = apiKey+ self.extra = extra+ // "auto": send max_tokens; switch for good if the server asks for max_completion_tokens+ if Self.tokenParams.contains(tokenParam) { (self.tokenParam, auto) = (tokenParam, false) }+ else { (self.tokenParam, auto) = ("max_tokens", true) }+ self.session = session ?? {+ let config = URLSessionConfiguration.default+ config.timeoutIntervalForRequest = 30 // no byte for this long = hung; the agent retries+ config.timeoutIntervalForResource = 90+ return URLSession(configuration: config)+ }()+ }++ func chat(system: String, text: String, image: Data? = nil, maxTokens: Int = 600,+ temperature: Double = 0) async throws -> ChatResult {+ try await chat(system: system, text: text, images: image.map { [$0] } ?? [], maxTokens: maxTokens,+ temperature: temperature)+ }++ /// Several screenshots in order (a demonstration's keyframes), then the text. An empty reply is asked once more.+ func chat(system: String, text: String, images: [Data], maxTokens: Int = 600,+ temperature: Double = 0) async throws -> ChatResult {+ let first = try await once(system: system, text: text, images: images, maxTokens: maxTokens, temperature: temperature)+ guard first.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return first }+ DebugLog.write("llm: empty reply (finish \(first.finishReason ?? "-"), reasoning \(first.reasoningChars) chars); asking once more")+ var again = try await once(system: system, text: text, images: images, maxTokens: maxTokens, temperature: temperature)+ again.retried = true+ again.total += first.total+ return again+ }++ private func once(system: String, text: String, images: [Data], maxTokens: Int,+ temperature: Double) async throws -> ChatResult {+ var content: [[String: Any]] = images.map {+ ["type": "image_url", "image_url": ["url": "data:image/jpeg;base64," + $0.base64EncodedString()]]+ }+ content.append(["type": "text", "text": text])+ var body: [String: Any] = ["model": model, "temperature": temperature]+ extra.forEach { body[$0.key] = $0.value }+ body["messages"] = [["role": "system", "content": system], ["role": "user", "content": content]]+ body["stream"] = true++ let started = now()+ let kb = images.reduce(0) { $0 + $1.count } / 1024+ DebugLog.write("llm → \(model): \(images.count) image(s) \(kb) KB, \(text.count) chars")+ var status = 0, result: ChatResult?, errorText = ""+ do {+ (status, result, errorText) = try await post(body, maxTokens: maxTokens, started: started)+ if status == 400 && auto && errorText.contains("max_completion_tokens") {+ (tokenParam, auto) = ("max_completion_tokens", false)+ (status, result, errorText) = try await post(body, maxTokens: maxTokens, started: started)+ }+ } catch {+ DebugLog.write(String(format: "llm ✗ %@ after %.1f s: %@", model, now() - started, error.localizedDescription))+ throw error+ }+ guard (200..<300).contains(status), var result else {+ DebugLog.write(String(format: "llm ✗ HTTP %d after %.1f s: %@", status, now() - started, String(errorText.prefix(200))))+ throw LLMError(message: "LLM HTTP \(status): \(errorText.prefix(300))")+ }+ result.total = now() - started+ DebugLog.write(String(format: "llm ← HTTP %d, first token %@, total %.1f s, %d chars", status,+ result.firstToken.map { String(format: "%.1f s", $0) } ?? "-", result.total, result.text.count)+ + " " + PyJSON.dumps(.obj(result.diagnostics)))+ return result+ }++ /// The first model id from GET {base}/models.+ static func firstModel(baseURL: String, apiKey: String) async throws -> String {+ guard let id = try await models(baseURL: baseURL, apiKey: apiKey).first else {+ throw LLMError(message: "the endpoint lists no models; type a model id in Settings › Model")+ }+ return id+ }++ /// The model ids from GET {base}/models (OpenAI list format: {"data": [{"id": ...}]}), in the endpoint's order.+ static func models(baseURL: String, apiKey: String) async throws -> [String] {+ var trimmed = baseURL+ while trimmed.hasSuffix("/") { trimmed.removeLast() }+ guard let base = URL(string: trimmed) else { throw LLMError(message: "invalid base URL") }+ var request = URLRequest(url: base.appendingPathComponent("models"), timeoutInterval: 20)+ if !apiKey.isEmpty { request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization") }+ let (data, response) = try await URLSession.shared.data(for: request)+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0+ guard (200..<300).contains(status) else {+ throw LLMError(message: "GET /models: HTTP \(status) \(String(decoding: data.prefix(200), as: UTF8.self))")+ }+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any]+ let list = (json?["data"] as? [[String: Any]]) ?? (json?["models"] as? [[String: Any]]) ?? []+ var seen = Set<String>()+ return list.compactMap { ($0["id"] ?? $0["name"]) as? String }.filter { !$0.isEmpty && seen.insert($0).inserted }+ }++ private func post(_ body: [String: Any], maxTokens: Int, started: Double) async throws+ -> (Int, ChatResult?, String) {+ var body = body+ body[tokenParam] = maxTokens+ var request = URLRequest(url: baseURL.appendingPathComponent("chat/completions"))+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")+ if !apiKey.isEmpty { request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization") }+ request.httpBody = try JSONSerialization.data(withJSONObject: body)++ let (bytes, response) = try await session.bytes(for: request)+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0+ let type = (response as? HTTPURLResponse)?.value(forHTTPHeaderField: "Content-Type") ?? ""+ DebugLog.write(String(format: "llm headers: HTTP %d %@ after %.1f s", status, type, now() - started))+ guard (200..<300).contains(status) else {+ var raw = Data()+ for try await b in bytes { raw.append(b) }+ return (status, nil, String(decoding: raw, as: UTF8.self))+ }+ if !type.contains("text/event-stream") { // a plain JSON answer+ var raw = Data()+ for try await b in bytes { raw.append(b) }+ return (status, try Self.message(raw), "")+ }+ var result = ChatResult(text: "", firstToken: nil, total: 0)+ for try await line in bytes.lines {+ guard line.hasPrefix("data:") else { continue }+ let payload = line.dropFirst(5).trimmingCharacters(in: .whitespaces)+ if payload == "[DONE]" { break }+ guard let json = (try? JSONSerialization.jsonObject(with: Data(payload.utf8))) as? [String: Any] else { continue }+ let choice = (json["choices"] as? [[String: Any]])?.first+ let delta = choice?["delta"] as? [String: Any]+ Self.note(json, choice, into: &result)+ result.reasoningChars += Self.reasoning(delta).count+ guard let piece = delta?["content"] as? String, !piece.isEmpty else { continue }+ if result.firstToken == nil { result.firstToken = now() - started }+ result.text += piece+ }+ result.rawChars = result.text.count+ return (status, result, "")+ }++ /// choices[0].message of a non-streamed reply.+ static func message(_ raw: Data) throws -> ChatResult {+ let json = try JSONSerialization.jsonObject(with: raw) as? [String: Any]+ let choice = (json?["choices"] as? [[String: Any]])?.first+ guard let json, let msg = choice?["message"] as? [String: Any] else {+ throw LLMError(message: "bad LLM reply: \(String(decoding: raw.prefix(200), as: UTF8.self))")+ }+ var result = ChatResult(text: msg["content"] as? String ?? "", firstToken: nil, total: 0)+ note(json, choice, into: &result)+ result.reasoningChars = reasoning(msg).count+ result.rawChars = result.text.count+ return result+ }++ /// finish_reason and usage, from whichever event carries them.+ private static func note(_ json: [String: Any], _ choice: [String: Any]?, into result: inout ChatResult) {+ if let reason = choice?["finish_reason"] as? String { result.finishReason = reason }+ if let usage = json["usage"] as? [String: Any] { result.usage = usage.compactMapValues { $0 as? Int } }+ }++ /// Reasoning text (vLLM/DeepSeek `reasoning_content`, others `reasoning`).+ private static func reasoning(_ part: [String: Any]?) -> String {+ part?["reasoning_content"] as? String ?? part?["reasoning"] as? String ?? ""+ }+}diff --git a/ios/IPhoneAgent/Services/LogUploader.swift b/ios/IPhoneAgent/Services/LogUploader.swiftnew file mode 100644index 0000000..99a57eb--- /dev/null+++ b/ios/IPhoneAgent/Services/LogUploader.swift@@ -0,0 +1,39 @@+import Foundation++/// Sends a log archive somewhere for debugging. No endpoint ships yet: `LogUpload.uploader` is nil and+/// uploading is off until the user agrees (a first-launch agreement listing `collected` will set the flag).+protocol LogUploader {+ func upload(_ archive: URL) async throws+}++enum LogUpload {+ static let consentKey = "logUploadConsent"++ /// The user agreed to send logs (off by default).+ static var consented: Bool {+ get { UserDefaults.standard.bool(forKey: consentKey) }+ set { UserDefaults.standard.set(newValue, forKey: consentKey) }+ }++ /// Set when an endpoint exists; nil = nothing is ever sent.+ @MainActor static var uploader: LogUploader?++ /// What the archive holds, for the agreement screen. Never the API key.+ static let collected = [+ "debug.log: app events, board commands and status, BLE disconnects, model request timing",+ "Runs: each run's steps, the model's prompts and replies, screenshots and the mirrored-screen video",+ ]++ /// Upload only with consent and an endpoint; returns whether it was sent.+ @MainActor static func uploadIfAllowed(_ archive: URL) async -> Bool {+ guard consented, let uploader else { return false }+ do {+ try await uploader.upload(archive)+ DebugLog.write("logs uploaded")+ return true+ } catch {+ DebugLog.write("log upload failed: \(error.localizedDescription)")+ return false+ }+ }+}diff --git a/ios/IPhoneAgent/Services/Metrics.swift b/ios/IPhoneAgent/Services/Metrics.swiftnew file mode 100644index 0000000..1ba84ba--- /dev/null+++ b/ios/IPhoneAgent/Services/Metrics.swift@@ -0,0 +1,104 @@+import Foundation++/// Live numbers for the Diagnostics page; a snapshot goes into every trace (metrics.json).+@MainActor final class Metrics: ObservableObject {+ struct Step: Codable { var frameMs = 0.0, llmMs = 0.0, hidMs = 0.0 }++ // board, from status+ @Published var board: BoardStatus?+ @Published var statusAge = 0.0 // s since the last status notify+ // BLE, measured in the app+ @Published var bleKbps = 0.0+ @Published var mtu = 0+ @Published var drops = 0+ @Published var benchKbps: Double?+ // video+ @Published var fps = 0.0+ @Published var idrIntervalMs: Double?+ @Published var snapMs: Double?+ @Published var decodeMs = 0.0+ @Published var decodeErrors = 0+ @Published var backgroundDecodeErrors = 0+ // agent+ @Published var steps: [Step] = []+ @Published var llmFirstMs: Double?+ @Published var llmTotalMs: Double?+ @Published var llmPingMs: Double?+ @Published var hidMs: [String: Double] = [:] // last round trip per command+ // background+ @Published var backgroundSince: Double?+ @Published var backgroundAlive = 0.0 // s alive in background (current or last stint)+ @Published var suspensions = 0++ private var windowBytes = 0, windowFrames = 0+ private var windowStart = now()+ private var lastIDR: Double?+ private var lastTick = now()+ private var lastStatus: Double?++ func status(_ s: BoardStatus) {+ board = s+ lastStatus = now()+ }++ func videoBytes(_ n: Int) { windowBytes += n }+ func videoDrops(_ n: Int) { drops += n }+ func frameDecoded(ms: Double) {+ windowFrames += 1+ decodeMs = ms+ }+ func decodeError(background: Bool) {+ decodeErrors += 1+ if background { backgroundDecodeErrors += 1 }+ }+ func idrSeen() {+ let t = now()+ if let lastIDR { idrIntervalMs = (t - lastIDR) * 1000 }+ lastIDR = t+ }+ func snapLatency(_ ms: Double) { snapMs = ms }+ func llm(first: Double?, total: Double) {+ llmFirstMs = first.map { $0 * 1000 }+ llmTotalMs = total * 1000+ }+ func step(_ s: Step) {+ steps = Array((steps + [s]).suffix(40))+ DebugLog.write(String(format: "step %d timing: frame %.0f ms, LLM %.0f ms, HID %.0f ms", steps.count, s.frameMs,+ s.llmMs, s.hidMs))+ }++ /// Called every second by a timer; also detects suspension (a gap far longer than the tick).+ func tick() {+ let t = now()+ if t - lastTick > 5 { suspensions += 1 }+ lastTick = t+ let span = max(t - windowStart, 0.001)+ bleKbps = Double(windowBytes) * 8 / 1000 / span+ fps = Double(windowFrames) / span+ windowBytes = 0; windowFrames = 0; windowStart = t+ statusAge = lastStatus.map { t - $0 } ?? 0+ if let since = backgroundSince { backgroundAlive = t - since }+ }++ func enteredBackground() { backgroundSince = now(); backgroundAlive = 0 }+ func enteredForeground() { backgroundSince = nil }++ /// Everything as JSON-ready values, for metrics.json.+ func snapshot() -> [String: Any] {+ var out: [String: Any] = [+ "ble_kbps_app": bleKbps, "mtu": mtu, "drops": drops, "fps": fps, "decode_ms": decodeMs,+ "decode_errors": decodeErrors, "background_decode_errors": backgroundDecodeErrors,+ "background_alive_s": backgroundAlive, "suspensions": suspensions, "hid_ms": hidMs,+ "steps": steps.map { ["frame_ms": $0.frameMs, "llm_ms": $0.llmMs, "hid_ms": $0.hidMs] },+ ]+ out["bench_kbps"] = benchKbps+ out["idr_interval_ms"] = idrIntervalMs+ out["snap_ms"] = snapMs+ out["llm_first_ms"] = llmFirstMs+ out["llm_total_ms"] = llmTotalMs+ if let board, let data = try? JSONEncoder().encode(board) {+ out["board"] = try? JSONSerialization.jsonObject(with: data)+ }+ return out+ }+}diff --git a/ios/IPhoneAgent/Services/Notifier.swift b/ios/IPhoneAgent/Services/Notifier.swiftnew file mode 100644index 0000000..a68940b--- /dev/null+++ b/ios/IPhoneAgent/Services/Notifier.swift@@ -0,0 +1,79 @@+import Foundation+import UserNotifications++/// Local notifications for runs: done / failed / needs help / mirroring lost / board disconnected, with+/// actions (Review, Retry, Stop, Continue, Skip, Take over). Tapping one opens the run's review.+@MainActor final class Notifier: NSObject, UNUserNotificationCenterDelegate {+ enum Kind: String { case done, failed, help, takeover, mirroring, board, wifi }+ enum Action: String { case review, retry, stop, resume, skip, takeOver }++ /// Called with the action (nil = the notification itself was tapped) and the run id.+ var onAction: ((Action?, String) -> Void)?+ private let center = UNUserNotificationCenter.current()+ static let askedKey = "askedNotifications"++ override init() {+ super.init()+ center.delegate = self+ let review = UNNotificationAction(identifier: Action.review.rawValue, title: String(localized: "Review"),+ options: [.foreground])+ let retry = UNNotificationAction(identifier: Action.retry.rawValue, title: String(localized: "Retry"),+ options: [.foreground])+ let stop = UNNotificationAction(identifier: Action.stop.rawValue, title: String(localized: "Stop"),+ options: [.destructive])+ let resume = UNNotificationAction(identifier: Action.resume.rawValue, title: String(localized: "Continue"))+ let skip = UNNotificationAction(identifier: Action.skip.rawValue, title: String(localized: "Skip step"))+ let takeOver = UNNotificationAction(identifier: Action.takeOver.rawValue, title: String(localized: "Take over"))+ center.setNotificationCategories([+ UNNotificationCategory(identifier: Kind.done.rawValue, actions: [review], intentIdentifiers: []),+ UNNotificationCategory(identifier: Kind.failed.rawValue, actions: [review, retry], intentIdentifiers: []),+ UNNotificationCategory(identifier: Kind.help.rawValue, actions: [takeOver, skip, stop], intentIdentifiers: []),+ UNNotificationCategory(identifier: Kind.takeover.rawValue, actions: [resume, stop], intentIdentifiers: []),+ UNNotificationCategory(identifier: Kind.mirroring.rawValue, actions: [stop, review], intentIdentifiers: []),+ UNNotificationCategory(identifier: Kind.board.rawValue, actions: [stop, review], intentIdentifiers: []),+ UNNotificationCategory(identifier: Kind.wifi.rawValue, actions: [stop, review], intentIdentifiers: []),+ ])+ }++ /// Asked once, on the first Start (with a one-line reason shown by the app first).+ static var asked: Bool { UserDefaults.standard.bool(forKey: askedKey) }++ func requestPermission() async {+ UserDefaults.standard.set(true, forKey: Self.askedKey)+ _ = try? await center.requestAuthorization(options: [.alert, .sound, .badge])+ }++ func post(_ kind: Kind, title: String, body: String, run: String) {+ let content = UNMutableNotificationContent()+ content.title = title+ content.body = body+ content.categoryIdentifier = kind.rawValue+ content.userInfo = ["run": run]+ let urgent: Set<Kind> = [.help, .mirroring, .board, .wifi] // the run waits for the user+ content.sound = urgent.contains(kind) ? .default : nil+ content.interruptionLevel = urgent.contains(kind) ? .timeSensitive : .active+ center.removeDeliveredNotifications(withIdentifiers: [Kind.help.rawValue, Kind.takeover.rawValue])+ center.add(UNNotificationRequest(identifier: kind.rawValue, content: content, trigger: nil))+ }++ func clearHelp() {+ center.removeDeliveredNotifications(withIdentifiers: [Kind.help.rawValue, Kind.takeover.rawValue])+ }++ /// The link is back: the "start mirroring / check the board / join Wi-Fi" asks are stale.+ func clearLinkAsks() {+ center.removeDeliveredNotifications(withIdentifiers: [Kind.mirroring.rawValue, Kind.board.rawValue, Kind.wifi.rawValue])+ }++ nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification)+ async -> UNNotificationPresentationOptions {+ [.banner, .list, .sound]+ }++ nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {+ let run = response.notification.request.content.userInfo["run"] as? String ?? ""+ let id = response.actionIdentifier+ let action = id == UNNotificationDefaultActionIdentifier ? nil : Action(rawValue: id)+ await MainActor.run { onAction?(action, run) }+ }+}diff --git a/ios/IPhoneAgent/Services/Redactor.swift b/ios/IPhoneAgent/Services/Redactor.swiftnew file mode 100644index 0000000..46adbd2--- /dev/null+++ b/ios/IPhoneAgent/Services/Redactor.swift@@ -0,0 +1,63 @@+import UIKit++/// Strips what must never leave the phone from shared run data: secrets (API key, base URL and its host, the+/// board's Wi-Fi name and password), IP addresses and typed text; and blacks out the top band of screenshots+/// (status bar, Dynamic Island with the Live Activity, where notification banners drop in).+struct Redactor {+ var secrets: [String]+ static let mask = "[redacted]"+ static let typed = "•••"+ static let band = 0.07 // top share of each screenshot that is blacked out++ private static let rules: [(String, String)] = [+ (#"\b(?:\d{1,3}\.){3}\d{1,3}\b"#, mask), // IPv4+ (#"("action": ?"type", ?"text": ?)"(?:[^"\\]|\\.)*""#, "$1\"\(typed)\""), // history in prompts+ (#"(DO: type) [^\n]*"#, "$1 \(typed)"), // model replies+ (#"(cmd #\d+ type) .*?( →|$)"#, "$1 \(typed)$2"), // debug.log commands+ ]++ /// Any text: a log line, metrics, a prompt.+ func text(_ s: String) -> String {+ var out = s+ for x in secrets.filter({ $0.count >= 4 }).sorted(by: { $0.count > $1.count }) {+ out = out.replacingOccurrences(of: x, with: Self.mask)+ }+ for (pattern, template) in Self.rules {+ out = out.replacingOccurrences(of: pattern, with: template, options: .regularExpression)+ }+ return out+ }++ /// One steps.jsonl line: every string redacted, and the text of `type` actions replaced.+ func jsonLine(_ line: String) -> String {+ guard let any = try? JSONSerialization.jsonObject(with: Data(line.utf8)),+ let data = try? JSONSerialization.data(withJSONObject: value(any), options: [.sortedKeys]) else {+ return text(line)+ }+ return String(decoding: data, as: UTF8.self)+ }++ private func value(_ v: Any) -> Any {+ switch v {+ case let s as String: return text(s)+ case let a as [Any]: return a.map(value)+ case var d as [String: Any]:+ for (k, x) in d { d[k] = value(x) }+ if d["action"] as? String == "type", d["text"] != nil { d["text"] = Self.typed }+ return d+ default: return v+ }+ }++ /// A screenshot with its top band blacked out; nil if it is not an image.+ func image(_ jpeg: Data) -> Data? {+ guard let img = UIImage(data: jpeg) else { return nil }+ let format = UIGraphicsImageRendererFormat()+ format.scale = img.scale+ return UIGraphicsImageRenderer(size: img.size, format: format).jpegData(withCompressionQuality: 0.8) { ctx in+ img.draw(at: .zero)+ UIColor.black.setFill()+ ctx.fill(CGRect(x: 0, y: 0, width: img.size.width, height: img.size.height * Self.band))+ }+ }+}diff --git a/ios/IPhoneAgent/Services/RunShare.swift b/ios/IPhoneAgent/Services/RunShare.swiftnew file mode 100644index 0000000..938d55b--- /dev/null+++ b/ios/IPhoneAgent/Services/RunShare.swift@@ -0,0 +1,146 @@+import Compression+import Foundation++/// Community data sharing, local only (nothing is uploaded): export picked runs as one redacted .zip for the+/// share sheet, and import such a .zip as read-only "Imported" runs.+enum RunShare {+ /// "Keep run data for sharing" (off by default; Export needs it on).+ static let keepKey = "shareRunData"+ /// The consent sheet was shown once.+ static let askedKey = "sharePrivacyAsked"+ /// A file in an imported run's folder.+ static let importedMarker = ".imported"++ struct Package {+ let url: URL+ let runs: Int+ let bytes: Int+ }++ static func isImported(_ folder: URL) -> Bool {+ FileManager.default.fileExists(atPath: folder.appendingPathComponent(importedMarker).path)+ }++ /// Copies each run redacted (steps, metrics, review edits, screenshots, video) plus debug.log, then zips it.+ static func export(_ runs: [URL], redactor: Redactor, debugLog: URL?) throws -> Package {+ let fm = FileManager.default+ let stage = fm.temporaryDirectory.appendingPathComponent("iPhone-Agent-runs")+ try? fm.removeItem(at: stage)+ try fm.createDirectory(at: stage, withIntermediateDirectories: true)+ for run in runs {+ let out = stage.appendingPathComponent(run.lastPathComponent)+ try fm.createDirectory(at: out.appendingPathComponent("video"), withIntermediateDirectories: true)+ for name in ["steps.jsonl", "metrics.json", "review.json"] {+ guard let text = try? String(contentsOf: run.appendingPathComponent(name), encoding: .utf8) else { continue }+ let lines = text.split(separator: "\n", omittingEmptySubsequences: false).map(String.init)+ let clean = name == "steps.jsonl" ? lines.map { $0.isEmpty ? $0 : redactor.jsonLine($0) }.joined(separator: "\n")+ : redactor.text(text)+ try Data(clean.utf8).write(to: out.appendingPathComponent(name))+ }+ for sub in ["", "video"] {+ let dir = sub.isEmpty ? run : run.appendingPathComponent(sub)+ for jpg in ((try? fm.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? [])+ where jpg.pathExtension == "jpg" {+ if let data = try? Data(contentsOf: jpg), let clean = redactor.image(data) {+ try clean.write(to: out.appendingPathComponent(sub).appendingPathComponent(jpg.lastPathComponent))+ }+ }+ }+ }+ if let debugLog, let text = try? String(contentsOf: debugLog, encoding: .utf8) {+ let clean = text.split(separator: "\n", omittingEmptySubsequences: false).map { redactor.text(String($0)) }+ try Data(clean.joined(separator: "\n").utf8).write(to: stage.appendingPathComponent("debug.log"))+ }+ let zip = try TraceStore.zip(stage, name: "iPhone-Agent-runs.zip")+ let bytes = (try? fm.attributesOfItem(atPath: zip.path)[.size] as? Int) ?? 0+ return Package(url: zip, runs: runs.count, bytes: bytes)+ }++ /// Unpacks a shared .zip; every folder with a steps.jsonl becomes an imported run in `root`. Returns their ids.+ static func importZip(_ zip: URL, into root: URL) throws -> [String] {+ let fm = FileManager.default+ let tmp = fm.temporaryDirectory.appendingPathComponent("import-\(UUID().uuidString)")+ defer { try? fm.removeItem(at: tmp) }+ try Unzip.extract(zip, to: tmp)+ var ids: [String] = []+ let all = fm.enumerator(at: tmp, includingPropertiesForKeys: nil)?.compactMap { $0 as? URL } ?? []+ for steps in all where steps.lastPathComponent == "steps.jsonl" {+ let run = steps.deletingLastPathComponent()+ let id = "imported-" + run.lastPathComponent+ let dest = root.appendingPathComponent(id)+ try? fm.removeItem(at: dest)+ try fm.createDirectory(at: root, withIntermediateDirectories: true)+ try fm.moveItem(at: run, to: dest)+ try Data().write(to: dest.appendingPathComponent(importedMarker))+ ids.append(id)+ }+ guard !ids.isEmpty else { throw DeviceError(message: String(localized: "No runs in this file.")) }+ return ids+ }+}++/// A minimal .zip reader (stored or deflated entries, no zip64), enough for archives this app writes.+enum Unzip {+ static func extract(_ zip: URL, to dir: URL) throws {+ let b = [UInt8](try Data(contentsOf: zip))+ func u16(_ i: Int) -> Int { i + 2 <= b.count ? Int(b[i]) | Int(b[i + 1]) << 8 : 0 }+ func u32(_ i: Int) -> Int { u16(i) | u16(i + 2) << 16 }+ let bad = DeviceError(message: String(localized: "This is not a run archive."))+ guard b.count >= 22, let end = stride(from: b.count - 22, through: 0, by: -1).first(where: { u32($0) == 0x0605_4b50 })+ else { throw bad }+ var p = u32(end + 16)+ for _ in 0..<u16(end + 10) {+ guard u32(p) == 0x0201_4b50 else { throw bad }+ let method = u16(p + 10), packed = u32(p + 20), size = u32(p + 24)+ let nameLen = u16(p + 28), local = u32(p + 42)+ let name = String(decoding: b[(p + 46)..<min(b.count, p + 46 + nameLen)], as: UTF8.self)+ p += 46 + nameLen + u16(p + 30) + u16(p + 32)+ guard !name.hasPrefix("/"), !name.split(separator: "/").contains("..") else { throw bad }+ let target = dir.appendingPathComponent(name)+ if name.hasSuffix("/") {+ try FileManager.default.createDirectory(at: target, withIntermediateDirectories: true)+ continue+ }+ let start = local + 30 + u16(local + 26) + u16(local + 28)+ guard u32(local) == 0x0403_4b50, start + packed <= b.count else { throw bad }+ let raw = Array(b[start..<(start + packed)])+ let data: Data+ switch method {+ case 0: data = Data(raw)+ case 8: data = try inflate(raw, size: size)+ default: throw bad+ }+ try FileManager.default.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true)+ try data.write(to: target)+ }+ }++ private static func inflate(_ raw: [UInt8], size: Int) throws -> Data {+ guard size > 0 else { return Data() }+ var out = [UInt8](repeating: 0, count: size)+ let n = compression_decode_buffer(&out, size, raw, raw.count, nil, COMPRESSION_ZLIB) // raw deflate+ guard n == size else { throw DeviceError(message: "unzip: bad deflate data") }+ return Data(out)+ }+}++extension AppModel {+ /// Everything that identifies this setup and must never be exported.+ var shareRedactor: Redactor {+ let secrets = [settings.apiKey, settings.baseURL, URL(string: settings.baseURL)?.host ?? "",+ board.net?.ssid ?? "", board.net?.pass ?? "", hotspotSSID ?? "", manualHotspot?.pass ?? ""]+ return Redactor(secrets: secrets.filter { !$0.isEmpty })+ }++ /// A shared .zip opened from Files, the share sheet or Runs › Import. Returns how many runs it held.+ @discardableResult+ func importRuns(_ url: URL) throws -> Int {+ let scoped = url.startAccessingSecurityScopedResource()+ defer { if scoped { url.stopAccessingSecurityScopedResource() } }+ let ids = try RunShare.importZip(url, into: traces.root)+ runs.reload()+ tab = .runs+ say("imported \(ids.count) run(s)")+ return ids.count+ }+}diff --git a/ios/IPhoneAgent/Services/Settings.swift b/ios/IPhoneAgent/Services/Settings.swiftnew file mode 100644index 0000000..dfa5691--- /dev/null+++ b/ios/IPhoneAgent/Services/Settings.swift@@ -0,0 +1,194 @@+import Foundation+import NetworkExtension+import Security+import UIKit++/// LLM settings. The API key lives in the Keychain, everything else in UserDefaults.+@MainActor final class Settings: ObservableObject {+ static let defaultBaseURL = "" // user enters their own OpenAI-compatible endpoint+ static let defaultModel = ""++ private let defaults: UserDefaults+ @Published var baseURL: String { didSet { defaults.set(baseURL, forKey: "baseURL"); if baseURL != oldValue { modelsChanged() } } }+ @Published var model: String { didSet { defaults.set(model, forKey: "model") } } // "" = first from GET /models+ /// The model picked from the endpoint's list when `model` is empty (forgotten when the endpoint or key changes).+ @Published private(set) var autoModel: String { didSet { defaults.set(autoModel, forKey: "autoModel") } }+ @Published var plannerModel: String { didSet { defaults.set(plannerModel, forKey: "plannerModel") } } // "" = model+ @Published var actorModel: String { didSet { defaults.set(actorModel, forKey: "actorModel") } } // "" = model+ @Published var tokenParam: String { didSet { defaults.set(tokenParam, forKey: "tokenParam") } } // auto | ...+ @Published var extraBody: String { didSet { defaults.set(extraBody, forKey: "extraBody") } } // JSON object+ @Published var apiKey: String { didSet { Keychain.set(apiKey, for: "llm-api-key"); DebugLog.redact([apiKey])+ if apiKey != oldValue { modelsChanged() } } }+ /// What the agent is called (Agent tab title, greeting, Live Activity); empty = the default.+ /// The endpoint's model list (GET /models), for the pickers; empty until loaded or when it can't be fetched.+ @Published private(set) var models: [String] = []+ @Published private(set) var loadingModels = false+ @Published private(set) var modelsError: String?+ private var modelsRequest = 0+ @Published var agentName: String {+ didSet {+ let trimmed = agentName.trimmingCharacters(in: .whitespacesAndNewlines)+ defaults.set(trimmed.isEmpty ? nil : trimmed, forKey: Self.agentNameKey)+ let shown = trimmed.isEmpty ? Self.defaultAgentName : trimmed+ if shown != agentName { agentName = shown } // no observer re-entry inside didSet+ }+ }+ static let agentNameKey = "agentName"+ static var defaultAgentName: String { String(localized: "ESP32 Agent") }+ /// The name, for code without a Settings instance (Live Activity).+ static var storedAgentName: String { UserDefaults.standard.string(forKey: agentNameKey) ?? defaultAgentName }+ @Published var onboarded: Bool { didSet { defaults.set(onboarded, forKey: "onboarded") } }+ @Published var acceptedDisclaimer: Bool { didSet { defaults.set(acceptedDisclaimer, forKey: "acceptedDisclaimer") } }++ /// info: where build-time presets are read from (the app's Info.plist; tests pass none).+ init(defaults: UserDefaults = .standard, info: [String: Any]? = Bundle.main.infoDictionary) {+ self.defaults = defaults+ let preset = { (key: String) in Self.stored((info?[key] as? String)?.trimmingCharacters(in: .whitespaces)) }+ baseURL = Self.stored(defaults.string(forKey: "baseURL")) ?? preset("IAPresetBaseURL") ?? Self.defaultBaseURL+ model = Self.stored(defaults.string(forKey: "model")) ?? preset("IAPresetModel") ?? Self.defaultModel+ autoModel = defaults.string(forKey: "autoModel") ?? ""+ plannerModel = defaults.string(forKey: "plannerModel") ?? ""+ actorModel = defaults.string(forKey: "actorModel") ?? ""+ tokenParam = defaults.string(forKey: "tokenParam") ?? "auto"+ extraBody = defaults.string(forKey: "extraBody") ?? "{}"+ apiKey = Self.stored(Keychain.get("llm-api-key")) ?? preset("IAPresetKey") ?? ""+ agentName = defaults.string(forKey: Self.agentNameKey) ?? Self.defaultAgentName+ onboarded = defaults.bool(forKey: "onboarded")+ acceptedDisclaimer = defaults.bool(forKey: "acceptedDisclaimer")+ DebugLog.redact([apiKey]) // never in debug.log+ }++ private static func stored(_ v: String?) -> String? { v?.isEmpty == false ? v : nil }++ /// The endpoint is filled in (the key is optional: some endpoints need none; the model is picked automatically).+ var isConfigured: Bool {+ URL(string: baseURL)?.scheme?.hasPrefix("http") == true+ }++ /// The manual override, else the model already picked from the endpoint, else nil.+ var currentModel: String? {+ let manual = model.trimmingCharacters(in: .whitespaces)+ if !manual.isEmpty { return manual }+ return autoModel.isEmpty ? nil : autoModel+ }++ /// The manual override, else the first model from GET {base}/models (fetched once per endpoint and key).+ func resolvedModel() async throws -> String {+ if let m = currentModel { return m }+ let picked = try await LLMClient.firstModel(baseURL: baseURL, apiKey: apiKey)+ autoModel = picked+ return picked+ }++ private func modelsChanged() {+ autoModel = ""+ models = []+ modelsError = nil+ }++ /// Fetch the model list; the latest request wins. "Automatic" becomes the first id.+ func loadModels() async {+ guard isConfigured else { return }+ modelsRequest += 1+ let request = modelsRequest+ loadingModels = true+ defer { if request == modelsRequest { loadingModels = false } }+ do {+ let list = try await LLMClient.models(baseURL: baseURL, apiKey: apiKey)+ guard request == modelsRequest else { return }+ models = list+ modelsError = list.isEmpty ? String(localized: "The endpoint lists no models.") : nil+ if let first = list.first { autoModel = first }+ DebugLog.write("models: \(list.count) listed, first \(list.first ?? "-")")+ } catch {+ guard request == modelsRequest else { return }+ models = []+ modelsError = error.localizedDescription+ DebugLog.write("models: \(error.localizedDescription)")+ }+ }++ var extra: [String: Any] {+ (try? JSONSerialization.jsonObject(with: Data(extraBody.utf8))) as? [String: Any] ?? [:]+ }++ /// role "planner" or "actor": its own model if set, else the shared one.+ func client(_ role: String) async throws -> LLMClient {+ let own = role == "planner" ? plannerModel : actorModel+ return LLMClient(baseURL: baseURL, model: own.isEmpty ? try await resolvedModel() : own, apiKey: apiKey,+ extra: extra, tokenParam: tokenParam)+ }+}++enum Keychain {+ private static func query(_ account: String) -> [CFString: Any] {+ [kSecClass: kSecClassGenericPassword, kSecAttrService: Bundle.main.bundleIdentifier ?? "iphoneagent", kSecAttrAccount: account]+ }++ static func get(_ account: String) -> String? {+ var q = query(account)+ q[kSecReturnData] = true+ var out: CFTypeRef?+ guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let data = out as? Data else { return nil }+ return String(data: data, encoding: .utf8)+ }++ static func set(_ value: String, for account: String) {+ SecItemDelete(query(account) as CFDictionary)+ guard !value.isEmpty else { return }+ var q = query(account)+ q[kSecValueData] = Data(value.utf8)+ q[kSecAttrAccessible] = kSecAttrAccessibleAfterFirstUnlock // the agent may run while the phone is locked+ SecItemAdd(q as CFDictionary, nil)+ }+}++/// Joins the board's SoftAP with the credentials read over BLE (never shown or logged).+enum Hotspot {+ static func join(_ net: NetConfig) async throws {+ guard let ssid = net.ssid, let pass = net.pass else { throw DeviceError(message: "board sent no hotspot credentials") }+ let config = NEHotspotConfiguration(ssid: ssid, passphrase: pass, isWEP: false)+ config.joinOnce = false+ do {+ try await NEHotspotConfigurationManager.shared.apply(config)+ } catch let e as NSError where e.domain == NEHotspotConfigurationErrorDomain+ && e.code == NEHotspotConfigurationError.alreadyAssociated.rawValue {+ return+ }+ }++ /// For the debug log: domain, code, the NEHotspotConfigurationError name and the message.+ static func describe(_ e: NSError) -> String {+ guard e.domain == NEHotspotConfigurationErrorDomain else { return "\(e.domain) \(e.code): \(e.localizedDescription)" }+ let names = ["invalid", "invalidSSID", "invalidWPAPassphrase", "invalidWEPPassphrase", "invalidEAPSettings",+ "invalidHS20Settings", "invalidHS20DomainName", "userDenied", "internal", "pending",+ "systemConfiguration", "unknown", "joinOnceNotSupported", "alreadyAssociated",+ "applicationIsNotInForeground", "invalidSSIDPrefix", "userUnauthorized", "systemDenied"]+ let name = names.indices.contains(e.code) ? names[e.code] : "?"+ return "\(e.domain) \(e.code) \(name): \(e.localizedDescription)"+ }++ static func userDenied(_ e: NSError) -> Bool {+ e.domain == NEHotspotConfigurationErrorDomain && e.code == NEHotspotConfigurationError.userDenied.rawValue+ }++ /// Settings › Wi-Fi when iOS allows the deep link, else this app's page in Settings.+ @MainActor static func openWiFiSettings() {+ let app = UIApplication.shared+ // iOS 18+ has no public or private link to the Wi-Fi page: page links like App-prefs:root=WIFI+ // "succeed" but land on this app's page. The bare scheme opens the top of Settings (Wi-Fi is+ // the second row). Last resort: this app's page.+ var urls = ["App-prefs:"].compactMap(URL.init(string:))+ urls.append(URL(string: UIApplication.openSettingsURLString)!)+ func next() {+ guard !urls.isEmpty else { return }+ app.open(urls.removeFirst()) { ok in if !ok { next() } }+ }+ next()+ }++ /// The SSID the phone is on, if it is one of ours (needs the hotspot entitlement).+ static func currentSSID() async -> String? {+ await NEHotspotNetwork.fetchCurrent()?.ssid+ }+}diff --git a/ios/IPhoneAgent/Services/Stores.swift b/ios/IPhoneAgent/Services/Stores.swiftnew file mode 100644index 0000000..500f719--- /dev/null+++ b/ios/IPhoneAgent/Services/Stores.swift@@ -0,0 +1,165 @@+import Foundation++/// A task saved for reuse ("intent"): a short name and the prompt the agent gets.+struct SavedTask: Codable, Identifiable, Equatable, Hashable {+ var id = UUID()+ var name: String+ var prompt: String+ var icon: String?+ var hints: [String]? // checklist, appended to the actor prompt as hints when it runs+ var refRun: String? // the run it was made from+ var history: [RunStat]? // its runs, newest last++ var symbol: String { icon ?? "bolt.fill" }+ var checklist: [String] { hints ?? [] }+ var runs: [RunStat] { history ?? [] }+ var successRate: Double? { runs.isEmpty ? nil : Double(runs.filter(\.ok).count) / Double(runs.count) }+ var averageSeconds: Double? { runs.isEmpty ? nil : runs.map(\.seconds).reduce(0, +) / Double(runs.count) }+}++struct RunStat: Codable, Equatable, Hashable {+ var run: String+ var ok: Bool+ var seconds: Double+ var date = Date()+}++/// Saved tasks, kept in UserDefaults. Seeded once with the examples (the alarm demo first).+@MainActor final class IntentStore: ObservableObject {+ @Published private(set) var items: [SavedTask] = []+ private let defaults: UserDefaults+ private static let key = "savedTasks"++ init(defaults: UserDefaults = .standard) {+ self.defaults = defaults+ if let data = defaults.data(forKey: Self.key), let saved = try? JSONDecoder().decode([SavedTask].self, from: data) {+ items = saved+ } else {+ items = Self.examples+ save()+ }+ }++ static var examples: [SavedTask] {+ [SavedTask(name: String(localized: "8 AM Mon & Tue alarm"),+ prompt: String(localized: "Set an alarm for 8:00 AM that repeats every Monday and Tuesday, then save it")),+ SavedTask(name: String(localized: "Draw a smiley"), prompt: String(localized: "Open Whiteboard and draw a smiley face")),+ SavedTask(name: String(localized: "Wi-Fi settings"), prompt: String(localized: "Open Settings and go to Wi-Fi")),+ SavedTask(name: String(localized: "Note: hello"), prompt: String(localized: "Open Notes and write \"hello\""))]+ }++ func add(name: String, prompt: String) {+ let trimmed = name.trimmingCharacters(in: .whitespacesAndNewlines)+ items.insert(SavedTask(name: trimmed.isEmpty ? String(prompt.prefix(30)) : trimmed, prompt: prompt), at: 0)+ save()+ }++ func delete(at offsets: IndexSet) {+ items.remove(atOffsets: offsets)+ save()+ }++ func delete(_ id: UUID) {+ items.removeAll { $0.id == id }+ save()+ }++ /// Adds a new intent or replaces the one with the same id.+ func upsert(_ item: SavedTask) {+ if let i = items.firstIndex(where: { $0.id == item.id }) { items[i] = item } else { items.insert(item, at: 0) }+ save()+ }++ func item(_ id: UUID?) -> SavedTask? { items.first { $0.id == id } }++ func record(_ id: UUID, _ stat: RunStat) {+ guard let i = items.firstIndex(where: { $0.id == id }) else { return }+ items[i].history = Array((items[i].runs + [stat]).suffix(50))+ save()+ }++ private func save() {+ defaults.set(try? JSONEncoder().encode(items), forKey: Self.key)+ }+}++/// One past or current agent run, read back from its trace folder.+struct Run: Identifiable, Equatable {+ struct Step: Identifiable, Equatable {+ let id: Int+ let action: JObject+ let frame: URL? // the screenshot the model decided on+ let t: Double?++ var name: String { action["action"]?.str ?? "" }+ var isMove: Bool { !StepText.notMoves.contains(name) }+ }++ let id: String // folder name, yyyyMMdd-HHmmss+ let folder: URL+ let task: String+ let date: Date+ let steps: [Step]++ /// The low-fps recording of the mirror stream (video/<ms>.jpg), if it was on.+ var video: [(url: URL, t: Double)] {+ let dir = folder.appendingPathComponent("video")+ let files = (try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? []+ return files.compactMap { u in Double(u.deletingPathExtension().lastPathComponent).map { (u, $0 / 1000) } }+ .sorted { $0.t < $1.t }+ }++ var moves: [Step] { steps.filter(\.isMove) }+ /// From someone else's shared archive: replay only.+ var imported: Bool { RunShare.isImported(folder) }+ var outcome: Outcome { Outcome(last: steps.last?.name, running: false) }+ var cover: URL? { steps.last(where: { $0.frame != nil })?.frame }+ var firstFrame: URL? { steps.first(where: { $0.frame != nil })?.frame }+ var duration: Double? {+ guard let a = steps.first?.t, let b = steps.last?.t else { return nil }+ return max(0, b - a)+ }+}++/// Runs on disk (Documents/traces), newest first.+@MainActor final class RunStore: ObservableObject {+ @Published private(set) var runs: [Run] = []+ let traces: TraceStore++ init(traces: TraceStore) { self.traces = traces }++ func reload(limit: Int = 30) {+ runs = traces.runs().prefix(limit).compactMap(Self.load)+ }++ static func load(_ folder: URL) -> Run? {+ guard let text = try? String(contentsOf: folder.appendingPathComponent("steps.jsonl"), encoding: .utf8) else { return nil }+ var task = "", frame: URL?, steps: [Run.Step] = []+ for line in text.split(separator: "\n") {+ guard let any = try? JSONSerialization.jsonObject(with: Data(line.utf8)),+ case .obj(let rec) = PyJSON.from(any) else { continue }+ if let f = rec["frame"]?.str { frame = folder.appendingPathComponent(f) }+ switch rec["kind"]?.str {+ case "task": task = rec["task"]?.str ?? ""+ case "step": steps.append(Run.Step(id: steps.count, action: rec.without(["n", "t", "kind", "frame"]), frame: frame,+ t: rec["t"]?.double))+ default: break+ }+ }+ let f = DateFormatter()+ f.dateFormat = "yyyyMMdd-HHmmss"+ f.locale = Locale(identifier: "en_US_POSIX")+ return Run(id: folder.lastPathComponent, folder: folder, task: task,+ date: f.date(from: folder.lastPathComponent.replacingOccurrences(of: "imported-", with: "")) ?? Date(),+ steps: steps)+ }++ func run(_ id: String) -> Run? {+ runs.first { $0.id == id } ?? Self.load(traces.root.appendingPathComponent(id))+ }++ func delete(_ run: Run) {+ try? FileManager.default.removeItem(at: run.folder)+ runs.removeAll { $0.id == run.id }+ }+}diff --git a/ios/IPhoneAgent/Services/TraceStore.swift b/ios/IPhoneAgent/Services/TraceStore.swiftnew file mode 100644index 0000000..89cbbb9--- /dev/null+++ b/ios/IPhoneAgent/Services/TraceStore.swift@@ -0,0 +1,74 @@+import Foundation++/// Debug traces: one folder per agent run (Documents/traces/<date>) with every model call, the screenshot it+/// saw, step timings and a metrics.json snapshot. Port of debug.py; Documents is shared with Finder/devicectl.+@MainActor final class TraceStore {+ let root: URL+ private(set) var dir: URL?+ private var n = 0++ init(root: URL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]+ .appendingPathComponent("traces")) {+ self.root = root+ }++ func start(task: String) {+ let f = DateFormatter()+ f.dateFormat = "yyyyMMdd-HHmmss"+ f.locale = Locale(identifier: "en_US_POSIX")+ let d = root.appendingPathComponent(f.string(from: Date()))+ try? FileManager.default.createDirectory(at: d, withIntermediateDirectories: true)+ dir = d+ n = 0+ write(kind: "task", ["task": .str(task)])+ }++ func write(_ frame: Data? = nil, kind: String, _ record: JObject) {+ guard let dir else { return }+ n += 1+ var line = JObject([("n", .int(n)), ("t", .num(now())), ("kind", .str(kind))]).merging(record)+ if let frame {+ let name = String(format: "%03d.jpg", n)+ line["frame"] = .str(name)+ try? frame.write(to: dir.appendingPathComponent(name))+ }+ append(PyJSON.dumps(line, ascii: false) + "\n", to: dir.appendingPathComponent("steps.jsonl"))+ }++ func writeMetrics(_ metrics: [String: Any]) {+ guard let dir, JSONSerialization.isValidJSONObject(metrics),+ let data = try? JSONSerialization.data(withJSONObject: metrics, options: [.prettyPrinted, .sortedKeys])+ else { return }+ try? data.write(to: dir.appendingPathComponent("metrics.json"))+ }++ func runs() -> [URL] {+ let items = (try? FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil)) ?? []+ return items.filter(\.hasDirectoryPath).sorted { $0.lastPathComponent > $1.lastPathComponent }+ }++ /// All traces zipped (via a coordinated read "for uploading"), for the share sheet.+ nonisolated static func zip(_ folder: URL, name: String = "traces.zip") throws -> URL {+ var result: URL?, failure: Error?+ var coordError: NSError?+ NSFileCoordinator().coordinate(readingItemAt: folder, options: .forUploading, error: &coordError) { tmp in+ let out = FileManager.default.temporaryDirectory.appendingPathComponent(name)+ try? FileManager.default.removeItem(at: out)+ do { try FileManager.default.copyItem(at: tmp, to: out); result = out } catch { failure = error }+ }+ if let e = coordError ?? failure { throw e }+ guard let result else { throw DeviceError(message: "zip failed") }+ return result+ }++ private func append(_ text: String, to url: URL) {+ let data = Data(text.utf8)+ if let h = try? FileHandle(forWritingTo: url) {+ h.seekToEndOfFile()+ h.write(data)+ try? h.close()+ } else {+ try? data.write(to: url)+ }+ }+}diff --git a/ios/IPhoneAgent/UI/AboutView.swift b/ios/IPhoneAgent/UI/AboutView.swiftnew file mode 100644index 0000000..8f22a0d--- /dev/null+++ b/ios/IPhoneAgent/UI/AboutView.swift@@ -0,0 +1,182 @@+import SwiftUI++/// Settings › About: version, source code, acknowledgements, disclaimer and the text logs.+struct AboutView: View {+ @ObservedObject var app: AppModel+ static let repo = URL(string: "https://github.com/onehumanbeing/esp32-iphone-agent")!+ static let author = URL(string: "https://x.com/iamhenryyuan")!+ static let discord = URL(string: "https://discord.gg/BSJEnfdDX")!++ private var version: String {+ let info = Bundle.main.infoDictionary+ return "\(info?["CFBundleShortVersionString"] as? String ?? "1.0") (\(info?["CFBundleVersion"] as? String ?? "1"))"+ }++ var body: some View {+ List {+ Section {+ VStack(spacing: Space.m) {+ Image("Logo").resizable().scaledToFit().frame(width: 96, height: 96)+ .accessibilityHidden(true)+ Text(verbatim: "ESP32 Agent").font(.title2.bold())+ Text("Version \(version)").font(.subheadline).foregroundStyle(.secondary)+ }+ .frame(maxWidth: .infinity)+ .padding(.vertical, Space.s)+ .listRowBackground(Color.clear)+ }+ Section("Community") {+ CommunityRow(logo: "GitHubMark", title: "View source on GitHub", url: Self.repo)+ CommunityRow(logo: "XLogo", title: "Author on X", detail: "@iamhenryyuan", url: Self.author)+ CommunityRow(logo: "DiscordLogo", title: "Join the Discord", url: Self.discord)+ }+ Section {+ NavigationLink { AcknowledgementsView() } label: {+ SettingsLabel(title: "Acknowledgements", symbol: "heart.fill", color: .pink)+ }+ NavigationLink { DisclaimerView() } label: {+ SettingsLabel(title: "Disclaimer", symbol: "exclamationmark.shield.fill", color: .orange)+ }+ } footer: {+ Text("Open source. No data leaves this iPhone except the requests to the model endpoint you set up.")+ }+ Section {+ NavigationLink { LogsView(app: app) } label: {+ SettingsLabel(title: "Logs", symbol: "text.alignleft", color: .gray)+ }+ }+ }+ .navigationTitle("About")+ .navigationBarTitleDisplayMode(.inline)+ }+}++/// A link row with a brand mark (template image: black or white with the appearance), opened with openURL.+struct CommunityRow: View {+ let logo: String+ let title: LocalizedStringKey+ var detail: String?+ let url: URL+ @Environment(\.openURL) private var openURL++ var body: some View {+ Button { openURL(url) } label: {+ HStack {+ Label {+ Text(title)+ } icon: {+ Image(logo).renderingMode(.template).resizable().scaledToFit()+ .frame(width: 20, height: 20)+ .frame(width: 29, height: 29)+ .background(Color(.tertiarySystemFill), in: RoundedRectangle(cornerRadius: 7, style: .continuous))+ .accessibilityHidden(true)+ }+ Spacer()+ if let detail { Text(verbatim: detail).foregroundStyle(.secondary) }+ Image(systemName: "arrow.up.forward").font(.footnote).foregroundStyle(.tertiary)+ }+ }+ .tint(.primary)+ }+}++struct AcknowledgementsView: View {+ private let items: [(name: String, license: String, note: LocalizedStringKey)] = [+ ("UxPlay", "GPL-3.0", "The board's AirPlay receiver is ported from UxPlay."),+ ("Arduino-ESP32 / ESP-IDF", "LGPL-2.1 / Apache-2.0", "Espressif's frameworks for the board firmware."),+ ("NimBLE", "Apache-2.0", "The board's Bluetooth LE stack."),+ ("TinyUSB", "MIT", "The board's USB mouse and keyboard."),+ ]++ var body: some View {+ List {+ ForEach(items, id: \.name) { item in+ VStack(alignment: .leading, spacing: Space.xs) {+ HStack {+ Text(verbatim: item.name).font(.headline)+ Spacer()+ Text(verbatim: item.license).font(.caption.weight(.semibold)).foregroundStyle(.secondary)+ }+ Text(item.note).font(.subheadline).foregroundStyle(.secondary)+ }+ .padding(.vertical, Space.xs)+ }+ }+ .navigationTitle("Acknowledgements")+ .navigationBarTitleDisplayMode(.inline)+ }+}++struct DisclaimerView: View {+ var body: some View {+ ScrollView {+ VStack(alignment: .leading, spacing: Space.l) {+ PokeableFace(mood: .idle).frame(width: 64, height: 72)+ Text(Disclaimer.text).font(.body)+ }+ .padding(Space.xl)+ }+ .navigationTitle("Disclaimer")+ .navigationBarTitleDisplayMode(.inline)+ }+}++/// The app's text log, newest first; copyable.+struct LogsView: View {+ @ObservedObject var app: AppModel+ @State private var shareURL: URL?+ @State private var exporting = false++ var body: some View {+ List {+ Section {+ Button { exportAll() } label: {+ HStack {+ Label("Export all logs", systemImage: "archivebox")+ Spacer()+ if exporting { ProgressView() }+ }+ }+ .disabled(exporting)+ if FileManager.default.fileExists(atPath: DebugLog.url.path) {+ ShareLink(item: DebugLog.url) { Label("Share debug log", systemImage: "doc.text.magnifyingglass") }+ }+ } footer: {+ Text("A zip of debug.log and every run (steps, model replies, screenshots, video). Your API key is never in it.")+ }+ if app.log.isEmpty {+ Text("Nothing logged yet.").foregroundStyle(.secondary)+ }+ ForEach(app.log.reversed()) { line in+ VStack(alignment: .leading, spacing: 2) {+ Text(line.time, format: .dateTime.hour().minute().second()).font(.caption2).foregroundStyle(.secondary)+ Text(verbatim: line.text).font(.caption.monospaced()).textSelection(.enabled)+ }+ }+ }+ .listStyle(.plain)+ .sheet(item: $shareURL) { ShareSheet(items: [$0]) }+ .navigationTitle("Logs")+ .navigationBarTitleDisplayMode(.inline)+ .toolbar {+ ToolbarItem(placement: .topBarTrailing) {+ ShareLink(item: app.log.map { "\($0.time.formatted(.iso8601)) \($0.text)" }.joined(separator: "\n"))+ }+ }+ }++ /// Zip the whole Documents folder (debug.log, debug.1.log, traces/) off the main thread.+ private func exportAll() {+ exporting = true+ let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]+ DebugLog.write("export: all logs")+ Task {+ let result = await Task.detached { Result { try TraceStore.zip(docs, name: "iphone-agent-logs.zip") } }.value+ exporting = false+ switch result {+ case .success(let url): shareURL = url+ case .failure(let e): app.say("export: \(e.localizedDescription)")+ }+ }+ }+}diff --git a/ios/IPhoneAgent/UI/CalibrationToast.swift b/ios/IPhoneAgent/UI/CalibrationToast.swiftnew file mode 100644index 0000000..248f25d--- /dev/null+++ b/ios/IPhoneAgent/UI/CalibrationToast.swift@@ -0,0 +1,175 @@+import SwiftUI++/// Lives in the overlay window above every page: the calibration board while it is open, and a small toast+/// at the top after a successful calibration.+struct CalibrationOverlay: View {+ @ObservedObject var calibrator: AutoCalibrator+ @ObservedObject var probe: TouchProbe+ @ObservedObject var pointer: Pointer++ var body: some View {+ ZStack(alignment: .top) {+ if calibrator.boardOpen {+ CalibrationBoard(calibrator: calibrator, probe: probe).transition(.opacity)+ }+ if calibrator.toast {+ CalibratedToast(pointer: pointer)+ .padding(.top, Space.s)+ .transition(.move(edge: .top).combined(with: .opacity))+ .allowsHitTesting(false)+ }+ }+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .animation(.spring(response: 0.4, dampingFraction: 0.85), value: calibrator.toast)+ .animation(.easeOut(duration: 0.25), value: calibrator.boardOpen)+ }+}++/// The full-screen calibration board: a white grid (so the dark pointer stands out, for the pixel finder,+/// the vision model and the user), Back at the top right, and a card at the bottom with progress, or after+/// a failure the problem, Try Again and "Tap the pointer yourself".+struct CalibrationBoard: View {+ @ObservedObject var calibrator: AutoCalibrator+ @ObservedObject var probe: TouchProbe++ var body: some View {+ ZStack {+ ProbeGrid(flashes: probe.flashes)+ VStack {+ HStack {+ Spacer()+ Button { calibrator.cancel() } label: {+ Text("Back").font(.body.weight(.semibold)).foregroundStyle(.black)+ .padding(.horizontal, Space.l).padding(.vertical, Space.s)+ .background(Color.white, in: Capsule())+ .overlay(Capsule().stroke(Color.black, lineWidth: 1.5))+ }+ .area("back", probe)+ }+ .padding(.trailing, Space.xl)+ .padding(.top, Space.s)+ Spacer()+ card.padding(.horizontal, Space.l).padding(.bottom, Space.xs)+ }+ }+ .environment(\.colorScheme, .light)+ .onChange(of: calibrator.phase) { _, p in if p == .failed { Haptics.stop() } }+ }++ private var card: some View {+ HStack(alignment: .top, spacing: Space.m) {+ AgentFace(mood: mood, showsTab: false).frame(width: 30, height: 30)+ VStack(alignment: .leading, spacing: Space.s) {+ switch calibrator.phase {+ case .failed:+ Text("Calibration didn't work").font(.subheadline.weight(.semibold))+ if let problem = calibrator.problem {+ Text(verbatim: problem).font(.footnote).foregroundStyle(.secondary)+ .fixedSize(horizontal: false, vertical: true)+ }+ HStack(spacing: Space.s) {+ Button("Try Again") { calibrator.calibrate() }+ .buttonStyle(.borderedProminent).area("retry", probe)+ Button("Tap the pointer yourself") { calibrator.startManual() }+ .buttonStyle(.bordered).area("manual", probe)+ }+ .controlSize(.small).buttonBorderShape(.capsule).padding(.top, Space.xs)+ case .needsTap:+ Text("Tap exactly where the pointer is").font(.subheadline.weight(.semibold))+ Text("It's the grey dot, near the top left.").font(.footnote).foregroundStyle(.secondary)+ default:+ Group {+ if let p = calibrator.progress {+ Text("Calibrating pointer… \(p.done)/\(p.total)")+ } else {+ Text("Calibrating pointer…")+ }+ }+ .font(.subheadline.weight(.semibold)).monospacedDigit()+ Text("Hands off the screen for a few seconds.").font(.footnote).foregroundStyle(.secondary)+ }+ }+ Spacer(minLength: 0)+ }+ .padding(Space.m)+ .frame(maxWidth: 440)+ .background(Color.white, in: RoundedRectangle(cornerRadius: 16, style: .continuous))+ .overlay(RoundedRectangle(cornerRadius: 16, style: .continuous).stroke(Color.black.opacity(0.15)))+ .shadow(color: .black.opacity(0.1), radius: 8, y: 2)+ }++ private var mood: Mood {+ switch calibrator.phase {+ case .failed: return .failure+ case .needsTap: return .listening+ default: return .acting+ }+ }+}++private extension View {+ /// Register this button's frame so the board lets touches through to it.+ func area(_ id: String, _ probe: TouchProbe) -> some View {+ onGeometryChange(for: CGRect.self) { $0.frame(in: .global) } action: { probe.setButtonArea(id, $0) }+ .onDisappear { probe.setButtonArea(id, nil) }+ }+}++/// White, lines every 10% (darker every 50%), labels 100-900 on the top and left edges, a coloured square+/// in each corner (red, green, blue, orange from top-left, clockwise from the top) to register a frame, and a+/// dot where each probe tap landed.+struct ProbeGrid: View {+ let flashes: [CGPoint]+ static let corners: [Color] = [.red, .green, .orange, .blue] // TL, TR, BR, BL++ var body: some View {+ Canvas { ctx, size in+ ctx.fill(Path(CGRect(origin: .zero, size: size)), with: .color(.white))+ for i in 1..<10 {+ let x = size.width * Double(i) / 10, y = size.height * Double(i) / 10+ var line = Path()+ line.move(to: CGPoint(x: x, y: 0)); line.addLine(to: CGPoint(x: x, y: size.height))+ line.move(to: CGPoint(x: 0, y: y)); line.addLine(to: CGPoint(x: size.width, y: y))+ ctx.stroke(line, with: .color(.black.opacity(i == 5 ? 0.55 : 0.28)), lineWidth: i == 5 ? 1.5 : 1)+ let label = Text(verbatim: "\(i * 100)").font(.system(size: 10, weight: .semibold).monospacedDigit())+ .foregroundStyle(Color.black.opacity(0.7))+ ctx.draw(label, at: CGPoint(x: x + 2, y: size.height * 0.035), anchor: .leading)+ ctx.draw(label, at: CGPoint(x: 4, y: y - 1), anchor: .bottomLeading)+ }+ let m: CGFloat = 26, inset = min(size.width, size.height) * 0.03+ let origins = [CGPoint(x: inset, y: inset), CGPoint(x: size.width - inset - m, y: inset),+ CGPoint(x: size.width - inset - m, y: size.height - inset - m),+ CGPoint(x: inset, y: size.height - inset - m)]+ for (o, color) in zip(origins, Self.corners) {+ ctx.fill(Path(CGRect(x: o.x, y: o.y, width: m, height: m)), with: .color(color))+ ctx.fill(Path(CGRect(x: o.x + 8, y: o.y + 8, width: m - 16, height: m - 16)), with: .color(.white))+ }+ for f in flashes {+ let r = CGRect(x: f.x * size.width - 7, y: f.y * size.height - 7, width: 14, height: 14)+ ctx.fill(Path(ellipseIn: r), with: .color(.green.opacity(0.75)))+ }+ }+ .ignoresSafeArea()+ .allowsHitTesting(false)+ .accessibilityHidden(true)+ }+}++/// "Pointer calibrated ±0.6%", briefly, at the top.+struct CalibratedToast: View {+ @ObservedObject var pointer: Pointer++ var body: some View {+ Label {+ Text("Pointer calibrated \(pointer.quality.map(CalibrationText.percent) ?? "")").monospacedDigit()+ } icon: {+ Image(systemName: "checkmark.circle.fill").foregroundStyle(Palette.ok)+ }+ .font(.subheadline.weight(.semibold))+ .padding(.horizontal, Space.l)+ .padding(.vertical, Space.s)+ .background(.regularMaterial, in: Capsule())+ .shadow(color: .black.opacity(0.12), radius: 10, y: 3)+ .onAppear { Haptics.success() }+ }+}diff --git a/ios/IPhoneAgent/UI/CalibrationViews.swift b/ios/IPhoneAgent/UI/CalibrationViews.swiftnew file mode 100644index 0000000..db31d9d--- /dev/null+++ b/ios/IPhoneAgent/UI/CalibrationViews.swift@@ -0,0 +1,85 @@+import SwiftUI++/// The calibration state in words, e.g. "±0.6%".+struct CalibrationText: View {+ @ObservedObject var calibrator: AutoCalibrator+ @ObservedObject var pointer: Pointer++ var body: some View {+ Group {+ if calibrator.busy {+ Text("Calibrating…")+ } else if let q = pointer.quality, pointer.calibrated {+ Text(verbatim: Self.percent(q))+ } else if pointer.calibrated {+ Text("Calibrated")+ } else {+ Text("Not calibrated")+ }+ }+ .monospacedDigit()+ }++ static func percent(_ q: Double) -> String { String(format: "±%.1f%%", q * 100) }+}++/// A round Calibrate button under the record button, shown only when calibration is due and the mouse and+/// mirroring are up; it wiggles every few seconds. The first time, a small hint says why. Tapping it opens+/// the calibration board.+struct CalibrateButton: View {+ @ObservedObject var calibrator: AutoCalibrator+ @ObservedObject var board: BoardLink // re-evaluates `offer` on status changes+ @ObservedObject var pointer: Pointer+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @AppStorage("calibrateHintSeen") private var hintSeen = false+ @State private var wiggles = 0++ var body: some View {+ if calibrator.offer {+ HStack(alignment: .top, spacing: Space.s) {+ if !hintSeen && !pointer.calibrated {+ Text("Calibrate before first use")+ .font(.caption.weight(.semibold))+ .padding(.horizontal, Space.m).padding(.vertical, Space.s)+ .background(.regularMaterial, in: Capsule())+ .padding(.top, 6)+ .transition(.opacity.combined(with: .move(edge: .trailing)))+ }+ Button {+ hintSeen = true+ calibrator.calibrate()+ } label: {+ VStack(spacing: 2) {+ Image(systemName: "scope")+ .font(.system(size: 19, weight: .semibold))+ .foregroundStyle(.white)+ .frame(width: 44, height: 44)+ .background(Circle().fill(Color.accentColor))+ .shadow(color: .black.opacity(0.18), radius: 6, y: 2)+ Text("Calibrate").font(.caption2.weight(.medium)).foregroundStyle(Color.accentColor)+ }+ }+ .buttonStyle(.plain)+ .keyframeAnimator(initialValue: 0.0, trigger: wiggles) { view, angle in+ view.rotationEffect(.degrees(angle))+ } keyframes: { _ in+ KeyframeTrack {+ SpringKeyframe(-12, duration: 0.1)+ SpringKeyframe(10, duration: 0.12)+ SpringKeyframe(-6, duration: 0.12)+ SpringKeyframe(0, duration: 0.2)+ }+ }+ .accessibilityLabel(Text("Calibrate"))+ .accessibilityHint(Text("Calibrates the pointer on a grid; takes a few seconds."))+ }+ .task {+ while !Task.isCancelled {+ try? await Task.sleep(nanoseconds: 4_000_000_000)+ if !reduceMotion { wiggles += 1 }+ }+ }+ .transition(.scale.combined(with: .opacity))+ }+ }+}diff --git a/ios/IPhoneAgent/UI/DiagnosticsView.swift b/ios/IPhoneAgent/UI/DiagnosticsView.swiftnew file mode 100644index 0000000..d3566a1--- /dev/null+++ b/ios/IPhoneAgent/UI/DiagnosticsView.swift@@ -0,0 +1,100 @@+import SwiftUI++/// Live metrics and the built-in tests (BLE bench, snap latency, LLM ping, background run), plus trace export.+struct DiagnosticsView: View {+ @ObservedObject var app: AppModel+ @ObservedObject var metrics: Metrics+ @ObservedObject var board: BoardLink+ @ObservedObject var feed: VideoFeed+ @State private var busy = false+ @State private var shareURL: URL?++ var body: some View {+ List {+ SwiftUI.Section("Tests") {+ test("BLE bench (256 KB)", "speedometer") { await app.bench() }+ test("Snap latency", "camera.viewfinder") { await app.snapTest() }+ test("LLM ping", "bolt") { await app.pingLLM() }+ test("Background test (10 min)", "moon.zzz") { await app.backgroundTest() }+ Button { export() } label: { Label("Export traces", systemImage: "square.and.arrow.up") }+ }+ SwiftUI.Section("BLE") {+ row("App-side video kbps", f(metrics.bleKbps))+ row("Board BLE kbps", f(board.status?.ble?.kbps))+ row("Bench kbps", f(metrics.benchKbps))+ row("MTU (app / board)", "\(metrics.mtu) / \(board.status?.ble?.mtu.map(String.init) ?? "–")")+ row("PHY", board.status?.ble?.phy.map { "\($0)M" } ?? "–")+ row("Drops (app / board)", "\(metrics.drops) / \(board.status?.ble?.drop.map(String.init) ?? "–")")+ row("Status age", String(format: "%.1f s", metrics.statusAge))+ }+ SwiftUI.Section("Video") {+ row("AirPlay kbps", f(board.status?.kbps))+ row("AirPlay fps", f(board.status?.fps, "%.1f"))+ row("IDR interval (board / app)", "\(board.status?.idr.map { "\($0) ms" } ?? "–") / \(f(metrics.idrIntervalMs)) ms")+ row("GOP buffered", board.status?.gop.map { "\($0 / 1024) KB" } ?? "–")+ row("Resolution", board.status.map { "\($0.w ?? 0) x \($0.h ?? 0)" } ?? "–")+ row("Decoded fps", f(metrics.fps, "%.1f"))+ row("Decode", f(metrics.decodeMs, "%.1f") + " ms")+ row("Snap -> decoded", f(metrics.snapMs) + " ms")+ row("Decode errors (bg)", "\(metrics.decodeErrors) (\(metrics.backgroundDecodeErrors))")+ if !feed.note.isEmpty { Text(feed.note).font(.caption) }+ }+ SwiftUI.Section("Agent") {+ row("LLM first token / total", "\(f(metrics.llmFirstMs)) / \(f(metrics.llmTotalMs)) ms")+ row("LLM ping", f(metrics.llmPingMs) + " ms")+ if let s = metrics.steps.last {+ row("Last step frame / LLM / HID", "\(f(s.frameMs)) / \(f(s.llmMs)) / \(f(s.hidMs)) ms")+ }+ ForEach(metrics.hidMs.keys.sorted(), id: \.self) { k in row("HID \(k)", f(metrics.hidMs[k]) + " ms") }+ }+ SwiftUI.Section("Background") {+ row("Alive in background", String(format: "%.0f s", metrics.backgroundAlive))+ row("Suspensions", "\(metrics.suspensions)")+ }+ SwiftUI.Section("Board") {+ row("Uptime", board.status?.up.map { "\($0 / 1000) s" } ?? "–")+ row("Reset reason", board.status?.rst ?? "–")+ row("Heap", board.status?.heap.map { "\($0 / 1024) KB" } ?? "–")+ row("PSRAM", board.status?.psram.map { "\($0 / 1024) KB" } ?? "–")+ row("USB", board.status?.usb ?? "–")+ row("Network", "\(board.status?.net ?? "–") \(board.status?.ip ?? "")")+ }+ }+ .navigationTitle("Diagnostics")+ .navigationBarTitleDisplayMode(.inline)+ .sheet(item: $shareURL) { ShareSheet(items: [$0]) }+ }++ private func test(_ title: LocalizedStringKey, _ symbol: String, _ run: @escaping () async -> Void) -> some View {+ Button {+ busy = true+ Haptics.tick()+ Task { await run(); busy = false }+ } label: {+ HStack {+ Label(title, systemImage: symbol)+ Spacer()+ if busy { ProgressView() }+ }+ }+ .disabled(busy)+ }++ private func export() {+ do { shareURL = try TraceStore.zip(app.traces.root) } catch { app.say("export: \(error.localizedDescription)") }+ }++ private func row(_ k: LocalizedStringKey, _ v: String) -> some View { ValueRow(title: k, value: v) }++ private func f(_ v: Double?, _ format: String = "%.0f") -> String { v.map { String(format: format, $0) } ?? "–" }+}++extension URL: @retroactive Identifiable { public var id: String { absoluteString } }++struct ShareSheet: UIViewControllerRepresentable {+ let items: [Any]+ func makeUIViewController(context: Context) -> UIActivityViewController {+ UIActivityViewController(activityItems: items, applicationActivities: nil)+ }+ func updateUIViewController(_ vc: UIActivityViewController, context: Context) {}+}diff --git a/ios/IPhoneAgent/UI/HomeParts.swift b/ios/IPhoneAgent/UI/HomeParts.swiftnew file mode 100644index 0000000..017a497--- /dev/null+++ b/ios/IPhoneAgent/UI/HomeParts.swift@@ -0,0 +1,128 @@+import SwiftUI++/// The character takes off before a run: a hop, then up and away (a fade under Reduce Motion).+struct DepartureOverlay: View {+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @State private var gone = false++ var body: some View {+ ZStack {+ Rectangle().fill(.ultraThinMaterial).ignoresSafeArea()+ VStack(spacing: Space.l) {+ AgentFace(mood: .acting)+ .frame(width: 140, height: 157)+ .offset(y: gone && !reduceMotion ? -520 : 0)+ .scaleEffect(gone && !reduceMotion ? 0.6 : 1)+ .opacity(gone ? 0 : 1)+ Text("See you later!").font(.title2.bold()).opacity(gone ? 0 : 1)+ }+ }+ .transition(.opacity)+ .onAppear {+ withAnimation(.easeIn(duration: 0.4).delay(0.35)) { gone = true } // 0.75 s, inside the 0.8 s wait+ }+ .accessibilityLabel(Text("Starting"))+ }+}++/// "Needs your help": why, and Take over / Continue / Skip / Stop (the same as the Live Activity).+struct HelpPanel: View {+ @ObservedObject var app: AppModel++ var body: some View {+ Section {+ Label { Text(verbatim: app.help ?? "") } icon: {+ Image(systemName: "hand.raised.fill").foregroundStyle(Palette.warning)+ }+ .font(.body.weight(.semibold))+ if app.takingOver {+ Text("Do the step yourself, then tap Continue.").font(.subheadline).foregroundStyle(.secondary)+ }+ HStack(spacing: Space.s) {+ if app.takingOver {+ Button { app.answerHelp(.resume) } label: { Label("Continue", systemImage: "play.fill") }+ .buttonStyle(.borderedProminent).tint(Palette.ok)+ } else {+ Button { app.takeOver() } label: { Label("Take Over", systemImage: "hand.point.up.left.fill") }+ .buttonStyle(.borderedProminent)+ }+ Button { app.answerHelp(.skip) } label: { Text("Skip Step") }.buttonStyle(.bordered)+ Spacer()+ Button(role: .destructive) { Task { await app.stopAgent() } } label: { Image(systemName: "stop.fill") }+ .buttonStyle(.bordered).accessibilityLabel(Text("Stop"))+ }+ .controlSize(.regular)+ } header: {+ Text("Needs your help")+ }+ }+}++/// The run is paused for a lost link: what is missing, how long, and what (if anything) the user should do.+struct RecoveryPanel: View {+ @ObservedObject var app: AppModel+ let stage: Recovery.Stage++ var body: some View {+ Section {+ HStack(spacing: Space.m) {+ if stage.ask {+ Image(systemName: "hand.raised.fill").foregroundStyle(Palette.warning)+ } else {+ ProgressView()+ }+ Text(verbatim: stage.status.full).font(.body.weight(.semibold))+ Spacer()+ Text(timerInterval: app.recoverySince...Date.distantFuture, countsDown: false)+ .font(.subheadline.monospacedDigit()).foregroundStyle(.secondary)+ }+ Text(verbatim: stage.line).font(.subheadline).foregroundStyle(.secondary)+ HStack {+ Spacer()+ Button(role: .destructive) { Task { await app.stopAgent() } } label: { Label("Stop", systemImage: "stop.fill") }+ .buttonStyle(.bordered)+ }+ } header: {+ Text("Connection lost, run paused")+ }+ }+}++/// A demonstration in progress: timer, screens captured, Stop / Cancel; then "working out the steps".+struct RecordingPanel: View {+ @ObservedObject var recorder: DemoRecorder++ var body: some View {+ Section {+ if recorder.recording {+ HStack {+ Image(systemName: "record.circle.fill").foregroundStyle(.red)+ .symbolEffect(.pulse, options: .repeating)+ Text(timerInterval: recorder.started...Date.distantFuture, countsDown: false)+ .font(.title3.monospacedDigit().weight(.semibold))+ Spacer()+ Text("\(recorder.keyframes) screens").foregroundStyle(.secondary).monospacedDigit()+ }+ Text("Go to the Home Screen and do the task. Stop here or in the Dynamic Island.")+ .font(.subheadline).foregroundStyle(.secondary)+ HStack {+ Button { Task { await recorder.stop() } } label: { Label("Stop Recording", systemImage: "stop.fill") }+ .buttonStyle(.borderedProminent).tint(.red)+ Spacer()+ Button("Cancel", role: .destructive) { recorder.cancel() }+ }+ } else if recorder.inferring {+ HStack(spacing: Space.m) {+ ProgressView()+ Text("Working out the steps from \(recorder.keyframes) screens…")+ }+ } else if let error = recorder.error {+ Label { Text(verbatim: error) } icon: { Image(systemName: "exclamationmark.triangle.fill") }+ .foregroundStyle(Palette.warning)+ Button("OK") { recorder.error = nil }+ }+ } header: {+ Text("Recording")+ }+ }+}diff --git a/ios/IPhoneAgent/UI/HomeView.swift b/ios/IPhoneAgent/UI/HomeView.swiftnew file mode 100644index 0000000..310e686--- /dev/null+++ b/ios/IPhoneAgent/UI/HomeView.swift@@ -0,0 +1,325 @@+import SwiftUI++/// The Agent tab: the character, what is ready, the task, saved intents, and Start pinned at the bottom.+struct HomeView: View {+ @ObservedObject var app: AppModel+ @ObservedObject var board: BoardLink+ @ObservedObject var feed: VideoFeed+ @ObservedObject var agent: AgentLoop+ @ObservedObject var settings: Settings+ @ObservedObject var intents: IntentStore+ @ObservedObject var recorder: DemoRecorder+ @State private var task = ""+ @State private var recordSheet = false+ @State private var askNotifications = false+ @State private var pending: (String, SavedTask?)?+ @State private var naming = false+ @State private var intentName = ""+ @FocusState private var editing: Bool+ @State private var renaming = false++ var body: some View {+ NavigationStack {+ List {+ Section { hero }+ .listRowBackground(Color.clear)+ .listRowInsets(EdgeInsets())+ if recorder.recording || recorder.inferring || recorder.error != nil {+ RecordingPanel(recorder: recorder)+ }+ if app.help != nil { HelpPanel(app: app) }+ if let stage = app.recovering { RecoveryPanel(app: app, stage: stage) }+ if agent.running || app.runMood != nil { liveSection }+ taskSection+ intentSection+ }+ .listStyle(.insetGrouped)+ .scrollDismissesKeyboard(.interactively)+ .navigationTitle(Text(verbatim: settings.agentName))+ .navigationBarTitleDisplayMode(.inline)+ .navigationDestination(for: UUID.self) { id in IntentDetailView(app: app, intents: intents, id: id) }+ .toolbar {+ ToolbarItem(placement: .principal) {+ Button { renaming = true } label: {+ HStack(spacing: 4) {+ Text(verbatim: settings.agentName).font(.headline).foregroundStyle(.primary)+ Image(systemName: "pencil").font(.caption.weight(.semibold)).foregroundStyle(.tertiary)+ }+ }+ .accessibilityLabel(Text("Rename \(settings.agentName)"))+ }+ ToolbarItem(placement: .topBarTrailing) {+ Button { recordSheet = true } label: {+ Image(systemName: recorder.recording ? "record.circle.fill" : "record.circle")+ .foregroundStyle(recorder.recording ? Color.red : Color.accentColor)+ .symbolEffect(.pulse, options: .repeating, isActive: recorder.recording)+ }+ .accessibilityLabel(Text("New intent"))+ .disabled(recorder.recording || recorder.inferring)+ }+ }+ .sheet(isPresented: $recordSheet) { RecordSheet(app: app, recorder: recorder) }+ .sheet(isPresented: $renaming) { RenameSheet(settings: settings) }+ .alert("Get notified?", isPresented: $askNotifications) {+ Button("Continue") { Task { await app.notifier.requestPermission(); go() } }+ Button("Not Now", role: .cancel) { UserDefaults.standard.set(true, forKey: Notifier.askedKey); go() }+ } message: {+ Text("I'll tell you when a run is done or needs your help, since you won't see this app while I work.")+ }+ .overlay { if app.departing { DepartureOverlay() } }+ .overlay(alignment: .top) {+ if let hint = app.homeHint {+ Label { Text(verbatim: hint) } icon: { Image(systemName: "arrow.up.to.line") }+ .font(.subheadline.weight(.semibold))+ .padding(.horizontal, Space.l).padding(.vertical, Space.s)+ .background(.regularMaterial, in: Capsule())+ .padding(.top, Space.s)+ .transition(.move(edge: .top).combined(with: .opacity))+ }+ }+ .animation(.easeOut(duration: 0.25), value: app.homeHint)+ .overlay(alignment: .topTrailing) { // right under the record button+ if !agent.running {+ CalibrateButton(calibrator: app.calibrator, board: board, pointer: app.pointer)+ .padding(.trailing, Space.l).padding(.top, Space.xs)+ }+ }+ .safeAreaInset(edge: .bottom) { bottomBar }+ .alert("Save as intent", isPresented: $naming) {+ TextField("Name", text: $intentName)+ Button("Save") { intents.add(name: intentName, prompt: task); Haptics.success() }+ Button("Cancel", role: .cancel) {}+ } message: {+ Text("Run it again later with one tap.")+ }+ .animation(.spring(response: 0.4, dampingFraction: 0.85), value: agent.running)+ }+ }++ // MARK: - hero++ private var hero: some View {+ VStack(spacing: Space.m) {+ PokeableFace(mood: editing ? .listening : app.mood, look: lookAt, busy: app.agent.running)+ .frame(width: 128, height: 143)+ .padding(.top, Space.s)+ Text(greeting)+ .font(.subheadline)+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.center)+ .padding(.horizontal, Space.xl)+ StatusChips(app: app, board: board, pointer: app.pointer, calibrator: app.calibrator)+ }+ .frame(maxWidth: .infinity)+ .padding(.bottom, Space.s)+ }++ /// Where the eyes look while acting: toward the last tap.+ private var lookAt: CGPoint {+ guard let s = agent.steps.last, let x = s["x"]?.double, let y = s["y"]?.double else { return .zero }+ return CGPoint(x: x / 500 - 1, y: y / 500 - 1)+ }++ private var greeting: LocalizedStringKey {+ if app.help != nil { return "I need your help with one step." }+ if app.recovering != nil { return "The connection dropped. I'll go on when it's back." }+ if recorder.recording { return "I'm watching. Do the task, then stop the recording." }+ if agent.running { return "Working on it. Watch the Dynamic Island, or stop me anytime." }+ switch app.runMood {+ case .success: return "Done! Open Runs to replay what I did."+ case .failure: return "That did not work out. The replay shows where I got stuck."+ default: break+ }+ if !board.connected { return "Plug me into the USB-C port to wake me up." }+ if blocker != nil { return "Almost there. Tap an orange item to finish setup." }+ return "Hi, I'm \(settings.agentName). Tell me what to do on this iPhone."+ }++ // MARK: - sections++ private var liveSection: some View {+ Section {+ HStack(alignment: .top, spacing: Space.m) {+ Group {+ if let jpeg = feed.frame, let img = UIImage(data: jpeg) {+ Image(uiImage: img).resizable().scaledToFit()+ } else {+ Color(uiColor: .tertiarySystemFill)+ }+ }+ .frame(width: 64, height: 138)+ .clipShape(RoundedRectangle(cornerRadius: 10, style: .continuous))+ VStack(alignment: .leading, spacing: Space.s) {+ Text(verbatim: agent.task).font(.headline).lineLimit(2)+ if let last = agent.steps.last {+ Label { Text(verbatim: StepText.line(last)).lineLimit(3) } icon: {+ Image(systemName: StepText.symbol(last["action"]?.str))+ }+ .font(.subheadline)+ .foregroundStyle(.secondary)+ }+ ProgressView(value: Double(min(app.moveCount, agent.maxSteps)), total: Double(agent.maxSteps))+ Text("Step \(app.moveCount) of up to \(agent.maxSteps)")+ .font(.caption.monospacedDigit()).foregroundStyle(.secondary)+ }+ }+ .padding(.vertical, Space.xs)+ } header: {+ Text(agent.running ? "Now" : "Last run")+ }+ }++ private var taskSection: some View {+ Section {+ TextField("What should I do on this iPhone?", text: $task, axis: .vertical)+ .lineLimit(3...6)+ .focused($editing)+ .submitLabel(.done)+ if !task.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty {+ Button { intentName = ""; naming = true } label: {+ Label("Save as intent", systemImage: "bookmark")+ }+ }+ } header: {+ HStack {+ Text("Task")+ Spacer()+ Menu {+ ForEach(IntentStore.examples) { e in+ Button(e.name) { task = e.prompt; Haptics.tick() }+ }+ } label: {+ Label("Examples", systemImage: "sparkles").font(.footnote.weight(.semibold)).textCase(nil)+ }+ }+ }+ }++ private var intentSection: some View {+ Section {+ ForEach(intents.items) { item in+ NavigationLink(value: item.id) {+ HStack(spacing: Space.m) {+ SettingsIcon(symbol: item.symbol, color: .accentColor)+ VStack(alignment: .leading, spacing: 2) {+ Text(verbatim: item.name).font(.body).foregroundStyle(.primary)+ Text(verbatim: item.prompt).font(.caption).foregroundStyle(.secondary).lineLimit(1)+ }+ Spacer()+ Button { run(item) } label: {+ Image(systemName: "play.circle.fill").font(.title2).foregroundStyle(Color.accentColor)+ .opacity(blocker == nil && !agent.running ? 1 : 0.35)+ }+ .buttonStyle(.borderless)+ .accessibilityLabel(Text("Run \(item.name)"))+ }+ }+ .contextMenu {+ Button { task = item.prompt } label: { Label("Edit as task", systemImage: "pencil") }+ Button(role: .destructive) { intents.delete(item.id) } label: { Label("Delete", systemImage: "trash") }+ }+ .swipeActions(edge: .trailing) {+ Button(role: .destructive) { intents.delete(item.id) } label: { Label("Delete", systemImage: "trash") }+ }+ }+ HStack(spacing: Space.m) {+ SettingsIcon(symbol: "record.circle", color: Color(uiColor: .systemGray3))+ Text("Record an intent").foregroundStyle(.secondary)+ Spacer()+ Text("Coming soon").font(.caption.weight(.semibold)).foregroundStyle(.secondary)+ .padding(.horizontal, Space.s).padding(.vertical, 3)+ .background(Capsule().fill(Color(uiColor: .tertiarySystemFill)))+ }+ } header: {+ Text("My intents")+ } footer: {+ Text("Tap ▶ to run, tap the row for details. Swipe left to delete.")+ }+ }++ // MARK: - bottom++ private var bottomBar: some View {+ BottomBar {+ if agent.running {+ Button {+ Haptics.stop()+ Task { await app.stopAgent() }+ } label: { Label("Stop", systemImage: "stop.fill") }+ .buttonStyle(BigButton(tint: Palette.stop))+ } else {+ Button { start(task) } label: { Label("Start", systemImage: "play.fill") }+ .buttonStyle(BigButton())+ .disabled(task.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || blocker != nil+ || app.departing || recorder.recording)+ if let blocker {+ Button { app.setupPage = blocker.page } label: {+ Label(blocker.text, systemImage: "exclamationmark.circle").font(.footnote)+ }+ .tint(Palette.warning)+ }+ }+ }+ }++ private func run(_ item: SavedTask) {+ task = item.prompt+ guard blocker == nil, !agent.running else { return }+ start(item.prompt, intent: item)+ }++ /// The first Start asks for notifications (one line why), then the character takes off.+ private func start(_ text: String, intent: SavedTask? = nil) {+ Haptics.start()+ editing = false+ pending = (text, intent)+ if Notifier.asked { go() } else { askNotifications = true }+ }++ private func go() {+ guard let (text, intent) = pending else { return }+ pending = nil+ Task { await app.run(text, intent: intent) }+ }++ /// The first thing missing before a run, and the setup page that fixes it.+ private var blocker: (text: LocalizedStringKey, page: SetupPage)? {+ if !board.connected { return ("Connect the board", .connect) }+ if board.status?.ap != "streaming" { return ("Start Screen Mirroring", .see) }+ if !app.pointer.calibrated { return ("Calibrate the pointer", .act) }+ if !app.modelReady { return ("Set up the model", .brain) }+ return nil+ }+}++/// Rename the agent (title, greeting, Live Activity).+struct RenameSheet: View {+ @ObservedObject var settings: Settings+ @Environment(\.dismiss) private var dismiss+ @State private var name = ""++ var body: some View {+ NavigationStack {+ Form {+ Section {+ TextField("Name", text: $name).submitLabel(.done).onSubmit(save)+ } footer: {+ Text("Shown on the Agent tab, in greetings and in the Live Activity.")+ }+ }+ .navigationTitle("Rename Agent")+ .navigationBarTitleDisplayMode(.inline)+ .toolbar {+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }+ ToolbarItem(placement: .confirmationAction) { Button("Save", action: save) }+ }+ .onAppear { name = settings.agentName }+ }+ .presentationDetents([.height(240)])+ }++ private func save() {+ settings.agentName = name+ dismiss()+ }+}diff --git a/ios/IPhoneAgent/UI/IntentDetailView.swift b/ios/IPhoneAgent/UI/IntentDetailView.swiftnew file mode 100644index 0000000..93c8f9f--- /dev/null+++ b/ios/IPhoneAgent/UI/IntentDetailView.swift@@ -0,0 +1,131 @@+import SwiftUI++/// An intent: run it, its stats (last run, success rate, average time), its words, edit and delete.+struct IntentDetailView: View {+ @ObservedObject var app: AppModel+ @ObservedObject var intents: IntentStore+ let id: UUID+ @Environment(\.dismiss) private var dismiss+ @State private var confirmDelete = false++ var body: some View {+ if let item = intents.item(id) {+ List {+ Section {+ VStack(spacing: Space.m) {+ Image(systemName: item.symbol)+ .font(.system(size: 34, weight: .semibold))+ .foregroundStyle(.white)+ .frame(width: 72, height: 72)+ .background(RoundedRectangle(cornerRadius: 18, style: .continuous).fill(Color.accentColor))+ Text(verbatim: item.name).font(.title2.bold()).multilineTextAlignment(.center)+ }+ .frame(maxWidth: .infinity)+ .listRowBackground(Color.clear)+ }+ Section {+ stat("Last run", item.runs.last.map { ($0.ok ? "✓ " : "✗ ") + $0.date.formatted(.relative(presentation: .named)) })+ stat("Success rate", item.successRate.map { $0.formatted(.percent.precision(.fractionLength(0))) })+ stat("Average time", item.averageSeconds?.durationText)+ stat("Runs", item.runs.isEmpty ? nil : "\(item.runs.count)")+ }+ Section("Instruction") { Text(verbatim: item.prompt) }+ if !item.checklist.isEmpty {+ Section("Checklist") {+ ForEach(item.checklist, id: \.self) { h in+ Label { Text(verbatim: h) } icon: { Image(systemName: "checkmark.circle").foregroundStyle(Palette.ok) }+ }+ }+ }+ Section {+ Button { edit(item) } label: { Label("Edit", systemImage: "slider.horizontal.3") }+ if let last = item.runs.last?.run ?? item.refRun {+ Button { app.openReview(run: last) } label: { Label("Review Last Run", systemImage: "play.rectangle") }+ }+ Button(role: .destructive) { confirmDelete = true } label: { Label("Delete Intent", systemImage: "trash") }+ }+ }+ .navigationTitle(Text(verbatim: item.name))+ .navigationBarTitleDisplayMode(.inline)+ .safeAreaInset(edge: .bottom) {+ BottomBar {+ Button {+ Haptics.start()+ dismiss()+ Task { await app.run(item.prompt, intent: item) }+ } label: { Label("Run", systemImage: "play.fill") }+ .buttonStyle(BigButton())+ .disabled(app.agent.running)+ }+ }+ .confirmationDialog("Delete this intent?", isPresented: $confirmDelete, titleVisibility: .visible) {+ Button("Delete", role: .destructive) { intents.delete(id); dismiss() }+ }+ } else {+ ContentUnavailableView("Intent deleted", systemImage: "trash")+ }+ }++ private func stat(_ title: LocalizedStringKey, _ value: String?) -> some View {+ LabeledContent(title) { Text(verbatim: value ?? "–").monospacedDigit() }+ }++ /// The same editor as a run's review: with its last run's steps if it has one.+ private func edit(_ item: SavedTask) {+ let ref = (item.runs.last?.run ?? item.refRun).flatMap { app.runs.run($0) }+ app.review = ref.map { ReviewDraft(run: $0, intent: item) } ?? ReviewDraft(intent: item)+ }+}++/// The ⏺ sheet: record a demonstration, or save the last run as an intent.+struct RecordSheet: View {+ @ObservedObject var app: AppModel+ @ObservedObject var recorder: DemoRecorder+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ NavigationStack {+ List {+ Section {+ Button {+ recorder.start()+ dismiss()+ } label: {+ option("Record me doing it", "record.circle.fill", .red,+ "Do the task yourself. I watch the mirrored screen and write the steps down.")+ }+ .disabled(!(app.board.connected && app.board.status?.ap == "streaming") || app.agent.running)+ Button {+ guard let last = app.runs.runs.first else { return }+ dismiss()+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.45) { // after the sheet is gone+ app.openReview(run: last.id)+ app.review?.showSaveOnOpen = true+ }+ } label: {+ option("Save last run as intent", "bookmark.fill", .accentColor,+ "Keep the last run as a reference and reuse it with one tap.")+ }+ .disabled(app.runs.runs.isEmpty)+ } footer: {+ Text("Recording needs Screen Mirroring. Your fingers are not visible to the board, so I guess each step from the screen and mark the unsure ones yellow.")+ }+ }+ .navigationTitle("New Intent")+ .navigationBarTitleDisplayMode(.inline)+ .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } } }+ }+ .presentationDetents([.medium])+ }++ private func option(_ title: LocalizedStringKey, _ symbol: String, _ color: Color, _ text: LocalizedStringKey) -> some View {+ HStack(spacing: Space.m) {+ SettingsIcon(symbol: symbol, color: color)+ VStack(alignment: .leading, spacing: 2) {+ Text(title).font(.body.weight(.semibold)).foregroundStyle(.primary)+ Text(text).font(.footnote).foregroundStyle(.secondary)+ }+ }+ .padding(.vertical, Space.xs)+ }+}diff --git a/ios/IPhoneAgent/UI/ModelSettingsView.swift b/ios/IPhoneAgent/UI/ModelSettingsView.swiftnew file mode 100644index 0000000..2a8bd5e--- /dev/null+++ b/ios/IPhoneAgent/UI/ModelSettingsView.swift@@ -0,0 +1,131 @@+import SwiftUI++/// Settings › Model: endpoint, key and the model picked from the endpoint's list; overrides under Advanced.+struct ModelSettingsView: View {+ @ObservedObject var app: AppModel+ @ObservedObject var settings: Settings+ @State private var testing = false+ @State private var advanced = false++ var body: some View {+ Form {+ Section {+ TextField("Base URL", text: $settings.baseURL, prompt: Text(verbatim: "https://example.com/v1"))+ .keyboardType(.URL)+ SecureField("API key", text: $settings.apiKey, prompt: Text("API key (optional)"))+ ModelPicker(settings: settings, title: "Model", selection: $settings.model, automatic: ModelPicker.automatic(settings))+ Button { Task { await settings.loadModels() } } label: {+ HStack {+ Text("Refresh Model List")+ Spacer()+ if settings.loadingModels { ProgressView() }+ }+ }+ .disabled(settings.loadingModels || !settings.isConfigured)+ } header: {+ Text("OpenAI-compatible API")+ } footer: {+ if let error = settings.modelsError {+ Text("Could not load the model list: \(error) Type a model id instead.")+ } else {+ Text("Your key stays in this iPhone's Keychain and is only sent to this endpoint.")+ }+ }+ Section {+ Button {+ testing = true+ Task { await app.pingLLM(); testing = false }+ } label: {+ HStack {+ Text("Test Connection")+ Spacer()+ if testing { ProgressView() } else if let ok = app.modelOK {+ Image(systemName: ok ? "checkmark.circle.fill" : "xmark.octagon.fill")+ .foregroundStyle(ok ? Palette.ok : Palette.stop)+ }+ }+ }+ .disabled(testing || !app.modelReady)+ }+ Section {+ DisclosureGroup("Advanced", isExpanded: $advanced) {+ let same = String(localized: "Same as Model")+ ModelPicker(settings: settings, title: "Planner model", selection: $settings.plannerModel, automatic: same)+ ModelPicker(settings: settings, title: "Actor model", selection: $settings.actorModel, automatic: same)+ Picker("Token parameter", selection: $settings.tokenParam) {+ ForEach(["auto"] + LLMClient.tokenParams, id: \.self) { Text(verbatim: $0) }+ }+ TextField("Extra body JSON", text: $settings.extraBody, prompt: Text(verbatim: "{}"))+ .font(.body.monospaced())+ }+ }+ }+ .textInputAutocapitalization(.never)+ .autocorrectionDisabled()+ .navigationTitle("Model")+ .navigationBarTitleDisplayMode(.inline)+ .task(id: settings.baseURL + "\n" + settings.apiKey) {+ guard (try? await Task.sleep(nanoseconds: 600_000_000)) != nil else { return } // typing: wait for a pause+ await settings.loadModels()+ }+ }+}++/// A model id: a menu of the endpoint's models when the list loaded, else a text field to type one.+/// "" is the automatic choice (`automatic` labels it).+struct ModelPicker: View {+ @ObservedObject var settings: Settings+ let title: LocalizedStringKey+ @Binding var selection: String+ let automatic: String++ static func automatic(_ settings: Settings) -> String {+ settings.models.first.map { String(localized: "Automatic (first: \($0))") } ?? String(localized: "Automatic")+ }++ var body: some View {+ if settings.models.isEmpty {+ LabeledContent {+ if settings.loadingModels && selection.isEmpty {+ ProgressView()+ } else {+ TextField(title, text: $selection, prompt: Text(verbatim: automatic))+ .multilineTextAlignment(.trailing)+ }+ } label: { Text(title) }+ } else {+ Picker(title, selection: $selection) {+ Text(verbatim: automatic).tag("")+ if !selection.isEmpty && !settings.models.contains(selection) { Text(verbatim: selection).tag(selection) }+ ForEach(settings.models, id: \.self) { Text(verbatim: $0).tag($0) }+ }+ .pickerStyle(.menu)+ }+ }+}++/// Onboarding, after Test Connection: the model in use and a menu to change it.+struct PickedModelRow: View {+ @ObservedObject var settings: Settings++ var body: some View {+ HStack {+ VStack(alignment: .leading, spacing: 2) {+ Text("Model").font(.subheadline).foregroundStyle(.secondary)+ Text(verbatim: settings.currentModel ?? ModelPicker.automatic(settings)).font(.body.monospaced()).lineLimit(1)+ }+ Spacer()+ if settings.loadingModels {+ ProgressView()+ } else if !settings.models.isEmpty {+ Menu("Change") {+ Picker("Model", selection: $settings.model) {+ Text(verbatim: ModelPicker.automatic(settings)).tag("")+ ForEach(settings.models, id: \.self) { Text(verbatim: $0).tag($0) }+ }+ }+ }+ }+ .task { if settings.models.isEmpty { await settings.loadModels() } }+ }+}diff --git a/ios/IPhoneAgent/UI/OnboardingDemos.swift b/ios/IPhoneAgent/UI/OnboardingDemos.swiftnew file mode 100644index 0000000..50b1137--- /dev/null+++ b/ios/IPhoneAgent/UI/OnboardingDemos.swift@@ -0,0 +1,247 @@+import SwiftUI++/// A looping mini-iPhone that shows where to tap for a system setting, with a finger and a caption.+/// Under Reduce Motion the frames cross-fade instead of moving.+struct MiniPhoneDemo: View {+ enum Kind { case plugIn, wifi, controlCenter, assistiveTouch }++ let kind: Kind+ var ssid = "ESP32Agent-7C3E"+ @State private var frame = 0+ @Environment(\.accessibilityReduceMotion) private var reduceMotion++ private var frames: [(caption: LocalizedStringKey, finger: CGPoint?)] {+ switch kind {+ case .plugIn:+ return [("Plug the board into the USB-C port", nil), ("Plug the board into the USB-C port", nil),+ ("Tap Pair when iOS asks", CGPoint(x: 0.68, y: 0.56))]+ case .wifi:+ return [("Open Settings › Wi-Fi", CGPoint(x: 0.5, y: 0.3)), ("Choose the board's network", CGPoint(x: 0.5, y: 0.42)),+ ("Paste the password, then Join", CGPoint(x: 0.84, y: 0.13))]+ case .controlCenter:+ return [("Swipe down from the top-right corner", CGPoint(x: 0.85, y: 0.04)),+ ("Swipe down from the top-right corner", CGPoint(x: 0.85, y: 0.36)),+ ("Tap Screen Mirroring", CGPoint(x: 0.3, y: 0.42)), ("Choose “ESP32 Agent”", CGPoint(x: 0.5, y: 0.43))]+ case .assistiveTouch:+ return [("Settings › Accessibility", CGPoint(x: 0.5, y: 0.42)), ("Touch", CGPoint(x: 0.5, y: 0.22)),+ ("AssistiveTouch", CGPoint(x: 0.5, y: 0.22)), ("Turn AssistiveTouch on", CGPoint(x: 0.84, y: 0.22))]+ }+ }++ var body: some View {+ VStack(spacing: Space.m) {+ MiniPhone { screen }+ .overlay { GeometryReader { g in finger(in: g.size) } }+ .frame(width: 132, height: 270)+ Text(frames[frame].caption)+ .font(.subheadline.weight(.semibold))+ .multilineTextAlignment(.center)+ .id(frame)+ .transition(.opacity)+ }+ .frame(maxWidth: .infinity)+ .accessibilityElement(children: .ignore)+ .accessibilityLabel(Text(frames.map(\.caption).last ?? ""))+ .task(id: kind) {+ frame = 0+ while !Task.isCancelled {+ try? await Task.sleep(nanoseconds: frame == frames.count - 1 ? 2_000_000_000 : 1_300_000_000)+ withAnimation(reduceMotion ? .easeInOut(duration: 0.25) : .spring(response: 0.5, dampingFraction: 0.85)) {+ frame = (frame + 1) % frames.count+ }+ }+ }+ }++ @ViewBuilder private func finger(in size: CGSize) -> some View {+ if let p = frames[frame].finger {+ Circle()+ .fill(Color.white.opacity(0.85))+ .overlay(Circle().stroke(Color.black.opacity(0.25), lineWidth: 1))+ .shadow(color: .black.opacity(0.3), radius: 4, y: 2)+ .frame(width: 22, height: 22)+ .position(x: p.x * size.width, y: p.y * size.height)+ .transition(.opacity)+ }+ }++ // MARK: - screens++ @ViewBuilder private var screen: some View {+ switch kind {+ case .plugIn: plugIn+ case .wifi:+ switch frame {+ case 0: MiniList(title: "Settings", rows: ["Airplane Mode", "Wi-Fi", "Bluetooth", "Cellular"], hot: 1)+ case 1: MiniList(title: "Wi-Fi", rows: ["Home", LocalizedStringKey(stringLiteral: ssid), "Office"], hot: 1)+ default: MiniList(title: LocalizedStringKey(stringLiteral: ssid), rows: ["Password", "••••••••"], hot: 1,+ action: "Join")+ }+ case .controlCenter: controlCenter+ case .assistiveTouch:+ switch frame {+ case 0: MiniList(title: "Settings", rows: ["General", "Display", "Accessibility", "Privacy"], hot: 2)+ case 1: MiniList(title: "Accessibility", rows: ["Touch", "Face ID", "Voice Control"], hot: 0)+ case 2: MiniList(title: "Touch", rows: ["AssistiveTouch", "Haptic Touch", "Tap to Wake"], hot: 0)+ default: MiniList(title: "AssistiveTouch", rows: ["AssistiveTouch", "Pointer Devices"], hot: 0, toggle: true)+ }+ }+ }++ private var plugIn: some View {+ ZStack {+ HomeGrid()+ if frame == 2 {+ VStack(spacing: 6) {+ Text("Bluetooth Pairing Request").font(.system(size: 8, weight: .semibold))+ Text(verbatim: "“ESP32 Agent”").font(.system(size: 7))+ HStack(spacing: 0) {+ Text("Cancel").frame(maxWidth: .infinity)+ Text("Pair").fontWeight(.semibold).frame(maxWidth: .infinity)+ }+ .font(.system(size: 8))+ .foregroundStyle(Color.blue)+ }+ .padding(8)+ .frame(width: 100)+ .background(RoundedRectangle(cornerRadius: 10).fill(.regularMaterial))+ .transition(.scale(scale: 0.9).combined(with: .opacity))+ }+ }+ .overlay(alignment: .bottom) {+ AgentFace(mood: frame == 0 ? .sleeping : .idle, animated: false)+ .frame(width: 38, height: 42)+ .rotationEffect(.degrees(180))+ .offset(y: frame == 0 ? 70 : 38)+ .opacity(frame == 0 ? 0.6 : 1)+ }+ }++ private var controlCenter: some View {+ ZStack(alignment: .top) {+ HomeGrid()+ if frame >= 1 {+ Color.black.opacity(0.35)+ VStack(spacing: 6) {+ HStack(spacing: 6) {+ tile(nil, "airplane").frame(height: 34)+ tile(nil, "wifi").frame(height: 34)+ }+ HStack(spacing: 6) {+ tile("Screen Mirroring", "rectangle.on.rectangle", hot: frame == 2).frame(height: 34)+ tile(nil, "flashlight.off.fill").frame(height: 34)+ }+ }+ .padding(.horizontal, 10)+ .padding(.top, 30)+ .transition(.move(edge: .top).combined(with: .opacity))+ }+ if frame == 3 {+ VStack(alignment: .leading, spacing: 6) {+ Text("Screen Mirroring").font(.system(size: 9, weight: .bold))+ HStack {+ Image(systemName: "appletv").font(.system(size: 8))+ Text(verbatim: "Living Room").font(.system(size: 8))+ }+ .foregroundStyle(.secondary)+ HStack {+ Image(systemName: "checkmark").font(.system(size: 8, weight: .bold))+ Text(verbatim: "ESP32 Agent").font(.system(size: 8, weight: .semibold))+ }+ .padding(5)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 6).fill(Color.accentColor.opacity(0.3)))+ }+ .padding(10)+ .background(RoundedRectangle(cornerRadius: 12).fill(.regularMaterial))+ .padding(.horizontal, 10)+ .padding(.top, 90)+ .transition(.scale(scale: 0.9).combined(with: .opacity))+ }+ }+ }++ private func tile(_ title: LocalizedStringKey?, _ symbol: String, hot: Bool = false) -> some View {+ HStack(spacing: 3) {+ Image(systemName: symbol).font(.system(size: 9, weight: .semibold))+ if let title { Text(title).font(.system(size: 6, weight: .semibold)).lineLimit(2) }+ }+ .foregroundStyle(.white)+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .background(RoundedRectangle(cornerRadius: 9).fill(hot ? Color.accentColor : Color.white.opacity(0.22)))+ }+}++/// A phone outline with a Dynamic Island; the content is its screen.+struct MiniPhone<Screen: View>: View {+ @ViewBuilder let screen: Screen++ var body: some View {+ screen+ .frame(maxWidth: .infinity, maxHeight: .infinity)+ .background(Color(uiColor: .systemGroupedBackground))+ .clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))+ .overlay(alignment: .top) { Capsule().fill(.black).frame(width: 36, height: 10).padding(.top, 6) }+ .padding(5)+ .background(RoundedRectangle(cornerRadius: 25, style: .continuous).fill(.black))+ .overlay(RoundedRectangle(cornerRadius: 25, style: .continuous).stroke(Color(uiColor: .systemGray3), lineWidth: 1.5))+ }+}++/// A home screen of colored app icons.+private struct HomeGrid: View {+ private let colors: [Color] = [.blue, .green, .orange, .pink, .purple, .teal, .yellow, .red, .indigo, .mint, .cyan, .gray]++ var body: some View {+ LinearGradient(colors: [.indigo.opacity(0.7), .teal.opacity(0.6)], startPoint: .top, endPoint: .bottom)+ .overlay(alignment: .top) {+ LazyVGrid(columns: Array(repeating: GridItem(.fixed(20), spacing: 9), count: 4), spacing: 10) {+ ForEach(0..<12, id: \.self) { i in+ RoundedRectangle(cornerRadius: 5, style: .continuous).fill(colors[i]).frame(width: 20, height: 20)+ }+ }+ .padding(.top, 34)+ }+ }+}++/// A Settings-style list with one row highlighted.+private struct MiniList: View {+ let title: LocalizedStringKey+ let rows: [LocalizedStringKey]+ let hot: Int+ var toggle = false+ var action: LocalizedStringKey?++ var body: some View {+ VStack(alignment: .leading, spacing: 6) {+ HStack {+ Text(title).font(.system(size: 11, weight: .bold)).lineLimit(1)+ Spacer()+ if let action { Text(action).font(.system(size: 8, weight: .semibold)).foregroundStyle(Color.accentColor) }+ }+ .padding(.top, 26)+ VStack(spacing: 0) {+ ForEach(Array(rows.enumerated()), id: \.offset) { i, row in+ HStack {+ Text(row).font(.system(size: 8)).lineLimit(1)+ Spacer()+ if toggle && i == hot {+ Capsule().fill(Color.green).frame(width: 18, height: 11)+ .overlay(alignment: .trailing) { Circle().fill(.white).frame(width: 9).padding(1) }+ } else {+ Image(systemName: "chevron.right").font(.system(size: 6)).foregroundStyle(.tertiary)+ }+ }+ .padding(.horizontal, 7)+ .frame(height: 22)+ .background(i == hot ? Color.accentColor.opacity(0.22) : Color.clear)+ if i < rows.count - 1 { Divider().padding(.leading, 7) }+ }+ }+ .background(RoundedRectangle(cornerRadius: 8).fill(Color(uiColor: .secondarySystemGroupedBackground)))+ Spacer()+ }+ .padding(.horizontal, 8)+ }+}diff --git a/ios/IPhoneAgent/UI/OnboardingPages.swift b/ios/IPhoneAgent/UI/OnboardingPages.swiftnew file mode 100644index 0000000..e46c714--- /dev/null+++ b/ios/IPhoneAgent/UI/OnboardingPages.swift@@ -0,0 +1,271 @@+import SwiftUI+import UIKit++/// 0 · Welcome: the character wakes up and says hello; the disclaimer must be accepted to go on.+struct WelcomePage: View {+ @Binding var accepted: Bool+ @State private var awake = false++ var body: some View {+ VStack(spacing: Space.xl) {+ PageHeader(mood: awake ? .idle : .sleeping, title: "Hi, I'm ESP32 Agent",+ message: "Tell me a task and I'll do it on this iPhone: I see the screen through Screen Mirroring and tap with a USB mouse.")+ Panel {+ DisclosureGroup {+ Text(Disclaimer.text).font(.footnote).foregroundStyle(.secondary).padding(.top, Space.s)+ } label: {+ Label("Understand the risks", systemImage: "exclamationmark.shield").font(.body.weight(.semibold))+ }+ Divider().padding(.vertical, Space.m)+ Toggle("I understand and accept", isOn: $accepted)+ }+ }+ .task {+ try? await Task.sleep(nanoseconds: 700_000_000)+ awake = true+ }+ }+}++enum Disclaimer {+ static var text: LocalizedStringKey {+ "ESP32 Agent is experimental software that controls this iPhone on its own. It can tap the wrong thing, send messages, change settings, buy things or delete data. Watch it while it runs and stop it if anything looks wrong. Screenshots of your screen are sent to the model endpoint you choose. You use it at your own risk; the authors accept no liability for any loss or damage."+ }+}++/// 1 · Connect the board: Bluetooth permission, scan, pair (automatically when only one board is found).+struct ConnectPage: View {+ @ObservedObject var board: BoardLink++ var body: some View {+ VStack(spacing: Space.xl) {+ PageHeader(mood: board.connected ? .success : board.scanning ? .listening : .sleeping,+ title: "Plug Me In",+ message: "Connect the board to the USB-C port. I'll find it over Bluetooth; tap Pair when iOS asks.")+ if !board.connected { MiniPhoneDemo(kind: .plugIn) }+ Panel {+ switch board.state {+ case .unauthorized:+ Label("Bluetooth is not allowed for ESP32 Agent.", systemImage: "exclamationmark.triangle.fill")+ .foregroundStyle(Palette.warning)+ Button("Open Settings") { UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!) }+ .padding(.top, Space.s)+ case .poweredOff:+ Label("Turn on Bluetooth in Control Center.", systemImage: "antenna.radiowaves.left.and.right.slash")+ default:+ boards+ }+ }+ }+ .onAppear { board.scan(); autoPair() }+ .onChange(of: board.state) { _, s in if s == .poweredOn { board.scan() } }+ .onChange(of: board.found) { autoPair() }+ }++ /// Only one board nearby: pair it without asking.+ private func autoPair() {+ if board.found.count == 1, board.pairedID == nil, let f = board.found.first { board.pair(f.id) }+ }++ /// Not connected → Found → Pairing → Connected. A paired board reconnects by itself when it is plugged in.+ @ViewBuilder private var boards: some View {+ if board.connected {+ CheckRow(title: "Connected to \(board.name.isEmpty ? "the board" : board.name)", done: true)+ } else if board.linking {+ CheckRow(title: "Pairing… tap Pair when iOS asks", done: false, active: true, waiting: true)+ } else if board.pairedID == nil, board.found.count == 1, let f = board.found.first {+ CheckRow(title: "Found \(f.name)", done: false, active: true, waiting: true)+ } else if board.pairedID == nil, board.found.count > 1 {+ Text("Several boards nearby. Choose yours:").font(.subheadline).foregroundStyle(.secondary)+ .padding(.bottom, Space.s)+ ForEach(board.found) { f in+ Button { board.pair(f.id) } label: {+ HStack {+ Text(verbatim: f.name)+ Spacer()+ Image(systemName: "chevron.right").foregroundStyle(.tertiary)+ }+ .padding(.vertical, Space.s)+ }+ }+ } else {+ CheckRow(title: "Not connected — plug the board into USB-C", done: false, active: true, waiting: true,+ detail: "I'll connect as soon as it's plugged in.")+ }+ }+}++/// 2 · Let it see the screen: join the board's Wi-Fi (one tap, the system asks), then Screen Mirroring.+/// The page's one action is the bottom button (OnboardingView); manual join shows only if one-tap fails.+struct SeePage: View {+ @ObservedObject var app: AppModel+ @ObservedObject var board: BoardLink+ @Binding var onWiFi: Bool+ @State private var copied = false+ @Environment(\.scenePhase) private var scenePhase++ private var streaming: Bool { board.connected && board.status?.ap == "streaming" }+ // The board counts hotspot clients, so joining by hand is detected without the hotspot entitlement.+ private var joined: Bool {+ app.otherWiFi == nil && (onWiFi || app.join == .joined || app.hotspotSSID != nil || streaming || (board.connected && (board.status?.sta ?? 0) > 0))+ }+ private var failure: String? { if case .failed(let why) = app.join { return why } else { return nil } }++ var body: some View {+ VStack(spacing: Space.xl) {+ PageHeader(mood: streaming ? .success : (app.join.busy || joined) ? .listening : failure != nil ? .failure : .idle,+ title: "Let Me See the Screen",+ message: "Screen Mirroring goes to the board over its own Wi-Fi.")+ Panel {+ CheckRow(title: "Join the board's Wi-Fi", done: joined, active: !joined, waiting: app.join.busy && !joined,+ detail: joined ? nil : app.join == .verifying ? "Checking the connection…"+ : app.join.busy ? "Joining usually takes up to 10 seconds — hang tight." : failure.map { LocalizedStringKey($0) })+ Divider().padding(.vertical, Space.s)+ CheckRow(title: "Start Screen Mirroring", done: streaming, active: joined && !streaming)+ }+ if !joined {+ if let net = app.manualHotspot, let ssid = net.ssid, failure != nil { manual(ssid: ssid, pass: net.pass) }+ Label("Internet uses cellular data while on the board's Wi-Fi.", systemImage: "antenna.radiowaves.left.and.right")+ .font(.footnote).foregroundStyle(.secondary)+ Button("I'm already on the board's Wi-Fi") { onWiFi = true }.font(.footnote)+ } else if !streaming {+ Text("Now swipe down from the top-right corner and tap **Screen Mirroring → ESP32 Agent**.")+ .multilineTextAlignment(.center)+ .fixedSize(horizontal: false, vertical: true)+ MiniPhoneDemo(kind: .controlCenter)+ VStack(spacing: Space.s) {+ HStack(spacing: Space.s) {+ ProgressView().controlSize(.small)+ Text("Waiting for Screen Mirroring…")+ }+ Label("Keep the screen unlocked: locking stops mirroring.", systemImage: "lock.open")+ }+ .font(.footnote).foregroundStyle(.secondary)+ }+ }+ .animation(.spring(response: 0.4, dampingFraction: 0.85), value: joined)+ .animation(.spring(response: 0.4, dampingFraction: 0.85), value: app.join)+ .task { // join once by itself, then keep checking every 2 s while on this step+ if !joined { app.startJoin(auto: true) }+ while !Task.isCancelled && !streaming {+ await app.refreshHotspot()+ try? await Task.sleep(nanoseconds: 2_000_000_000)+ }+ }+ .onChange(of: scenePhase) { _, phase in if phase == .active { Task { await app.refreshHotspot() } } }+ .animation(.spring(response: 0.4, dampingFraction: 0.85), value: app.manualHotspot?.ssid)+ }++ /// One-tap join failed: the network and its password, to join in Settings › Wi-Fi.+ private func manual(ssid: String, pass: String?) -> some View {+ Panel {+ LabeledContent("Network") { Text(verbatim: ssid).font(.body.monospaced()).textSelection(.enabled) }+ if let pass {+ Divider().padding(.vertical, Space.s)+ LabeledContent("Password") {+ HStack(spacing: Space.s) {+ Text(verbatim: pass).font(.body.monospaced().weight(.semibold)).textSelection(.enabled)+ Button {+ UIPasteboard.general.string = pass+ copied = true+ Haptics.success()+ } label: { Image(systemName: copied ? "checkmark" : "doc.on.doc") }+ .accessibilityLabel(Text(copied ? "Copied" : "Copy"))+ }+ }+ Divider().padding(.vertical, Space.s)+ Button {+ UIPasteboard.general.string = pass; copied = true+ Hotspot.openWiFiSettings()+ } label: { Label("Copy Password & Open Settings", systemImage: "gear") }+ .font(.subheadline.weight(.semibold))+ }+ }+ }+}++/// 3 · Let it act: AssistiveTouch (shown as a demo), then calibration on the grid board (bottom button).+struct ActPage: View {+ @ObservedObject var app: AppModel+ @ObservedObject var board: BoardLink+ @ObservedObject var calibrator: AutoCalibrator+ @ObservedObject var pointer: Pointer++ private var mouse: Bool { MockMode.on || board.status?.usb == "ok" }+ private var mirroring: Bool { MockMode.on || board.status?.ap == "streaming" }++ var body: some View {+ VStack(spacing: Space.xl) {+ PageHeader(mood: pointer.calibrated ? .success : calibrator.busy ? .acting : .idle,+ title: "Let Me Use the Pointer",+ message: "The board is a USB mouse. iOS shows its pointer only with AssistiveTouch on. Then I calibrate on a grid, like a 3D printer levelling its bed.")+ if !pointer.calibrated { MiniPhoneDemo(kind: .assistiveTouch) }+ Panel {+ CheckRow(title: "Mouse connected", done: mouse, active: !mouse, waiting: board.connected && !mouse)+ Divider().padding(.vertical, Space.s)+ CheckRow(title: "Screen Mirroring on", done: mirroring, active: mouse && !mirroring)+ Divider().padding(.vertical, Space.s)+ CheckRow(title: "Pointer calibrated", done: pointer.calibrated, active: mouse && mirroring && !pointer.calibrated,+ waiting: calibrator.busy,+ detail: pointer.quality.map { "Accuracy \(CalibrationText.percent($0))" })+ }+ if !pointer.calibrated {+ Label("Recommended: calibrate before first use.", systemImage: "scope")+ .font(.footnote.weight(.semibold)).foregroundStyle(Color.accentColor)+ Text("Tip: in AssistiveTouch › Pointer Devices, set Tracking Speed to the middle and turn Pointer Animations off.")+ .font(.footnote).foregroundStyle(.secondary).multilineTextAlignment(.center)+ }+ }+ }+}++/// 4 · Give it a brain: an OpenAI-compatible vision model; Test Connection; a first task to try.+struct BrainPage: View {+ @ObservedObject var app: AppModel+ @ObservedObject var settings: Settings++ var body: some View {+ VStack(spacing: Space.xl) {+ PageHeader(mood: app.modelOK == true ? .success : app.modelOK == false ? .failure : .thinking,+ title: "Give Me a Brain",+ message: "Any OpenAI-compatible vision model works. The key stays in this iPhone's Keychain.")+ if MockMode.on {+ Panel { Label("Demo data simulates the model.", systemImage: "theatermasks") }+ } else {+ ModelFieldsPanel(settings: settings)+ }+ switch app.modelOK {+ case true?:+ Panel {+ Label("Connected. Try this first:", systemImage: "checkmark.circle.fill").foregroundStyle(Palette.ok)+ Text(verbatim: IntentStore.examples[0].prompt).font(.subheadline).foregroundStyle(.secondary)+ .padding(.top, Space.s)+ }+ if !MockMode.on {+ Panel { PickedModelRow(settings: settings) }+ }+ case false?:+ Label("Could not reach the model. Check the URL and key.", systemImage: "xmark.octagon.fill")+ .foregroundStyle(Palette.stop).font(.subheadline)+ case nil:+ EmptyView()+ }+ }+ }+}++/// Endpoint and key with placeholders only; the model is picked from the endpoint (nothing personal is built in), as a grouped box.+struct ModelFieldsPanel: View {+ @ObservedObject var settings: Settings++ var body: some View {+ Panel {+ TextField("Base URL", text: $settings.baseURL, prompt: Text(verbatim: "https://example.com/v1"))+ .keyboardType(.URL).textContentType(.URL)+ Divider().padding(.vertical, Space.m)+ SecureField("API key", text: $settings.apiKey, prompt: Text("API key (optional)"))+ }+ .textInputAutocapitalization(.never)+ .autocorrectionDisabled()+ }+}diff --git a/ios/IPhoneAgent/UI/OnboardingView.swift b/ios/IPhoneAgent/UI/OnboardingView.swiftnew file mode 100644index 0000000..e6dc4d3--- /dev/null+++ b/ios/IPhoneAgent/UI/OnboardingView.swift@@ -0,0 +1,272 @@+import SwiftUI++/// First-run setup: welcome + four screens (connect, see, act, brain). One thing per screen, the character+/// as the guide, animated demos for system settings, auto-advance when a step is detected, the main button+/// pinned at the bottom and "Later" on every step. Home's status chips open a single page directly.+struct OnboardingView: View {+ @ObservedObject var app: AppModel+ @ObservedObject var board: BoardLink+ @ObservedObject var feed: VideoFeed+ @ObservedObject var settings: Settings+ @ObservedObject var calibrator: AutoCalibrator+ @ObservedObject var pointer: Pointer+ let start: SetupPage+ @State private var page = SetupPage.welcome+ @State private var forward = true+ @State private var accepted = false+ @State private var onWiFi = false // the user says they joined by hand+ @State private var testing = false++ init(app: AppModel, board: BoardLink, feed: VideoFeed, settings: Settings, calibrator: AutoCalibrator,+ pointer: Pointer, start: SetupPage) {+ self.app = app; self.board = board; self.feed = feed; self.settings = settings+ self.calibrator = calibrator; self.pointer = pointer; self.start = start+ _page = State(initialValue: start)+ _accepted = State(initialValue: settings.acceptedDisclaimer)+ _onWiFi = State(initialValue: app.hotspotSSID != nil)+ }++ var body: some View {+ VStack(spacing: 0) {+ topBar+ ScrollView {+ pageContent+ .padding(.horizontal, Space.xl)+ .padding(.bottom, Space.xl)+ .id(page)+ .transition(.asymmetric(insertion: .move(edge: forward ? .trailing : .leading).combined(with: .opacity),+ removal: .move(edge: forward ? .leading : .trailing).combined(with: .opacity)))+ }+ .scrollDismissesKeyboard(.interactively)+ }+ .safeAreaInset(edge: .bottom, spacing: 0) { bottomBar } // always pinned, whatever the page's height+ .background(Palette.grouped.ignoresSafeArea())+ .animation(.spring(response: 0.45, dampingFraction: 0.9), value: page)+ .onChange(of: pageDone) { _, done in+ guard done, page != .welcome, page != .brain else { return }+ let from = page+ Task {+ try? await Task.sleep(nanoseconds: 900_000_000)+ if page == from { advance() }+ }+ }+ }++ // MARK: - chrome++ private var single: Bool { settings.onboarded } // opened from a Home chip: just this page++ private var topBar: some View {+ HStack {+ if page != .welcome && !single {+ HStack(spacing: 6) {+ ForEach(SetupPage.allCases.dropFirst()) { p in+ Capsule().fill(p.rawValue <= page.rawValue ? Color.accentColor : Color(uiColor: .tertiarySystemFill))+ .frame(width: p == page ? 22 : 8, height: 8)+ }+ }+ .accessibilityElement()+ .accessibilityLabel(Text("Step \(page.rawValue) of 4"))+ }+ Spacer()+ if single || page != .welcome {+ Button(single ? "Done" : "Later") { later() }.fontWeight(single ? .semibold : .regular)+ }+ }+ .frame(height: 44)+ .padding(.horizontal, Space.xl)+ }++ private var bottomBar: some View {+ BottomBar {+ Button { primary() } label: {+ HStack(spacing: Space.s) {+ if waiting { ProgressView().tint(primaryEnabled ? .white : .secondary) }+ Text(primaryTitle)+ }+ }+ .buttonStyle(BigButton())+ .disabled(!primaryEnabled)+ }+ }++ private func advance() {+ forward = true+ if single || page == .brain { return finish() }+ if let next = SetupPage(rawValue: page.rawValue + 1) { page = next }+ Haptics.tick()+ }++ private func later() {+ if single || page == .brain { return finish() }+ advance()+ }++ private func finish() {+ settings.acceptedDisclaimer = true+ settings.onboarded = true+ if MockMode.on { app.mockReady() } // demo data: everything ready, even what was skipped+ app.setupPage = nil+ }++ // MARK: - per page state++ private var streaming: Bool { board.connected && board.status?.ap == "streaming" }++ /// The page's goal is reached (drives auto-advance).+ private var pageDone: Bool {+ switch page {+ case .welcome: return false+ case .connect: return board.connected+ case .see: return streaming+ case .act: return pointer.calibrated && !calibrator.busy+ case .brain: return app.modelOK == true+ }+ }++ /// Waiting on something the app detects by itself.+ private var waiting: Bool {+ switch page {+ case .connect: return !board.connected && board.state == .poweredOn+ case .see: return !streaming && (onHotspot || app.join.busy)+ case .act: return calibrator.busy+ case .brain: return testing+ default: return false+ }+ }++ /// The mouse and mirroring are up: calibration can run.+ private var actReady: Bool { MockMode.on || (calibrator.boardReady && calibrator.mirroring) }++ /// On the board's hotspot: joined in-app, confirmed by hand, or the board reports a client.+ private var onHotspot: Bool {+ app.otherWiFi == nil && (onWiFi || app.join == .joined || app.hotspotSSID != nil || (board.connected && (board.status?.sta ?? 0) > 0))+ }++ private var primaryTitle: LocalizedStringKey {+ switch page {+ case .welcome: return "Get Started"+ case .connect: return board.connected ? "Continue" : "Looking for the board…"+ case .see:+ if streaming { return "Continue" }+ if onHotspot { return "Waiting for mirroring…" }+ switch app.join {+ case .joining: return "Joining…"+ case .verifying: return "Checking…"+ case .failed: return "Try Again"+ default: return "Join the Board's Wi-Fi"+ }+ case .act:+ if pointer.calibrated { return "Continue" }+ if calibrator.busy { return "Calibrating…" }+ return actReady ? "Calibrate" : "Waiting for the mouse…"+ case .brain:+ if app.modelOK == true { return "Start Using ESP32 Agent" }+ return testing ? "Testing…" : "Test Connection"+ }+ }++ private var primaryEnabled: Bool {+ switch page {+ case .welcome: return accepted+ case .connect: return board.connected+ case .see: return streaming || (!onHotspot && !app.join.busy)+ case .act: return !calibrator.busy && (pointer.calibrated || actReady)+ case .brain: return !testing && (app.modelOK == true || app.modelReady)+ }+ }++ private func primary() {+ switch page {+ case .see where !streaming:+ app.startJoin()+ case .act where !pointer.calibrated:+ calibrator.calibrate(why: String(localized: "first setup"))+ case .brain where app.modelOK != true:+ testing = true+ Task {+ await app.pingLLM()+ testing = false+ if app.modelOK == true { Haptics.success() }+ }+ default:+ advance()+ }+ }++ // MARK: - pages++ @ViewBuilder private var pageContent: some View {+ switch page {+ case .welcome: WelcomePage(accepted: $accepted)+ case .connect: ConnectPage(board: board)+ case .see: SeePage(app: app, board: board, onWiFi: $onWiFi)+ case .act: ActPage(app: app, board: board, calibrator: calibrator, pointer: pointer)+ case .brain: BrainPage(app: app, settings: settings)+ }+ }+}++/// Title block shared by the pages: the character, a large title and one sentence.+struct PageHeader: View {+ let mood: Mood+ var look: CGPoint = .zero+ let title: LocalizedStringKey+ let message: LocalizedStringKey++ var body: some View {+ VStack(spacing: Space.m) {+ PokeableFace(mood: mood, look: look).frame(width: 96, height: 108)+ Text(title).font(.title.bold()).multilineTextAlignment(.center)+ Text(message).font(.body).foregroundStyle(.secondary).multilineTextAlignment(.center)+ }+ .frame(maxWidth: .infinity)+ .padding(.top, Space.l)+ }+}++/// A grouped, rounded container like an inset list section.+struct Panel<Content: View>: View {+ @ViewBuilder let content: Content++ var body: some View {+ VStack(alignment: .leading, spacing: 0) { content }+ .padding(Space.l)+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(RoundedRectangle(cornerRadius: 12, style: .continuous).fill(Palette.surface))+ }+}++/// A row in a checklist: done, in progress (a spinner while the app waits for it) or to do, with an+/// optional line below.+struct CheckRow: View {+ let title: LocalizedStringKey+ let done: Bool+ var active = false+ var waiting = false+ var detail: LocalizedStringKey?++ var body: some View {+ HStack(alignment: .top, spacing: Space.m) {+ ZStack { // every state in the same box, as tall as the title's line, so it centres on the title+ if waiting && !done {+ ProgressView().controlSize(.regular)+ } else {+ Image(systemName: done ? "checkmark.circle.fill" : active ? "circle.dotted" : "circle")+ .font(.title3)+ .foregroundStyle(done ? Palette.ok : active ? Color.accentColor : Color(uiColor: .tertiaryLabel))+ .symbolEffect(.pulse, options: .repeating, isActive: active && !done)+ }+ }+ .frame(width: 24, height: 22)+ VStack(alignment: .leading, spacing: 2) {+ Text(title).font(.body.weight(active || waiting ? .semibold : .regular))+ if let detail { Text(detail).font(.footnote).foregroundStyle(.secondary) }+ }+ Spacer()+ }+ .padding(.vertical, Space.xs)+ .animation(.spring(response: 0.4, dampingFraction: 0.8), value: done)+ .animation(.spring(response: 0.4, dampingFraction: 0.8), value: waiting)+ }+}diff --git a/ios/IPhoneAgent/UI/PokeableFace.swift b/ios/IPhoneAgent/UI/PokeableFace.swiftnew file mode 100644index 0000000..437c436--- /dev/null+++ b/ios/IPhoneAgent/UI/PokeableFace.swift@@ -0,0 +1,192 @@+import SwiftUI+import UIKit++/// The character, pokeable. One touch gesture drives everything:+/// - tap: squish + bounce, happy eyes, light haptic+/// - double tap: a little jump and a wink+/// - 3+ quick taps: dizzy spiral eyes, then it shakes it off+/// - long press: leans into the finger, eyes close contentedly (petting), soft haptics+/// - drag: eyes follow the finger, the body leans after it; on release it springs back+/// While the agent works (`busy`), a poke only gets a brief glance. Springs ≤ 0.6 s; under Reduce Motion+/// only the eyes and haptics react.+struct PokeableFace: View {+ var mood: Mood+ var look: CGPoint = .zero+ var busy = false+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @State private var override: Mood?+ @State private var gaze: CGPoint?+ @State private var squish = CGSize(width: 1, height: 1)+ @State private var lift: CGFloat = 0+ @State private var lean = CGSize.zero+ @State private var tilt = 0.0+ @State private var taps: [Date] = []+ @State private var touchStart: Date?+ @State private var dragging = false+ @State private var petting = false+ @State private var reset: Task<Void, Never>?+ @State private var pet: Task<Void, Never>?++ var body: some View {+ GeometryReader { g in+ AgentFace(mood: override ?? mood, look: gaze ?? look, reacts: override == nil)+ .scaleEffect(x: squish.width, y: squish.height, anchor: .bottom)+ .rotationEffect(.degrees(tilt), anchor: .bottom)+ .offset(x: lean.width, y: lift + lean.height)+ .frame(width: g.size.width, height: g.size.height)+ .contentShape(Rectangle())+ .gesture(touch(in: g.size))+ }+ .accessibilityAction(named: Text("Poke")) { tapped() }+ }++ // MARK: - gesture++ private func touch(in size: CGSize) -> some Gesture {+ DragGesture(minimumDistance: 0)+ .onChanged { v in+ if touchStart == nil { began() }+ let moved = hypot(v.translation.width, v.translation.height)+ if moved > 8 && !petting { dragging = true }+ if dragging { follow(v.location, in: size, translation: v.translation) }+ }+ .onEnded { _ in ended() }+ }++ private func began() {+ touchStart = Date()+ pet?.cancel()+ guard !busy else { return }+ pet = Task { // held still: petting+ try? await Task.sleep(nanoseconds: 400_000_000)+ guard !Task.isCancelled, !dragging else { return }+ petting = true+ reset?.cancel()+ override = .content+ spring(0.5, 0.6) { squish = CGSize(width: 1.06, height: 0.95); tilt = 4 }+ while !Task.isCancelled && petting {+ UIImpactFeedbackGenerator(style: .soft).impactOccurred(intensity: 0.6)+ try? await Task.sleep(nanoseconds: 650_000_000)+ }+ }+ }++ private func follow(_ p: CGPoint, in size: CGSize, translation: CGSize) {+ let dir = CGPoint(x: max(-1, min(1, (p.x / max(size.width, 1)) * 2 - 1)),+ y: max(-1, min(1, (p.y / max(size.height, 1)) * 2 - 1)))+ gaze = dir+ guard !busy, !reduceMotion else { return }+ override = override ?? .listening+ // rubber band: the body follows a little, never far+ let k: CGFloat = 0.18, limit: CGFloat = 22+ lean = CGSize(width: max(-limit, min(limit, translation.width * k)),+ height: max(-limit, min(limit, translation.height * k)))+ tilt = Double(lean.width) * 0.35+ }++ private func ended() {+ pet?.cancel()+ let held = touchStart.map { Date().timeIntervalSince($0) } ?? 0+ touchStart = nil+ if petting || dragging {+ let wasDragging = dragging+ petting = false+ dragging = false+ settle(after: wasDragging ? 0 : 0.35)+ spring(0.45, 0.55) { lean = .zero; tilt = 0; squish = CGSize(width: 1, height: 1) }+ if !busy { UIImpactFeedbackGenerator(style: .light).impactOccurred(intensity: 0.5) }+ return+ }+ if held < 0.4 { tapped() } else { settle(after: 0) }+ }++ // MARK: - reactions++ private func tapped() {+ if busy { return glance() }+ let now = Date()+ taps = taps.filter { now.timeIntervalSince($0) < 1.2 } + [now]+ if taps.count >= 3 { return dizzy() }+ if taps.count == 2, now.timeIntervalSince(taps[0]) < 0.35 { return jumpAndWink() }+ UIImpactFeedbackGenerator(style: .light).impactOccurred()+ override = .success+ squash(depth: 0.18)+ settle(after: 0.7)+ }++ /// Busy: just look up at the finger for a moment.+ private func glance() {+ UISelectionFeedbackGenerator().selectionChanged()+ gaze = CGPoint(x: 0, y: -0.8)+ reset?.cancel()+ reset = Task {+ try? await Task.sleep(nanoseconds: 600_000_000)+ guard !Task.isCancelled else { return }+ gaze = nil+ }+ }++ private func jumpAndWink() {+ UIImpactFeedbackGenerator(style: .medium).impactOccurred()+ override = .wink+ if !reduceMotion {+ spring(0.22, 0.6) { lift = -26; squish = CGSize(width: 0.94, height: 1.08) }+ after(0.2) { spring(0.38, 0.55) { lift = 0; squish = CGSize(width: 1, height: 1) } }+ }+ settle(after: 0.8)+ }++ private func dizzy() {+ taps = []+ UIImpactFeedbackGenerator(style: .rigid).impactOccurred()+ override = .dizzy+ if !reduceMotion { spring(0.3, 0.4) { tilt = 8 } }+ reset?.cancel()+ reset = Task {+ try? await Task.sleep(nanoseconds: 1_300_000_000)+ guard !Task.isCancelled else { return }+ override = .idle // shakes it off+ UIImpactFeedbackGenerator(style: .light).impactOccurred()+ if !reduceMotion {+ for x in [-10.0, 9, -6, 4, 0] {+ spring(0.09, 0.4) { tilt = x / 2; lean.width = x }+ try? await Task.sleep(nanoseconds: 80_000_000)+ }+ }+ tilt = 0+ lean = .zero+ try? await Task.sleep(nanoseconds: 300_000_000)+ guard !Task.isCancelled else { return }+ override = nil+ }+ }++ /// Squish down and bounce back up.+ private func squash(depth: CGFloat) {+ guard !reduceMotion else { return }+ spring(0.12, 0.7) { squish = CGSize(width: 1 + depth * 0.6, height: 1 - depth) }+ after(0.12) {+ spring(0.45, 0.45) { squish = CGSize(width: 1, height: 1); lift = -8 }+ after(0.15) { spring(0.35, 0.6) { lift = 0 } }+ }+ }++ /// Back to the real mood after a while (cancelled by the next poke).+ private func settle(after seconds: Double) {+ reset?.cancel()+ reset = Task {+ try? await Task.sleep(nanoseconds: UInt64(seconds * 1_000_000_000))+ guard !Task.isCancelled else { return }+ override = nil+ gaze = nil+ }+ }++ private func spring(_ response: Double, _ damping: Double, _ change: () -> Void) {+ withAnimation(reduceMotion ? .easeInOut(duration: 0.2) : .spring(response: response, dampingFraction: damping), change)+ }++ private func after(_ seconds: Double, _ work: @escaping () -> Void) {+ DispatchQueue.main.asyncAfter(deadline: .now() + seconds, execute: work)+ }+}diff --git a/ios/IPhoneAgent/UI/PrivacyViews.swift b/ios/IPhoneAgent/UI/PrivacyViews.swiftnew file mode 100644index 0000000..6d9e03f--- /dev/null+++ b/ios/IPhoneAgent/UI/PrivacyViews.swift@@ -0,0 +1,126 @@+import SwiftUI++/// What run data holds, for the consent sheet and Settings › Privacy. Nothing is uploaded.+struct PrivacyLists: View {+ var body: some View {+ Section {+ ForEach(Self.kept.indices, id: \.self) { Label(Self.kept[$0], systemImage: "checkmark.circle") }+ } header: {+ Text("Kept on this iPhone")+ }+ Section {+ ForEach(Self.never.indices, id: \.self) { Label(Self.never[$0], systemImage: "xmark.circle") }+ } header: {+ Text("Never collected")+ } footer: {+ Text("Nothing is uploaded. An export is redacted: secrets and IP addresses removed, typed text hidden, the top of every screenshot blacked out.")+ }+ }++ static let kept: [LocalizedStringKey] = ["Per-step screenshots", "Actions", "Model replies", "Timings",+ "Board metrics", "Device model and iOS version"]+ static let never: [LocalizedStringKey] = ["Wi-Fi password", "API key", "Base URL", "Contacts"]+}++/// First launch, before setup: what is kept, and the sharing switch (off by default).+struct ConsentSheet: View {+ @AppStorage(RunShare.keepKey) private var keep = false+ @Environment(\.dismiss) private var dismiss++ var body: some View {+ NavigationStack {+ List {+ PrivacyLists()+ Section {+ Toggle("Keep run data for sharing", isOn: $keep)+ } footer: {+ Text("Lets you export redacted runs from Settings › Privacy to share with the community. You can change this anytime.")+ }+ }+ .navigationTitle("Your Data")+ .toolbar {+ ToolbarItem(placement: .confirmationAction) { Button("Continue") { dismiss() } }+ }+ }+ .interactiveDismissDisabled()+ }+}++/// Settings › Privacy: the same lists, the switch, and Export run data.+struct PrivacySettingsView: View {+ @ObservedObject var app: AppModel+ @ObservedObject var runs: RunStore+ @AppStorage(RunShare.keepKey) private var keep = false+ @State private var picked = Set<String>()+ @State private var package: RunShare.Package?+ @State private var working = false+ @State private var error: String?++ var body: some View {+ List {+ PrivacyLists()+ Section { Toggle("Keep run data for sharing", isOn: $keep) }+ if keep { export }+ }+ .navigationTitle("Privacy")+ .onAppear { runs.reload() }+ .onChange(of: picked) { package = nil }+ }++ @ViewBuilder private var export: some View {+ Section {+ ForEach(runs.runs.filter { !$0.imported }) { run in+ Button { toggle(run.id) } label: {+ HStack {+ Image(systemName: picked.contains(run.id) ? "checkmark.circle.fill" : "circle")+ .foregroundStyle(picked.contains(run.id) ? Color.accentColor : .secondary)+ Text(verbatim: run.task.isEmpty ? run.id : run.task).lineLimit(1)+ Spacer()+ Text(run.date, style: .date).font(.caption).foregroundStyle(.secondary)+ }+ }+ .tint(.primary)+ }+ } header: {+ Text("Export run data")+ }+ Section {+ if let package {+ Text("\(package.runs) runs, \(ByteCountFormatter.string(fromByteCount: Int64(package.bytes), countStyle: .file)), redacted")+ ShareLink(item: package.url) { Label("Share", systemImage: "square.and.arrow.up") }+ } else {+ Button { prepare() } label: {+ HStack {+ Label("Prepare Export", systemImage: "doc.zipper")+ if working { Spacer(); ProgressView() }+ }+ }+ .disabled(picked.isEmpty || working)+ }+ if let error { Text(verbatim: error).foregroundStyle(Palette.stop).font(.footnote) }+ } footer: {+ Text("A .zip with steps, metrics, screenshots, video frames and debug.log, redacted before it is written.")+ }+ }++ private func toggle(_ id: String) {+ if picked.contains(id) { picked.remove(id) } else { picked.insert(id) }+ }++ private func prepare() {+ working = true+ error = nil+ let folders = runs.runs.filter { picked.contains($0.id) }.map(\.folder)+ let redactor = app.shareRedactor+ Task.detached {+ let result = Result { try RunShare.export(folders, redactor: redactor, debugLog: DebugLog.url) }+ await MainActor.run {+ working = false+ switch result {+ case .success(let p): package = p+ case .failure(let e): error = e.localizedDescription+ }+ }+ }+ }+}diff --git a/ios/IPhoneAgent/UI/RunsView.swift b/ios/IPhoneAgent/UI/RunsView.swiftnew file mode 100644index 0000000..fa13eba--- /dev/null+++ b/ios/IPhoneAgent/UI/RunsView.swift@@ -0,0 +1,114 @@+import SwiftUI+import UniformTypeIdentifiers++/// The Runs tab: every run as a row with its last screen, outcome, steps and time; tap to replay.+struct RunsView: View {+ @ObservedObject var app: AppModel+ @ObservedObject var runs: RunStore+ @ObservedObject var agent: AgentLoop+ @State private var importing = false+ @State private var importError: String?++ var body: some View {+ NavigationStack {+ List {+ if runs.runs.isEmpty {+ EmptyState(mood: .idle, title: "No runs yet",+ message: "Every run is recorded here step by step, so you can replay what I did.")+ .listRowBackground(Color.clear)+ } else {+ Section {+ ForEach(runs.runs) { run in+ Button { app.openReview(run: run.id) } label: { RunRow(run: run, running: isRunning(run)) }+ .buttonStyle(.plain)+ }+ .onDelete { offsets in offsets.map { runs.runs[$0] }.forEach(runs.delete) }+ }+ }+ }+ .listStyle(.insetGrouped)+ .navigationTitle("Runs")+ .toolbar {+ ToolbarItem(placement: .topBarTrailing) {+ Button { importing = true } label: { Label("Import run", systemImage: "square.and.arrow.down") }+ }+ }+ .fileImporter(isPresented: $importing, allowedContentTypes: [.zip]) { result in+ do { try app.importRuns(result.get()) } catch { importError = error.localizedDescription }+ }+ .alert("Could not import", isPresented: Binding(get: { importError != nil }, set: { if !$0 { importError = nil } })) {+ Button("OK", role: .cancel) {}+ } message: { Text(verbatim: importError ?? "") }+ .refreshable { runs.reload() }+ .onAppear { runs.reload() }+ }+ }++ private func isRunning(_ run: Run) -> Bool {+ agent.running && run.id == app.traces.dir?.lastPathComponent+ }+}++struct RunRow: View {+ let run: Run+ var running = false++ var body: some View {+ HStack(spacing: Space.m) {+ Thumb(url: run.cover).frame(width: 52, height: 112)+ VStack(alignment: .leading, spacing: Space.xs) {+ Text(verbatim: run.task.isEmpty ? String(localized: "Untitled run") : run.task)+ .font(.headline).lineLimit(2)+ if run.imported {+ Label("Imported", systemImage: "square.and.arrow.down").foregroundStyle(.secondary)+ } else {+ OutcomeLabel(outcome: running ? .running : run.outcome)+ }+ Text(details).font(.caption).foregroundStyle(.secondary).monospacedDigit()+ }+ Spacer(minLength: 0)+ Image(systemName: "play.circle.fill").font(.title).foregroundStyle(Color.accentColor)+ }+ .padding(.vertical, Space.xs)+ .contentShape(Rectangle())+ .accessibilityElement(children: .combine)+ .accessibilityHint(Text("Opens the replay"))+ }++ private var details: String {+ var parts = [String(localized: "\(run.moves.count) steps")]+ if let d = run.duration { parts.append(d.durationText) }+ parts.append(run.date.formatted(.relative(presentation: .named)))+ return parts.joined(separator: " · ")+ }+}++struct OutcomeLabel: View {+ let outcome: Outcome++ var body: some View {+ switch outcome {+ case .running: Label("Running", systemImage: "circle.dotted").foregroundStyle(Color.accentColor)+ case .done: Label("Done", systemImage: "checkmark.circle.fill").foregroundStyle(Palette.ok)+ case .failed: Label("Failed", systemImage: "xmark.circle.fill").foregroundStyle(Palette.stop)+ case .stopped: Label("Stopped", systemImage: "stop.circle.fill").foregroundStyle(.secondary)+ }+ }+}++/// A screenshot from disk, phone-shaped.+struct Thumb: View {+ let url: URL?++ var body: some View {+ Group {+ if let url, let img = UIImage(contentsOfFile: url.path) {+ Image(uiImage: img).resizable().scaledToFill()+ } else {+ Color(uiColor: .tertiarySystemFill).overlay(Image(systemName: "iphone").foregroundStyle(.tertiary))+ }+ }+ .clipShape(RoundedRectangle(cornerRadius: 8, style: .continuous))+ .overlay(RoundedRectangle(cornerRadius: 8, style: .continuous).stroke(Color(uiColor: .separator), lineWidth: 0.5))+ }+}diff --git a/ios/IPhoneAgent/UI/SettingsView.swift b/ios/IPhoneAgent/UI/SettingsView.swiftnew file mode 100644index 0000000..33fbb37--- /dev/null+++ b/ios/IPhoneAgent/UI/SettingsView.swift@@ -0,0 +1,191 @@+import SwiftUI+import UIKit++/// Settings: Model, Board, Calibration, Language, Diagnostics, About. Logs and raw metrics live one level down.+struct SettingsView: View {+ @ObservedObject var app: AppModel+ @ObservedObject var settings: Settings+ @ObservedObject var board: BoardLink+ @AppStorage(MockMode.key) private var demoData = false++ var body: some View {+ NavigationStack {+ List {+ Section {+ NavigationLink { ModelSettingsView(app: app, settings: settings) } label: {+ row("Model", "brain", .pink, value: app.modelReady ? (MockMode.on ? "Demo" : settings.currentModel ?? String(localized: "Auto")) : nil)+ }+ NavigationLink { BoardSettingsView(app: app, board: board) } label: {+ row("Board", "cable.connector", .blue,+ value: board.connected ? board.name : String(localized: "Not connected"))+ }+ CalibrationRow(app: app, calibrator: app.calibrator, pointer: app.pointer)+ Button { UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!) } label: {+ HStack {+ SettingsLabel(title: "Language", symbol: "globe", color: .indigo)+ Spacer()+ Image(systemName: "arrow.up.forward.app").foregroundStyle(.tertiary)+ }+ }+ .tint(.primary)+ } footer: {+ Text("ESP32 Agent follows your iPhone's language. To change it just for this app, open Settings › ESP32 Agent › Language.")+ }+ Section {+ Button { UIApplication.shared.open(URL(string: UIApplication.openNotificationSettingsURLString)!) } label: {+ HStack {+ SettingsLabel(title: "Notifications", symbol: "bell.badge.fill", color: .red)+ Spacer()+ Image(systemName: "arrow.up.forward.app").foregroundStyle(.tertiary)+ }+ }+ .tint(.primary)+ } header: {+ Text("Runs")+ } footer: {+ Text("Every run keeps a low-frame-rate video of the mirrored screen, next to the step screenshots, for the review.")+ }+ Section {+ NavigationLink { DiagnosticsView(app: app, metrics: app.metrics, board: board, feed: app.feed) } label: {+ SettingsLabel(title: "Diagnostics", symbol: "waveform.path.ecg", color: .green)+ }+ Toggle(isOn: $demoData) { SettingsLabel(title: "Demo data", symbol: "theatermasks", color: .purple) }+ Button { settings.onboarded = false; app.setupPage = .welcome } label: {+ SettingsLabel(title: "Run setup again", symbol: "arrow.counterclockwise", color: .gray)+ }+ .tint(.primary)+ } footer: {+ Text("Demo data fakes a board, a finished run and the whole setup, to try the app without hardware. Takes effect after you quit and reopen the app.")+ }+ Section {+ NavigationLink { PrivacySettingsView(app: app, runs: app.runs) } label: {+ SettingsLabel(title: "Privacy", symbol: "hand.raised.fill", color: .blue)+ }+ NavigationLink { AboutView(app: app) } label: {+ SettingsLabel(title: "About", symbol: "info", color: .gray)+ }+ }+ }+ .navigationTitle("Settings")+ }+ }++ private func row(_ title: LocalizedStringKey, _ symbol: String, _ color: Color, value: String?) -> some View {+ HStack {+ SettingsLabel(title: title, symbol: symbol, color: color)+ Spacer()+ Text(verbatim: value ?? String(localized: "Not set up")).foregroundStyle(.secondary).lineLimit(1)+ }+ }+}++/// Settings › Model: base URL and key (placeholders only), Test Connection, and an Advanced disclosure with+/// the model override (empty = first model from GET {base}/models), per-role models and request tweaks.+struct BoardSettingsView: View {+ @ObservedObject var app: AppModel+ @ObservedObject var board: BoardLink++ var body: some View {+ List {+ Section {+ HStack(spacing: Space.l) {+ AgentFace(mood: board.connected ? .idle : .sleeping).frame(width: 52, height: 58)+ VStack(alignment: .leading, spacing: 2) {+ Text(verbatim: board.name.isEmpty ? "ESP32 Agent" : board.name).font(.headline)+ Text(board.connected ? "Connected" : board.pairedID != nil ? "Connecting…" : "Not paired")+ .font(.subheadline).foregroundStyle(.secondary)+ }+ }+ .padding(.vertical, Space.xs)+ if board.connected, let s = board.status {+ ValueRow(title: "Mouse", value: s.usb ?? "–")+ ValueRow(title: "Mirroring", value: s.ap ?? "–")+ }+ }+ if board.pairedID == nil || !board.connected {+ Section {+ ForEach(board.found.filter { $0.id != board.pairedID }) { f in+ Button { Haptics.tick(); board.pair(f.id) } label: {+ LabeledContent { Text(verbatim: "\(f.rssi) dBm") } label: { Text(verbatim: f.name) }+ }+ .tint(.primary)+ }+ Button { board.scan() } label: {+ HStack {+ Text(board.scanning ? "Scanning…" : "Scan for Boards")+ if board.scanning { Spacer(); ProgressView() }+ }+ }+ .disabled(board.scanning)+ } header: {+ Text("Nearby")+ }+ }+ Section {+ Button { app.startJoin() } label: {+ HStack {+ Text("Join the Board's Wi-Fi")+ Spacer()+ if app.join.busy { ProgressView() }+ }+ }+ .disabled(app.join.busy)+ if let ssid = app.hotspotSSID { ValueRow(title: "Network", value: ssid) }+ if let net = app.manualHotspot, let pass = net.pass {+ if let ssid = net.ssid { ValueRow(title: "Network", value: ssid) }+ ValueRow(title: "Password", value: pass)+ Button { UIPasteboard.general.string = pass; Haptics.success() } label: { Text("Copy Wi-Fi Password") }+ Button { UIPasteboard.general.string = pass; Hotspot.openWiFiSettings() } label: { Text("Open Settings") }+ }+ } header: {+ Text("Wi-Fi")+ } footer: {+ Text("While joined, the internet goes over cellular data. Switch back in Settings › Wi-Fi when you are done.")+ }+ if board.pairedID != nil {+ Section {+ Button("Unpair Board", role: .destructive) { Task { await board.unpair() } }+ Button("Forget in This App", role: .destructive) { board.forget() }+ } footer: {+ Text("Unpair erases the bonds on the board. iOS keeps its own: also tap (i) next to \"ESP32 Agent\" in Settings › Bluetooth and choose Forget This Device.")+ }+ }+ }+ .navigationTitle("Board")+ .navigationBarTitleDisplayMode(.inline)+ .task { await app.refreshHotspot() }+ }+}++/// Settings › Calibration: one tap calibrates on the grid board; accuracy and span in a small second line.+struct CalibrationRow: View {+ @ObservedObject var app: AppModel+ @ObservedObject var calibrator: AutoCalibrator+ @ObservedObject var pointer: Pointer++ private var ready: Bool { MockMode.on || calibrator.boardReady }++ var body: some View {+ Button { calibrator.calibrate() } label: {+ HStack {+ Label {+ VStack(alignment: .leading, spacing: 2) {+ Text("Calibration")+ if let span = pointer.span {+ Text(verbatim: "\(pointer.quality.map(CalibrationText.percent) ?? "–") · \(span.w) × \(span.h)")+ .font(.caption).foregroundStyle(.secondary).monospacedDigit()+ }+ }+ } icon: { SettingsIcon(symbol: "scope", color: .orange) }+ Spacer()+ if ready {+ Text("Calibrate").foregroundStyle(Color.accentColor)+ } else {+ Text("Connect the board").foregroundStyle(.secondary)+ }+ }+ }+ .tint(.primary)+ .disabled(!ready || calibrator.busy)+ }+}diff --git a/ios/IPhoneAgent/UI/StatusChips.swift b/ios/IPhoneAgent/UI/StatusChips.swiftnew file mode 100644index 0000000..ca70989--- /dev/null+++ b/ios/IPhoneAgent/UI/StatusChips.swift@@ -0,0 +1,90 @@+import SwiftUI++/// Home's readiness at a glance: board, mirroring, mouse, pointer and model. A problem chip turns orange;+/// tapping it opens the setup page that fixes it.+struct StatusChips: View {+ @ObservedObject var app: AppModel+ @ObservedObject var board: BoardLink+ @ObservedObject var pointer: Pointer+ @ObservedObject var calibrator: AutoCalibrator++ var body: some View {+ FlowLayout(spacing: Space.s) {+ chip("Board", "cable.connector", ok: board.connected, page: .connect)+ chip("Mirroring", "rectangle.on.rectangle", ok: board.connected && board.status?.ap == "streaming", page: .see)+ chip("Mouse", "cursorarrow", ok: board.connected && board.status?.usb == "ok", page: .act)+ chip(calibrator.busy ? "Calibrating" : "Pointer", "scope", ok: pointer.calibrated, busy: calibrator.busy, page: .act)+ chip("Model", "brain", ok: app.modelReady && app.modelOK != false, page: .brain)+ }+ .padding(.horizontal, Space.l)+ }++ private func chip(_ title: LocalizedStringKey, _ symbol: String, ok: Bool, busy: Bool = false,+ page: SetupPage) -> some View {+ Button {+ Haptics.tick()+ app.setupPage = page+ } label: {+ HStack(spacing: 5) {+ if busy {+ ProgressView().controlSize(.mini)+ } else {+ Image(systemName: ok ? "checkmark.circle.fill" : symbol)+ .foregroundStyle(ok ? Palette.ok : Palette.warning)+ }+ Text(title)+ }+ .font(.footnote.weight(.medium))+ .foregroundStyle(ok ? Color.primary : Palette.warning)+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ .background(Capsule().fill(ok ? Palette.surface : Palette.warning.opacity(0.14)))+ }+ .buttonStyle(.plain)+ .accessibilityValue(Text(ok ? "Ready" : "Needs setup"))+ .animation(.spring(response: 0.35, dampingFraction: 0.8), value: ok)+ }+}++/// Lays children out left to right, wrapping to new lines, each line centered.+struct FlowLayout: Layout {+ var spacing: CGFloat = 8++ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {+ let rows = rows(subviews, width: proposal.width ?? .infinity)+ let height = rows.map(\.height).reduce(0, +) + spacing * CGFloat(max(rows.count - 1, 0))+ return CGSize(width: proposal.width ?? rows.map(\.width).max() ?? 0, height: height)+ }++ func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {+ var y = bounds.minY+ for row in rows(subviews, width: bounds.width) {+ var x = bounds.minX + (bounds.width - row.width) / 2+ for i in row.items {+ let size = subviews[i].sizeThatFits(.unspecified)+ subviews[i].place(at: CGPoint(x: x, y: y + (row.height - size.height) / 2), proposal: .unspecified)+ x += size.width + spacing+ }+ y += row.height + spacing+ }+ }++ private struct Row { var items: [Int] = []; var width: CGFloat = 0; var height: CGFloat = 0 }++ private func rows(_ subviews: Subviews, width: CGFloat) -> [Row] {+ var rows = [Row()]+ for (i, v) in subviews.enumerated() {+ let size = v.sizeThatFits(.unspecified)+ let extra = rows[rows.count - 1].items.isEmpty ? size.width : size.width + spacing+ if rows[rows.count - 1].width + extra > width && !rows[rows.count - 1].items.isEmpty {+ rows.append(Row())+ }+ var r = rows[rows.count - 1]+ r.width += r.items.isEmpty ? size.width : size.width + spacing+ r.height = max(r.height, size.height)+ r.items.append(i)+ rows[rows.count - 1] = r+ }+ return rows+ }+}diff --git a/ios/IPhoneAgent/UI/Theme.swift b/ios/IPhoneAgent/UI/Theme.swiftnew file mode 100644index 0000000..b0c357a--- /dev/null+++ b/ios/IPhoneAgent/UI/Theme.swift@@ -0,0 +1,127 @@+import SwiftUI+import UIKit++/// Spacing on the 8 pt grid; colors are the system's semantic colors plus the app's accent (the eyes' glow).+enum Space {+ static let xs: CGFloat = 4+ static let s: CGFloat = 8+ static let m: CGFloat = 12+ static let l: CGFloat = 16+ static let xl: CGFloat = 24+ static let xxl: CGFloat = 32+}++enum Palette {+ static let ink = Color.primary+ static let muted = Color.secondary+ static let accent = Color.accentColor+ static let stop = Color.red+ static let warning = Color.orange+ static let ok = Color.green+ static let surface = Color(uiColor: .secondarySystemGroupedBackground)+ static let grouped = Color(uiColor: .systemGroupedBackground)+ static let background = Color(uiColor: .systemBackground)+ static let line = Color(uiColor: .separator)+}++enum Haptics {+ static func start() { UIImpactFeedbackGenerator(style: .medium).impactOccurred() }+ static func stop() { UINotificationFeedbackGenerator().notificationOccurred(.warning) }+ static func success() { UINotificationFeedbackGenerator().notificationOccurred(.success) }+ static func tick() { UISelectionFeedbackGenerator().selectionChanged() }+}++/// The screen's main action, pinned above the home indicator (HIG: one prominent button at the bottom).+struct BottomBar<Content: View>: View {+ @ViewBuilder let content: Content++ var body: some View {+ VStack(spacing: Space.s) { content }+ .padding(.horizontal, Space.xl)+ .padding(.top, Space.m)+ .padding(.bottom, Space.s)+ .frame(maxWidth: .infinity)+ .background(.bar)+ }+}++/// Full-width prominent button label: `Button { } label: { BigLabel("Start", "play.fill") }`.+struct BigButton: ButtonStyle {+ var tint: Color = .accentColor+ @Environment(\.isEnabled) private var enabled++ func makeBody(configuration: Configuration) -> some View {+ configuration.label+ .font(.headline)+ .frame(maxWidth: .infinity, minHeight: 50)+ .foregroundStyle(enabled ? Color.white : Color.secondary)+ .background(RoundedRectangle(cornerRadius: 14, style: .continuous)+ .fill(enabled ? tint : Color(uiColor: .tertiarySystemFill)))+ .opacity(configuration.isPressed ? 0.8 : 1)+ .scaleEffect(configuration.isPressed ? 0.98 : 1)+ .animation(.spring(response: 0.25, dampingFraction: 0.8), value: configuration.isPressed)+ }+}++/// A centered "nothing here yet" message with the character.+struct EmptyState: View {+ var mood: Mood = .sleeping+ let title: LocalizedStringKey+ var message: LocalizedStringKey?++ var body: some View {+ VStack(spacing: Space.m) {+ PokeableFace(mood: mood).frame(width: 72, height: 80)+ Text(title).font(.headline)+ if let message {+ Text(message).font(.subheadline).foregroundStyle(.secondary).multilineTextAlignment(.center)+ }+ }+ .frame(maxWidth: .infinity)+ .padding(.vertical, Space.xl)+ }+}++/// A key/value row for Diagnostics and Settings.+struct ValueRow: View {+ let title: LocalizedStringKey+ let value: String++ var body: some View {+ LabeledContent(title) { Text(verbatim: value).monospacedDigit().foregroundStyle(.secondary) }+ }+}++/// A row icon in a rounded colored square, like Settings.app.+struct SettingsIcon: View {+ let symbol: String+ let color: Color++ var body: some View {+ Image(systemName: symbol)+ .font(.system(size: 15, weight: .semibold))+ .foregroundStyle(.white)+ .frame(width: 29, height: 29)+ .background(RoundedRectangle(cornerRadius: 7, style: .continuous).fill(color))+ }+}++struct SettingsLabel: View {+ let title: LocalizedStringKey+ let symbol: String+ let color: Color++ var body: some View {+ Label { Text(title) } icon: { SettingsIcon(symbol: symbol, color: color) }+ }+}++extension Double {+ /// "12 s" / "1 min 4 s".+ var durationText: String {+ let f = DateComponentsFormatter()+ f.allowedUnits = self >= 60 ? [.minute, .second] : [.second]+ f.unitsStyle = .abbreviated+ return f.string(from: self) ?? "–"+ }+}diff --git a/ios/IPhoneAgent/Video/H264Decoder.swift b/ios/IPhoneAgent/Video/H264Decoder.swiftnew file mode 100644index 0000000..c30e5b3--- /dev/null+++ b/ios/IPhoneAgent/Video/H264Decoder.swift@@ -0,0 +1,154 @@+import CoreMedia+import Foundation+import ImageIO+import UniformTypeIdentifiers+import VideoToolbox++/// Annex-B access units -> VideoToolbox -> JPEG (q 0.75). Runs on its own serial queue.+final class H264Decoder: @unchecked Sendable { // confined to `queue`+ struct Frame {+ let jpeg: Data+ let width: Int, height: Int+ let decodeMs: Double+ let unit: AccessUnit+ }++ var onFrame: ((Frame) -> Void)?+ var onError: ((String) -> Void)?+ var quality: Double = 0.75+ let queue = DispatchQueue(label: "video.decode")++ private var sps: Data?, pps: Data?+ private var format: CMVideoFormatDescription?+ private var session: VTDecompressionSession?+ /// Every unit since the last IDR. A still screen gets an IDR only every few minutes, so when iOS drops+ /// the session (e.g. going to background) the GOP is decoded again from here instead of fetched again+ /// over BLE (a snap of a long GOP takes up to a minute).+ private var gop: [AccessUnit] = []+ private var gopBytes = 0+ private static let gopMax = 64 << 20++ /// Decode one access unit (call on `queue`).+ func decode(_ unit: AccessUnit) {+ if unit.idr { (gop, gopBytes) = ([], 0) }+ if gopBytes + unit.data.count <= Self.gopMax, unit.idr || !gop.isEmpty {+ gop.append(unit)+ gopBytes += unit.data.count+ }+ let status = decodeOne(unit, emit: true)+ guard status != noErr else { return }+ resetSession()+ if gop.last?.data == unit.data, gop.first?.idr == true, replay() {+ let n = gop.count+ DispatchQueue.main.async { DebugLog.write("decoder: session lost (\(status)); decoded the GOP again (\(n) units)") }+ return+ }+ onError?("decode failed \(status)" + (status == kVTInvalidSessionErr ? " (session lost, e.g. in background)" : ""))+ resetSession() // rebuilt at the next IDR/config+ }++ /// Decode the cached GOP into a fresh session; only its last frame is shown.+ private func replay() -> Bool {+ for (i, u) in gop.enumerated() where decodeOne(u, emit: i == gop.count - 1) != noErr { return false }+ return true+ }++ /// noErr also when there is nothing to decode yet (no slices, no SPS/PPS).+ private func decodeOne(_ unit: AccessUnit, emit: Bool) -> OSStatus {+ var slices: [Data] = []+ for nal in annexBUnits(unit.data) {+ switch nal[nal.startIndex] & 0x1f {+ case 7: if nal != sps { sps = nal; resetSession() }+ case 8: if nal != pps { pps = nal; resetSession() }+ case 9, 6: break // access unit delimiter, SEI+ default: slices.append(nal)+ }+ }+ guard !slices.isEmpty else { return noErr }+ guard ensureSession(), let session, let format else { return noErr }+ var avcc = Data()+ for s in slices {+ var len = UInt32(s.count).bigEndian+ avcc.append(Data(bytes: &len, count: 4))+ avcc.append(s)+ }+ guard let sample = makeSample(avcc, format) else { return noErr }+ let started = CFAbsoluteTimeGetCurrent()+ var flags = VTDecodeInfoFlags()+ let status = VTDecompressionSessionDecodeFrame(session, sampleBuffer: sample, flags: [],+ infoFlagsOut: &flags) { [weak self] status, _, image, _, _ in+ guard let self else { return }+ guard status == noErr, let image else {+ self.onError?("decode callback status \(status)")+ return+ }+ guard emit else { return }+ let ms = (CFAbsoluteTimeGetCurrent() - started) * 1000+ if let frame = self.jpeg(image, ms: ms, unit: unit) { self.onFrame?(frame) }+ }+ return status+ }++ private func resetSession() {+ if let session { VTDecompressionSessionInvalidate(session) }+ session = nil+ format = nil+ }++ private func ensureSession() -> Bool {+ if session != nil { return true }+ guard let sps, let pps else { return false }+ var desc: CMFormatDescription?+ let ok = sps.withUnsafeBytes { s in+ pps.withUnsafeBytes { p in+ let ptrs = [s.bindMemory(to: UInt8.self).baseAddress!, p.bindMemory(to: UInt8.self).baseAddress!]+ let sizes = [sps.count, pps.count]+ return CMVideoFormatDescriptionCreateFromH264ParameterSets(+ allocator: nil, parameterSetCount: 2, parameterSetPointers: ptrs, parameterSetSizes: sizes,+ nalUnitHeaderLength: 4, formatDescriptionOut: &desc)+ }+ }+ guard ok == noErr, let desc else { onError?("bad SPS/PPS \(ok)"); return false }+ let attrs: [CFString: Any] = [kCVPixelBufferPixelFormatTypeKey: kCVPixelFormatType_32BGRA]+ var made: VTDecompressionSession?+ let status = VTDecompressionSessionCreate(allocator: nil, formatDescription: desc, decoderSpecification: nil,+ imageBufferAttributes: attrs as CFDictionary,+ outputCallback: nil, decompressionSessionOut: &made)+ guard status == noErr, let made else { onError?("decoder create failed \(status)"); return false }+ format = desc+ session = made+ return true+ }++ private func makeSample(_ avcc: Data, _ format: CMVideoFormatDescription) -> CMSampleBuffer? {+ var block: CMBlockBuffer?+ guard CMBlockBufferCreateWithMemoryBlock(allocator: nil, memoryBlock: nil, blockLength: avcc.count,+ blockAllocator: nil, customBlockSource: nil, offsetToData: 0,+ dataLength: avcc.count, flags: 0, blockBufferOut: &block) == noErr,+ let block else { return nil }+ let copied = avcc.withUnsafeBytes {+ CMBlockBufferReplaceDataBytes(with: $0.baseAddress!, blockBuffer: block, offsetIntoDestination: 0,+ dataLength: avcc.count)+ }+ guard copied == noErr else { return nil }+ var sample: CMSampleBuffer?+ var size = avcc.count+ CMSampleBufferCreateReady(allocator: nil, dataBuffer: block, formatDescription: format, sampleCount: 1,+ sampleTimingEntryCount: 0, sampleTimingArray: nil, sampleSizeEntryCount: 1,+ sampleSizeArray: &size, sampleBufferOut: &sample)+ return sample+ }++ private func jpeg(_ buffer: CVImageBuffer, ms: Double, unit: AccessUnit) -> Frame? {+ var image: CGImage?+ VTCreateCGImageFromCVPixelBuffer(buffer, options: nil, imageOut: &image)+ guard let image else { onError?("frame -> image failed"); return nil }+ let out = NSMutableData()+ guard let dest = CGImageDestinationCreateWithData(out, UTType.jpeg.identifier as CFString, 1, nil) else {+ return nil+ }+ CGImageDestinationAddImage(dest, image, [kCGImageDestinationLossyCompressionQuality: quality] as CFDictionary)+ guard CGImageDestinationFinalize(dest) else { return nil }+ return Frame(jpeg: out as Data, width: image.width, height: image.height, decodeMs: ms, unit: unit)+ }+}diff --git a/ios/IPhoneAgent/Video/VideoAssembler.swift b/ios/IPhoneAgent/Video/VideoAssembler.swiftnew file mode 100644index 0000000..1e27225--- /dev/null+++ b/ios/IPhoneAgent/Video/VideoAssembler.swift@@ -0,0 +1,97 @@+import Foundation++/// One H.264 access unit (Annex-B) rebuilt from `video` chunks.+struct AccessUnit: Equatable {+ var data: Data+ var idr: Bool+ var config: Bool+ var snap: Bool+ var boardMs: UInt32 // board timestamp from the START chunk+}++/// Rebuilds access units from `video` notifies: `[seq u16 LE][flags u8][payload]` (docs/ble-protocol.md).+///+/// A seq gap counts as a drop; everything is then discarded until the next START chunk that is an IDR or+/// CONFIG, because P-frames after a lost chunk cannot be decoded.+struct VideoAssembler {+ struct Flags: OptionSet {+ let rawValue: UInt8+ static let start = Flags(rawValue: 1 << 0)+ static let end = Flags(rawValue: 1 << 1)+ static let idr = Flags(rawValue: 1 << 2)+ static let config = Flags(rawValue: 1 << 3)+ static let bench = Flags(rawValue: 1 << 4)+ static let snap = Flags(rawValue: 1 << 5)+ }++ private(set) var drops = 0 // chunks lost (seq gaps)+ private(set) var bytes = 0 // all chunk bytes received, bench included+ private(set) var benchBytes = 0+ private(set) var waitingForKey = true // until the first IDR/CONFIG+ private var lastSeq: UInt16?+ private var current: AccessUnit?++ mutating func reset() {+ lastSeq = nil+ current = nil+ waitingForKey = true+ }++ /// Feed one notify; returns a completed access unit, if this chunk finished one.+ mutating func add(_ chunk: Data) -> AccessUnit? {+ let c = [UInt8](chunk)+ guard c.count >= 3 else { return nil }+ bytes += c.count+ let seq = UInt16(c[0]) | UInt16(c[1]) << 8+ let flags = Flags(rawValue: c[2])+ if let last = lastSeq, seq != last &+ 1 {+ drops += Int(seq &- last &- 1)+ current = nil+ waitingForKey = true+ }+ lastSeq = seq+ var payload = Data(c[3...])+ if flags.contains(.bench) {+ benchBytes += c.count+ return nil+ }+ if flags.contains(.start) {+ let key = flags.contains(.idr) || flags.contains(.config)+ if waitingForKey && !key { current = nil; return nil }+ waitingForKey = false+ guard payload.count >= 4 else { current = nil; return nil }+ let p = [UInt8](payload.prefix(4))+ let ms = UInt32(p[0]) | UInt32(p[1]) << 8 | UInt32(p[2]) << 16 | UInt32(p[3]) << 24+ payload = payload.dropFirst(4)+ current = AccessUnit(data: Data(payload), idr: flags.contains(.idr), config: flags.contains(.config),+ snap: flags.contains(.snap), boardMs: ms)+ } else if current != nil {+ current!.data.append(payload)+ } else {+ return nil // a middle chunk without its start: skip+ }+ guard flags.contains(.end) else { return nil }+ defer { current = nil }+ return current+ }+}++/// NAL units of an Annex-B buffer (start codes 00 00 01 or 00 00 00 01), without the start codes.+func annexBUnits(_ data: Data) -> [Data] {+ let b = [UInt8](data)+ var starts: [(Int, Int)] = [] // (start code index, payload index)+ var i = 0+ while i + 2 < b.count {+ if b[i] == 0 && b[i + 1] == 0 && b[i + 2] == 1 {+ let code = i > 0 && b[i - 1] == 0 ? i - 1 : i+ starts.append((code, i + 3))+ i += 3+ } else {+ i += 1+ }+ }+ return starts.enumerated().compactMap { n, s in+ let end = n + 1 < starts.count ? starts[n + 1].0 : b.count+ return end > s.1 ? Data(b[s.1..<end]) : nil+ }+}diff --git a/ios/IPhoneAgent/Video/VideoFeed.swift b/ios/IPhoneAgent/Video/VideoFeed.swiftnew file mode 100644index 0000000..4180757--- /dev/null+++ b/ios/IPhoneAgent/Video/VideoFeed.swift@@ -0,0 +1,216 @@+import Foundation+import UIKit++/// What the agent and the pointer need from the screen (VideoFeed, or a fake in tests). Port of screen.py.+@MainActor protocol ScreenSource: AnyObject {+ var live: Bool { get }+ var frame: Data? { get }+ var updated: Double { get }+ var capturedAt: Double { get }+ var aspect: Double { get }+ /// After a gesture that ended at `since`: wait until the screen shows its result (and fetch it, in snap mode).+ func afterAction(since: Double) async+}++/// How a run gets its frames: the live stream (`stream on`, the default: a frame in under a second), or one+/// snap after each action (`stream off`; waits for the board's whole GOP, often 20-30 s).+enum FrameMode: String {+ case stream, snap+ static let key = "frameModeV2" // V2: drops the old saved "snap" left by earlier automatic fallbacks+ /// A command timeout switches the current run to snap; not saved, so the next run streams again.+ static var fallback: FrameMode?+ static var current: FrameMode {+ get { fallback ?? FrameMode(rawValue: UserDefaults.standard.string(forKey: key) ?? "") ?? .stream }+ set { UserDefaults.standard.set(newValue.rawValue, forKey: key); fallback = nil }+ }+}++extension ScreenSource {+ func afterAction(since: Double) async { await settled() }++ /// Wait until the screen stops changing (AirPlay only sends frames on change). Mid-animation frames are big and+ /// can reach us late over BLE, so a gap is only "quiet" once it also covers the last frame's transport lag.+ func settled(quiet: Double = 0.5, least: Double = 0.3, most: Double = 4) async {+ let started = now()+ try? await Task.sleep(nanoseconds: UInt64(least * 1e9))+ while now() - updated < quiet + lag && now() - started < most {+ try? await Task.sleep(nanoseconds: 100_000_000)+ }+ }++ /// How late the shown frame arrived after the board got it (0 when unknown), capped.+ private var lag: Double { capturedAt > 0 ? min(max(updated - capturedAt, 0), 1) : 0 }++ /// The first frame captured after `since` (received, when capture times are unknown), or nil if none in time.+ func fresh(since: Double, timeout: Double = 0.8) async -> Data? {+ let deadline = now() + timeout+ while (capturedAt > 0 ? capturedAt : updated) <= since {+ if now() > deadline { return nil }+ try? await Task.sleep(nanoseconds: 20_000_000)+ }+ return frame+ }+}++/// The phone's screen, mirrored over AirPlay to the board and forwarded over BLE, as JPEG frames.+@MainActor final class VideoFeed: ObservableObject, ScreenSource {+ @Published private(set) var frame: Data?+ @Published private(set) var size = CGSize.zero+ @Published private(set) var note = "" // last decoder problem, shown in Diagnostics+ private(set) var updated = 0.0+ /// When the board received the shown frame, in local time (≈; see `boardClock`).+ private(set) var capturedAt = 0.0+ /// A decode error or a lost chunk since the last good frame: the shown frame is stale until the next IDR.+ private(set) var broken = false+ private var clockOffset: Double? // local s − board s, the smallest seen (≈ the link latency)+ var mirroring = false // board status says ap == streaming+ var metrics: Metrics?+ weak var device: HIDDevice?++ private var assembler = VideoAssembler()+ private let decoder = H264Decoder()++ init() {+ decoder.onFrame = { [weak self] f in DispatchQueue.main.async { self?.publish(f) } }+ decoder.onError = { [weak self] msg in+ DispatchQueue.main.async {+ let bg = UIApplication.shared.applicationState == .background+ self?.note = bg ? "\(msg) [in background]" : msg+ self?.metrics?.decodeError(background: bg)+ self?.broken = true+ }+ }+ }++ var live: Bool { mirroring && frame != nil && (device?.connected ?? false) }++ /// Frame width / height (portrait iPhone as a fallback).+ var aspect: Double { size.width > 0 && size.height > 0 ? size.width / size.height : 9 / 19.5 }++ /// One `video` notify from BoardLink.+ func receive(_ chunk: Data) {+ metrics?.videoBytes(chunk.count)+ let dropsBefore = assembler.drops+ let unit = assembler.add(chunk)+ if assembler.drops > dropsBefore { metrics?.videoDrops(assembler.drops - dropsBefore); broken = true }+ guard let unit else { return }+ if !unit.snap { boardClock(ms: Int(unit.boardMs)) } // snap units are resent late: their ages say nothing+ if unit.idr { metrics?.idrSeen() }+ decoder.queue.async { [decoder] in decoder.decode(unit) }+ }++ /// The link (re)connected: chunk numbering starts over.+ func resetStream() { assembler.reset(); clockOffset = nil } // the board may have rebooted: its clock too++ /// A board timestamp (status `up`, or a streamed unit) just arrived: keep the smallest offset.+ func boardClock(ms: Int) {+ let offset = now() - Double(ms) / 1000+ clockOffset = min(clockOffset ?? offset, offset)+ }++ /// Show a still frame (demo data).+ func show(_ jpeg: Data, width: Int, height: Int) {+ publish(H264Decoder.Frame(jpeg: jpeg, width: width, height: height, decodeMs: 4.2,+ unit: AccessUnit(data: Data(), idr: false, config: false, snap: false, boardMs: 0)))+ }++ private func publish(_ f: H264Decoder.Frame) {+ frame = f.jpeg+ updated = now()+ capturedAt = clockOffset.map { Double(f.unit.boardMs) / 1000 + $0 } ?? updated+ broken = false+ if size.width != CGFloat(f.width) || size.height != CGFloat(f.height) {+ size = CGSize(width: f.width, height: f.height)+ }+ metrics?.frameDecoded(ms: f.decodeMs)+ }++ /// The app asked the board to forward the stream (`stream on`).+ private(set) var streamOn = false++ /// Seconds a snap may take: the buffered GOP over the measured BLE rate, doubled, at least 8 s.+ var snapTimeout: Double {+ let gopBytes = Double(metrics?.board?.gop ?? 0)+ let kbps = max(metrics?.bleKbps ?? 0, metrics?.board?.ble?.kbps ?? 0, 40)+ return max(8, gopBytes * 8 / 1000 / kbps * 2 + 3)+ }++ /// A current frame for the model. While the board streams, the live stream has it (an IDR comes every+ /// ~2 s): use a frame younger than `maxAge`, or wait for the next one. Snap only as a fallback, retried+ /// once with a longer timeout. Returns where the frame came from, for the log.+ @discardableResult+ func currentFrame(maxAge: Double = 1, wait: Double = 3) async throws -> String {+ if streamOn && mirroring {+ if frame != nil && now() - updated < maxAge { return "live" }+ if await fresh(since: now() - maxAge, timeout: wait) != nil { return "live (waited)" }+ }+ do {+ try await snap()+ } catch is BoardTimeout {+ DebugLog.write("snap timed out; retrying once with a longer timeout")+ try await snap(timeout: snapTimeout * 1.5)+ }+ return "snap"+ }++ /// Ask the board for the current GOP and wait until it is decoded. Returns the latency in ms.+ @discardableResult+ func snap(timeout: Double? = nil) async throws -> Double {+ guard let device else { throw DeviceError(message: "board not connected") }+ let started = now()+ if let channel = device as? CommandChannel {+ try await channel.send("snap", timeout: timeout ?? snapTimeout)+ } else {+ try await device.send("snap")+ }+ await withCheckedContinuation { c in decoder.queue.async { c.resume() } } // the GOP is decoded+ try? await Task.sleep(nanoseconds: 30_000_000) // let the last frame reach the main queue+ let ms = (now() - started) * 1000+ metrics?.snapLatency(ms)+ return ms+ }++ func stream(_ on: Bool) async throws {+ try await device?.send("stream \(on ? "on" : "off")")+ streamOn = on+ }++ /// The model must never see a frame from before the action that ended at `since`. Stream: let the screen+ /// settle, then wait (bounded) for a frame captured after the action; none while the stream is healthy means+ /// the screen did not change, but a broken stream (waiting for an IDR) needs a snap. Snap: give the UI a moment,+ /// snap, and snap once more if the GOP still ends before the action.+ func afterAction(since: Double) async {+ do {+ if FrameMode.current == .snap {+ try await Task.sleep(nanoseconds: 700_000_000)+ try await currentFrame()+ guard capturedAt < since else { return }+ DebugLog.write(String(format: "frame: snap ends %.1f s before the action; snapping again", since - capturedAt))+ try await Task.sleep(nanoseconds: 500_000_000)+ try await currentFrame()+ } else {+ await settled()+ if await newer(than: since, timeout: 1.5) { return }+ guard broken || !streamOn else { return DebugLog.write("frame: none after the action; screen unchanged") }+ DebugLog.write("frame: stream stale (waiting for an IDR); snapping")+ try await snap()+ }+ } catch {+ DebugLog.write("frame after action failed: \(error.localizedDescription)")+ }+ if capturedAt < since { DebugLog.write(String(format: "frame: still %.1f s older than the action", since - capturedAt)) }+ }++ /// Waits until the shown frame was captured after `t`; false on timeout.+ private func newer(than t: Double, timeout: Double) async -> Bool {+ let deadline = now() + timeout+ while capturedAt < t {+ if now() > deadline { return false }+ try? await Task.sleep(nanoseconds: 50_000_000)+ }+ return true+ }++ /// The link dropped: the board forgets `stream on`.+ func linkLost() { streamOn = false }+}diff --git a/ios/IPhoneAgentTests/AgentTests.swift b/ios/IPhoneAgentTests/AgentTests.swiftnew file mode 100644index 0000000..0c024a9--- /dev/null+++ b/ios/IPhoneAgentTests/AgentTests.swift@@ -0,0 +1,173 @@+import XCTest+@testable import IPhoneAgent++/// Port of server/tests/test_agent.py.+@MainActor final class AgentTests: XCTestCase {+ func testParseSingleAction() throws {+ let acts = try Actions.parseActions("THINK: The Search pill is visible, so I tap it.\nDO: tap 500 814")+ XCTAssertEqual(acts, [["thought": .str("The Search pill is visible, so I tap it."), "thought_zh": .str(""),+ "action": .str("tap"), "x": .int(500), "y": .int(814)]])+ XCTAssertEqual(acts[0].keys, ["thought", "thought_zh", "action", "x", "y"])+ }++ func testParseSeveralActionsKeepsThoughtOnFirst() throws {+ let acts = try Actions.parseActions("THINK: Type and search.\nDO: type Whiteboard\nDO: key enter")+ XCTAssertEqual(acts.map { $0["action"]?.str }, ["type", "key"])+ XCTAssertEqual(acts[0]["text"], .str("Whiteboard"))+ XCTAssertEqual(acts[1]["combo"], .str("enter"))+ XCTAssertNil(acts[1]["thought"])+ }++ func testParseCapsAtSixActions() throws {+ let reply = "THINK: draw\n" + (0..<10).map { "DO: tap \($0) \($0)" }.joined(separator: "\n")+ XCTAssertEqual(try Actions.parseActions(reply).count, 6)+ }++ func testParsePathAndCircle() throws {+ XCTAssertEqual(try Actions.parseCommand("path 100 200 300 400 500 600")["points"],+ .arr([.arr([.int(100), .int(200)]), .arr([.int(300), .int(400)]), .arr([.int(500), .int(600)])]))+ XCTAssertEqual(try Actions.parseCommand("circle 500 450 200"),+ ["action": .str("circle"), "x": .int(500), "y": .int(450), "r": .int(200)])+ }++ func testParseRejectsBadCommands() {+ for line in ["fly 1 2", "tap 500", "path 1 2 3"] {+ XCTAssertThrowsError(try Actions.parseCommand(line), line)+ }+ }++ func testParseRequiresADoLine() {+ XCTAssertThrowsError(try Actions.parseActions("THINK: I am not sure what to do."))+ }++ func testParsePlanWithAndWithoutLanguages() {+ XCTAssertTrue(Actions.parsePlan("EN:\n1. Tap Search\nZH:\n1. 点搜索") == ("1. Tap Search", "1. 点搜索"))+ XCTAssertTrue(Actions.parsePlan("1. Tap Search") == ("1. Tap Search", "1. Tap Search"))+ }++ func testCircleIsClosedAndRoundOnATallScreen() {+ let aspect = 0.46 // width / height of a portrait iPhone frame+ let pts = circle(0.5, 0.5, 0.2, aspect: aspect)+ XCTAssertEqual(pts[0].x, pts.last!.x, accuracy: 1e-9)+ XCTAssertEqual(pts[0].y, pts.last!.y, accuracy: 1e-9)+ for p in pts { // equal radius in pixels: y offsets shrink by the aspect ratio+ XCTAssertEqual(hypot(p.x - 0.5, (p.y - 0.5) / aspect), 0.2, accuracy: 1e-9)+ }+ }++ func testActorMayNotRepeatAMoveThatChangedNothing() async throws {+ let actor = FakeModel { n in+ n == 1 ? "THINK: again\nDO: swipe 382 253 382 150" : "THINK: other\nDO: tap 1 2"+ }+ let agent = AgentLoop(phone: nil, screen: FakeScreen(), actor: actor, planner: actor, trace: nil)+ agent.steps = [["action": .str("swipe"), "x1": .int(382), "y1": .int(253), "x2": .int(382), "y2": .int(150),+ "changed": .bool(false)]]+ let acts = try await agent.nextActions()+ XCTAssertEqual(acts[0].act["action"], .str("tap"))+ XCTAssertTrue(actor.prompts[1].contains("changed nothing"))+ }++ func testRepeatingAMoveThatKeepsChangingTheScreenIsNotStuck() {+ let agent = AgentLoop(phone: nil, screen: nil, actor: nil, planner: nil, trace: nil)+ let swipe: JObject = ["action": .str("swipe"), "x1": .int(500), "y1": .int(800), "x2": .int(500), "y2": .int(400)]+ agent.steps = [swipe.merging(["changed": .bool(true)]), swipe.merging(["changed": .bool(true)])]+ XCTAssertFalse(agent.repeating(swipe))+ agent.steps[1]["changed"] = .bool(false) // reached the end of the list+ XCTAssertTrue(agent.repeating(swipe))+ }++ func testPreciseTapFlag() throws {+ XCTAssertEqual(try Actions.parseCommand("tap 120 640 precise"),+ ["action": .str("tap"), "x": .int(120), "y": .int(640), "precise": .bool(true)])+ XCTAssertNil(try Actions.parseCommand("tap 120 640")["precise"])+ }++ // MARK: - beyond the Python tests++ func testHistoryIsFormattedLikePythonJSONDumps() async throws {+ let actor = FakeModel { _ in "THINK: ok\nDO: wait" }+ let agent = AgentLoop(phone: nil, screen: FakeScreen(), actor: actor, planner: actor, trace: nil)+ agent.steps = [+ ["t": .num(1), "shot": .bool(true), "action": .str("plan"), "plan": .str("1. x")],+ ["t": .num(2), "shot": .bool(true), "thought": .str("hi"), "action": .str("tap"), "x": .int(1), "y": .int(2),+ "think_s": .num(1.5), "changed": .bool(true)],+ ["t": .num(3), "shot": .bool(false), "action": .str("type"), "text": .str("café")],+ ]+ _ = try await agent.nextActions()+ XCTAssertTrue(actor.prompts[0].hasSuffix(+ "Recent actions:\n{\"action\": \"tap\", \"x\": 1, \"y\": 2} -> screen changed\n"+ + "{\"action\": \"type\", \"text\": \"caf\\u00e9\"}\n\nNext action?"))+ }++ func testPromptsAreVerbatimFromThePythonServer() throws {+ let agentPy = URL(fileURLWithPath: #filePath).deletingLastPathComponent()+ .appendingPathComponent("../../server/hidagent/agent.py").standardized+ guard let source = try? String(contentsOf: agentPy, encoding: .utf8) else {+ throw XCTSkip("server source not reachable from the test runner")+ }+ XCTAssertTrue(source.contains("PLANNER_PROMPT = \"\"\"" + Prompts.planner + "\"\"\""))+ XCTAssertTrue(source.contains("ACTOR_PROMPT = \"\"\"" + Prompts.actorServer + "\"\"\""))+ }++ func testRunStopsAfterThreeErrorsInARow() async {+ let model = FakeModel { n in n == 1 ? "1. do it" : "no action here" }+ let agent = AgentLoop(phone: FakeGestures(), screen: FakeScreen(), actor: model, planner: model, trace: nil)+ await agent.run()+ XCTAssertEqual(agent.steps.last?["action"], .str("fail"))+ XCTAssertEqual(agent.steps.last?["reason"], .str("3 errors in a row"))+ }++ func testRunFinishesOnDone() async {+ let model = FakeModel { n in n == 1 ? "1. go home" : n == 2 ? "THINK: home\nDO: home" : "THINK: there\nDO: done ok" }+ let phone = FakeGestures()+ let agent = AgentLoop(phone: phone, screen: FakeScreen(), actor: model, planner: model, trace: nil)+ await agent.run()+ XCTAssertEqual(phone.calls, ["home"])+ XCTAssertEqual(agent.steps.map { $0["action"]?.str }, ["plan", "home", "done"])+ XCTAssertEqual(agent.steps.last?["answer"], .str("ok"))+ }+}++// MARK: - fakes++@MainActor final class FakeModel: ChatModel {+ let model = "fake"+ private(set) var prompts: [String] = []+ private let reply: (Int) -> String++ init(_ reply: @escaping (Int) -> String) { self.reply = reply }++ func chat(system: String, text: String, image: Data?, maxTokens: Int, temperature: Double) async throws -> ChatResult {+ prompts.append(text)+ return ChatResult(text: reply(prompts.count), firstToken: nil, total: 0)+ }+}++@MainActor final class FakeScreen: ScreenSource {+ var live = true+ var frame: Data? = Data([0xff, 0xd8])+ var updated = 0.0+ var capturedAt = 0.0+ var aspect = 0.46+}++@MainActor final class FakeDevice: HIDDevice {+ var links = 1+ var connected = true+ var sent: [String] = []+ func send(_ command: String) async throws -> String { sent.append(command); return "" }+ func waitConnected(_ timeout: TimeInterval) async -> Bool { connected }+}++@MainActor final class FakeGestures: Gestures {+ let device: HIDDevice = FakeDevice()+ var calls: [String] = []+ func tap(_ x: Double, _ y: Double, aim: Bool) async throws { calls.append("tap") }+ func swipe(_ x1: Double, _ y1: Double, _ x2: Double, _ y2: Double, hold: Bool) async throws { calls.append("swipe") }+ func drag(_ points: [CGPoint], hold: Bool) async throws { calls.append("drag") }+ func type(_ text: String) async throws { calls.append("type") }+ func key(_ combo: String) async throws { calls.append("key") }+ func goHome() async throws { calls.append("home") }+ func goBack() async throws { calls.append("back") }+ func reset() async throws { calls.append("reset") }+}diff --git a/ios/IPhoneAgentTests/DeviceTests.swift b/ios/IPhoneAgentTests/DeviceTests.swiftnew file mode 100644index 0000000..93098e7--- /dev/null+++ b/ios/IPhoneAgentTests/DeviceTests.swift@@ -0,0 +1,159 @@+import XCTest+@testable import IPhoneAgent++/// A board that answers every command like the firmware does.+@MainActor final class FakeBoard: BoardTransport {+ var isConnected = true+ var lines: [String] = []+ var drops = 0+ var silent = false+ weak var channel: CommandChannel?++ func write(_ line: String) throws {+ lines.append(line)+ guard !silent else { return }+ let parts = line.split(separator: " ", maxSplits: 1).map(String.init)+ let reply = parts[1] == "bad" ? "\(parts[0]) err unknown command" : "\(parts[0]) ok"+ Task { @MainActor in self.channel?.handleReply(reply) }+ }++ func dropLink() { drops += 1 }+}++/// Port of server/tests/test_device.py, with a fake BLE transport instead of a TCP socket.+@MainActor final class DeviceTests: XCTestCase {+ func testTimeoutGrowsWithMoveDistanceAndTextLength() {+ XCTAssertEqual(CommandChannel.timeout("click"), 5)+ XCTAssertGreaterThan(CommandChannel.timeout("move 1000 -20"), CommandChannel.timeout("move 10 10"))+ XCTAssertGreaterThanOrEqual(CommandChannel.timeout("move 10 10"), 5)+ XCTAssertGreaterThan(CommandChannel.timeout("type " + String(repeating: "x", count: 40)),+ CommandChannel.timeout("type hi"))+ }++ func testSendWithoutBoardFailsFast() async {+ do {+ try await CommandChannel().send("ping")+ XCTFail("expected an error")+ } catch {+ XCTAssertTrue(error.localizedDescription.contains("not connected"))+ }+ }++ func testRoundTripWithAFakeBoard() async throws {+ let board = FakeBoard()+ let channel = CommandChannel(transport: board)+ board.channel = channel+ channel.linkUp()+ let ok = await channel.waitConnected(2)+ XCTAssertTrue(ok)+ try await channel.send("ping")+ do {+ try await channel.send("bad")+ XCTFail("expected an error")+ } catch {+ XCTAssertTrue(error.localizedDescription.contains("unknown command"))+ }+ XCTAssertEqual(channel.links, 1)+ let ids = board.lines.compactMap { Int($0.split(separator: " ")[0]) } // request ids: random start, then +1+ XCTAssertEqual(board.lines.map { $0.split(separator: " ")[1] }, ["ping", "bad"])+ XCTAssertEqual(ids.count == 2 ? ids[1] - ids[0] : 0, 1)+ }++ func testCommandsGoOneAtATime() async throws {+ let board = FakeBoard()+ let channel = CommandChannel(transport: board)+ board.channel = channel+ async let a: String = channel.send("move 1 0")+ async let b: String = channel.send("move -1 0")+ _ = try await (a, b)+ XCTAssertEqual(board.lines.count, 2)+ }++ func testLinkDownFailsCommandsInFlight() async {+ let board = FakeBoard()+ board.silent = true+ let channel = CommandChannel(transport: board)+ board.channel = channel+ Task { @MainActor in+ try? await Task.sleep(nanoseconds: 50_000_000)+ channel.linkDown()+ }+ do {+ try await channel.send("click")+ XCTFail("expected an error")+ } catch {+ XCTAssertTrue(error.localizedDescription.contains("disconnected"))+ }+ }++ func testReplyParsing() {+ XCTAssertEqual(BoardReply.parse("12 ok"), BoardReply(id: 12, ok: true, text: ""))+ XCTAssertEqual(BoardReply.parse("3 ok 812\n"), BoardReply(id: 3, ok: true, text: "812"))+ XCTAssertEqual(BoardReply.parse("4 err unknown command"), BoardReply(id: 4, ok: false, text: "unknown command"))+ XCTAssertNil(BoardReply.parse("ok"))+ }++ func testStatusDecoding() throws {+ let json = #"{"up":123456,"rst":"power-on","heap":81234,"psram":6200000,"usb":"ok","net":"ap","ip":"192.168.4.1","sta":1,"ap":"streaming","w":480,"h":1040,"kbps":180,"fps":4.8,"idr":2000,"gop":42000,"ble":{"mtu":247,"phy":2,"kbps":350,"drop":0}}"#+ let s = try XCTUnwrap(BoardStatus.decode(Data(json.utf8)))+ XCTAssertEqual(s.ap, "streaming")+ XCTAssertEqual(s.ble?.mtu, 247)+ XCTAssertEqual(s.fps, 4.8)+ }++ func testPointerRehomesEveryTenGestures() async throws {+ let device = FakeDevice()+ let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".json")+ let pointer = Pointer(device: device, calibrationFile: file)+ pointer.finishCalibration(x: 0.5, y: 0.25) // span 400 x 800+ for _ in 0..<11 { try await pointer.point(0.5, 0.5) }+ XCTAssertEqual(device.sent.filter { $0 == "home" }.count, 2)+ XCTAssertEqual(device.sent[0], "release") // a new link: let go first+ XCTAssertEqual(device.sent[2], "move 200 400")+ }++ func testShortStatusNotifyIsMergedWithTheFullRead() throws {+ let full = try XCTUnwrap(BoardStatus.decode(Data(#"{"up":1,"heap":81234,"usb":"ok","net":"ap","sta":2,"ap":"idle","kbps":180,"ble":{"mtu":247,"phy":2}}"#.utf8)))+ let short = try XCTUnwrap(BoardStatus.decode(Data(#"{"up":2,"usb":"asleep","net":"ap","ap":"streaming","ble":{"mtu":23}}"#.utf8)))+ let m = full.merged(with: short)+ XCTAssertEqual(m.up, 2)+ XCTAssertEqual(m.usb, "asleep")+ XCTAssertEqual(m.ap, "streaming")+ XCTAssertEqual(m.heap, 81234) // kept from the full read+ XCTAssertEqual(m.sta, 2)+ XCTAssertEqual(m.ble?.mtu, 23)+ XCTAssertEqual(m.ble?.phy, 2)+ }++ func testFreshCalibrationHasNoDriftAndSurvivesARestart() {+ let file = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString + ".json")+ let pointer = Pointer(device: FakeDevice(), calibrationFile: file)+ XCTAssertFalse(pointer.calibrated)+ pointer.finishCalibration(x: 0.5, y: 0.25)+ XCTAssertEqual(pointer.drift, 0)+ let again = Pointer(device: FakeDevice(), calibrationFile: file)+ XCTAssertEqual(again.span, Pointer.Span(w: 400, h: 800))+ }++ func testModelSettingsNeedOnlyAnEndpoint() {+ let defaults = UserDefaults(suiteName: UUID().uuidString)!+ let settings = Settings(defaults: defaults, info: nil) // no build-time preset+ XCTAssertFalse(settings.isConfigured) // nothing is built in+ settings.baseURL = "https://example.com/v1"+ XCTAssertTrue(settings.isConfigured) // the model is picked from GET /models+ XCTAssertNil(settings.currentModel)+ settings.model = "some-model"+ XCTAssertEqual(settings.currentModel, "some-model")+ }++ func testProbeFitRecoversScaleAndOffset() {+ let samples: [(Double, Double)] = [150.0, 350, 60].map { u in (u, 0.02 + u / 400) }+ let line = ProbeFit.line(samples)+ XCTAssertEqual(line?.a ?? 0, 1 / 400, accuracy: 1e-9)+ XCTAssertEqual(line?.b ?? 0, 0.02, accuracy: 1e-9)+ XCTAssertEqual(line?.rms ?? 1, 0, accuracy: 1e-9)+ XCTAssertEqual(line?.units(for: 0.52), 200)+ XCTAssertNil(ProbeFit.line([(100, 0.3)]))+ XCTAssertFalse(ProbeFit.usable(0.995)) // stuck at the edge+ }+}diff --git a/ios/IPhoneAgentTests/IslandTests.swift b/ios/IPhoneAgentTests/IslandTests.swiftnew file mode 100644index 0000000..4988e38--- /dev/null+++ b/ios/IPhoneAgentTests/IslandTests.swift@@ -0,0 +1,26 @@+import XCTest+@testable import IPhoneAgent++/// What the character says in the Dynamic Island, and where its eyes go.+@MainActor final class IslandTests: XCTestCase {+ func testTargetFromThought() {+ XCTAssertEqual(IslandStatus.target("I am on the home screen. I tap the Search pill to find Clock."), "Search")+ XCTAssertEqual(IslandStatus.target("My last tap opened Alarms. I tap + to add an alarm."), "+")+ XCTAssertEqual(IslandStatus.target("The time is 08:00. I open Repeat."), "Repeat")+ XCTAssertEqual(IslandStatus.target("I tap “Save” at the top right."), "Save")+ XCTAssertNil(IslandStatus.target("Clock is the top result, so I open it."))+ }++ func testLabelsFitTheCompactIsland() {+ let tap: JObject = ["thought": .str("I tap the Clock app."), "action": .str("tap"), "x": .int(900), "y": .int(100)]+ let s = IslandStatus.acting(tap)+ XCTAssertEqual(s.full, "Tapping Clock")+ XCTAssertLessThanOrEqual(s.short.count, IslandStatus.compactLimit)+ XCTAssertEqual(s.look!.x, 0.8, accuracy: 0.001)+ XCTAssertEqual(s.look!.y, -0.8, accuracy: 0.001)+ let long = IslandStatus.acting(["action": .str("type"), "text": .str("Set an alarm for eight o'clock")])+ XCTAssertLessThanOrEqual(long.short.count, IslandStatus.compactLimit)+ XCTAssertEqual(IslandStatus.acting(["action": .str("type"), "text": .str("0800")]).short, "Typing 0800")+ XCTAssertTrue(IslandStatus.thinking.waits)+ }+}diff --git a/ios/IPhoneAgentTests/LLMTests.swift b/ios/IPhoneAgentTests/LLMTests.swiftnew file mode 100644index 0000000..dd86312--- /dev/null+++ b/ios/IPhoneAgentTests/LLMTests.swift@@ -0,0 +1,138 @@+import XCTest+@testable import IPhoneAgent++/// An in-memory endpoint: records request bodies and answers with `respond`.+final class StubProtocol: URLProtocol {+ nonisolated(unsafe) static var respond: ([String: Any]) -> (Int, String, String) = { _ in (200, "application/json", "{}") }+ nonisolated(unsafe) static var seen: [[String: Any]] = []++ override class func canInit(with request: URLRequest) -> Bool { true }+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }++ override func startLoading() {+ var body = request.httpBody ?? Data()+ if body.isEmpty, let stream = request.httpBodyStream {+ stream.open()+ var buf = [UInt8](repeating: 0, count: 65536)+ while stream.hasBytesAvailable {+ let n = stream.read(&buf, maxLength: buf.count)+ if n <= 0 { break }+ body.append(buf, count: n)+ }+ stream.close()+ }+ let json = (try? JSONSerialization.jsonObject(with: body)) as? [String: Any] ?? [:]+ Self.seen.append(json)+ let (status, type, text) = Self.respond(json)+ let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil,+ headerFields: ["Content-Type": type])!+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)+ client?.urlProtocol(self, didLoad: Data(text.utf8))+ client?.urlProtocolDidFinishLoading(self)+ }++ override func stopLoading() {}+}++/// Port of server/tests/test_llm.py, plus streaming.+@MainActor final class LLMTests: XCTestCase {+ func client(_ model: String, extra: [String: Any] = [:], tokenParam: String = "auto") -> LLMClient {+ let config = URLSessionConfiguration.ephemeral+ config.protocolClasses = [StubProtocol.self]+ return LLMClient(baseURL: "http://test/v1/", model: model, extra: extra, tokenParam: tokenParam,+ session: URLSession(configuration: config))+ }++ /// Only accept the `wants` token parameter, like servers that reject the other one.+ func fakeServer(wants: String) {+ StubProtocol.seen = []+ StubProtocol.respond = { body in+ guard body[wants] != nil else {+ return (400, "application/json", "{\"error\": {\"message\": \"Unsupported parameter. Use '\(wants)' instead.\"}}")+ }+ return (200, "application/json", "{\"choices\": [{\"message\": {\"content\": \"DO: wait\"}}]}")+ }+ }++ func testClassicServersGetMaxTokensOnce() async throws {+ let llm = client("qwen")+ fakeServer(wants: "max_tokens")+ let reply = try await llm.chat(system: "sys", text: "hi", image: nil, maxTokens: 600, temperature: 0)+ XCTAssertEqual(reply.text, "DO: wait")+ XCTAssertEqual(StubProtocol.seen.count, 1)+ XCTAssertEqual(StubProtocol.seen[0]["max_tokens"] as? Int, 600)+ XCTAssertEqual(StubProtocol.seen[0]["stream"] as? Bool, true)+ }++ func testAutoSwitchesToMaxCompletionTokensAndRemembers() async throws {+ let llm = client("gpt")+ fakeServer(wants: "max_completion_tokens")+ _ = try await llm.chat(system: "sys", text: "hi", image: nil, maxTokens: 600, temperature: 0)+ _ = try await llm.chat(system: "sys", text: "again", image: nil, maxTokens: 600, temperature: 0)+ let flags = StubProtocol.seen.map { [$0["max_tokens"] != nil, $0["max_completion_tokens"] != nil] }+ XCTAssertEqual(flags, [[true, false], [false, true], [false, true]])+ }++ func testExplicitTokenParamIsUsedDirectly() async throws {+ let llm = client("gpt", tokenParam: "max_completion_tokens")+ fakeServer(wants: "max_completion_tokens")+ _ = try await llm.chat(system: "sys", text: "hi", image: nil, maxTokens: 600, temperature: 0)+ XCTAssertEqual(StubProtocol.seen.count, 1)+ }++ func testExtraBodyAndImageAreSent() async throws {+ let llm = client("gpt", extra: ["reasoning_effort": "none"])+ fakeServer(wants: "max_tokens")+ _ = try await llm.chat(system: "sys", text: "hi", image: Data([0xff, 0xd8]) + Data("jpeg".utf8),+ maxTokens: 600, temperature: 0)+ let body = StubProtocol.seen[0]+ XCTAssertEqual(body["reasoning_effort"] as? String, "none")+ let user = (body["messages"] as? [[String: Any]])?[1]["content"] as? [[String: Any]]+ let url = (user?[0]["image_url"] as? [String: Any])?["url"] as? String+ XCTAssertTrue(url?.hasPrefix("data:image/jpeg;base64,") ?? false)+ }++ func testStreamedReplyIsJoinedAndTimed() async throws {+ let llm = client("qwen")+ StubProtocol.seen = []+ StubProtocol.respond = { _ in+ let events = ["THINK: ", "ok\n", "DO: wait"].map {+ "data: {\"choices\": [{\"delta\": {\"content\": \"\($0.replacingOccurrences(of: "\n", with: "\\n"))\"}}]}\n\n"+ }+ return (200, "text/event-stream", events.joined() + "data: [DONE]\n\n")+ }+ let reply = try await llm.chat(system: "sys", text: "hi", image: nil, maxTokens: 600, temperature: 0)+ XCTAssertEqual(reply.text, "THINK: ok\nDO: wait")+ XCTAssertNotNil(reply.firstToken)+ }++ func testEmptyReplyIsAskedOnceMoreWithItsReasonLogged() async throws {+ let llm = client("qwen")+ StubProtocol.seen = []+ StubProtocol.respond = { _ in+ let first = StubProtocol.seen.count == 1+ let delta = first ? "{\"reasoning_content\": \"hmm\"}" : "{\"content\": \"DO: wait\"}"+ let finish = first ? "length" : "stop"+ return (200, "text/event-stream", "data: {\"choices\": [{\"delta\": \(delta)}]}\n\n"+ + "data: {\"choices\": [{\"delta\": {}, \"finish_reason\": \"\(finish)\"}], \"usage\": {\"completion_tokens\": 9}}\n\n"+ + "data: [DONE]\n\n")+ }+ let reply = try await llm.chat(system: "sys", text: "hi", image: nil, maxTokens: 600, temperature: 0)+ XCTAssertEqual(StubProtocol.seen.count, 2)+ XCTAssertEqual(reply.text, "DO: wait")+ XCTAssertTrue(reply.retried)+ XCTAssertEqual(reply.finishReason, "stop")+ XCTAssertEqual(reply.usage["completion_tokens"], 9)+ }++ func testHTTPErrorsAreThrown() async {+ let llm = client("qwen")+ StubProtocol.respond = { _ in (500, "text/plain", "boom") }+ do {+ _ = try await llm.chat(system: "sys", text: "hi", image: nil, maxTokens: 600, temperature: 0)+ XCTFail("expected an error")+ } catch {+ XCTAssertTrue(error.localizedDescription.contains("500"))+ }+ }+}diff --git a/ios/IPhoneAgentTests/PromptTests.swift b/ios/IPhoneAgentTests/PromptTests.swiftnew file mode 100644index 0000000..a5a1052--- /dev/null+++ b/ios/IPhoneAgentTests/PromptTests.swift@@ -0,0 +1,21 @@+import XCTest+@testable import IPhoneAgent++/// The prompts come from the bundled prompts/ folder.+final class PromptTests: XCTestCase {+ func testPromptsLoadFromTheBundle() {+ XCTAssertTrue(Prompts.planner.hasPrefix("You plan tasks on an iPhone."))+ XCTAssertTrue(Prompts.actorServer.contains("DO: <action>"))+ XCTAssertFalse(Prompts.appRules.isEmpty)+ XCTAssertFalse(Prompts.planner.hasSuffix("\n")) // the file's final newline is not part of the prompt+ XCTAssertEqual(Prompts.actor, Prompts.actorServer + "\n" + Prompts.appRules)+ XCTAssertEqual(Prompts.plannerApp, Prompts.planner + "\n" + Prompts.appRules)+ }++ func testActionsTheParserKnowsAreDocumented() {+ for verb in ["tap X Y", "swipe X1", "path X1", "circle X Y R", "type TEXT", "key COMBO", "home | back | wait",+ "replan", "done ANSWER", "fail REASON"] {+ XCTAssertTrue(Prompts.actor.contains(verb), verb)+ }+ }+}diff --git a/ios/IPhoneAgentTests/RecoveryTests.swift b/ios/IPhoneAgentTests/RecoveryTests.swiftnew file mode 100644index 0000000..919ba9e--- /dev/null+++ b/ios/IPhoneAgentTests/RecoveryTests.swift@@ -0,0 +1,88 @@+import XCTest+@testable import IPhoneAgent++@MainActor final class RecoveryTests: XCTestCase {+ private func link(_ connected: Bool = true, sta: Int? = 1, ap: String? = "streaming", frameAt: Double = 0) -> Recovery.Link {+ Recovery.Link(connected: connected, sta: sta, ap: ap, frameAt: frameAt)+ }++ func testStagesAfterABoardReboot() {+ var r = Recovery(at: 100)+ XCTAssertEqual(r.next(link(false), at: 100), .wait(.init(part: .board, ask: false)))+ XCTAssertEqual(r.next(link(sta: 0, ap: "idle"), at: 107), .wait(.init(part: .hotspot, ask: false)))+ XCTAssertEqual(r.next(link(sta: 1, ap: "idle"), at: 133), .wait(.init(part: .mirroring, ask: false)))+ XCTAssertEqual(r.next(link(frameAt: 99), at: 140), .wait(.init(part: .mirroring, ask: false)),+ "streaming, but no frame newer than the loss yet")+ XCTAssertEqual(r.next(link(frameAt: 141), at: 141), .live)+ }++ func testAsksOnlyAfterEachPartsQuietTime() {+ var r = Recovery(at: 0)+ XCTAssertEqual(r.next(link(sta: 0), at: 0), .wait(.init(part: .hotspot, ask: false)))+ XCTAssertEqual(r.next(link(sta: 0), at: 29), .wait(.init(part: .hotspot, ask: false)))+ XCTAssertEqual(r.next(link(sta: 0), at: 30), .wait(.init(part: .hotspot, ask: true)))+ XCTAssertEqual(r.next(link(ap: "idle"), at: 31), .wait(.init(part: .mirroring, ask: false)), "a new part starts quiet")+ XCTAssertEqual(r.next(link(ap: "idle"), at: 50), .wait(.init(part: .mirroring, ask: false)))+ XCTAssertEqual(r.next(link(ap: "idle"), at: 51), .wait(.init(part: .mirroring, ask: true)))+ }++ func testGivesUpAfterFiveMinutesNamingWhatIsMissing() {+ var r = Recovery(at: 0)+ XCTAssertEqual(r.next(link(ap: "idle"), at: 0), .wait(.init(part: .mirroring, ask: false)))+ XCTAssertEqual(r.next(link(ap: "idle"), at: 299), .wait(.init(part: .mirroring, ask: true)))+ guard case .giveUp(let reason) = r.next(link(ap: "idle"), at: 300) else { return XCTFail() }+ XCTAssertTrue(reason.contains("Screen Mirroring"))+ }++ func testTheStatusLabelsSayWhatIsMissing() {+ XCTAssertEqual(Recovery.Stage(part: .board, ask: false).status.full, "Reconnecting…")+ XCTAssertEqual(Recovery.Stage(part: .mirroring, ask: false).status.full, "Waiting for mirroring…")+ XCTAssertEqual(Recovery.Stage(part: .mirroring, ask: true).status.full, "Tap Screen Mirroring → ESP32 Agent to continue")+ for part in [Recovery.Part.board, .hotspot, .mirroring] {+ for ask in [false, true] {+ XCTAssertLessThanOrEqual(Recovery.Stage(part: part, ask: ask).status.short.count, IslandStatus.compactLimit)+ }+ }+ }++ func testRunPausesForALostScreenAndGoesOnFromTheSameStep() async {+ let screen = FakeScreen()+ let model = FakeModel { n in n == 1 ? "1. go home" : n == 2 ? "THINK: home\nDO: home" : "THINK: there\nDO: done ok" }+ let phone = FakeGestures()+ let agent = AgentLoop(phone: phone, screen: screen, actor: model, planner: model, trace: nil)+ var stages: [Recovery.Stage?] = []+ var restored = 0+ var state = Recovery.Link(connected: true, sta: 1, ap: "idle", frameAt: 0)+ agent.link = { state }+ agent.onRecover = { stages.append($0) }+ agent.restore = { restored += 1 }+ agent.onStep = { // the link drops right after the first move+ guard agent.steps.last?["action"] == .str("home") else { return }+ screen.live = false+ Task {+ try? await Task.sleep(nanoseconds: 800_000_000) // longer than settling after the move+ state = Recovery.Link(connected: true, sta: 1, ap: "streaming", frameAt: now())+ screen.live = true+ }+ }+ await agent.run()+ XCTAssertEqual(agent.steps.map { $0["action"]?.str }, ["plan", "home", "reconnected", "done"])+ XCTAssertEqual(stages, [Recovery.Stage(part: .mirroring, ask: false), nil])+ XCTAssertEqual(restored, 1)+ XCTAssertTrue(model.prompts[2].contains("the connection was lost and restored; re-check the screen"))+ XCTAssertFalse(model.prompts[1].contains("connection was lost"))+ }++ func testRunEndsWithAClearReasonWhenTheScreenNeverComesBack() async {+ let screen = FakeScreen()+ screen.live = false+ let model = FakeModel { _ in "1. go home" }+ let agent = AgentLoop(phone: FakeGestures(), screen: screen, actor: model, planner: model, trace: nil)+ agent.link = { Recovery.Link(connected: true, sta: 1, ap: "idle", frameAt: 0) }+ agent.recoveryLimit = 0.3+ await agent.run()+ XCTAssertEqual(agent.steps.last?["action"], .str("fail"))+ XCTAssertEqual(agent.steps.last?["reason"], .str(Recovery.reason(.mirroring)))+ XCTAssertTrue(model.prompts.isEmpty, "the model never saw a stale screen")+ }+}diff --git a/ios/IPhoneAgentTests/ReviewTests.swift b/ios/IPhoneAgentTests/ReviewTests.swiftnew file mode 100644index 0000000..9a1cb41--- /dev/null+++ b/ios/IPhoneAgentTests/ReviewTests.swift@@ -0,0 +1,94 @@+import XCTest+@testable import IPhoneAgent++/// Needs-your-help pauses, intent hints, the AI optimizer's reply and demonstration drafts.+@MainActor final class ReviewTests: XCTestCase {+ func testGivingUpAsksForHelpAndGoesOnAfterTakeOver() async {+ let model = SystemRecorder { n in+ switch n {+ case 1: return "1. open it"+ case 2: return "THINK: I need a login\nDO: fail login required"+ case 3: return "1. go on"+ default: return "THINK: there\nDO: done ok"+ }+ }+ let agent = AgentLoop(phone: FakeGestures(), screen: FakeScreen(), actor: model, planner: model, trace: nil)+ var asked: [String] = []+ agent.onHelp = { reason in asked.append(reason); return .resume }+ await agent.run()+ XCTAssertEqual(asked, ["login required"])+ XCTAssertEqual(agent.steps.map { $0["action"]?.str },+ ["plan", "fail", "help", "takeover", "replan (stuck)", "done"])+ }++ func testStopFromHelpEndsTheRun() async {+ let model = SystemRecorder { n in n == 1 ? "1. open it" : "THINK: stuck\nDO: fail no button" }+ let agent = AgentLoop(phone: FakeGestures(), screen: FakeScreen(), actor: model, planner: model, trace: nil)+ agent.onHelp = { _ in .stop }+ await agent.run()+ XCTAssertEqual(agent.steps.last?["action"], .str("stopped"))+ }++ func testIntentHintsAreAppendedToTheActorPromptOnly() async {+ let model = SystemRecorder { n in n == 1 ? "1. go" : "THINK: there\nDO: done ok" }+ let agent = AgentLoop(phone: FakeGestures(), screen: FakeScreen(), actor: model, planner: model, trace: nil)+ agent.hints = ["Type the time instead of scrolling"]+ await agent.run()+ let rule = "\n" + AssistiveTouchSpots.rule+ XCTAssertEqual(model.systems[0], Prompts.plannerApp + rule)+ XCTAssertEqual(model.systems[1], Prompts.actor + rule + "\n\nHints for this task:\n- Type the time instead of scrolling")+ agent.hints = []+ XCTAssertEqual(agent.actorPrompt, Prompts.actor + rule)+ }++ func testOptimizerReplyIsParsed() {+ let r = ReviewDraft.parseOptimized("Sure.\nPROMPT: Set a 7 AM alarm\nHINTS:\n- Type the time\n- Tap Save\n")+ XCTAssertEqual(r?.prompt, "Set a 7 AM alarm")+ XCTAssertEqual(r?.hints, ["Type the time", "Tap Save"])+ XCTAssertNil(ReviewDraft.parseOptimized("no idea"))+ }++ func testDemonstrationReplyBecomesADraftWithUnsureSteps() {+ let frames = (1...3).map { URL(fileURLWithPath: "/tmp/k00\($0).jpg") }+ let draft = DemoRecorder.draft("""+ NAME: Alarm+ PROMPT: Set an alarm+ STEP 1: tap 500 814 | sure+ STEP 3: type "0700" | unsure+ STEP 2: something odd | sure+ """, frames: frames, folder: URL(fileURLWithPath: "/tmp/none"))+ XCTAssertEqual(draft.name, "Alarm")+ XCTAssertEqual(draft.prompt, "Set an alarm")+ XCTAssertEqual(draft.steps.map(\.name), ["tap", "type", "note"])+ XCTAssertEqual(draft.steps.map(\.uncertain), [false, true, true])+ XCTAssertEqual(draft.steps[1].frame, frames[2])+ }++ func testCorrectionsReachTheOptimizerInput() {+ let draft = ReviewDraft(source: .run, folder: nil, runID: nil, outcome: .failed,+ steps: [DraftStep(action: ["action": .str("tap"), "x": .int(1), "y": .int(2)])],+ name: "", prompt: "Set an alarm")+ draft.setFix(draft.steps[0].id, point: CGPoint(x: 905, y: 88), note: "tap the +")+ draft.insert(after: draft.steps[0].id, text: "then tap Save")+ let text = draft.optimizerInput()+ XCTAssertTrue(text.contains("[USER: wrong]"))+ XCTAssertTrue(text.contains("the right spot is 905 88"))+ XCTAssertTrue(text.contains("[USER NOTE: tap the +]"))+ XCTAssertTrue(text.contains("[ADDED BY USER]"))+ XCTAssertEqual(draft.corrections, 2)+ }+}++/// A fake model that also keeps each system prompt.+@MainActor final class SystemRecorder: ChatModel {+ let model = "fake"+ private(set) var systems: [String] = []+ private let reply: (Int) -> String++ init(_ reply: @escaping (Int) -> String) { self.reply = reply }++ func chat(system: String, text: String, image: Data?, maxTokens: Int, temperature: Double) async throws -> ChatResult {+ systems.append(system)+ return ChatResult(text: reply(systems.count), firstToken: nil, total: 0)+ }+}diff --git a/ios/IPhoneAgentTests/ShareTests.swift b/ios/IPhoneAgentTests/ShareTests.swiftnew file mode 100644index 0000000..00521fb--- /dev/null+++ b/ios/IPhoneAgentTests/ShareTests.swift@@ -0,0 +1,58 @@+import XCTest+import UIKit+@testable import IPhoneAgent++/// Redacted run export and import.+final class ShareTests: XCTestCase {+ let redactor = Redactor(secrets: ["sk-test-secret-123", "https://llm.example.com/v1", "llm.example.com", "AgentNet-7C3E", "hunter22"])++ func testTextLosesSecretsIPsAndTypedText() {+ let line = "POST https://llm.example.com/v1 key sk-test-secret-123 on AgentNet-7C3E (hunter22) at 192.168.4.1"+ XCTAssertEqual(redactor.text(line), "POST [redacted] key [redacted] on [redacted] ([redacted]) at [redacted]")+ XCTAssertEqual(redactor.text("THINK: set it\nDO: type 0700\nDO: key enter"), "THINK: set it\nDO: type •••\nDO: key enter")+ XCTAssertEqual(redactor.text("cmd #12 type my secret → ok (21 ms)"), "cmd #12 type ••• → ok (21 ms)")+ }++ func testStepLinesRedactTypeActionsAndPromptHistory() throws {+ let line = #"{"kind": "llm", "prompt": "Recent actions:\n{\"action\": \"type\", \"text\": \"hello mom\"}", "reply": "DO: type hi"}"#+ let step = #"{"kind": "step", "action": "type", "text": "hello mom", "act_s": 0.05}"#+ let a = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(redactor.jsonLine(line).utf8)) as? [String: Any])+ XCTAssertEqual(a["prompt"] as? String, "Recent actions:\n{\"action\": \"type\", \"text\": \"•••\"}")+ XCTAssertEqual(a["reply"] as? String, "DO: type •••")+ let b = try XCTUnwrap(JSONSerialization.jsonObject(with: Data(redactor.jsonLine(step).utf8)) as? [String: Any])+ XCTAssertEqual(b["text"] as? String, "•••")+ XCTAssertEqual(b["act_s"] as? Double, 0.05)+ }++ func testScreenshotTopBandIsBlack() throws {+ let img = UIGraphicsImageRenderer(size: CGSize(width: 10, height: 100)).image { ctx in+ UIColor.white.setFill(); ctx.fill(CGRect(x: 0, y: 0, width: 10, height: 100))+ }+ let out = try XCTUnwrap(redactor.image(try XCTUnwrap(img.jpegData(compressionQuality: 1))))+ let cg = try XCTUnwrap(UIImage(data: out)?.cgImage)+ let pixels = try XCTUnwrap(cg.dataProvider?.data as Data?)+ let bpr = cg.bytesPerRow+ XCTAssertLessThan(pixels[bpr * 2], 40) // row 2: blacked out+ XCTAssertGreaterThan(pixels[bpr * (cg.height - 2)], 200) // near the bottom: untouched+ }++ @MainActor func testExportThenImportRoundTrip() throws {+ let fm = FileManager.default+ let root = fm.temporaryDirectory.appendingPathComponent("share-\(UUID().uuidString)")+ let run = root.appendingPathComponent("20261015-060431")+ try fm.createDirectory(at: run.appendingPathComponent("video"), withIntermediateDirectories: true)+ try Data(#"{"kind": "task", "task": "Alarm at 192.168.4.1"}"#.utf8).write(to: run.appendingPathComponent("steps.jsonl"))+ let package = try RunShare.export([run], redactor: redactor, debugLog: nil)+ XCTAssertEqual(package.runs, 1)+ XCTAssertGreaterThan(package.bytes, 0)++ let into = root.appendingPathComponent("imported")+ XCTAssertEqual(try RunShare.importZip(package.url, into: into), ["imported-20261015-060431"])+ let back = into.appendingPathComponent("imported-20261015-060431")+ XCTAssertTrue(RunShare.isImported(back))+ let loaded = try XCTUnwrap(RunStore.load(back))+ XCTAssertEqual(loaded.task, "Alarm at [redacted]")+ XCTAssertTrue(loaded.imported)+ try? fm.removeItem(at: root)+ }+}diff --git a/ios/IPhoneAgentTests/StoreTests.swift b/ios/IPhoneAgentTests/StoreTests.swiftnew file mode 100644index 0000000..e8d3b15--- /dev/null+++ b/ios/IPhoneAgentTests/StoreTests.swift@@ -0,0 +1,37 @@+import XCTest+@testable import IPhoneAgent++/// Runs read back from trace folders (what the Runs list and the replay player show), and saved intents.+@MainActor final class StoreTests: XCTestCase {+ func testRunIsReadBackWithFramesOutcomeAndDuration() throws {+ let root = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString)+ let traces = TraceStore(root: root)+ traces.start(task: "Open Settings")+ traces.write(Data([0xFF, 0xD8]), kind: "llm", ["role": .str("actor")])+ traces.write(kind: "step", ["action": .str("tap"), "x": .int(500), "y": .int(300), "changed": .bool(true)])+ traces.write(kind: "step", ["action": .str("done"), "answer": .str("ok")])++ let store = RunStore(traces: traces)+ store.reload()+ let run = try XCTUnwrap(store.runs.first)+ XCTAssertEqual(run.task, "Open Settings")+ XCTAssertEqual(run.steps.count, 2)+ XCTAssertEqual(run.moves.count, 1)+ XCTAssertEqual(run.outcome, .done)+ XCTAssertNotNil(run.steps[0].frame)+ XCTAssertNotNil(run.duration)+ XCTAssertEqual(StepText.title(run.steps[0].action), "Tap at 500, 300")+ try? FileManager.default.removeItem(at: root)+ }++ func testIntentsAreSavedAndDeleted() {+ let defaults = UserDefaults(suiteName: UUID().uuidString)!+ let store = IntentStore(defaults: defaults)+ XCTAssertFalse(store.items.isEmpty) // seeded with the examples+ store.add(name: "", prompt: "Open Notes and write hello")+ XCTAssertEqual(store.items.first?.name, "Open Notes and write hello")+ XCTAssertEqual(IntentStore(defaults: defaults).items.count, store.items.count)+ store.delete(at: IndexSet(integer: 0))+ XCTAssertEqual(IntentStore(defaults: defaults).items.first?.name, IntentStore.examples[0].name)+ }+}diff --git a/ios/IPhoneAgentTests/VideoTests.swift b/ios/IPhoneAgentTests/VideoTests.swiftnew file mode 100644index 0000000..800f580--- /dev/null+++ b/ios/IPhoneAgentTests/VideoTests.swift@@ -0,0 +1,65 @@+import XCTest+@testable import IPhoneAgent++/// `video` chunk reassembly (docs/ble-protocol.md).+final class VideoTests: XCTestCase {+ typealias F = VideoAssembler.Flags++ func chunk(_ seq: UInt16, _ flags: F, _ payload: [UInt8], ms: UInt32? = nil) -> Data {+ var d = Data([UInt8(seq & 0xff), UInt8(seq >> 8), flags.rawValue])+ if let ms { d.append(contentsOf: [UInt8(ms & 0xff), UInt8(ms >> 8 & 0xff), UInt8(ms >> 16 & 0xff), UInt8(ms >> 24)]) }+ d.append(contentsOf: payload)+ return d+ }++ let sps: [UInt8] = [0, 0, 0, 1, 0x67, 1, 2]+ let idr: [UInt8] = [0, 0, 0, 1, 0x65, 9, 9]+ let p: [UInt8] = [0, 0, 0, 1, 0x41, 7]++ func testInOrderChunksMakeAccessUnits() {+ var a = VideoAssembler()+ XCTAssertEqual(a.add(chunk(0, [.start, .end, .config], sps, ms: 1000))?.config, true)+ XCTAssertNil(a.add(chunk(1, [.start, .idr], Array(idr[0..<5]), ms: 1001)))+ let unit = a.add(chunk(2, [.end, .idr], Array(idr[5...])))+ XCTAssertEqual(unit, AccessUnit(data: Data(idr), idr: true, config: false, snap: false, boardMs: 1001))+ XCTAssertEqual(a.add(chunk(3, [.start, .end], p, ms: 1200))?.data, Data(p))+ XCTAssertEqual(a.drops, 0)+ }++ func testGapDropsUntilTheNextKeyUnit() {+ var a = VideoAssembler()+ _ = a.add(chunk(10, [.start, .end, .idr], idr, ms: 1))+ XCTAssertNil(a.add(chunk(11, [.start], p, ms: 2)))+ XCTAssertNil(a.add(chunk(13, [.end], p))) // 12 lost: the half unit is dropped+ XCTAssertEqual(a.drops, 1)+ XCTAssertNil(a.add(chunk(14, [.start, .end], p, ms: 3))) // a P-frame after a gap is useless+ XCTAssertNotNil(a.add(chunk(15, [.start, .end, .config], sps, ms: 4))) // recovered on CONFIG+ XCTAssertNotNil(a.add(chunk(16, [.start, .end], p, ms: 5)))+ }++ func testRecoversOnIDRAndWrapsSeq() {+ var a = VideoAssembler()+ _ = a.add(chunk(65534, [.start, .end, .idr], idr, ms: 1))+ XCTAssertNotNil(a.add(chunk(65535, [.start, .end], p, ms: 2)))+ XCTAssertNotNil(a.add(chunk(0, [.start, .end], p, ms: 3))) // u16 wrap is not a gap+ XCTAssertEqual(a.drops, 0)+ XCTAssertNil(a.add(chunk(5, [.start, .end], p, ms: 4)))+ XCTAssertEqual(a.drops, 4)+ let unit = a.add(chunk(6, [.start, .end, .idr, .snap], idr, ms: 5))+ XCTAssertEqual(unit?.snap, true)+ }++ func testWaitsForAKeyUnitAtStartAndIgnoresBench() {+ var a = VideoAssembler()+ XCTAssertNil(a.add(chunk(0, [.start, .end], p, ms: 1)))+ XCTAssertNil(a.add(chunk(1, [.bench], [UInt8](repeating: 0, count: 100))))+ XCTAssertEqual(a.benchBytes, 103)+ XCTAssertNotNil(a.add(chunk(2, [.start, .end, .idr], idr, ms: 2)))+ }++ func testAnnexBSplitsNALUnits() {+ let units = annexBUnits(Data(sps + [0, 0, 1, 0x68, 5] + idr))+ XCTAssertEqual(units.map { $0.first! & 0x1f }, [7, 8, 5])+ XCTAssertEqual(units[0], Data([0x67, 1, 2]))+ }+}diff --git a/ios/IPhoneAgentTests/VisionTests.swift b/ios/IPhoneAgentTests/VisionTests.swiftnew file mode 100644index 0000000..bd4678f--- /dev/null+++ b/ios/IPhoneAgentTests/VisionTests.swift@@ -0,0 +1,91 @@+import CoreGraphics+import ImageIO+import UniformTypeIdentifiers+import XCTest+@testable import IPhoneAgent++/// Port of server/tests/test_vision.py, with the synthetic frames drawn by CoreGraphics.+final class VisionTests: XCTestCase {+ static let W = 498, H = 1080 // a mirrored iPhone frame+ var W: Double { Double(Self.W) }+ var H: Double { Double(Self.H) }++ /// A synthetic home screen: gradient background, optional button, pointer dot and checkmark.+ func screen(pointer: (Double, Double)? = nil, button: Bool = false, checked: Bool = false) -> Data {+ let ctx = CGContext(data: nil, width: Self.W, height: Self.H, bitsPerComponent: 8, bytesPerRow: 0,+ space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!+ ctx.translateBy(x: 0, y: CGFloat(Self.H)) // draw with a top-left origin, like PIL+ ctx.scaleBy(x: 1, y: -1)+ func rgb(_ r: Int, _ g: Int, _ b: Int) -> CGColor {+ CGColor(red: CGFloat(r) / 255, green: CGFloat(g) / 255, blue: CGFloat(b) / 255, alpha: 1)+ }+ for y in 0..<Self.H {+ ctx.setFillColor(rgb(40, 60 + y / 10, 120))+ ctx.fill(CGRect(x: 0, y: y, width: Self.W, height: 1))+ }+ if button {+ ctx.setFillColor(rgb(250, 250, 250))+ ctx.fill(CGRect(x: 150, y: 400, width: 201, height: 201))+ }+ if let (x, y) = pointer {+ ctx.setFillColor(rgb(200, 200, 200))+ ctx.fillEllipse(in: CGRect(x: x - 12, y: y - 12, width: 25, height: 25))+ }+ if checked {+ ctx.setStrokeColor(rgb(255, 149, 0))+ ctx.setLineWidth(4)+ ctx.addLines(between: [CGPoint(x: 430, y: 495), CGPoint(x: 438, y: 505), CGPoint(x: 452, y: 485)])+ ctx.strokePath()+ }+ let out = NSMutableData()+ let dest = CGImageDestinationCreateWithData(out, UTType.jpeg.identifier as CFString, 1, nil)!+ CGImageDestinationAddImage(dest, ctx.makeImage()!, [kCGImageDestinationLossyCompressionQuality: 0.75] as CFDictionary)+ CGImageDestinationFinalize(dest)+ return out as Data+ }++ func p(_ x: Double, _ y: Double) -> CGPoint { CGPoint(x: x / W, y: y / H) }++ func testPointerMoveIsNotAScreenChange() {+ XCTAssertFalse(Vision.changed(screen(pointer: (260, 856)), screen(pointer: (272, 856)),+ ignore: [p(260, 856), p(272, 856)]))+ }++ func testNewContentIsAScreenChange() {+ XCTAssertTrue(Vision.changed(screen(pointer: (260, 856)), screen(pointer: (260, 856), button: true)))+ }++ func testMissingFrameCountsAsChanged() {+ XCTAssertTrue(Vision.changed(nil, screen()))+ }++ func testPointerIsFoundFromANudge() throws {+ let found = try XCTUnwrap(Vision.pointer(screen(pointer: (262, 856)), screen(pointer: (274, 856)),+ near: CGPoint(x: 0.5, y: 0.8), shift: 12 / W))+ XCTAssertEqual(found.x * W, 262, accuracy: 3)+ XCTAssertEqual(found.y * H, 856, accuracy: 3)+ }++ func testPointerNotFoundWhenNothingMoved() {+ let frame = screen(pointer: (262, 856))+ XCTAssertNil(Vision.pointer(frame, frame, near: CGPoint(x: 0.5, y: 0.8), shift: 12 / W))+ }++ func testSmallCheckmarkCountsAsAChange() {+ XCTAssertTrue(Vision.changed(screen(pointer: (100, 500)), screen(pointer: (100, 500), checked: true)))+ }++ func testMaskedPointerMoveIsNotAChange() {+ XCTAssertFalse(Vision.changed(screen(pointer: (100, 500)), screen(pointer: (300, 500)),+ ignore: [p(100, 500), p(300, 500)]))+ }++ func testPointerFarFromTheTargetIsFoundWithAFullScreenSearch() throws {+ let before = screen(pointer: (354, 136)), after = screen(pointer: (366, 136))+ XCTAssertNil(Vision.pointer(before, after, near: CGPoint(x: 0.9, y: 0.1), shift: 12 / W)) // outside the window+ let found = try XCTUnwrap(Vision.pointer(before, after, near: CGPoint(x: 0.5, y: 0.5), shift: 12 / W,+ reach: CGPoint(x: 0.5, y: 0.5)))+ XCTAssertEqual(found.x * W, 354, accuracy: 3)+ XCTAssertEqual(found.y * H, 136, accuracy: 3)+ }+}diff --git a/ios/Shared/AgentActivity.swift b/ios/Shared/AgentActivity.swiftnew file mode 100644index 0000000..7a6ee66--- /dev/null+++ b/ios/Shared/AgentActivity.swift@@ -0,0 +1,78 @@+import ActivityKit+import AppIntents+import Foundation++/// The Live Activity / Dynamic Island of a run or a demonstration recording: while the agent works the app+/// is in the background, so this is the only thing the user sees.+struct AgentActivityAttributes: ActivityAttributes {+ enum Phase: String, Codable, Hashable { case running, help, recording }++ struct ContentState: Codable, Hashable {+ var mood: Mood+ var step: Int // actions done+ var limit: Int // the step limit of a run+ var line: String // what it does now, one line+ var finished = false+ var phase = Phase.running+ var since = Date() // recording start, for the timer+ var label = "" // what the character says, compact island ("Thinking…", "Tapping Clock")+ var labelFull = "" // the same, longer, for the expanded island and the Lock Screen+ var lookX = 0.0 // where the eyes look, -1...1 (darting while it waits, toward the pointer's target)+ var lookY = 0.0++ var look: CGPoint { CGPoint(x: lookX, y: lookY) }+ }++ var task: String+ var runID: String+ var name: String? // the agent's name, as the user calls it++ static func url(run: String) -> URL { URL(string: "iphoneagent://run/\(run)")! }+}++/// What the Live Activity buttons and notification actions ask the app to do.+enum AgentCommand: String {+ case stop, resume, skip, takeOver, stopRecording+}++/// Set by the app; nil inside the widget extension (the intents run in the app's process).+@MainActor enum AgentControl {+ static var handle: ((AgentCommand) async -> Void)?+}++/// Stop button: releases everything and stops the agent.+struct StopAgentIntent: LiveActivityIntent {+ static let title: LocalizedStringResource = "Stop the agent"+ static let description = IntentDescription("Stops the running task and lets go of the screen.")+ func perform() async throws -> some IntentResult {+ await AgentControl.handle?(.stop)+ return .result()+ }+}++/// "Needs your help": the user did it by hand, the agent goes on from the current screen.+struct ContinueAgentIntent: LiveActivityIntent {+ static let title: LocalizedStringResource = "Continue"+ func perform() async throws -> some IntentResult {+ await AgentControl.handle?(.resume)+ return .result()+ }+}++/// "Needs your help": skip the step the agent is stuck on.+struct SkipStepIntent: LiveActivityIntent {+ static let title: LocalizedStringResource = "Skip step"+ func perform() async throws -> some IntentResult {+ await AgentControl.handle?(.skip)+ return .result()+ }+}++/// Ends a demonstration recording.+struct StopRecordingIntent: LiveActivityIntent {+ static let title: LocalizedStringResource = "Stop recording"+ func perform() async throws -> some IntentResult {+ await AgentControl.handle?(.stopRecording)+ return .result()+ }+}diff --git a/ios/Shared/AgentFace.swift b/ios/Shared/AgentFace.swiftnew file mode 100644index 0000000..e9fea52--- /dev/null+++ b/ios/Shared/AgentFace.swift@@ -0,0 +1,241 @@+import SwiftUI++/// The agent's mood; drives the character on Home, in onboarding, in the replay player and in the Live Activity.+enum Mood: String, Codable, Hashable {+ case sleeping, idle, listening, thinking, acting, success, failure+ /// Poke reactions (Home): spiral eyes after a flurry of taps, closed smiling eyes while petted, a wink.+ case dizzy, content, wink+}++/// The character: the logo redrawn as vectors (rounded black board, two glowing eyes, a USB-C tab), so it can+/// blink, look around and hop. Animations are short springs and stop under Reduce Motion.+struct AgentFace: View {+ var mood: Mood+ /// Where the eyes look, -1...1 on each axis (e.g. toward a tap point).+ var look: CGPoint = .zero+ /// How far the eyes travel for a full look (1 = Home size; the tiny island face needs more to read).+ var lookRange: CGFloat = 1+ var animated = true+ var showsTab = true+ /// Hop / shake by itself when the mood changes (off while a poke drives the face).+ var reacts = true+ @Environment(\.accessibilityReduceMotion) private var reduceMotion+ @State private var hop: CGFloat = 0+ @State private var shake: CGFloat = 0++ var body: some View {+ GeometryReader { g in+ let s = min(g.size.width, g.size.height / (showsTab ? 1.12 : 1))+ Group {+ if animated && !reduceMotion {+ TimelineView(.animation(minimumInterval: 1 / 30)) { t in face(s, t: t.date.timeIntervalSinceReferenceDate) }+ } else {+ face(s, t: 0)+ }+ }+ .offset(x: shake, y: hop)+ .frame(width: g.size.width, height: g.size.height)+ }+ .aspectRatio(showsTab ? 1 / 1.12 : 1, contentMode: .fit)+ .onChange(of: mood) { _, m in react(to: m) }+ .accessibilityElement()+ .accessibilityLabel(Text("ESP32 Agent"))+ .accessibilityValue(Text(LocalizedStringKey(mood.rawValue)))+ }++ private func react(to m: Mood) {+ guard animated && !reduceMotion && reacts else { return }+ switch m {+ case .acting:+ jump(1)+ case .success:+ jump(2)+ case .failure:+ withAnimation(.spring(response: 0.12, dampingFraction: 0.2)) { shake = 6 }+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) {+ withAnimation(.spring(response: 0.35, dampingFraction: 0.4)) { shake = 0 }+ }+ default:+ break+ }+ }++ private func jump(_ times: Int) {+ for i in 0..<times {+ DispatchQueue.main.asyncAfter(deadline: .now() + Double(i) * 0.32) {+ withAnimation(.spring(response: 0.16, dampingFraction: 0.6)) { hop = -14 }+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.14) {+ withAnimation(.spring(response: 0.3, dampingFraction: 0.55)) { hop = 0 }+ }+ }+ }+ }++ // MARK: - drawing++ private func face(_ s: CGFloat, t: Double) -> some View {+ let breathe = mood == .idle ? 1 + 0.012 * sin(t * 1.6) : 1+ let float = mood == .thinking ? 3 * sin(t * 2.4) : 0+ let lean: Double = mood == .listening ? 6 : 0+ return VStack(spacing: 0) {+ ZStack {+ RoundedRectangle(cornerRadius: s * 0.24, style: .continuous)+ .fill(LinearGradient(colors: [Color(white: 0.86), Color(white: 0.55), Color(white: 0.8)],+ startPoint: .topLeading, endPoint: .bottomTrailing))+ RoundedRectangle(cornerRadius: s * 0.2, style: .continuous)+ .fill(Color.black)+ .padding(s * 0.045)+ RoundedRectangle(cornerRadius: s * 0.2, style: .continuous) // glass highlight+ .fill(LinearGradient(colors: [.white.opacity(0.16), .clear], startPoint: .topLeading, endPoint: .center))+ .padding(s * 0.045)+ eyes(s, t: t)+ if mood == .sleeping { zz(s, t: t) }+ }+ .frame(width: s, height: s)+ if showsTab {+ UnevenRoundedRectangle(bottomLeadingRadius: s * 0.04, bottomTrailingRadius: s * 0.04)+ .fill(Color(white: 0.7))+ .frame(width: s * 0.2, height: s * 0.1)+ .overlay(HStack(spacing: s * 0.025) {+ ForEach(0..<3, id: \.self) { _ in+ Capsule().fill(Color(red: 0.86, green: 0.66, blue: 0.2)).frame(width: s * 0.022, height: s * 0.05)+ }+ })+ .padding(.top, -s * 0.01)+ }+ }+ .scaleEffect(breathe)+ .rotation3DEffect(.degrees(lean), axis: (x: 1, y: 0, z: 0))+ .offset(y: float)+ }++ private static let glow = Color(red: 1, green: 0.96, blue: 0.86)++ @ViewBuilder private func eyes(_ s: CGFloat, t: Double) -> some View {+ let w = s * 0.14, h = s * 0.25, gap = s * 0.37+ let gaze = gazeOffset(t: t)+ let dx = gaze.x * s * 0.05 * lookRange, dy = gaze.y * s * 0.04 * lookRange+ switch mood {+ case .sleeping:+ HStack(spacing: gap - w) {+ ForEach(0..<2, id: \.self) { _ in Capsule().fill(Self.glow.opacity(0.55)).frame(width: w, height: s * 0.025) }+ }+ .offset(y: s * 0.05)+ case .success:+ HStack(spacing: gap - w) {+ ForEach(0..<2, id: \.self) { _ in Caret().stroke(Self.glow, style: StrokeStyle(lineWidth: s * 0.05, lineCap: .round, lineJoin: .round))+ .frame(width: w * 1.3, height: h * 0.45) }+ }+ .shadow(color: Self.glow.opacity(0.8), radius: s * 0.04)+ .offset(y: -s * 0.02)+ case .dizzy:+ HStack(spacing: gap - w * 1.4) {+ ForEach(0..<2, id: \.self) { i in+ Spiral().stroke(Self.glow, style: StrokeStyle(lineWidth: s * 0.03, lineCap: .round))+ .frame(width: w * 1.7, height: w * 1.7)+ .rotationEffect(.radians((i == 0 ? 1 : -1) * t * 9))+ }+ }+ .shadow(color: Self.glow.opacity(0.8), radius: s * 0.04)+ case .content:+ HStack(spacing: gap - w * 1.3) {+ ForEach(0..<2, id: \.self) { _ in+ Smile().stroke(Self.glow, style: StrokeStyle(lineWidth: s * 0.045, lineCap: .round))+ .frame(width: w * 1.3, height: h * 0.28)+ }+ }+ .shadow(color: Self.glow.opacity(0.8), radius: s * 0.04)+ .offset(y: s * 0.04)+ case .wink:+ HStack(spacing: gap - w * 1.15) {+ Capsule().fill(Self.glow).frame(width: w, height: h)+ Caret().stroke(Self.glow, style: StrokeStyle(lineWidth: s * 0.05, lineCap: .round, lineJoin: .round))+ .frame(width: w * 1.3, height: h * 0.35)+ }+ .shadow(color: Self.glow.opacity(0.9), radius: s * 0.05)+ .offset(y: -s * 0.02)+ case .failure:+ HStack(alignment: .bottom, spacing: gap - w) {+ Capsule().fill(Self.glow).frame(width: w * 1.1, height: h * 0.85)+ Capsule().fill(Self.glow).frame(width: w * 0.8, height: h * 0.55)+ }+ .shadow(color: Self.glow.opacity(0.7), radius: s * 0.04)+ .offset(y: s * 0.05)+ default:+ let scale: CGFloat = mood == .listening ? 1.15 : 1+ HStack(spacing: gap - w) {+ ForEach(0..<2, id: \.self) { i in+ let tilt = mood == .thinking ? (i == 0 ? -1.0 : 1.0) * s * 0.02 * sin(t * 2.4) : 0+ Capsule().fill(Self.glow)+ .frame(width: w * scale, height: h * scale * blink(t))+ .offset(y: tilt)+ }+ }+ .shadow(color: Self.glow.opacity(0.9), radius: s * 0.05)+ .offset(x: dx, y: dy - s * 0.02)+ }+ }++ /// 1 = open; closes briefly every few seconds while idle or listening.+ private func blink(_ t: Double) -> CGFloat {+ guard mood == .idle || mood == .listening, animated else { return 1 }+ let phase = t.truncatingRemainder(dividingBy: 4.3)+ return phase < 0.13 ? max(0.08, abs(phase - 0.065) / 0.065) : 1+ }++ private func gazeOffset(t: Double) -> CGPoint {+ switch mood {+ case .acting: return look+ case .listening: return CGPoint(x: 0, y: 0.6)+ case .thinking: return animated ? CGPoint(x: sin(t * 2.4), y: -0.2) : look // static (island): the app moves it+ case .idle where animated: // a look around now and then+ let p = t.truncatingRemainder(dividingBy: 9)+ return CGPoint(x: p > 6 && p < 7 ? -0.7 : p > 7.4 && p < 8.2 ? 0.7 : 0, y: 0)+ default: return .zero+ }+ }++ private func zz(_ s: CGFloat, t: Double) -> some View {+ let p = animated ? t.truncatingRemainder(dividingBy: 3) / 3 : 0.5+ return Text(verbatim: "z")+ .font(.system(size: s * 0.12, weight: .bold, design: .rounded))+ .foregroundStyle(Self.glow.opacity(1 - p))+ .offset(x: s * 0.24 + p * s * 0.08, y: -s * 0.18 - p * s * 0.12)+ }+}++/// "^" for the happy eyes.+struct Caret: Shape {+ func path(in r: CGRect) -> Path {+ var p = Path()+ p.move(to: CGPoint(x: r.minX, y: r.maxY))+ p.addLine(to: CGPoint(x: r.midX, y: r.minY))+ p.addLine(to: CGPoint(x: r.maxX, y: r.maxY))+ return p+ }+}++/// "‿" for closed, contented eyes.+struct Smile: Shape {+ func path(in r: CGRect) -> Path {+ var p = Path()+ p.move(to: CGPoint(x: r.minX, y: r.minY))+ p.addQuadCurve(to: CGPoint(x: r.maxX, y: r.minY), control: CGPoint(x: r.midX, y: r.maxY * 2 - r.minY))+ return p+ }+}++/// A spiral for dizzy eyes.+struct Spiral: Shape {+ func path(in r: CGRect) -> Path {+ var p = Path()+ let c = CGPoint(x: r.midX, y: r.midY), maxR = min(r.width, r.height) / 2+ for i in 0...60 {+ let a = Double(i) / 60 * 2.6 * 2 * .pi+ let rad = maxR * Double(i) / 60+ let pt = CGPoint(x: c.x + rad * cos(a), y: c.y + rad * sin(a))+ if i == 0 { p.move(to: pt) } else { p.addLine(to: pt) }+ }+ return p+ }+}diff --git a/ios/Shared/AgentIntents.swift b/ios/Shared/AgentIntents.swiftnew file mode 100644index 0000000..a7f561a--- /dev/null+++ b/ios/Shared/AgentIntents.swift@@ -0,0 +1,77 @@+import AppIntents+import Foundation++/// A request from Siri, Shortcuts, a widget or a control, handled by the app process (AppModel sets `handle`).+enum AgentRequest {+ case runTask(String), runSaved(UUID?), status, calibrate+}++@MainActor enum AgentRequests {+ /// Returns the line to say or show.+ static var handle: ((AgentRequest) async -> String)?+ nonisolated static var unavailable: String { String(localized: "Open ESP32 Agent once, then try again.") }+}++/// A saved intent (My Intents), as Siri and Shortcuts see it.+struct SavedIntentEntity: AppEntity {+ static let typeDisplayRepresentation: TypeDisplayRepresentation = "Saved Intent"+ static let defaultQuery = SavedIntentQuery()++ let id: UUID+ let name: String+ let symbol: String++ init(_ item: AgentSnapshot.Item) {+ id = item.id+ name = item.name+ symbol = item.symbol+ }++ var displayRepresentation: DisplayRepresentation {+ DisplayRepresentation(title: "\(name)", image: .init(systemName: symbol))+ }+}++struct SavedIntentQuery: EntityStringQuery {+ private var items: [SavedIntentEntity] { (SharedState.load()?.intents ?? []).map(SavedIntentEntity.init) }++ func entities(for identifiers: [UUID]) async throws -> [SavedIntentEntity] {+ items.filter { identifiers.contains($0.id) }+ }++ func entities(matching string: String) async throws -> [SavedIntentEntity] {+ items.filter { $0.name.localizedCaseInsensitiveContains(string) }+ }++ func suggestedEntities() async throws -> [SavedIntentEntity] { items }+}++/// Runs a saved intent. A LiveActivityIntent, so it runs in the app process (also from a widget button)+/// and may start the Live Activity from the background.+struct RunSavedIntentIntent: LiveActivityIntent {+ static let title: LocalizedStringResource = "Run a Saved Intent"+ static let description = IntentDescription("Runs one of your saved intents on ESP32 Agent.")++ @Parameter(title: "Intent") var intent: SavedIntentEntity++ init() {}+ init(intent: SavedIntentEntity) { self.intent = intent }++ static var parameterSummary: some ParameterSummary { Summary("Run \(\.$intent)") }++ func perform() async throws -> some IntentResult & ProvidesDialog {+ let line = await AgentRequests.handle?(.runSaved(intent.id)) ?? AgentRequests.unavailable+ return .result(dialog: "\(line)")+ }+}++/// Runs the intent run last (else the first saved one): the Control Center button.+struct RunLastIntentIntent: LiveActivityIntent {+ static let title: LocalizedStringResource = "Run Last Intent"+ static let description = IntentDescription("Runs the saved intent you ran last on ESP32 Agent.")++ func perform() async throws -> some IntentResult & ProvidesDialog {+ let line = await AgentRequests.handle?(.runSaved(nil)) ?? AgentRequests.unavailable+ return .result(dialog: "\(line)")+ }+}diff --git a/ios/Shared/AgentSnapshot.swift b/ios/Shared/AgentSnapshot.swiftnew file mode 100644index 0000000..dc79af1--- /dev/null+++ b/ios/Shared/AgentSnapshot.swift@@ -0,0 +1,68 @@+import Foundation+import WidgetKit++/// What the widgets, controls and the intent entity query need from the app, written by the app to the+/// App Group (falls back to the app's own defaults when the group isn't signed in, e.g. the open-source build).+struct AgentSnapshot: Codable, Equatable {+ enum Status: String, Codable { case ready, running, offline, needsSetup }++ struct Item: Codable, Equatable, Identifiable {+ var id: UUID+ var name: String+ var prompt: String+ var symbol: String+ }++ struct LastRun: Codable, Equatable {+ var task: String+ var ok: Bool+ var line: String // the answer, or why it stopped+ var date: Date+ }++ var status: Status+ var step = 0+ var task = ""+ var intents: [Item] = []+ var lastIntent: UUID?+ var lastRun: LastRun?+ var demo = false++ var mood: Mood {+ switch status {+ case .ready: return .idle+ case .running: return .thinking+ case .offline, .needsSetup: return .sleeping+ }+ }++ /// The intent "Run last intent" starts: the last one run, else the first saved.+ var lastItem: Item? { intents.first { $0.id == lastIntent } ?? intents.first }++ /// Mock data for widget previews and the gallery.+ static let preview = AgentSnapshot(+ status: .ready,+ intents: [Item(id: UUID(), name: String(localized: "Daily 7 AM alarm"), prompt: "", symbol: "alarm.fill"),+ Item(id: UUID(), name: String(localized: "Draw a smiley"), prompt: "", symbol: "scribble"),+ Item(id: UUID(), name: String(localized: "Wi-Fi settings"), prompt: "", symbol: "wifi"),+ Item(id: UUID(), name: String(localized: "Note: hello"), prompt: "", symbol: "note.text")],+ lastRun: LastRun(task: String(localized: "Draw a smiley"), ok: true, line: String(localized: "Smiley drawn"),+ date: Date().addingTimeInterval(-1800)),+ demo: true)+}++enum SharedState {+ /// group.<bundle ID>, set at build time (IA_BUNDLE_ID in Config/*.xcconfig)+ static let group = Bundle.main.object(forInfoDictionaryKey: "IAAppGroup") as? String ?? "group.com.example.esp32agent"+ static let kind = "AgentStatus"+ private static let key = "agentSnapshot"+ static var defaults: UserDefaults { UserDefaults(suiteName: group) ?? .standard }++ static func load() -> AgentSnapshot? {+ defaults.data(forKey: key).flatMap { try? JSONDecoder().decode(AgentSnapshot.self, from: $0) }+ }++ static func save(_ snapshot: AgentSnapshot) {+ defaults.set(try? JSONEncoder().encode(snapshot), forKey: key)+ }+}diff --git a/ios/project.yml b/ios/project.ymlnew file mode 100644index 0000000..afa150a--- /dev/null+++ b/ios/project.yml@@ -0,0 +1,109 @@+name: IPhoneAgent+options:+ developmentLanguage: en+ deploymentTarget:+ iOS: "18.0"+configFiles:+ Debug: Config/Shared.xcconfig+ Release: Config/Shared.xcconfig+settings:+ base:+ SWIFT_VERSION: "5.0"+ CODE_SIGN_STYLE: Automatic+ TARGETED_DEVICE_FAMILY: "1"+targets:+ IPhoneAgent:+ type: application+ platform: iOS+ sources:+ - IPhoneAgent+ - Shared+ - path: ../prompts # the model prompts, bundled as a folder+ type: folder+ buildPhase: resources+ dependencies:+ - target: AgentActivity+ embed: true+ info:+ path: IPhoneAgent/Info.plist+ properties:+ CFBundleDisplayName: ESP32 Agent+ CFBundleDevelopmentRegion: en+ CFBundleLocalizations: [en, zh-Hans]+ UILaunchScreen:+ UIColorName: LaunchBackground+ UIImageName: LaunchLogo+ NSSupportsLiveActivities: true+ CFBundleURLTypes:+ - CFBundleURLName: $(IA_BUNDLE_ID)+ CFBundleURLSchemes: [iphoneagent]+ UIRequiresFullScreen: true+ UISupportedInterfaceOrientations: [UIInterfaceOrientationPortrait]+ NSBluetoothAlwaysUsageDescription: ESP32 Agent talks to its USB board over Bluetooth to see the screen and move the pointer.+ UIBackgroundModes: [bluetooth-central]+ UIFileSharingEnabled: true+ LSSupportsOpeningDocumentsInPlace: true+ CFBundleDocumentTypes: # shared run archives (Settings › Privacy › Export) open as imported runs+ - CFBundleTypeName: ESP32 Agent runs+ LSHandlerRank: Alternate+ LSItemContentTypes: [public.zip-archive]+ # Optional build-time LLM preset from Config/Local.xcconfig (empty in the open-source build)+ IAPresetBaseURL: $(IA_PRESET_BASE_URL)+ IAPresetModel: $(IA_PRESET_MODEL)+ IAPresetKey: $(IA_PRESET_KEY)+ IAAppGroup: group.$(IA_BUNDLE_ID)+ settings:+ base:+ PRODUCT_BUNDLE_IDENTIFIER: $(IA_BUNDLE_ID)+ PRODUCT_NAME: IPhoneAgent+ GENERATE_INFOPLIST_FILE: NO+ SWIFT_EMIT_LOC_STRINGS: YES+ ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon+ ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME: AccentColor+ LOCALIZATION_PREFERS_STRING_CATALOGS: YES+ # Hotspot entitlement needs an Apple ID in Xcode; opt in via Local.xcconfig.+ CODE_SIGN_ENTITLEMENTS: $(IA_ENTITLEMENTS)+ AgentActivity:+ type: app-extension+ platform: iOS+ sources: [AgentActivity, Shared]+ info:+ path: AgentActivity/Info.plist+ properties:+ CFBundleDisplayName: ESP32 Agent+ CFBundleDevelopmentRegion: en+ CFBundleLocalizations: [en, zh-Hans]+ CFBundleShortVersionString: "1.0"+ CFBundleVersion: "1"+ IAAppGroup: group.$(IA_BUNDLE_ID)+ NSExtension:+ NSExtensionPointIdentifier: com.apple.widgetkit-extension+ settings:+ base:+ PRODUCT_BUNDLE_IDENTIFIER: $(IA_BUNDLE_ID).activity+ CODE_SIGN_ENTITLEMENTS: $(IA_WIDGET_ENTITLEMENTS)+ PRODUCT_NAME: AgentActivity+ GENERATE_INFOPLIST_FILE: NO+ SWIFT_EMIT_LOC_STRINGS: YES+ LOCALIZATION_PREFERS_STRING_CATALOGS: YES+ SKIP_INSTALL: YES+ IPhoneAgentTests:+ type: bundle.unit-test+ platform: iOS+ sources: [IPhoneAgentTests]+ dependencies:+ - target: IPhoneAgent+ settings:+ base:+ PRODUCT_BUNDLE_IDENTIFIER: $(IA_BUNDLE_ID).tests+ GENERATE_INFOPLIST_FILE: YES+ TEST_HOST: "$(BUILT_PRODUCTS_DIR)/IPhoneAgent.app/IPhoneAgent"+ BUNDLE_LOADER: "$(TEST_HOST)"+schemes:+ IPhoneAgent:+ build:+ targets:+ IPhoneAgent: all+ IPhoneAgentTests: [test]+ test:+ targets: [IPhoneAgentTests]diff --git a/ios/scripts/l10n.py b/ios/scripts/l10n.pynew file mode 100755index 0000000..32ef32f--- /dev/null+++ b/ios/scripts/l10n.py@@ -0,0 +1,79 @@+#!/usr/bin/env python3+"""Keep IPhoneAgent/Localizable.xcstrings in sync with the code.++ scripts/l10n.py sync add every UI string the compiler found (build first) to the catalog+ scripts/l10n.py import fr fr.json merge {"English key": "translation"} for a language+ scripts/l10n.py check list keys without a translation, per language in CFBundleLocalizations++Adding a language: put its code in project.yml (CFBundleLocalizations), run `import`, run `check`.+"""+import glob+import json+import re+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+CATALOG = ROOT / "IPhoneAgent" / "Localizable.xcstrings"+SAME = {" ", "BLE", "USB", "PHY", "PSRAM", "Wi-Fi", "{}", "ESP32 Agent", "https://your-endpoint/v1", "HID %@"}+++def load():+ return json.loads(CATALOG.read_text()) if CATALOG.exists() else {"sourceLanguage": "en", "strings": {}, "version": "1.0"}+++def save(cat):+ cat["strings"] = dict(sorted(cat["strings"].items()))+ CATALOG.write_text(json.dumps(cat, ensure_ascii=False, indent=2, separators=(",", " : ")) + "\n")+++def languages():+ text = (ROOT / "project.yml").read_text()+ return [l for l in re.search(r"CFBundleLocalizations: \[(.*?)\]", text).group(1).replace(" ", "").split(",") if l != "en"]+++def compiled_keys():+ keys = set()+ for f in glob.glob(str(ROOT / "build/Build/Intermediates.noindex/IPhoneAgent.build/*/IPhoneAgent.build/**/*.stringsdata"),+ recursive=True):+ for entries in json.load(open(f)).get("tables", {}).values():+ keys.update(e["key"] for e in entries)+ return keys+++def main(cmd, *args):+ cat = load()+ if cmd == "sync":+ keys = compiled_keys()+ if not keys:+ sys.exit("no .stringsdata found: build the app first (derivedDataPath build)")+ for k in keys:+ entry = cat["strings"].setdefault(k, {})+ if k in SAME:+ entry["shouldTranslate"] = False+ for k in set(cat["strings"]) - keys:+ cat["strings"][k]["extractionState"] = "stale"+ save(cat)+ print(f"{len(keys)} keys")+ elif cmd == "import":+ lang, path = args+ for k, v in json.loads(Path(path).read_text()).items():+ if k in cat["strings"]:+ cat["strings"][k].setdefault("localizations", {})[lang] = {"stringUnit": {"state": "translated", "value": v}}+ save(cat)+ elif cmd == "check":+ missing = 0+ for lang in languages():+ for k, e in cat["strings"].items():+ if not e.get("shouldTranslate", True) or e.get("extractionState") == "stale":+ continue+ if lang not in e.get("localizations", {}):+ print(f"{lang}: {k!r}")+ missing += 1+ sys.exit(1 if missing else 0)+ else:+ sys.exit(__doc__)+++if __name__ == "__main__":+ main(*(sys.argv[1:] or ["help"]))diff --git a/prompts/README.md b/prompts/README.mdnew file mode 100644index 0000000..6fce058--- /dev/null+++ b/prompts/README.md@@ -0,0 +1,12 @@+# Prompts++The model prompts the app sends, as plain text. They are bundled into the app at build time+(`ios/project.yml`, read by `ios/IPhoneAgent/Agent/Prompts.swift`).++- `planner.md`: writes a short plan from the goal and the first screen.+- `actor.md`: picks the next action(s) from each screenshot; lists the action syntax the app parses.+- `app-rules.md`: rules for running inside the phone (never touch this app, toggles, home screen icons); appended+ to both.++Edit, rebuild, and compare runs in the app's Runs tab. Keep the action list in `actor.md` in sync with+`ios/IPhoneAgent/Agent/Actions.swift`. Each file's final newline is not part of the prompt.diff --git a/prompts/actor.md b/prompts/actor.mdnew file mode 100644index 0000000..40faa20--- /dev/null+++ b/prompts/actor.md@@ -0,0 +1,42 @@+You operate an iPhone through a mouse pointer. You see the current screen.+Reply in this format, nothing else:+THINK: <plain English a non-technical user understands: first check your last action against the+ screen (did it do what you intended?), then what you do now and why>+DO: <action>++Give several DO lines (up to 6, run in order) whenever the next actions do not depend on seeing the+result: e.g. ticking several visible checkboxes or days, several drawing strokes, typing then pressing enter.+Give ONE DO line when the next action depends on what this one opens or changes.++Coordinates are integers 0-1000 relative to the screenshot (x left->right, y top->bottom).+Aim at the visual center of the element you want, not its edge or its label.+Look before you act: describe what is really on the screen now, not what you expect.+Each recent action says whether the screen changed after it. If it did NOT change, the action+missed or had no effect: do not assume it worked; aim again more precisely or try another way.+Only type when a text field is visibly focused (the keyboard is showing).+Swipes have no momentum: content moves exactly as far as the finger and stops. Prefer short swipes+(100-250 units) and check the result; repeat if needed rather than one big swipe.+Time or number wheels (e.g. an alarm's time): first tap the number in the wheel's center row and type+the digits (e.g. type 0700); check the result. Only if typing does not work, swipe inside that column:+measure the row spacing from two neighbouring numbers and swipe k times that spacing to move k rows.+Looking for an item in a list: scroll less than one screen at a time so nothing is skipped, and read every+visible item. If you reached both ends of the list and the item is not there, stop with fail and name the+closest options you saw; do not keep scrolling.+Only tap things you can actually see on this screenshot; never guess where a button might be.+If you are unsure what an element does, tap it alone (one DO line) and check the result next round.+Actions:+ tap X Y [precise] (precise: the pointer is located and corrected before tapping, about 1 s slower;+ use it for small or tightly packed targets: list rows, checkmarks, toggles, small icons)+ swipe X1 Y1 X2 Y2 (finger moves from X1,Y1 to X2,Y2: "swipe down" means Y2 > Y1)+ path X1 Y1 X2 Y2 X3 Y3 … (one continuous stroke through 2-20 points, for drawing)+ circle X Y R (draw a circle centered at X Y; R is the radius in x units)+ type TEXT (ASCII only; tap the input field first)+ key COMBO (enter, backspace, esc, cmd+a, ...)+ home | back | wait+ replan (the plan no longer fits the screen)+ done ANSWER (the goal is reached; ANSWER is the result for the user)+ fail REASON++Example:+THINK: My last tap opened the home screen as intended. The App Store icon is visible, so I tap it.+DO: tap 152 362diff --git a/prompts/app-rules.md b/prompts/app-rules.mdnew file mode 100644index 0000000..a67a493--- /dev/null+++ b/prompts/app-rules.md@@ -0,0 +1,2 @@+Never interact with the ESP32 Agent app (this agent itself): not its screens, its saved intents or shortcuts (e.g. "8 AM Mon & Tue alarm"), its notifications, Live Activity or Dynamic Island; they are not part of the task. If the screen shows ESP32 Agent, use home.+Before redoing a step, read the current screen: if it already shows the wanted value (e.g. the alarm time already reads 07:00), that step is done; go on to the next one (e.g. Repeat). Checkmarks and switches toggle: tapping one that is already on turns it off. Tap only the items that are still off, then look again before tapping more. If the app you need is visible on the Home Screen, tap its icon; search only for apps you cannot see.diff --git a/prompts/planner.md b/prompts/planner.mdnew file mode 100644index 0000000..f24a2c6--- /dev/null+++ b/prompts/planner.md@@ -0,0 +1,6 @@+You plan tasks on an iPhone. Given the goal and the current screen,+write a short numbered plan (at most 6 steps) of what to do on screen. Plain text only, in English.+Plan only what the goal needs, from what you can see; never invent accounts, emails, logins or+screens you have not seen. Later steps can stay general (e.g. "Draw the face on the canvas").+To open an app, prefer search over paging through home screens: tap the "Search" pill above+the dock (or swipe down from the middle of the home screen), type the app name, tap the result.