From 19e74819e75af376c76b3f3676d248b7dad277da Mon Sep 17 00:00:00 2001 From: vn572rzb8w-design Date: Sat, 21 Nov 2026 21:02:24 +0400 Subject: [PATCH 1/7] AI: Apple's on-device model as a provider (Foundation Models) A switch in AI settings routes the coach, briefings and journal to Apple's on-device model: no key, no network, nothing leaves the phone. The coach gets a short prompt with today's numbers, weekly averages and the last two weeks (read through the same guarded SQL), sized for the model's window. Shows why it is unavailable (Apple Intelligence off, model downloading, older iOS). Co-Authored-By: Claude Opus 5.5 --- ios/Runner/AppDelegate.swift | 110 ++++++++++++++++++++ lib/coach/coach_apple.dart | 195 +++++++++++++++++++++++++++++++++++ lib/coach/coach_config.dart | 34 ++++-- lib/coach/coach_engine.dart | 9 ++ lib/ui2/screens/coach.dart | 80 +++++++++++++- test/coach_apple_test.dart | 46 +++++++++ 6 files changed, 463 insertions(+), 11 deletions(-) create mode 100644 lib/coach/coach_apple.dart create mode 100644 test/coach_apple_test.dart diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index 384db0ee9..fab640867 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,106 @@ 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 message is shown to the user. +enum AppleIntelligenceBridge { + private static let channelName = "openstrap/apple_ai" + + 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 + Task { + let out = await respond(instructions: instructions, prompt: prompt, + temperature: temperature) + DispatchQueue.main.async { + switch out { + case .success(let text): result(text) + case .failure(let message): + result(FlutterError(code: "apple_ai", message: message, details: nil)) + } + } + } + default: + result(FlutterMethodNotImplemented) + } + } + } + + enum Outcome { case success(String), failure(String) } + + 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(unavailableMessage(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("That was too long for Apple's on-device model. Start a new chat or ask a shorter question.") + case .guardrailViolation: + return .failure("Apple's on-device model declined to answer that. Try wording it differently.") + default: + return .failure("Apple's on-device model couldn't answer: \(error.localizedDescription)") + } + } catch { + return .failure("Apple's on-device model couldn't answer: \(error.localizedDescription)") + } + } + #endif + return .failure(unavailableMessage("unsupportedOS")) + } + + static func unavailableMessage(_ state: String) -> String { + switch state { + case "notEnabled": + return "Turn on Apple Intelligence in Settings to use the on-device model." + case "notReady": + return "Apple's on-device model is still downloading. Try again in a little while." + case "deviceNotEligible": + return "This iPhone can't run Apple's on-device model." + default: + return "Apple's on-device model needs iOS 26 or later with Apple Intelligence." + } + } +} diff --git a/lib/coach/coach_apple.dart b/lib/coach/coach_apple.dart new file mode 100644 index 000000000..80680388f --- /dev/null +++ b/lib/coach/coach_apple.dart @@ -0,0 +1,195 @@ +// 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 'package:flutter/foundation.dart'; +import 'package:flutter/services.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.', + }; +} + +class AppleOnDevice { + AppleOnDevice._(); + + static const _ch = MethodChannel('openstrap/apple_ai'); + + /// Budgets in characters (≈3.5 per token): the model's window holds the + /// instructions, the prompt AND its answer. + static const int instructionBudget = 3200; + static const int promptBudget = 4200; + + 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. + static Future> reply(Map body) 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; + final instructions = isCoach + ? '$kAppleCoachInstructions\n\n${await _snapshot()}' + : _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(); + try { + final text = await _ch.invokeMethod('respond', { + 'instructions': _clip(instructions, instructionBudget + 2600, + keepEnd: false), + 'prompt': prompt, + 'temperature': ?temperature, + }); + return {'content': (text ?? '').trim()}; + } on PlatformException catch (e) { + throw StateError(e.message ?? 'Apple’s on-device model couldn’t answer.'); + } on MissingPluginException { + throw StateError(AppleAiStatus.unsupported.message); + } + } + + /// 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 - last.length - 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'; + } + + static String _clip(String s, int max, {bool keepEnd = true}) { + if (s.length <= max) return s; + return keepEnd + ? '…${s.substring(s.length - max + 1)}' + : '${s.substring(0, max - 1)}…'; + } + + /// The last 14 days from the coach's own guarded read-only view. + static Future _snapshot() async { + try { + 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 ' + 'ORDER BY date DESC LIMIT 14', + rowCap: 14); + final week = await CoachDb.runCoachSql( + 'WITH d AS (SELECT date, readiness, strain, sleep_min, resting_hr, ' + 'hrv FROM v_daily ORDER BY date DESC LIMIT 14), n AS (SELECT *, ' + 'ROW_NUMBER() OVER (ORDER BY date DESC) AS i FROM d) ' + "SELECT CASE WHEN i <= 7 THEN 'this week' ELSE 'last week' END AS " + 'week, 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 n GROUP BY 1', + rowCap: 2); + final today = await CoachDb.runCoachSql( + 'SELECT date, readiness AS recovery, strain, sleep_min, resting_hr, ' + 'hrv FROM v_daily ORDER BY date DESC LIMIT 1', + rowCap: 1); + return 'TODAY: ${_clip(today, 300, keepEnd: false)}\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).'; + } + } +} + +/// 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. 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.'''; diff --git a/lib/coach/coach_config.dart b/lib/coach/coach_config.dart index bef899e2c..d0746a3ee 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,12 @@ 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 && !_useApple; + + /// 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; + bool get usesApple => _useApple; String _baseUrl = defaultBaseUrl; CoachApi _api = CoachApi.defaultFor(defaultBaseUrl); @@ -256,8 +266,8 @@ 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 => _useApple ? kAppleOnDeviceModel : _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 +288,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 => _useApple || 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 => _useApple || isPrivateCoachHost(apiBase); - bool get configured => _useChatGpt + bool get configured => _useApple + ? 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 => + _useApple ? true : (_useChatGpt ? configured : hasKey); /// Normalised base, no trailing slash. String get apiBase { + if (_useApple) return kAppleOnDeviceBase; if (_useChatGpt) return kChatGptApiBase; var b = _baseUrl.trim(); while (b.endsWith('/')) { @@ -313,6 +327,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, @@ -422,6 +437,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 +494,10 @@ class CoachConfig extends ChangeNotifier { _keyUnreadable = false; _keyUndetermined = false; } + if (useApple != null) { + _useApple = useApple; + await prefs.setBool(_kUseApple, 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..298b94941 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'; @@ -875,6 +876,14 @@ class CoachEngine { Map body, { http.Client? client, }) async { + // Apple's on-device model: no HTTP, nothing leaves the phone. + if (config.usesApple) { + try { + return await AppleOnDevice.reply(body); + } 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/ui2/screens/coach.dart b/lib/ui2/screens/coach.dart index faefdb557..e98cbc048 100644 --- a/lib/ui2/screens/coach.dart +++ b/lib/ui2/screens/coach.dart @@ -22,6 +22,7 @@ import 'coach_text.dart'; import '../../data/db.dart'; import '../../l10n/display_text.dart'; 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'; @@ -484,9 +485,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), @@ -938,6 +939,11 @@ 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; 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 @@ -977,6 +983,10 @@ class _CoachSetupState extends State { _timeout = TextEditingController(text: cfg.timeoutSeconds.toString()); _api = cfg.api; _chatgpt = cfg.usesChatGpt; + _apple = cfg.usesApple; + AppleOnDevice.status().then((st) { + if (mounted) setState(() => _appleStatus = st); + }); _chatgptAuth = cfg.chatgpt; _model = cfg.model; _keyOrigin = coachEndpointOrigin(cfg.baseUrl); @@ -1375,6 +1385,64 @@ 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, + onChanged: (on) async { + if (on && st != null && !ready) { + setState(() => _msg = st.message); + return; + } + await context.read().save(useApple: on); + if (mounted) setState(() => _apple = on); + }, + ), + ]), + 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 (_apple && _msg != null) ...[ + const SizedBox(height: S.x2), + Text(_msg!, style: F.cap.copyWith(color: p.on(C.red))), + ], + ]), + ); + } + @override Widget build(BuildContext c) { final p = P.of(c); @@ -1400,7 +1468,9 @@ class _CoachSetupState extends State { child: ListView( padding: pad, children: [ - Section( + _appleCard(c, p), + const SizedBox(height: S.x4), + if (!_apple) Section( l?.coachWhereModelRuns ?? 'Where the model runs', Column( children: [ @@ -1414,7 +1484,9 @@ class _CoachSetupState extends State { ], ), ), - if (_chatgpt) + if (_apple) + const SizedBox.shrink() + else if (_chatgpt) ..._chatGptFields(c, p) else ...[ const SizedBox(height: S.x2), diff --git a/test/coach_apple_test.dart b/test/coach_apple_test.dart new file mode 100644 index 000000000..a08c5da81 --- /dev/null +++ b/test/coach_apple_test.dart @@ -0,0 +1,46 @@ +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:shared_preferences/shared_preferences.dart'; + +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 { + 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); + }); +} From 0772870c9e50c3a9ef58657b490b971e7b7a026a Mon Sep 17 00:00:00 2001 From: vn572rzb8w-design Date: Sat, 21 Nov 2026 21:50:42 +0400 Subject: [PATCH 2/7] AI settings: with Apple on-device on, hide the endpoint, model list and Save They belong to the bring-your-own-model route; with Apple chosen, List models hit OpenAI with no key and its 401 showed inside the Apple card. Co-Authored-By: Claude Opus 5.5 --- lib/ui2/screens/coach.dart | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/lib/ui2/screens/coach.dart b/lib/ui2/screens/coach.dart index e98cbc048..e4f21a337 100644 --- a/lib/ui2/screens/coach.dart +++ b/lib/ui2/screens/coach.dart @@ -944,6 +944,7 @@ class _CoachSetupState extends State { /// 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 @@ -1414,11 +1415,17 @@ class _CoachSetupState extends State { value: _apple, onChanged: (on) async { if (on && st != null && !ready) { - setState(() => _msg = st.message); + setState(() => _appleMsg = st.message); return; } await context.read().save(useApple: on); - if (mounted) setState(() => _apple = on); + if (mounted) { + setState(() { + _apple = on; + _appleMsg = null; + _msg = null; + }); + } }, ), ]), @@ -1435,9 +1442,9 @@ class _CoachSetupState extends State { '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 (_apple && _msg != null) ...[ + if (_appleMsg != null) ...[ const SizedBox(height: S.x2), - Text(_msg!, style: F.cap.copyWith(color: p.on(C.red))), + Text(_appleMsg!, style: F.cap.copyWith(color: p.on(C.red))), ], ]), ); @@ -1568,6 +1575,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'), @@ -1662,6 +1671,7 @@ class _CoachSetupState extends State { color: kCoachAccent, onTap: _save, ), + ], // end of the bring-your-own-model fields ], ), ), From 9d22c3a76055b659d8572a81c8f958fb08f82c23 Mon Sep 17 00:00:00 2001 From: obinfalah1 Date: Sun, 22 Nov 2026 11:21:54 +0400 Subject: [PATCH 3/7] AI: Apple on-device is iPhone-only, and translated The settings card and the routing only apply on iOS (a restored setting elsewhere is ignored), and its text has de/es/fr/hi/ru/th/zh strings. Co-Authored-By: Claude Opus 5.5 --- lib/coach/coach_config.dart | 5 ++++- lib/l10n/app_de.arb | 11 ++++++++++- lib/l10n/app_en.arb | 36 ++++++++++++++++++++++++++++++++++++ lib/l10n/app_es.arb | 11 ++++++++++- lib/l10n/app_fr.arb | 11 ++++++++++- lib/l10n/app_hi.arb | 11 ++++++++++- lib/l10n/app_ru.arb | 11 ++++++++++- lib/l10n/app_th.arb | 11 ++++++++++- lib/l10n/app_zh.arb | 11 ++++++++++- lib/l10n/display_text.dart | 9 +++++++++ lib/ui2/screens/coach.dart | 8 ++++++-- test/coach_apple_test.dart | 11 +++++++++++ 12 files changed, 136 insertions(+), 10 deletions(-) diff --git a/lib/coach/coach_config.dart b/lib/coach/coach_config.dart index d0746a3ee..172953bbd 100644 --- a/lib/coach/coach_config.dart +++ b/lib/coach/coach_config.dart @@ -198,7 +198,10 @@ class CoachConfig extends ChangeNotifier { /// 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; - bool get usesApple => _useApple; + /// 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); diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 1da0cdda3..5f775c652 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -4022,5 +4022,14 @@ "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." } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 4fc2ce9fa..c19e651b4 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -18301,5 +18301,41 @@ "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." } } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 874a62c7e..f50fb9f9b 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -4022,5 +4022,14 @@ "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." } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 7decd45a8..403c92cf1 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -4022,5 +4022,14 @@ "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." } diff --git a/lib/l10n/app_hi.arb b/lib/l10n/app_hi.arb index 14b5d6923..d6c9fa3f9 100644 --- a/lib/l10n/app_hi.arb +++ b/lib/l10n/app_hi.arb @@ -4022,5 +4022,14 @@ "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 चाहिए।" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 205e4e670..52e766ffa 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -9158,5 +9158,14 @@ }, "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 или новее." } diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index 9b423d891..7bd3ad602 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -17332,5 +17332,14 @@ "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 ขึ้นไป" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 9f2f25c5f..2758e2dc5 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -4022,5 +4022,14 @@ "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。" } diff --git a/lib/l10n/display_text.dart b/lib/l10n/display_text.dart index 3dcc7bc05..8ae87a629 100644 --- a/lib/l10n/display_text.dart +++ b/lib/l10n/display_text.dart @@ -155,6 +155,15 @@ 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, "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/screens/coach.dart b/lib/ui2/screens/coach.dart index e4f21a337..5c1633638 100644 --- a/lib/ui2/screens/coach.dart +++ b/lib/ui2/screens/coach.dart @@ -21,6 +21,7 @@ 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'; @@ -1475,8 +1476,11 @@ class _CoachSetupState extends State { child: ListView( padding: pad, children: [ - _appleCard(c, p), - const SizedBox(height: S.x4), + // 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( diff --git a/test/coach_apple_test.dart b/test/coach_apple_test.dart index a08c5da81..6dc390fdc 100644 --- a/test/coach_apple_test.dart +++ b/test/coach_apple_test.dart @@ -1,3 +1,4 @@ +import 'package:flutter/foundation.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:openstrap_edge/coach/coach_apple.dart'; import 'package:openstrap_edge/coach/coach_config.dart'; @@ -28,6 +29,8 @@ void main() { }); 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(); @@ -43,4 +46,12 @@ void main() { 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); + }); } From b2fd26bdd566bebac49b375f8e4a1d91d8bb1746 Mon Sep 17 00:00:00 2001 From: obinfalah1 Date: Sun, 22 Nov 2026 13:51:09 +0400 Subject: [PATCH 4/7] AI: harden the Apple on-device route after review - Use the iOS-only usesApple in every route getter (configured, remindersConfigured, apiBase, model, isLocal/isPrivateEndpoint, provider precedence). - Snapshot: TODAY is today's local date with the headline readiness the engine passes to run_sql; week averages use calendar windows. - Refuse ECG analysis on this route with a clear message. - Timeout on the native respond call (60 s native, Dart backstop); the bridge returns error codes that Dart maps to translated messages. - Setup: switch disabled until availability is known, re-checked before turning on and on resume; refusal translated; switching off restores the saved ChatGPT/model choice; pref persisted before in-memory state. - coach_use_apple in the backup type registry and settings audit test. - Briefing disclosure treats apple://on-device as local. - Budget non-Latin text at 4x per character. - Apple starters limited to questions the route can answer. --- ios/Runner/AppDelegate.swift | 69 ++++-- lib/coach/coach_apple.dart | 170 +++++++++++--- lib/coach/coach_config.dart | 25 ++- lib/coach/coach_engine.dart | 5 +- lib/data/backup_extras.dart | 1 + lib/l10n/app_de.arb | 7 +- lib/l10n/app_en.arb | 20 ++ lib/l10n/app_es.arb | 7 +- lib/l10n/app_fr.arb | 7 +- lib/l10n/app_hi.arb | 7 +- lib/l10n/app_ru.arb | 7 +- lib/l10n/app_th.arb | 7 +- lib/l10n/app_zh.arb | 7 +- lib/l10n/display_text.dart | 5 + lib/ui2/screens/ai_briefing.dart | 6 +- lib/ui2/screens/coach.dart | 93 ++++++-- test/backup/settings_audit_guard_test.dart | 2 +- test/coach_apple_test.dart | 245 +++++++++++++++++++++ 18 files changed, 594 insertions(+), 96 deletions(-) diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index fab640867..e736ca23b 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -393,10 +393,16 @@ enum AppIconBridge { /// /// `status` → "available" | "notEnabled" | "notReady" | "deviceNotEligible" | /// "unsupportedOS". `respond` takes {instructions, prompt, temperature} and -/// returns the text, or a FlutterError whose message is shown to the user. +/// 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 @@ -408,15 +414,15 @@ enum AppleIntelligenceBridge { let instructions = args["instructions"] as? String ?? "" let prompt = args["prompt"] as? String ?? "" let temperature = args["temperature"] as? Double - Task { + let reply = ReplyOnce(result) + let work = Task { let out = await respond(instructions: instructions, prompt: prompt, temperature: temperature) - DispatchQueue.main.async { - switch out { - case .success(let text): result(text) - case .failure(let message): - result(FlutterError(code: "apple_ai", message: message, details: nil)) - } + 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: @@ -425,7 +431,26 @@ enum AppleIntelligenceBridge { } } - enum Outcome { case success(String), failure(String) } + 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) @@ -452,7 +477,9 @@ enum AppleIntelligenceBridge { #if canImport(FoundationModels) if #available(iOS 26.0, *) { let state = status() - guard state == "available" else { return .failure(unavailableMessage(state)) } + guard state == "available" else { + return .failure(code: unavailableCode(state), detail: state) + } do { let session = LanguageModelSession(instructions: instructions) let options = GenerationOptions(temperature: temperature) @@ -461,30 +488,26 @@ enum AppleIntelligenceBridge { } catch let error as LanguageModelSession.GenerationError { switch error { case .exceededContextWindowSize: - return .failure("That was too long for Apple's on-device model. Start a new chat or ask a shorter question.") + return .failure(code: "tooLong", detail: error.localizedDescription) case .guardrailViolation: - return .failure("Apple's on-device model declined to answer that. Try wording it differently.") + return .failure(code: "declined", detail: error.localizedDescription) default: - return .failure("Apple's on-device model couldn't answer: \(error.localizedDescription)") + return .failure(code: "failed", detail: error.localizedDescription) } } catch { - return .failure("Apple's on-device model couldn't answer: \(error.localizedDescription)") + return .failure(code: "failed", detail: error.localizedDescription) } } #endif - return .failure(unavailableMessage("unsupportedOS")) + return .failure(code: "unsupported", detail: "unsupportedOS") } - static func unavailableMessage(_ state: String) -> String { + static func unavailableCode(_ state: String) -> String { switch state { - case "notEnabled": - return "Turn on Apple Intelligence in Settings to use the on-device model." - case "notReady": - return "Apple's on-device model is still downloading. Try again in a little while." - case "deviceNotEligible": - return "This iPhone can't run Apple's on-device model." + case "notEnabled", "notReady", "deviceNotEligible": + return state default: - return "Apple's on-device model needs iOS 26 or later with Apple Intelligence." + return "unsupported" } } } diff --git a/lib/coach/coach_apple.dart b/lib/coach/coach_apple.dart index 80680388f..33332ac16 100644 --- a/lib/coach/coach_apple.dart +++ b/lib/coach/coach_apple.dart @@ -12,9 +12,13 @@ // 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 { @@ -45,16 +49,50 @@ enum AppleAiStatus { }; } +/// 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 characters (≈3.5 per token): the model's window holds the - /// instructions, the prompt AND its answer. + /// 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; @@ -69,14 +107,26 @@ class AppleOnDevice { /// 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. - static Future> reply(Map body) async { + /// + /// [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()}' + ? '$kAppleCoachInstructions\n\n' + '${await _snapshot(today == null ? null : await today())}' : _clip( messages .where((m) => m['role'] == 'system') @@ -86,19 +136,48 @@ class AppleOnDevice { keepEnd: false); final prompt = buildPrompt(messages); final temperature = (body['temperature'] as num?)?.toDouble(); + final String? text; try { - final text = await _ch.invokeMethod('respond', { + text = await _ch.invokeMethod('respond', { 'instructions': _clip(instructions, instructionBudget + 2600, keepEnd: false), 'prompt': prompt, 'temperature': ?temperature, - }); - return {'content': (text ?? '').trim()}; + }).timeout(respondTimeout); + } on TimeoutException { + throw StateError(kAppleTimeoutMessage); } on PlatformException catch (e) { - throw StateError(e.message ?? 'Apple’s on-device model couldn’t answer.'); + 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 @@ -117,7 +196,7 @@ class AppleOnDevice { if (turns.length == 1) return _clip(turns.single, promptBudget); final last = turns.removeLast(); final history = turns.join('\n\n'); - final room = promptBudget - last.length - 40; + final room = promptBudget - cost(last) - 40; return room <= 200 ? _clip(last, promptBudget) : 'Earlier in this chat:\n${_clip(history, room)}\n\nNow: $last'; @@ -133,35 +212,53 @@ class AppleOnDevice { 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 (s.length <= max) return s; - return keepEnd - ? '…${s.substring(s.length - max + 1)}' - : '${s.substring(0, max - 1)}…'; + 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 days from the coach's own guarded read-only view. - static Future _snapshot() async { + /// 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 ' - 'ORDER BY date DESC LIMIT 14', - rowCap: 14); + "WHERE date BETWEEN '$d13' AND '$d0' ORDER BY date DESC LIMIT 14", + rowCap: 14, + today: today); final week = await CoachDb.runCoachSql( - 'WITH d AS (SELECT date, readiness, strain, sleep_min, resting_hr, ' - 'hrv FROM v_daily ORDER BY date DESC LIMIT 14), n AS (SELECT *, ' - 'ROW_NUMBER() OVER (ORDER BY date DESC) AS i FROM d) ' - "SELECT CASE WHEN i <= 7 THEN 'this week' ELSE 'last week' END AS " - 'week, 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 n GROUP BY 1', - rowCap: 2); - final today = 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 ORDER BY date DESC LIMIT 1', - rowCap: 1); - return 'TODAY: ${_clip(today, 300, keepEnd: false)}\n' + "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 ' @@ -171,6 +268,15 @@ class AppleOnDevice { 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. @@ -186,10 +292,10 @@ HRV and habits, using ONLY the data below. Rules: 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. Use THE WEEK for "this - week vs last". +- 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.'''; + 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 172953bbd..6d6d11cbb 100644 --- a/lib/coach/coach_config.dart +++ b/lib/coach/coach_config.dart @@ -193,7 +193,7 @@ class CoachConfig extends ChangeNotifier { /// the BYOK settings are kept untouched for switching back. final ChatGptAuth chatgpt; bool _useChatGpt = false; - bool get usesChatGpt => _useChatGpt && !_useApple; + 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. @@ -270,7 +270,12 @@ class CoachConfig extends ChangeNotifier { String get baseUrl => _baseUrl; CoachApi get api => usesChatGpt ? CoachApi.responses : _api; - String get model => _useApple ? kAppleOnDeviceModel : _model; + 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 @@ -291,14 +296,14 @@ 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 => _useApple || 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 => _useApple || isPrivateCoachHost(apiBase); + bool get isPrivateEndpoint => usesApple || isPrivateCoachHost(apiBase); - bool get configured => _useApple + bool get configured => usesApple ? true : _useChatGpt ? chatgpt.sharing && _model.isNotEmpty @@ -308,11 +313,11 @@ class CoachConfig extends ChangeNotifier { /// 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 => - _useApple ? true : (_useChatGpt ? configured : hasKey); + usesApple ? true : (_useChatGpt ? configured : hasKey); /// Normalised base, no trailing slash. String get apiBase { - if (_useApple) return kAppleOnDeviceBase; + if (usesApple) return kAppleOnDeviceBase; if (_useChatGpt) return kChatGptApiBase; var b = _baseUrl.trim(); while (b.endsWith('/')) { @@ -498,8 +503,12 @@ class CoachConfig extends ChangeNotifier { _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; - await prefs.setBool(_kUseApple, useApple); } if (useChatGpt != null) { _useChatGpt = useChatGpt; diff --git a/lib/coach/coach_engine.dart b/lib/coach/coach_engine.dart index 298b94941..d35651069 100644 --- a/lib/coach/coach_engine.dart +++ b/lib/coach/coach_engine.dart @@ -833,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 @@ -875,11 +875,12 @@ 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); + return await AppleOnDevice.reply(body, today: appleToday); } on StateError catch (e) { throw CoachException(e.message); } 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 5f775c652..8cbaf69b7 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -4031,5 +4031,10 @@ "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." + "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." } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index c19e651b4..fe019ce2d 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -18337,5 +18337,25 @@ "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." } } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index f50fb9f9b..6909d809c 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -4031,5 +4031,10 @@ "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." + "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." } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 403c92cf1..6133b411d 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -4031,5 +4031,10 @@ "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." + "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." } diff --git a/lib/l10n/app_hi.arb b/lib/l10n/app_hi.arb index d6c9fa3f9..572e6ed16 100644 --- a/lib/l10n/app_hi.arb +++ b/lib/l10n/app_hi.arb @@ -4031,5 +4031,10 @@ "coachAppleNotEnabled": "ऑन-डिवाइस मॉडल इस्तेमाल करने के लिए सेटिंग्स में Apple Intelligence चालू करें।", "coachAppleNotReady": "Apple का ऑन-डिवाइस मॉडल अभी डाउनलोड हो रहा है। बाद में फिर कोशिश करें।", "coachAppleNotEligible": "यह iPhone Apple का ऑन-डिवाइस मॉडल नहीं चला सकता।", - "coachAppleUnsupported": "iOS 26 या बाद के संस्करण पर Apple Intelligence वाला iPhone चाहिए।" + "coachAppleUnsupported": "iOS 26 या बाद के संस्करण पर Apple Intelligence वाला iPhone चाहिए।", + "coachAppleFailed": "Apple का ऑन-डिवाइस मॉडल जवाब नहीं दे सका। फिर कोशिश करें।", + "coachAppleTooLong": "यह Apple के ऑन-डिवाइस मॉडल के लिए बहुत लंबा था। नई चैट शुरू करें या छोटा सवाल पूछें।", + "coachAppleDeclined": "Apple के ऑन-डिवाइस मॉडल ने इसका जवाब देने से मना कर दिया। इसे दूसरे शब्दों में पूछकर देखें।", + "coachAppleTimeout": "Apple के ऑन-डिवाइस मॉडल ने जवाब देने में बहुत देर लगाई। फिर कोशिश करें, या छोटा सवाल पूछें।", + "coachAppleNoEcg": "Apple का ऑन-डिवाइस मॉडल ECG वेवफ़ॉर्म नहीं पढ़ सकता। इस रीडिंग का विश्लेषण करने के लिए कोच की AI सेटिंग्स में Apple Intelligence बंद करें और कोई दूसरा मॉडल इस्तेमाल करें।" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 52e766ffa..46941913f 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -9167,5 +9167,10 @@ "coachAppleNotEnabled": "Включите Apple Intelligence в Настройках, чтобы использовать модель на устройстве.", "coachAppleNotReady": "Модель Apple на устройстве ещё загружается. Попробуйте позже.", "coachAppleNotEligible": "Этот iPhone не может запускать модель Apple на устройстве.", - "coachAppleUnsupported": "Нужен iPhone с Apple Intelligence на iOS 26 или новее." + "coachAppleUnsupported": "Нужен iPhone с Apple Intelligence на iOS 26 или новее.", + "coachAppleFailed": "Модель Apple на устройстве не смогла ответить. Попробуйте ещё раз.", + "coachAppleTooLong": "Это слишком длинно для модели Apple на устройстве. Начните новый чат или задайте вопрос короче.", + "coachAppleDeclined": "Модель Apple на устройстве отказалась на это отвечать. Попробуйте сформулировать иначе.", + "coachAppleTimeout": "Модель Apple на устройстве отвечала слишком долго. Попробуйте ещё раз или задайте вопрос короче.", + "coachAppleNoEcg": "Модель Apple на устройстве не может читать кривую ЭКГ. Чтобы проанализировать эту запись, выключите Apple Intelligence в настройках ИИ коуча и используйте другую модель." } diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index 7bd3ad602..07a1cab2a 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -17341,5 +17341,10 @@ "coachAppleNotEnabled": "เปิด Apple Intelligence ในการตั้งค่าเพื่อใช้โมเดลบนอุปกรณ์", "coachAppleNotReady": "โมเดลบนอุปกรณ์ของ Apple ยังดาวน์โหลดไม่เสร็จ ลองอีกครั้งภายหลัง", "coachAppleNotEligible": "iPhone เครื่องนี้ใช้โมเดลบนอุปกรณ์ของ Apple ไม่ได้", - "coachAppleUnsupported": "ต้องใช้ iPhone ที่มี Apple Intelligence บน iOS 26 ขึ้นไป" + "coachAppleUnsupported": "ต้องใช้ iPhone ที่มี Apple Intelligence บน iOS 26 ขึ้นไป", + "coachAppleFailed": "โมเดลบนอุปกรณ์ของ Apple ตอบไม่ได้ ลองอีกครั้ง", + "coachAppleTooLong": "ข้อความนี้ยาวเกินไปสำหรับโมเดลบนอุปกรณ์ของ Apple เริ่มแชตใหม่หรือถามให้สั้นลง", + "coachAppleDeclined": "โมเดลบนอุปกรณ์ของ Apple ปฏิเสธที่จะตอบเรื่องนี้ ลองถามด้วยคำอื่น", + "coachAppleTimeout": "โมเดลบนอุปกรณ์ของ Apple ใช้เวลาตอบนานเกินไป ลองอีกครั้งหรือถามให้สั้นลง", + "coachAppleNoEcg": "โมเดลบนอุปกรณ์ของ Apple อ่านคลื่น ECG ไม่ได้ หากต้องการวิเคราะห์การวัดนี้ ให้ปิด Apple Intelligence ในการตั้งค่า AI ของโค้ชแล้วใช้โมเดลอื่น" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 2758e2dc5..2d526f534 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -4031,5 +4031,10 @@ "coachAppleNotEnabled": "在“设置”中打开 Apple 智能即可使用设备端模型。", "coachAppleNotReady": "Apple 设备端模型仍在下载,请稍后再试。", "coachAppleNotEligible": "此 iPhone 无法运行 Apple 设备端模型。", - "coachAppleUnsupported": "需要搭载 iOS 26 或更高版本并支持 Apple 智能的 iPhone。" + "coachAppleUnsupported": "需要搭载 iOS 26 或更高版本并支持 Apple 智能的 iPhone。", + "coachAppleFailed": "Apple 设备端模型无法回答,请再试一次。", + "coachAppleTooLong": "这对 Apple 设备端模型来说太长了。请开始新的对话,或问一个更短的问题。", + "coachAppleDeclined": "Apple 设备端模型拒绝回答这个问题。请换一种说法试试。", + "coachAppleTimeout": "Apple 设备端模型回答用时过长。请再试一次,或问一个更短的问题。", + "coachAppleNoEcg": "Apple 设备端模型无法读取心电图波形。要分析这条记录,请在教练的 AI 设置中关闭 Apple Intelligence,并使用其他模型。" } diff --git a/lib/l10n/display_text.dart b/lib/l10n/display_text.dart index 8ae87a629..0da401206 100644 --- a/lib/l10n/display_text.dart +++ b/lib/l10n/display_text.dart @@ -164,6 +164,11 @@ String localizedText(AppLocalizations? l, String text) { "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/screens/ai_briefing.dart b/lib/ui2/screens/ai_briefing.dart index 691086c54..73e358125 100644 --- a/lib/ui2/screens/ai_briefing.dart +++ b/lib/ui2/screens/ai_briefing.dart @@ -237,6 +237,8 @@ class SentPayload extends StatelessWidget { /// 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,7 +260,9 @@ 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 host = config.usesApple + ? kAppleOnDeviceModel + : (Uri.tryParse(config.apiBase)?.host ?? config.apiBase); final local = isLocal(config.apiBase); final keys = inputs.keys.toList()..sort(); // An empty payload is not "we sent an empty payload". The nightly sweep diff --git a/lib/ui2/screens/coach.dart b/lib/ui2/screens/coach.dart index 5c1633638..bb9f2ab62 100644 --- a/lib/ui2/screens/coach.dart +++ b/lib/ui2/screens/coach.dart @@ -124,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', @@ -930,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; @@ -983,14 +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; - AppleOnDevice.status().then((st) { - if (mounted) setState(() => _appleStatus = st); - }); + _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 @@ -1043,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(); @@ -1414,20 +1436,47 @@ class _CoachSetupState extends State { ), Switch.adaptive( value: _apple, - onChanged: (on) async { - if (on && st != null && !ready) { - setState(() => _appleMsg = st.message); - return; - } - await context.read().save(useApple: on); - if (mounted) { - setState(() { - _apple = on; - _appleMsg = null; - _msg = null; - }); - } - }, + // 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), @@ -1445,7 +1494,7 @@ class _CoachSetupState extends State { ], if (_appleMsg != null) ...[ const SizedBox(height: S.x2), - Text(_appleMsg!, style: F.cap.copyWith(color: p.on(C.red))), + Text(uiText(c, _appleMsg!), style: F.cap.copyWith(color: p.on(C.red))), ], ]), ); 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 index 6dc390fdc..52d3d9a80 100644 --- a/test/coach_apple_test.dart +++ b/test/coach_apple_test.dart @@ -1,8 +1,40 @@ +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(); @@ -54,4 +86,217 @@ void main() { 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'))); + }); + }); } From fe6d94fa5106c7f47d200424466431dd0b69ae39 Mon Sep 17 00:00:00 2001 From: obinfalah1 Date: Sun, 22 Nov 2026 14:56:19 +0400 Subject: [PATCH 5/7] AI: record each briefing's endpoint; ignore key errors on Apple - Briefing stores the endpoint (scheme, host, port only) and model it was generated with; SentPayload reads those instead of the live CoachConfig. A briefing saved before this has no endpoint and says it can't tell where it was sent, never on-device. - keyUnreadable is false while usesApple is true, so a saved provider's unreadable key does not hide the Apple chat. --- lib/ai/briefing.dart | 13 ++++++ lib/ai/briefing_engine.dart | 14 ++++++ lib/coach/coach_config.dart | 7 ++- lib/l10n/app_de.arb | 3 +- lib/l10n/app_en.arb | 4 ++ lib/l10n/app_es.arb | 3 +- lib/l10n/app_fr.arb | 3 +- lib/l10n/app_hi.arb | 3 +- lib/l10n/app_ru.arb | 3 +- lib/l10n/app_th.arb | 3 +- lib/l10n/app_zh.arb | 3 +- lib/ui2/profile/gallery.dart | 3 +- lib/ui2/screens/ai_briefing.dart | 34 ++++++++++---- test/ai_briefing_test.dart | 78 ++++++++++++++++++++++++++++++++ test/coach_config_key_test.dart | 20 ++++++++ 15 files changed, 176 insertions(+), 18 deletions(-) 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..a7be7745b 100644 --- a/lib/ai/briefing_engine.dart +++ b/lib/ai/briefing_engine.dart @@ -27,6 +27,18 @@ 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; + return '${u.scheme}://${u.host}${u.hasPort ? ':${u.port}' : ''}'; +} + /// Injectable one-shot completion (tests pass a fake; production defaults to /// [CoachEngine.completeText] — the shared BYOK plumbing). typedef BriefingComplete = Future Function({ @@ -574,6 +586,8 @@ class BriefingEngine { breakdownMd: parsed.breakdownMd, generatedAtMs: (wallNow ?? effectiveNow).millisecondsSinceEpoch, inputs: inputs, + endpoint: briefingEndpointOf(config), + model: config.model, ); // 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_config.dart b/lib/coach/coach_config.dart index 6d6d11cbb..70e8c0d05 100644 --- a/lib/coach/coach_config.dart +++ b/lib/coach/coach_config.dart @@ -214,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 diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 8cbaf69b7..211907940 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -4036,5 +4036,6 @@ "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." + "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 fe019ce2d..2e08be844 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -18357,5 +18357,9 @@ "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 6909d809c..c6aaa4835 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -4036,5 +4036,6 @@ "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." + "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 6133b411d..865b6d52b 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -4036,5 +4036,6 @@ "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." + "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 572e6ed16..4372ce0d8 100644 --- a/lib/l10n/app_hi.arb +++ b/lib/l10n/app_hi.arb @@ -4036,5 +4036,6 @@ "coachAppleTooLong": "यह Apple के ऑन-डिवाइस मॉडल के लिए बहुत लंबा था। नई चैट शुरू करें या छोटा सवाल पूछें।", "coachAppleDeclined": "Apple के ऑन-डिवाइस मॉडल ने इसका जवाब देने से मना कर दिया। इसे दूसरे शब्दों में पूछकर देखें।", "coachAppleTimeout": "Apple के ऑन-डिवाइस मॉडल ने जवाब देने में बहुत देर लगाई। फिर कोशिश करें, या छोटा सवाल पूछें।", - "coachAppleNoEcg": "Apple का ऑन-डिवाइस मॉडल ECG वेवफ़ॉर्म नहीं पढ़ सकता। इस रीडिंग का विश्लेषण करने के लिए कोच की AI सेटिंग्स में Apple Intelligence बंद करें और कोई दूसरा मॉडल इस्तेमाल करें।" + "coachAppleNoEcg": "Apple का ऑन-डिवाइस मॉडल ECG वेवफ़ॉर्म नहीं पढ़ सकता। इस रीडिंग का विश्लेषण करने के लिए कोच की AI सेटिंग्स में Apple Intelligence बंद करें और कोई दूसरा मॉडल इस्तेमाल करें।", + "aiBriefingUnknownBody": "यह नोट ऐप के यह दर्ज करने से पहले सहेजा गया था कि ब्रीफ़िंग कहाँ जाती हैं, इसलिए यह नहीं बता सकता कि ये आंकड़े कहाँ भेजे गए थे।" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 46941913f..819368f10 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -9172,5 +9172,6 @@ "coachAppleTooLong": "Это слишком длинно для модели Apple на устройстве. Начните новый чат или задайте вопрос короче.", "coachAppleDeclined": "Модель Apple на устройстве отказалась на это отвечать. Попробуйте сформулировать иначе.", "coachAppleTimeout": "Модель Apple на устройстве отвечала слишком долго. Попробуйте ещё раз или задайте вопрос короче.", - "coachAppleNoEcg": "Модель Apple на устройстве не может читать кривую ЭКГ. Чтобы проанализировать эту запись, выключите Apple Intelligence в настройках ИИ коуча и используйте другую модель." + "coachAppleNoEcg": "Модель Apple на устройстве не может читать кривую ЭКГ. Чтобы проанализировать эту запись, выключите Apple Intelligence в настройках ИИ коуча и используйте другую модель.", + "aiBriefingUnknownBody": "Эта заметка сохранена до того, как приложение стало записывать, куда уходят сводки, поэтому оно не может сказать, куда были отправлены эти данные." } diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index 07a1cab2a..7349a684f 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -17346,5 +17346,6 @@ "coachAppleTooLong": "ข้อความนี้ยาวเกินไปสำหรับโมเดลบนอุปกรณ์ของ Apple เริ่มแชตใหม่หรือถามให้สั้นลง", "coachAppleDeclined": "โมเดลบนอุปกรณ์ของ Apple ปฏิเสธที่จะตอบเรื่องนี้ ลองถามด้วยคำอื่น", "coachAppleTimeout": "โมเดลบนอุปกรณ์ของ Apple ใช้เวลาตอบนานเกินไป ลองอีกครั้งหรือถามให้สั้นลง", - "coachAppleNoEcg": "โมเดลบนอุปกรณ์ของ Apple อ่านคลื่น ECG ไม่ได้ หากต้องการวิเคราะห์การวัดนี้ ให้ปิด Apple Intelligence ในการตั้งค่า AI ของโค้ชแล้วใช้โมเดลอื่น" + "coachAppleNoEcg": "โมเดลบนอุปกรณ์ของ Apple อ่านคลื่น ECG ไม่ได้ หากต้องการวิเคราะห์การวัดนี้ ให้ปิด Apple Intelligence ในการตั้งค่า AI ของโค้ชแล้วใช้โมเดลอื่น", + "aiBriefingUnknownBody": "บันทึกนี้ถูกบันทึกไว้ก่อนที่แอปจะเริ่มจดว่าสรุปถูกส่งไปที่ใด จึงบอกไม่ได้ว่าตัวเลขเหล่านี้ถูกส่งไปที่ใด" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index 2d526f534..12f2164d2 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -4036,5 +4036,6 @@ "coachAppleTooLong": "这对 Apple 设备端模型来说太长了。请开始新的对话,或问一个更短的问题。", "coachAppleDeclined": "Apple 设备端模型拒绝回答这个问题。请换一种说法试试。", "coachAppleTimeout": "Apple 设备端模型回答用时过长。请再试一次,或问一个更短的问题。", - "coachAppleNoEcg": "Apple 设备端模型无法读取心电图波形。要分析这条记录,请在教练的 AI 设置中关闭 Apple Intelligence,并使用其他模型。" + "coachAppleNoEcg": "Apple 设备端模型无法读取心电图波形。要分析这条记录,请在教练的 AI 设置中关闭 Apple Intelligence,并使用其他模型。", + "aiBriefingUnknownBody": "这条记录保存于应用开始记录简报发送去向之前,因此无法说明这些数值被发送到了哪里。" } 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 73e358125..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,7 +238,8 @@ class SentPayload extends StatelessWidget { const SentPayload({ super.key, required this.inputs, - required this.config, + required this.endpoint, + this.model, this.asked = true, }); @@ -260,10 +268,15 @@ class SentPayload extends StatelessWidget { Widget build(BuildContext c) { final p = P.of(c); final l = AppLocalizations.of(c); - final host = config.usesApple - ? kAppleOnDeviceModel - : (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 @@ -295,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/test/ai_briefing_test.dart b/test/ai_briefing_test.dart index aa10c9561..e5effb5a6 100644 --- a/test/ai_briefing_test.dart +++ b/test/ai_briefing_test.dart @@ -2,6 +2,7 @@ // pure prompt building + response parsing, and the day+period cache round-trip. // The LLM is mocked (BriefingComplete injected) — no network. +import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:shared_preferences/shared_preferences.dart'; @@ -11,6 +12,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 +420,38 @@ 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 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 +516,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/coach_config_key_test.dart b/test/coach_config_key_test.dart index 981ae155e..42c9c223d 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'); From 1f51d72d97ba55fd4126987fdcc92819e51be9fb Mon Sep 17 00:00:00 2001 From: obinfalah1 Date: Sun, 22 Nov 2026 15:40:05 +0400 Subject: [PATCH 6/7] AI: snapshot a briefing's endpoint at request time; publish Apple early - BriefingEngine reads the endpoint and model in the same synchronous run as the request, so a provider switched while the model answers cannot relabel the briefing. Tested in both directions. - CoachConfig.load notifies as soon as a restored Apple choice is read, before the keychain read that may hang. --- lib/ai/briefing_engine.dart | 9 +++++++-- lib/coach/coach_config.dart | 3 +++ test/ai_briefing_test.dart | 33 +++++++++++++++++++++++++++++++++ test/coach_config_key_test.dart | 20 ++++++++++++++++++++ 4 files changed, 63 insertions(+), 2 deletions(-) diff --git a/lib/ai/briefing_engine.dart b/lib/ai/briefing_engine.dart index a7be7745b..70f64a999 100644 --- a/lib/ai/briefing_engine.dart +++ b/lib/ai/briefing_engine.dart @@ -568,6 +568,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( @@ -586,8 +591,8 @@ class BriefingEngine { breakdownMd: parsed.breakdownMd, generatedAtMs: (wallNow ?? effectiveNow).millisecondsSinceEpoch, inputs: inputs, - endpoint: briefingEndpointOf(config), - model: config.model, + 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_config.dart b/lib/coach/coach_config.dart index 70e8c0d05..6574d0c1c 100644 --- a/lib/coach/coach_config.dart +++ b/lib/coach/coach_config.dart @@ -359,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( diff --git a/test/ai_briefing_test.dart b/test/ai_briefing_test.dart index e5effb5a6..92db99189 100644 --- a/test/ai_briefing_test.dart +++ b/test/ai_briefing_test.dart @@ -2,6 +2,7 @@ // 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'; @@ -440,6 +441,38 @@ void main() { expect(cached?.model, 'm1'); }); + 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({ diff --git a/test/coach_config_key_test.dart b/test/coach_config_key_test.dart index 42c9c223d..a0b0ae86f 100644 --- a/test/coach_config_key_test.dart +++ b/test/coach_config_key_test.dart @@ -292,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(); From 8981dff93e2cdf69e6b9f0c65a8bfb71eaf27024 Mon Sep 17 00:00:00 2001 From: obinfalah1 Date: Sun, 22 Nov 2026 15:53:56 +0400 Subject: [PATCH 7/7] AI: keep IPv6 brackets in a briefing's recorded endpoint Built with Uri, so http://[::1]:11434 is stored as written and still reads as local. --- lib/ai/briefing_engine.dart | 4 +++- test/ai_briefing_test.dart | 14 ++++++++++++++ 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/lib/ai/briefing_engine.dart b/lib/ai/briefing_engine.dart index 70f64a999..ec138e001 100644 --- a/lib/ai/briefing_engine.dart +++ b/lib/ai/briefing_engine.dart @@ -36,7 +36,9 @@ String? briefingEndpointOf(CoachConfig config) { if (config.usesApple) return kAppleOnDeviceBase; final u = Uri.tryParse(config.apiBase.trim()); if (u == null || u.host.isEmpty) return null; - return '${u.scheme}://${u.host}${u.hasPort ? ':${u.port}' : ''}'; + // 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 diff --git a/test/ai_briefing_test.dart b/test/ai_briefing_test.dart index 92db99189..a690527c6 100644 --- a/test/ai_briefing_test.dart +++ b/test/ai_briefing_test.dart @@ -441,6 +441,20 @@ void main() { 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;