Skip to content

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.

Show model timings and recover timeouts with visible Island status

Henry7c7b656e0238
diff --git a/docs/run-feedback-2026-10-16.md b/docs/run-feedback-2026-10-16.md
new file mode 100644
index 0000000..052857c
--- /dev/null
+++ b/docs/run-feedback-2026-10-16.md
@@ -0,0 +1,24 @@
+# Model timing, timeout recovery, and Dynamic Island feedback
+
+Source HEAD: e8e811049760d7d607105b8e8526b618ba8a9bf6. Source had only untracked ios/fastlane/, left untouched. Work isolated in codex/run-feedback with separate build output.
+
+## Observed failure
+
+Phone logs show a planner request at 10:42:32 China time, HTTP 200 SSE headers after 2.8 seconds, then a timeout at 90.1 seconds (the configured resource deadline). No completed reply was recorded. This establishes a request completion timeout, not an authentication failure; it does not establish whether the provider was still reasoning or stalled. The initial planner call previously bypassed the actor loop's error recovery and ended the run immediately. Separate BLE connection timeouts occurred after 10:46; this change does not fix the radio link.
+
+## Changes
+
+- Show time to response headers, first answer token and total request time in both model setup screens, plus elapsed time while testing. Clearly label these as including network and model processing. Reset timing when configuration changes; failed tests retain total elapsed time.
+- Retry each timed-out model query at most once within that query, rechecking the foreground gate and current screen first. Existing actor-loop recovery remains bounded separately. No gestures are retried by this path. Cancellation is not retried, and the 90-second resource deadline remains in place.
+- Replace raw NSError dumps at the end of a failed planner call with an actionable timeout message.
+- Keep a Retrying status throughout the second request. Add waiting elapsed time in the expanded Island using a system-rendered timer.
+- Minimal Island previously rendered only a face. It now includes a short status underneath; compact/expanded presentations retain detailed status text. Multiple active activities (including screen mirroring in the reported screenshot) can force minimal presentation; the camera region cannot be treated as app content.
+- Swipe gaze now follows the displacement vector, not the endpoint's location relative to the screen center. Directional text accompanies the gaze in compact/expanded layouts. Eye animation respects Reduce Motion. The existing app-driven gaze changes are subject to iOS scheduling, not a guaranteed continuous widget animation.
+
+Apple reference: https://developer.apple.com/documentation/activitykit/displaying-live-data-with-live-activities
+
+## Validation
+
+77 simulator tests passed, including planner timeout recovery, bounded retry, repeat gate checks, and swipe direction. Signed device build succeeded and was installed on com.onehumanbeing.esp32agent. On-device sample-image test at 10:53 passed with Red: HTTP headers 1.3 seconds, first answer token 6.8 seconds, total 6.822 seconds. Key remained on the phone.
+
+The original long Notes task was not replayed; intermittent upstream timeouts remain possible. The updated two-activity Island layout and animation have not been visually verified on hardware. No claim of a full task completion or a radio-link fix is made.
diff --git a/ios/AgentActivity/AgentActivityWidget.swift b/ios/AgentActivity/AgentActivityWidget.swift
index 6c19748..6db274c 100644
--- a/ios/AgentActivity/AgentActivityWidget.swift
+++ b/ios/AgentActivity/AgentActivityWidget.swift
@@ -37,6 +37,10 @@ struct AgentLiveActivity: Widget {
DynamicIslandExpandedRegion(.bottom) {
VStack(alignment: .leading, spacing: 8) {
Says(state: s, full: true).font(.subheadline.weight(.semibold))
+ if let since = s.waitingSince, !s.finished {
+ Text(since, style: .timer).monospacedDigit().font(.footnote)
+ .accessibilityLabel("Waiting time")
+ }
if s.line != s.labelFull {
Text(verbatim: s.line).font(.footnote).foregroundStyle(.secondary).lineLimit(2)
}
@@ -56,13 +60,19 @@ struct AgentLiveActivity: Widget {
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)
+ Says(state: s, full: false).font(.caption.bold()).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)
+ VStack(spacing: 0) {
+ Eyes(state: s).frame(width: 16, height: 16)
+ Text(s.mood == .thinking ? "Think" : s.mood == .acting ? "Act" : s.finished ? "End" : "Wait")
+ .font(.caption2).foregroundStyle(.white).lineLimit(1)
+ }
+ .frame(width: 36)
+ .accessibilityLabel(Text(verbatim: s.labelFull))
}
}
.widgetURL(AgentActivityAttributes.url(run: context.attributes.runID))
@@ -113,10 +123,11 @@ private struct Buttons: View {
/// 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 {
+ @Environment(\.accessibilityReduceMotion) private var reduceMotion
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)
+ .animation(reduceMotion ? nil : .spring(response: 0.3, dampingFraction: 0.65), value: state.look)
}
}
diff --git a/ios/AgentActivity/Localizable.xcstrings b/ios/AgentActivity/Localizable.xcstrings
index d554827..167ed6c 100644
--- a/ios/AgentActivity/Localizable.xcstrings
+++ b/ios/AgentActivity/Localizable.xcstrings
@@ -446,6 +446,176 @@
}
}
}
+ },
+ "Waiting for the model…" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在等待模型…"
+ }
+ }
+ }
+ },
+ "Total request time" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "请求总耗时"
+ }
+ }
+ }
+ },
+ "Server response" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "服务端响应"
+ }
+ }
+ }
+ },
+ "First answer token" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "首个答案 token"
+ }
+ }
+ }
+ },
+ "Includes network and model processing time." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "包含网络传输和模型处理时间。"
+ }
+ }
+ }
+ },
+ "The model request timed out before it finished. Try again or choose a specific vision model instead of automatic routing." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "模型请求尚未完成便已超时。请重试,或选择具体的视觉模型而非自动路由。"
+ }
+ }
+ }
+ },
+ "Retrying…" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在重试…"
+ }
+ }
+ }
+ },
+ "The model timed out. Trying once more…" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "模型超时了,正在再试一次…"
+ }
+ }
+ }
+ },
+ "Swiping right" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "向右滑动"
+ }
+ }
+ }
+ },
+ "Swiping left" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "向左滑动"
+ }
+ }
+ }
+ },
+ "Swiping down" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "向下滑动"
+ }
+ }
+ }
+ },
+ "Swiping up" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "向上滑动"
+ }
+ }
+ }
+ },
+ "Think" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "思考"
+ }
+ }
+ }
+ },
+ "Act" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "操作"
+ }
+ }
+ }
+ },
+ "End" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "结束"
+ }
+ }
+ }
+ },
+ "Wait" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "等待"
+ }
+ }
+ }
+ },
+ "Waiting time" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "等待时长"
+ }
+ }
+ }
}
},
"version" : "1.0"
diff --git a/ios/IPhoneAgent.xcodeproj/project.pbxproj b/ios/IPhoneAgent.xcodeproj/project.pbxproj
index 6deb8a8..a4c7f90 100644
--- a/ios/IPhoneAgent.xcodeproj/project.pbxproj
+++ b/ios/IPhoneAgent.xcodeproj/project.pbxproj
@@ -97,6 +97,7 @@
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 */; };
+ E663D7886455DD700AF2469A /* ModelTestTimingView.swift in Sources */ = {isa = PBXBuildFile; fileRef = EDF50CDAB7D18F16B8D2299C /* ModelTestTimingView.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 */; };
@@ -106,6 +107,7 @@
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 */; };
+ FC0BD528A254726D869FDF5B /* ModelRequestFailure.swift in Sources */ = {isa = PBXBuildFile; fileRef = 96A8E3AF04195B586F10EDC4 /* ModelRequestFailure.swift */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -199,6 +201,7 @@
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>"; };
+ 96A8E3AF04195B586F10EDC4 /* ModelRequestFailure.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelRequestFailure.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; };
@@ -237,6 +240,7 @@
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>"; };
+ EDF50CDAB7D18F16B8D2299C /* ModelTestTimingView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelTestTimingView.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>"; };
@@ -336,6 +340,7 @@
24E3598C8B1D1025A419CE5D /* ModelPicker.swift */,
C2BE9FDCCB259EC7A7E259E4 /* ModelSelectionView.swift */,
3B94481DB51BD93A2900698F /* ModelSettingsView.swift */,
+ EDF50CDAB7D18F16B8D2299C /* ModelTestTimingView.swift */,
D17A722B1C48BF8FBF8B4222 /* OnboardingDemos.swift */,
22464AAA35416D0351B8063C /* OnboardingPages.swift */,
99381FBF82EA7EB76556866E /* OnboardingView.swift */,
@@ -414,6 +419,7 @@
B9719A5EC1DD7C5033CC8DF5 /* Metrics.swift */,
DAEFE87504F77098EF0AEFFC /* ModelConnectionCheck.swift */,
D8A02583BE955659071F3172 /* ModelProvider.swift */,
+ 96A8E3AF04195B586F10EDC4 /* ModelRequestFailure.swift */,
05DA6345A40715C8BD2AED6C /* Notifier.swift */,
541D1A2837E5F270700EAF55 /* Redactor.swift */,
B1B84B4F1C81E697ACB30630 /* RunShare.swift */,
@@ -665,8 +671,10 @@
1032BD2A5C93F44527463EC7 /* ModelConnectionCheck.swift in Sources */,
2CF0D6C8101BF02E0EDF44E2 /* ModelPicker.swift in Sources */,
A5A78F1B4D15D843B8932932 /* ModelProvider.swift in Sources */,
+ FC0BD528A254726D869FDF5B /* ModelRequestFailure.swift in Sources */,
38112BBE7634E2E538DBA9D0 /* ModelSelectionView.swift in Sources */,
7F412478410DC75BC26A0D5C /* ModelSettingsView.swift in Sources */,
+ E663D7886455DD700AF2469A /* ModelTestTimingView.swift in Sources */,
4CA70811574C401EB0012355 /* Notifier.swift in Sources */,
CFDC07BA9E09D3446164B1B9 /* OnboardingDemos.swift in Sources */,
189667BD260B5751915C28AF /* OnboardingPages.swift in Sources */,
diff --git a/ios/IPhoneAgent/Agent/AgentLoop.swift b/ios/IPhoneAgent/Agent/AgentLoop.swift
index e9b1064..13ef0eb 100644
--- a/ios/IPhoneAgent/Agent/AgentLoop.swift
+++ b/ios/IPhoneAgent/Agent/AgentLoop.swift
@@ -58,7 +58,7 @@ extension Pointer: Gestures {}
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) }
+ enum Doing { case looking, thinking, retrying, 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.
@@ -135,7 +135,7 @@ extension Pointer: Gestures {}
}
private func ask(_ role: String, _ llm: ChatModel, _ system: String, _ prompt: String,
- temperature: Double = 0) async throws -> (String, Double, Data?) {
+ temperature: Double = 0, retryTimeout: Bool = true) async throws -> (String, Double, Data?) {
try await gate?()
var prompt = prompt
if let lost = try await waitForScreen() {
@@ -145,9 +145,19 @@ extension Pointer: Gestures {}
}
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)
+ onDoing?(retryTimeout ? .thinking : .retrying)
+ let reply: ChatResult
+ do {
+ reply = try await llm.chat(system: system, text: prompt, image: frame,
+ maxTokens: Self.maxTokens[role] ?? 1000, temperature: temperature)
+ } catch {
+ guard retryTimeout, ModelRequestFailure.isTimeout(error), !Task.isCancelled else { throw error }
+ DebugLog.write("model request timed out (\(role)); retrying once with a fresh screen")
+ onDoing?(.retrying)
+ try await Task.sleep(for: .seconds(2))
+ // Re-enter the gate and screen checks before retrying; no gesture is repeated.
+ return try await ask(role, llm, system, prompt, temperature: temperature, retryTimeout: false)
+ }
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),
@@ -191,7 +201,7 @@ extension Pointer: Gestures {}
} 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))])
+ record(nil, ["action": .str("error"), "reason": .str(ModelRequestFailure.message(error))])
}
finish()
}
diff --git a/ios/IPhoneAgent/App/AppModel.swift b/ios/IPhoneAgent/App/AppModel.swift
index 58a6ef3..7759418 100644
--- a/ios/IPhoneAgent/App/AppModel.swift
+++ b/ios/IPhoneAgent/App/AppModel.swift
@@ -26,6 +26,10 @@ import UIKit
let agent: AgentLoop
@Published private(set) var log: [LogLine] = []
@Published var modelError: String?
+ @Published var modelTestStarted: Date?
+ @Published var modelTestSeconds: Double?
+ @Published var modelFirstTokenSeconds: Double?
+ @Published var modelResponseSeconds: Double?
@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
@@ -92,6 +96,9 @@ import UIKit
settingsSink = settings.$configurationRevision.dropFirst().sink { [weak self] _ in
self?.modelOK = nil
self?.modelError = nil
+ self?.modelTestSeconds = nil
+ self?.modelFirstTokenSeconds = nil
+ self?.modelResponseSeconds = nil
}
board.onVideo = { [weak self] in self?.feed.receive($0) }
board.onStatus = { [weak self] s in
@@ -231,6 +238,7 @@ import UIKit
}
func pingLLM() async {
+ guard modelTestStarted == nil else { return }
if MockMode.on {
try? await Task.sleep(nanoseconds: 900_000_000)
modelOK = true
@@ -239,6 +247,15 @@ import UIKit
let started = now()
let revision = settings.configurationRevision
modelError = nil
+ modelOK = nil
+ modelTestSeconds = nil
+ modelFirstTokenSeconds = nil
+ modelResponseSeconds = nil
+ modelTestStarted = Date()
+ defer {
+ modelTestStarted = nil
+ if revision == settings.configurationRevision { modelTestSeconds = now() - started }
+ }
do {
let client = try await settings.client("actor")
let image = UIGraphicsImageRenderer(size: CGSize(width: 64, height: 64)).image { context in
@@ -248,6 +265,8 @@ import UIKit
let r = try await client.chat(system: "Name the dominant color in the image. Reply with one English word.",
text: "What color is this image?", image: image, maxTokens: 600, temperature: 0)
guard revision == settings.configurationRevision else { return }
+ modelFirstTokenSeconds = r.firstToken
+ modelResponseSeconds = r.responseSeconds
try ModelConnectionCheck.validate(r)
metrics.llmPingMs = (now() - started) * 1000
metrics.llm(first: r.firstToken, total: r.total)
@@ -256,7 +275,7 @@ import UIKit
} catch {
guard revision == settings.configurationRevision else { return }
modelOK = false
- modelError = error.localizedDescription
+ modelError = ModelRequestFailure.message(error)
say("LLM: \(error.localizedDescription)")
}
}
diff --git a/ios/IPhoneAgent/App/IslandStatus.swift b/ios/IPhoneAgent/App/IslandStatus.swift
index 801e7e2..dba3d80 100644
--- a/ios/IPhoneAgent/App/IslandStatus.swift
+++ b/ios/IPhoneAgent/App/IslandStatus.swift
@@ -21,6 +21,10 @@ struct IslandStatus: Equatable {
Self(short: String(localized: "Thinking…"), full: String(localized: "Thinking…"), look: nil)
}
+ static var retrying: Self {
+ Self(short: String(localized: "Retrying…"), full: String(localized: "The model timed out. Trying once more…"), look: nil)
+ }
+
static var help: Self {
Self(short: String(localized: "Need help"), full: String(localized: "Need your help"), look: .zero)
}
@@ -54,7 +58,13 @@ struct IslandStatus: Equatable {
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)
+ let label: String
+ if abs(look.x) > abs(look.y) {
+ label = look.x > 0 ? String(localized: "Swiping right") : String(localized: "Swiping left")
+ } else {
+ label = look.y > 0 ? String(localized: "Swiping down") : String(localized: "Swiping up")
+ }
+ return Self(short: label, full: label, look: look)
case "path", "circle":
return Self(short: String(localized: "Drawing…"), full: String(localized: "Drawing…"), look: look)
case "home":
@@ -69,6 +79,12 @@ struct IslandStatus: Equatable {
/// 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) }
+ if act["action"]?.str == "swipe" {
+ let dx = (act["x2"]?.double ?? 0) - (act["x1"]?.double ?? 0)
+ let dy = (act["y2"]?.double ?? 0) - (act["y1"]?.double ?? 0)
+ let magnitude = max(abs(dx), abs(dy), 1)
+ return CGPoint(x: dx / magnitude, y: dy / magnitude)
+ }
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))
diff --git a/ios/IPhoneAgent/App/LiveActivity.swift b/ios/IPhoneAgent/App/LiveActivity.swift
index 5eb422c..093b55e 100644
--- a/ios/IPhoneAgent/App/LiveActivity.swift
+++ b/ios/IPhoneAgent/App/LiveActivity.swift
@@ -75,6 +75,7 @@ import Foundation
if state.phase != .recording { apply(.ended(outcome.mood), to: &state) }
}
state.finished = true
+ state.waitingSince = nil
DebugLog.write("Live Activity: ended" + (outcome.map { " (\($0.mood.rawValue))" } ?? ""))
self.activity = nil
last = nil
@@ -88,6 +89,9 @@ import Foundation
// MARK: - status and eyes
private func apply(_ status: IslandStatus, to state: inout State) {
+ if status.waits {
+ if state.label != status.short || state.waitingSince == nil { state.waitingSince = Date() }
+ } else { state.waitingSince = nil }
state.label = status.short
state.labelFull = status.full
if let look = status.look {
diff --git a/ios/IPhoneAgent/App/RunSession.swift b/ios/IPhoneAgent/App/RunSession.swift
index f57fe85..1639a69 100644
--- a/ios/IPhoneAgent/App/RunSession.swift
+++ b/ios/IPhoneAgent/App/RunSession.swift
@@ -138,6 +138,7 @@ extension AppModel {
switch d {
case .looking: live.show(.looking, mood: .thinking)
case .thinking: live.show(.thinking, mood: .thinking)
+ case .retrying: live.show(.retrying, mood: .thinking)
case .acting(let act): live.show(.acting(act), mood: .acting)
}
}
diff --git a/ios/IPhoneAgent/Localizable.xcstrings b/ios/IPhoneAgent/Localizable.xcstrings
index 14eb306..c205e7c 100644
--- a/ios/IPhoneAgent/Localizable.xcstrings
+++ b/ios/IPhoneAgent/Localizable.xcstrings
@@ -5187,6 +5187,166 @@
}
}
}
+ },
+ "Waiting for the model…" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在等待模型…"
+ }
+ }
+ }
+ },
+ "Total request time" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "请求总耗时"
+ }
+ }
+ }
+ },
+ "Server response" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "服务端响应"
+ }
+ }
+ }
+ },
+ "First answer token" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "首个答案 token"
+ }
+ }
+ }
+ },
+ "Includes network and model processing time." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "包含网络传输和模型处理时间。"
+ }
+ }
+ }
+ },
+ "The model request timed out before it finished. Try again or choose a specific vision model instead of automatic routing." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "模型请求尚未完成便已超时。请重试,或选择具体的视觉模型而非自动路由。"
+ }
+ }
+ }
+ },
+ "Retrying…" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在重试…"
+ }
+ }
+ }
+ },
+ "The model timed out. Trying once more…" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "模型超时了,正在再试一次…"
+ }
+ }
+ }
+ },
+ "Swiping right" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "向右滑动"
+ }
+ }
+ }
+ },
+ "Swiping left" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "向左滑动"
+ }
+ }
+ }
+ },
+ "Swiping down" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "向下滑动"
+ }
+ }
+ }
+ },
+ "Swiping up" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "向上滑动"
+ }
+ }
+ }
+ },
+ "Think" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "思考"
+ }
+ }
+ }
+ },
+ "Act" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "操作"
+ }
+ }
+ }
+ },
+ "End" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "结束"
+ }
+ }
+ }
+ },
+ "Waiting time" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "等待时长"
+ }
+ }
+ }
}
},
"version" : "1.0"
diff --git a/ios/IPhoneAgent/Services/LLMClient.swift b/ios/IPhoneAgent/Services/LLMClient.swift
index c403a1f..70dc4a7 100644
--- a/ios/IPhoneAgent/Services/LLMClient.swift
+++ b/ios/IPhoneAgent/Services/LLMClient.swift
@@ -8,6 +8,7 @@ struct ChatResult {
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 responseSeconds: Double? // time to HTTP headers, including server queue time
var retried = false // the first reply was empty
/// For the trace and the debug log: why a reply came back empty or cut.
@@ -158,6 +159,7 @@ struct LLMError: LocalizedError {
request.httpBody = try JSONSerialization.data(withJSONObject: body)
let (bytes, response) = try await session.bytes(for: request)
+ let responseSeconds = now() - started
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))
@@ -169,9 +171,12 @@ struct LLMError: LocalizedError {
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 = try Self.message(raw)
+ result.responseSeconds = responseSeconds
+ return (status, result, "")
}
var result = ChatResult(text: "", firstToken: nil, total: 0)
+ result.responseSeconds = responseSeconds
for try await line in bytes.lines {
guard line.hasPrefix("data:") else { continue }
let payload = line.dropFirst(5).trimmingCharacters(in: .whitespaces)
diff --git a/ios/IPhoneAgent/Services/ModelRequestFailure.swift b/ios/IPhoneAgent/Services/ModelRequestFailure.swift
new file mode 100644
index 0000000..0a57522
--- /dev/null
+++ b/ios/IPhoneAgent/Services/ModelRequestFailure.swift
@@ -0,0 +1,14 @@
+import Foundation
+
+enum ModelRequestFailure {
+ static func isTimeout(_ error: Error) -> Bool {
+ (error as? URLError)?.code == .timedOut
+ }
+
+ static func message(_ error: Error) -> String {
+ if isTimeout(error) {
+ return String(localized: "The model request timed out before it finished. Try again or choose a specific vision model instead of automatic routing.")
+ }
+ return error.localizedDescription
+ }
+}
diff --git a/ios/IPhoneAgent/UI/ModelSettingsView.swift b/ios/IPhoneAgent/UI/ModelSettingsView.swift
index 6effb8f..815c823 100644
--- a/ios/IPhoneAgent/UI/ModelSettingsView.swift
+++ b/ios/IPhoneAgent/UI/ModelSettingsView.swift
@@ -31,6 +31,7 @@ struct ModelSettingsView: View {
}
}
.disabled(testing || !app.modelReady)
+ ModelTestTimingView(app: app)
if let error = app.modelError {
Text(verbatim: error).font(.footnote).foregroundStyle(Palette.stop)
}
diff --git a/ios/IPhoneAgent/UI/ModelTestTimingView.swift b/ios/IPhoneAgent/UI/ModelTestTimingView.swift
new file mode 100644
index 0000000..5d656c2
--- /dev/null
+++ b/ios/IPhoneAgent/UI/ModelTestTimingView.swift
@@ -0,0 +1,31 @@
+import SwiftUI
+
+struct ModelTestTimingView: View {
+ @ObservedObject var app: AppModel
+
+ var body: some View {
+ VStack(alignment: .leading, spacing: Space.xs) {
+ if let started = app.modelTestStarted {
+ HStack {
+ ProgressView()
+ Text("Waiting for the model…")
+ Text(started, style: .timer).monospacedDigit()
+ }
+ } else if let total = app.modelTestSeconds {
+ LabeledContent("Total request time", value: seconds(total))
+ if let response = app.modelResponseSeconds {
+ LabeledContent("Server response", value: seconds(response))
+ }
+ if let first = app.modelFirstTokenSeconds {
+ LabeledContent("First answer token", value: seconds(first))
+ }
+ Text("Includes network and model processing time.")
+ }
+ }
+ .font(.footnote).foregroundStyle(.secondary)
+ }
+
+ private func seconds(_ value: Double) -> String {
+ value.formatted(.number.precision(.fractionLength(2))) + " s"
+ }
+}
diff --git a/ios/IPhoneAgent/UI/OnboardingPages.swift b/ios/IPhoneAgent/UI/OnboardingPages.swift
index 77e92da..39657cf 100644
--- a/ios/IPhoneAgent/UI/OnboardingPages.swift
+++ b/ios/IPhoneAgent/UI/OnboardingPages.swift
@@ -246,6 +246,7 @@ struct BrainPage: View {
} else {
ModelFieldsPanel(settings: settings)
}
+ ModelTestTimingView(app: app)
switch app.modelOK {
case true?:
Panel {
diff --git a/ios/IPhoneAgentTests/AgentTests.swift b/ios/IPhoneAgentTests/AgentTests.swift
index 0c024a9..fa85191 100644
--- a/ios/IPhoneAgentTests/AgentTests.swift
+++ b/ios/IPhoneAgentTests/AgentTests.swift
@@ -3,6 +3,29 @@ import XCTest
/// Port of server/tests/test_agent.py.
@MainActor final class AgentTests: XCTestCase {
+ func testPlannerTimeoutRetriesOnceAndChecksGateAgain() async throws {
+ let model = TimeoutModel(failures: 1)
+ let agent = AgentLoop(phone: nil, screen: FakeScreen(), actor: model, planner: model, trace: nil)
+ var gates = 0
+ var retryShown = false
+ agent.gate = { gates += 1 }
+ agent.onDoing = { if case .retrying = $0 { retryShown = true } }
+ try await agent.replan()
+ XCTAssertEqual(model.calls, 2)
+ XCTAssertEqual(gates, 2)
+ XCTAssertTrue(retryShown)
+ XCTAssertEqual(agent.plan, "1. Observe the screen")
+ }
+
+ func testPlannerTimeoutStopsAfterOneRetry() async {
+ let model = TimeoutModel(failures: 10)
+ let agent = AgentLoop(phone: nil, screen: FakeScreen(), actor: model, planner: model, trace: nil)
+ do { try await agent.replan(); XCTFail("Expected timeout") }
+ catch { XCTAssertTrue(ModelRequestFailure.isTimeout(error)) }
+ XCTAssertEqual(model.calls, 2)
+ XCTAssertTrue(agent.steps.isEmpty)
+ }
+
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(""),
@@ -171,3 +194,15 @@ import XCTest
func goBack() async throws { calls.append("back") }
func reset() async throws { calls.append("reset") }
}
+
+@MainActor private final class TimeoutModel: ChatModel {
+ let model = "timeout-test"
+ let failures: Int
+ var calls = 0
+ init(failures: Int) { self.failures = failures }
+ func chat(system: String, text: String, image: Data?, maxTokens: Int, temperature: Double) async throws -> ChatResult {
+ calls += 1
+ if calls <= failures { throw URLError(.timedOut) }
+ return ChatResult(text: "1. Observe the screen", total: 0)
+ }
+}
diff --git a/ios/IPhoneAgentTests/IslandTests.swift b/ios/IPhoneAgentTests/IslandTests.swift
index 4988e38..93cb7b1 100644
--- a/ios/IPhoneAgentTests/IslandTests.swift
+++ b/ios/IPhoneAgentTests/IslandTests.swift
@@ -3,6 +3,15 @@ import XCTest
/// What the character says in the Dynamic Island, and where its eyes go.
@MainActor final class IslandTests: XCTestCase {
+ func testSwipeGazeUsesDirectionRatherThanScreenPosition() {
+ let right: JObject = ["action": .str("swipe"), "x1": .int(100), "x2": .int(200), "y1": .int(200), "y2": .int(200)]
+ XCTAssertEqual(IslandStatus.acting(right).short, "Swiping right")
+ XCTAssertEqual(IslandStatus.gaze(right), CGPoint(x: 1, y: 0))
+ let up: JObject = ["action": .str("swipe"), "x1": .int(800), "x2": .int(800), "y1": .int(900), "y2": .int(700)]
+ XCTAssertEqual(IslandStatus.acting(up).short, "Swiping up")
+ XCTAssertEqual(IslandStatus.gaze(up), CGPoint(x: 0, y: -1))
+ }
+
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."), "+")
diff --git a/ios/Shared/AgentActivity.swift b/ios/Shared/AgentActivity.swift
index 7a6ee66..37b2e3c 100644
--- a/ios/Shared/AgentActivity.swift
+++ b/ios/Shared/AgentActivity.swift
@@ -17,6 +17,7 @@ struct AgentActivityAttributes: ActivityAttributes {
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 waitingSince: Date? // system-rendered elapsed timer, even between app updates
var lookX = 0.0 // where the eyes look, -1...1 (darting while it waits, toward the pointer's target)
var lookY = 0.0