Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 8 additions & 7 deletions PulseLoop/Coach/Apple/AppleFoundationModelsClient.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,8 @@ import FoundationModels
/// guided generation can't be built for that schema (the orchestrator's
/// `JSONRepair` then recovers the object).
///
/// **Text-only:** the shipping FoundationModels SDK has no image-input API
/// (`PromptBuilder` accepts only text), so image attachments aren't supported
/// on-device. The Settings UI hides the image-input option when this provider is
/// selected, so image turns never reach this client.
/// The coach sends text prompts to this client. Settings hides the image-input
/// option when this provider is selected.
///
/// Like `GeminiClient`, one instance covers a single agent turn and accumulates
/// the conversation across `send` calls so repair turns keep prior context.
Expand Down Expand Up @@ -150,8 +148,11 @@ final class AppleFoundationModelsClient: ResponsesClient, @unchecked Sendable {

@available(iOS 26.0, *)
private func generate(requestBody: Data) async throws -> OpenAIResponse {
guard SystemLanguageModel.default.isAvailable else {
throw ResponsesError.http(status: 503, body: AppleOnDeviceAvailability.current.statusMessage)
// iOS supplies the model, including Apple's updated version on iOS 27.
let model = SystemLanguageModel.default
guard model.isAvailable else {
let statusMessage = await MainActor.run { AppleOnDeviceAvailability.current.statusMessage }
throw ResponsesError.http(status: 503, body: statusMessage)
}

let (schema, schemaName) = try ingest(requestBody)
Expand All @@ -161,7 +162,7 @@ final class AppleFoundationModelsClient: ResponsesClient, @unchecked Sendable {
let instructions = systemText.isEmpty
? "You are a concise, supportive personal health coach."
: systemText
let session = LanguageModelSession(instructions: instructions)
let session = LanguageModelSession(model: model, instructions: instructions)

let text: String
if let schema, let generated = try? await respondGuided(session: session, prompt: prompt, schema: schema, name: schemaName) {
Expand Down
128 changes: 90 additions & 38 deletions PulseLoop/Coach/Config/CoachSettings.swift
Original file line number Diff line number Diff line change
Expand Up @@ -86,49 +86,42 @@ enum ReasoningEffort: String, CaseIterable, Identifiable {

/// Levels every reasoning-capable model accepts — offered for a Custom slug.
static let common: [ReasoningEffort] = [.low, .medium, .high]
/// GPT-6 Sol/Astra and Claude 5.5.
static let lowToMax: [ReasoningEffort] = [.low, .medium, .high, .xhigh, .max]
}

/// Preset MiniMax model choices surfaced in Settings. MiniMax's catalog is small
/// and fixed (unlike OpenRouter), so these are exact API model names rather than a
/// free-text field. The stored `CoachSettings.model` stays a string, so a new
/// model name still works if typed/served; these are just the curated picks.
///
/// The M2.5 and M2.7 families are omitted: MiniMax closes them to new users on
/// Oct 19 2026 and retires them on Nov 18 2026. `MiniMax-M3.1-Flash-Preview` is
/// plan-only (not pay-as-you-go), so it isn't offered to API-key users either.
/// free-text field. The stored `CoachSettings.model` stays a string.
enum MiniMaxModel: String, CaseIterable, Identifiable {
case m3 = "MiniMax-M3"
case m21 = "MiniMax-M2.1"
case m21highspeed = "MiniMax-M2.1-highspeed"
case m2 = "MiniMax-M2"
case m31Flash = "MiniMax-M3.1-Flash"
case m3 = "MiniMax-M3"

var id: String { rawValue }

var label: String { rawValue }

var blurb: String {
switch self {
case .m3: return "Latest — agentic reasoning, tool use, 1M context (default)"
case .m21: return "Strong multi-language programming (~60 tps)"
case .m21highspeed: return "M2.1 — faster (~100 tps)"
case .m2: return "Agentic capabilities, advanced reasoning"
case .m31Flash: return "Fast & lower cost (default)"
case .m3: return "Multimodal reasoning & tool use"
}
}

/// Sensible default when switching to MiniMax — the latest agentic model, best
/// suited to the coach's multi-round tool loop.
static let `default` = MiniMaxModel.m3
var reasoningEfforts: [ReasoningEffort] {
self == .m31Flash ? ReasoningEffort.lowToMax : []
}

static let `default` = MiniMaxModel.m31Flash
}

/// Preset Gemini model choices surfaced in Settings. `gemini-2.0-flash` was shut
/// down June 1 2026, and since Sep 18 2026 the 2.5 models only serve keys that
/// already used them, so the picks are the current Gemini 3/4 models.
/// Preset Gemini model choices surfaced in Settings.
enum GeminiModel: String, CaseIterable, Identifiable {
case flash38 = "gemini-3.8-flash"
case flashLite = "gemini-3.5-flash-lite"
case argon = "gemini-4-argon"
case hydrogen = "gemini-4-hydrogen"
case neon = "gemini-4-neon"
case carbon = "gemini-4-carbon"

var id: String { rawValue }

Expand All @@ -138,16 +131,19 @@ enum GeminiModel: String, CaseIterable, Identifiable {
switch self {
case .flash38: return "Fast & capable (default)"
case .flashLite: return "Lowest cost & latency"
case .argon: return "Best reasoning"
case .argon: return "Deep reasoning"
case .hydrogen: return "Fast Gemini 4 reasoning"
case .neon: return "Balanced Gemini 4 reasoning"
case .carbon: return "Best Gemini 4 reasoning"
}
}

/// Accepted `thinkingConfig.thinkingLevel` values — 3.8 Flash and 4 Argon
/// reject `minimal`.
/// Accepted `thinkingConfig.thinkingLevel` values.
var reasoningEfforts: [ReasoningEffort] {
switch self {
case .flashLite: return [.minimal, .low, .medium, .high]
case .flash38, .argon: return [.low, .medium, .high]
case .flash38, .argon, .carbon: return [.low, .medium, .high]
case .hydrogen, .neon: return [.low, .medium, .high, .xhigh]
}
}

Expand All @@ -163,11 +159,17 @@ enum OpenRouterModel: String, CaseIterable, Identifiable {
case claudeSonnet = "anthropic/claude-sonnet-5.5"
case claudeOpus = "anthropic/claude-opus-5.5"
case claudeHaiku = "anthropic/claude-haiku-5.5"
case gptSol = "openai/gpt-6.1-sol"
case claudeFable = "anthropic/claude-fable-5.2"
case gptAstra = "openai/gpt-6.2-astra"
case gptSol = "openai/gpt-6.2-sol"
case gptSol61 = "openai/gpt-6.1-sol"
case gptLuna = "openai/gpt-6-luna"
case geminiPro = "google/gemini-4-argon"
case geminiFlash = "google/gemini-3.8-flash"
case deepseek = "deepseek/deepseek-v4.1-flash"
case geminiNeon = "google/gemini-4-neon"
case geminiLite = "google/gemini-3.5-flash-lite"
case deepseek = "deepseek/deepseek-v4.1-flash-1017"
case deepseek910 = "deepseek/deepseek-v4.1-flash"

var id: String { rawValue }

Expand All @@ -176,23 +178,32 @@ enum OpenRouterModel: String, CaseIterable, Identifiable {
var blurb: String {
switch self {
case .claudeSonnet: return "Balanced, great for coaching (default)"
case .claudeOpus: return "Most capable Claude"
case .claudeOpus: return "Advanced reasoning"
case .claudeHaiku: return "Fastest, lowest-cost Claude"
case .claudeFable: return "Most capable Claude"
case .gptAstra: return "Best OpenAI reasoning"
case .gptSol: return "OpenAI balanced flagship"
case .gptSol61: return "Previous-generation Sol"
case .gptLuna: return "Lower cost & latency"
case .geminiPro: return "Deep reasoning"
case .geminiFlash: return "Fast & capable"
case .geminiNeon: return "Balanced Gemini 4 reasoning"
case .geminiLite: return "Lowest-cost Gemini"
case .deepseek: return "Strong open reasoning, low cost"
case .deepseek910: return "Previous DeepSeek V4.1 Flash snapshot"
}
}

/// Effort levels the model lists in OpenRouter's `reasoning.supported_efforts`.
var reasoningEfforts: [ReasoningEffort] {
switch self {
case .claudeSonnet, .claudeOpus, .claudeHaiku, .gptSol: return ReasoningEffort.lowToMax
case .gptLuna: return [.none] + ReasoningEffort.lowToMax
case .claudeSonnet, .claudeOpus, .claudeFable, .gptAstra, .gptSol, .gptSol61:
return ReasoningEffort.lowToMax
case .claudeHaiku, .gptLuna: return [.none] + ReasoningEffort.lowToMax
case .geminiPro, .geminiFlash: return [.low, .medium, .high]
case .deepseek: return [.low, .high, .max]
case .geminiNeon: return [.low, .medium, .high, .xhigh]
case .geminiLite: return [.minimal, .low, .medium, .high]
case .deepseek, .deepseek910: return [.none, .low, .high, .max]
}
}

Expand All @@ -206,8 +217,11 @@ enum OpenRouterModel: String, CaseIterable, Identifiable {
/// just the curated picks surfaced in Settings.
enum CoachModel: String, CaseIterable, Identifiable {
case luna = "gpt-6-luna"
case sol = "gpt-6.1-sol"
case astra = "gpt-6-astra"
case terra = "gpt-6.1-terra"
case sol = "gpt-6.2-sol"
case astra = "gpt-6.2-astra"
case sol61 = "gpt-6.1-sol"
case astra60 = "gpt-6-astra"

var id: String { rawValue }

Expand All @@ -216,16 +230,19 @@ enum CoachModel: String, CaseIterable, Identifiable {
var blurb: String {
switch self {
case .luna: return "Lower cost & latency"
case .terra: return "Efficient reasoning"
case .sol: return "Balanced (default)"
case .astra: return "Best reasoning"
case .sol61: return "Previous-generation Sol"
case .astra60: return "Previous-generation Astra"
}
}

/// Accepted `reasoning.effort` levels — Sol and Astra reject `none` (HTTP 400).
var reasoningEfforts: [ReasoningEffort] {
switch self {
case .luna: return [.none] + ReasoningEffort.lowToMax
case .sol, .astra: return ReasoningEffort.lowToMax
case .luna, .terra: return [.none] + ReasoningEffort.lowToMax
case .sol, .astra, .sol61, .astra60: return ReasoningEffort.lowToMax
}
}

Expand Down Expand Up @@ -326,9 +343,13 @@ struct CoachSettings: Codable, Equatable {
var knownReasoningEfforts: [ReasoningEffort]? {
switch providerMode {
case .userOpenAIKey: return CoachModel(rawValue: model)?.reasoningEfforts
case .userOpenRouterKey: return OpenRouterModel(rawValue: model)?.reasoningEfforts
// A non-preset Gemini model may be a 2.5 model, which rejects `thinkingLevel`.
case .userOpenRouterKey:
let slug = openRouterModel
let base = slug.hasSuffix(":online") ? String(slug.dropLast(":online".count)) : slug
return OpenRouterModel(rawValue: base)?.reasoningEfforts
// Older Gemini models can reject `thinkingLevel`.
case .userGeminiKey: return GeminiModel(rawValue: model)?.reasoningEfforts ?? []
case .userMiniMaxKey: return MiniMaxModel(rawValue: minimaxModel)?.reasoningEfforts ?? []
default: return nil
}
}
Expand All @@ -355,14 +376,45 @@ struct CoachSettings: Codable, Equatable {

init() {}

/// Replace only known retired IDs for the saved provider. Stored message IDs
/// and usage prices are separate from these settings.
private static func migrateRetiredModel(_ model: String, provider: CoachProviderMode) -> String {
let trimmed = model.trimmingCharacters(in: .whitespacesAndNewlines)
switch provider {
case .userGeminiKey:
switch trimmed {
case "gemini-2.0-flash", "gemini-2.0-flash-001", "gemini-2.5-pro": return GeminiModel.flash38.rawValue
case "gemini-2.5-flash": return GeminiModel.flashLite.rawValue
default: return model
}
case .userOpenRouterKey:
switch trimmed {
case "google/gemini-2.5-pro": return OpenRouterModel.geminiFlash.rawValue
case "google/gemini-2.5-pro:online": return OpenRouterModel.geminiFlash.rawValue + ":online"
case "google/gemini-2.5-flash": return OpenRouterModel.geminiLite.rawValue
case "google/gemini-2.5-flash:online": return OpenRouterModel.geminiLite.rawValue + ":online"
default: return model
}
case .userMiniMaxKey:
switch trimmed.lowercased() {
case "minimax-m2", "minimax-m2.1", "minimax-m2.1-highspeed",
"minimax-m2.5", "minimax-m2.5-highspeed", "minimax-m2.7", "minimax-m2.7-highspeed":
return MiniMaxModel.default.rawValue
default: return model
}
default: return model
}
}

/// Tolerant decode: missing keys (older stored settings, new fields) fall back
/// to defaults instead of failing the whole decode.
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
let d = CoachSettings.default
coachMasterEnabled = try c.decodeIfPresent(Bool.self, forKey: .coachMasterEnabled) ?? d.coachMasterEnabled
providerMode = try c.decodeIfPresent(CoachProviderMode.self, forKey: .providerMode) ?? d.providerMode
model = try c.decodeIfPresent(String.self, forKey: .model) ?? d.model
let storedModel = try c.decodeIfPresent(String.self, forKey: .model) ?? d.model
model = Self.migrateRetiredModel(storedModel, provider: providerMode)
reasoningEffort = try c.decodeIfPresent(String.self, forKey: .reasoningEffort)
enableWebSearch = try c.decodeIfPresent(Bool.self, forKey: .enableWebSearch) ?? d.enableWebSearch
orEnablePrivacyRouting = try c.decodeIfPresent(Bool.self, forKey: .orEnablePrivacyRouting) ?? d.orEnablePrivacyRouting
Expand Down
28 changes: 15 additions & 13 deletions PulseLoop/Coach/Config/CoachSettingsSection.swift
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,12 @@ struct CoachSettingsSection: View {
!OpenRouterModel.allCases.contains { $0.rawValue == store.settings.model }
}

/// Whether to offer the image-input (multimodal) toggle. Hidden on-device (no
/// image API) and on text-only MiniMax models — only MiniMax-M3 is multimodal,
/// so attaching a photo to M2.x would just error.
/// Whether to offer image input. The Apple coach client sends text prompts,
/// and image support on MiniMax is model-specific.
private var showsImageInputToggle: Bool {
switch store.settings.providerMode {
case .appleOnDevice: return false
case .userMiniMaxKey: return store.settings.model == MiniMaxModel.m3.rawValue
case .userMiniMaxKey: return MiniMaxModel(rawValue: store.settings.minimaxModel) != nil
default: return true
}
}
Expand Down Expand Up @@ -149,9 +148,7 @@ struct CoachSettingsSection: View {
}
}

// On-device has a single fixed model and runs only on-device (no
// cloud backup) — show a privacy/availability card instead of a
// model picker.
// iOS supplies the on-device model. Show its availability here.
if store.settings.providerMode == .appleOnDevice {
appleOnDeviceCard
} else if store.settings.providerMode == .localOpenAICompat {
Expand Down Expand Up @@ -276,6 +273,14 @@ struct CoachSettingsSection: View {
SettingsGroup(header: "Routing") {
FormToggleRow(title: "Privacy routing", isOn: privacyRoutingBinding)

let fable = OpenRouterModel.claudeFable.rawValue
let model = store.settings.openRouterModel
if model == fable || model == fable + ":online" {
Text("Claude Fable 5.2 requests are retained for safety monitoring.")
.font(.caption)
.foregroundStyle(PulseColors.textMuted)
}

FormValueRow(title: "Provider sort") {
Picker("Provider sort", selection: providerSortBinding) {
Text("Default").tag("")
Expand Down Expand Up @@ -408,7 +413,7 @@ struct CoachSettingsSection: View {
// MARK: - On-device (Apple) info card

/// Privacy + availability panel shown when the on-device provider is picked.
/// Replaces the model picker (the model is fixed) and explains the v1 limits.
/// Describes the system-supplied model and supported coach features.
private var appleOnDeviceCard: some View {
let availability = AppleOnDeviceAvailability.current
return FormField {
Expand All @@ -422,7 +427,7 @@ struct CoachSettingsSection: View {
.foregroundStyle(PulseColors.textPrimary)
}
Text(availability.isAvailable
? "Your health data is analyzed entirely on your iPhone and never leaves the device. No API key, no network — works offline and free of charge."
? "Coach uses Apple's updated on-device model on iOS 27 and later. It works offline and needs no API key."
: availability.statusMessage)
.font(PulseFont.caption.weight(.regular))
.foregroundStyle(PulseColors.textSecondary)
Expand Down Expand Up @@ -552,10 +557,7 @@ struct CoachSettingsSection: View {
} else {
store.settings.model = newValue
}
// MiniMax: only M3 is multimodal — drop image input on text-only
// picks so the (now hidden) toggle can't linger enabled.
if store.settings.providerMode == .userMiniMaxKey,
store.settings.model != MiniMaxModel.m3.rawValue {
if store.settings.providerMode == .userMiniMaxKey, !showsImageInputToggle {
store.settings.enableImageInput = false
}
}
Expand Down
Loading
Loading