diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index 384db0ee9..e736ca23b 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -4,6 +4,9 @@ import AudioToolbox import AVFoundation import BackgroundTasks import CoreMotion +#if canImport(FoundationModels) +import FoundationModels +#endif @main @objc class AppDelegate: FlutterAppDelegate { @@ -88,6 +91,10 @@ import CoreMotion } // Home-screen icon switching (setAlternateIconName). iOS only — see the // bridge below for the system-alert cost it carries. + // Apple's on-device model (Foundation Models) for the AI features. + if let registrar = registry.registrar(forPlugin: "AppleIntelligenceBridge") { + AppleIntelligenceBridge.register(messenger: registrar.messenger()) + } if let registrar = registry.registrar(forPlugin: "AppIconBridge") { AppIconBridge.register(messenger: registrar.messenger()) } @@ -378,3 +385,129 @@ enum AppIconBridge { } } } + + +/// Apple's on-device language model (Foundation Models, iOS 26+), for the +/// coach, briefings and journal when "Apple on-device" is chosen. No key, no +/// network: the prompt and the answer never leave the phone. +/// +/// `status` → "available" | "notEnabled" | "notReady" | "deviceNotEligible" | +/// "unsupportedOS". `respond` takes {instructions, prompt, temperature} and +/// returns the text, or a FlutterError whose CODE names the failure +/// ("notEnabled", "notReady", "deviceNotEligible", "unsupported", "tooLong", +/// "declined", "timeout", "failed"); the Dart side turns the code into +/// translated text, and the message is only a detail for logs. +enum AppleIntelligenceBridge { + private static let channelName = "openstrap/apple_ai" + + /// A stalled generation must not leave the Dart call waiting forever. + private static let respondTimeoutSeconds: Double = 60 + + static func register(messenger: FlutterBinaryMessenger) { + let channel = FlutterMethodChannel(name: channelName, binaryMessenger: messenger) + channel.setMethodCallHandler { call, result in + switch call.method { + case "status": + result(status()) + case "respond": + let args = call.arguments as? [String: Any] ?? [:] + let instructions = args["instructions"] as? String ?? "" + let prompt = args["prompt"] as? String ?? "" + let temperature = args["temperature"] as? Double + let reply = ReplyOnce(result) + let work = Task { + let out = await respond(instructions: instructions, prompt: prompt, + temperature: temperature) + DispatchQueue.main.async { _ = reply.send(out) } + } + DispatchQueue.main.asyncAfter(deadline: .now() + respondTimeoutSeconds) { + if reply.send(.failure(code: "timeout", detail: "no answer in \(Int(respondTimeoutSeconds)) s")) { + work.cancel() + } + } + default: + result(FlutterMethodNotImplemented) + } + } + } + + enum Outcome { case success(String), failure(code: String, detail: String) } + + /// Delivers the first outcome only: the answer or the timeout, whichever + /// comes first. Used on the main queue only, so it needs no lock. + final class ReplyOnce { + private var result: FlutterResult? + init(_ result: @escaping FlutterResult) { self.result = result } + + /// False when an outcome was already delivered. + func send(_ outcome: Outcome) -> Bool { + guard let r = result else { return false } + result = nil + switch outcome { + case .success(let text): r(text) + case .failure(let code, let detail): + r(FlutterError(code: code, message: detail, details: nil)) + } + return true + } + } + + static func status() -> String { + #if canImport(FoundationModels) + if #available(iOS 26.0, *) { + switch SystemLanguageModel.default.availability { + case .available: + return "available" + case .unavailable(.appleIntelligenceNotEnabled): + return "notEnabled" + case .unavailable(.modelNotReady): + return "notReady" + case .unavailable(.deviceNotEligible): + return "deviceNotEligible" + default: + return "unavailable" + } + } + #endif + return "unsupportedOS" + } + + static func respond(instructions: String, prompt: String, + temperature: Double?) async -> Outcome { + #if canImport(FoundationModels) + if #available(iOS 26.0, *) { + let state = status() + guard state == "available" else { + return .failure(code: unavailableCode(state), detail: state) + } + do { + let session = LanguageModelSession(instructions: instructions) + let options = GenerationOptions(temperature: temperature) + let response = try await session.respond(to: prompt, options: options) + return .success(response.content) + } catch let error as LanguageModelSession.GenerationError { + switch error { + case .exceededContextWindowSize: + return .failure(code: "tooLong", detail: error.localizedDescription) + case .guardrailViolation: + return .failure(code: "declined", detail: error.localizedDescription) + default: + return .failure(code: "failed", detail: error.localizedDescription) + } + } catch { + return .failure(code: "failed", detail: error.localizedDescription) + } + } + #endif + return .failure(code: "unsupported", detail: "unsupportedOS") + } + + static func unavailableCode(_ state: String) -> String { + switch state { + case "notEnabled", "notReady", "deviceNotEligible": + return state + default: + return "unsupported" + } + } +} diff --git a/lib/ai/briefing.dart b/lib/ai/briefing.dart index 6667f160b..2b39b3711 100644 --- a/lib/ai/briefing.dart +++ b/lib/ai/briefing.dart @@ -64,6 +64,13 @@ class Briefing { /// were actually present — absent metrics are never fabricated). final Map inputs; + /// Where the request went and which model answered, recorded when it was + /// written: the "what was sent" screen describes THIS briefing, not + /// whatever the settings say now. Null on a note saved before these were + /// recorded, and on one that called no model. + final String? endpoint; + final String? model; + const Briefing({ required this.day, required this.period, @@ -71,6 +78,8 @@ class Briefing { required this.breakdownMd, required this.generatedAtMs, required this.inputs, + this.endpoint, + this.model, }); /// Whether producing this note involved a model at all. @@ -90,6 +99,8 @@ class Briefing { 'breakdown_md': breakdownMd, 'generated_at_ms': generatedAtMs, 'inputs': inputs, + 'endpoint': ?endpoint, + 'model': ?model, }; static Briefing? fromJson(dynamic j) { @@ -108,6 +119,8 @@ class Briefing { inputs: j['inputs'] is Map ? (j['inputs'] as Map).cast() : const {}, + endpoint: j['endpoint'] is String ? j['endpoint'] as String : null, + model: j['model'] is String ? j['model'] as String : null, ); } } diff --git a/lib/ai/briefing_engine.dart b/lib/ai/briefing_engine.dart index bf0c33e2c..ec138e001 100644 --- a/lib/ai/briefing_engine.dart +++ b/lib/ai/briefing_engine.dart @@ -27,6 +27,20 @@ import '../ui2/screens/home_screen.dart' as ring show readinessBand; import 'briefing.dart'; import 'nightly_sweep.dart'; +/// Where a briefing's request went, as stored on the [Briefing]: Apple's +/// on-device pseudo-base, or the endpoint's scheme, host and port ONLY. A +/// custom base URL can carry an access key in its path or query, and saved +/// briefings travel in backups, so nothing past the host is kept. Null when +/// the endpoint has no host, which the screen then reports as unknown. +String? briefingEndpointOf(CoachConfig config) { + if (config.usesApple) return kAppleOnDeviceBase; + final u = Uri.tryParse(config.apiBase.trim()); + if (u == null || u.host.isEmpty) return null; + // Built with Uri so an IPv6 host keeps its brackets (http://[::1]:11434). + return Uri(scheme: u.scheme, host: u.host, port: u.hasPort ? u.port : null) + .toString(); +} + /// Injectable one-shot completion (tests pass a fake; production defaults to /// [CoachEngine.completeText] — the shared BYOK plumbing). typedef BriefingComplete = Future Function({ @@ -556,6 +570,11 @@ class BriefingEngine { BriefingStore.write(b); return b; } + // Where the request goes, read in the same synchronous run as the request + // itself (postChat reads the config before its first await): a provider + // switched while the model is answering must not relabel this briefing. + final sentTo = briefingEndpointOf(config); + final sentModel = config.model; final raw = await (complete ?? (({required String system, required String user}) => CoachEngine.completeText( @@ -574,6 +593,8 @@ class BriefingEngine { breakdownMd: parsed.breakdownMd, generatedAtMs: (wallNow ?? effectiveNow).millisecondsSinceEpoch, inputs: inputs, + endpoint: sentTo, + model: sentModel, ); // An older request must not overwrite a complete briefing a newer one // already stored while this one waited on the model. diff --git a/lib/coach/coach_apple.dart b/lib/coach/coach_apple.dart new file mode 100644 index 000000000..33332ac16 --- /dev/null +++ b/lib/coach/coach_apple.dart @@ -0,0 +1,301 @@ +// Apple's on-device model as an AI provider (coach, briefings, journal). +// +// Every AI request in the app goes through `CoachEngine.postChat`; when the +// user picks "Apple on-device" it lands here instead of on the network. The +// model is small and reads only a few thousand tokens, so: +// +// * the coach's long tool-driven prompt (run_sql over the derived views) is +// swapped for a short one plus a snapshot of the last two weeks, read +// here with the same guarded read-only SQL the coach tool uses — the model +// answers from that, it cannot query on its own; +// * briefing and journal prompts (already self-contained) go through as they +// are, trimmed to fit; +// * replies are plain text: no tool calls, no actions. + +import 'dart:async'; +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +import '../data/day_label.dart'; +import 'coach_db.dart'; + +enum AppleAiStatus { + available, + notEnabled, + notReady, + deviceNotEligible, + unsupported; + + static AppleAiStatus parse(String? s) => switch (s) { + 'available' => available, + 'notEnabled' => notEnabled, + 'notReady' => notReady, + 'deviceNotEligible' => deviceNotEligible, + _ => unsupported, + }; + + /// What the settings screen says about it. + String get message => switch (this) { + available => 'Ready. Runs on this iPhone; nothing leaves it.', + notEnabled => + 'Turn on Apple Intelligence in Settings to use the on-device model.', + notReady => + 'Apple’s on-device model is still downloading. Try again later.', + deviceNotEligible => 'This iPhone can’t run Apple’s on-device model.', + unsupported => + 'Needs an iPhone with Apple Intelligence on iOS 26 or later.', + }; +} + +/// User-facing failures of the on-device route. English here; the coach's +/// error card translates them through `localizedText`. +const String kAppleFailedMessage = + 'Apple’s on-device model couldn’t answer. Try again.'; +const String kAppleTooLongMessage = + 'That was too long for Apple’s on-device model. Start a new chat or ask a shorter question.'; +const String kAppleDeclinedMessage = + 'Apple’s on-device model declined to answer that. Try wording it differently.'; +const String kAppleTimeoutMessage = + 'Apple’s on-device model took too long to answer. Try again, or ask a shorter question.'; +const String kAppleNoEcgMessage = + 'Apple’s on-device model can’t read an ECG waveform. To analyse this reading, switch Apple Intelligence off in the coach’s AI settings and use another model.'; + +class AppleOnDevice { + AppleOnDevice._(); + + static const _ch = MethodChannel('openstrap/apple_ai'); + + /// Budgets in cost units (see [cost]): about 3.5 Latin characters per + /// token, so a unit is roughly a Latin character. The model's window holds + /// the instructions, the prompt AND its answer. + static const int instructionBudget = 3200; + static const int promptBudget = 4200; + + /// The native side gives up at 60 s; this backstop only covers a bridge + /// that never answers at all. Settable for tests only. + @visibleForTesting + static Duration respondTimeout = const Duration(seconds: 75); + + /// Cost of a text against the budgets. Scripts outside Latin (Cyrillic, + /// Devanagari, Thai, CJK…) take far more tokens per character, so each of + /// their characters counts as 4: a long Thai or Chinese chat is clipped + /// well before it can overflow the context window. + @visibleForTesting + static int cost(String s) { + var n = 0; + for (final r in s.runes) { + n += _runeCost(r); + } + return n; + } + + static int _runeCost(int rune) => rune < 0x0370 ? 1 : 4; + + static Future status() async { + if (defaultTargetPlatform != TargetPlatform.iOS) { + return AppleAiStatus.unsupported; + } + try { + return AppleAiStatus.parse(await _ch.invokeMethod('status')); + } catch (_) { + return AppleAiStatus.unsupported; + } + } + + /// One chat turn: `body` is the chat-completions-style request the engine + /// builds. Returns the normalized assistant message (`{'content': text}`). + /// Throws a [StateError] whose message is user-facing. + /// + /// [today] is the coach's headline readiness for today (the engine's + /// `_todayReadiness`), so the snapshot never shows a mid-sync partial night. + static Future> reply( + Map body, { + Future<({String day, num? readiness})?> Function()? today, + }) async { + final messages = [ + for (final m in (body['messages'] as List? ?? const [])) + if (m is Map) m.cast(), + ]; + final isCoach = body['tools'] is List && (body['tools'] as List).isNotEmpty; + // The ECG screen's "Analyze" asks for get_ecg_reading, a tool this route + // cannot call: say so instead of answering without the waveform. + if (isCoach && asksForEcgReading(messages)) { + throw StateError(kAppleNoEcgMessage); + } + final instructions = isCoach + ? '$kAppleCoachInstructions\n\n' + '${await _snapshot(today == null ? null : await today())}' + : _clip( + messages + .where((m) => m['role'] == 'system') + .map((m) => _text(m['content'])) + .join('\n\n'), + instructionBudget, + keepEnd: false); + final prompt = buildPrompt(messages); + final temperature = (body['temperature'] as num?)?.toDouble(); + final String? text; + try { + text = await _ch.invokeMethod('respond', { + 'instructions': _clip(instructions, instructionBudget + 2600, + keepEnd: false), + 'prompt': prompt, + 'temperature': ?temperature, + }).timeout(respondTimeout); + } on TimeoutException { + throw StateError(kAppleTimeoutMessage); + } on PlatformException catch (e) { + debugPrint('apple_ai respond: ${e.code}: ${e.message}'); + throw StateError(errorMessage(e.code)); + } on MissingPluginException { + throw StateError(AppleAiStatus.unsupported.message); + } + final t = (text ?? '').trim(); + if (t.isEmpty) throw StateError(kAppleFailedMessage); + return {'content': t}; + } + + /// The user-facing message for a native error code. + @visibleForTesting + static String errorMessage(String code) => switch (code) { + 'notEnabled' => AppleAiStatus.notEnabled.message, + 'notReady' => AppleAiStatus.notReady.message, + 'deviceNotEligible' => AppleAiStatus.deviceNotEligible.message, + 'unsupported' => AppleAiStatus.unsupported.message, + 'tooLong' => kAppleTooLongMessage, + 'declined' => kAppleDeclinedMessage, + 'timeout' => kAppleTimeoutMessage, + _ => kAppleFailedMessage, + }; + + /// Whether the newest user turn asks for an ECG reading's waveform. + @visibleForTesting + static bool asksForEcgReading(List> messages) { + for (final m in messages.reversed) { + if (m['role'] != 'user') continue; + return _text(m['content']).contains('get_ecg_reading'); + } + return false; + } + + /// The conversation as one prompt, newest last, trimmed from the oldest + /// end. Tool traffic is dropped: this route never calls tools. + @visibleForTesting + static String buildPrompt(List> messages) { + final turns = []; + for (final m in messages) { + final role = m['role']; + if (role != 'user' && role != 'assistant') continue; + final t = _text(m['content']).trim(); + if (t.isEmpty) continue; + turns.add(role == 'user' ? t : 'Previously you answered: $t'); + } + if (turns.isEmpty) return ''; + if (turns.length == 1) return _clip(turns.single, promptBudget); + final last = turns.removeLast(); + final history = turns.join('\n\n'); + final room = promptBudget - cost(last) - 40; + return room <= 200 + ? _clip(last, promptBudget) + : 'Earlier in this chat:\n${_clip(history, room)}\n\nNow: $last'; + } + + static String _text(Object? content) { + if (content is String) return content; + if (content is List) { + return content + .map((p) => p is Map ? '${p['text'] ?? ''}' : '$p') + .join(' '); + } + return content == null ? '' : '$content'; + } + + /// [s] cut to [max] cost units (see [cost]), marking the cut with '…'. + static String _clip(String s, int max, {bool keepEnd = true}) { + if (cost(s) <= max) return s; + final runes = s.runes.toList(); + final kept = []; + var n = 1; // the '…' + for (var i = 0; i < runes.length; i++) { + final r = runes[keepEnd ? runes.length - 1 - i : i]; + n += _runeCost(r); + if (n > max) break; + kept.add(r); + } + final body = + String.fromCharCodes(keepEnd ? kept.reversed.toList() : kept); + return keepEnd ? '…$body' : '$body…'; + } + + /// The last 14 calendar days from the coach's own guarded read-only view, + /// anchored on today's LOCAL date. [today] is the Home headline readiness + /// (the same value the engine hands run_sql), so a mid-sync partial night + /// never reaches the model as today's recovery. + static Future _snapshot(({String day, num? readiness})? today) async { + try { + // Re-formatted from its parsed parts: only a clean label reaches the SQL. + final d0 = dayLabelBefore(today?.day ?? '', 0) ?? todayLabel(); + final d6 = dayLabelBefore(d0, 6)!, d13 = dayLabelBefore(d0, 13)!; + final rows = await CoachDb.runCoachSql( + 'SELECT date, readiness, strain, sleep_min, deep_min, rem_min, ' + 'resting_hr, hrv, resp_rate, stress, steps FROM v_daily ' + "WHERE date BETWEEN '$d13' AND '$d0' ORDER BY date DESC LIMIT 14", + rowCap: 14, + today: today); + final week = await CoachDb.runCoachSql( + "SELECT CASE WHEN date >= '$d6' THEN 'last 7 days' ELSE " + "'the 7 days before' END AS period, ROUND(AVG(readiness)) AS " + 'recovery, ROUND(AVG(strain), 1) AS strain, ROUND(AVG(sleep_min)) ' + 'AS sleep_min, ROUND(AVG(resting_hr)) AS resting_hr, ' + 'ROUND(AVG(hrv)) AS hrv FROM v_daily ' + "WHERE date BETWEEN '$d13' AND '$d0' GROUP BY 1", + rowCap: 2, + today: today); + final todayRow = await CoachDb.runCoachSql( + 'SELECT date, readiness AS recovery, strain, sleep_min, resting_hr, ' + "hrv FROM v_daily WHERE date = '$d0'", + rowCap: 1, + today: today); + return 'TODAY ($d0): ${_hasRows(todayRow) ? _clip(todayRow, 300, keepEnd: false) : 'no data for today yet.'}\n' + 'THE WEEK (averages): ${_clip(week, 500, keepEnd: false)}\n' + 'THE DATA (newest first; null = not measured). Columns: date, ' + 'Recovery 0-100, Strain 0-21, sleep min, deep min, REM min, resting ' + 'HR, HRV ms, breathing rate, stress, steps.\n' + '${_clip(rows, 2400, keepEnd: false)}'; + } catch (e) { + return 'THE DATA: could not be read right now ($e).'; + } + } + + static bool _hasRows(String result) { + try { + final j = jsonDecode(result); + return j is Map && (j['row_count'] as num? ?? 0) > 0; + } catch (_) { + return false; + } + } +} + +/// The coach's rules, cut to what a small model can hold. +const String kAppleCoachInstructions = ''' +You are the Edge coach inside the user's own health app, running on their +iPhone. Answer only about their sleep, recovery, strain, training, heart rate, +HRV and habits, using ONLY the data below. Rules: +- Never state a number that is not in the data. If something is missing, say + it is missing. +- Recovery is 0-100, Strain is 0-21. Say "HRV" and "your usual". +- Compare with their own recent days, not population norms. +- Never diagnose. For worrying patterns suggest asking a clinician. Only if + the user mentions chest pain, fainting or severe breathlessness: urgent + care first. +- Talk naturally: don't repeat the words TODAY, THE WEEK or THE DATA. +- TODAY is today's numbers; quote them exactly. If it says there is no + data for today yet, say so. Use THE WEEK for "this week vs last". +- Recovery 67+ is a good day to push, 34-66 train moderately, under 34 keep + it easy and prioritise sleep. +- Be short and practical: 2-5 sentences or a few bullets. Plain language. +- You cannot log food, workouts or medications on this model; if asked, say + to use the app's Log screens. You cannot see ECG readings.'''; diff --git a/lib/coach/coach_config.dart b/lib/coach/coach_config.dart index bef899e2c..6574d0c1c 100644 --- a/lib/coach/coach_config.dart +++ b/lib/coach/coach_config.dart @@ -122,6 +122,10 @@ bool isPrivateCoachHost(String url) { } } +/// The model name and pseudo-base shown for Apple's on-device model. +const String kAppleOnDeviceModel = 'Apple on-device'; +const String kAppleOnDeviceBase = 'apple://on-device'; + class CoachConfig extends ChangeNotifier { static const _kBaseUrl = 'coach_base_url'; static const _kModel = 'coach_model'; @@ -129,6 +133,7 @@ class CoachConfig extends ChangeNotifier { static const _kKey = 'coach_api_key'; // secure storage static const _kTimeoutSeconds = 'coach_timeout_seconds'; static const _kUseChatGpt = 'coach_use_chatgpt'; + static const _kUseApple = 'coach_use_apple'; /// A local model's first response includes Ollama/LM Studio loading the /// whole model into memory, which alone can pass two minutes on modest @@ -188,7 +193,15 @@ class CoachConfig extends ChangeNotifier { /// the BYOK settings are kept untouched for switching back. final ChatGptAuth chatgpt; bool _useChatGpt = false; - bool get usesChatGpt => _useChatGpt; + bool get usesChatGpt => _useChatGpt && !usesApple; + + /// Apple's on-device model (Foundation Models, iOS 26+): no key, no network, + /// nothing leaves the phone. Takes precedence over every other route. + bool _useApple = false; + /// Apple's on-device model exists only on iPhone; a setting restored from + /// an iOS backup onto another platform must not route there. + bool get usesApple => + _useApple && defaultTargetPlatform == TargetPlatform.iOS; String _baseUrl = defaultBaseUrl; CoachApi _api = CoachApi.defaultFor(defaultBaseUrl); @@ -201,7 +214,12 @@ class CoachConfig extends ChangeNotifier { /// user can fix by pasting one — this one fixes itself on the next unlocked /// read, and telling them to set a key up again would be wrong. bool _keyUnreadable = false; - bool get keyUnreadable => _useChatGpt ? chatgpt.unreadable : _keyUnreadable; + /// Never while Apple's on-device model is in use: it needs no key, so a + /// saved provider's unreadable key must not hide its chat. The flags stay + /// as they are for when Apple is switched off. + bool get keyUnreadable => usesApple + ? false + : (_useChatGpt ? chatgpt.unreadable : _keyUnreadable); /// True while it is still unknown whether a key is stored — an install that /// predates the marker, read while the keychain was unavailable. Not shown to @@ -256,8 +274,13 @@ class CoachConfig extends ChangeNotifier { } String get baseUrl => _baseUrl; - CoachApi get api => _useChatGpt ? CoachApi.responses : _api; - String get model => _model; + CoachApi get api => usesChatGpt ? CoachApi.responses : _api; + String get model => usesApple ? kAppleOnDeviceModel : _model; + + /// The saved bring-your-own route and model, untouched by the Apple switch: + /// what the setup screen restores when Apple is switched off. + bool get savedUsesChatGpt => _useChatGpt; + String get savedModel => _model; /// The saved, user-configurable timeout — meaningful only for a local /// endpoint (see [requestTimeout]), but kept intact and readable regardless /// of the endpoint currently configured so a UI can show/restore it as the @@ -278,24 +301,28 @@ class CoachConfig extends ChangeNotifier { /// Save closed the form, `configured` stayed false, and the coach never came /// on with nothing on screen to explain why. See [isLocalCoachHost] for the /// host classification. - bool get isLocalEndpoint => isLocalCoachHost(apiBase); + bool get isLocalEndpoint => usesApple || isLocalCoachHost(apiBase); /// Whether the endpoint is on this device or a private network — the gate /// for skipping a consent prompt before health data leaves the phone. /// Narrower than [isLocalEndpoint]; see [isPrivateCoachHost]. - bool get isPrivateEndpoint => isPrivateCoachHost(apiBase); + bool get isPrivateEndpoint => usesApple || isPrivateCoachHost(apiBase); - bool get configured => _useChatGpt + bool get configured => usesApple + ? true + : _useChatGpt ? chatgpt.sharing && _model.isNotEmpty : (hasKey || isLocalEndpoint) && _baseUrl.isNotEmpty && _model.isNotEmpty; /// Whether AI reminders (briefings) may be scheduled. On the ChatGPT route /// only the ChatGPT sign-in counts: a BYOK key left over from before the /// switch is not used there, so a signed-out ChatGPT coach is not set up. - bool get remindersConfigured => _useChatGpt ? configured : hasKey; + bool get remindersConfigured => + usesApple ? true : (_useChatGpt ? configured : hasKey); /// Normalised base, no trailing slash. String get apiBase { + if (usesApple) return kAppleOnDeviceBase; if (_useChatGpt) return kChatGptApiBase; var b = _baseUrl.trim(); while (b.endsWith('/')) { @@ -313,6 +340,7 @@ class CoachConfig extends ChangeNotifier { unawaited(chatgpt.load(trusted: trusted).catchError((_) {})); final prefs = await SharedPreferences.getInstance(); _useChatGpt = prefs.getBool(_kUseChatGpt) ?? false; + _useApple = prefs.getBool(_kUseApple) ?? false; _baseUrl = prefs.getString(_kBaseUrl) ?? defaultBaseUrl; _api = switch (prefs.getString(_kApi)) { 'responses' => CoachApi.responses, @@ -331,6 +359,9 @@ class CoachConfig extends ChangeNotifier { // with the resume retry permanently disabled. _keyUnreadable = marker == true && !hasKey; _keyUndetermined = marker == null; + // Apple's on-device model needs no key, so its restored choice is + // complete here: published now, not after a keychain read that may hang. + if (usesApple) notifyListeners(); try { final read = await _secure.read( @@ -422,6 +453,7 @@ class CoachConfig extends ChangeNotifier { String? apiKey, int? timeoutSeconds, bool? useChatGpt, + bool? useApple, }) async { final prefs = await SharedPreferences.getInstance(); // The key goes first: if the keychain refuses it, nothing else is applied, @@ -478,6 +510,14 @@ class CoachConfig extends ChangeNotifier { _keyUnreadable = false; _keyUndetermined = false; } + if (useApple != null) { + // Stored first, and in memory only once that landed: a failed write + // must not leave this run on Apple while the saved choice says off. + if (!await prefs.setBool(_kUseApple, useApple)) { + throw StateError('Couldn’t save the AI provider choice.'); + } + _useApple = useApple; + } if (useChatGpt != null) { _useChatGpt = useChatGpt; await prefs.setBool(_kUseChatGpt, useChatGpt); diff --git a/lib/coach/coach_engine.dart b/lib/coach/coach_engine.dart index c3521f8d1..d35651069 100644 --- a/lib/coach/coach_engine.dart +++ b/lib/coach/coach_engine.dart @@ -28,6 +28,7 @@ import 'coach_actions.dart'; import 'coach_chat_completions.dart'; import 'coach_chatgpt.dart'; import 'coach_config.dart'; +import 'coach_apple.dart'; import 'coach_db.dart'; import 'coach_prompt.dart'; import 'coach_responses.dart'; @@ -832,7 +833,7 @@ class CoachEngine { 'tools': _toolDefs, 'tool_choice': 'auto', 'temperature': 0.3, - }, client: _http); + }, client: _http, appleToday: _todayReadiness); /// True when [model] names a Claude version that rejects OpenAI sampling /// params (temperature/top_p/top_k) with a 400: Opus >= 4.7, Sonnet and @@ -874,7 +875,16 @@ class CoachEngine { CoachConfig config, Map body, { http.Client? client, + Future<({String day, num? readiness})?> Function()? appleToday, }) async { + // Apple's on-device model: no HTTP, nothing leaves the phone. + if (config.usesApple) { + try { + return await AppleOnDevice.reply(body, today: appleToday); + } on StateError catch (e) { + throw CoachException(e.message); + } + } final c = client ?? http.Client(); final model = body['model'] as String? ?? ''; final api = config.api; diff --git a/lib/data/backup_extras.dart b/lib/data/backup_extras.dart index c1ca43865..aea8bec5f 100644 --- a/lib/data/backup_extras.dart +++ b/lib/data/backup_extras.dart @@ -110,6 +110,7 @@ const Map kPrefTypes = { 'coach_api': 'string', 'coach_model': 'string', 'coach_timeout_seconds': 'int', + 'coach_use_apple': 'bool', 'coach_use_chatgpt': 'bool', 'cycle_tracking_enabled': 'bool', 'dev.mode': 'bool', diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 1da0cdda3..211907940 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -4022,5 +4022,20 @@ "notifLookbackTemp": "erhöhte Hauttemperatur ×{count}", "notifLookbackRhrHigherBody": "Dein Ruhepuls lag gegen Ende der Woche etwa {bpm} bpm höher als am Anfang.", "notifLookbackRhrLowerBody": "Dein Ruhepuls lag gegen Ende der Woche etwa {bpm} bpm niedriger als am Anfang.", - "notifSyncStaleBody": "Seit etwa {hours} Stunden keine neuen Daten. Öffne OpenStrap, um neu zu verbinden – die Hintergrundsynchronisierung ist vielleicht hängen geblieben." + "notifSyncStaleBody": "Seit etwa {hours} Stunden keine neuen Daten. Öffne OpenStrap, um neu zu verbinden – die Hintergrundsynchronisierung ist vielleicht hängen geblieben.", + "coachAppleTitle": "Apple Intelligence auf diesem iPhone", + "coachAppleSub": "Kostenlos, offline, privat. Kein Schlüssel nötig.", + "coachAppleChecking": "Apple Intelligence wird geprüft …", + "coachAppleOnNote": "Coach, Briefings und Tagebuch nutzen jetzt Apples kleines Modell auf dem Gerät. Es antwortet anhand deiner letzten zwei Wochen und kann nichts für dich eintragen; schalte es aus, um ein größeres Modell zu nutzen.", + "coachAppleReady": "Bereit. Läuft auf diesem iPhone; nichts verlässt es.", + "coachAppleNotEnabled": "Schalte Apple Intelligence in den Einstellungen ein, um das Modell auf dem Gerät zu nutzen.", + "coachAppleNotReady": "Apples Modell auf dem Gerät wird noch geladen. Versuche es später erneut.", + "coachAppleNotEligible": "Dieses iPhone kann Apples Modell auf dem Gerät nicht ausführen.", + "coachAppleUnsupported": "Benötigt ein iPhone mit Apple Intelligence ab iOS 26.", + "coachAppleFailed": "Apples Modell auf dem Gerät konnte nicht antworten. Versuche es erneut.", + "coachAppleTooLong": "Das war zu lang für Apples Modell auf dem Gerät. Starte einen neuen Chat oder stelle eine kürzere Frage.", + "coachAppleDeclined": "Apples Modell auf dem Gerät hat eine Antwort darauf abgelehnt. Versuche es anders zu formulieren.", + "coachAppleTimeout": "Apples Modell auf dem Gerät hat zu lange für eine Antwort gebraucht. Versuche es erneut oder stelle eine kürzere Frage.", + "coachAppleNoEcg": "Apples Modell auf dem Gerät kann keine EKG-Kurve lesen. Um diese Messung zu analysieren, schalte Apple Intelligence in den KI-Einstellungen des Coachs aus und nutze ein anderes Modell.", + "aiBriefingUnknownBody": "Diese Notiz wurde gespeichert, bevor die App festhielt, wohin Briefings gehen. Daher kann sie nicht sagen, wohin diese Werte gesendet wurden." } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 4fc2ce9fa..2e08be844 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -18301,5 +18301,65 @@ "type": "int" } } + }, + "coachAppleTitle": "Apple Intelligence on this iPhone", + "@coachAppleTitle": { + "description": "Coach, AI settings: Apple's on-device model (Foundation Models) option." + }, + "coachAppleSub": "Free, offline, private. No key needed.", + "@coachAppleSub": { + "description": "Coach, AI settings: Apple's on-device model (Foundation Models) option." + }, + "coachAppleChecking": "Checking Apple Intelligence…", + "@coachAppleChecking": { + "description": "Coach, AI settings: Apple's on-device model (Foundation Models) option." + }, + "coachAppleOnNote": "The coach, briefings and journal now use Apple’s small on-device model. It answers from your last two weeks and can’t log things for you; switch it off to use a bigger model instead.", + "@coachAppleOnNote": { + "description": "Coach, AI settings: Apple's on-device model (Foundation Models) option." + }, + "coachAppleReady": "Ready. Runs on this iPhone; nothing leaves it.", + "@coachAppleReady": { + "description": "Coach, AI settings: Apple's on-device model (Foundation Models) option." + }, + "coachAppleNotEnabled": "Turn on Apple Intelligence in Settings to use the on-device model.", + "@coachAppleNotEnabled": { + "description": "Coach, AI settings: Apple's on-device model (Foundation Models) option." + }, + "coachAppleNotReady": "Apple’s on-device model is still downloading. Try again later.", + "@coachAppleNotReady": { + "description": "Coach, AI settings: Apple's on-device model (Foundation Models) option." + }, + "coachAppleNotEligible": "This iPhone can’t run Apple’s on-device model.", + "@coachAppleNotEligible": { + "description": "Coach, AI settings: Apple's on-device model (Foundation Models) option." + }, + "coachAppleUnsupported": "Needs an iPhone with Apple Intelligence on iOS 26 or later.", + "@coachAppleUnsupported": { + "description": "Coach, AI settings: Apple's on-device model (Foundation Models) option." + }, + "coachAppleFailed": "Apple’s on-device model couldn’t answer. Try again.", + "@coachAppleFailed": { + "description": "Coach, AI settings: Apple's on-device model (Foundation Models) option." + }, + "coachAppleTooLong": "That was too long for Apple’s on-device model. Start a new chat or ask a shorter question.", + "@coachAppleTooLong": { + "description": "Coach, AI settings: Apple's on-device model (Foundation Models) option." + }, + "coachAppleDeclined": "Apple’s on-device model declined to answer that. Try wording it differently.", + "@coachAppleDeclined": { + "description": "Coach, AI settings: Apple's on-device model (Foundation Models) option." + }, + "coachAppleTimeout": "Apple’s on-device model took too long to answer. Try again, or ask a shorter question.", + "@coachAppleTimeout": { + "description": "Coach, AI settings: Apple's on-device model (Foundation Models) option." + }, + "coachAppleNoEcg": "Apple’s on-device model can’t read an ECG waveform. To analyse this reading, switch Apple Intelligence off in the coach’s AI settings and use another model.", + "@coachAppleNoEcg": { + "description": "Coach, AI settings: Apple's on-device model (Foundation Models) option." + }, + "aiBriefingUnknownBody": "This note was saved before the app recorded where briefings go, so it can’t say where these numbers were sent.", + "@aiBriefingUnknownBody": { + "description": "AI briefing, what-was-sent banner: a briefing saved before its endpoint was recorded." } } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 874a62c7e..c6aaa4835 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -4022,5 +4022,20 @@ "notifLookbackTemp": "temperatura de la piel elevada ×{count}", "notifLookbackRhrHigherBody": "Tu frecuencia cardíaca en reposo fue unos {bpm} lpm más alta al final de la semana que al principio.", "notifLookbackRhrLowerBody": "Tu frecuencia cardíaca en reposo fue unos {bpm} lpm más baja al final de la semana que al principio.", - "notifSyncStaleBody": "No hay datos nuevos desde hace unas {hours} horas. Abre OpenStrap para reconectar: puede que la sincronización en segundo plano se haya detenido." + "notifSyncStaleBody": "No hay datos nuevos desde hace unas {hours} horas. Abre OpenStrap para reconectar: puede que la sincronización en segundo plano se haya detenido.", + "coachAppleTitle": "Apple Intelligence en este iPhone", + "coachAppleSub": "Gratis, sin conexión, privado. Sin clave.", + "coachAppleChecking": "Comprobando Apple Intelligence…", + "coachAppleOnNote": "El coach, los resúmenes y el diario usan ahora el modelo pequeño de Apple en el dispositivo. Responde con tus dos últimas semanas y no puede registrar nada por ti; desactívalo para usar un modelo más grande.", + "coachAppleReady": "Listo. Funciona en este iPhone; nada sale de él.", + "coachAppleNotEnabled": "Activa Apple Intelligence en Ajustes para usar el modelo del dispositivo.", + "coachAppleNotReady": "El modelo de Apple en el dispositivo aún se está descargando. Inténtalo más tarde.", + "coachAppleNotEligible": "Este iPhone no puede ejecutar el modelo de Apple en el dispositivo.", + "coachAppleUnsupported": "Requiere un iPhone con Apple Intelligence en iOS 26 o posterior.", + "coachAppleFailed": "El modelo de Apple en el dispositivo no pudo responder. Inténtalo de nuevo.", + "coachAppleTooLong": "Era demasiado largo para el modelo de Apple en el dispositivo. Empieza un chat nuevo o haz una pregunta más corta.", + "coachAppleDeclined": "El modelo de Apple en el dispositivo se negó a responder a eso. Prueba a decirlo de otra forma.", + "coachAppleTimeout": "El modelo de Apple en el dispositivo tardó demasiado en responder. Inténtalo de nuevo o haz una pregunta más corta.", + "coachAppleNoEcg": "El modelo de Apple en el dispositivo no puede leer la curva de un ECG. Para analizar esta lectura, desactiva Apple Intelligence en los ajustes de IA del coach y usa otro modelo.", + "aiBriefingUnknownBody": "Esta nota se guardó antes de que la app registrara adónde van los resúmenes, así que no puede decir adónde se enviaron estas cifras." } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 7decd45a8..865b6d52b 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -4022,5 +4022,20 @@ "notifSyncStaleBody": "Aucune nouvelle donnée depuis environ {hours} heures. Ouvre OpenStrap pour te reconnecter : la synchronisation en arrière-plan s’est peut-être bloquée.", "devicesTimeUnknown": "Heure inconnue", "devicesClockNotSetSub": "Le bracelet a enregistré des données mais son horloge n’est pas réglée", - "homeSyncedTimeUnknown": "Données du bracelet, horloge non réglée" + "homeSyncedTimeUnknown": "Données du bracelet, horloge non réglée", + "coachAppleTitle": "Apple Intelligence sur cet iPhone", + "coachAppleSub": "Gratuit, hors ligne, privé. Aucune clé requise.", + "coachAppleChecking": "Vérification d’Apple Intelligence…", + "coachAppleOnNote": "Le coach, les briefings et le journal utilisent désormais le petit modèle d’Apple sur l’appareil. Il répond à partir de tes deux dernières semaines et ne peut rien enregistrer pour toi ; désactive-le pour utiliser un modèle plus grand.", + "coachAppleReady": "Prêt. Fonctionne sur cet iPhone ; rien n’en sort.", + "coachAppleNotEnabled": "Active Apple Intelligence dans Réglages pour utiliser le modèle sur l’appareil.", + "coachAppleNotReady": "Le modèle d’Apple sur l’appareil est encore en téléchargement. Réessaie plus tard.", + "coachAppleNotEligible": "Cet iPhone ne peut pas exécuter le modèle d’Apple sur l’appareil.", + "coachAppleUnsupported": "Nécessite un iPhone avec Apple Intelligence sous iOS 26 ou version ultérieure.", + "coachAppleFailed": "Le modèle d’Apple sur l’appareil n’a pas pu répondre. Réessaie.", + "coachAppleTooLong": "C’était trop long pour le modèle d’Apple sur l’appareil. Commence une nouvelle discussion ou pose une question plus courte.", + "coachAppleDeclined": "Le modèle d’Apple sur l’appareil a refusé de répondre à cela. Essaie de le formuler autrement.", + "coachAppleTimeout": "Le modèle d’Apple sur l’appareil a mis trop de temps à répondre. Réessaie, ou pose une question plus courte.", + "coachAppleNoEcg": "Le modèle d’Apple sur l’appareil ne peut pas lire le tracé d’un ECG. Pour analyser cet enregistrement, désactive Apple Intelligence dans les réglages IA du coach et utilise un autre modèle.", + "aiBriefingUnknownBody": "Cette note a été enregistrée avant que l’app ne note où vont les briefings ; elle ne peut donc pas dire où ces chiffres ont été envoyés." } diff --git a/lib/l10n/app_hi.arb b/lib/l10n/app_hi.arb index 14b5d6923..4372ce0d8 100644 --- a/lib/l10n/app_hi.arb +++ b/lib/l10n/app_hi.arb @@ -4022,5 +4022,20 @@ "notifSyncStaleBody": "लगभग {hours} घंटे से कोई नया डेटा नहीं आया। दोबारा कनेक्ट करने के लिए OpenStrap खोलें — हो सकता है बैकग्राउंड सिंक रुक गया हो।", "devicesTimeUnknown": "समय अज्ञात", "devicesClockNotSetSub": "स्ट्रैप ने डेटा रिकॉर्ड किया, लेकिन उसकी घड़ी सेट नहीं है", - "homeSyncedTimeUnknown": "बैंड का डेटा, घड़ी सेट नहीं है" + "homeSyncedTimeUnknown": "बैंड का डेटा, घड़ी सेट नहीं है", + "coachAppleTitle": "इस iPhone पर Apple Intelligence", + "coachAppleSub": "मुफ़्त, ऑफ़लाइन, निजी। कोई कुंजी नहीं चाहिए।", + "coachAppleChecking": "Apple Intelligence जाँची जा रही है…", + "coachAppleOnNote": "कोच, ब्रीफ़िंग और जर्नल अब Apple का छोटा ऑन-डिवाइस मॉडल इस्तेमाल करते हैं। यह आपके पिछले दो हफ़्तों के आधार पर जवाब देता है और आपके लिए कुछ दर्ज नहीं कर सकता; बड़ा मॉडल इस्तेमाल करने के लिए इसे बंद करें।", + "coachAppleReady": "तैयार। इसी iPhone पर चलता है; कुछ भी बाहर नहीं जाता।", + "coachAppleNotEnabled": "ऑन-डिवाइस मॉडल इस्तेमाल करने के लिए सेटिंग्स में Apple Intelligence चालू करें।", + "coachAppleNotReady": "Apple का ऑन-डिवाइस मॉडल अभी डाउनलोड हो रहा है। बाद में फिर कोशिश करें।", + "coachAppleNotEligible": "यह iPhone Apple का ऑन-डिवाइस मॉडल नहीं चला सकता।", + "coachAppleUnsupported": "iOS 26 या बाद के संस्करण पर Apple Intelligence वाला iPhone चाहिए।", + "coachAppleFailed": "Apple का ऑन-डिवाइस मॉडल जवाब नहीं दे सका। फिर कोशिश करें।", + "coachAppleTooLong": "यह Apple के ऑन-डिवाइस मॉडल के लिए बहुत लंबा था। नई चैट शुरू करें या छोटा सवाल पूछें।", + "coachAppleDeclined": "Apple के ऑन-डिवाइस मॉडल ने इसका जवाब देने से मना कर दिया। इसे दूसरे शब्दों में पूछकर देखें।", + "coachAppleTimeout": "Apple के ऑन-डिवाइस मॉडल ने जवाब देने में बहुत देर लगाई। फिर कोशिश करें, या छोटा सवाल पूछें।", + "coachAppleNoEcg": "Apple का ऑन-डिवाइस मॉडल ECG वेवफ़ॉर्म नहीं पढ़ सकता। इस रीडिंग का विश्लेषण करने के लिए कोच की AI सेटिंग्स में Apple Intelligence बंद करें और कोई दूसरा मॉडल इस्तेमाल करें।", + "aiBriefingUnknownBody": "यह नोट ऐप के यह दर्ज करने से पहले सहेजा गया था कि ब्रीफ़िंग कहाँ जाती हैं, इसलिए यह नहीं बता सकता कि ये आंकड़े कहाँ भेजे गए थे।" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 205e4e670..819368f10 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -9158,5 +9158,20 @@ }, "devicesTimeUnknown": "Время неизвестно", "devicesClockNotSetSub": "Браслет записал данные, но его часы не установлены", - "homeSyncedTimeUnknown": "Данные с браслета, часы не установлены" + "homeSyncedTimeUnknown": "Данные с браслета, часы не установлены", + "coachAppleTitle": "Apple Intelligence на этом iPhone", + "coachAppleSub": "Бесплатно, офлайн, приватно. Ключ не нужен.", + "coachAppleChecking": "Проверяем Apple Intelligence…", + "coachAppleOnNote": "Коуч, сводки и дневник теперь используют небольшую модель Apple на устройстве. Она отвечает по данным за последние две недели и не может ничего записывать за вас; выключите её, чтобы использовать более крупную модель.", + "coachAppleReady": "Готово. Работает на этом iPhone; ничего не покидает его.", + "coachAppleNotEnabled": "Включите Apple Intelligence в Настройках, чтобы использовать модель на устройстве.", + "coachAppleNotReady": "Модель Apple на устройстве ещё загружается. Попробуйте позже.", + "coachAppleNotEligible": "Этот iPhone не может запускать модель Apple на устройстве.", + "coachAppleUnsupported": "Нужен iPhone с Apple Intelligence на iOS 26 или новее.", + "coachAppleFailed": "Модель Apple на устройстве не смогла ответить. Попробуйте ещё раз.", + "coachAppleTooLong": "Это слишком длинно для модели Apple на устройстве. Начните новый чат или задайте вопрос короче.", + "coachAppleDeclined": "Модель Apple на устройстве отказалась на это отвечать. Попробуйте сформулировать иначе.", + "coachAppleTimeout": "Модель Apple на устройстве отвечала слишком долго. Попробуйте ещё раз или задайте вопрос короче.", + "coachAppleNoEcg": "Модель Apple на устройстве не может читать кривую ЭКГ. Чтобы проанализировать эту запись, выключите Apple Intelligence в настройках ИИ коуча и используйте другую модель.", + "aiBriefingUnknownBody": "Эта заметка сохранена до того, как приложение стало записывать, куда уходят сводки, поэтому оно не может сказать, куда были отправлены эти данные." } diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index 9b423d891..7349a684f 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -17332,5 +17332,20 @@ "type": "int" } } - } + }, + "coachAppleTitle": "Apple Intelligence บน iPhone เครื่องนี้", + "coachAppleSub": "ฟรี ออฟไลน์ เป็นส่วนตัว ไม่ต้องใช้คีย์", + "coachAppleChecking": "กำลังตรวจสอบ Apple Intelligence…", + "coachAppleOnNote": "โค้ช สรุป และบันทึกประจำวันจะใช้โมเดลขนาดเล็กของ Apple บนอุปกรณ์ โดยตอบจากข้อมูลสองสัปดาห์ล่าสุดของคุณและบันทึกอะไรแทนคุณไม่ได้ ปิดไว้หากต้องการใช้โมเดลที่ใหญ่กว่า", + "coachAppleReady": "พร้อมแล้ว ทำงานบน iPhone เครื่องนี้ ไม่มีข้อมูลออกไปภายนอก", + "coachAppleNotEnabled": "เปิด Apple Intelligence ในการตั้งค่าเพื่อใช้โมเดลบนอุปกรณ์", + "coachAppleNotReady": "โมเดลบนอุปกรณ์ของ Apple ยังดาวน์โหลดไม่เสร็จ ลองอีกครั้งภายหลัง", + "coachAppleNotEligible": "iPhone เครื่องนี้ใช้โมเดลบนอุปกรณ์ของ Apple ไม่ได้", + "coachAppleUnsupported": "ต้องใช้ iPhone ที่มี Apple Intelligence บน iOS 26 ขึ้นไป", + "coachAppleFailed": "โมเดลบนอุปกรณ์ของ Apple ตอบไม่ได้ ลองอีกครั้ง", + "coachAppleTooLong": "ข้อความนี้ยาวเกินไปสำหรับโมเดลบนอุปกรณ์ของ Apple เริ่มแชตใหม่หรือถามให้สั้นลง", + "coachAppleDeclined": "โมเดลบนอุปกรณ์ของ Apple ปฏิเสธที่จะตอบเรื่องนี้ ลองถามด้วยคำอื่น", + "coachAppleTimeout": "โมเดลบนอุปกรณ์ของ Apple ใช้เวลาตอบนานเกินไป ลองอีกครั้งหรือถามให้สั้นลง", + "coachAppleNoEcg": "โมเดลบนอุปกรณ์ของ Apple อ่านคลื่น ECG ไม่ได้ หากต้องการวิเคราะห์การวัดนี้ ให้ปิด Apple Intelligence ในการตั้งค่า AI ของโค้ชแล้วใช้โมเดลอื่น", + "aiBriefingUnknownBody": "บันทึกนี้ถูกบันทึกไว้ก่อนที่แอปจะเริ่มจดว่าสรุปถูกส่งไปที่ใด จึงบอกไม่ได้ว่าตัวเลขเหล่านี้ถูกส่งไปที่ใด" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 9f2f25c5f..12f2164d2 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -4022,5 +4022,20 @@ "notifSyncStaleBody": "已约 {hours} 小时没有新数据。打开 OpenStrap 重新连接,后台同步可能已停止。", "devicesTimeUnknown": "时间未知", "devicesClockNotSetSub": "腕带已记录数据,但时钟未设置", - "homeSyncedTimeUnknown": "腕带数据,时钟未设置" + "homeSyncedTimeUnknown": "腕带数据,时钟未设置", + "coachAppleTitle": "此 iPhone 上的 Apple 智能", + "coachAppleSub": "免费、离线、私密。无需密钥。", + "coachAppleChecking": "正在检查 Apple 智能…", + "coachAppleOnNote": "教练、简报和日记现在使用 Apple 的小型设备端模型。它根据你最近两周的数据回答,不能替你记录;关闭后可使用更大的模型。", + "coachAppleReady": "已就绪。在此 iPhone 上运行,数据不会离开设备。", + "coachAppleNotEnabled": "在“设置”中打开 Apple 智能即可使用设备端模型。", + "coachAppleNotReady": "Apple 设备端模型仍在下载,请稍后再试。", + "coachAppleNotEligible": "此 iPhone 无法运行 Apple 设备端模型。", + "coachAppleUnsupported": "需要搭载 iOS 26 或更高版本并支持 Apple 智能的 iPhone。", + "coachAppleFailed": "Apple 设备端模型无法回答,请再试一次。", + "coachAppleTooLong": "这对 Apple 设备端模型来说太长了。请开始新的对话,或问一个更短的问题。", + "coachAppleDeclined": "Apple 设备端模型拒绝回答这个问题。请换一种说法试试。", + "coachAppleTimeout": "Apple 设备端模型回答用时过长。请再试一次,或问一个更短的问题。", + "coachAppleNoEcg": "Apple 设备端模型无法读取心电图波形。要分析这条记录,请在教练的 AI 设置中关闭 Apple Intelligence,并使用其他模型。", + "aiBriefingUnknownBody": "这条记录保存于应用开始记录简报发送去向之前,因此无法说明这些数值被发送到了哪里。" } diff --git a/lib/l10n/display_text.dart b/lib/l10n/display_text.dart index 3dcc7bc05..0da401206 100644 --- a/lib/l10n/display_text.dart +++ b/lib/l10n/display_text.dart @@ -155,6 +155,20 @@ String localizedText(AppLocalizations? l, String text) { return l.findingLowReadinessScoredDetail(int.parse(lowScore[1]!)); } return switch (text) { + "Apple Intelligence on this iPhone" => l.coachAppleTitle, + "Free, offline, private. No key needed." => l.coachAppleSub, + "Checking Apple Intelligence…" => l.coachAppleChecking, + "The coach, briefings and journal now use Apple’s small on-device model. It answers from your last two weeks and can’t log things for you; switch it off to use a bigger model instead." => l.coachAppleOnNote, + "Ready. Runs on this iPhone; nothing leaves it." => l.coachAppleReady, + "Turn on Apple Intelligence in Settings to use the on-device model." => l.coachAppleNotEnabled, + "Apple’s on-device model is still downloading. Try again later." => l.coachAppleNotReady, + "This iPhone can’t run Apple’s on-device model." => l.coachAppleNotEligible, + "Needs an iPhone with Apple Intelligence on iOS 26 or later." => l.coachAppleUnsupported, + "Apple’s on-device model couldn’t answer. Try again." => l.coachAppleFailed, + "That was too long for Apple’s on-device model. Start a new chat or ask a shorter question." => l.coachAppleTooLong, + "Apple’s on-device model declined to answer that. Try wording it differently." => l.coachAppleDeclined, + "Apple’s on-device model took too long to answer. Try again, or ask a shorter question." => l.coachAppleTimeout, + "Apple’s on-device model can’t read an ECG waveform. To analyse this reading, switch Apple Intelligence off in the coach’s AI settings and use another model." => l.coachAppleNoEcg, "Resting heart rate has been raised" => l.findingIllnessTitle, "Recent nights put your resting heart rate above your usual, from one very high night or a few slightly raised ones. One signal: a pattern, not a cause." => l.findingIllnessDetail, diff --git a/lib/ui2/profile/gallery.dart b/lib/ui2/profile/gallery.dart index d531bf354..194d5570e 100644 --- a/lib/ui2/profile/gallery.dart +++ b/lib/ui2/profile/gallery.dart @@ -387,7 +387,8 @@ Map _coachFigureCases() => { // default cloud endpoint — which is the case worth capturing: the local one // is the reassuring half. 'coach_sent_payload': SentPayload( - config: CoachConfig(), + endpoint: CoachConfig().apiBase, + model: CoachConfig().model, inputs: const { 'readiness': 62, 'rmssd_ms': 48, diff --git a/lib/ui2/screens/ai_briefing.dart b/lib/ui2/screens/ai_briefing.dart index 691086c54..6946e7562 100644 --- a/lib/ui2/screens/ai_briefing.dart +++ b/lib/ui2/screens/ai_briefing.dart @@ -202,7 +202,8 @@ class _AiBriefingScreenState extends State { if (b != null) SentPayload( inputs: b.inputs, - config: cfg, + endpoint: b.endpoint, + model: b.model, asked: b.calledModel, ), ], @@ -221,7 +222,13 @@ class _AiBriefingScreenState extends State { /// trusted about the exact question it exists to answer. class SentPayload extends StatelessWidget { final Map inputs; - final CoachConfig config; + + /// The endpoint and model recorded on the briefing ([Briefing.endpoint]). + /// A null endpoint is a note saved before it was recorded: the banner then + /// says it cannot tell, rather than reading today's settings, which may be + /// a different provider (or Apple's on-device model) than the one it went to. + final String? endpoint; + final String? model; /// Whether a model was called at all — [Briefing.calledModel]. False for a /// nightly sweep that found nothing: there was no request, so the banner may @@ -231,12 +238,15 @@ class SentPayload extends StatelessWidget { const SentPayload({ super.key, required this.inputs, - required this.config, + required this.endpoint, + this.model, this.asked = true, }); /// True when the endpoint is on this machine, in which case nothing left it. static bool isLocal(String base) { + // Apple's on-device model: the request never leaves the phone. + if (base == kAppleOnDeviceBase) return true; final h = Uri.tryParse(base)?.host.toLowerCase() ?? ''; return h == 'localhost' || h == '127.0.0.1' || h == '::1'; } @@ -258,8 +268,15 @@ class SentPayload extends StatelessWidget { Widget build(BuildContext c) { final p = P.of(c); final l = AppLocalizations.of(c); - final host = Uri.tryParse(config.apiBase)?.host ?? config.apiBase; - final local = isLocal(config.apiBase); + final base = endpoint; + final unknown = base == null; + final host = base == null + ? '' + : base == kAppleOnDeviceBase + ? kAppleOnDeviceModel + : (Uri.tryParse(base)?.host ?? base); + final local = base != null && isLocal(base); + final modelName = model ?? ''; final keys = inputs.keys.toList()..sort(); // An empty payload is not "we sent an empty payload". The nightly sweep // calls no model at all on a day with no finding, so the banner must not go @@ -291,13 +308,16 @@ class SentPayload extends StatelessWidget { ? (l?.aiBriefingNoneBody ?? 'Nothing. There was no request — the note above was ' 'written on this phone.') + : unknown + ? (l?.aiBriefingUnknownBody ?? + 'This note was saved before the app recorded where briefings go, so it can’t say where these numbers were sent.') : local ? (l?.aiBriefingLocalBody(host) ?? 'These numbers went to $host, on this machine. ' 'Nothing left it.') - : (l?.aiBriefingCloudBody(host, config.model) ?? + : (l?.aiBriefingCloudBody(host, modelName) ?? 'These numbers, and nothing else, were sent to ' - '$host as ${config.model}. No raw ' + '$host as $modelName. No raw ' 'recordings, no name, no identifier.'), style: F.cap.copyWith(color: p.ink, height: 1.5), ), diff --git a/lib/ui2/screens/coach.dart b/lib/ui2/screens/coach.dart index faefdb557..bb9f2ab62 100644 --- a/lib/ui2/screens/coach.dart +++ b/lib/ui2/screens/coach.dart @@ -21,7 +21,9 @@ import 'coach_text.dart'; import '../../data/db.dart'; import '../../l10n/display_text.dart'; +import 'package:flutter/foundation.dart' show defaultTargetPlatform, TargetPlatform; import 'package:flutter/material.dart'; +import '../../coach/coach_apple.dart'; import 'package:gpt_markdown/gpt_markdown.dart'; import 'package:lucide_icons_flutter/lucide_icons.dart'; import 'package:provider/provider.dart'; @@ -122,6 +124,14 @@ class _CoachScreenState extends State { static List _starters(BuildContext c) { final l = AppLocalizations.of(c); + // Apple's on-device model answers from the last two weeks and cannot + // chart or log, so it is offered only the questions it can answer. + if (c.watch().usesApple) { + return [ + l?.coachStarterRecovery ?? 'How recovered am I today, and why?', + l?.coachStarterSleep ?? 'How has my sleep been this week?', + ]; + } return [ l?.coachStarterRecovery ?? 'How recovered am I today, and why?', l?.coachStarterHrvChart ?? 'Chart my HRV over the last month', @@ -484,9 +494,9 @@ class _CoachScreenState extends State { SizedBox( width: 14, height: 14, - child: CircularProgressIndicator( + child: CircularProgressIndicator.adaptive( strokeWidth: 2, - color: p.on(kCoachAccent), + valueColor: AlwaysStoppedAnimation(p.on(kCoachAccent)), ), ), const SizedBox(width: S.x3), @@ -928,7 +938,7 @@ class CoachSetup extends StatefulWidget { State createState() => _CoachSetupState(); } -class _CoachSetupState extends State { +class _CoachSetupState extends State with WidgetsBindingObserver { late final TextEditingController _base; late final TextEditingController _key; late final TextEditingController _search; @@ -938,6 +948,12 @@ class _CoachSetupState extends State { /// "ChatGPT" is chosen instead of a base URL + key. Saved by [_save] only; /// signing in alone does not switch how the coach is paid for. late bool _chatgpt; + + /// Apple's on-device model is the coach's provider. Saved the moment the + /// switch moves; while on, the other provider fields are hidden. + late bool _apple; + AppleAiStatus? _appleStatus; + String? _appleMsg; late final ChatGptAuth _chatgptAuth; // for dispose, which must not read context bool _signingIn = false; /// The model Save will store when nothing has been typed: the saved one at @@ -975,10 +991,16 @@ class _CoachSetupState extends State { _key = TextEditingController(text: cfg.apiKey ?? ''); _search = TextEditingController(); _timeout = TextEditingController(text: cfg.timeoutSeconds.toString()); - _api = cfg.api; - _chatgpt = cfg.usesChatGpt; + // The saved bring-your-own route and model, not the Apple display values: + // they are what switching Apple off must bring back. + _chatgpt = cfg.savedUsesChatGpt; + _api = _chatgpt ? CoachApi.responses : cfg.api; + _apple = cfg.usesApple; + _refreshAppleStatus(); + // Apple Intelligence may be turned on in Settings while this is open. + WidgetsBinding.instance.addObserver(this); _chatgptAuth = cfg.chatgpt; - _model = cfg.model; + _model = cfg.savedModel; _keyOrigin = coachEndpointOrigin(cfg.baseUrl); // The base URL decides which preset is lit and whether a key is needed, and // the search box filters the list — both are read during build, so both @@ -1031,8 +1053,20 @@ class _CoachSetupState extends State { if (mounted) setState(() {}); } + @override + void didChangeAppLifecycleState(AppLifecycleState state) { + if (state == AppLifecycleState.resumed) _refreshAppleStatus(); + } + + Future _refreshAppleStatus() async { + final st = await AppleOnDevice.status(); + if (mounted) setState(() => _appleStatus = st); + return st; + } + @override void dispose() { + WidgetsBinding.instance.removeObserver(this); if (_signingIn) _chatgptAuth.cancelSignIn(); _base.dispose(); _key.dispose(); @@ -1375,6 +1409,97 @@ class _CoachSetupState extends State { ]; } + /// Apple's on-device model: one switch, and what state the model is in. + Widget _appleCard(BuildContext c, P p) { + final st = _appleStatus; + final ready = st == AppleAiStatus.available; + return Surface( + child: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Row(children: [ + Container( + width: 36, + height: 36, + alignment: Alignment.center, + decoration: + BoxDecoration(color: p.wash(C.indigo), borderRadius: R.rSm), + child: Icon(LucideIcons.sparkles, size: 18, color: p.on(C.indigo)), + ), + const SizedBox(width: S.x3), + Expanded( + child: + Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(uiText(c, 'Apple Intelligence on this iPhone'), + style: F.head.copyWith(color: p.ink)), + Text(uiText(c, 'Free, offline, private. No key needed.'), + style: F.cap.copyWith(color: p.ink2)), + ]), + ), + Switch.adaptive( + value: _apple, + // Off until the first availability check is in: nothing is saved + // on a guess. + onChanged: st == null + ? null + : (on) async { + final cfg = context.read(); + if (on) { + // Checked again, not the cached status: the user may + // have just turned Apple Intelligence on in Settings. + final fresh = await _refreshAppleStatus(); + if (!mounted) return; + if (fresh != AppleAiStatus.available) { + setState(() => _appleMsg = fresh.message); + return; + } + } + try { + await cfg.save(useApple: on); + } catch (_) { + if (mounted) { + setState(() => _appleMsg = + AppLocalizations.of(context) + ?.logWorkoutCouldNotSave ?? + 'Could not save that — try again.'); + } + return; + } + if (mounted) { + setState(() { + _apple = on; + _appleMsg = null; + _msg = null; + if (!on) { + // Back to the saved route and model. + _chatgpt = cfg.savedUsesChatGpt; + _api = _chatgpt ? CoachApi.responses : cfg.api; + _model = cfg.savedModel; + } + }); + } + }, + ), + ]), + const SizedBox(height: S.x3), + Text( + st == null + ? uiText(c, 'Checking Apple Intelligence…') + : uiText(c, st.message), + style: F.cap.copyWith(color: ready ? p.on(C.green) : p.ink3)), + if (_apple) ...[ + const SizedBox(height: S.x2), + Text( + uiText(c, + 'The coach, briefings and journal now use Apple’s small on-device model. It answers from your last two weeks and can’t log things for you; switch it off to use a bigger model instead.'), + style: F.cap.copyWith(color: p.ink3)), + ], + if (_appleMsg != null) ...[ + const SizedBox(height: S.x2), + Text(uiText(c, _appleMsg!), style: F.cap.copyWith(color: p.on(C.red))), + ], + ]), + ); + } + @override Widget build(BuildContext c) { final p = P.of(c); @@ -1400,7 +1525,12 @@ class _CoachSetupState extends State { child: ListView( padding: pad, children: [ - Section( + // Apple's on-device model exists only on iPhone (iOS 26+). + if (defaultTargetPlatform == TargetPlatform.iOS) ...[ + _appleCard(c, p), + const SizedBox(height: S.x4), + ], + if (!_apple) Section( l?.coachWhereModelRuns ?? 'Where the model runs', Column( children: [ @@ -1414,7 +1544,9 @@ class _CoachSetupState extends State { ], ), ), - if (_chatgpt) + if (_apple) + const SizedBox.shrink() + else if (_chatgpt) ..._chatGptFields(c, p) else ...[ const SizedBox(height: S.x2), @@ -1496,6 +1628,8 @@ class _CoachSetupState extends State { style: F.cap.copyWith(color: p.ink3, height: 1.5), ), ], + // Apple on-device needs no endpoint, model list or Save. + if (!_apple) ...[ const SizedBox(height: S.x4), BigButton( _loading ? (l?.coachAsking ?? 'Asking…') : (l?.coachListModels ?? 'List models'), @@ -1590,6 +1724,7 @@ class _CoachSetupState extends State { color: kCoachAccent, onTap: _save, ), + ], // end of the bring-your-own-model fields ], ), ), diff --git a/test/ai_briefing_test.dart b/test/ai_briefing_test.dart index aa10c9561..a690527c6 100644 --- a/test/ai_briefing_test.dart +++ b/test/ai_briefing_test.dart @@ -2,6 +2,8 @@ // pure prompt building + response parsing, and the day+period cache round-trip. // The LLM is mocked (BriefingComplete injected) — no network. +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -11,6 +13,9 @@ import 'package:openstrap_edge/ai/nightly_sweep.dart'; import 'package:openstrap_edge/coach/coach_config.dart'; import 'package:openstrap_edge/data/day_label.dart'; import 'package:openstrap_edge/data/local_repository.dart'; +import 'package:openstrap_edge/l10n/app_localizations.dart'; +import 'package:openstrap_edge/ui2/screens/ai_briefing.dart' show SentPayload; +import 'package:openstrap_edge/ui2/ui2.dart' show buildTheme; import 'package:openstrap_edge/state/prefs.dart'; /// A repository stub returning canned Today/sleep/session shapes. @@ -416,6 +421,84 @@ void main() { expect(BriefingStore.read(BriefingPeriod.evening), isNull); }); + test('a briefing records where it went: host only, never the path or query', + () async { + final cfg = CoachConfig(); + await cfg.save( + baseUrl: 'https://llm.example.com:8443/v1/secret-path?token=abc', + model: 'm1'); + final engine = BriefingEngine( + config: cfg, + repo: _FakeRepo(today: _sampleToday()), + complete: ({required system, required user}) async => + 'Recovered and ready.\n---\n- Readiness 74', + ); + final b = await engine.generate(BriefingPeriod.morning); + expect(b.endpoint, 'https://llm.example.com:8443'); + expect(b.model, 'm1'); + final cached = BriefingStore.read(BriefingPeriod.morning); + expect(cached?.endpoint, 'https://llm.example.com:8443'); + expect(cached?.model, 'm1'); + }); + + test('a local IPv6 endpoint is recorded so it still reads as local', + () async { + final cfg = CoachConfig(); + await cfg.save(baseUrl: 'http://[::1]:11434/v1', model: 'm1'); + final b = await BriefingEngine( + config: cfg, + repo: _FakeRepo(today: _sampleToday()), + complete: ({required system, required user}) async => + 'Recovered and ready.\n---\n- Readiness 74', + ).generate(BriefingPeriod.morning); + expect(b.endpoint, 'http://[::1]:11434'); + expect(SentPayload.isLocal(b.endpoint!), isTrue); + }); + + test('a provider switched mid-request does not relabel the briefing', + () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + final cfg = CoachConfig(); + await cfg.save(baseUrl: 'https://api.example.com/v1', model: 'm1'); + + // Cloud at the start, Apple by the time the answer lands. + var b = await BriefingEngine( + config: cfg, + repo: _FakeRepo(today: _sampleToday()), + complete: ({required system, required user}) async { + await cfg.save(useApple: true); + return 'Recovered and ready.\n---\n- Readiness 74'; + }, + ).generate(BriefingPeriod.morning); + expect(b.endpoint, 'https://api.example.com'); + expect(b.model, 'm1'); + + // And the reverse: Apple at the start, cloud by the end. + b = await BriefingEngine( + config: cfg, + repo: _FakeRepo(today: _sampleToday()), + complete: ({required system, required user}) async { + await cfg.save(useApple: false); + return 'Recovered and ready.\n---\n- Readiness 74'; + }, + ).generate(BriefingPeriod.morning); + expect(b.endpoint, kAppleOnDeviceBase); + expect(b.model, kAppleOnDeviceModel); + }); + + test('a briefing saved before the endpoint was recorded reads as unknown', + () { + final b = Briefing.fromJson({ + 'day': '2026-11-21', + 'period': 'morning', + 'one_liner': 'x', + 'inputs': {'readiness': 70}, + }); + expect(b?.endpoint, isNull); + expect(b?.model, isNull); + }); + test('a boring evening calls nobody and says so in one line', () async { var called = false; final engine = BriefingEngine( @@ -480,4 +563,46 @@ void main() { expect(BriefingStore.journalDoneToday(), isTrue); expect(BriefingStore.journalDoneToday('1999-01-01'), isFalse); }); + + group('SentPayload describes the briefing, not today\'s settings', () { + Future bannerFor(WidgetTester tester, String? endpoint) async { + await tester.pumpWidget(MaterialApp( + theme: buildTheme(Brightness.dark), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: Scaffold( + body: SingleChildScrollView( + child: SentPayload( + inputs: const {'readiness': 70}, + endpoint: endpoint, + model: 'm1'), + ), + ), + )); + await tester.pumpAndSettle(); + return tester + .widgetList(find.byType(Text)) + .map((t) => t.data ?? '') + .join('\n'); + } + + testWidgets('an unrecorded endpoint is never called on-device', + (tester) async { + final text = await bannerFor(tester, null); + expect(text, contains('can’t say where these numbers were sent')); + expect(text, isNot(contains('Nothing left it'))); + }); + + testWidgets('a cloud briefing stays a cloud briefing', (tester) async { + final text = await bannerFor(tester, 'https://api.openai.com'); + expect(text, contains('api.openai.com')); + expect(text, isNot(contains('Nothing left it'))); + }); + + testWidgets('an Apple on-device briefing says nothing left the phone', + (tester) async { + final text = await bannerFor(tester, kAppleOnDeviceBase); + expect(text, contains('Nothing left it')); + }); + }); } diff --git a/test/backup/settings_audit_guard_test.dart b/test/backup/settings_audit_guard_test.dart index 7df4fba8b..eef729892 100644 --- a/test/backup/settings_audit_guard_test.dart +++ b/test/backup/settings_audit_guard_test.dart @@ -22,7 +22,7 @@ const _mustTravel = { // alert_after_ts, so a restored timestamp cannot log old naps. 'activity.nap_auto_log_since_sec', 'coach_api', 'coach_model', 'coach_timeout_seconds', - 'coach_use_chatgpt', + 'coach_use_apple', 'coach_use_chatgpt', 'ai_morning_enabled', 'ai_morning_min', 'ai_evening_enabled', 'ai_evening_min', 'ai_journal_enabled', 'ai_journal_min', 'workout.zone_alert_enabled', 'workout.zone_alert_target_zone', 'workout.rpe_skips', diff --git a/test/coach_apple_test.dart b/test/coach_apple_test.dart new file mode 100644 index 000000000..52d3d9a80 --- /dev/null +++ b/test/coach_apple_test.dart @@ -0,0 +1,302 @@ +import 'dart:async'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:openstrap_edge/coach/coach_apple.dart'; +import 'package:openstrap_edge/coach/coach_config.dart'; +import 'package:openstrap_edge/coach/coach_db.dart'; +import 'package:openstrap_edge/data/db.dart'; +import 'package:openstrap_edge/ui2/screens/ai_briefing.dart' show SentPayload; +import 'package:openstrap_edge/ui2/screens/ecg.dart' show ecgAnalyzePrompt; +import 'package:path/path.dart' as p; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; + +const _channel = MethodChannel('openstrap/apple_ai'); + +/// Answers `respond` with [handler] and records the arguments it was given. +Map? _lastArgs; +void _mockRespond(Future Function() handler) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_channel, (call) async { + if (call.method != 'respond') return 'available'; + _lastArgs = (call.arguments as Map).cast(); + return handler(); + }); +} + +Map _coachBody(String question) => { + 'messages': [ + {'role': 'system', 'content': 'long tool-driven rules'}, + {'role': 'user', 'content': question}, + ], + 'tools': [ + {'type': 'function'}, + ], + }; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('one question goes through as it is', () { + expect( + AppleOnDevice.buildPrompt([ + {'role': 'system', 'content': 'rules'}, + {'role': 'user', 'content': 'How did I sleep?'}, + ]), + 'How did I sleep?'); + }); + + test('a chat keeps the latest question whole and drops tool traffic', () { + final p = AppleOnDevice.buildPrompt([ + {'role': 'user', 'content': 'first ' * 2000}, + {'role': 'assistant', 'content': 'an answer'}, + {'role': 'tool', 'content': 'SECRET ROWS'}, + {'role': 'user', 'content': 'And today?'}, + ]); + expect(p.endsWith('Now: And today?'), isTrue); + expect(p.contains('SECRET ROWS'), isFalse); + expect(p.length, lessThanOrEqualTo(AppleOnDevice.promptBudget + 40)); + }); + + test('choosing Apple needs no key and counts as on-device', () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + SharedPreferences.setMockInitialValues({}); + final cfg = CoachConfig(); + await cfg.load(); + expect(cfg.configured, isFalse); + await cfg.save(useApple: true); + expect(cfg.usesApple, isTrue); + expect(cfg.configured, isTrue); + expect(cfg.remindersConfigured, isTrue); + expect(cfg.isPrivateEndpoint, isTrue); + expect(cfg.usesChatGpt, isFalse); + expect(cfg.model, kAppleOnDeviceModel); + final again = CoachConfig(); + await again.load(); + expect(again.usesApple, isTrue); + }); + + test('a saved Apple choice is ignored off iPhone', () async { + SharedPreferences.setMockInitialValues({}); + final cfg = CoachConfig(); + await cfg.load(); + await cfg.save(useApple: true); + expect(cfg.usesApple, isFalse); + }); + + test('a restored Apple choice off iPhone leaves the saved provider in charge', + () async { + SharedPreferences.setMockInitialValues({ + 'coach_use_apple': true, + 'coach_base_url': 'https://api.example.com/v1', + 'coach_model': 'gpt-x', + }); + final cfg = CoachConfig(); + await cfg.load(); + expect(cfg.usesApple, isFalse); + expect(cfg.apiBase, isNot(kAppleOnDeviceBase)); + expect(cfg.model, 'gpt-x'); + expect(cfg.isPrivateEndpoint, isFalse); + expect(cfg.isLocalEndpoint, isFalse); + expect(cfg.configured, isFalse, reason: 'no key for the saved endpoint'); + expect(cfg.remindersConfigured, isFalse); + }); + + test('Apple on keeps the saved ChatGPT route and model for switching back', + () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + SharedPreferences.setMockInitialValues({ + 'coach_use_chatgpt': true, + 'coach_model': 'gpt-5', + }); + final cfg = CoachConfig(); + await cfg.load(); + await cfg.save(useApple: true); + expect(cfg.usesChatGpt, isFalse); + expect(cfg.model, kAppleOnDeviceModel); + expect(cfg.savedUsesChatGpt, isTrue); + expect(cfg.savedModel, 'gpt-5'); + await cfg.save(useApple: false); + expect(cfg.usesChatGpt, isTrue); + expect(cfg.model, 'gpt-5'); + }); + + test('the briefing disclosure counts Apple on-device as local', () { + expect(SentPayload.isLocal(kAppleOnDeviceBase), isTrue); + expect(SentPayload.isLocal('https://api.openai.com/v1'), isFalse); + }); + + test('non-Latin text is budgeted more tightly than Latin', () { + expect(AppleOnDevice.cost('abc'), 3); + expect(AppleOnDevice.cost('สวัสดี'), 6 * 4); + final p = AppleOnDevice.buildPrompt([ + {'role': 'user', 'content': 'นอนหลับ' * 2000}, + {'role': 'assistant', 'content': '你好' * 500}, + {'role': 'user', 'content': 'วันนี้ล่ะ?'}, + ]); + expect(p.endsWith('Now: วันนี้ล่ะ?'), isTrue); + expect(AppleOnDevice.cost(p), + lessThanOrEqualTo(AppleOnDevice.promptBudget + 40)); + expect(p.runes.length, lessThan(AppleOnDevice.promptBudget ~/ 3)); + }); + + test('native error codes become translatable messages', () { + expect(AppleOnDevice.errorMessage('tooLong'), kAppleTooLongMessage); + expect(AppleOnDevice.errorMessage('declined'), kAppleDeclinedMessage); + expect(AppleOnDevice.errorMessage('timeout'), kAppleTimeoutMessage); + expect(AppleOnDevice.errorMessage('notEnabled'), + AppleAiStatus.notEnabled.message); + expect(AppleOnDevice.errorMessage('anything else'), kAppleFailedMessage); + }); + + group('reply over the channel', () { + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_channel, null); + AppleOnDevice.respondTimeout = const Duration(seconds: 75); + _lastArgs = null; + }); + + test('an ECG analysis is refused, not answered without the waveform', + () async { + _mockRespond(() async => 'an answer'); + await expectLater( + AppleOnDevice.reply(_coachBody(ecgAnalyzePrompt('r1'))), + throwsA(isA() + .having((e) => e.message, 'message', kAppleNoEcgMessage)), + ); + expect(_lastArgs, isNull, reason: 'the model was never asked'); + }); + + test('a bridge that never answers times out with a clear message', + () async { + AppleOnDevice.respondTimeout = const Duration(milliseconds: 50); + _mockRespond(() => Completer().future); + await expectLater( + AppleOnDevice.reply({ + 'messages': [ + {'role': 'user', 'content': 'hi'}, + ], + }), + throwsA(isA() + .having((e) => e.message, 'message', kAppleTimeoutMessage)), + ); + }); + + test('a native error code reaches the user as its message', () async { + _mockRespond(() async => + throw PlatformException(code: 'tooLong', message: 'detail')); + await expectLater( + AppleOnDevice.reply({ + 'messages': [ + {'role': 'user', 'content': 'hi'}, + ], + }), + throwsA(isA() + .having((e) => e.message, 'message', kAppleTooLongMessage)), + ); + }); + + test('an empty answer is an error, not a blank reply', () async { + _mockRespond(() async => ' '); + await expectLater( + AppleOnDevice.reply({ + 'messages': [ + {'role': 'user', 'content': 'hi'}, + ], + }), + throwsA(isA()), + ); + }); + }); + + group('snapshot', () { + setUpAll(() async { + sqfliteFfiInit(); + databaseFactory = databaseFactoryFfi; + LocalDb.dbName = 'openstrap_coach_apple_test.db'; + await databaseFactory.deleteDatabase( + p.join(await databaseFactory.getDatabasesPath(), LocalDb.dbName), + ); + }); + tearDownAll(() async { + await CoachDb.close(); + await LocalDb.close(); + await databaseFactory.deleteDatabase( + p.join(await databaseFactory.getDatabasesPath(), LocalDb.dbName), + ); + }); + setUp(() async { + final db = await LocalDb.instance; + await db.delete('metric_series'); + }); + tearDown(() { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger + .setMockMethodCallHandler(_channel, null); + _lastArgs = null; + }); + + Future seed(Map readinessByDay) async { + final db = await LocalDb.instance; + for (final e in readinessByDay.entries) { + await db.insert('metric_series', + {'date': e.key, 'key': 'readiness', 'value': e.value}); + } + } + + Future instructionsFor(({String day, num? readiness}) today) async { + _mockRespond(() async => 'ok'); + await AppleOnDevice.reply(_coachBody('How am I today?'), + today: () async => today); + return _lastArgs!['instructions'] as String; + } + + test('TODAY is today, with the headline readiness, never a stale row', + () async { + // Today's stored readiness is a mid-sync partial (80); Home shows 77. + await seed({'2026-03-10': 80, '2026-03-09': 60}); + final ins = + await instructionsFor((day: '2026-03-10', readiness: 77)); + final todayLine = + ins.split('\n').firstWhere((l) => l.startsWith('TODAY')); + expect(todayLine, contains('2026-03-10')); + expect(todayLine, contains('77')); + expect(todayLine, isNot(contains('80'))); + }); + + test('no row for today says so instead of using yesterday', () async { + await seed({'2026-03-09': 60}); + final ins = + await instructionsFor((day: '2026-03-10', readiness: null)); + final todayLine = + ins.split('\n').firstWhere((l) => l.startsWith('TODAY')); + expect(todayLine, contains('no data for today yet')); + expect(todayLine, isNot(contains('2026-03-09'))); + }); + + test('the week averages follow calendar days across gaps and DST', + () async { + // Gaps in both weeks, a DST change (US, 2026-03-08) inside the window, + // and an old row that 14-newest-rows would have pulled in. + await seed({ + '2026-03-10': 50, '2026-03-08': 50, '2026-03-04': 50, // last 7 days + '2026-03-03': 70, '2026-02-28': 70, '2026-02-25': 70, // the 7 before + '2026-02-01': 10, // outside the 14 days + }); + final ins = + await instructionsFor((day: '2026-03-10', readiness: 50)); + final weekLine = + ins.split('\n').firstWhere((l) => l.startsWith('THE WEEK')); + expect(weekLine, contains('last 7 days')); + expect(weekLine, contains('the 7 days before')); + expect(weekLine, contains('50')); + expect(weekLine, contains('70')); + expect(weekLine, isNot(contains('10'))); + expect(ins, isNot(contains('2026-02-01'))); + }); + }); +} diff --git a/test/coach_config_key_test.dart b/test/coach_config_key_test.dart index 981ae155e..a0b0ae86f 100644 --- a/test/coach_config_key_test.dart +++ b/test/coach_config_key_test.dart @@ -150,6 +150,26 @@ void main() { expect(relaunched.keyUnreadable, isFalse); }); + test('an unreadable saved key does not hide the Apple on-device chat', + () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + final saved = CoachConfig(); + await saved.save(apiKey: 'sk-test', model: 'gpt-4o'); + await saved.save(useApple: true); + + keychain.locked = true; + final relaunched = CoachConfig(); + await relaunched.load(); + expect(relaunched.usesApple, isTrue); + expect(relaunched.keyUnreadable, isFalse, + reason: 'Apple needs no key, so the warning must not replace its chat'); + + // Switched back, the saved provider's state is reported again. + await relaunched.save(useApple: false); + expect(relaunched.keyUnreadable, isTrue); + }); + test('a read that throws does not erase a key already in memory', () async { final cfg = CoachConfig(); await cfg.save(apiKey: 'sk-test', model: 'gpt-4o'); @@ -272,6 +292,26 @@ void main() { reason: 'the state must be pending BEFORE the read, not after it'); }); + test('a restored Apple choice is published without waiting on the keychain', + () async { + debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + addTearDown(() => debugDefaultTargetPlatformOverride = null); + await CoachConfig().save(useApple: true); + + keychain.hangReads = true; + final relaunched = CoachConfig(); + var notified = false; + relaunched.addListener(() => notified = true); + unawaited(relaunched.load()); + await Future.delayed(const Duration(milliseconds: 20)); + + expect(relaunched.usesApple, isTrue); + expect(relaunched.configured, isTrue); + expect(notified, isTrue, + reason: 'the coach must not sit on "not set up" behind a hung read'); + keychain.releaseHung(); + }); + test('a save during an in-flight load is not clobbered by it', () async { keychain.hangReads = true; final cfg = CoachConfig();