From 03d46e5d846c5ee94a3cd8f65c05c811cc2f6e00 Mon Sep 17 00:00:00 2001 From: Boyonabike Date: Wed, 2 Dec 2026 16:11:31 +0000 Subject: [PATCH] feat(help): guide #9, set up the AI coach A new Help guide under Today walks the user's real screens from the avatar to Profile > Connected apps > AI coach, then through the AI settings form: pick where the model runs, the provider's own step, List models, pick a model, Save. The provider's step is one of four, each shown only while its part of the form is on screen: the Base URL for Ollama / LM Studio, the API key field for OpenAI / Anthropic, "Sign in with OpenRouter" (or a pasted key), and "Continue with ChatGPT". Each points at its own field, so the card sits clear of where the user pastes, and the later steps keep those fields clear too. Guide engine: - GuideStep.onlyWhen / unlessShown: a branch step applies only while a control is on screen; requiresPreviousTap looks past branches that do not apply. - The card counts a run of adjacent branch steps as one step. - A single highlighted row inside a card's side padding (a settings row) is highlighted across the card's full width. - Neighbouring steps' controls inside a keyed unit stay real. - Profile and Connected apps join the navigation tree; AI settings now sits under Connected apps. OsTextField takes an optional fieldKey that makes its drawn box one guide unit. The "AI coach" row in Connected apps is now translated. All copy in the 8 ARB files. Co-Authored-By: Claude Opus 5.5 --- lib/l10n/app_de.arb | 20 ++- lib/l10n/app_en.arb | 182 +++++++++++++++++++ lib/l10n/app_es.arb | 20 ++- lib/l10n/app_fr.arb | 20 ++- lib/l10n/app_hi.arb | 20 ++- lib/l10n/app_ru.arb | 175 +++++++++++++++++- lib/l10n/app_th.arb | 20 ++- lib/l10n/app_zh.arb | 20 ++- lib/l10n/display_text.dart | 1 + lib/ui2/guides/guide.dart | 27 +++ lib/ui2/guides/guide_catalogue.dart | 4 +- lib/ui2/guides/guide_coach_setup.dart | 207 ++++++++++++++++++++++ lib/ui2/guides/guide_copy.dart | 42 ++++- lib/ui2/guides/guide_labels.dart | 38 +++- lib/ui2/guides/guide_navigation.dart | 12 +- lib/ui2/guides/guide_run.dart | 28 ++- lib/ui2/guides/live_guide_overlay.dart | 28 ++- lib/ui2/screens/coach.dart | 11 ++ lib/ui2/screens/journal_compose.dart | 10 +- lib/ui2/skeleton/unit_paint.dart | 21 ++- test/support/guide_r2_scenes.dart | 41 ++++- test/ui2/guide_catalogue_test.dart | 26 ++- test/ui2/guide_conformance_test.dart | 29 ++- test/ui2/guide_r5_scenes_test.dart | 4 +- test/ui2/help_screen_test.dart | 2 +- test/ui2/live_guide_integration_test.dart | 27 ++- 26 files changed, 985 insertions(+), 50 deletions(-) create mode 100644 lib/ui2/guides/guide_coach_setup.dart diff --git a/lib/l10n/app_de.arb b/lib/l10n/app_de.arb index 45b397116..93a421bad 100644 --- a/lib/l10n/app_de.arb +++ b/lib/l10n/app_de.arb @@ -4159,5 +4159,23 @@ "activitySummaryUploadStrava": "Auf Strava hochladen", "activitySummaryExportGpx": "GPX exportieren", "settingsWorkoutMapRowTitle": "Karte bei Workouts", - "settingsWorkoutMapRowSub": "Aus zeigt nur, wo das Workout begann" + "settingsWorkoutMapRowSub": "Aus zeigt nur, wo das Workout begann", + "guideCoachTitle": "So richtest du den KI-Coach ein", + "guideCoachIntro": "Verbinde den Coach mit einem Modell: auf deinem eigenen Computer, über dein ChatGPT-Abo oder bei einem Anbieter mit deinem eigenen Schlüssel.", + "guideCoachStep1": "Tippe oben rechts auf dein Bild (**{profile}**).", + "guideCoachStep2": "Tippe auf **{connectedApps}**.", + "guideCoachStep3": "Tippe auf **{aiCoach}**.", + "guideCoachStep4": "Wähle unter **{where}**, wo dein Modell läuft: **{ollama}** oder LM Studio auf deinem eigenen Computer, ChatGPT mit deinem ChatGPT-Abo oder OpenAI, Anthropic oder OpenRouter mit deinem eigenen Schlüssel. Wenn du ChatGPT wählst, startet die Anmeldung sofort.", + "guideCoachLocalAddress": "Ollama und LM Studio laufen auf deinem Computer, nicht auf diesem Handy. Tippe auf **{baseUrl}** und ersetze „localhost“ durch die Adresse deines Computers im WLAN, zum Beispiel 192.168.1.20. Lass **{apiKey}** leer.", + "guideCoachPasteKey": "Tippe auf **{apiKey}** und füge den Schlüssel ein, den du auf der Website deines Anbieters erstellt hast. Schlüssel beginnen meist mit „sk-“.", + "guideCoachOpenRouter": "Tippe auf **{signIn}** und melde dich im Browser, der sich öffnet, bei OpenRouter an. Wenn du schon einen OpenRouter-Schlüssel hast, füge ihn stattdessen unter **{apiKey}** ein.", + "guideCoachChatgpt": "Tippe auf **{continueButton}**. Lies die Bedingungen von OpenAI, tippe auf **{agree}** und melde dich dann im Browser bei ChatGPT an. Danach kommst du hierher zurück.", + "guideCoachListModels": "Tippe auf **{listModels}**, um die Modelle abzurufen, die du nutzen kannst. Wenn ein Fehler erscheint, prüfe die Adresse oder den Schlüssel oben.", + "guideCoachPickModel": "Tippe in der Liste unter **{model}** auf das gewünschte Modell. Du kannst seinen genauen Namen auch in das Feld eingeben.", + "guideCoachSave": "Tippe auf **{save}**. Der Coach nutzt jetzt dieses Modell.", + "guideCoachAltBody": "Solange der Coach nicht eingerichtet ist, öffnet **{chip}** unter **{today}** denselben Bildschirm.", + "guideCoachMissingTitle": "„{where}“ nicht zu sehen?", + "guideCoachMissingBody": "Auf dem iPhone sind die Auswahlmöglichkeiten ausgeblendet, solange **{apple}** eingeschaltet ist, denn dann nutzt der Coach Apples Modell auf dem Gerät. Schalte es aus, um ein anderes Modell zu wählen.", + "guideCoachDataTitle": "Wohin gehen meine Daten?", + "guideCoachDataBody": "Mit einem Modell auf deinem eigenen Computer verlässt nichts dein Gerät. Mit ChatGPT oder einem Cloud-Anbieter gehen deine Fragen und die Zeilen, die der Coach liest, direkt an diesen Anbieter, nie über OpenStrap. **{sent}** im Menü des Coachs zeigt genau, was gesendet wurde." } diff --git a/lib/l10n/app_en.arb b/lib/l10n/app_en.arb index 79e2f5305..f0ffdb857 100644 --- a/lib/l10n/app_en.arb +++ b/lib/l10n/app_en.arb @@ -18889,5 +18889,187 @@ "settingsWorkoutMapRowSub": "Off shows only where the workout started", "@settingsWorkoutMapRowSub": { "description": "Subtitle under the Map on workouts settings row" + }, + "guideCoachTitle": "How to set up the AI coach", + "@guideCoachTitle": { + "description": "Title of the navigation guide for connecting the AI coach to a model." + }, + "guideCoachIntro": "Connect the coach to a model: one on your own computer, your ChatGPT plan, or a provider with your own key.", + "@guideCoachIntro": { + "description": "One line under the AI coach guide title." + }, + "guideCoachStep1": "Tap your picture at the top right (**{profile}**).", + "@guideCoachStep1": { + "description": "Step 1 caption. {profile} is the accessible name of the round profile picture at the top right.", + "placeholders": { + "profile": { + "type": "String", + "description": "Accessible name of the profile picture button" + } + } + }, + "guideCoachStep2": "Tap **{connectedApps}**.", + "@guideCoachStep2": { + "description": "Step 2 caption. {connectedApps} is the Profile row that opens Connected apps.", + "placeholders": { + "connectedApps": { + "type": "String", + "description": "Name of the Connected apps row" + } + } + }, + "guideCoachStep3": "Tap **{aiCoach}**.", + "@guideCoachStep3": { + "description": "Step 3 caption. {aiCoach} is the AI coach row in Connected apps.", + "placeholders": { + "aiCoach": { + "type": "String", + "description": "Name of the AI coach row" + } + } + }, + "guideCoachStep4": "Under **{where}**, choose where your model runs: **{ollama}** or LM Studio on your own computer, ChatGPT with your ChatGPT plan, or OpenAI, Anthropic or OpenRouter with your own key. Choosing ChatGPT starts its sign-in straight away.", + "@guideCoachStep4": { + "description": "Step 4 caption. {where} is the section heading listing the model choices; {ollama} the first choice. Ollama, LM Studio, ChatGPT, OpenAI, Anthropic and OpenRouter are brand names: do not translate.", + "placeholders": { + "where": { + "type": "String", + "description": "Heading of the model choices section" + }, + "ollama": { + "type": "String", + "description": "Name of the first model choice" + } + } + }, + "guideCoachLocalAddress": "Ollama and LM Studio run on your computer, not on this phone. Tap **{baseUrl}** and replace \"localhost\" with your computer's address on your Wi-Fi, for example 192.168.1.20. Leave **{apiKey}** empty.", + "@guideCoachLocalAddress": { + "description": "AI coach guide step: a model on the user's own computer. {baseUrl} is the address field, {apiKey} the key field (not needed locally).", + "placeholders": { + "baseUrl": { + "type": "String", + "description": "Label of the Base URL field" + }, + "apiKey": { + "type": "String", + "description": "Label of the API key field when no key is needed" + } + } + }, + "guideCoachPasteKey": "Tap **{apiKey}** and paste the key you created on your provider's website. Keys usually start with \"sk-\".", + "@guideCoachPasteKey": { + "description": "AI coach guide step: paste an API key. {apiKey} is the key field.", + "placeholders": { + "apiKey": { + "type": "String", + "description": "Label of the API key field" + } + } + }, + "guideCoachOpenRouter": "Tap **{signIn}** and log in to OpenRouter in the browser that opens. If you already have an OpenRouter key, paste it into **{apiKey}** instead.", + "@guideCoachOpenRouter": { + "description": "AI coach guide step for OpenRouter. {signIn} is the OpenRouter sign-in button, {apiKey} the key field.", + "placeholders": { + "signIn": { + "type": "String", + "description": "Name of the OpenRouter sign-in button" + }, + "apiKey": { + "type": "String", + "description": "Label of the API key field" + } + } + }, + "guideCoachChatgpt": "Tap **{continueButton}**. Read OpenAI's terms and tap **{agree}**, then sign in to ChatGPT in the browser. You come back here once you're signed in.", + "@guideCoachChatgpt": { + "description": "AI coach guide step for ChatGPT. {continueButton} is the ChatGPT sign-in button, {agree} the button on the OpenAI terms sheet.", + "placeholders": { + "continueButton": { + "type": "String", + "description": "Name of the ChatGPT sign-in button" + }, + "agree": { + "type": "String", + "description": "Name of the button that accepts the OpenAI terms" + } + } + }, + "guideCoachListModels": "Tap **{listModels}** to fetch the models you can use. If an error shows, check the address or key above.", + "@guideCoachListModels": { + "description": "AI coach guide step. {listModels} is the button that lists models.", + "placeholders": { + "listModels": { + "type": "String", + "description": "Name of the List models button" + } + } + }, + "guideCoachPickModel": "Tap the model you want in the list below **{model}**. You can also type its exact name into the field.", + "@guideCoachPickModel": { + "description": "AI coach guide step. {model} is the label of the model field; the list of models is below it.", + "placeholders": { + "model": { + "type": "String", + "description": "Label of the model field" + } + } + }, + "guideCoachSave": "Tap **{save}**. The coach now uses this model.", + "@guideCoachSave": { + "description": "AI coach guide step. {save} is the Save button.", + "placeholders": { + "save": { + "type": "String", + "description": "Name of the Save button" + } + } + }, + "guideCoachAltBody": "While the coach is not set up, **{chip}** on **{today}** opens the same screen.", + "@guideCoachAltBody": { + "description": "Footer card body (another way in). {chip} is the button on the Today tab, {today} the Today tab.", + "placeholders": { + "chip": { + "type": "String", + "description": "Name of the Set up the coach button" + }, + "today": { + "type": "String", + "description": "Today tab name" + } + } + }, + "guideCoachMissingTitle": "Don't see \"{where}\"?", + "@guideCoachMissingTitle": { + "description": "Footer card title (the \"Don't see it?\" help). {where} is the section heading listing the model choices.", + "placeholders": { + "where": { + "type": "String", + "description": "Heading of the model choices section" + } + } + }, + "guideCoachMissingBody": "On an iPhone, the choices are hidden while **{apple}** is switched on, because the coach then uses Apple's on-device model. Switch it off to choose another model.", + "@guideCoachMissingBody": { + "description": "Footer card body. {apple} is the name of the Apple on-device model switch.", + "placeholders": { + "apple": { + "type": "String", + "description": "Name of the Apple Intelligence switch" + } + } + }, + "guideCoachDataTitle": "Where does my data go?", + "@guideCoachDataTitle": { + "description": "Footer card title of the AI coach guide: where the data is sent." + }, + "guideCoachDataBody": "With a model on your own computer, nothing leaves your machine. With ChatGPT or a cloud provider, your questions and the rows the coach reads go straight to that provider, never through OpenStrap. **{sent}** in the coach's menu shows exactly what was sent.", + "@guideCoachDataBody": { + "description": "Footer card body. {sent} is the coach menu row that shows what was sent.", + "placeholders": { + "sent": { + "type": "String", + "description": "Name of the coach menu row that shows what was sent" + } + } } } diff --git a/lib/l10n/app_es.arb b/lib/l10n/app_es.arb index 46fbd8b55..42120987d 100644 --- a/lib/l10n/app_es.arb +++ b/lib/l10n/app_es.arb @@ -4159,5 +4159,23 @@ "activitySummaryUploadStrava": "Subir a Strava", "activitySummaryExportGpx": "Exportar GPX", "settingsWorkoutMapRowTitle": "Mapa en entrenamientos", - "settingsWorkoutMapRowSub": "Desactivado muestra solo dónde empezó el entrenamiento" + "settingsWorkoutMapRowSub": "Desactivado muestra solo dónde empezó el entrenamiento", + "guideCoachTitle": "Cómo configurar el coach de IA", + "guideCoachIntro": "Conecta el coach a un modelo: uno en tu propio ordenador, tu plan de ChatGPT o un proveedor con tu propia clave.", + "guideCoachStep1": "Toca tu foto arriba a la derecha (**{profile}**).", + "guideCoachStep2": "Toca **{connectedApps}**.", + "guideCoachStep3": "Toca **{aiCoach}**.", + "guideCoachStep4": "En **{where}**, elige dónde se ejecuta tu modelo: **{ollama}** o LM Studio en tu propio ordenador, ChatGPT con tu plan de ChatGPT, u OpenAI, Anthropic u OpenRouter con tu propia clave. Si eliges ChatGPT, el inicio de sesión empieza enseguida.", + "guideCoachLocalAddress": "Ollama y LM Studio se ejecutan en tu ordenador, no en este teléfono. Toca **{baseUrl}** y cambia «localhost» por la dirección de tu ordenador en tu wifi, por ejemplo 192.168.1.20. Deja **{apiKey}** vacío.", + "guideCoachPasteKey": "Toca **{apiKey}** y pega la clave que creaste en la web de tu proveedor. Las claves suelen empezar por «sk-».", + "guideCoachOpenRouter": "Toca **{signIn}** e inicia sesión en OpenRouter en el navegador que se abre. Si ya tienes una clave de OpenRouter, pégala en **{apiKey}**.", + "guideCoachChatgpt": "Toca **{continueButton}**. Lee los términos de OpenAI y toca **{agree}**; después inicia sesión en ChatGPT en el navegador. Volverás aquí al terminar.", + "guideCoachListModels": "Toca **{listModels}** para obtener los modelos que puedes usar. Si aparece un error, revisa la dirección o la clave de arriba.", + "guideCoachPickModel": "Toca el modelo que quieras en la lista bajo **{model}**. También puedes escribir su nombre exacto en el campo.", + "guideCoachSave": "Toca **{save}**. El coach ya usa este modelo.", + "guideCoachAltBody": "Mientras el coach no esté configurado, **{chip}** en **{today}** abre la misma pantalla.", + "guideCoachMissingTitle": "¿No ves «{where}»?", + "guideCoachMissingBody": "En un iPhone, las opciones se ocultan mientras **{apple}** está activado, porque el coach usa entonces el modelo de Apple en el dispositivo. Desactívalo para elegir otro modelo.", + "guideCoachDataTitle": "¿Adónde van mis datos?", + "guideCoachDataBody": "Con un modelo en tu propio ordenador, nada sale de tu equipo. Con ChatGPT o un proveedor en la nube, tus preguntas y las filas que lee el coach van directamente a ese proveedor, nunca a través de OpenStrap. **{sent}** en el menú del coach muestra exactamente lo que se envió." } diff --git a/lib/l10n/app_fr.arb b/lib/l10n/app_fr.arb index 7a5e7bc45..98496890c 100644 --- a/lib/l10n/app_fr.arb +++ b/lib/l10n/app_fr.arb @@ -4159,5 +4159,23 @@ "activitySummaryUploadStrava": "Importer sur Strava", "activitySummaryExportGpx": "Exporter en GPX", "settingsWorkoutMapRowTitle": "Carte sur les entraînements", - "settingsWorkoutMapRowSub": "Désactivé, seul le point de départ s'affiche" + "settingsWorkoutMapRowSub": "Désactivé, seul le point de départ s'affiche", + "guideCoachTitle": "Configurer le coach IA", + "guideCoachIntro": "Connectez le coach à un modèle : sur votre propre ordinateur, via votre abonnement ChatGPT ou chez un fournisseur avec votre propre clé.", + "guideCoachStep1": "Touchez votre photo en haut à droite (**{profile}**).", + "guideCoachStep2": "Touchez **{connectedApps}**.", + "guideCoachStep3": "Touchez **{aiCoach}**.", + "guideCoachStep4": "Sous **{where}**, choisissez où tourne votre modèle : **{ollama}** ou LM Studio sur votre propre ordinateur, ChatGPT avec votre abonnement ChatGPT, ou OpenAI, Anthropic ou OpenRouter avec votre propre clé. Si vous choisissez ChatGPT, la connexion démarre aussitôt.", + "guideCoachLocalAddress": "Ollama et LM Studio tournent sur votre ordinateur, pas sur ce téléphone. Touchez **{baseUrl}** et remplacez « localhost » par l'adresse de votre ordinateur sur votre Wi-Fi, par exemple 192.168.1.20. Laissez **{apiKey}** vide.", + "guideCoachPasteKey": "Touchez **{apiKey}** et collez la clé créée sur le site de votre fournisseur. Les clés commencent souvent par « sk- ».", + "guideCoachOpenRouter": "Touchez **{signIn}** et connectez-vous à OpenRouter dans le navigateur qui s'ouvre. Si vous avez déjà une clé OpenRouter, collez-la plutôt dans **{apiKey}**.", + "guideCoachChatgpt": "Touchez **{continueButton}**. Lisez les conditions d'OpenAI, touchez **{agree}**, puis connectez-vous à ChatGPT dans le navigateur. Vous revenez ici une fois connecté.", + "guideCoachListModels": "Touchez **{listModels}** pour récupérer les modèles disponibles. Si une erreur s'affiche, vérifiez l'adresse ou la clé plus haut.", + "guideCoachPickModel": "Touchez le modèle voulu dans la liste sous **{model}**. Vous pouvez aussi saisir son nom exact dans le champ.", + "guideCoachSave": "Touchez **{save}**. Le coach utilise désormais ce modèle.", + "guideCoachAltBody": "Tant que le coach n’est pas configuré, **{chip}** sur **{today}** ouvre le même écran.", + "guideCoachMissingTitle": "Vous ne voyez pas « {where} » ?", + "guideCoachMissingBody": "Sur iPhone, les choix sont masqués tant que **{apple}** est activé, car le coach utilise alors le modèle d’Apple sur l’appareil. Désactivez-le pour choisir un autre modèle.", + "guideCoachDataTitle": "Où vont mes données ?", + "guideCoachDataBody": "Avec un modèle sur votre propre ordinateur, rien ne quitte votre machine. Avec ChatGPT ou un fournisseur cloud, vos questions et les lignes que lit le coach vont directement à ce fournisseur, jamais via OpenStrap. **{sent}** dans le menu du coach montre exactement ce qui a été envoyé." } diff --git a/lib/l10n/app_hi.arb b/lib/l10n/app_hi.arb index 798ec22df..4decb39bd 100644 --- a/lib/l10n/app_hi.arb +++ b/lib/l10n/app_hi.arb @@ -4159,5 +4159,23 @@ "activitySummaryUploadStrava": "Strava पर अपलोड करें", "activitySummaryExportGpx": "GPX एक्सपोर्ट करें", "settingsWorkoutMapRowTitle": "वर्कआउट पर मैप", - "settingsWorkoutMapRowSub": "बंद होने पर सिर्फ़ वह जगह दिखती है जहाँ वर्कआउट शुरू हुआ" + "settingsWorkoutMapRowSub": "बंद होने पर सिर्फ़ वह जगह दिखती है जहाँ वर्कआउट शुरू हुआ", + "guideCoachTitle": "AI कोच कैसे सेट करें", + "guideCoachIntro": "कोच को किसी मॉडल से जोड़ें: अपने कंप्यूटर पर चलने वाला, अपने ChatGPT प्लान से, या अपनी कुंजी के साथ किसी प्रदाता से।", + "guideCoachStep1": "ऊपर दाईं ओर अपनी तस्वीर (**{profile}**) पर टैप करें।", + "guideCoachStep2": "**{connectedApps}** पर टैप करें।", + "guideCoachStep3": "**{aiCoach}** पर टैप करें।", + "guideCoachStep4": "**{where}** में चुनें कि आपका मॉडल कहाँ चलता है: अपने कंप्यूटर पर **{ollama}** या LM Studio, अपने ChatGPT प्लान के साथ ChatGPT, या अपनी कुंजी के साथ OpenAI, Anthropic या OpenRouter। ChatGPT चुनते ही उसका साइन-इन शुरू हो जाता है।", + "guideCoachLocalAddress": "Ollama और LM Studio आपके कंप्यूटर पर चलते हैं, इस फ़ोन पर नहीं। **{baseUrl}** पर टैप करें और \"localhost\" की जगह अपने Wi-Fi पर अपने कंप्यूटर का पता लिखें, जैसे 192.168.1.20। **{apiKey}** खाली छोड़ दें।", + "guideCoachPasteKey": "**{apiKey}** पर टैप करें और अपने प्रोवाइडर की वेबसाइट पर बनाई गई कुंजी पेस्ट करें। कुंजियाँ आम तौर पर \"sk-\" से शुरू होती हैं।", + "guideCoachOpenRouter": "**{signIn}** पर टैप करें और खुलने वाले ब्राउज़र में OpenRouter में लॉग इन करें। अगर आपके पास पहले से OpenRouter कुंजी है, तो उसे **{apiKey}** में पेस्ट करें।", + "guideCoachChatgpt": "**{continueButton}** पर टैप करें। OpenAI की शर्तें पढ़ें और **{agree}** पर टैप करें, फिर ब्राउज़र में ChatGPT में साइन इन करें। साइन इन होने के बाद आप यहाँ लौट आएँगे।", + "guideCoachListModels": "जिन मॉडलों का आप उपयोग कर सकते हैं, उन्हें लाने के लिए **{listModels}** पर टैप करें। कोई त्रुटि दिखे तो ऊपर का पता या कुंजी जाँचें।", + "guideCoachPickModel": "**{model}** के नीचे की सूची में अपना मनचाहा मॉडल टैप करें। आप फ़ील्ड में उसका सटीक नाम भी लिख सकते हैं।", + "guideCoachSave": "**{save}** पर टैप करें। अब कोच इसी मॉडल का उपयोग करेगा।", + "guideCoachAltBody": "जब तक कोच सेट नहीं है, **{today}** पर **{chip}** वही स्क्रीन खोलता है।", + "guideCoachMissingTitle": "\"{where}\" नहीं दिख रहा?", + "guideCoachMissingBody": "iPhone पर, जब तक **{apple}** चालू है, विकल्प छिपे रहते हैं, क्योंकि तब कोच Apple का ऑन-डिवाइस मॉडल इस्तेमाल करता है। दूसरा मॉडल चुनने के लिए इसे बंद करें।", + "guideCoachDataTitle": "मेरा डेटा कहाँ जाता है?", + "guideCoachDataBody": "आपके अपने कंप्यूटर पर चलने वाले मॉडल के साथ कुछ भी आपकी मशीन से बाहर नहीं जाता। ChatGPT या किसी क्लाउड प्रदाता के साथ, आपके सवाल और कोच जो पंक्तियाँ पढ़ता है, सीधे उसी प्रदाता को जाती हैं, कभी OpenStrap से होकर नहीं। कोच के मेनू में **{sent}** ठीक-ठीक दिखाता है कि क्या भेजा गया।" } diff --git a/lib/l10n/app_ru.arb b/lib/l10n/app_ru.arb index 0ed257491..c991c5a35 100644 --- a/lib/l10n/app_ru.arb +++ b/lib/l10n/app_ru.arb @@ -9489,5 +9489,178 @@ "activitySummaryUploadStrava": "Загрузить в Strava", "activitySummaryExportGpx": "Экспорт GPX", "settingsWorkoutMapRowTitle": "Карта в тренировках", - "settingsWorkoutMapRowSub": "Если выключено, видно только место старта" + "settingsWorkoutMapRowSub": "Если выключено, видно только место старта", + "guideCoachTitle": "Как настроить ИИ-тренера", + "guideCoachIntro": "Подключите тренера к модели: на вашем компьютере, по вашей подписке ChatGPT или у провайдера с вашим ключом.", + "guideCoachStep1": "Нажмите на свою фотографию справа вверху (**{profile}**).", + "@guideCoachStep1": { + "description": "Step 1 caption. {profile} is the accessible name of the round profile picture at the top right.", + "placeholders": { + "profile": { + "type": "String", + "description": "Accessible name of the profile picture button" + } + } + }, + "guideCoachStep2": "Нажмите **{connectedApps}**.", + "@guideCoachStep2": { + "description": "Step 2 caption. {connectedApps} is the Profile row that opens Connected apps.", + "placeholders": { + "connectedApps": { + "type": "String", + "description": "Name of the Connected apps row" + } + } + }, + "guideCoachStep3": "Нажмите **{aiCoach}**.", + "@guideCoachStep3": { + "description": "Step 3 caption. {aiCoach} is the AI coach row in Connected apps.", + "placeholders": { + "aiCoach": { + "type": "String", + "description": "Name of the AI coach row" + } + } + }, + "guideCoachStep4": "В разделе **{where}** выберите, где работает модель: **{ollama}** или LM Studio на вашем компьютере, ChatGPT по вашей подписке ChatGPT или OpenAI, Anthropic или OpenRouter с вашим ключом. Если выбрать ChatGPT, вход начнётся сразу.", + "@guideCoachStep4": { + "description": "Step 4 caption. {where} is the section heading listing the model choices; {ollama} the first choice. Ollama, LM Studio, ChatGPT, OpenAI, Anthropic and OpenRouter are brand names: do not translate.", + "placeholders": { + "where": { + "type": "String", + "description": "Heading of the model choices section" + }, + "ollama": { + "type": "String", + "description": "Name of the first model choice" + } + } + }, + "guideCoachLocalAddress": "Ollama и LM Studio работают на вашем компьютере, а не на этом телефоне. Нажмите **{baseUrl}** и замените «localhost» адресом компьютера в вашей сети Wi-Fi, например 192.168.1.20. Поле **{apiKey}** оставьте пустым.", + "@guideCoachLocalAddress": { + "description": "AI coach guide step: a model on the user's own computer. {baseUrl} is the address field, {apiKey} the key field (not needed locally).", + "placeholders": { + "baseUrl": { + "type": "String", + "description": "Label of the Base URL field" + }, + "apiKey": { + "type": "String", + "description": "Label of the API key field when no key is needed" + } + } + }, + "guideCoachPasteKey": "Нажмите **{apiKey}** и вставьте ключ, созданный на сайте вашего провайдера. Обычно ключи начинаются с «sk-».", + "@guideCoachPasteKey": { + "description": "AI coach guide step: paste an API key. {apiKey} is the key field.", + "placeholders": { + "apiKey": { + "type": "String", + "description": "Label of the API key field" + } + } + }, + "guideCoachOpenRouter": "Нажмите **{signIn}** и войдите в OpenRouter в открывшемся браузере. Если у вас уже есть ключ OpenRouter, вставьте его в поле **{apiKey}**.", + "@guideCoachOpenRouter": { + "description": "AI coach guide step for OpenRouter. {signIn} is the OpenRouter sign-in button, {apiKey} the key field.", + "placeholders": { + "signIn": { + "type": "String", + "description": "Name of the OpenRouter sign-in button" + }, + "apiKey": { + "type": "String", + "description": "Label of the API key field" + } + } + }, + "guideCoachChatgpt": "Нажмите **{continueButton}**. Прочитайте условия OpenAI и нажмите **{agree}**, затем войдите в ChatGPT в браузере. После входа вы вернётесь сюда.", + "@guideCoachChatgpt": { + "description": "AI coach guide step for ChatGPT. {continueButton} is the ChatGPT sign-in button, {agree} the button on the OpenAI terms sheet.", + "placeholders": { + "continueButton": { + "type": "String", + "description": "Name of the ChatGPT sign-in button" + }, + "agree": { + "type": "String", + "description": "Name of the button that accepts the OpenAI terms" + } + } + }, + "guideCoachListModels": "Нажмите **{listModels}**, чтобы получить доступные модели. Если появится ошибка, проверьте адрес или ключ выше.", + "@guideCoachListModels": { + "description": "AI coach guide step. {listModels} is the button that lists models.", + "placeholders": { + "listModels": { + "type": "String", + "description": "Name of the List models button" + } + } + }, + "guideCoachPickModel": "Нажмите нужную модель в списке под **{model}**. Можно также ввести её точное название в поле.", + "@guideCoachPickModel": { + "description": "AI coach guide step. {model} is the label of the model field; the list of models is below it.", + "placeholders": { + "model": { + "type": "String", + "description": "Label of the model field" + } + } + }, + "guideCoachSave": "Нажмите **{save}**. Теперь коуч использует эту модель.", + "@guideCoachSave": { + "description": "AI coach guide step. {save} is the Save button.", + "placeholders": { + "save": { + "type": "String", + "description": "Name of the Save button" + } + } + }, + "guideCoachAltBody": "Пока тренер не настроен, кнопка **{chip}** на вкладке **{today}** открывает тот же экран.", + "@guideCoachAltBody": { + "description": "Footer card body (another way in). {chip} is the button on the Today tab, {today} the Today tab.", + "placeholders": { + "chip": { + "type": "String", + "description": "Name of the Set up the coach button" + }, + "today": { + "type": "String", + "description": "Today tab name" + } + } + }, + "guideCoachMissingTitle": "Не видите «{where}»?", + "@guideCoachMissingTitle": { + "description": "Footer card title (the \"Don't see it?\" help). {where} is the section heading listing the model choices.", + "placeholders": { + "where": { + "type": "String", + "description": "Heading of the model choices section" + } + } + }, + "guideCoachMissingBody": "На iPhone варианты скрыты, пока включено **{apple}**: тогда тренер использует модель Apple на устройстве. Выключите его, чтобы выбрать другую модель.", + "@guideCoachMissingBody": { + "description": "Footer card body. {apple} is the name of the Apple on-device model switch.", + "placeholders": { + "apple": { + "type": "String", + "description": "Name of the Apple Intelligence switch" + } + } + }, + "guideCoachDataTitle": "Куда уходят мои данные?", + "guideCoachDataBody": "С моделью на вашем компьютере ничего не покидает вашу машину. С ChatGPT или облачным провайдером ваши вопросы и строки, которые читает тренер, уходят прямо этому провайдеру, никогда не через OpenStrap. **{sent}** в меню тренера показывает, что именно было отправлено.", + "@guideCoachDataBody": { + "description": "Footer card body. {sent} is the coach menu row that shows what was sent.", + "placeholders": { + "sent": { + "type": "String", + "description": "Name of the coach menu row that shows what was sent" + } + } + } } diff --git a/lib/l10n/app_th.arb b/lib/l10n/app_th.arb index 20e86ffc0..e1fbd2617 100644 --- a/lib/l10n/app_th.arb +++ b/lib/l10n/app_th.arb @@ -17667,5 +17667,23 @@ "activitySummaryUploadStrava": "อัปโหลดไปยัง Strava", "activitySummaryExportGpx": "ส่งออก GPX", "settingsWorkoutMapRowTitle": "แผนที่ในการออกกำลังกาย", - "settingsWorkoutMapRowSub": "เมื่อปิด จะแสดงเฉพาะจุดเริ่มต้นของการออกกำลังกาย" + "settingsWorkoutMapRowSub": "เมื่อปิด จะแสดงเฉพาะจุดเริ่มต้นของการออกกำลังกาย", + "guideCoachTitle": "วิธีตั้งค่าโค้ช AI", + "guideCoachIntro": "เชื่อมโค้ชกับโมเดล: บนคอมพิวเตอร์ของคุณเอง แพ็กเกจ ChatGPT ของคุณ หรือผู้ให้บริการที่ใช้คีย์ของคุณเอง", + "guideCoachStep1": "แตะรูปของคุณที่มุมขวาบน (**{profile}**)", + "guideCoachStep2": "แตะ **{connectedApps}**", + "guideCoachStep3": "แตะ **{aiCoach}**", + "guideCoachStep4": "ใน **{where}** เลือกว่าโมเดลของคุณทำงานที่ไหน: **{ollama}** หรือ LM Studio บนคอมพิวเตอร์ของคุณเอง ChatGPT ด้วยแพ็กเกจ ChatGPT ของคุณ หรือ OpenAI, Anthropic หรือ OpenRouter ด้วยคีย์ของคุณเอง ถ้าเลือก ChatGPT การลงชื่อเข้าใช้จะเริ่มทันที", + "guideCoachLocalAddress": "Ollama และ LM Studio ทำงานบนคอมพิวเตอร์ของคุณ ไม่ใช่บนโทรศัพท์เครื่องนี้ แตะ **{baseUrl}** แล้วเปลี่ยน \"localhost\" เป็นที่อยู่ของคอมพิวเตอร์ในวง Wi-Fi ของคุณ เช่น 192.168.1.20 และเว้น **{apiKey}** ว่างไว้", + "guideCoachPasteKey": "แตะ **{apiKey}** แล้ววางคีย์ที่คุณสร้างไว้บนเว็บไซต์ของผู้ให้บริการ คีย์มักขึ้นต้นด้วย \"sk-\"", + "guideCoachOpenRouter": "แตะ **{signIn}** แล้วเข้าสู่ระบบ OpenRouter ในเบราว์เซอร์ที่เปิดขึ้น ถ้าคุณมีคีย์ OpenRouter อยู่แล้ว ให้วางลงใน **{apiKey}** แทน", + "guideCoachChatgpt": "แตะ **{continueButton}** อ่านข้อกำหนดของ OpenAI แล้วแตะ **{agree}** จากนั้นลงชื่อเข้าใช้ ChatGPT ในเบราว์เซอร์ เมื่อลงชื่อเข้าใช้แล้วจะกลับมาที่หน้านี้", + "guideCoachListModels": "แตะ **{listModels}** เพื่อดึงรายการโมเดลที่คุณใช้ได้ ถ้ามีข้อผิดพลาด ให้ตรวจสอบที่อยู่หรือคีย์ด้านบน", + "guideCoachPickModel": "แตะโมเดลที่ต้องการในรายการใต้ **{model}** หรือพิมพ์ชื่อโมเดลให้ตรงลงในช่องก็ได้", + "guideCoachSave": "แตะ **{save}** ตอนนี้โค้ชจะใช้โมเดลนี้", + "guideCoachAltBody": "ระหว่างที่ยังไม่ได้ตั้งค่าโค้ช **{chip}** ใน **{today}** จะเปิดหน้าจอเดียวกันนี้", + "guideCoachMissingTitle": "ไม่เห็น \"{where}\" ใช่ไหม", + "guideCoachMissingBody": "บน iPhone ตัวเลือกจะถูกซ่อนไว้ขณะที่ **{apple}** เปิดอยู่ เพราะโค้ชจะใช้โมเดลบนเครื่องของ Apple ปิดสวิตช์นี้เพื่อเลือกโมเดลอื่น", + "guideCoachDataTitle": "ข้อมูลของฉันไปที่ไหน", + "guideCoachDataBody": "เมื่อใช้โมเดลบนคอมพิวเตอร์ของคุณเอง ไม่มีอะไรออกจากเครื่องของคุณ เมื่อใช้ ChatGPT หรือผู้ให้บริการคลาวด์ คำถามของคุณและแถวข้อมูลที่โค้ชอ่านจะส่งตรงไปยังผู้ให้บริการนั้น ไม่ผ่าน OpenStrap เลย **{sent}** ในเมนูของโค้ชแสดงสิ่งที่ส่งไปอย่างละเอียด" } diff --git a/lib/l10n/app_zh.arb b/lib/l10n/app_zh.arb index acf920567..aad369bec 100644 --- a/lib/l10n/app_zh.arb +++ b/lib/l10n/app_zh.arb @@ -4159,5 +4159,23 @@ "activitySummaryUploadStrava": "上传到 Strava", "activitySummaryExportGpx": "导出 GPX", "settingsWorkoutMapRowTitle": "锻炼中显示地图", - "settingsWorkoutMapRowSub": "关闭时只显示锻炼的起点" + "settingsWorkoutMapRowSub": "关闭时只显示锻炼的起点", + "guideCoachTitle": "如何设置 AI 教练", + "guideCoachIntro": "把教练连接到一个模型:你自己电脑上的模型、你的 ChatGPT 套餐,或使用你自己密钥的服务商。", + "guideCoachStep1": "点按右上角你的头像(**{profile}**)。", + "guideCoachStep2": "点按**{connectedApps}**。", + "guideCoachStep3": "点按**{aiCoach}**。", + "guideCoachStep4": "在**{where}**下选择模型运行的位置:在你自己电脑上用**{ollama}**或 LM Studio,用你的 ChatGPT 套餐使用 ChatGPT,或用你自己的密钥使用 OpenAI、Anthropic 或 OpenRouter。选择 ChatGPT 后会立即开始登录。", + "guideCoachLocalAddress": "Ollama 和 LM Studio 运行在你的电脑上,而不是这部手机上。点按**{baseUrl}**,把“localhost”换成你电脑在 Wi-Fi 中的地址,例如 192.168.1.20。**{apiKey}**留空即可。", + "guideCoachPasteKey": "点按**{apiKey}**,粘贴你在服务商网站上创建的密钥。密钥通常以“sk-”开头。", + "guideCoachOpenRouter": "点按**{signIn}**,在打开的浏览器中登录 OpenRouter。如果你已有 OpenRouter 密钥,也可以直接粘贴到**{apiKey}**。", + "guideCoachChatgpt": "点按**{continueButton}**。阅读 OpenAI 的条款并点按**{agree}**,然后在浏览器中登录 ChatGPT。登录后会回到这里。", + "guideCoachListModels": "点按**{listModels}**获取你可以使用的模型。如果出现错误,请检查上方的地址或密钥。", + "guideCoachPickModel": "在**{model}**下方的列表中点按你想要的模型。也可以在该栏中输入模型的准确名称。", + "guideCoachSave": "点按**{save}**。教练现在会使用这个模型。", + "guideCoachAltBody": "在教练尚未设置时,**{today}**上的**{chip}**会打开同一个页面。", + "guideCoachMissingTitle": "没有看到“{where}”?", + "guideCoachMissingBody": "在 iPhone 上,**{apple}**开启时这些选项会被隐藏,因为此时教练使用 Apple 的设备端模型。关闭它即可选择其他模型。", + "guideCoachDataTitle": "我的数据会发到哪里?", + "guideCoachDataBody": "使用你自己电脑上的模型时,任何数据都不会离开你的机器。使用 ChatGPT 或云端服务商时,你的问题和教练读取的数据行会直接发送给该服务商,绝不经过 OpenStrap。教练菜单中的**{sent}**会准确显示发送了什么。" } diff --git a/lib/l10n/display_text.dart b/lib/l10n/display_text.dart index eb57924a4..f31c89cbe 100644 --- a/lib/l10n/display_text.dart +++ b/lib/l10n/display_text.dart @@ -165,6 +165,7 @@ String localizedText(AppLocalizations? l, String text) { "Sign in with OpenRouter" => l.coachSignInOpenRouter, "Share a report for your doctor" => l.healthShareDoctorReport, "Connected apps" => l.profileConnectedApps, + "AI coach" => l.profileAiCoach, "AI coach, intervals.icu, weather, calendar, Hue" => l.profileConnectedAppsSub, "Send the last 7 days now" => l.connectedAppsSendLast7, "Disconnect" => l.connectedAppsDisconnect, diff --git a/lib/ui2/guides/guide.dart b/lib/ui2/guides/guide.dart index d809ad5f1..cf9b7034c 100644 --- a/lib/ui2/guides/guide.dart +++ b/lib/ui2/guides/guide.dart @@ -91,6 +91,17 @@ class GuideStep { /// step can match. Used when its anchor can predate the guide, as with undo. final bool requiresPreviousTap; + /// A branch of the screen: the step applies only while [onlyWhen] resolves + /// on the page and [unlessShown] does not (the AI settings form shows a key + /// field, a ChatGPT button or an OpenRouter button by provider). A step that + /// does not apply is passed over: the next step's [requiresPreviousTap] + /// looks past it to the step before. + final GuideTarget? onlyWhen; + final GuideTarget? unlessShown; + + /// True for a step that is shown only on some branches of its screen. + bool get isBranch => onlyWhen != null || unlessShown != null; + /// Extra units kept readable besides the target's (step 3 keeps "Your zones"). final List alsoKeep; /// P7: caption-offered controls kept full colour; tapping one also completes @@ -119,6 +130,8 @@ class GuideStep { this.node, required this.anchor, this.requiresPreviousTap = false, + this.onlyWhen, + this.unlessShown, this.alsoKeep = const [], this.alsoTap = const [], this.alsoRead = const [], @@ -158,6 +171,20 @@ class GuideVariant { final Set devices; final List steps; const GuideVariant({this.devices = const {}, required this.steps}); + + /// The step number the card shows for [index] (1-based). A run of adjacent branch steps + /// ([GuideStep.isBranch]) is alternatives, one per branch of the screen, and counts as ONE step: + /// the user walks only one of them. + int numberOf(int index) { + var number = 0; + for (var i = 0; i <= index; i++) { + if (!(steps[i].isBranch && i > 0 && steps[i - 1].isBranch)) number++; + } + return number; + } + + /// How many steps the card says there are, branch alternatives counted once. + int get shownTotal => steps.isEmpty ? 0 : numberOf(steps.length - 1); } sealed class GuideVariantResult { diff --git a/lib/ui2/guides/guide_catalogue.dart b/lib/ui2/guides/guide_catalogue.dart index 2676ef699..81b45c0ac 100644 --- a/lib/ui2/guides/guide_catalogue.dart +++ b/lib/ui2/guides/guide_catalogue.dart @@ -8,6 +8,7 @@ import '../../sync/paired_device.dart' show PairedDevice; import 'guide.dart'; import 'guide_add_nap.dart'; import 'guide_alarm_schedule.dart'; +import 'guide_coach_setup.dart'; import 'guide_delete_workout.dart'; import 'guide_fix_sleep_times.dart'; import 'guide_heart_rate_zones.dart'; @@ -34,7 +35,7 @@ class GuideTopicGroup { } /// Every shipped guide, in the order the list shows them within a topic. -/// Guide #1 (heart-rate zones) and #2-#8. +/// Guide #1 (heart-rate zones) and #2-#9. List get kGuideCatalogue => [ GuideEntry(GuideTopic.today, heartRateZonesGuide), GuideEntry(GuideTopic.sleep, alarmScheduleGuide), @@ -44,6 +45,7 @@ List get kGuideCatalogue => [ GuideEntry(GuideTopic.activity, deleteWorkoutGuide), GuideEntry(GuideTopic.activity, startStopWorkoutGuide), GuideEntry(GuideTopic.activity, logPastWorkoutGuide), + GuideEntry(GuideTopic.today, coachSetupGuide), ]; /// The groups to show for [band]: topics in [GuideTopic] order, empty topics diff --git a/lib/ui2/guides/guide_coach_setup.dart b/lib/ui2/guides/guide_coach_setup.dart new file mode 100644 index 000000000..a738a3615 --- /dev/null +++ b/lib/ui2/guides/guide_coach_setup.dart @@ -0,0 +1,207 @@ +// GUIDE #9: connect the AI coach to a model. +// +// any tab: the avatar ("Profile and settings") -> Profile: "Connected apps" +// -> "AI coach" -> AI settings: pick where the model runs -> the +// provider's own step -> "List models" -> pick a model -> "Save". +// +// The settings door, not Today's chip: the chip opens setup only while the +// coach is NOT set up (home_screen.dart coachChip), and the chat's own menu has +// no door to the form on purpose (coach.dart _menu). The chip is footer 0. +// +// One screen whatever the provider: the AI settings form keeps "List models", +// "Model" and "Save" for every choice and changes only its middle. Each middle +// gets a step of its own that applies only while that middle is on screen +// (onlyWhen / unlessShown); the others are passed over: +// Ollama / LM Studio: the Base URL (the key field reads "not needed locally") +// OpenAI / Anthropic: the API key field +// OpenRouter: "Sign in with OpenRouter", or the key field +// ChatGPT: "Continue with ChatGPT" (choosing ChatGPT opens its +// sign-in at once; the button stays only while signed out) +// Each points at its own field, so the card is placed clear of where the user +// pastes or types, and the later steps keep those fields clear too (alsoKeep). +// +// Every step on the form waits for the previous step's tap (requiresPreviousTap) +// instead of jumping ahead on its anchor: all its controls are built at once. +// +// Apple's on-device switch (iPhone only) hides the choices; footer 1 says so. +// The overlay and form never branch on band generation: ONE 'any' variant. + +import 'guide.dart'; +import 'guide_content.dart'; +import 'guide_copy.dart'; +import 'guide_labels.dart'; +import 'guide_navigation.dart'; +import 'guide_target.dart'; +import '../screens/coach.dart' show CoachSetup; + +final _avatar = GuideTarget.label(ScreenLabel.homeProfileSettings); +final _connectedApps = GuideTarget.label(ScreenLabel.profileConnectedApps); +final _aiCoach = GuideTarget.label(ScreenLabel.connectedAppsAiCoach); +// The form's title sits above its list, so it is built at any scroll and text +// size; "List models" and "Model" can start below the fold. +final _aiSettings = GuideTarget.label(ScreenLabel.coachSetupNavTitle); +final _ollama = GuideTarget.label(ScreenLabel.coachOllama); +final _listModels = GuideTarget.label(ScreenLabel.coachListModels); +final _save = GuideTarget.label(ScreenLabel.actionSave); +final _baseUrl = GuideTarget.key(CoachSetup.baseUrlKey); +final _apiKey = GuideTarget.key(CoachSetup.apiKeyKey); +final _model = GuideTarget.key(CoachSetup.modelKey); +// The key field's label tells the branches apart (it prints as a Text and a +// field's Semantics, so the first of the two). +final _localKeyLabel = GuideTarget.firstLabel(ScreenLabel.coachApiKeyLocalLabel); +final _keyLabel = GuideTarget.firstLabel(ScreenLabel.coachApiKeyLabel); +final _openRouter = GuideTarget.label(ScreenLabel.coachSignInOpenRouter); +final _chatgpt = GuideTarget.label(ScreenLabel.coachChatgptContinue); + +/// The fields the user has typed into on the way; later steps keep them clear of the card. +final _typed = [_baseUrl, _apiKey]; + +/// Every provider the form offers, in the order it lists them. +const _providers = LabelledContent([ + ScreenLabel.coachOllama, + ScreenLabel.coachLmStudio, + ScreenLabel.coachChatGpt, + ScreenLabel.coachOpenAi, + ScreenLabel.coachAnthropic, + ScreenLabel.coachOpenRouter, +]); + +Guide get coachSetupGuide => Guide( + id: 'coach-setup', + title: GuideCopy.coachTitle, + intro: GuideCopy.coachIntro, + start: GuideStart.today, + variants: [ + GuideVariant(steps: [ + GuideStep( + id: 'coach-open-profile', + node: GuideNode.today, + target: _avatar, + anchor: _avatar, + action: GuideAction.tap, + caption: GuideCopy.coachCaptionOpenProfile, + ), + GuideStep( + id: 'coach-open-connected-apps', + node: GuideNode.profileHome, + target: _connectedApps, + anchor: _connectedApps, + action: GuideAction.tap, + caption: GuideCopy.coachCaptionOpenConnectedApps, + ), + GuideStep( + id: 'coach-open-ai-coach', + node: GuideNode.connectedApps, + target: _aiCoach, + anchor: _aiCoach, + action: GuideAction.tap, + caption: GuideCopy.coachCaptionOpenAiCoach, + ), + GuideStep( + id: 'coach-pick-provider', + node: GuideNode.coachSetup, + target: _ollama, + anchor: _aiSettings, + alsoTap: [_providers], // any provider does the step + multi: GuideMultiTarget( + targets: _providers, + label: GuideCopy.tapOneOfLabel, + visit: GuideVisit.list, + ), + action: GuideAction.tap, + caption: GuideCopy.coachCaptionPickProvider, + ), + GuideStep( + id: 'coach-local-address', + node: GuideNode.coachSetup, + target: _baseUrl, + anchor: _aiSettings, + requiresPreviousTap: true, + onlyWhen: _localKeyLabel, + alsoKeep: [_apiKey], + action: GuideAction.scrollThenTap, + caption: GuideCopy.coachCaptionLocalAddress, + ), + GuideStep( + id: 'coach-paste-key', + node: GuideNode.coachSetup, + target: _apiKey, + anchor: _aiSettings, + requiresPreviousTap: true, + onlyWhen: _keyLabel, + unlessShown: _openRouter, + action: GuideAction.scrollThenTap, + caption: GuideCopy.coachCaptionPasteKey, + ), + GuideStep( + id: 'coach-openrouter', + node: GuideNode.coachSetup, + target: _openRouter, + anchor: _aiSettings, + requiresPreviousTap: true, + onlyWhen: _openRouter, + alsoTap: [TargetContent(_apiKey)], // pasting a key does the step too + action: GuideAction.scrollThenTap, + caption: GuideCopy.coachCaptionOpenRouter, + ), + GuideStep( + id: 'coach-chatgpt', + node: GuideNode.coachSetup, + target: _chatgpt, + anchor: _aiSettings, + requiresPreviousTap: true, + onlyWhen: _chatgpt, + action: GuideAction.scrollThenTap, + caption: GuideCopy.coachCaptionChatgpt, + ), + GuideStep( + id: 'coach-list-models', + node: GuideNode.coachSetup, + target: _listModels, + anchor: _aiSettings, + requiresPreviousTap: true, + alsoKeep: _typed, + action: GuideAction.scrollThenTap, + caption: GuideCopy.coachCaptionListModels, + ), + GuideStep( + id: 'coach-pick-model', + node: GuideNode.coachSetup, + target: _model, + anchor: _aiSettings, + requiresPreviousTap: true, + // Tapping a listed model does the step, as does typing a name. + alsoTap: [KeyedContent([CoachSetup.modelListKey])], + action: GuideAction.scrollThenTap, + caption: GuideCopy.coachCaptionPickModel, + ), + GuideStep( + id: 'coach-save', + node: GuideNode.coachSetup, + target: _save, + anchor: _aiSettings, + requiresPreviousTap: true, + alsoKeep: [_model], + action: GuideAction.scrollThenTap, + caption: GuideCopy.coachCaptionSave, + ), + ]), + ], + footers: [ + GuideFooter( + kind: GuideFooterKind.anotherWay, + title: GuideCopy.coachFooter0Title, + body: GuideCopy.coachFooter0Body, + ), + GuideFooter( + kind: GuideFooterKind.missingTarget, + title: GuideCopy.coachFooter1Title, + body: GuideCopy.coachFooter1Body, + ), + GuideFooter( + kind: GuideFooterKind.note, + title: GuideCopy.coachFooter2Title, + body: GuideCopy.coachFooter2Body, + ), + ], + ); diff --git a/lib/ui2/guides/guide_copy.dart b/lib/ui2/guides/guide_copy.dart index f91f8f3ab..5a711affb 100644 --- a/lib/ui2/guides/guide_copy.dart +++ b/lib/ui2/guides/guide_copy.dart @@ -9,6 +9,7 @@ import '../../compute/nap_edits.dart' show kMinManualNapSec, kMaxManualNapSec; import '../../l10n/app_localizations.dart'; +import '../../l10n/display_text.dart' show localizedText; import 'guide_text.dart'; enum GuideCopy implements GuideText { @@ -78,7 +79,26 @@ enum GuideCopy implements GuideText { logPastFooter0Title, logPastFooter0Body, logPastFooter1Title, - logPastFooter1Body,; + logPastFooter1Body, + coachTitle, + coachIntro, + coachCaptionOpenProfile, + coachCaptionOpenConnectedApps, + coachCaptionOpenAiCoach, + coachCaptionPickProvider, + coachCaptionLocalAddress, + coachCaptionPasteKey, + coachCaptionOpenRouter, + coachCaptionChatgpt, + coachCaptionListModels, + coachCaptionPickModel, + coachCaptionSave, + coachFooter0Title, + coachFooter0Body, + coachFooter1Title, + coachFooter1Body, + coachFooter2Title, + coachFooter2Body,; @override String of(AppLocalizations l) => switch (this) { @@ -149,5 +169,25 @@ enum GuideCopy implements GuideText { GuideCopy.logPastFooter0Body => l.guideLogPastScoreBody, GuideCopy.logPastFooter1Title => l.guideLogPastMissingTitle(l.workoutLogPastFix), GuideCopy.logPastFooter1Body => l.guideLogPastMissingBody(l.workoutTabHistory), + GuideCopy.coachTitle => l.guideCoachTitle, + GuideCopy.coachIntro => l.guideCoachIntro, + GuideCopy.coachCaptionOpenProfile => l.guideCoachStep1(l.homeProfileSettings), + GuideCopy.coachCaptionOpenConnectedApps => l.guideCoachStep2(l.profileConnectedApps), + GuideCopy.coachCaptionOpenAiCoach => l.guideCoachStep3(l.profileAiCoach), + GuideCopy.coachCaptionPickProvider => l.guideCoachStep4(l.coachWhereModelRuns, 'Ollama'), + GuideCopy.coachCaptionLocalAddress => l.guideCoachLocalAddress(l.coachBaseUrlLabel, l.coachApiKeyLocalLabel), + GuideCopy.coachCaptionPasteKey => l.guideCoachPasteKey(l.coachApiKeyLabel), + GuideCopy.coachCaptionOpenRouter => l.guideCoachOpenRouter(l.coachSignInOpenRouter, l.coachApiKeyLabel), + GuideCopy.coachCaptionChatgpt => + l.guideCoachChatgpt(l.coachChatgptContinue, localizedText(l, 'I’ve read them, continue')), + GuideCopy.coachCaptionListModels => l.guideCoachListModels(l.coachListModels), + GuideCopy.coachCaptionPickModel => l.guideCoachPickModel(l.coachModelLabel), + GuideCopy.coachCaptionSave => l.guideCoachSave(l.actionSave), + GuideCopy.coachFooter0Title => l.guideAnotherWayInTitle, + GuideCopy.coachFooter0Body => l.guideCoachAltBody(l.homeCoachSetUpChip, l.tabToday), + GuideCopy.coachFooter1Title => l.guideCoachMissingTitle(l.coachWhereModelRuns), + GuideCopy.coachFooter1Body => l.guideCoachMissingBody(localizedText(l, 'Apple Intelligence on this iPhone')), + GuideCopy.coachFooter2Title => l.guideCoachDataTitle, + GuideCopy.coachFooter2Body => l.guideCoachDataBody(l.coachBriefingMenuTitle), }; } diff --git a/lib/ui2/guides/guide_labels.dart b/lib/ui2/guides/guide_labels.dart index e5c0b8acf..5c49869a3 100644 --- a/lib/ui2/guides/guide_labels.dart +++ b/lib/ui2/guides/guide_labels.dart @@ -48,7 +48,24 @@ enum ScreenLabel implements GuideText { workoutNoSessionsTitle, workoutStartSessionLabel, workoutTabHistory, - workoutTrackedLabel,; + workoutTrackedLabel, + homeProfileSettings, + profileConnectedApps, + connectedAppsAiCoach, + coachSetupNavTitle, + coachOllama, + coachLmStudio, + coachChatGpt, + coachOpenAi, + coachAnthropic, + coachOpenRouter, + coachApiKeyLabel, + coachApiKeyLocalLabel, + coachListModels, + coachChatgptContinue, + coachSignInOpenRouter, + coachModelLabel, + actionSave,; @override String of(AppLocalizations l) => switch (this) { @@ -91,5 +108,24 @@ enum ScreenLabel implements GuideText { ScreenLabel.workoutStartSessionLabel => l.workoutStartSessionLabel, ScreenLabel.workoutTabHistory => l.workoutTabHistory, ScreenLabel.workoutTrackedLabel => l.workoutTrackedLabel, + ScreenLabel.homeProfileSettings => l.homeProfileSettings, + ScreenLabel.profileConnectedApps => l.profileConnectedApps, + // Connected apps prints it through uiText, which maps it to this getter. + ScreenLabel.connectedAppsAiCoach => l.profileAiCoach, + ScreenLabel.coachSetupNavTitle => l.coachSetupNavTitle, + // Provider names are brands the setup screen prints as literals. + ScreenLabel.coachOllama => 'Ollama', + ScreenLabel.coachLmStudio => 'LM Studio', + ScreenLabel.coachChatGpt => 'ChatGPT', + ScreenLabel.coachOpenAi => 'OpenAI', + ScreenLabel.coachAnthropic => 'Anthropic', + ScreenLabel.coachOpenRouter => 'OpenRouter', + ScreenLabel.coachApiKeyLabel => l.coachApiKeyLabel, + ScreenLabel.coachApiKeyLocalLabel => l.coachApiKeyLocalLabel, + ScreenLabel.coachListModels => l.coachListModels, + ScreenLabel.coachChatgptContinue => l.coachChatgptContinue, + ScreenLabel.coachSignInOpenRouter => l.coachSignInOpenRouter, + ScreenLabel.coachModelLabel => l.coachModelLabel, + ScreenLabel.actionSave => l.actionSave, }; } diff --git a/lib/ui2/guides/guide_navigation.dart b/lib/ui2/guides/guide_navigation.dart index 2a8f7e7c3..34458fb47 100644 --- a/lib/ui2/guides/guide_navigation.dart +++ b/lib/ui2/guides/guide_navigation.dart @@ -43,6 +43,8 @@ enum GuideNode { nutritionLog, coach, coachSetup, + profileHome, + connectedApps, circadian, sleepDebt, sleepConsistency, @@ -115,7 +117,11 @@ const guideNavigationTree = { 'LogFoodSheet', ]), GuideNode.coach: GuideDestination(GuideNode.today, ['CoachScreen']), - GuideNode.coachSetup: GuideDestination(GuideNode.coach, ['CoachSetup']), + // The settings door (coach.dart keeps it out of the chat's own menu): + // the avatar on any tab -> Profile -> Connected apps -> AI coach. + GuideNode.profileHome: GuideDestination(GuideNode.today, ['ProfileHome']), + GuideNode.connectedApps: GuideDestination(GuideNode.profileHome, ['ConnectedApps']), + GuideNode.coachSetup: GuideDestination(GuideNode.connectedApps, ['CoachSetup']), GuideNode.month: GuideDestination(GuideNode.today, ['MonthGrid']), GuideNode.whatChanged: GuideDestination(GuideNode.today, [ 'WhatChangedScreen', @@ -362,7 +368,7 @@ class GuideNavigation { }; static TargetFound? entry(Element page, GuideHop hop, AppLocalizations l) { - if (hop.node == GuideNode.settings) { + if (hop.node == GuideNode.settings || hop.node == GuideNode.profileHome) { final avatar = onstageElements(page) .where((e) => e.widget.runtimeType.toString() == 'ProfileAvatar') .firstOrNull; @@ -380,6 +386,8 @@ class GuideNavigation { GuideNode.review => ScreenLabel.activityReviewTitle, GuideNode.picker => ScreenLabel.workoutStartSessionLabel, GuideNode.logWorkout => ScreenLabel.workoutLogPastFix, + GuideNode.connectedApps => ScreenLabel.profileConnectedApps, + GuideNode.coachSetup => ScreenLabel.connectedAppsAiCoach, _ => null, }; if (label == null) return null; diff --git a/lib/ui2/guides/guide_run.dart b/lib/ui2/guides/guide_run.dart index ff1975a46..357dadff7 100644 --- a/lib/ui2/guides/guide_run.dart +++ b/lib/ui2/guides/guide_run.dart @@ -86,10 +86,29 @@ class GuideRun extends ChangeNotifier { // on every other screen (or become ambiguous with that button). final content = _contentOf(root); return [for (var i = 0; i < variant.steps.length; i++) - if ((!variant.steps[i].requiresPreviousTap || tappedSteps.contains(i - 1)) && + if (_eligible(variant, i, tappedSteps, content, l) && _anchorMatches(variant.steps[i].anchor.resolve(content, l))) i].lastOrNull; } + /// Step [i] applies on this page ([GuideStep.onlyWhen] / [GuideStep.unlessShown]). + static bool _applies(GuideStep step, Element content, AppLocalizations l) => + (step.onlyWhen == null || _anchorMatches(step.onlyWhen!.resolve(content, l))) && + (step.unlessShown == null || !_anchorMatches(step.unlessShown!.resolve(content, l))); + + /// Step [i]'s tap requirement is met: the step before it was tapped, or it is + /// a branch that does not apply here and ITS requirement is met. + static bool _ready(GuideVariant variant, int i, Set tapped, Element content, AppLocalizations l) { + if (!variant.steps[i].requiresPreviousTap) return true; + final prev = i - 1; + if (prev < 0) return false; + if (tapped.contains(prev)) return true; + final before = variant.steps[prev]; + return before.isBranch && !_applies(before, content, l) && _ready(variant, prev, tapped, content, l); + } + + static bool _eligible(GuideVariant variant, int i, Set tapped, Element content, AppLocalizations l) => + _applies(variant.steps[i], content, l) && _ready(variant, i, tapped, content, l); + static bool _anchorMatches(TargetResolution resolution) => resolution is TargetFound || resolution is TargetBehindAccordion; @@ -126,15 +145,14 @@ class GuideRun extends ChangeNotifier { final location = GuideNavigation.location(topPage); int? index; if (variant.steps.every((s) => s.node != null)) { + final content = _contentOf(topPage); final exact = [ for (var i = 0; i < variant.steps.length; i++) - if (variant.steps[i].node == location && - (!variant.steps[i].requiresPreviousTap || _tappedSteps.contains(i - 1))) i, + if (variant.steps[i].node == location && _eligible(variant, i, _tappedSteps, content, l)) i, ]; if (exact.isNotEmpty) { final anchored = exact.where( - (i) => - _anchorMatches(variant.steps[i].anchor.resolve(_contentOf(topPage), l)), + (i) => _anchorMatches(variant.steps[i].anchor.resolve(content, l)), ); index = anchored.lastOrNull ?? diff --git a/lib/ui2/guides/live_guide_overlay.dart b/lib/ui2/guides/live_guide_overlay.dart index 0d60688b7..967d413ac 100644 --- a/lib/ui2/guides/live_guide_overlay.dart +++ b/lib/ui2/guides/live_guide_overlay.dart @@ -73,7 +73,7 @@ import 'guide_target.dart'; import 'tree_geometry.dart'; import '../skeleton/skeleton.dart'; -import '../skeleton/unit_paint.dart' show hasLooseLayer, guideHoverMark; +import '../skeleton/unit_paint.dart' show hasLooseLayer, guideHoverMark, guideRowBand; import '../skeleton/guide_plot.dart' show GuideDecoration; import 'guide_dim.dart'; import 'guide_run.dart'; @@ -361,12 +361,14 @@ class LiveGuideOverlayState extends State with TickerProviderS final bindings = {}; final at = []; for (final target in _hl) { - final mark = guideHoverMark(target.object); + // One highlighted row spans its card; several in one card keep their own shapes (one hover per card). + final band = _hl.length == 1 ? guideRowBand(target.object) : null; + final mark = band?.$1 ?? guideHoverMark(target.object); if (mark == null || !mark.attached || !mark.hasSize || bindings.containsKey(mark)) { at.add(null); continue; } - final local = MatrixUtils.transformRect(target.object.getTransformTo(mark), Offset.zero & target.object.size); + final local = band?.$2 ?? MatrixUtils.transformRect(target.object.getTransformTo(mark), Offset.zero & target.object.size); final radius = math.min(target.radius, local.shortestSide / 2); final kept = _bound[mark]; final hover = kept != null && !kept.isDisposed && kept.rect == local && kept.radius == radius && kept.color == handColor @@ -1557,18 +1559,28 @@ class LiveGuideOverlayState extends State with TickerProviderS /// Every control element of [page] whose box holds [object] and is about its size (the control /// itself and the wrappers drawn tight around it: a page-wide gesture detector is no part of it). + /// When none does, the controls INSIDE [object]: a keyed unit drawn around its control (a text + /// field's box around the field). static List _controlsAround(Element page, RenderBox object) { - final found = []; + bool inside(RenderObject inner, RenderObject outer) { + for (RenderObject? o = inner; o != null; o = o.parent) { + if (identical(o, outer)) return true; + } + return false; + } + final found = [], within = []; for (final e in onstageElements(page)) { if (!isGuideControl(e.widget)) continue; final box = laidOutBox(e); if (box == null || !box.hasSize || !object.hasSize) continue; if (box.size.width > object.size.width + 24 || box.size.height > object.size.height + 24) continue; - for (RenderObject? o = object; o != null; o = o.parent) { - if (identical(o, box)) { found.add(e); break; } + if (inside(object, box)) { + found.add(e); + } else if (inside(box, object)) { + within.add(e); } } - return found; + return found.isEmpty ? within : found; } /// The other controls of the row [controls] sit in: the nearest Flex around the outermost one, @@ -1673,7 +1685,7 @@ class LiveGuideOverlayState extends State with TickerProviderS final state = run.state; final step = run.currentStep; final model = switch (state) { - GuideAtStep(:final index) => GuideCardOnStep(number: index + 1, total: run.variant.steps.length, + GuideAtStep(:final index) => GuideCardOnStep(number: run.variant.numberOf(index), total: run.variant.shownTotal, caption: _accordionHop == null ? run.variant.steps[index].captionFor(still: !Motion.enabled(context)).of(l) : l.guideExpandAccordion(_accordionHop!.title), missingHelp: run.guide.missingTargetHelp), GuideOffPath() => GuideCardOffPath(tapsBack: _returnHops), diff --git a/lib/ui2/screens/coach.dart b/lib/ui2/screens/coach.dart index f9281a6e3..aa1080830 100644 --- a/lib/ui2/screens/coach.dart +++ b/lib/ui2/screens/coach.dart @@ -936,6 +936,12 @@ List<_Preset> _presets(BuildContext c) { class CoachSetup extends StatefulWidget { const CoachSetup({super.key}); + /// The fields Help's coach-setup guide points at (guide_coach_setup.dart). + static const baseUrlKey = ValueKey('coach-setup-base-url'); + static const apiKeyKey = ValueKey('coach-setup-api-key'); + static const modelKey = ValueKey('coach-setup-model'); + static const modelListKey = ValueKey('coach-setup-model-list'); + @override State createState() => _CoachSetupState(); } @@ -1582,6 +1588,7 @@ class _CoachSetupState extends State with WidgetsBindingObserver { else ...[ const SizedBox(height: S.x2), OsTextField( + fieldKey: CoachSetup.baseUrlKey, controller: _base, label: l?.coachBaseUrlLabel ?? 'Base URL', hint: 'http://localhost:11434/v1', @@ -1636,6 +1643,7 @@ class _CoachSetupState extends State with WidgetsBindingObserver { ), const SizedBox(height: S.x4), OsTextField( + fieldKey: CoachSetup.apiKeyKey, controller: _key, label: _isLocal ? (l?.coachApiKeyLocalLabel ?? 'API key (not needed locally)') @@ -1689,6 +1697,7 @@ class _CoachSetupState extends State with WidgetsBindingObserver { ], const SizedBox(height: S.x4), OsTextField( + fieldKey: CoachSetup.modelKey, controller: _search, label: l?.coachModelLabel ?? 'Model', hint: l?.coachModelHint ?? 'search, or type an id', @@ -1703,6 +1712,8 @@ class _CoachSetupState extends State with WidgetsBindingObserver { const SizedBox(height: S.x1), Builder( builder: (_) => Padding( + // Only while it lists something: an empty list is no place to tap. + key: shown.isEmpty ? null : CoachSetup.modelListKey, padding: const EdgeInsets.only(top: S.x2), child: Column( children: [ diff --git a/lib/ui2/screens/journal_compose.dart b/lib/ui2/screens/journal_compose.dart index 0a25a2765..823b834d6 100644 --- a/lib/ui2/screens/journal_compose.dart +++ b/lib/ui2/screens/journal_compose.dart @@ -694,8 +694,12 @@ class OsTextField extends StatelessWidget { this.hint = '', this.lines = 1, this.keyboard, + this.fieldKey, }); + /// Keys the drawn field box, which is then one guide unit (a Help guide can + /// point at the field itself, not its label). + final Key? fieldKey; final TextEditingController controller; final String label; final String hint; @@ -710,7 +714,7 @@ class OsTextField extends StatelessWidget { children: [ Text(label.toUpperCase(), style: F.over.copyWith(color: p.ink3)), const SizedBox(height: S.x2), - Container( + _guided(Container( padding: const EdgeInsets.symmetric(horizontal: S.x3, vertical: S.x2), decoration: BoxDecoration( color: p.card, @@ -742,10 +746,12 @@ class OsTextField extends StatelessWidget { ), ), ), - ), + )), ], ); } + + Widget _guided(Widget field) => fieldKey == null ? field : GuideBox(key: fieldKey, child: field); } // ══════════════════════════ MT-03 · WEIGHT ══════════════════════════ diff --git a/lib/ui2/skeleton/unit_paint.dart b/lib/ui2/skeleton/unit_paint.dart index b45840913..3e2ad0197 100644 --- a/lib/ui2/skeleton/unit_paint.dart +++ b/lib/ui2/skeleton/unit_paint.dart @@ -28,7 +28,7 @@ import 'dart:ui' show ClipOp; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; -import '../grammar.dart' show Pressable; +import '../grammar.dart' show Pressable, Surface; import '../guides/guide_dim.dart'; import '../guides/guide_accordion.dart'; import '../guides/tree_geometry.dart'; @@ -128,6 +128,25 @@ RenderGuideUnit? guideHoverMark(RenderBox target) { return null; } +/// A row drawn inside a card's side padding, edge to edge with nothing else beside it (a settings +/// row in its group): the card paints its hover across the card's full width, so the highlight +/// covers the whole row and not just its content. Null for anything else (a button in a padded card +/// keeps its own shape). +(RenderGuideUnit, Rect)? guideRowBand(RenderBox target) { + for (RenderObject? parent = target.parent; parent != null; parent = parent.parent) { + if (parent is RenderAbstractViewport || parent is RenderSliver) return null; + if (parent is! RenderGuideUnit) continue; + final card = parent._component.widget; + if (card is! Surface || card.pad.top != 0 || card.pad.bottom != 0 || card.pad.horizontal == 0 || !parent.hasSize) { + return null; + } + final row = MatrixUtils.transformRect(target.getTransformTo(parent), Offset.zero & target.size); + final flush = (row.left - card.pad.left).abs() < 1 && (parent.size.width - card.pad.right - row.right).abs() < 1; + return flush ? (parent, Rect.fromLTRB(0, row.top, parent.size.width, row.bottom)) : null; + } + return null; +} + /// Paints the child, then the component's own look over it. class RenderGuideUnit extends RenderProxyBox { RenderGuideUnit(this._component, this._controller); diff --git a/test/support/guide_r2_scenes.dart b/test/support/guide_r2_scenes.dart index eaa0286e5..c1f6943b8 100644 --- a/test/support/guide_r2_scenes.dart +++ b/test/support/guide_r2_scenes.dart @@ -10,13 +10,19 @@ import 'package:openstrap_edge/ui2/guides/guide_run.dart'; import 'package:opens import 'package:openstrap_edge/ui2/guides/guide_target.dart'; import 'package:openstrap_edge/ui2/guides/live_guide_overlay.dart'; import 'package:openstrap_edge/ui2/profile/alarm.dart'; import 'package:openstrap_edge/ui2/screens/detected_activities.dart'; import 'package:openstrap_edge/ui2/screens/log_workout.dart'; import 'package:openstrap_edge/ui2/screens/naps.dart'; -import 'package:path/path.dart' as p; import 'package:sqflite_common_ffi/sqflite_ffi.dart'; import 'live_guide_harness.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:openstrap_edge/coach/coach_config.dart'; +import 'package:openstrap_edge/ui2/profile/connected_apps.dart'; import 'package:openstrap_edge/ui2/profile/profile.dart'; +import 'package:openstrap_edge/ui2/screens/coach.dart' show CoachSetup; import 'package:path/path.dart' as p; import 'package:sqflite_common_ffi/sqflite_ffi.dart'; import 'live_guide_harness.dart'; const r2Size = Size(412, 915); final r2Locale = lookupAppLocalizations(const Locale('en')); Guide r2Guide(String id) => kGuideCatalogue.firstWhere((e) => e.guide.id == id).guide; Finder r2Tabs({bool hidden = false}) => find.byWidgetPredicate( (w) => w.runtimeType.toString() == '_TabBar', skipOffstage: !hidden); Finder r2Tab(int index, {bool hidden = false}) => find.descendant( of: r2Tabs(hidden: hidden), matching: find.byWidgetPredicate( (w) => w.runtimeType.toString() == '_Tab', skipOffstage: !hidden), skipOffstage: !hidden).at(index); class R2Scene { final String guide, step; final Widget Function()? page; final bool history, staged, manual; - const R2Scene(this.guide, this.step, {this.page, this.history = false, this.staged = false, this.manual = false}); + /// Taps the run has already seen on this page: a step that waits for the previous step's tap (requiresPreviousTap). + final int priorTaps; + /// The AI settings form's provider, chosen before the run starts (null: the form's own default). + final String? provider; + const R2Scene(this.guide, this.step, {this.page, this.history = false, this.staged = false, this.manual = false, this.priorTaps = 0, this.provider}); String get id => '$guide/$step'; bool get shell => page == null; } final r2Scenes = [ const R2Scene('heart-rate-zones', 'open-strain'), R2Scene('heart-rate-zones', 'open-zones', page: () => const DayStrainDetail()), R2Scene('heart-rate-zones', 'set-own-zones', page: () => const ZonesDetail()), const R2Scene('alarm-schedule', 'open-alarm'), @@ -31,7 +37,25 @@ class R2Scene { final String guide, step; final Widget Function()? page; final b R2Scene('start-workout', 'start', page: () => ActivitySetup(quickStart.first, weightKg: 70)), R2Scene('start-workout', 'finish', page: () => liveFor(quickStart.first, weightKg: 70)), const R2Scene('log-past-workout', 'open-history'), const R2Scene('log-past-workout', 'log-past', history: true), - R2Scene('log-past-workout', 'log-it', page: () => const LogWorkout()), ]; + R2Scene('log-past-workout', 'log-it', page: () => const LogWorkout()), const R2Scene('coach-setup', 'coach-open-profile'), + R2Scene('coach-setup', 'coach-open-connected-apps', page: () => const ProfileHome()), + R2Scene('coach-setup', 'coach-open-ai-coach', page: () => const ConnectedApps()), + R2Scene('coach-setup', 'coach-pick-provider', page: () => const CoachSetup()), + R2Scene('coach-setup', 'coach-local-address', page: () => const CoachSetup(), priorTaps: 1, provider: 'Ollama'), + // The form opens on OpenAI (CoachConfig.defaultBaseUrl): the key field. + R2Scene('coach-setup', 'coach-paste-key', page: () => const CoachSetup(), priorTaps: 1), + R2Scene('coach-setup', 'coach-openrouter', page: () => const CoachSetup(), priorTaps: 1, provider: 'OpenRouter'), + R2Scene('coach-setup', 'coach-chatgpt', page: () => const CoachSetup(), priorTaps: 1, provider: 'ChatGPT'), + R2Scene('coach-setup', 'coach-list-models', page: () => const CoachSetup(), priorTaps: 2), + R2Scene('coach-setup', 'coach-pick-model', page: () => const CoachSetup(), priorTaps: 3), + R2Scene('coach-setup', 'coach-save', page: () => const CoachSetup(), priorTaps: 4), ]; +/// Chooses [provider] on the AI settings form. ChatGPT opens its terms sheet at once; the sheet is dismissed (the +/// sign-in cancelled), which leaves the form on ChatGPT with "Continue with ChatGPT" showing. +Future coachPickProvider(WidgetTester t, String provider) async { + final tile = find.text(provider).first; await t.ensureVisible(tile); await settleLiveGuide(t); await t.tap(tile); await settleLiveGuide(t); + if (provider == 'ChatGPT') { await t.tapAt(const Offset(10, 10)); await settleLiveGuide(t); } } +/// The coach's settings for a scene whose screens read them (and the keychain behind them); null for every other guide. +CoachConfig? r2CoachConfig(String guide) { if (guide != 'coach-setup') return null; FlutterSecureStorage.setMockInitialValues({}); return CoachConfig(); } Future r2OpenDb(String name) async { sqfliteFfiInit(); databaseFactory = databaseFactoryFfi; await LocalDb.close(); LocalDb.dbName = name; await databaseFactory.deleteDatabase(p.join(await databaseFactory.getDatabasesPath(), name)); } class R2Mounted { final LiveGuideApp app; final GuideRun run; final OverlayEntry? entry; final TargetResolution? initialTarget; @@ -44,7 +68,7 @@ Future pumpR2Scene(WidgetTester t, R2Scene scene, {Size size = r2Size final guide = r2Guide(scene.guide); repo ??= GuideFakeRepo(sleepSource: scene.manual ? 'manual' : 'auto', singlePending: singlePending); // The alarm buzzes the band, so its door only shows with one paired. final app = await pumpLiveGuideApp(t, size: size, repo: repo, brightness: brightness, captureKey: captureKey, devicePixelRatio: devicePixelRatio, - paired: scene.guide == 'alarm-schedule' ? PairedDevice('guide', 'guide-band', generation: 'gen4') : null); if (scene.shell) { + coachConfig: r2CoachConfig(scene.guide), paired: scene.guide == 'alarm-schedule' ? PairedDevice('guide', 'guide-band', generation: 'gen4') : null); if (scene.shell) { // Use the shipped runner here: tab-navigation signals may be owned by GuideRunner. A separately inserted run would bypass that real seam. final started = await app.runner.start(guide, band: null); expect(started, isA()); final run = (started as GuideStarted).run; @@ -58,10 +82,17 @@ Future pumpR2Scene(WidgetTester t, R2Scene scene, {Size size = r2Size await t.tap(r2Tab(index)); await settleLiveGuide(t); if (scene.page != null) { // Pin the review's pending data at entry: unrelated remembered moment follow-ups must not select another day in this activity-only fixture. final page = scene.guide == 'remove-detected' ? DetectedActivitiesScreen(preloaded: await repo.pendingActivities()) : scene.page!(); - app.navigator.push(MaterialPageRoute(builder: (_) => page)); await settleLiveGuide(t); } + app.navigator.push(MaterialPageRoute(builder: (_) => page)); await settleLiveGuide(t); + if (scene.provider != null) await coachPickProvider(t, scene.provider!); } final run = GuideRun(guide: guide, variant: (guide.variantFor(null) as GuideVariantFound).variant); final entry = OverlayEntry(builder: (_) => LiveGuideOverlay(run: run, navigatorKey: app.navigatorKey, routes: app.runner.routes, onExit: run.exit, onBackToGuide: () => app.navigator.maybePop())); app.navigator.overlay!.insert(entry); + // Tap through the earlier steps on this page until the run is on the scene's own step. A real tap rebuilds the + // form (setState), which re-plans the overlay and so re-observes the page; the bare targetTapped() changes nothing + // on screen, so the scene observes for it. + for (var i = 0; i < scene.priorTaps * 3 && run.currentStep?.id != scene.step; i++) { + await settleLiveGuide(t); if (run.currentStep?.id == scene.step) break; run.targetTapped(); run.observe(app.runner.routes.page, r2Locale); } + if (scene.priorTaps > 0) { await settleLiveGuide(t); expect(run.currentStep?.id, scene.step, reason: '${scene.id}: the earlier taps reach the step'); } final initial = run.variant.steps.firstWhere((s) => s.id == scene.step).target .resolve(app.runner.routes.page!, r2Locale); final mounted = R2Mounted(app, run, entry, initialTarget: initial); addTearDown(() { mounted.removeOverlay(); run.dispose(); }); return mounted; } Future disposeR2(WidgetTester t, R2Mounted mounted) async { mounted.removeOverlay(); await t.pumpWidget(const SizedBox()); mounted.app.dispose(); await t.pump(); } diff --git a/test/ui2/guide_catalogue_test.dart b/test/ui2/guide_catalogue_test.dart index e700e5d48..3913d29d6 100644 --- a/test/ui2/guide_catalogue_test.dart +++ b/test/ui2/guide_catalogue_test.dart @@ -29,16 +29,16 @@ void main() { group('helpGroups', () { final entries = [ GuideEntry(GuideTopic.a final groups = helpGroups([GuideEntry(GuideTopic.health, _only5), GuideEntry(GuideTopic.sleep, _any)], BandGeneration.whoop4); expect([for (final g in groups) g.topic], [GuideTopic.sleep]); }); test('nothing to list gives no groups', () { expect(helpGroups(const [], null), isEmpty); expect(helpGroups([GuideEntry(GuideTopic.today, _only5)], BandGeneration.whoop4), isEmpty); }); }); - group('the shipped catalogue', () { test('guides #1-#8, once each, filed under the tab they start on', () { - // why: #1 starts on the Today ring, #2/#3/#5 on the Sleep tab, #4 on the Today "Detected activities" card, #6-#8 on the Activity tab. + group('the shipped catalogue', () { test('guides #1-#9, once each, filed under the tab they start on', () { + // why: #1 starts on the Today ring, #2/#3/#5 on the Sleep tab, #4 on the Today "Detected activities" card, #6-#8 on the Activity tab, #9 on Today's profile avatar. final byId = {for (final e in kGuideCatalogue) e.guide.id: e.topic}; expect(kGuideCatalogue.map((e) => e.guide.id).toList(), [ 'heart-rate-zones', 'alarm-schedule', 'add-nap', 'remove-detected', 'fix-sleep-times', 'delete-workout', 'start-workout', - 'log-past-workout', ]); expect(byId, { 'heart-rate-zones': GuideTopic.today, 'alarm-schedule': GuideTopic.sleep, + 'log-past-workout', 'coach-setup', ]); expect(byId, { 'heart-rate-zones': GuideTopic.today, 'alarm-schedule': GuideTopic.sleep, 'add-nap': GuideTopic.sleep, 'remove-detected': GuideTopic.today, 'fix-sleep-times': GuideTopic.sleep, - 'delete-workout': GuideTopic.activity, 'start-workout': GuideTopic.activity, 'log-past-workout': GuideTopic.activity, }); }); + 'delete-workout': GuideTopic.activity, 'start-workout': GuideTopic.activity, 'log-past-workout': GuideTopic.activity, 'coach-setup': GuideTopic.today, }); }); test('grouped for an unknown band: Today, Sleep, Activity in catalogue order', () { final groups = helpGroups(kGuideCatalogue, null); expect([for (final g in groups) g.topic], [GuideTopic.today, GuideTopic.sleep, GuideTopic.activity]); - expect([for (final g in groups) [for (final e in g.entries) e.guide.id]], [ ['heart-rate-zones', 'remove-detected'], + expect([for (final g in groups) [for (final e in g.entries) e.guide.id]], [ ['heart-rate-zones', 'remove-detected', 'coach-setup'], ['alarm-schedule', 'add-nap', 'fix-sleep-times'], ['delete-workout', 'start-workout', 'log-past-workout'], ]); }); }); group('live-run model: start destination and footer roles', () { test('a guide starts on the shell tab it is filed under', () { // why: GuideTopic is "the tab its first step is on"; the run brings the app to Guide.start. A guide filed under Sleep that starts on Today would put @@ -49,7 +49,7 @@ void main() { group('helpGroups', () { final entries = [ GuideEntry(GuideTopic.a // guideFixTimesBackTitle / guideDeleteNoneTitle): guide #7 has only notes. #3 (add-nap) has // one on integrate/next, where its Naps button sits in a section the person may have folded. final l = lookupAppLocalizations(const Locale('en')); final withHelp = {for (final e in kGuideCatalogue) if (e.guide.missingTargetHelp != null) e.guide.id}; - expect(withHelp, {'heart-rate-zones', 'alarm-schedule', 'add-nap', 'remove-detected', 'fix-sleep-times', 'delete-workout', 'log-past-workout'}); + expect(withHelp, {'heart-rate-zones', 'alarm-schedule', 'add-nap', 'remove-detected', 'fix-sleep-times', 'delete-workout', 'log-past-workout', 'coach-setup'}); for (final id in withHelp) { final title = kGuideCatalogue.firstWhere((e) => e.guide.id == id).guide.missingTargetHelp!.title.of(l); expect(title, endsWith('?'), reason: '$id: the missing-target footer is a question ($title)'); } }); test('the Done card shows every footer except the missing-target help, in the guide\'s order', () { @@ -66,4 +66,16 @@ void main() { group('helpGroups', () { final entries = [ GuideEntry(GuideTopic.a expect(bandGenerationOf(PairedDevice('r', 's', generation: 'gen4')), BandGeneration.whoop4); expect(bandGenerationOf(PairedDevice('r', 's', generation: 'gen5')), BandGeneration.whoop5); expect(bandGenerationOf(PairedDevice('r', 's')), isNull); expect(bandGenerationOf(null), isNull); - expect(bandGenerationOf(PairedDevice('r', 's', generation: 'ble_hrs')), isNull); expect(bandGenerationOf(PairedDevice('r', 's', generation: '')), isNull); }); }); } + expect(bandGenerationOf(PairedDevice('r', 's', generation: 'ble_hrs')), isNull); expect(bandGenerationOf(PairedDevice('r', 's', generation: '')), isNull); }); }); + test('the card counts adjacent branch steps as one: the user walks only one of them', () { + // why: the AI coach guide has one step per provider (a model on your computer, a key, OpenRouter, ChatGPT); + // numbered by index, OpenAI read "4" then "6" and the dots promised steps the user never sees. + final steps = (kGuideCatalogue.firstWhere((e) => e.guide.id == 'coach-setup').guide.variantFor(null) as GuideVariantFound).variant; + final numbers = {for (final (i, s) in steps.steps.indexed) s.id: steps.numberOf(i)}; + expect(numbers['coach-pick-provider'], 4); + for (final id in ['coach-local-address', 'coach-paste-key', 'coach-openrouter', 'coach-chatgpt']) { expect(numbers[id], 5, reason: id); } + expect(numbers['coach-list-models'], 6); expect(numbers['coach-save'], 8); expect(steps.shownTotal, 8); + // A guide with no branch steps numbers them 1..n as before. + final plain = (kGuideCatalogue.firstWhere((e) => e.guide.id == 'start-workout').guide.variantFor(null) as GuideVariantFound).variant; + expect([for (var i = 0; i < plain.steps.length; i++) plain.numberOf(i)], [for (var i = 1; i <= plain.steps.length; i++) i]); + expect(plain.shownTotal, plain.steps.length); }); } diff --git a/test/ui2/guide_conformance_test.dart b/test/ui2/guide_conformance_test.dart index a96566f28..817ba38b0 100644 --- a/test/ui2/guide_conformance_test.dart +++ b/test/ui2/guide_conformance_test.dart @@ -22,6 +22,8 @@ import 'package:openstrap_edge/ui2/guides/guide_catalogue.dart'; import 'package import 'package:openstrap_edge/ui2/profile/alarm.dart' show AlarmScreenView; import 'package:openstrap_edge/ui2/screens/screens.dart'; import 'package:openstrap_edge/ui2/screens/detected_activities.dart' show DetectedActivitiesScreen; import 'package:openstrap_edge/ui2/screens/log_workout.dart' show LogWorkout; import 'package:openstrap_edge/ui2/screens/sleep_tab.dart' show SleepTab; import 'package:path/path.dart' as p; import 'package:sqflite_common_ffi/sqflite_ffi.dart'; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import '../support/guide_r2_scenes.dart' show coachPickProvider; import 'package:openstrap_edge/coach/coach_config.dart' show CoachConfig; +import 'package:openstrap_edge/ui2/profile/connected_apps.dart' show ConnectedApps; import 'package:openstrap_edge/ui2/profile/profile.dart' show ProfileHome; import '../support/guide_search.dart'; import '../support/live_guide_harness.dart'; /// One step on its real screen. class _Scene { final String guideId, stepId; @@ -32,7 +34,9 @@ class _Scene { final String guideId, stepId; /// The state the user is in when the step shows (a sub-tab already tapped). final Future Function(WidgetTester t, AppLocalizations l)? prepare; /// 'manual' = the user has set the sleep times themselves. - final String sleepSource; const _Scene(this.guideId, this.stepId, this.screen, this.home, this.label, {this.printed = true, this.prepare, this.sleepSource = 'auto'}); } + final String sleepSource; + /// The screen reads the coach's settings (a CoachConfig provider above it). + final bool coach; const _Scene(this.guideId, this.stepId, this.screen, this.home, this.label, {this.printed = true, this.prepare, this.sleepSource = 'auto', this.coach = false}); } Widget _tab(Widget w) => Scaffold(body: w); Future _tapHistory(WidgetTester t, AppLocalizations l) async { // At 1.3x many translations put History outside the horizontal viewport. A tap at its offscreen centre does not select the tab. await t.ensureVisible(find.text(l.workoutTabHistory)); await t.pump(); await t.tap(find.text(l.workoutTabHistory)); await settleLiveGuide(t); } @@ -57,11 +61,26 @@ final _tuesdayOn = fillDefaultAlarmSchedule([const AlarmScheduleEntry(weekday: 1 _Scene('start-workout', 'finish', Scaffold, () => liveFor(quickStart.first, weightKg: 70), (l) => l.activityLiveFinishSessionLabel, printed: false), _Scene('log-past-workout', 'open-history', WorkoutScreen, () => _tab(const WorkoutScreen()), (l) => l.workoutTabHistory), _Scene('log-past-workout', 'log-past', WorkoutScreen, () => _tab(const WorkoutScreen()), (l) => l.workoutLogPastFix, prepare: _tapHistory), - _Scene('log-past-workout', 'log-it', LogWorkout, () => const LogWorkout(), (l) => l.logWorkoutLogIt), ]; + _Scene('log-past-workout', 'log-it', LogWorkout, () => const LogWorkout(), (l) => l.logWorkoutLogIt), + // The avatar is an icon (or an initial): its semantics label is the oracle. + _Scene('coach-setup', 'coach-open-profile', HomeScreen, () => _tab(const HomeScreen()), (l) => l.homeProfileSettings, printed: false), + _Scene('coach-setup', 'coach-open-connected-apps', ProfileHome, () => const ProfileHome(), (l) => l.profileConnectedApps), + _Scene('coach-setup', 'coach-open-ai-coach', ConnectedApps, () => const ConnectedApps(), (l) => l.profileAiCoach, coach: true), + _Scene('coach-setup', 'coach-pick-provider', CoachSetup, () => const CoachSetup(), (l) => 'Ollama', coach: true), + _Scene('coach-setup', 'coach-local-address', CoachSetup, () => const CoachSetup(), (l) => l.coachBaseUrlLabel, printed: false, coach: true, + prepare: (t, l) => coachPickProvider(t, 'Ollama')), + _Scene('coach-setup', 'coach-paste-key', CoachSetup, () => const CoachSetup(), (l) => l.coachApiKeyLabel, printed: false, coach: true), + _Scene('coach-setup', 'coach-openrouter', CoachSetup, () => const CoachSetup(), (l) => l.coachSignInOpenRouter, coach: true, + prepare: (t, l) => coachPickProvider(t, 'OpenRouter')), + _Scene('coach-setup', 'coach-chatgpt', CoachSetup, () => const CoachSetup(), (l) => l.coachChatgptContinue, coach: true, + prepare: (t, l) => coachPickProvider(t, 'ChatGPT')), + _Scene('coach-setup', 'coach-list-models', CoachSetup, () => const CoachSetup(), (l) => l.coachListModels, coach: true), + _Scene('coach-setup', 'coach-pick-model', CoachSetup, () => const CoachSetup(), (l) => l.coachModelLabel, printed: false, coach: true), + _Scene('coach-setup', 'coach-save', CoachSetup, () => const CoachSetup(), (l) => l.actionSave, coach: true), ]; GuideStep _stepOf(_Scene s) { final guide = kGuideCatalogue.firstWhere((e) => e.guide.id == s.guideId).guide; final variant = (guide.variantFor(null) as GuideVariantFound).variant; return variant.steps.firstWhere((x) => x.id == s.stepId); } Finder _printed(String label) => find.byWidgetPredicate( (w) => w is Text && (w.data ?? w.textSpan?.toPlainText() ?? '').trim().toLowerCase() == label.trim().toLowerCase()); -void main() { setUpAll(() async { sqfliteFfiInit(); databaseFactory = databaseFactoryFfi; await LocalDb.close(); +void main() { setUpAll(() async { FlutterSecureStorage.setMockInitialValues({}); sqfliteFfiInit(); databaseFactory = databaseFactoryFfi; await LocalDb.close(); LocalDb.dbName = 'guide_conformance_test.db'; final dir = await databaseFactory.getDatabasesPath(); await databaseFactory.deleteDatabase(p.join(dir, LocalDb.dbName)); }); tearDownAll(() async => LocalDb.close()); test('CLAIM(guide-covered): the table covers exactly the catalogue\'s steps, once each', () { @@ -69,11 +88,11 @@ void main() { setUpAll(() async { sqfliteFfiInit(); databaseFactory = databaseFa final shipped = { for (final e in kGuideCatalogue) for (final v in e.guide.variants) for (final s in v.steps) '${e.guide.id}/${s.id}', }; final covered = [for (final s in _scenes) '${s.guideId}/${s.stepId}']; expect(covered.toSet(), hasLength(covered.length), reason: 'no scene twice'); expect(covered.toSet(), shipped); - expect(shipped, hasLength(21), reason: 'guide #1 has 3 steps, #2 3, #3 2, #4 2, #5 2, #6 2, #7 4, #8 3'); }); + expect(shipped, hasLength(32), reason: 'guide #1 has 3 steps, #2 3, #3 2, #4 2, #5 2, #6 2, #7 4, #8 3, #9 11'); }); for (final locale in AppLocalizations.supportedLocales) { group(locale.languageCode, () { for (final scene in _scenes) { testWidgets('${scene.guideId} / ${scene.stepId}: anchor and target resolve on the real ${scene.screen}', (t) async { final l = lookupAppLocalizations(locale); await pumpLiveGuideApp(t, home: scene.home(), locale: locale, textScale: 1.3, - repo: GuideFakeRepo(sleepSource: scene.sleepSource), + repo: GuideFakeRepo(sleepSource: scene.sleepSource), coachConfig: scene.coach ? CoachConfig() : null, // The alarm's door only shows with a band paired. paired: scene.guideId == 'alarm-schedule' ? PairedDevice('guide', 'guide-band', generation: 'gen4') : null); await settleLiveGuide(t, frames: 30); await scene.prepare?.call(t, l); await settleLiveGuide(t, frames: 30); final step = _stepOf(scene); final screens = find.byType(scene.screen).evaluate().toList(); diff --git a/test/ui2/guide_r5_scenes_test.dart b/test/ui2/guide_r5_scenes_test.dart index 30c494da0..e17a03ecf 100644 --- a/test/ui2/guide_r5_scenes_test.dart +++ b/test/ui2/guide_r5_scenes_test.dart @@ -56,7 +56,7 @@ GuideUnitLook? _look(Element e) => GuideDimScope.controllerOf(e)?.looks?.lookOf( // is covered until the next one. At NO frame from the push on may the back arrow be a placeholder or absorb a tap. CLAIM(back-arrow-always-usable). // catches: GuidePlan._unseen treating chrome like content. for (final scene in _pageScenes) { testWidgets('R5-4c ${scene.id}: the back arrow is usable in every frame of the page\'s arrival', (t) async { - final repo = GuideFakeRepo(singlePending: false); final app = await pumpLiveGuideApp(t, size: r2Size, repo: repo); final guide = r2Guide(scene.guide); + final repo = GuideFakeRepo(singlePending: false); final app = await pumpLiveGuideApp(t, size: r2Size, repo: repo, coachConfig: r2CoachConfig(scene.guide)); final guide = r2Guide(scene.guide); final run = GuideRun(guide: guide, variant: (guide.variantFor(null) as GuideVariantFound).variant); try { await t.tap(r2Tab(ShellDomain.values.byName(guide.start.name).index)); await settleLiveGuide(t); final entry = OverlayEntry(builder: (_) => LiveGuideOverlay(run: run, navigatorKey: app.navigatorKey, routes: app.runner.routes, onExit: run.exit, onBackToGuide: () {})); @@ -75,7 +75,7 @@ GuideUnitLook? _look(Element e) => GuideDimScope.controllerOf(e)?.looks?.lookOf( // back (or at least chrome): lit, not a placeholder, and it takes taps. CLAIM(back-arrow-always-usable). // catches: off-path plans that dim or cover the app bar, a route control that is not the arrow. for (final scene in _pageScenes) { testWidgets('R5-4d ${scene.id}: off path, the back arrow is lit and takes taps', (t) async { - final repo = GuideFakeRepo(singlePending: false); final app = await pumpLiveGuideApp(t, size: r2Size, repo: repo); + final repo = GuideFakeRepo(singlePending: false); final app = await pumpLiveGuideApp(t, size: r2Size, repo: repo, coachConfig: r2CoachConfig(scene.guide)); final guide = r2Guide(scene.guide == 'heart-rate-zones' ? 'alarm-schedule' : 'heart-rate-zones'); final run = GuideRun(guide: guide, variant: (guide.variantFor(null) as GuideVariantFound).variant); try { final entry = OverlayEntry(builder: (_) => LiveGuideOverlay(run: run, navigatorKey: app.navigatorKey, routes: app.runner.routes, onExit: run.exit, onBackToGuide: () {})); diff --git a/test/ui2/help_screen_test.dart b/test/ui2/help_screen_test.dart index c5cbf3821..1dab944a3 100644 --- a/test/ui2/help_screen_test.dart +++ b/test/ui2/help_screen_test.dart @@ -116,7 +116,7 @@ void main() { setUp(() => SharedPreferences.setMockInitialValues({})); testWidgets('the shipped catalogue: all eight guides for an unknown band, titles in the app language', (t) async { // why: the default list is the catalogue; rows show the translated title. await _pumpHelp(t, locale: const Locale('ru')); final l = lookupAppLocalizations(const Locale('ru')); - expect(kGuideCatalogue, hasLength(8)); for (final e in kGuideCatalogue) { final row = find.byKey(HelpScreen.guideRowKey(e.guide.id)); + expect(kGuideCatalogue, hasLength(9)); for (final e in kGuideCatalogue) { final row = find.byKey(HelpScreen.guideRowKey(e.guide.id)); expect(row, findsOneWidget, reason: e.guide.id); expect(find.descendant(of: row, matching: find.text(e.guide.title.of(l))), findsOneWidget); } expect(t.takeException(), isNull); }); testWidgets('semantics: headings are headings, rows are tappable and named by the guide, read in order', (t) async { diff --git a/test/ui2/live_guide_integration_test.dart b/test/ui2/live_guide_integration_test.dart index 05c165872..233a2bae5 100644 --- a/test/ui2/live_guide_integration_test.dart +++ b/test/ui2/live_guide_integration_test.dart @@ -18,6 +18,8 @@ import 'package:openstrap_edge/ui2/guides/guide_catalogue.dart'; import 'package import 'package:openstrap_edge/ui2/guides/guide_runner.dart'; import 'package:openstrap_edge/ui2/guides/guide_step_card.dart'; import 'package:openstrap_edge/ui2/guides/help_screen.dart'; import 'package:openstrap_edge/ui2/guides/live_guide_overlay.dart'; import 'package:openstrap_edge/ui2/screens/screens.dart'; import 'package:openstrap_edge/ui2/grammar.dart' show Surface; +import 'package:flutter_secure_storage/flutter_secure_storage.dart'; import 'package:openstrap_edge/coach/coach_config.dart'; +import 'package:openstrap_edge/ui2/profile/profile.dart' show ProfileAvatar; import 'package:path/path.dart' as p; import 'package:sqflite_common_ffi/sqflite_ffi.dart'; import '../support/live_guide_harness.dart'; // skipOffstage: false - while Help is open the shell is offstage under it. AppLocalizations _l(WidgetTester t) => AppLocalizations.of(t.element(find.byType(AppMainShell, skipOffstage: false)))!; @@ -32,7 +34,9 @@ int _step(LiveGuideApp app) => (_run(app).state as GuideAtStep).index; Guide _gu /// user would, then lets the run bring the app to the start and reveal step 1. Future _startFromHelp(WidgetTester t, LiveGuideApp app, String guideId) async { app.navigator.push(MaterialPageRoute(builder: (_) => const HelpScreen())); await settleLiveGuide(t); - final row = find.byKey(HelpScreen.guideRowKey(guideId)); await t.ensureVisible(row); await t.pump(); + final row = find.byKey(HelpScreen.guideRowKey(guideId)); + // The list is lazy: a row far down is not built until the list scrolls towards it. + await t.scrollUntilVisible(row, 200, scrollable: find.descendant(of: find.byType(HelpScreen), matching: find.byType(Scrollable)).first); await t.pump(); expect(row.hitTestable(), findsOneWidget, reason: 'the Help row is visible before the user taps it'); await t.tap(row); await settleLiveGuide(t, frames: 18); } Future _reveal(WidgetTester t) => settleLiveGuide(t, frames: 18); Future _dbChanges() async => ((await (await LocalDb.instance) .rawQuery('SELECT total_changes() AS n')).single['n'] as num).toInt(); @@ -176,4 +180,23 @@ void main() { setUpAll(() async { sqfliteFfiInit(); databaseFactory = databaseFa await t.tap(_label(l.workoutTabHistory)); await _reveal(t); expect(_step(app), 1); expect(find.byKey(LiveGuideOverlay.scrollMarkerKey), findsNothing, reason: 'revealed and in view: no scroll indicator'); expect(liveGuideFocus, findsOneWidget); expect(_label(l.workoutLogPastFix), findsOneWidget); await t.tap(_label(l.workoutLogPastFix)); - await _reveal(t); expect(_step(app), 2); expect(_caption(t), _plain(l.guideLogPastStep3(l.logWorkoutWhenGroup, l.logWorkoutLogIt))); }); }); } + await _reveal(t); expect(_step(app), 2); expect(_caption(t), _plain(l.guideLogPastStep3(l.logWorkoutWhenGroup, l.logWorkoutLogIt))); }); }); + group('guide #9 set up the AI coach', () { + testWidgets('avatar -> Profile -> Connected apps -> AI coach -> a provider -> the key step, on the real screens', (t) async { + // why: the guide's route runs through pages the navigation tree only learnt for it (ProfileHome, ConnectedApps, CoachSetup + // under them), and its later steps share one screen and wait for the previous tap instead of jumping ahead on their anchors. + FlutterSecureStorage.setMockInitialValues({}); final app = await pumpLiveGuideApp(t, coachConfig: CoachConfig()); + await _startFromHelp(t, app, 'coach-setup'); final l = _l(t); expect(_step(app), 0); + expect(_caption(t), _plain(l.guideCoachStep1(l.homeProfileSettings))); + await t.tap(find.byType(ProfileAvatar).hitTestable().first); await _reveal(t); expect(_step(app), 1); + await t.tap(_label(l.profileConnectedApps)); await _reveal(t); expect(_step(app), 2); + await t.tap(_label('AI coach')); await _reveal(t); expect(find.byType(CoachSetup), findsOneWidget); expect(_step(app), 3, + reason: 'every control of the form is built at once; the key step must wait for a provider to be picked'); + await t.ensureVisible(_label('OpenAI')); await t.pump(); await t.tap(_label('OpenAI')); await _reveal(t); + // The steps for a model on your own computer (4), OpenRouter (6) and ChatGPT (7) are passed over for OpenAI. + expect(_step(app), 5); expect(_caption(t), _plain(l.guideCoachPasteKey(l.coachApiKeyLabel))); + final field = find.byKey(CoachSetup.apiKeyKey); + expect(t.getRect(find.byKey(GuideStepCard.cardKey)).overlaps(t.getRect(field)), isFalse, reason: 'the card leaves the key field free to paste into'); + await t.tap(find.descendant(of: field, matching: find.byType(TextField))); await _reveal(t); expect(_step(app), 8); + expect(_caption(t), _plain(l.guideCoachListModels(l.coachListModels))); + expect(t.getRect(find.byKey(GuideStepCard.cardKey)).overlaps(t.getRect(field)), isFalse, reason: 'still free while the key is pasted'); }); }); }