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.

Clarify OpenRouter checks and add searchable model selection

Henryacc3a24e4b93
diff --git a/docs/openrouter-model-selection-2026-10-16.md b/docs/openrouter-model-selection-2026-10-16.md
new file mode 100644
index 0000000..b8473a2
--- /dev/null
+++ b/docs/openrouter-model-selection-2026-10-16.md
@@ -0,0 +1,33 @@
+# OpenRouter setup and model selection — 2026-10-16
+
+Source: local checkout at `70857e503ca2ade9376ca8360335d663a11810a3`.
+Existing uncommitted content: untracked `ios/fastlane/`, left untouched.
+Implementation isolated in branch `codex/openrouter-model-selection`, with separate build output; no live databases or processes copied.
+
+## Findings
+
+The active phone app (`com.onehumanbeing.esp32agent`) logged HTTP 200 for the 10:02 image check, with 17 response characters and a normal stop. The response text was not logged, so its exact contents and reason for failing the color check are unknown. At 10:08 it returned `Red` successfully in 2.23 seconds using the same router. This does not establish an API-key or networking failure.
+
+`openrouter/free` is a valid API model ID for automatic free-model routing, not an individual model. OpenRouter documents capability-aware routing, including images: https://github.com/OpenRouterTeam/docs/blob/main/guides/routing/routers/free-router.mdx
+
+## Changes
+
+- Consolidate the duplicate Free provider into OpenRouter, preserving the saved endpoint, key and `openrouter/free` selection.
+- Replace long menus in setup and advanced overrides with a shared searchable list, checkmarks, refresh, and a custom-ID disclosure at the top.
+- Separate `openrouter/free` and `openrouter/auto` into an automatic routing section with explicit labels and explanatory text.
+- Report inconclusive image checks and empty responses accurately, rather than asserting that image input is unsupported. Include a bounded answer excerpt on mismatch. Do not accept substrings such as `infrared` or negated answers.
+- Surface provider errors embedded in HTTP 200 JSON/SSE responses instead of treating them as empty completions.
+- Add a DEBUG-only `-test-model` launch argument for testing the phone's existing configuration without extracting its key.
+- Add Simplified Chinese translations for new copy.
+
+## Validation
+
+- 74 iOS unit tests passed, including legacy-provider migration, image-check validation, and streamed provider errors.
+- Final signed device build succeeded.
+- Simulator layout inspected with the live public OpenRouter model catalog. A temporary presentation override opened the sheet for inspection; it was removed before the final device build. Search typing and large Dynamic Type interactions were not manually exercised.
+- Updated the active phone app. A fresh test launch was blocked by the phone's lock screen; post-update live inference remains pending unlock. The 10:08 success above predates this update.
+- No API key was read, exported, or included in source.
+
+## Design convention
+
+Installed `swiftui-pro` from https://github.com/twostraws/SwiftUI-Agent-Skill and recorded Henry's default SwiftUI convention in `~/.codex/design-principles.md`. Existing iOS deployment target retained.
diff --git a/ios/IPhoneAgent.xcodeproj/project.pbxproj b/ios/IPhoneAgent.xcodeproj/project.pbxproj
index a2da39a..019cfd3 100644
--- a/ios/IPhoneAgent.xcodeproj/project.pbxproj
+++ b/ios/IPhoneAgent.xcodeproj/project.pbxproj
@@ -13,6 +13,7 @@
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 */; };
+ 1032BD2A5C93F44527463EC7 /* ModelConnectionCheck.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAEFE87504F77098EF0AEFFC /* ModelConnectionCheck.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 */; };
@@ -25,8 +26,10 @@
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 */; };
+ 2CF0D6C8101BF02E0EDF44E2 /* ModelPicker.swift in Sources */ = {isa = PBXBuildFile; fileRef = 24E3598C8B1D1025A419CE5D /* ModelPicker.swift */; };
2CF6A30C3D72E05EEBC6FFED /* IslandTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = A54BC007EE5C64A13CDEE9EE /* IslandTests.swift */; };
3607786AAF7296B3414B6F08 /* VisionTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1887982FE1A729487269296E /* VisionTests.swift */; };
+ 38112BBE7634E2E538DBA9D0 /* ModelSelectionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C2BE9FDCCB259EC7A7E259E4 /* ModelSelectionView.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 */; };
@@ -153,6 +156,7 @@
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; };
+ 24E3598C8B1D1025A419CE5D /* ModelPicker.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelPicker.swift; sourceTree = "<group>"; };
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>"; };
@@ -210,6 +214,7 @@
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>"; };
+ C2BE9FDCCB259EC7A7E259E4 /* ModelSelectionView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelSelectionView.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>"; };
@@ -220,6 +225,7 @@
D8A02583BE955659071F3172 /* ModelProvider.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelProvider.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>"; };
+ DAEFE87504F77098EF0AEFFC /* ModelConnectionCheck.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ModelConnectionCheck.swift; 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>"; };
@@ -324,6 +330,8 @@
406D13832E556B804F6F3887 /* HomeParts.swift */,
6DCAEE3FDF94357F8875E473 /* HomeView.swift */,
D222722DF7856F9253B9784E /* IntentDetailView.swift */,
+ 24E3598C8B1D1025A419CE5D /* ModelPicker.swift */,
+ C2BE9FDCCB259EC7A7E259E4 /* ModelSelectionView.swift */,
3B94481DB51BD93A2900698F /* ModelSettingsView.swift */,
D17A722B1C48BF8FBF8B4222 /* OnboardingDemos.swift */,
22464AAA35416D0351B8063C /* OnboardingPages.swift */,
@@ -401,6 +409,7 @@
DCDA925D0FFD42810895573C /* LLMClient.swift */,
4D9FABC284798F9949C1A8EF /* LogUploader.swift */,
B9719A5EC1DD7C5033CC8DF5 /* Metrics.swift */,
+ DAEFE87504F77098EF0AEFFC /* ModelConnectionCheck.swift */,
D8A02583BE955659071F3172 /* ModelProvider.swift */,
05DA6345A40715C8BD2AED6C /* Notifier.swift */,
541D1A2837E5F270700EAF55 /* Redactor.swift */,
@@ -649,7 +658,10 @@
F2FFDB2986493F65EB6A9738 /* LogUploader.swift in Sources */,
7B684FAA8B218BB9798F9EC3 /* Metrics.swift in Sources */,
B356EECAFE045249704E63FD /* MockMode.swift in Sources */,
+ 1032BD2A5C93F44527463EC7 /* ModelConnectionCheck.swift in Sources */,
+ 2CF0D6C8101BF02E0EDF44E2 /* ModelPicker.swift in Sources */,
A5A78F1B4D15D843B8932932 /* ModelProvider.swift in Sources */,
+ 38112BBE7634E2E538DBA9D0 /* ModelSelectionView.swift in Sources */,
7F412478410DC75BC26A0D5C /* ModelSettingsView.swift in Sources */,
4CA70811574C401EB0012355 /* Notifier.swift in Sources */,
CFDC07BA9E09D3446164B1B9 /* OnboardingDemos.swift in Sources */,
diff --git a/ios/IPhoneAgent/App/AppModel.swift b/ios/IPhoneAgent/App/AppModel.swift
index 244b4b0..58a6ef3 100644
--- a/ios/IPhoneAgent/App/AppModel.swift
+++ b/ios/IPhoneAgent/App/AppModel.swift
@@ -248,9 +248,7 @@ 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 }
- guard r.text.lowercased().contains("red") else {
- throw LLMError(message: "The model did not identify the sample image. Choose a model that supports images.")
- }
+ try ModelConnectionCheck.validate(r)
metrics.llmPingMs = (now() - started) * 1000
metrics.llm(first: r.firstToken, total: r.total)
modelOK = true
diff --git a/ios/IPhoneAgent/App/DebugEntry.swift b/ios/IPhoneAgent/App/DebugEntry.swift
index a69bc53..236d75b 100644
--- a/ios/IPhoneAgent/App/DebugEntry.swift
+++ b/ios/IPhoneAgent/App/DebugEntry.swift
@@ -85,6 +85,7 @@ extension AppModel {
#if DEBUG
if let requested = value(after: "-setup"),
let page = ["connect": SetupPage.connect, "brain": .brain][requested] { setupPage = page }
+ if args.contains("-test-model") { Task { await pingLLM() } }
#endif
if let task = value(after: "-run") { debugCommand("run", task: task) }
if args.contains("-calibrate") { debugCommand("calibrate") }
diff --git a/ios/IPhoneAgent/Localizable.xcstrings b/ios/IPhoneAgent/Localizable.xcstrings
index 4721256..14eb306 100644
--- a/ios/IPhoneAgent/Localizable.xcstrings
+++ b/ios/IPhoneAgent/Localizable.xcstrings
@@ -5027,6 +5027,166 @@
},
"••••••••" : {
"shouldTranslate" : false
+ },
+ "Choose a model" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "选择模型"
+ }
+ }
+ }
+ },
+ "Automatic · Free models" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "自动 · 免费模型"
+ }
+ }
+ }
+ },
+ "Automatic · OpenRouter" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "自动 · OpenRouter"
+ }
+ }
+ }
+ },
+ "Automatic routing" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "自动路由"
+ }
+ }
+ }
+ },
+ "OpenRouter chooses a model for each request. Free model availability and responses can vary." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "OpenRouter 会为每次请求选择模型。免费模型的可用性和回复可能有所不同。"
+ }
+ }
+ }
+ },
+ "Models" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "模型"
+ }
+ }
+ }
+ },
+ "Loading models…" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "正在加载模型…"
+ }
+ }
+ }
+ },
+ "No models loaded" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "尚未加载模型"
+ }
+ }
+ }
+ },
+ "Refresh the list or enter a model ID below." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "刷新列表,或在下方输入模型 ID。"
+ }
+ }
+ }
+ },
+ "Custom model" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "自定义模型"
+ }
+ }
+ }
+ },
+ "Use Model ID" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "使用此模型 ID"
+ }
+ }
+ }
+ },
+ "Search models" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "搜索模型"
+ }
+ }
+ }
+ },
+ "Selected" : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "已选择"
+ }
+ }
+ }
+ },
+ "Connected, but the model returned no answer. Try again or choose another vision model." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "连接成功,但模型未返回答案。请重试或选择其他视觉模型。"
+ }
+ }
+ }
+ },
+ "Connected, but the image check was inconclusive. Try again or choose a specific vision model." : {
+ "localizations" : {
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "连接成功,但图片测试未通过。请重试或选择一个具体的视觉模型。"
+ }
+ }
+ }
+ },
+ "Model reply:" : {
+ "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 41ccb34..c403a1f 100644
--- a/ios/IPhoneAgent/Services/LLMClient.swift
+++ b/ios/IPhoneAgent/Services/LLMClient.swift
@@ -177,6 +177,7 @@ struct LLMError: LocalizedError {
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 }
+ try Self.checkError(json)
let choice = (json["choices"] as? [[String: Any]])?.first
let delta = choice?["delta"] as? [String: Any]
Self.note(json, choice, into: &result)
@@ -192,6 +193,7 @@ struct LLMError: LocalizedError {
/// 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]
+ if let json { try Self.checkError(json) }
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))")
@@ -203,6 +205,13 @@ struct LLMError: LocalizedError {
return result
}
+ /// Providers can report errors inside an HTTP 200 stream or JSON response.
+ private static func checkError(_ json: [String: Any]) throws {
+ guard let error = json["error"] else { return }
+ let message = (error as? [String: Any])?["message"] as? String ?? (error as? String) ?? "Provider error"
+ throw LLMError(message: String(message.prefix(300)))
+ }
+
/// 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 }
diff --git a/ios/IPhoneAgent/Services/ModelConnectionCheck.swift b/ios/IPhoneAgent/Services/ModelConnectionCheck.swift
new file mode 100644
index 0000000..04f52fa
--- /dev/null
+++ b/ios/IPhoneAgent/Services/ModelConnectionCheck.swift
@@ -0,0 +1,16 @@
+import Foundation
+
+/// An unsuccessful image check does not imply an authentication or connectivity failure.
+enum ModelConnectionCheck {
+ static func validate(_ reply: ChatResult) throws {
+ let answer = reply.text.trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !answer.isEmpty else {
+ throw LLMError(message: String(localized: "Connected, but the model returned no answer. Try again or choose another vision model."))
+ }
+ let words = answer.lowercased().split { !$0.isLetter }
+ guard words == ["red"] else {
+ throw LLMError(message: String(localized: "Connected, but the image check was inconclusive. Try again or choose a specific vision model.")
+ + "\n" + String(localized: "Model reply:") + " " + String(answer.prefix(160)))
+ }
+ }
+}
diff --git a/ios/IPhoneAgent/Services/ModelProvider.swift b/ios/IPhoneAgent/Services/ModelProvider.swift
index 430aba9..0e77e7b 100644
--- a/ios/IPhoneAgent/Services/ModelProvider.swift
+++ b/ios/IPhoneAgent/Services/ModelProvider.swift
@@ -2,11 +2,10 @@ import Foundation
/// Presets only configure public endpoints. Users always supply their own credentials.
enum ModelProvider: String, CaseIterable, Identifiable {
- case openRouterFree, openAI, gemini, qwen, qwenInternational, deepSeek, openRouter, others
+ case openAI, gemini, qwen, qwenInternational, deepSeek, openRouter, others
var id: String { rawValue }
var title: String {
switch self {
- case .openRouterFree: return "OpenRouter Free"
case .openAI: return "OpenAI"
case .gemini: return "Google Gemini"
case .qwen: return "Qwen · China"
@@ -18,7 +17,7 @@ enum ModelProvider: String, CaseIterable, Identifiable {
}
var baseURL: String {
switch self {
- case .openRouterFree, .openRouter: return "https://openrouter.ai/api/v1"
+ case .openRouter: return "https://openrouter.ai/api/v1"
case .openAI: return "https://api.openai.com/v1"
case .gemini: return "https://generativelanguage.googleapis.com/v1beta/openai"
case .qwen: return "https://dashscope.aliyuncs.com/compatible-mode/v1"
@@ -30,7 +29,7 @@ enum ModelProvider: String, CaseIterable, Identifiable {
var keyURL: URL? {
let address: String
switch self {
- case .openRouterFree, .openRouter: address = "https://openrouter.ai/settings/keys"
+ case .openRouter: address = "https://openrouter.ai/settings/keys"
case .openAI: address = "https://platform.openai.com/api-keys"
case .gemini: address = "https://aistudio.google.com/apikey"
case .qwen: address = "https://bailian.console.aliyun.com/"
@@ -42,7 +41,7 @@ enum ModelProvider: String, CaseIterable, Identifiable {
}
static func infer(baseURL: String, model: String) -> Self {
let base = baseURL.trimmingCharacters(in: CharacterSet(charactersIn: "/"))
- if base == openRouter.baseURL { return model == "openrouter/free" ? .openRouterFree : .openRouter }
+ if base == openRouter.baseURL { return .openRouter }
return allCases.first { $0 != .others && $0.baseURL == base } ?? .others
}
}
diff --git a/ios/IPhoneAgent/Services/Settings.swift b/ios/IPhoneAgent/Services/Settings.swift
index fcfb7f1..fcc4dce 100644
--- a/ios/IPhoneAgent/Services/Settings.swift
+++ b/ios/IPhoneAgent/Services/Settings.swift
@@ -114,7 +114,7 @@ import UIKit
let changedEndpoint = baseURL != choice.baseURL
baseURL = choice.baseURL
if changedEndpoint { apiKey = Keychain.get("llm-endpoint-" + baseURL) ?? "" }
- model = choice == .openRouterFree ? "openrouter/free" : ""
+ model = ""
plannerModel = ""
actorModel = ""
tokenParam = "auto"
diff --git a/ios/IPhoneAgent/UI/ModelPicker.swift b/ios/IPhoneAgent/UI/ModelPicker.swift
new file mode 100644
index 0000000..d25b73f
--- /dev/null
+++ b/ios/IPhoneAgent/UI/ModelPicker.swift
@@ -0,0 +1,32 @@
+import SwiftUI
+
+/// A searchable selection sheet shared by setup and all model overrides.
+struct ModelPicker: View {
+ @ObservedObject var settings: Settings
+ let title: LocalizedStringKey
+ @Binding var selection: String
+ let automatic: String
+ var allowsDefault = true
+ @State private var showingModels = false
+
+ var body: some View {
+ Button { showingModels = true } label: {
+ LabeledContent(title) {
+ HStack {
+ Text(selection.isEmpty ? automatic : ModelSelectionView.displayName(selection))
+ .multilineTextAlignment(.trailing)
+ .lineLimit(2)
+ Image(systemName: "chevron.right").font(.footnote)
+ .accessibilityHidden(true)
+ }
+ .foregroundStyle(.secondary)
+ }
+ .frame(minHeight: 44)
+ .contentShape(.rect)
+ }
+ .buttonStyle(.plain)
+ .sheet(isPresented: $showingModels) {
+ ModelSelectionView(settings: settings, selection: $selection, allowsDefault: allowsDefault)
+ }
+ }
+}
diff --git a/ios/IPhoneAgent/UI/ModelSelectionView.swift b/ios/IPhoneAgent/UI/ModelSelectionView.swift
new file mode 100644
index 0000000..939a3e4
--- /dev/null
+++ b/ios/IPhoneAgent/UI/ModelSelectionView.swift
@@ -0,0 +1,106 @@
+import SwiftUI
+
+struct ModelSelectionView: View {
+ @ObservedObject var settings: Settings
+ @Binding var selection: String
+ let allowsDefault: Bool
+ @Environment(\.dismiss) private var dismiss
+ @State private var search = ""
+ @State private var customID = ""
+
+ static let routers: Set<String> = ["openrouter/free", "openrouter/auto"]
+
+ static func displayName(_ id: String) -> String {
+ switch id {
+ case "openrouter/free": String(localized: "Automatic · Free models")
+ case "openrouter/auto": String(localized: "Automatic · OpenRouter")
+ default: id
+ }
+ }
+
+ private var matches: [String] {
+ let ids = Set(settings.models + (selection.isEmpty ? [] : [selection]))
+ return ids.filter { search.isEmpty || $0.localizedStandardContains(search)
+ || Self.displayName($0).localizedStandardContains(search) }.sorted()
+ }
+
+ var body: some View {
+ let visible = matches
+ NavigationStack {
+ List {
+ if allowsDefault && search.isEmpty {
+ Button("Use Default") { choose("") }
+ }
+ DisclosureGroup("Custom model") {
+ TextField("Model ID", text: $customID)
+ .textInputAutocapitalization(.never).autocorrectionDisabled()
+ Button("Use Model ID") { choose(customID.trimmingCharacters(in: .whitespacesAndNewlines)) }
+ .disabled(customID.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
+ }
+ if !visible.filter({ Self.routers.contains($0) }).isEmpty {
+ Section {
+ ForEach(visible.filter { Self.routers.contains($0) }, id: \.self) { id in row(id) }
+ } header: { Text("Automatic routing") } footer: {
+ Text("OpenRouter chooses a model for each request. Free model availability and responses can vary.")
+ }
+ }
+ Section("Models") {
+ ForEach(visible.filter { !Self.routers.contains($0) }, id: \.self) { id in row(id) }
+ }
+ if settings.loadingModels {
+ ProgressView("Loading models…")
+ } else if visible.isEmpty {
+ if search.isEmpty {
+ ContentUnavailableView("No models loaded", systemImage: "list.bullet",
+ description: Text("Refresh the list or enter a model ID below."))
+ } else { ContentUnavailableView.search(text: search) }
+ }
+ if let error = settings.modelsError {
+ Text(verbatim: error).font(.footnote).foregroundStyle(.secondary)
+ }
+
+ }
+ .searchable(text: $search, prompt: "Search models")
+ .navigationTitle("Choose Model")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
+ ToolbarItem(placement: .primaryAction) {
+ Button("Refresh Models", systemImage: "arrow.clockwise") {
+ Task { await settings.loadModels() }
+ }
+ .disabled(settings.loadingModels || !settings.isConfigured)
+ }
+ }
+ .task {
+ if settings.models.isEmpty && !settings.loadingModels { await settings.loadModels() }
+ }
+ }
+ }
+
+ private func row(_ id: String) -> some View {
+ Button { choose(id) } label: {
+ HStack {
+ VStack(alignment: .leading) {
+ Text(Self.displayName(id)).foregroundStyle(.primary)
+ if Self.routers.contains(id) {
+ Text(verbatim: id).font(.footnote).foregroundStyle(.secondary)
+ }
+ }
+ Spacer()
+ if selection == id {
+ Image(systemName: "checkmark").accessibilityLabel("Selected")
+ }
+ }
+ .frame(minHeight: 44)
+ .contentShape(.rect)
+ }
+ .buttonStyle(.plain)
+ .accessibilityAddTraits(selection == id ? .isSelected : [])
+ }
+
+ private func choose(_ id: String) {
+ selection = id
+ dismiss()
+ }
+}
diff --git a/ios/IPhoneAgent/UI/ModelSettingsView.swift b/ios/IPhoneAgent/UI/ModelSettingsView.swift
index 13840df..6effb8f 100644
--- a/ios/IPhoneAgent/UI/ModelSettingsView.swift
+++ b/ios/IPhoneAgent/UI/ModelSettingsView.swift
@@ -55,29 +55,3 @@ struct ModelSettingsView: View {
}
}
-
-/// A model ID is always editable, even when the endpoint supplies a model list.
-struct ModelPicker: View {
- @ObservedObject var settings: Settings
- let title: LocalizedStringKey
- @Binding var selection: String
- let automatic: String
-
- var body: some View {
- HStack {
- TextField(title, text: $selection, prompt: Text(verbatim: automatic))
- .textInputAutocapitalization(.never).autocorrectionDisabled()
- .accessibilityLabel(title)
- if settings.loadingModels { ProgressView() }
- if !settings.models.isEmpty {
- Menu {
- if title != "Model ID" { Button("Use Default") { selection = "" } }
- ForEach(settings.models, id: \.self) { id in
- Button { selection = id } label: { Text(verbatim: id) }
- }
- } label: { Image(systemName: "list.bullet") }
- .accessibilityLabel("Choose Model")
- }
- }
- }
-}
diff --git a/ios/IPhoneAgent/UI/ProviderFields.swift b/ios/IPhoneAgent/UI/ProviderFields.swift
index 01fbe01..cd83696 100644
--- a/ios/IPhoneAgent/UI/ProviderFields.swift
+++ b/ios/IPhoneAgent/UI/ProviderFields.swift
@@ -29,29 +29,9 @@ struct ProviderFields: View {
}
.frame(minHeight: 44).padding(.vertical, Space.xs)
Divider()
- LabeledContent("Model") {
- HStack(spacing: Space.xs) {
- TextField("Model ID", text: $settings.model, prompt: Text("Choose or enter"))
- .multilineTextAlignment(.trailing).labelsHidden()
- if settings.loadingModels {
- ProgressView().frame(minWidth: 44, minHeight: 44)
- } else {
- Menu("Choose Model", systemImage: "chevron.up.chevron.down") {
- ForEach(settings.models, id: \.self) { id in
- Button { settings.model = id } label: { Text(verbatim: id) }
- }
- Divider()
- Button("Refresh Models", systemImage: "arrow.clockwise") {
- Task { await settings.loadModels() }
- }
- .disabled(!settings.isConfigured)
- }
- .labelStyle(.iconOnly).tint(.secondary)
- .frame(minWidth: 44, minHeight: 44)
- }
- }
- }
- .frame(minHeight: 44).padding(.vertical, Space.xs)
+ ModelPicker(settings: settings, title: "Model", selection: $settings.model,
+ automatic: String(localized: "Choose a model"), allowsDefault: false)
+ .frame(minHeight: 44).padding(.vertical, Space.xs)
if let error = settings.modelsError {
Text(verbatim: error).font(.footnote).foregroundStyle(.secondary)
.frame(maxWidth: .infinity, alignment: .leading)
diff --git a/ios/IPhoneAgentTests/LLMTests.swift b/ios/IPhoneAgentTests/LLMTests.swift
index 766fa7f..c0a253e 100644
--- a/ios/IPhoneAgentTests/LLMTests.swift
+++ b/ios/IPhoneAgentTests/LLMTests.swift
@@ -37,7 +37,7 @@ final class StubProtocol: URLProtocol {
/// Port of server/tests/test_llm.py, plus streaming.
@MainActor final class LLMTests: XCTestCase {
func testProviderInferenceAndCustomEndpoints() {
- XCTAssertEqual(ModelProvider.infer(baseURL: "https://openrouter.ai/api/v1/", model: "openrouter/free"), .openRouterFree)
+ XCTAssertEqual(ModelProvider.infer(baseURL: "https://openrouter.ai/api/v1/", model: "openrouter/free"), .openRouter)
XCTAssertEqual(ModelProvider.infer(baseURL: "https://api.openai.com/v1", model: "custom"), .openAI)
XCTAssertEqual(ModelProvider.infer(baseURL: "http://192.168.1.4:8080/v1", model: "local"), .others)
XCTAssertNotEqual(ModelProvider.qwen.baseURL, ModelProvider.qwenInternational.baseURL)
@@ -48,7 +48,8 @@ final class StubProtocol: URLProtocol {
let defaults = UserDefaults(suiteName: name)!
defer { defaults.removePersistentDomain(forName: name) }
let settings = Settings(defaults: defaults, info: [:])
- settings.selectProvider(.openRouterFree)
+ settings.selectProvider(.openRouter)
+ settings.model = "openrouter/free"
XCTAssertEqual(settings.baseURL, "https://openrouter.ai/api/v1")
let model = try await settings.resolvedModel()
XCTAssertEqual(model, "openrouter/free")
@@ -70,6 +71,39 @@ final class StubProtocol: URLProtocol {
XCTAssertFalse(settings.isConfigured)
}
+ func testImageCheckDoesNotTreatSubstringsOrNegationAsSuccess() throws {
+ XCTAssertNoThrow(try ModelConnectionCheck.validate(ChatResult(text: "Red.", total: 0)))
+ for text in ["infrared", "not red", "", "I cannot identify the image"] {
+ XCTAssertThrowsError(try ModelConnectionCheck.validate(ChatResult(text: text, total: 0)))
+ }
+ }
+
+ func testLegacyFreeProviderPreservesModelAndMigratesProvider() {
+ let name = "migration-" + UUID().uuidString
+ let defaults = UserDefaults(suiteName: name)!
+ defer { defaults.removePersistentDomain(forName: name) }
+ defaults.set("openRouterFree", forKey: "modelProvider")
+ defaults.set(ModelProvider.openRouter.baseURL, forKey: "baseURL")
+ defaults.set("openrouter/free", forKey: "model")
+ let settings = Settings(defaults: defaults, info: [:])
+ XCTAssertEqual(settings.provider, .openRouter)
+ XCTAssertEqual(settings.currentModel, "openrouter/free")
+ }
+
+ func testStreamErrorIsNotMistakenForEmptyReply() async {
+ StubProtocol.seen = []
+ StubProtocol.respond = { _ in
+ (200, "text/event-stream", "data: {\"error\": {\"message\": \"No available provider\"}}\n\ndata: [DONE]\n\n")
+ }
+ do {
+ _ = try await client("router").chat(system: "test", text: "test")
+ XCTFail("Expected provider error")
+ } catch {
+ XCTAssertEqual(error.localizedDescription, "No available provider")
+ XCTAssertEqual(StubProtocol.seen.count, 1)
+ }
+ }
+
func client(_ model: String, extra: [String: Any] = [:], tokenParam: String = "auto") -> LLMClient {
let config = URLSessionConfiguration.ephemeral
config.protocolClasses = [StubProtocol.self]