diff --git a/guides/AI_COACH.md b/guides/AI_COACH.md index a88d59b9c..55353f205 100644 --- a/guides/AI_COACH.md +++ b/guides/AI_COACH.md @@ -2,26 +2,48 @@ The AI features in OpenStrap Edge (the Coach chat, the morning and evening briefings, and the pre-sleep journal) are all powered by a model **you** -provide. There's no OpenStrap AI service. There are two ways to set it up: -paste in an API key for any OpenAI-compatible provider, or -[sign in with your ChatGPT plan](#use-your-chatgpt-plan). Either way the app -talks to that provider directly. +choose. +You can [use an API provider or a model you host](#setup-with-an-api-key), +[sign in with ChatGPT](#use-your-chatgpt-plan), or use +[Apple Intelligence](#use-apple-intelligence). Your key is stored in the device keychain/keystore and is only ever sent to the base URL you configure — never to OpenStrap. -The same goes for your data: your chat messages, and the health metrics the -coach's tools pull from the on-device database to answer them, are sent to -the provider you configure. Before enabling the feature, check that -provider's data retention and training policies — or point the app at a -model you host yourself. +When you use a cloud provider, it receives your chat messages and the +health metrics the coach reads to answer them. Check the provider's data +retention and training policies before you connect it. A model you host +receives the data at the server address you enter. + +## Open AI settings + +On **Today**, tap **Set up the coach**. To change your provider later, +tap your avatar and open **Connected apps → AI coach**. + +[Download the in-app setup walkthrough (MP4)](images/ai-coach/setup.mp4). + +The walkthrough shows one provider-choice step. Tap a provider to move on, +or scroll down to configure the provider already selected. Scroll back to +the picker to change your choice. + +## Ask your first question + +After saving a model, sync your band so the coach has data to read. +Return to **Today** and tap **Ask the coach**. +Try asking “How has my sleep been this week?” + +To review the data the app records as shared, open the Coach menu (**⋯**) +and tap **Briefing, and what was sent**. ## Use your ChatGPT plan -If you pay for ChatGPT Plus or Pro, you can skip the API key: open -**AI Coach → settings**, tap **ChatGPT** and sign in. Eligible coach, briefing and journal requests then use -the usage included in your ChatGPT plan instead of API billing. Tap **List -models** and pick one, then **Save**. +1. In **AI settings**, tap **ChatGPT**. If prompted, tap **Continue with ChatGPT**. +2. Review the terms, sign in in the browser, and allow OpenStrap to use your ChatGPT plan. +3. Back in Edge, dismiss the welcome message if it appears. Tap **List + models** if the list is empty, including when switching back to an + account you already authorized. Choose a model and tap **Save**. + +Eligible requests use your ChatGPT plan or credits balance. Before the sign-in starts, the app links OpenAI's [Terms of Use](https://openai.com/policies/terms-of-use/) and @@ -46,20 +68,26 @@ your use of ChatGPT here, so read them before you continue. OpenStrap in ChatGPT settings. The coach then stays off until you sign in again or pick another provider. -## Setup with an API key +## Use Apple Intelligence - +On a supported iPhone running iOS 26 or later, turn on Apple Intelligence +in iOS Settings. In Edge, turn on **Apple Intelligence on this iPhone** in +**AI settings**. The switch saves your choice. Apple Intelligence processes +your questions and the health data it reads on your iPhone. It can answer +questions about the last two weeks of data. -Open **AI Coach → settings** and fill in three things: +## Setup with an API key -1. **Base URL** — your provider's OpenAI-compatible endpoint (see the table - below). The app calls `{base URL}/chat/completions`, so enter the base - only, without the `/chat/completions` part. -2. **API key** — from your provider's dashboard. -3. **Model** — tap **Fetch** to pull your provider's live model list and pick - one, or just type a model id and it's used as-is. +1. In **AI settings**, choose a preset under **Where the model runs**. + Check **Base URL** against your provider's endpoint. Enter the API base URL + from the table below. +2. Paste a key from your provider's dashboard into **API key**. For a + self-hosted server, use its network address and enter a key if it requires one. +3. Tap **List models** and choose a model that supports tool calling. If the + provider returns no list, type the exact model ID in **Model**. +4. Tap **Save**. -Tap **Save** and you're done. +For OpenRouter, you can also use **Sign in with OpenRouter** to fill in the key. ## Providers @@ -68,7 +96,7 @@ Tap **Save** and you're done. You don't need a paid account to try the AI features. [OpenRouter](https://openrouter.ai) offers a set of [free models](https://openrouter.ai/collections/free-models) — sign up, create -a key, set the base URL to `https://openrouter.ai/api/v1`, tap **Fetch** and +a key, set the base URL to `https://openrouter.ai/api/v1`, tap **List models** and pick a model whose id ends in `:free`. Free models are rate-limited and vary in quality, so prefer one of the larger ones and check it supports tool calling. Running a model on your own hardware via Ollama or LM Studio (see @@ -118,13 +146,13 @@ Notes: ## Troubleshooting -- **"Enter your API key first"** — Fetch needs the key filled in before it +- **"Enter your API key first"** — List models needs the key filled in before it can list models. - **"Provider returned no models"** — the provider answered with an empty list; type the model id manually. - **"Models request failed (404)"** — the gateway doesn't implement `GET /models` (or the base URL is wrong). If the base URL checks out, - skip Fetch and type the model id manually. + skip List models and type the model id manually. - **Provider error 401/403** — wrong key, or the key isn't enabled for the model you picked. - **Provider error 404** — the base URL is usually wrong; check it against diff --git a/guides/images/ai-coach/setup.mp4 b/guides/images/ai-coach/setup.mp4 new file mode 100644 index 000000000..56b3f09d8 Binary files /dev/null and b/guides/images/ai-coach/setup.mp4 differ diff --git a/lib/ui2/guides/guide.dart b/lib/ui2/guides/guide.dart index d809ad5f1..300491635 100644 --- a/lib/ui2/guides/guide.dart +++ b/lib/ui2/guides/guide.dart @@ -113,6 +113,12 @@ class GuideStep { /// Several choices visited by the moving hand; any can perform the step. final GuideMultiTarget? multi; + /// A divider on the same screen as the previous step. Choose this step + /// when the divider passes the middle of the viewport, or when the previous + /// step's target is tapped. Scrolling back above the divider returns to the + /// previous step. The divider must stay laid out while the page scrolls. + final GuideTarget? enterBelow; + const GuideStep({ required this.id, required this.target, @@ -126,6 +132,7 @@ class GuideStep { required this.caption, this.stillCaption, this.multi, + this.enterBelow, }); /// Anchor presence for compatibility/review fixtures. The live run uses its diff --git a/lib/ui2/guides/guide_run.dart b/lib/ui2/guides/guide_run.dart index ff1975a46..2ef62d033 100644 --- a/lib/ui2/guides/guide_run.dart +++ b/lib/ui2/guides/guide_run.dart @@ -20,7 +20,7 @@ // the top page after every frame and draws its state. import 'package:flutter/foundation.dart' show ChangeNotifier, visibleForTesting; -import 'package:flutter/widgets.dart' show Element, IndexedStack; +import 'package:flutter/widgets.dart' show Axis, Element, IndexedStack, Scrollable, ScrollPosition; import '../../l10n/app_localizations.dart'; import '../app_shell.dart' show AppShell; @@ -77,6 +77,16 @@ class GuideRun extends ChangeNotifier { GuideStep? get currentStep => !_exited && _state is GuideAtStep ? variant.steps[(_state as GuideAtStep).index] : null; + /// On either side of a divider, scrolling itself chooses the active step. + bool get followsViewport { + if (_state case GuideAtStep(:final index)) { + final steps = variant.steps; + return steps[index].enterBelow != null || + (index + 1 < steps.length && steps[index + 1].enterBelow != null); + } + return false; + } + /// The index of the HIGHEST step of [variant] whose anchor resolves /// ([TargetFound]) under [root] and whose tap requirement is met; null when none does. /// ↳ CLAIM(run-match-furthest) @@ -117,6 +127,41 @@ class GuideRun extends ChangeNotifier { return onstageElements(content).skip(2).firstOrNull ?? root; } + ScrollPosition? _dividerScroll; + double? _heldAtPixels; + + int? _stepAtDivider(List exact, Element root, AppLocalizations l) { + for (final index in exact) { + final divider = variant.steps[index].enterBelow; + if (divider == null || !exact.contains(index - 1)) continue; + final box = laidOutBox(root); + if (box == null) return null; + final location = divider.resolve(root, l); + if (location is! TargetFound) return index - 1; + + final element = location.element; + final scroll = element == null ? null : Scrollable.maybeOf(element, axis: Axis.vertical)?.position; + if (!identical(scroll, _dividerScroll)) { + _dividerScroll = scroll; + _heldAtPixels = null; + } + if (location.rect.top <= box.size.height / 2) { + _heldAtPixels = null; + return index; + } + // A tap advances immediately. An upward scroll can still undo it + // before the divider reaches the middle of the screen. + final pixels = scroll?.pixels; + if (_heldAtPixels case final previous? when pixels != null && pixels >= previous) { + _heldAtPixels = pixels; + return index; + } + _heldAtPixels = null; + return index - 1; + } + return null; + } + /// Called after every frame with the top PAGE's element, or null while a /// dialog / sheet / picker is on top (the run holds its state then: the /// user is acting on the step, not leaving it). Notifies only on change. @@ -137,6 +182,7 @@ class GuideRun extends ChangeNotifier { _anchorMatches(variant.steps[i].anchor.resolve(_contentOf(topPage), l)), ); index = + _stepAtDivider(exact, _contentOf(topPage), l) ?? anchored.lastOrNull ?? (exact.contains(_lastIndex) ? _lastIndex : exact.first); } else { @@ -174,10 +220,13 @@ class GuideRun extends ChangeNotifier { if (index != null) { _lastIndex = index; _matchedPages[key] = index; + if (variant.steps[index].enterBelow == null) _heldAtPixels = null; if (_state case GuideAtStep(index: final old) when old == index) return; _state = GuideAtStep(index); } else { if (_state is GuideOffPath) return; + _heldAtPixels = null; + _dividerScroll = null; _state = GuideOffPath(_lastIndex); } notifyListeners(); @@ -187,9 +236,21 @@ class GuideRun extends ChangeNotifier { /// On any other step: no change (the next frame decides). void targetTapped() { if (_exited) return; - if (_state case GuideAtStep(:final index)) _tappedSteps.add(index); + if (_state case GuideAtStep(:final index)) { + _tappedSteps.add(index); + final next = index + 1; + if (next < variant.steps.length && variant.steps[next].enterBelow != null) { + _lastIndex = next; + _heldAtPixels = _dividerScroll?.pixels; + _state = GuideAtStep(next); + notifyListeners(); + return; + } + } if (_state case GuideAtStep(:final index) when index == variant.steps.length - 1) { _matchedPages.clear(); + _dividerScroll = null; + _heldAtPixels = null; _state = const GuideFinished(); notifyListeners(); } @@ -199,6 +260,8 @@ class GuideRun extends ChangeNotifier { void exit() { if (_exited) return; _exited = true; + _dividerScroll = null; + _heldAtPixels = null; _matchedPages.clear(); notifyListeners(); } diff --git a/lib/ui2/guides/guide_target.dart b/lib/ui2/guides/guide_target.dart index 6b5f3974f..7d7e1743f 100644 --- a/lib/ui2/guides/guide_target.dart +++ b/lib/ui2/guides/guide_target.dart @@ -32,7 +32,8 @@ final class TargetFound extends TargetResolution { final Rect rect; /// The actual control used for pointer hit-path validation by live guides. final RenderBox renderObject; - const TargetFound(this.rect, {required this.renderObject}); + final Element? element; + const TargetFound(this.rect, {required this.renderObject, this.element}); } /// No match in the built tree, but a scrollable under the root could still @@ -147,7 +148,7 @@ sealed class GuideTarget { if (w is GuideAccordionBody && w.offstage) closed.add(w); return true; }); - return closed.isEmpty ? TargetFound(rect, renderObject: laidOutBox(element)!) + return closed.isEmpty ? TargetFound(rect, renderObject: laidOutBox(element)!, element: element) : TargetBehindAccordion(this, closed.reversed.toList()); } diff --git a/lib/ui2/guides/live_guide_overlay.dart b/lib/ui2/guides/live_guide_overlay.dart index 0d60688b7..9d9593207 100644 --- a/lib/ui2/guides/live_guide_overlay.dart +++ b/lib/ui2/guides/live_guide_overlay.dart @@ -1297,7 +1297,10 @@ class LiveGuideOverlayState extends State with TickerProviderS final retry = _searchingPage == null && _scrollAtReveal == scrollSignature && ((targetNow == null && _searchSignature != signature) || (outside && _lastRevealRect != targetNow)); - if (page != null && step != null && (newStep || retry) && !_touched) { + if (page != null && step != null && widget.run.followsViewport) { + // A viewport-following step shows focus without moving the page. + if (_reveal.value != 1) _reveal.value = 1; + } else if (page != null && step != null && (newStep || retry) && !_touched) { _revealedPage = page; _revealedStep = step; _revealedHeader = accordionHop?.headerKey; diff --git a/lib/ui2/screens/coach.dart b/lib/ui2/screens/coach.dart index f9281a6e3..cd676ab28 100644 --- a/lib/ui2/screens/coach.dart +++ b/lib/ui2/screens/coach.dart @@ -934,6 +934,8 @@ List<_Preset> _presets(BuildContext c) { } class CoachSetup extends StatefulWidget { + static const providerDetailsDivider = ValueKey('coach-provider-details'); + const CoachSetup({super.key}); @override @@ -1553,220 +1555,225 @@ class _CoachSetupState extends State with WidgetsBindingObserver { sub: l?.coachSetupNavSub ?? 'Bring your own model'), ), Expanded( - child: ListView( + child: SingleChildScrollView( padding: pad, - children: [ - // Apple's on-device model exists only on iPhone (iOS 26+). - if (defaultTargetPlatform == TargetPlatform.iOS) ...[ - _appleCard(c, p), - const SizedBox(height: S.x4), - ], - if (!_apple) Section( - l?.coachWhereModelRuns ?? 'Where the model runs', - Column( - children: [ - // After the local presets: they are the only option - // where the data never leaves the user's control. - for (final preset in _presets(c).where((x) => x.local)) - _presetTile(c, p, preset), - _chatGptCard(c, p), - for (final preset in _presets(c).where((x) => !x.local)) - _presetTile(c, p, preset), - ], - ), - ), - if (_apple) - const SizedBox.shrink() - else if (_chatgpt) - ..._chatGptFields(c, p) - else ...[ - const SizedBox(height: S.x2), - OsTextField( - controller: _base, - label: l?.coachBaseUrlLabel ?? 'Base URL', - hint: 'http://localhost:11434/v1', + // Keep the picker/form boundary laid out across fast scrolls. + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Apple's on-device model exists only on iPhone (iOS 26+). + if (defaultTargetPlatform == TargetPlatform.iOS) ...[ + _appleCard(c, p), + const SizedBox(height: S.x4), + ], + if (!_apple) Section( + l?.coachWhereModelRuns ?? 'Where the model runs', + Column( + children: [ + // After the local presets: they are the only option + // where the data never leaves the user's control. + for (final preset in _presets(c).where((x) => x.local)) + _presetTile(c, p, preset), + _chatGptCard(c, p), + for (final preset in _presets(c).where((x) => !x.local)) + _presetTile(c, p, preset), + ], + ), ), - const SizedBox(height: S.x4), - Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(l?.coachApiFormatLabel ?? 'API', - style: F.over.copyWith(color: p.ink3)), - const SizedBox(height: S.x2), - Container( - padding: const EdgeInsets.symmetric(horizontal: S.x3), - decoration: BoxDecoration( - color: p.card, - borderRadius: R.rMd, - border: Border.all(color: p.line), - ), - child: Semantics( - label: l?.coachApiFormatLabel ?? 'API', - child: DropdownButtonHideUnderline( - child: DropdownButton( - value: _api, - isExpanded: true, - dropdownColor: p.card, - style: F.body.copyWith(color: p.ink), - items: const [ - DropdownMenuItem( - value: CoachApi.responses, - child: Text('Responses'), - ), - DropdownMenuItem( - value: CoachApi.chatCompletions, - child: Text('Chat Completions'), - ), - ], - onChanged: (api) { - if (api != null) setState(() => _api = api); - }, + const SizedBox(key: CoachSetup.providerDetailsDivider), + if (_apple) + const SizedBox.shrink() + else if (_chatgpt) + ..._chatGptFields(c, p) + else ...[ + const SizedBox(height: S.x2), + OsTextField( + controller: _base, + label: l?.coachBaseUrlLabel ?? 'Base URL', + hint: 'http://localhost:11434/v1', + ), + const SizedBox(height: S.x4), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(l?.coachApiFormatLabel ?? 'API', + style: F.over.copyWith(color: p.ink3)), + const SizedBox(height: S.x2), + Container( + padding: const EdgeInsets.symmetric(horizontal: S.x3), + decoration: BoxDecoration( + color: p.card, + borderRadius: R.rMd, + border: Border.all(color: p.line), + ), + child: Semantics( + label: l?.coachApiFormatLabel ?? 'API', + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: _api, + isExpanded: true, + dropdownColor: p.card, + style: F.body.copyWith(color: p.ink), + items: const [ + DropdownMenuItem( + value: CoachApi.responses, + child: Text('Responses'), + ), + DropdownMenuItem( + value: CoachApi.chatCompletions, + child: Text('Chat Completions'), + ), + ], + onChanged: (api) { + if (api != null) setState(() => _api = api); + }, + ), ), ), ), - ), - const SizedBox(height: S.x2), - Text( - l?.coachApiFormatHelp ?? - 'Choose the API your endpoint supports. Responses ' - 'supports OpenAI reasoning with tools.', - style: F.cap.copyWith(color: p.ink3, height: 1.5), + const SizedBox(height: S.x2), + Text( + l?.coachApiFormatHelp ?? + 'Choose the API your endpoint supports. Responses ' + 'supports OpenAI reasoning with tools.', + style: F.cap.copyWith(color: p.ink3, height: 1.5), + ), + ], + ), + const SizedBox(height: S.x4), + OsTextField( + controller: _key, + label: _isLocal + ? (l?.coachApiKeyLocalLabel ?? 'API key (not needed locally)') + : (l?.coachApiKeyLabel ?? 'API key'), + hint: 'sk-…', + ), + if (coachEndpointOrigin(_base.text.trim()) == 'https://openrouter.ai') ...[ + const SizedBox(height: S.x3), + BigButton( + uiText(c, 'Sign in with OpenRouter'), + icon: LucideIcons.logIn, + color: kCoachAccent, + soft: true, + onTap: _loading ? null : _signInOpenRouter, ), ], + const SizedBox(height: S.x3), + // The one sentence that decides whether a cloud key is a + // reasonable choice. It is here, next to the field, and not + // in a settings page nobody opens. Private hosts only: a + // shared-network address may be used without a key even if another device owns it. + Text( + isPrivateCoachHost(_base.text.trim()) + ? (l?.coachLocalDataNote ?? + 'Your questions and the rows the coach reads stay on ' + 'your own machine.') + : (l?.coachCloudDataNote ?? + 'Your questions and the rows the coach reads are sent ' + 'to this endpoint. See exactly what that is on ' + '"What was sent".'), + 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'), + icon: LucideIcons.refreshCw, + color: kCoachAccent, + soft: true, + onTap: _loading || + (_chatgpt && + !context.watch().chatgpt.sharing) + ? null + : _fetch, ), + if (_msg != null) ...[ + const SizedBox(height: S.x3), + Text(coachPresentationText(l, _msg!), style: F.cap.copyWith(color: p.ink3)), + ], const SizedBox(height: S.x4), OsTextField( - controller: _key, - label: _isLocal - ? (l?.coachApiKeyLocalLabel ?? 'API key (not needed locally)') - : (l?.coachApiKeyLabel ?? 'API key'), - hint: 'sk-…', + controller: _search, + label: l?.coachModelLabel ?? 'Model', + hint: l?.coachModelHint ?? 'search, or type an id', ), - if (coachEndpointOrigin(_base.text.trim()) == 'https://openrouter.ai') ...[ - const SizedBox(height: S.x3), - BigButton( - uiText(c, 'Sign in with OpenRouter'), - icon: LucideIcons.logIn, - color: kCoachAccent, - soft: true, - onTap: _loading ? null : _signInOpenRouter, + if (_model.isNotEmpty) ...[ + const SizedBox(height: S.x2), + Text( + l?.coachModelSelected(_model) ?? 'Saving model: $_model', + style: F.cap.copyWith(color: p.ink3), ), ], - const SizedBox(height: S.x3), - // The one sentence that decides whether a cloud key is a - // reasonable choice. It is here, next to the field, and not - // in a settings page nobody opens. Private hosts only: a - // 100.64.0.0/10 address needs no key but may not be yours. - Text( - isPrivateCoachHost(_base.text.trim()) - ? (l?.coachLocalDataNote ?? - 'Your questions and the rows the coach reads stay on ' - 'your own machine.') - : (l?.coachCloudDataNote ?? - 'Your questions and the rows the coach reads are sent ' - 'to this endpoint. See exactly what that is on ' - '"What was sent".'), - 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'), - icon: LucideIcons.refreshCw, - color: kCoachAccent, - soft: true, - onTap: _loading || - (_chatgpt && - !context.watch().chatgpt.sharing) - ? null - : _fetch, - ), - if (_msg != null) ...[ - const SizedBox(height: S.x3), - Text(coachPresentationText(l, _msg!), style: F.cap.copyWith(color: p.ink3)), - ], - const SizedBox(height: S.x4), - OsTextField( - controller: _search, - label: l?.coachModelLabel ?? 'Model', - hint: l?.coachModelHint ?? 'search, or type an id', - ), - if (_model.isNotEmpty) ...[ - const SizedBox(height: S.x2), - Text( - l?.coachModelSelected(_model) ?? 'Saving model: $_model', - style: F.cap.copyWith(color: p.ink3), - ), - ], - const SizedBox(height: S.x1), - Builder( - builder: (_) => Padding( - padding: const EdgeInsets.only(top: S.x2), - child: Column( - children: [ - for (final m in shown.take(60)) - Pressable( - onTap: () => setState(() => _model = m), - child: Padding( - padding: const EdgeInsets.symmetric( - vertical: S.x3, - ), - child: Row( - children: [ - Icon( - m == _model - ? LucideIcons.circleCheck - : LucideIcons.circle, - size: 16, - color: m == _model - ? p.on(kCoachAccent) - : p.ink3, - ), - const SizedBox(width: S.x3), - Expanded( - child: Text( - m, - style: F.cap.copyWith(color: p.ink), - maxLines: 1, - overflow: TextOverflow.ellipsis, + const SizedBox(height: S.x1), + Builder( + builder: (_) => Padding( + padding: const EdgeInsets.only(top: S.x2), + child: Column( + children: [ + for (final m in shown.take(60)) + Pressable( + onTap: () => setState(() => _model = m), + child: Padding( + padding: const EdgeInsets.symmetric( + vertical: S.x3, + ), + child: Row( + children: [ + Icon( + m == _model + ? LucideIcons.circleCheck + : LucideIcons.circle, + size: 16, + color: m == _model + ? p.on(kCoachAccent) + : p.ink3, ), - ), - ], + const SizedBox(width: S.x3), + Expanded( + child: Text( + m, + style: F.cap.copyWith(color: p.ink), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), ), ), - ), - ], + ], + ), ), ), - ), - if (_isLocal) ...[ - const SizedBox(height: S.x4), - OsTextField( - controller: _timeout, - label: uiText(c, 'Request timeout (seconds)'), - hint: '300', - keyboard: TextInputType.number, - ), - const SizedBox(height: S.x3), - Text( - uiText( - c, - 'A local model can take a while to load before its first reply. Default is 5 minutes (300s). Cloud providers always use 2 minutes.', + if (_isLocal) ...[ + const SizedBox(height: S.x4), + OsTextField( + controller: _timeout, + label: uiText(c, 'Request timeout (seconds)'), + hint: '300', + keyboard: TextInputType.number, ), - style: F.cap.copyWith(color: p.ink3, height: 1.5), + const SizedBox(height: S.x3), + Text( + uiText( + c, + 'A local model can take a while to load before its first reply. Default is 5 minutes (300s). Cloud providers always use 2 minutes.', + ), + style: F.cap.copyWith(color: p.ink3, height: 1.5), + ), + ], + const SizedBox(height: S.x4), + BigButton( + l?.actionSave ?? 'Save', + icon: LucideIcons.check, + color: kCoachAccent, + onTap: _save, ), + ], // end of the bring-your-own-model fields ], - const SizedBox(height: S.x4), - BigButton( - l?.actionSave ?? 'Save', - icon: LucideIcons.check, - color: kCoachAccent, - onTap: _save, - ), - ], // end of the bring-your-own-model fields - ], + ), ), ), ], diff --git a/test/ui2/coach_guide_scroll_test.dart b/test/ui2/coach_guide_scroll_test.dart new file mode 100644 index 000000000..302f53b4e --- /dev/null +++ b/test/ui2/coach_guide_scroll_test.dart @@ -0,0 +1,160 @@ +// Observe the real CoachSetup page after each scroll position change. +import 'package:flutter/material.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:provider/provider.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import 'package:openstrap_edge/coach/coach_config.dart'; +import 'package:openstrap_edge/l10n/app_localizations.dart'; +import 'package:openstrap_edge/ui2/guides/guide.dart'; +import 'package:openstrap_edge/ui2/guides/guide_navigation.dart'; +import 'package:openstrap_edge/ui2/guides/guide_run.dart'; +import 'package:openstrap_edge/ui2/guides/guide_target.dart'; +import 'package:openstrap_edge/ui2/screens/coach.dart'; +import 'package:openstrap_edge/ui2/ui2.dart'; + +import '../support/guide_text.dart'; + +final _english = lookupAppLocalizations(const Locale('en')); + +GuideRun _coachRun() { + final guide = Guide( + id: 'coach-provider-scroll', + title: fnText((_) => 'Choose a provider'), + start: GuideStart.today, + variants: [ + GuideVariant(steps: [ + GuideStep( + id: 'choose', + node: GuideNode.coachSetup, + target: GuideTarget.label(fnText((_) => 'OpenAI')), + anchor: GuideTarget.label(fnText((_) => 'OpenAI')), + action: GuideAction.tap, + caption: fnText((_) => 'Choose OpenAI'), + ), + GuideStep( + id: 'details', + node: GuideNode.coachSetup, + target: GuideTarget.label(fnText((_) => 'Base URL')), + anchor: GuideTarget.label(fnText((_) => 'Base URL')), + enterBelow: GuideTarget.key(CoachSetup.providerDetailsDivider), + action: GuideAction.scrollThenTap, + caption: fnText((_) => 'Review the provider details'), + ), + ]), + ], + ); + return GuideRun(guide: guide, variant: (guide.variantFor(null) as GuideVariantFound).variant); +} + +Future<(GuideRun, ScrollPosition)> _mount(WidgetTester t) async { + t.view.physicalSize = const Size(390, 500); + t.view.devicePixelRatio = 1; + addTearDown(t.view.reset); + final config = CoachConfig(); + addTearDown(config.dispose); + final run = _coachRun(); + addTearDown(run.dispose); + await t.pumpWidget(ChangeNotifierProvider.value( + value: config, + child: MaterialApp( + theme: buildTheme(Brightness.dark), + localizationsDelegates: AppLocalizations.localizationsDelegates, + supportedLocales: AppLocalizations.supportedLocales, + home: const CoachSetup(), + ), + )); + await t.pumpAndSettle(); + expect(find.byType(CoachSetup), findsOneWidget); + expect(GuideNavigation.location(t.element(find.byType(CoachSetup))), GuideNode.coachSetup); + final position = t.state(find.descendant( + of: find.byType(CoachSetup), + matching: find.byType(Scrollable), + ).first).position; + expect(position.maxScrollExtent, greaterThan(0)); + run.observe(t.element(find.byType(CoachSetup)), _english); + expect(run.state, isA().having((s) => s.index, 'index', 0)); + return (run, position); +} + +void _observe(WidgetTester t, GuideRun run) => + run.observe(t.element(find.byType(CoachSetup)), _english); + +void _expectStep(GuideRun run, int index) => expect( + run.state, + isA().having((s) => s.index, 'index', index), +); + +void main() { + setUp(() { + SharedPreferences.setMockInitialValues({}); + FlutterSecureStorage.setMockInitialValues({}); + }); + + testWidgets('reversing above the details divider returns to the chooser', (t) async { + // why: after a provider tap, a short downward scroll can be reversed before + // the details reach the viewport midpoint. The pending details step must + // release the chooser when the wearer moves back toward the provider rows. + // catches: treating targetTapped's pending step as permanently past the divider. + final (run, position) = await _mount(t); + await t.ensureVisible(find.text('OpenAI')); + await t.pump(); + await t.tap(find.text('OpenAI')); + await t.pumpAndSettle(); + position.jumpTo(0); + await t.pump(); + run.targetTapped(); + _expectStep(run, 1); + position.jumpTo(80); + await t.pump(); + _observe(t, run); + _expectStep(run, 1); + position.jumpTo(20); + await t.pump(); + expect(find.byKey(CoachSetup.providerDetailsDivider), findsOneWidget); + expect(t.getRect(find.byKey(CoachSetup.providerDetailsDivider)).top, + greaterThan(500 / 2), reason: 'details have not reached the viewport midpoint'); + _observe(t, run); + _expectStep(run, 0); + }); + + testWidgets('a fast jump to the bottom enters details', (t) async { + // why: ListView can unmount the zero-height divider before a frame observes + // it crossing the viewport. The visible details still mean step 2. + // catches: using the last chooser step as the side of a missing divider. + final (run, position) = await _mount(t); + position.jumpTo(position.maxScrollExtent); + await t.pump(); + expect(find.text('Save').hitTestable(), findsOneWidget, + reason: 'the provider details are the visible destination'); + _observe(t, run); + _expectStep(run, 1); + }); + + testWidgets('a fast jump back from details restores the chooser', (t) async { + // why: a jump to the top can skip the divider-crossing frame in reverse. + // The chooser is visible again even if details were the last observed step. + // catches: retaining the details side solely from the previous observation. + final (run, position) = await _mount(t); + final dividerTop = t.getRect(find.byKey(CoachSetup.providerDetailsDivider)).top; + position.jumpTo( + (dividerTop - 200).clamp(0.0, position.maxScrollExtent).toDouble(), + ); + await t.pump(); + expect(find.byKey(CoachSetup.providerDetailsDivider), findsOneWidget); + expect(t.getRect(find.byKey(CoachSetup.providerDetailsDivider)).top, + lessThan(500 / 2), reason: 'the divider has crossed into details'); + _observe(t, run); + _expectStep(run, 1); + position.jumpTo(position.maxScrollExtent); + await t.pump(); + _observe(t, run); + _expectStep(run, 1); + position.jumpTo(0); + await t.pump(); + expect(find.text('Ollama').hitTestable(), findsOneWidget); + _observe(t, run); + _expectStep(run, 0); + }); +} diff --git a/test/ui2/live_guide_overlay_test.dart b/test/ui2/live_guide_overlay_test.dart index 5203405a6..db4d1056d 100644 --- a/test/ui2/live_guide_overlay_test.dart +++ b/test/ui2/live_guide_overlay_test.dart @@ -125,6 +125,36 @@ Future _pumpOccludedTarget(WidgetTester t) async { final stage = awai last = fadeOf(t); expect(s.paintedShapes.map((x) => '${x.kind.name}@${x.rect}').toList(), first, reason: 'the shapes do not change while the dim ramps'); } await t.pump(kGuideRevealDuration); await t.pump(); expect(fadeOf(t), 1); expect(s.revealProgress, 1); expect(liveGuideFocus, findsOneWidget); expect(find.byKey(LiveGuideOverlay.tapPillKey), findsOneWidget); }); + testWidgets('direct entry into a viewport-following guide reveals focus in place', (t) async { + // A visible target needs a marker even when the guide leaves scroll position to the user. + final steps = (stageGuide().variantFor(null) as GuideVariantFound).variant.steps; + final guide = Guide( + id: 'viewport-entry', + title: fnText((_) => 'Viewport guide'), + start: GuideStart.today, + variants: [ + GuideVariant(steps: [ + steps.first, + GuideStep( + id: 'details', + target: steps.last.target, + anchor: steps.last.anchor, + enterBelow: GuideTarget.key(stageOtherAction), + action: GuideAction.tap, + caption: stageCaption2, + ), + ]), + ], + ); + final stage = await pumpLiveStage(t, guide: guide); + final target = find.byKey(stageOpenDetails); + final before = t.getRect(target); + await _settleReveal(t); + expect(stage.run.followsViewport, isTrue); + expect(_overlay(t).revealProgress, 1); + expect(liveGuideFocus, findsOneWidget); + expect(t.getRect(target), before); + }); testWidgets('a new step restarts the reveal', (t) async { // why: each step fades in; step 2 must not appear already complete. final stage = await pumpLiveStage(t); await _settleReveal(t); expect(_overlay(t).revealProgress, 1); diff --git a/tool/guides/README.md b/tool/guides/README.md index b48e0ae29..ee75522fa 100644 --- a/tool/guides/README.md +++ b/tool/guides/README.md @@ -11,3 +11,20 @@ Run them through the project Boat runner, in a separate run directory for each s `capture_activity.dart` walks the eight main-screen guides with real pointer actions. `capture_markers.dart`, `capture_chrome.dart`, `capture_hand.dart` and `capture_phone.dart` use `GUIDE_RERENDER_DIR` instead. `profile_frames.dart` prints debug frame timings and needs no output directory. The captures are review artifacts, not golden baselines. Run `python3 tool/guides/build_media.py OUTPUT_DIRECTORY` with ImageMagick available to turn the eight capture manifests into contact sheets and GIFs. + +## AI Coach capture + +From the chosen checkout, set `GUIDE_SHOTS_DIR` to a fresh output directory +and run `flutter test --no-pub tool/guides/capture_ai_coach.dart` on a Flutter test host. +The driver starts a live guide, holds on the provider picker, then taps +OpenAI once and records model setup. It captures the scroll animations as +part of the walkthrough. +It uses an isolated database and a fixture provider. + +Encode the captured 100 ms samples as an MP4: + +```sh +ffmpeg -framerate 10 -i "$GUIDE_SHOTS_DIR/ai-coach/frames/%05d.png" \ + -vf 'pad=ceil(iw/2)*2:ceil(ih/2)*2' -c:v libx264 -pix_fmt yuv420p \ + -movflags +faststart ai-coach-setup.mp4 +``` diff --git a/tool/guides/capture_ai_coach.dart b/tool/guides/capture_ai_coach.dart new file mode 100644 index 000000000..b7c8e457c --- /dev/null +++ b/tool/guides/capture_ai_coach.dart @@ -0,0 +1,252 @@ +// Opt-in capture of the real AI settings screen. The guide harness uses a +// fixture database and the provider transport never leaves the test process. +// ignore_for_file: invalid_use_of_visible_for_testing_member +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:openstrap_edge/coach/coach_config.dart'; +import 'package:openstrap_edge/data/db.dart'; +import 'package:openstrap_edge/state/prefs.dart'; +import 'package:openstrap_edge/ui2/screens/coach.dart'; +import 'package:openstrap_edge/ui2/screens/journal_compose.dart' show OsTextField; +import 'package:openstrap_edge/ui2/guides/guide.dart'; +import 'package:openstrap_edge/ui2/guides/guide_content.dart'; +import 'package:openstrap_edge/ui2/guides/guide_navigation.dart'; +import 'package:openstrap_edge/ui2/guides/guide_run.dart'; +import 'package:openstrap_edge/ui2/guides/guide_runner.dart'; +import 'package:openstrap_edge/ui2/guides/guide_target.dart'; +import 'package:openstrap_edge/ui2/guides/tree_geometry.dart'; +import 'package:openstrap_edge/l10n/app_localizations.dart'; + +import '../../test/support/bundled_fonts.dart'; +import '../../test/support/guide_r2_scenes.dart' show r2OpenDb; +import '../../test/support/live_guide_harness.dart'; +import '../../test/support/guide_text.dart'; +import '../../test/support/skeleton_fixture.dart' show skLoadAppFonts; + +const _size = Size(412, 915); +const _frameInterval = Duration(milliseconds: 100); + +const _providerNames = ['Ollama', 'LM Studio', 'ChatGPT', 'Anthropic', 'OpenRouter', 'OpenAI']; + +GuideTarget _label(String text) => GuideTarget.label(fnText((_) => text)); + +class _SettingsFields implements GuideContent { + const _SettingsFields(); + + @override + List resolve(Element root, AppLocalizations l) { + final bounds = laidOutBox(root); + if (bounds == null) return const []; + return [ + for (final element in onstageElements(root)) + if (laidOutBox(element) case final RenderBox box when element.widget is OsTextField || element.widget is Switch) + TargetFound( + rectInRoot(box, bounds).intersect(visibleBoundsInRoot(box, bounds)), + renderObject: box, + ), + ]; + } +} + +Guide _setupGuide() { + final setup = _label('Set up the coach'); + final settings = _label('AI settings'); + final choices = ContentList([ + for (final provider in _providerNames) + TargetContent(_label(provider)), + ]); + final fields = [ + const _SettingsFields(), + LabelledContent([ + for (final text in ['API', 'List models', 'Continue with ChatGPT', 'Apple Intelligence on this iPhone']) + fnText((_) => text), + ]), + ]; + return Guide( + id: 'ai-coach-setup-capture', + title: fnText((_) => 'Set up AI Coach'), + start: GuideStart.today, + variants: [ + GuideVariant(steps: [ + GuideStep( + id: 'open-settings', + node: GuideNode.today, + target: setup, + anchor: setup, + action: GuideAction.tap, + caption: fnText((_) => 'Tap **Set up the coach** on Today.'), + ), + GuideStep( + id: 'choose-provider', + node: GuideNode.coachSetup, + target: _label('Ollama'), + anchor: settings, + action: GuideAction.tap, + caption: fnText((_) => 'Choose a provider. Scroll down to use the provider already selected.'), + alsoRead: fields, + alsoTap: [choices], + multi: GuideMultiTarget(targets: choices, visit: GuideVisit.list), + ), + GuideStep( + id: 'configure-provider', + node: GuideNode.coachSetup, + target: _label('Save'), + anchor: settings, + enterBelow: GuideTarget.key(CoachSetup.providerDetailsDivider), + alsoRead: fields, + action: GuideAction.tap, + caption: fnText((_) => 'Complete your provider settings, then tap **Save**.'), + ), + ]), + ], + ); +} + +class _Capture { + _Capture(this.tester, this.key, this.directory); + + final WidgetTester tester; + final GlobalKey key; + final Directory directory; + int frame = 0; + + Future frames(int count) async { + for (var i = 0; i < count; i++) { + await tester.runAsync(() => Future.delayed(const Duration(milliseconds: 20))); + await tester.pump(_frameInterval); + await tester.pump(); + expect(tester.takeException(), isNull); + final boundary = tester.renderObject(find.byKey(key)); + final file = File('${directory.path}/${(frame++).toString().padLeft(5, '0')}.png'); + await tester.runAsync(() async { + final layer = boundary.debugLayer! as OffsetLayer; + final image = await layer.toImage(Offset.zero & _size); + try { + final bytes = await image.toByteData(format: ui.ImageByteFormat.png); + await file.writeAsBytes(bytes!.buffer.asUint8List()); + } finally { + image.dispose(); + } + }); + } + } + + Future reveal(Finder finder, Finder scrollable) async { + final position = tester.state(scrollable).position; + for (var attempt = 0; finder.evaluate().isEmpty && attempt < 12; attempt++) { + final offset = (position.pixels + position.viewportDimension * 0.45) + .clamp(position.minScrollExtent, position.maxScrollExtent) + .toDouble(); + if (offset == position.pixels) break; + final scroll = position.animateTo(offset, + duration: const Duration(milliseconds: 450), curve: Curves.easeInOut); + await frames(6); + await scroll; + } + + expect(finder, findsOneWidget); + if (finder.hitTestable().evaluate().isEmpty) { + final scroll = Scrollable.ensureVisible(tester.element(finder), + alignment: 0.35, + duration: const Duration(milliseconds: 550), + curve: Curves.easeInOut); + await frames(7); + await scroll; + } + } + + Future tap(Finder finder, {required Finder scrollable}) async { + await reveal(finder, scrollable); + expect(finder.hitTestable(), findsOneWidget); + await tester.tap(finder); + await frames(12); + } +} + +void main() { + final output = Platform.environment['GUIDE_SHOTS_DIR']; + final directory = output == null ? null : Directory('$output/ai-coach/frames'); + + setUpAll(() async { + if (directory == null) return; + await directory.create(recursive: true); + await loadFonts(); + await skLoadAppFonts(); + await r2OpenDb('guide_ai_coach_capture.db'); + }); + tearDownAll(() async { + if (directory != null) await LocalDb.close(); + }); + + testWidgets('capture AI Coach provider setup on the live app screens', (tester) async { + const apple = MethodChannel('openstrap/apple_ai'); + final messenger = TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger; + messenger.setMockMethodCallHandler(apple, (call) async { + expect(call.method, 'status'); + return 'available'; + }); + addTearDown(() => messenger.setMockMethodCallHandler(apple, null)); + FlutterSecureStorage.setMockInitialValues({}); + final config = CoachConfig(); + addTearDown(config.dispose); + final key = GlobalKey(); + final capture = _Capture(tester, key, directory!); + final client = MockClient((request) async { + expect(request.method, 'GET'); + expect(request.url.host, 'api.openai.com'); + return http.Response('{"data":[{"id":"gpt-5-mini"}]}', 200); + }); + + await http.runWithClient(() async { + final app = await pumpLiveGuideApp(tester, size: _size, captureKey: key, + brightness: Brightness.dark, coachConfig: config); + await Prefs.reload(); + final started = await app.runner.start(_setupGuide(), band: null); + expect(started, isA()); + final run = (started as GuideStarted).run; + await capture.frames(18); + await capture.tap(find.text('Set up the coach'), scrollable: find.byType(Scrollable).first); + + final screen = find.byType(CoachSetup); + expect(screen, findsOneWidget); + final scrollable = find.descendant(of: screen, matching: find.byType(Scrollable)).first; + Finder text(String label) => find.descendant(of: screen, matching: find.text(label)); + + expect(run.currentStep?.id, 'choose-provider'); + final appleCard = text('Apple Intelligence on this iPhone'); + expect(appleCard.hitTestable(), findsOneWidget); + expect(config.usesApple, isFalse); + await capture.frames(30); + expect(text('OpenAI').hitTestable(), findsOneWidget); + await tester.tap(text('OpenAI')); + await capture.frames(12); + expect(run.currentStep?.id, 'configure-provider', reason: 'a real provider tap advances'); + expect(config.configured, isFalse); + final keyInput = find.byWidgetPredicate( + (widget) => widget is OsTextField && widget.label == 'API key', + ); + final apiKey = find.descendant(of: keyInput, matching: find.byType(TextField)); + await capture.reveal(apiKey, scrollable); + await tester.enterText(apiKey, 'example-key'); + await capture.frames(10); + await capture.tap(text('List models'), scrollable: scrollable); + await capture.tap(text('gpt-5-mini'), scrollable: scrollable); + await capture.tap(text('Save'), scrollable: scrollable); + expect(config.configured, isTrue); + expect(config.baseUrl, CoachConfig.defaultBaseUrl); + expect(config.model, 'gpt-5-mini'); + expect(run.state, isA()); + await capture.frames(15); + app.runner.exit(); + await tester.pumpWidget(const SizedBox()); + }, () => client); + }, skip: directory == null, variant: TargetPlatformVariant.only(TargetPlatform.iOS)); +}