diff --git a/.claude/settings.local.json b/.claude/settings.local.json index 233e812..ac624df 100644 --- a/.claude/settings.local.json +++ b/.claude/settings.local.json @@ -28,7 +28,8 @@ "Bash(curl:*)", "Bash(python:*)", "Bash(npm test:*)", - "Skill(bmad:bmm:agents:ux-designer)" + "Skill(bmad:bmm:agents:ux-designer)", + "Skill(bmad:bmm:workflows:create-prd)" ] } } diff --git a/_bmad-output/analysis/brainstorming-session-2026-01-09.md b/_bmad-output/analysis/brainstorming-session-2026-01-09.md new file mode 100644 index 0000000..438b08c --- /dev/null +++ b/_bmad-output/analysis/brainstorming-session-2026-01-09.md @@ -0,0 +1,443 @@ +--- +stepsCompleted: [1, 2, 3] +inputDocuments: [] +session_topic: 'Amélioration de l''utilisation de l''IA dans Memento' +session_goals: 'Explorer des cas d''usage IA pertinents, définir l''architecture multilingue, prioriser les fonctionnalités par valeur utilisateur' +selected_approach: 'ai-recommended' +techniques_used: ['SCAMPER Method', 'Future Self Interview', 'Six Thinking Hats'] +ideas_generated: ['20+ idées SCAMPER', 'Solution 3-couches confiance', '7 alternatives créatives Six Hats'] +context_file: '' +session_status: 'completed' +completion_date: '2026-01-09' +--- + +# Brainstorming Session Results + +**Facilitator:** AI Brainstorming Guide +**Date:** 2026-01-09 + +## Session Overview + +**Topic:** Amélioration de l'utilisation de l'IA dans Memento + +**Goals:** +- Explorer des cas d'usage IA pertinents pour une app de prise de notes +- Définir l'architecture multilingue (prompts système en anglais, données en langue utilisateur) +- Prioriser les fonctionnalités par valeur utilisateur + +## Technique Selection + +**Approach:** AI-Recommended Techniques + +**Analysis Context:** Amélioration IA dans Memento avec focus sur cas d'usage pertinents, architecture multilingue et priorisation + +**Recommended Techniques:** + +### Phase 1: SCAMPER Method (Structured) ✅ TERMINÉ +**Why this fits:** Vous avez déjà 3 idées de base. SCAMPER permet de les expandre systématiquement selon 7 dimensions créatives +**Expected outcome:** 15-20 variantes et améliorations des 3 idées initiales ✅ ATTEINT + +### Phase 2: Future Self Interview (Introspective Delight) 🔄 EN COURS +**Why this builds on Phase 1:** Projection dans le futur pour comprendre les vrais besoins utilisateurs et frictions potentielles +**Expected outcome:** Compréhension profonde des besoins réels et problèmes d'usage + +### Phase 3: Six Thinking Hats (Structured) +**Why this concludes effectively:** Vision complète des implications techniques, UX et business pour l'architecture multilingue +**Expected outcome:** Architecture multilingue robuste avec analyse multi-perspectives + +--- + +## Phase 1: SCAMPER Method - Results + +### S - Substitute: Pattern ON/OFF +**Idées clés:** +- Auto-description d'images ON/OFF → Bouton transparent sur image quand OFF +- Auto-reformulation ON/OFF → Bouton crayon sur paragraphes + menu contextuel +- Auto-titres ON/OFF → 3 suggestions IA sous champ titre +- Page Settings IA avec checkboxes pour chaque fonctionnalité +- Philosophie: "Zéro friction par défaut, mais contrôlable" + +### C - Combine: Hybrides intelligents +**Idées clés:** +- Images + Titres → Photo sans titre → analyse + titre auto +- Reformulation + Titres → Bouton "Optimiser la note" → contenu + titre +- Mode "Super IA" → Un bouton pour TOUT faire d'un coup +- Tags hybrides → Catégories IA hiérarchiques + tags utilisateur personnalisés + +### A - Adapt: Extensions contextuelles +**Idées clés:** +- Liens/URLs → Bouton IA pour résumer OU extraire points clés (choix paramètres) +- Codes/citations → IA explique le contexte +- Recherche sémantique → "Rechercher par sens" au lieu de mots-clés +- Multilinguisme → Détection automatique par note + bouton régénération + +### M - Modify: Améliorations UX +**Idées clés:** +- Tags hybrides → Catégories IA (hiérarchiques) + tags perso +- Choix paramètres → Options configurables (résumé vs bullets vs analyse) +- Proposition langue → IA détecte + propose/confirme avant générer +- Bouton → Décision par A/B testing plus tard (itération pragmatique) + +### P - Put to Other Uses: Extensions futures +**Idées clés:** +- Audio → Transcription + résumé notes vocales (pour plus tard) +- IA priorisation → Organisation auto des notes +- Business model → Freemium avec IA payante (type n8n, "paiement un café") +- Contrainte Zéro DevOps → Solutions managées (Vercel, Netlify) + +### E - Eliminate: Simplification +**Idées clés:** +- RÉTABLISSEMENT: Garde la détection AUTO de la langue (plus prévisible) +- Bouton → Test A/B des scénarios pour décision itérative + +### R - Reverse: Inversions innovantes +**Idées clés:** +- Workflow inversé → IA propose des brouillons basés sur patterns historiques +- Rôle inversé → IA donne conseils d'organisation et structuration +- Priorité inversée → IA suggère des suites logiques après chaque note +- Travail fond (NON) → Pas d'IA en arrière-plan pendant sommeil + +**Total idées générées:** 20+ concepts concrets + +--- + +## Phase 2: Future Self Interview - Results ✅ + +**Approche:** Projection temporelle pour comprendre vrais besoins utilisateurs + +### Interview Insights: + +**Fonctionnalité la plus appréciée:** +- 🎯 **"IA suggère des suites logiques"** - Gain de temps, évite d'oublier, flux de travail fluide + +**Principal défi identifié:** +- ⚠️ **Hallucinations de l'IA** - Erreurs, inventions, pertes de confiance + +### Solution Élégante Proposée: Système de Confiance à 3 Couches + +**1. Score de Confiance (Transparence)** +- Score % affiché pour chaque génération IA +- >90% = ✅ Solide (auto-application) +- 70-89% = ⚠️ Moyen (à vérifier) +- <70% = ❌ Faible (pas d'auto-génération) + +**2. Feedback & Apprentissage** +- Boutons 👍👎 à côté de chaque génération +- "Ça marche!" → IA retient les patterns positifs +- "Faux" → IA apprend et évite les erreurs + +**3. Mode Conservatif (Safety First)** +- Générations auto seulement si confiance >90% +- Si doute: IA demande confirmation + +--- + +## Phase 3: Six Thinking Hats - Results ✅ + +**Approche:** Vision multi-perspectives pour validation complète de l'architecture multilingue et des fonctionnalités IA + +--- + +### 🎩 White Hat - Faits & Techniques (Architecture) + +**Faits techniques actuels:** +- Stack Next.js 15 + Prisma + SQLite +- IA providers supportés: Ollama, OpenAI, Custom OpenAI +- Tags AI déjà implémenté avec embeddings +- Base de données existante avec User, Note, Label +- Système auth fonctionnel + +**Besoins techniques identifiés:** +- API embeddings pour recherche sémantique (vector search) +- API generation pour titres, résumés, reformulations +- Stockage embeddings dans DB (nouvelle colonne/vector DB) +- Scoring de confiance (mécanisme interne IA ou meta-layer) +- Système feedback user (nouvelle table/user_feedback) +- File upload pour images (OCR/description) +- Configuration multi-provider (dans Settings admin) + +**Architecture multilingue:** +- Prompts système en anglais (stabilité) +- Détection auto langue par note (user data) +- Embeddings multi-langues supportés + +**Contraintes:** +- Zéro DevOps → Vercel/Netlify hosting +- SQLite en prod (pas de vector DB séparée) +- Modèles locaux via Ollama ou API externes + +--- + +### ❤️ Red Hat - Émotions & Ressenti Utilisateur + +**Ce que les utilisateurs vont ressentir:** +- 😊 **Soulagement**: "Ça marche tout seul, je ne fais rien" +- 🤩 **Délice**: "Wow, il a deviné ce que je voulais faire!" +- 😰 **Frustration potentielle**: "Pourquoi la IA s'est trompée?" +- 😕 **Confusion**: "Comment ça marche ce score de confiance?" +- 🎯 **Contrôle**: "Je peux désactiver si je veux" + +**Points de friction émotionnelle identifiés:** +- Hallucinations = perte de confiance rapide +- Trop d'options = overwhelm +- IA trop présente = sentiment d'être surveillé +- IA invisible = "magie" mais aussi manque de compréhension + +**Design émotionnel recommandé:** +- Transparence sur ce que fait la IA +- Feedback immédiat (spinners, toast notifications) +- Contrôle utilisateur TOUJOURS disponible +- Messages humains, pas techniques + +--- + +### 🌞 Yellow Hat - Bénéfices & Valeur + +**Valeur utilisateur directe:** +- ⏱️ **Gain de temps**: Titres auto, tags auto, reformulations rapides +- 🧠 **Moins de charge cognitive**: IA gère la organisation, user se concentre sur contenu +- 🔍 **Retrouvabilité**: Recherche sémantique = trouver par sens, pas mots-clés +- 📈 **Qualité**: Reformulations améliorent clarté des notes +- 🎯 **Flow**: Suggestions de suites logiques = ne pas oublier, continuation fluide + +**Valeur business (modèle freemium):** +- 💰 **Revenus**: Abonnement pour features IA avancées +- 🎁 **Attraction**: Version gratuite = acquisition users +- ☕ **Payment friendly**: "Buy me a coffee" = low friction +- 🚀 **Scalabilité**: Zéro DevOps = coûts maîtrisés + +**Valeur technique:** +- 🔧 **Maintenabilité**: Architecture modulaire (factory pattern pour providers) +- 🌍 **International**: Support multi-langues out-of-the-box +- 🛡️ **Confiance**: Système de feedback = amélioration continue + +**Différenciation vs concurrents:** +- Google Keep: pas de IA avancée +- Notion: IA payante seulement, complexe +- Memento: simple + IA progressive + respect privacy (Ollama local) + +--- + +### ⚫ Black Hat - Risques & Défis + +**Risques techniques:** +- ⚠️ **Performance**: Embeddings = ralentissements si beaucoup de notes +- 💾 **Stockage**: SQLite avec embeddings = taille DB rapide +- 🔐 **Sécurité**: File upload images = validation nécessaire +- 🐛 **Hallucinations**: IA peut générer faux, même avec score de confiance +- 🌐 **API limits**: OpenAI = coûts, rate limits; Ollama = nécessite installation locale + +**Risques UX:** +- 😤 **Frustration**: IA qui se trompe = abandon +- 🤔 **Complexité**: Trop de features = overwhelm +- 🎭 **Incohérence**: Tags IA qui ne font pas sens pour l'utilisateur +- 🔔 **Spam**: Notifications IA trop fréquentes = désactivation + +**Risques business:** +- 💸 **Coûts IA**: OpenAI API = margin pressure si beaucoup d'users +- 📉 **Adoption**: Users ne voient pas la valeur IA = pas de conversion freemium +- 🏃 **Churn**: Une mauvaise expérience IA = perte user +- ⚖️ **Concurrence**: Notion, Obsidian ajoutent IA aussi + +**Risques adoption:** +- 🔒 **Privacy**: Users inquiets que IA lise leurs notes +- 🏠 **Setup local**: Ollama = barrière à l'entrée pour utilisateurs non-techniques +- 📊 **Data usage**: Users sur connexion limitée = embeddings = consommation data + +**Mitigations identifiées:** +- Système confiance + feedback = réduit hallucinations impact +- Mode conservatif = moins d'erreurs auto +- ON/OFF granulaire = user contrôle = réduit frustration +- Hosting managé = zéro DevOps mais coûts hosting +- Ollama optionnel = fallback OpenAI pour users non-tech + +--- + +### 🌱 Green Hat - Alternatives Créatives + +**Nouvelles idées issues de l'analyse:** + +**1. IA Contextuelle (Smart Context)** +- IA adapte son comportement selon le type de note +- Note code = suggestions techniques +- Note liste = checkboxes, organisation +- Note réflexion = questions de synthèse + +**2. Templates IA-Enhanced** +- IA génère templates personnalisés selon patterns utilisateur +- "Meeting notes", "Brainstorming", "Project planning" +- Auto-complétion de sections + +**3. IA Collaborative** +- Mode "Brainstorm avec IA" = IA propose des idées +- IA joue rôle de "devils advocate" = challenge les idées +- IA suggère des connexions entre notes + +**4. Gamification Subtile** +- "Note du jour" = IA met en avant une note à relire +- "Patterns découverts" = IA montre tendances d'écriture +- "Insight semaine" = IA résume les thèmes récurrents + +**5. IA Prédictive** +- IA suggère de créer une note avant même qu'on le demande +- "Tu créés souvent des notes X le mardi, veux-tu un template?" +- Anticipation basée sur historique + +**6. Mode "Focus IA"** +- Interface simplifiée avec IA en avant +- Tout est automatique, minimal UI +- Pour utilisateurs qui veulent zéro friction + +**7. IA + Voice (future-proofing)** +- Préparer architecture pour transcription vocale +- Commandes vocales: "Crée une note sur X" +- Dictée avec reformulation IA en temps réel + +--- + +### 🔵 Blue Hat - Process & Organisation + +**Synthèse des 3 phases:** + +**20+ idées générées (SCAMPER):** +- Catégorisation: UX (5), Architecture (4), Business (3), Features (8) + +**Problème critique identifié (Future Self):** +- Hallucinations → Solution: Système confiance 3 couches ✅ + +**Validation multi-perspectives (Six Hats):** +- Technique: Faisable avec stack actuel + quelques ajouts +- Émotionnel: Besoin transparence + contrôle +- Valeur: Gain temps + différenciation claire +- Risques: Mitigables avec architecture solide +- Créatif: 7 nouvelles directions innovantes + +--- + +### 📊 Priorisation des Fonctionnalités + +**Phase 1 - MVP IA (Maximum Value, Quick Wins):** +1. ✅ **Tags IA automatiques** (déjà implémenté) +2. 🎯 **Titres auto** (3 suggestions, pas d'auto-génération) +3. 🔍 **Recherche sémantique** (vector search avec embeddings) +4. 🎨 **Bouton reformulation** (manuel, par paragraphe) + +**Phase 2 - Experience Enhancement:** +5. 🖼️ **Description images** (OCR + description) +6. 🔗 **Résumé URLs** (extraction points clés) +7. 💡 **Suggestions suites logiques** (après chaque note) +8. ⚙️ **Settings IA granulaires** (ON/OFF par feature) + +**Phase 3 - Trust & Intelligence:** +9. 📊 **Score de confiance** (transparence) +10. 👍👎 **Feedback learning** (amélioration continue) +11. 🛡️ **Mode conservatif** (safety first) +12. 🌍 **Détection langue auto** (multilingue) + +**Phase 4 - Advanced Features (Freemium):** +13. 🎙️ **Transcription audio** (notes vocales) +14. 📁 **Organisation auto** (IA propose dossiers/catégories) +15. 🧠 **Templates IA personnalisés** (patterns utilisateur) +16. 🤖 **Mode "Super IA"** (optimisation complète note) + +--- + +### 🎯 Architecture Technique Recommandée + +**Base de données (Prisma + SQLite):** +``` +Note (existante) + + embedding: Vector (512) // embeddings pour recherche sémantique + + autoGenerated: Boolean // True si titre/tags par IA + + aiConfidence: Int? // Score 0-100 si généré par IA + + language: String? // Langue détectée: 'fr', 'en', etc. + +AiFeedback (nouvelle) + + id: ID + + noteId: Note + + userId: User + + feedbackType: Enum (thumbs_up, thumbs_down, correction) + + originalContent: String + + correctedContent: String? + + createdAt: DateTime +``` + +**API Routes:** +- `/api/ai/tags` (existante) +- `/api/ai/embeddings` (génération embeddings note) +- `/api/ai/search` (recherche sémantique) +- `/api/ai/titles` (suggestions titres) +- `/api/ai/refactor` (reformulation texte) +- `/api/ai/image` (description OCR) +- `/api/ai/url-summary` (résumé URL) +- `/api/ai/feedback` (collecte feedback) +- `/api/ai/next-steps` (suggestions suites) + +**Components:** +- `` (bouton générique avec loading state) +- `` (suggestion avec score confiance) +- `` (👍👎 avec tooltip) +- `` (ON/OFF granulaire) +- `` (affichage score) + +**Services:** +- `ai.service.ts` (orchestration appels IA) +- `confidence.service.ts` (calcul score confiance) +- `feedback.service.ts` (collecte et analyse feedback) +- `embedding.service.ts` (génération et stockage embeddings) + +--- + +### 🚀 Next Steps Concrets + +**Immédiat (cette semaine):** +1. ✅ Valider architecture technique avec équipe +2. 📝 Créer PRD pour features Phase 1 +3. 🔧 Setup infrastructure embeddings (colonne Vector DB) +4. 🧪 Tester modèles Ollama + OpenAI pour titres/refactor + +**Court terme (2-4 semaines):** +5. 💻 Implémenter recherche sémantique (MVP +) +6. 🎨 Développer suggestions titres +7. ✨ Bouton reformulation UX +8. 🧪 Tests utilisateurs avec petits cohort + +**Moyen terme (1-2 mois):** +9. 🖼️ Description images + OCR +10. 🔗 Résumé URLs +11. ⚙️ Settings IA granulaires +12. 📊 Système feedback + scoring confiance + +**Long terme (3+ mois):** +13. 🎙️ Transcription audio +14. 🤖 Mode "Super IA" +15. 🧠 Templates intelligents +16. 💰 Lancement freemium + paiement + +--- + +## 🎉 Conclusion Session Brainstorming + +**Résumé exécutif:** +- **20+ idées IA générées** via SCAMPER +- **Problème critique identifié**: hallucinations → solution élégante proposée +- **Architecture multilingue validée**: prompts anglais, données utilisateur multi-langues +- **Priorisation claire**: 4 phases de MVP à features avancées +- **Business model défini**: freemium avec "buy me a coffee", zéro DevOps + +**Décision clef:** +"Zéro prise de tête" = automatique par défaut, contrôle utilisateur TOUJOURS disponible + +**Prochaine étape:** +Créer PRD détaillé pour Phase 1 (MVP IA) avec specs techniques + mockups UX + +--- + +✅ **Session terminée avec succès!** + +**Date:** 2026-01-09 +**Durée:** 3 phases (SCAMPER, Future Self Interview, Six Thinking Hats) +**Output:** Architecture validée + roadmap priorisée + next steps concrets + +--- + diff --git a/_bmad-output/planning-artifacts/prd-phase1-mvp-ai.md b/_bmad-output/planning-artifacts/prd-phase1-mvp-ai.md new file mode 100644 index 0000000..248521a --- /dev/null +++ b/_bmad-output/planning-artifacts/prd-phase1-mvp-ai.md @@ -0,0 +1,1585 @@ +--- +stepsCompleted: [1, 2, 3, 4, 6, 7, 8, 9, 10, 11] +inputDocuments: + - _bmad-output/analysis/brainstorming-session-2026-01-09.md + - docs/project-overview.md + - docs/architecture-keep-notes.md + - docs/data-models.md +workflowType: 'prd' +lastStep: 11 +documentTitle: 'Phase 1 MVP AI - Memento' +focusArea: 'AI-Powered Note Taking Features' +status: 'complete' +completedAt: '2026-01-10' +--- + +# Product Requirements Document - Phase 1 MVP AI + +**Project:** Memento +**Author:** Ramez +**Date:** 2026-01-10 +**Focus:** Phase 1 MVP IA - AI-Powered Note Taking Features + +## Executive Summary + +**Memento Phase 1 MVP AI** transforme l'application de prise de notes existante en un **partenaire cognitif proactif** qui élimine la charge mentale liée à l'organisation, tout en préservant la simplicité et le contrôle total de l'utilisateur. S'appuyant sur l'architecture Next.js 16 + Prisma + SQLite existante, cette évolution ajoute une couche d'intelligence contextuelle conçue pour **suggérer et faciliter, sans jamais imposer**. + +L'objectif est de créer un flux de travail où la capture reste instantanée, mais l'organisation est accélérée par une **IA qui comprend les relations entre les notes** et propose des connexions proactives. Le système comprend l'intention, mais l'utilisateur garde toujours la main via un pattern ON/OFF granulaire. + +### What Makes This Special + +**🚀 Zero-Friction Intelligence (Philosophie "Zéro Prise de Tête")** + +Contrairement à Google Keep (pas d'IA) et Notion (IA à la demande et complexe), Memento Phase 1 introduit **trois innovations exclusives**: + +1. **Contextual Smart Assistance** - Les fonctionnalités IA n'apparaissent que quand c'est pertinent: + - Suggestions de titres uniquement après 50+ mots sans titre + - Toast non-intrusive avec options "Voir | Plus tard | Ne plus demander" + - L'utilisateur découvre les features naturellement sans être overwhelmed + +2. **Hybrid Semantic Discovery** - Recherche unifiée qui "marche juste": + - L'utilisateur ne sait pas si c'est des mots-clés ou du sens + - Résultats avec badges: "Correspondance exacte" | "Correspondance sémantique" + - **"Memory Echo"** - Connexions proactives entre notes liées (jusqu'à 1 insight/jour) + +3. **Privacy-First Multi-Provider AI**: + - Support Ollama (100% local, data ne quitte jamais l'infrastructure) + - Support OpenAI (cloud option pour utilisateurs non-techniques) + - Architecture multilingue: Prompts système en anglais, données utilisateur en langue locale + +**🎯 The "Aha!" Moment: "I didn't search, it found me"** + +Le différenciateur killer de Memento est **"Memory Echo"** - une feature qui révèle des connexions entre notes que l'utilisateur n'avait pas vues: + +> 💡 *"I noticed something..."* +> +> *"You noted `[Node.js performance tips]` in January and `[Next.js optimization]` this week. These notes are connected - want me to link them?"* +> +> [View Connection] [Dismiss] [That's clever!] + +Cela crée un moment unique où l'utilisateur réalise que Memento ne stocke pas seulement ses notes, mais **comprend ses connaissances** et les connecte proactivement. + +**🌍 Multilingual Out-of-the-Box** + +Architecture multilingue validée lors du brainstorming: +- Système: Prompts en anglais (stabilité des modèles) +- Données utilisateur: Détection automatique par note +- Pas besoin de configurer la langue - ça fonctionne nativement + +**⚙️ Granular ON/OFF Control** + +Respectant la philosophie "zéro prise de tête", chaque feature IA est contrôlable indépendamment: +- Settings IA avec checkboxes pour chaque fonctionnalité +- L'utilisateur peut désactiver ce qui ne lui convient pas +- Mode "Conservatif" (futur Phase 3) pour safety-first + +### Project Success Vision + +**Si Phase 1 réussit sauvagement, ce qui change pour les utilisateurs:** + +- ✅ **"Je retrouve ce que j'ai oublié"** - Les connexions proactives rappellent des notes anciennes liées au travail actuel +- ✅ **"Je ne perds plus rien"** - Memento se souvient des relations même quand l'utilisateur oublie +- ✅ **"Je suis plus intelligent"** - Les connexions IA révèlent des patterns que l'utilisateur n'avait pas vus +- ✅ **"Je reste dans le flow"** - Pas besoin d'organiser manuellement, Memento le fait silencieusement + +## Project Classification + +**Technical Type:** web_app +**Domain:** general +**Complexity:** medium +**Project Context:** Brownfield - Extension intelligent avec focus UX + +### Technical Context + +**Existing Stack:** +- Next.js 16.1.1 (App Router) + React 19.2.3 + TypeScript 5 +- Prisma 5.22.0 ORM + SQLite (better-sqlite3) +- Vercel AI SDK 6.0.23 + OpenAI/Ollama providers +- NextAuth 5.0.0-beta.30 (authentication) + +**Current AI Capabilities (Already Implemented):** +- ✅ Auto-tagging with embeddings +- ✅ Multi-provider support (OpenAI, Ollama) +- ✅ Factory pattern for AI providers + +**Phase 1 Additions:** +- Contextual title suggestions (3 options, no auto-generation) +- Enhanced semantic search with connection insights +- Paragraph-level reformulation (manual trigger) +- "Memory Echo" proactive connections (max 1 insight/day) + +### Architecture Alignment + +Phase 1 respects existing patterns: +- API Routes in `/api/ai/` namespace +- Components in shared structure +- Prisma schema extensions (not rewrites) +- Multilingual architecture (system prompts English, user data in local language) + +### Competitive Positioning + +| Feature | Google Keep | Notion | **Memento Phase 1** | +|---------|-------------|--------|---------------------| +| **Fast Capture** | ✅ Yes | ❌ No | ✅ **Yes** | +| **Integrated AI** | ❌ No | ⚠️ Paid/add-on | ✅ **Yes, native** | +| **Semantic Search** | ❌ No | ⚠️ Partial | ✅ **Yes, hybrid** | +| **Proactive Insights** | ❌ No | ❌ No | ✅ **EXCLUSIVE** | +| **Zero-Config** | ✅ Yes | ❌ No | ✅ **Yes** | +| **Privacy (Local)** | ❌ No | ❌ No | ✅ **EXCLUSIVE** | +| **Multilingual** | ⚠️ Limited | ⚠️ Limited | ✅ **Yes, native** | + +## Success Criteria + +### User Success + +**1. Adoption "Aha!" Moment** + +**Moment où l'utilisateur réalise que Memento est différent:** +- **Mesure:** % d'utilisateurs qui acceptent au moins une suggestion de titre dans les 7 premiers jours +- **Cible:** > 60% (si moins, les suggestions ne sont pas pertinentes) +- **Pourquoi:** Indique que les features IA sont découvertes et perçues comme utiles + +**Délice avec Memory Echo:** +- **Mesure:** % d'utilisateurs qui cliquent sur "Voir la connexion" lors d'un insight proactif +- **Cible:** > 40% (montre que les connexions proactives ont de la valeur) +- **Pourquoi:** C'est le moment différenciant vs Google Keep/Notion + +**2. Retrouvabilité "Je l'ai retrouvé!"** + +**Capacité à retrouver des notes oubliées via recherche sémantique:** +- **Mesure:** % de recherches où la correspondance sémantique est dans le top 3 résultats +- **Cible:** > 30% des recherches complexes (non-mots-clés exacts) +- **Pourquoi:** La recherche sémantique doit retrouver ce que la recherche par mots-clés ne trouve pas + +**Gain de temps de recherche:** +- **Mesure:** Temps moyen pour trouver une note connue vs. recherche mots-clés actuelle +- **Cible:** -40% de temps en moyenne +- **Pourquoi:** L'IA doit accélérer le workflow, pas le ralentir + +**3. Confiance en l'IA "Je fais confiance"** + +**Taux d'acceptation des suggestions:** +- **Mesure:** % de suggestions de titres acceptées vs. ignorées/modifiées +- **Cible:** > 50% acceptance rate +- **Pourquoi:** Si en dessous, l'IA ne comprend pas le contexte utilisateur + +**Feedback positif Memory Echo:** +- **Mesure:** Ratio boutons 👍 sur 👎 pour les connexions proactives +- **Cible:** > 3:1 (3 positifs pour 1 négatif) +- **Pourquoi:** Les insights doivent être pertinents, pas du spam + +**4. Qualité des Reformulations** + +**Satisfaction reformulation:** +- **Mesure:** % de reformulations gardées telles quelles vs. annulées +- **Cible:** > 70% gardées +- **Pourquoi:** La reformulation doit améliorer le contenu, pas le dégrader + +### Business Success + +**Open Source Adoption (3 mois):** +- **GitHub Stars:** 100+ étoiles (indicateur d'intérêt communauté) +- **Utilisateurs Actifs Hebdomadaires (WAU):** 50+ utilisateurs actifs par semaine +- **Engagement:** 30% des utilisateurs reviennent chaque semaine (retention semaine 1 à semaine 4) + +**Open Source Growth (12 mois):** +- **GitHub Stars:** 500+ étoiles +- **Contribution Communautaire:** Au moins 2 contributeurs externes soumettent des PRs +- **Traction:** Articles/blogs de mentionner Memento (indicateur de buzz organique) + +**Freemium Readiness (Futur):** +- **Intent de paiement:** 5-10% des utilisateurs actifs cliquent sur "Buy me a coffee" (même sans payer, indique la valeur perçue) +- **Conversion potentielle:** Si activé, > 2% conversion freemium payant + +**Métrique Ultime:** +- **"Wow, c'est génial, je vais le sponsoriser!"** - Si un utilisateur dit ça spontanément, c'est un succès business + +### Technical Success + +**Performance:** +- **Recherche sémantique:** < 300ms pour une base de 1000 notes + - **Pourquoi:** Ne pas ralentir l'UX, l'utilisateur ne doit pas attendre +- **Suggestions titres:** < 2s après détection (50+ mots sans titre) + - **Pourquoi:** Doit paraître "instantané" pour l'utilisateur +- **Memory Echo analysis:** Traitement en arrière-plan, blocage UI < 100ms + - **Pourquoi:** L'utilisateur ne doit jamais sentir que l'IA "travaille" + +**Architecture:** +- **Zero Breaking Change:** Toutes les features existantes continuent de fonctionner + - **Pourquoi:** C'est un projet brownfield, on ne casse pas ce qui marche +- **Multi-Provider Support:** Ollama ET OpenAI fonctionnent sans changement de code + - **Pourquoi:** Respecte la philosophie privacy-first + accessibilité +- **Multilingual Detection:** Fonctionne pour FR, EN, ES, DE minimum + - **Pourquoi:** Architecture multilingue validée lors du brainstorming + +**Qualité IA:** +- **Taux de fausses positives Memory Echo:** < 20% + - **Pourquoi:** Au-dessus, c'est perçu comme du spam utilisateur +- **Suggestions titres pertinentes:** > 70% acceptation + - **Pourquoi:** Les titres doivent capturer l'essence de la note +- **Hallucinations contrôlées:** < 5% des générations contiennent des erreurs factuelles + - **Pourquoi:** Mode conservateur + score de confiance (Phase 3, mais préparer l'architecture) + +### Measurable Outcomes + +**Metrics Dashboard (à implémenter pour tracking):** + +| Metric | Current | Phase 1 Target | Measurement Method | +|--------|---------|----------------|-------------------| +| Title suggestion acceptance | N/A | > 60% | Tracking accept/ignore | +| Semantic search top-3 hit rate | 0% | > 30% | Search analytics | +| Memory Echo CTR | N/A | > 40% | Insight click tracking | +| 👍👎 Feedback Ratio | N/A | > 3:1 | Feedback buttons | +| Avg search time improvement | Baseline | -40% | Time-to-find analytics | +| WAU (Week 4) | 0 | 50+ | Active user tracking | +| Week 1-4 retention | 0% | 30% | Cohort analysis | +| GitHub Stars (Month 3) | Current | +100 | GitHub API | +| Community contributors | 0 | 2+ | PR count | + +## Product Scope + +### MVP - Minimum Viable Product (Phase 1) + +**Core User Journeys Supported:** +- Alex (Zero-friction note taker) +- Sarah (Self-hoster privée) +- Max (Local-first advocate) + +**Must-Have Capabilities:** + +**1. Intelligent Title Suggestions** +- Déclenchement automatique après 50+ mots sans titre +- Toast non-intrusive: "J'ai 3 idées de titres pour ta note, les voir?" +- 3 suggestions IA présentées en dropdown +- Options: "Voir" | "Plus tard" | "Ne plus demander" +- Détection langue automatique (FR, EN, ES, DE) + +**2. Hybrid Semantic Search** +- Recherche unifiée (pas de distinction visible utilisateur) +- Badges sur résultats: "Correspondance exacte" | "Correspondance sémantique" +- Affichage top 10 résultats, mix mots-clés + sens +- Toggle IA dans Settings (ON/OFF granulaire) + +**3. Paragraph-Level Reformulation** +- Menu "..." sur chaque note card +- Sous-menu "IA Assist" → "Réécrire paragraphe" +- Modal pour sélectionner paragraphe et choisir reformulation +- Options: "Clarifier", "Raccourcir", "Améliorer style" +- Bouton 👍👎 pour feedback + +**4. Memory Echo (Proactive Connections) ⭐ DIFFÉRENCIATEUR** +- Analyse silencieuse en arrière-plan des embeddings existants +- **Max 1 insight proactif par jour** (configurable 0-3 dans Settings) +- Notification subtile: "J'ai remarqué quelque chose..." +- Affichage des 2 notes connectées avec option de lier +- Toggle ON/OFF dans Settings IA +- Boutons 👍👎 pour apprentissage + +**5. AI Settings Panel** +- Page `/settings/ai` avec checkboxes ON/OFF pour chaque feature: + - ☑ Suggestions de titres + - ☑ Recherche sémantique + - ☑ Reformulation + - ☑ Memory Echo +- Slider pour fréquence Memory Echo (0-3 insights/jour) +- Sélection provider IA (Ollama/OpenAI) si configuré + +**Technical Requirements:** +- API Routes: `/api/ai/titles`, `/api/ai/search`, `/api/ai/refactor`, `/api/ai/echo` +- Database: Extensions Prisma pour embeddings, language detection +- Components: ``, ``, `` +- Services: `ai.service.ts`, `embedding.service.ts`, `memory-echo.service.ts` + +**Out of Scope (Explicitement Non-MVP):** +- Score de confiance visible (Phase 3) +- Système feedback 👍👎 généralisé (Phase 3) +- Mode conservateur (Phase 3) +- Description images OCR (Phase 2) +- Résumé URLs (Phase 2) +- Templates IA personnalisés (Phase 4) +- Transcription audio (Phase 4) + +### Growth Features (Phase 2 - Post-MVP) + +**Enhancement de l'expérience IA:** +- Description images + OCR (bouton sur image) +- Résumé URLs (extraction points clés) +- "Suggestions suites logiques" après chaque note +- Settings IA avancés (paramètres configurables par feature) +- Feedback learning amélioré (patterns utilisateur) + +**Adoption & Engagement:** +- Onboarding IA pour nouveaux utilisateurs +- Tours guidés des features IA +- Analytics dashboard pour propriétaire + +### Vision (Future - Phase 3+) + +**Trust & Intelligence:** +- Score de confiance visible (transparence) +- Système feedback 👍👎 généralisé +- Mode conservateur (safety first) +- Détection langue auto améliorée (plus de langues) + +**Advanced Features:** +- Transcription audio (notes vocales) +- Organisation auto (IA propose dossiers/catégories) +- Templates IA personnalisés (patterns utilisateur) +- Mode "Super IA" (optimisation complète note) + +**Business Model:** +- Lancement freemium avec "Buy me a coffee" +- Features avancées payantes (Phase 4) +- Monétisation éthique sans lock-in + +## User Journeys + +### Journey 1: Alex - Le Déclic "Ça me comprend!" + +**Alex**, Freelance Creative & Developer, 32 ans, Paris + +**Persona:** +Alex travaille dans le chaos créatif. Il a des idées brillantes partout - dans le métro, pendant des réunions, à 3h du matin. Il utilise déjà Memento pour capturer ses pensées, mais il est frustré: + +- "J'ai 300+ notes et je ne retrouve plus rien" +- "Je passe 20 min à chercher cette astuce CSS que j'ai notée le mois dernier" +- "Mes titres sont soit vides, soit 'Note 34' - pas inspirant" + +**The Discovery (Opening Scene):** + +Un lundi matin, Alex ouvre Memento pour continuer une note sur React qu'il a commencée la veille. Il tape frénétiquement, complètement focused sur son code - **pas le temps pour un titre**. + +Soudain, une notification subtile apparaît: +> 💭 *"J'ai 3 idées de titres pour ta note, les voir?"* + +Alex sourit - c'est non-intrusif. Il clique "Voir" et voit: +1. "React State Management: useMemo Optimization Pattern" +2. "Performance Hook Pattern pour Composants React" +3. "Astuce React: mémoisation avec useMemo" + +**Le choix d'Alex:** "Wow, le premier capture exactement l'essence!" - Il clique pour l'appliquer. + +**The Revelation (Rising Action):** + +Deux jours plus tard, Alex cherche cette note. Au lieu de taper "React useMemo" (le titre exact), il tape naturellement: *"comment optimiser les performances des hooks"* + +Memento lui montre 10 résultats. Les 3 premiers ont un badge 🎯 **"Correspondance sémantique"**. Le premier est SA note - elle ne contient même pas les mots "hook" ou "performance" dans le texte, mais l'IA a compris le sens! + +**The "Aha!" Moment (Climax):** + +Une semaine passe. Alex reçoit une notification inattendue: +> 💡 *"J'ai remarqué quelque chose..."* +> +> *"Tu as noté `[Node.js performance tips]` en janvier et `[Optimisation Next.js]` cette semaine. Ces notes sont connectées - veux-tu que je les lie ?"* + +Alex clique "Voir la connexion" - son souffle coupé. Les deux notes traitent toutes les deux de... **server-side rendering optimization**. Il n'avait jamais fait le lien! + +**The Transformation (Resolution):** + +Trois mois plus tard: +- Alex a 400+ notes, mais il les retrouve **instantanément** +- Il accepte 80% des suggestions de titres (économie de temps massive) +- Memory Echo lui a fait découvrir 12 connexions entre ses notes +- **"C'est comme si j'avais un assistant de recherche personnel qui lit tout ce que j'écris"** + +**Journey Requirements Revealed:** +- Détection intelligente du moment opportun (50+ mots sans titre) +- Recherche sémantique qui comprend l'intention, pas juste les mots +- Memory Echo avec fréquence contrôlable (pas spam) +- Feedback utilisateur pour apprentissage (👍👎) + +--- + +### Journey 2: Max - "Mes données ne quittent jamais mon laptop" + +**Max**, Privacy Advocate & Software Engineer, 28 ans, Berlin + +**Persona:** +Max est passionné par la privacy. Il utilise déjà Memento avec Next.js en local sur sa machine, mais il est: + +- **Sceptique:** "Pourquoi une IA devrait lire mes notes personnelles?" +- **Exigeant:** "Si une seule donnée quitte mon laptop, je désinstalle" +- **Technique:** Il a Ollama installé avec des modèles locaux + +**The Discovery (Opening Scene):** + +Max lit sur le blog Memento qu'il y a maintenant des features IA. Son premier réflexe: **méfiance**. + +Il va dans Settings > AI et voit: +- ☑ Use AI Provider: [Ollama (Local) | OpenAI Cloud] +- Checkbox: "🔒 Keep all AI processing local (Ollama only)" +- Un message rassurant: *"With Ollama, your note data never leaves your device. Embeddings and processing happen entirely on your machine."* + +Max soulagé, coche la case Ollama. Il voit un indicateur de statut: *"✅ Connected to local Ollama at http://localhost:11434"* + +**The First Test (Rising Action):** + +Max crée une note sur une architecture système qu'il conçoit pour un client. 60 mots plus tard, la suggestion de titre apparaît. + +Il hésite... puis clique "Voir". Les 3 suggestions apparaissent instantanément (< 1s). Il choisit la troisième. + +**The Verification (Climax):** + +Curieux, Max ouvre les DevTools réseau pour vérifier: +- **0 appels vers des API externes** (pas d'OpenAI, pas de Google) +- Juste des appels locaux vers `localhost:11434` (Ollama) + +Il sourit: *"Bon, ils ont tenu parole. Vraiment local."* + +**The Memory Echo Experience (The Real Test):** + +Une semaine plus tard, Max reçoit son premier Memory Echo: +> 💡 *"J'ai remarqué quelque chose..."* +> +> *"Tu as noté `[Microservices patterns]` et `[Event-driven architecture]`. Ces notes sont liées."* + +Max clique "Voir la connexion" - et réalise que l'IA a fait le lien entre deux notes qu'il a écrites à 2 mois d'intervalle. Le plus fou? **Tout s'est passé localement.** + +Il clique 👍 ("That's clever!"). Le système apprend. + +**The Transformation (Resolution):** + +Deux mois plus tard: +- Max a accepté 65% des suggestions de titres (elles sont vraiment pertinentes!) +- Il a désactivé Memory Echo à 0 (il préfère chercher manuellement) +- **"L'IA locale est aussi intelligente que le cloud, mais sans compromis privacy"** +- Il recommande Memento sur Reddit: *"Seul app de notes avec IA 100% locale et zéro telemetry"* + +**Journey Requirements Revealed:** +- Configuration Ollama fonctionnelle out-of-the-box +- Détection automatique du provider Ollama local +- Indicateurs de statut de connexion IA +- Zero data exfiltration (tous les appels sont locaux) +- Toggle granulaire pour chaque feature IA (Max a désactivé Memory Echo) +- Performance locale acceptable (pas plus lent que le cloud) + +--- + +### Journey 3: Léa - Admin Système "Zero Maintenance" + +**Léa**, DevOps Engineer, 35 ans, Lyon - Admin de l'instance Memento de son équipe de 15 développeurs + +**Persona:** +L'équipe de Léa utilise Memento pour partager des connaissances techniques. Elle a déployé Memento sur leur serveur interne. Maintenant avec les features IA, elle doit: + +- Configurer les providers IA pour l'équipe +- Surveiller les coûts et la performance +- Gérer les utilisateurs qui ont des problèmes + +**Initial Configuration (Opening Scene):** + +Léa accède à `/settings/ai` (admin-only). Elle voit: + +**Team AI Configuration:** +- Default AI Provider: [OpenAI Team API | Ollama Self-hosted | Custom] +- API Key Management: [Add team keys] (chiffrées en base) +- Per-user limits: Max embeddings per day, Max Memory Echo insights + +Elle configure: +- Provider: OpenAI Team API (clé d'équipe partagée) +- Rate limits: 100 embeddings/jour/utilisateur +- Memory Echo: Max 1 insight/jour par utilisateur (pour éviter l'overwhelm) + +**Monitoring (Rising Action):** + +Dans le nouveau Dashboard Admin, Léa voit des métriques IA en temps réel: +- AI Usage Today: 1,247 embeddings générés +- Average Response Time: 180ms +- Top Feature Used: Title Suggestions (78%) +- Memory Echo Feedback Ratio: 4.2:1 👍/👎 (excellent!) + +**The Problem (Climax):** + +Un développeur (Thomas) se plaint: *"L'IA me suggère des titres en anglais alors que j'écris en français!"* + +Léa va dans User Settings de Thomas et voit: +- Language Detection: Auto ✅ +- Last Detected Language: FR (français) +- **Mais:** Le modèle utilisé a tendance à suggérer en anglais + +Elle ajuste la config pour Thomas: Force language = FR, et augmente la température du modèle pour plus de créativité en français. + +**The Optimization (Resolution):** + +Un mois plus tard: +- L'équipe a généré 45,000 embeddings (coût OpenAI: ~$12/mois - gérable!) +- Léa a ajusté les settings basés sur les analytics: + - Memory Echo limité à 2/sem pour les utilisateurs power-users + - Titre suggestions activées par défaut (80% d'acceptation!) +- **"L'IA booste la productivité de l'équipe sans moi passer du temps à configurer"** + +**Journey Requirements Revealed:** +- Admin dashboard avec métriques IA en temps réel +- Configuration par utilisateur ou par défaut d'équipe +- Gestion des clés API chiffrées +- Rate limiting par utilisateur +- Surveillance des coûts IA +- Ajustement des paramètres par utilisateur (langue, température, etc.) +- Analytics d'utilisation pour optimiser les settings + +--- + +### Journey 4: Sophie - Quand l'IA se trompe + +**Sophie**, Content Marketing Manager, 29 ans, Bordeaux - Utilisatrice régulière de Memento + +**Persona:** +Sophie utilise Memento pour organiser ses idées de contenu. Elle est enthousiaste à l'idée des features IA, mais... elle va rencontrer des problèmes. + +**The First Problem (Opening Scene):** + +Sophie écrit une note sur une idée d'article. 70 mots plus tard, la suggestion de titre apparaît. Excitée, elle clique "Voir" et voit: + +1. "Stratégie de Contenu B2B: Guide Complet" +2. "Marketing B2B: Plan d'Action 2025" +3. "Idées Articles: Marketing de Contenu" + +Sophie déçoitée: *"None of these capture my idea at all!"* + +Elle clique "Ne plus demander" pour cette note. Le système respecte son choix. + +**The Second Problem - Memory Echo (Rising Action):** + +Le lendemain, Sophie reçoit une Memory Echo: +> 💡 *"J'ai remarqué quelque chose..."* +> +> *"Tu as noté `[Recettes de smoothies]` et `[Stratégie SEO]`. Ces notes sont connectées."* + +Sophie confuse: *"What? These have nothing to do with each other!"* + +Elle clique 👎 ("Faux") - et un modal apparaît: +> *"Merci pour ton feedback! Pourquoi cette connexion n'est-elle pas pertinente?"* + +Sophie explique: *"Les recettes de smoothies sont pour ma vie personnelle, le SEO c'est pro. Pas de rapport."* + +Le système apprend. + +**The Recovery (Climax):** + +Sophie va dans Settings > IA et voit: +- Title Suggestions: ☑ Activé +- Memory Echo: ☑ Activé (Max 1/jour) + +Elle décide d'ajuster: +- Title Suggestions: Activé, mais **"Me demander seulement si je dépasse 100 mots"** (elle a besoin de plus de contexte) +- Memory Echo: Activé, mais **"Seulement pour les notes des 30 derniers jours"** (éviter les connexions avec des notes anciennes) + +**The Return to Trust (Resolution):** + +Une semaine plus tard, Sophie écrit un long article (200+ mots). Cette fois, les suggestions de titres sont: +1. "Content Marketing: Comment créer du contenu qui convertit" +2. "Guide Marketing de Contenu: De la stratégie à l'exécution" +3. "Stratégie de Contenu: Les 5 piliers du marketing B2B" + +Sophie sourit: *"Number 3 is perfect!"* - Elle clique pour l'appliquer. + +Pour Memory Echo, elle reçoit une connexion entre deux notes sur le marketing (toutes deux des 30 derniers jours). Cette fois, elle clique 👍 ("That's clever!")! + +**The Transformation:** + +Un mois plus tard: +- Sophie a personnalisé ses settings IA selon ses préférences +- Elle accepte maintenant **55% des suggestions** (en hausse!) +- Son feedback 👎 a aidé le système à mieux comprendre son contexte +- **"L'IA n'est pas parfaite, mais je peux la configurer pour mes besoins"** + +**Journey Requirements Revealed:** +- Bouton "Ne plus demander" respecté immédiatement +- Feedback 👎 avec modal pour comprendre **pourquoi** c'est faux +- Settings IA personnalisables par utilisateur (seuil de mots, période Memory Echo) +- Système d'apprentissage qui s'améliore avec le feedback +- Bouton d'annulation (undo) pour les suggestions appliquées par erreur +- Mode "conservateur" pour réduire les fausses positives + +--- + +### Journey Requirements Summary + +**Core Requirements Across All Journeys:** + +**1. Intelligent & Contextual Triggers** +- Detection automatique des moments opportuns (50+ mots sans titre) +- Toast notifications non-intrusives avec options "Voir | Plus tard | Ne plus demander" +- Respect immédiat du choix utilisateur + +**2. Hybrid Semantic Search** +- Recherche unifiée (pas de distinction visible) +- Badges sur résultats: "Correspondance exacte" | "Correspondance sémantique" +- Compréhension de l'intention utilisateur, pas juste mots-clés + +**3. Memory Echo (Proactive Connections)** +- Fréquence configurable 0-3 insights/jour +- Période configurable (notes des X derniers jours) +- Connexions pertinentes (faux positifs < 20%) + +**4. Privacy-First Architecture** +- Support Ollama local 100% fonctionnel +- Zéro appel API externe en mode local +- Indicateurs de statut de connexion IA +- Performance locale acceptable (< 1s suggestions) + +**5. Granular User Control** +- Settings IA avec checkboxes ON/OFF par feature +- Personnalisation par utilisateur (seuil mots, période Memory Echo, etc.) +- Boutons 👍👎 pour feedback et apprentissage +- Bouton "Ne plus demander" immédiat + +**6. Admin & Operations** +- Admin dashboard avec métriques IA temps réel +- Configuration par défaut d'équipe + overrides par utilisateur +- Gestion clés API chiffrées +- Rate limiting par utilisateur +- Surveillance coûts IA +- Analytics d'utilisation pour optimiser les settings + +**7. Error Recovery & Learning** +- Feedback 👎 avec modal explicatif +- Système apprentissage avec feedback utilisateur +- Bouton annulation (undo) pour les suggestions appliquées +- Mode conservateur pour réduire fausses positives (Phase 3) +- Ajustement paramètres par utilisateur (langue, température, etc.) + +## Innovation & Novel Patterns + +Memento Phase 1 introduces **two major innovations** that radically differentiate the application from existing solutions like Google Keep and Notion. + +### Innovation 1: Memory Echo - "I Didn't Search, It Found Me" ⭐ + +**The Breakthrough:** + +Memory Echo inverse le paradigme traditionnel de la recherche d'information. Au lieu de demander à l'utilisateur de penser à chercher, l'IA **pense pour lui** en identifiant proactivement les connexions entre des notes que l'utilisateur n'avait pas vues. + +**Why This Is Revolutionary:** + +| Traditional Apps (Google Keep, Notion) | **Memento with Memory Echo** | +|----------------------------------------|------------------------------| +| **Reactive** - User must think to search | **Proactive** - AI finds connections automatically | +| User queries → System retrieves | System surfaces → User discovers | +| "I hope I find that note..." | "I didn't even know these were related!" | +| Discoverability depends on user memory | Discoverability enhanced by AI intelligence | + +**The Insight:** + +Most knowledge workers have hundreds or thousands of notes but forget the connections between them. A note written in January about "Node.js performance" might be directly relevant to a note written in June about "Next.js optimization" - but the user never makes the link. + +Memory Echo solves this by: +- **Analyzing existing embeddings** for semantic similarity patterns +- **Identifying cross-temporal connections** (notes written days/weeks/months apart) +- **Surfacing one insight per day maximum** (configurable 0-3) +- **Learning from user feedback** (👍👎 buttons improve future suggestions) + +**Market Context:** + +- **Obsidian** has graph view and backlinks - but requires manual user action +- **Roam Research** has suggestions - but only highlights explicit keyword overlaps +- **Notion AI** - can search semantically but doesn't suggest proactively +- **Memento** - first to combine proactive discovery + semantic understanding + user feedback loop + +**Validation Approach:** + +**Technical Validation:** +- Cosine similarity threshold > 0.75 (ensures meaningful connections) +- Time diversity filter: Notes must be from different time periods (avoid same-session duplicates) +- Context relevance: Exclude obvious connections (identical keywords/categories) + +**UX Validation:** +- Frequency limit: Max 1 insight/day (prevents overwhelming users) +- User control: Slider for 0-3 insights/day, complete ON/OFF toggle +- Feedback loop: 👍👎 buttons train the system on user preferences + +**Success Criteria:** +- 👍👎 feedback ratio > 3:1 (3 positive for 1 negative) +- CTR (Click-Through Rate) > 40% (users click "View Connection") +- User retention: Users who engage with Memory Echo show 30% higher week-4 retention + +**Risk Mitigation:** + +**Risk 1: "Connections feel random/spammy"** +- **Mitigation:** High similarity threshold (0.75), conservative by default +- **Fallback:** User can set frequency to 0 (disable completely) + +**Risk 2: "I already knew these were related"** +- **Mitigation:** Focus on cross-temporal connections (notes far apart in time) +- **Enhancement:** Add serendipity factor (connections user likely missed) + +**Risk 3: Performance impact from analysis** +- **Mitigation:** Background processing, non-blocking UI +- **Target:** Analysis completes in < 100ms UI freeze time + +**Competitive Moat:** + +Memory Echo is difficult to copy because it requires: +1. **Existing embeddings** from user's notes (incumbents don't have this data) +2. **Feedback learning system** (requires engineering investment) +3. **Conservative-by-default philosophy** (most AI companies are aggressive) +4. **Privacy-first architecture** (local processing possible with Ollama) + +--- + +### Innovation 2: Contextual AI "Zero-Friction" Pattern + +**The Breakthrough:** + +Memento introduces a new interaction pattern for AI features: **context-aware appearance**. The AI doesn't demand attention (always-visible toolbar) nor hide completely (buried in menus) - it appears **only when contextually appropriate**. + +**Why This Is Revolutionary:** + +| Current AI Apps | **Memento Contextual AI** | +|-----------------|---------------------------| +| Always-visible toolbars (overwhelming) | Appears when relevant | +| Hidden in menus (hard to discover) | Non-intrusive toast notifications | +| All features active simultaneously | Single interaction at a time | +| User manages complexity | System manages complexity | + +**The Pattern:** + +**Example 1 - Title Suggestions:** +- **Trigger:** User writes 50+ words without a title +- **Appearance:** Subtle toast: "I have 3 title ideas for this note, view them?" +- **Options:** "View" | "Not now" | "Don't ask for this note" +- **Outcome:** Feature discovered naturally, not overwhelming + +**Example 2 - Reformulation:** +- **Trigger:** User opens "..." menu on a note card +- **Appearance:** "AI Assist" → "Rewrite paragraph" (intentional, not disruptive) +- **Context:** User is already in editing mode, so AI suggestion fits naturally + +**Example 3 - Memory Echo:** +- **Trigger:** Background analysis finds strong connection +- **Appearance:** Once per day max (configurable) +- **Priority:** If multiple AI interactions possible, Memory Echo takes precedence + +**The Insight:** + +The "zero-friction" philosophy means: +- **Zero cognitive load** - User doesn't need to remember where features are +- **Zero interruption** - AI never overwhelms with multiple simultaneous requests +- **Zero learning curve** - Features are discovered when needed +- **Zero lock-in** - Every feature can be disabled independently + +**Market Context:** + +- **Notion AI** - AI features hidden in "/ai" command (hard to discover) +- **Obsidian Copilot** - Sidebar always visible (can be distracting) +- **Memento** - Contextual appearance balances discoverability with non-intrusiveness + +**Scalability Strategy:** + +As AI features grow (Phase 2: Image OCR, URL summaries, etc.), the pattern scales via: + +**1. Single-Interaction Rule:** +``` +IF (title_suggested AND memory_echo_pending): + Show Memory Echo (higher value) + Defer title suggestion to next trigger +``` + +**2. Priority Hierarchy:** +``` +Priority 1: Memory Echo (proactive discovery) +Priority 2: Title suggestions (capture value) +Priority 3: Reformulation (enhancement) +Priority 4: URL summaries, OCR, etc. (nice-to-have) +``` + +**3. "Focus Mode" Toggle:** +- User can disable ALL proactive AI temporarily +- Perfect for deep work sessions +- One-click re-enable when ready + +**Validation Approach:** + +**UX Validation:** +- A/B test trigger thresholds (50 words vs. 75 vs. 100) +- Measure "accept/ignore" ratio per feature +- Track user settings changes (if users disable, adjust defaults) + +**Success Criteria:** +- Feature discovery rate > 70% (users find features without tutorial) +- Feature acceptance rate > 50% (users accept suggestions when offered) +- Overwhelm rate < 5% (users rarely disable all AI features) + +**Risk Mitigation:** + +**Risk 1: "Users never discover features"** +- **Mitigation:** Progressive disclosure - show more prominently after first use +- **Fallback:** Optional onboarding tour for AI features + +**Risk 2: "Too many features become overwhelming"** +- **Mitigation:** Single-interaction rule enforced at UX level +- **Fallback:** "Focus Mode" to disable all proactive AI + +**Risk 3: "Context detection fails"** +- **Mitigation:** Conservative triggers (better to miss than to annoy) +- **Fallback:** Manual trigger in settings for all features + +**Competitive Moat:** + +This interaction pattern is difficult to copy because it requires: +1. **Philosophical commitment** to user-centric design (most AI companies prioritize engagement over UX) +2. **Engineering discipline** to build context-aware triggers +3. **User feedback loops** to refine triggers over time +4. **Multi-feature coordination** (preventing feature conflicts) + +--- + +## Why These Innovations Matter + +**Combined Impact:** + +Memory Echo (proactive discovery) + Contextual AI (respectful interaction) create a **new paradigm for AI-assisted knowledge management**: + +1. **AI as Partner, Not Tool** - The system thinks with you, not just for you +2. **Serendipity at Scale** - Discover connections you'd never find manually +3. **Zero-Friction Intelligence** - AI enhances without interrupting +4. **Privacy-First** - All innovations work locally via Ollama + +**The "Aha!" Moment:** + +When users experience Memory Echo discovering a connection they missed, they realize: +> *"This isn't just a note-taking app. It's a partner that understands my knowledge better than I do."* + +This creates emotional lock-in that features alone cannot achieve. + +## Web App Specific Requirements + +### Project-Type Overview + +Memento is a **Single Page Application (SPA)** built with Next.js 16 App Router, combining server-side rendering (SSR) for performance with client-side navigation for fluid user experience. Phase 1 MVP AI focuses on **progressive enhancement** - AI features add value without breaking existing core functionality. + +### Browser Support Matrix + +**Primary Target (Modern Browsers):** + +| Browser | Minimum Version | Rationale | +|---------|-----------------|-----------| +| Chrome/Edge | 120+ (Jan 2024) | Chromium engine, latest APIs | +| Firefox | 120+ (Jan 2024) | Gecko engine, modern JS | +| Safari | 17+ (Sep 2023) | WebKit engine, macOS/iOS | +| Mobile Safari | iOS 17+ | iPhone/iPad support | + +**Technical Approach:** +- **No polyfills** - Use modern JavaScript features (ES2023+, CSS Grid, Flexbox) +- **Feature detection** - Graceful degradation if APIs unavailable +- **Progressive enhancement** - Core features work without JavaScript if possible + +**Out of Scope (Explicit):** +- IE11 or legacy browsers - Too much technical debt for Phase 1 +- Opera Mini or other niche browsers - < 0.1% market share +- Android < 10 - Too old for modern web APIs + +**Rationale:** +- Memento targets tech-savvy users (developers, knowledge workers) +- Modern browser usage > 95% in target demographics +- Reduces bundle size and technical complexity + +--- + +### Responsive Design Strategy + +**Breakpoint Strategy (Mobile-First):** + +``` +Mobile First: 320px - 639px (Smartphones) +Tablet: 640px - 1023px (iPad, tablets) +Desktop: 1024px - 1439px (Laptops) +Desktop Wide: 1440px+ (Large monitors) +``` + +**AI Feature Adaptation:** + +| Feature | Mobile | Tablet | Desktop | +|---------|--------|--------|---------| +| Title suggestions toast | Bottom sheet | Bottom-right toast | Top-right toast | +| Memory Echo notification | Full-width banner | Top-right card | Sidebar card | +| Reformulation modal | Full-screen | Modal | Side panel | +| Search results | Single column | 2 columns | 3 columns + filters | + +**Touch Targets (WCAG 2.1 AA):** +- Minimum tap target size: 44×44px (mobile) +- Spacing between targets: 8px minimum +- AI buttons (👍👎) must be tappable without zoom + +--- + +### Performance Targets + +**Critical Performance Metrics (Phase 1):** + +| Metric | Target | Measurement Method | +|--------|--------|-------------------| +| **Title Suggestions Generation** | < 2s | Time from trigger to display | +| **Semantic Search** | < 300ms | Time from query to results | +| **Memory Echo Analysis** | < 100ms UI freeze | Background processing time | +| **Initial Page Load** | < 3s (FCP) | First Contentful Paint | +| **Time to Interactive** | < 5s (TTI) | Full app interactivity | + +**Performance Budget:** +- **JavaScript bundle:** < 200KB gzipped (excluding AI providers) +- **CSS:** < 50KB gzipped +- **First paint:** < 1.5s on 4G connection + +**Optimization Strategies:** +1. **Code splitting:** AI features loaded on-demand (not in initial bundle) +2. **Lazy loading:** Components loaded when needed +3. **ISR (Incremental Static Regeneration):** Pre-render pages, revalidate in background +4. **Image optimization:** Next.js Image component with WebP/AVIF +5. **AI processing:** Always background, never block main thread + +**Monitoring:** +- Core Web Vitals tracked in production +- Performance regression tests in CI/CD +- Real User Monitoring (RUM) for actual usage data + +--- + +### SEO Strategy + +**Approach:** SEO is **not critical** for Phase 1 MVP AI because: + +1. **Authentication Required** - Main app is behind login (no public content) +2. **B2C Community-Driven** - Growth through word-of-mouth, not organic search +3. **Privacy-First** - Users prefer private apps over discoverable ones + +**SEO for Public Pages Only:** + +**Public Pages Requiring SEO:** +- Landing page (`/`) - Product overview, features +- Documentation (`/docs`) - User guides, API docs +- Blog (future) - Content marketing + +**SEO Best Practices for Public Pages:** +- Meta tags (title, description, Open Graph) +- Structured data (JSON-LD for rich snippets) +- Sitemap auto-generation +- Robots.txt configuration +- Canonical URLs for duplicate content prevention + +**AI Features NO-INDEX:** +- All authenticated pages behind login +- User-generated content (notes, labels) +- Search results, dashboards +- AI-generated content (titles, suggestions) + +**Rationale:** Prevent search engines from indexing private user data and AI-generated content. + +--- + +### Accessibility Level (WCAG 2.1 AA) + +**Target:** **WCAG 2.1 Level AA** for Phase 1 + +**AI Feature Accessibility Requirements:** + +**1. Title Suggestions:** +- Toast must announce: "3 title suggestions available" to screen readers +- Each suggestion must be keyboard navigable (Arrow keys + Enter) +- Visual focus indicators on all interactive elements + +**2. Memory Echo Notifications:** +- Must NOT interrupt screen reader navigation +- Use `role="status"` (not `role="alert"`) for non-critical notifications +- Provide mechanism to dismiss without activating (ESC key) + +**3. Semantic Search:** +- Results must be announceable: "5 results found, 3 semantic matches" +- Badges must be descriptive: "Semantic match" (not just icons) +- Keyboard shortcuts for advanced users (Cmd+K for search) + +**4. Reformulation Modal:** +- Focus trap in modal (Tab cycles within modal only) +- ESC to close, Enter to confirm +- Progress indicators for AI processing (ARIA live regions) + +**Color Contrast:** +- All text: Minimum 4.5:1 contrast ratio (WCAG AA) +- AI UI elements (buttons, badges): 3:1 contrast ratio for large text +- Focus indicators: 3:1 contrast ratio against background + +**Testing:** +- Automated testing: axe-core DevTools, WAVE browser extension +- Manual testing: Keyboard-only navigation, screen reader testing (NVDA/JAWS) +- User testing: Include users with disabilities in beta testing + +**Accessibility Success Metrics:** +- All AI features usable without mouse +- Zero keyboard traps in AI modals/toasts +- Screen reader compatibility > 90% (NVDA, JAWS, VoiceOver) + +--- + +### Technical Architecture Considerations + +**Next.js 16 App Router Patterns:** + +**1. Server Components (RSC) for Performance:** +- Note list, search results as Server Components +- AI features as Client Components (need interactivity) +- Hybrid approach: Static shell + dynamic AI content + +**2. Streaming for AI Responses:** +- Use Suspense + streaming for slow AI features +- Progressive loading: Show skeleton → partial results → complete results +- Example: Semantic search streams results as they're computed + +**3. Error Boundaries:** +- Graceful degradation if AI features fail +- User-friendly error messages (not technical jargon) +- Retry mechanisms with exponential backoff + +**4. Caching Strategy:** +- Embeddings cached in database (not regenerated) +- AI responses cached per note (TTL: 24 hours) +- Search results cached for 5 minutes (user-specific) + +**Data Flow Architecture:** + +``` +User Action → Client Component → Server Action → AI Provider + ↓ ↓ ↓ + UI Update Prisma DB Embedding Generation + ↓ ↓ + Display Cache Store +``` + +**State Management:** +- Server State: Prisma + Server Actions (no separate API layer needed) +- Client State: React hooks (useState, useTransition) +- AI State: Server Actions with progressive enhancement + +--- + +### Implementation Considerations + +**Phase 1 MVP Scope:** + +**IN Scope:** +- Responsive design for mobile/tablet/desktop +- WCAG 2.1 AA compliance +- Performance targets met (< 2s titles, < 300ms search) +- Modern browsers only (Chrome 120+, Firefox 120+, Safari 17+) +- Basic SEO for landing page only + +**OUT of Scope (Phase 2+):** +- PWA capabilities (offline mode, install prompt) +- Real-time features (WebSocket, live updates) +- Legacy browser support (IE11, old Safari) +- Advanced SEO (blog, content marketing) +- Accessibility AAA (full compliance) + +**Technical Debt to Avoid:** +- Skipping accessibility for "speed" (creates debt later) +- Hardcoding for desktop only (mobile-first approach) +- Blocking UI for AI processing (always background) +- Ignoring performance monitoring (leads to regressions) + +## Project Scoping & Phased Development + +### MVP Strategy & Philosophy + +**MVP Approach:** **Problem-Solving + Experience Hybrid** + +Memento Phase 1 MVP IA combines two MVP philosophies: + +**1. Problem-Solving MVP:** +- **Core Problem:** "J'ai des centaines de notes et je ne retrouve plus rien" +- **Solution:** Recherche sémantique + suggestions de titres +- **Value:** Utilité immédiate - l'utilisateur retrouve ses notes instantanément + +**2. Experience MVP:** +- **Core Experience:** Le moment "Aha!" - "Je n'ai pas cherché, elle m'a trouvée" +- **Solution:** Memory Echo (connexions proactives) +- **Value:** Différenciation unique - innovation que personne n'a + +**Resource Requirements:** +- **Team Size:** 1-2 developers (possible pour side project) +- **Timeline:** 8-12 semaines pour MVP complet +- **Skills:** Next.js, Prisma, AI integration (OpenAI/Ollama), Vector embeddings +- **Infrastructure:** Vercel/Netlify (zero DevOps), SQLite database, Ollama optionnel + +**Launch Strategy:** +- **Private Beta:** 10-20 early adopters (friends, colleagues) +- **Public Beta:** Open source release with "Beta" badge +- **Growth:** Word-of-mouth, Reddit (r/NoteTaking, r/SideProject), HackerNews + +--- + +### MVP Feature Set (Phase 1) + +**Core User Journeys Supported:** + +✅ **Journey 1: Alex (Primary User - Success Path)** +- Title suggestions when writing 50+ words +- Semantic search finds notes by meaning +- Memory Echo reveals hidden connections +- Complete workflow: capture → search → discover + +✅ **Journey 2: Max (Privacy-First)** +- Ollama local AI processing 100% functional +- Zero data exfiltration (verified in DevTools) +- All features work offline (local provider) + +✅ **Journey 4: Sophie (Edge Case)** +- Customizable AI settings (thresholds, frequencies) +- Feedback learning from 👎 responses +- Granular ON/OFF control per feature + +**Must-Have Capabilities (MVP):** + +**1. Intelligent Title Suggestions** +- Déclenchement automatique après 50+ mots sans titre +- Toast notification non-intrusive avec options "Voir | Plus tard | Ne plus demander" +- 3 suggestions IA générées en < 2s +- Application one-click ou saisie manuelle +- Détection langue automatique (FR, EN, ES, DE) + +**2. Hybrid Semantic Search** +- Recherche unifiée (pas de distinction visible utilisateur) +- Badges sur résultats: "Correspondance exacte" | "Correspondance sémantique" +- Affichage top 10 résultats mixés (mots-clés + sémantique) +- Performance < 300ms pour 1000 notes +- Toggle ON/OFF dans Settings IA + +**3. Paragraph-Level Reformulation** +- Menu "..." sur chaque note card → "IA Assist" → "Réécrire paragraphe" +- Modal pour sélectionner paragraphe +- Options: "Clarifier", "Raccourcir", "Améliorer style" +- Boutons 👍👎 pour feedback + +**4. Memory Echo (Proactive Connections) ⭐ DIFFÉRENCIATEUR** +- Analyse silencieuse en arrière-plan des embeddings existants +- **Max 1 insight proactif par jour** (configurable 0-3) +- Notification: "J'ai remarqué quelque chose..." avec 2 notes connectées +- Boutons "View Connection" | "Dismiss" | 👍👎 +- Cosine similarity threshold > 0.75 +- Time diversity filter (notes de périodes différentes) + +**5. AI Settings Panel** +- Page `/settings/ai` avec checkboxes ON/OFF pour chaque feature: + - ☑ Title Suggestions + - ☑ Semantic Search + - ☑ Reformulation + - ☑ Memory Echo +- Slider pour fréquence Memory Echo (0-3 insights/jour) +- Sélection provider IA: [Ollama (Local) | OpenAI Cloud] +- Indicateurs de statut de connexion IA + +**6. Multi-Provider AI Support** +- Ollama local (http://localhost:11434) +- OpenAI API (cloud option) +- Factory pattern pour extensibilité +- Fallback automatique si provider unavailable + +**7. Privacy & Control** +- Zéro appel API externe en mode Ollama (vérifiable) +- Boutons feedback 👍👎 pour apprentissage +- Bouton "Ne plus demander" immédiat +- Personnalisation par utilisateur (seuil mots, période Memory Echo) + +**Out of Scope (Explicitly Non-MVP):** +- Score de confiance visible (Phase 3) +- Système feedback généralisé (Phase 3) +- Mode conservateur (Phase 3) +- Description images OCR (Phase 2) +- Résumé URLs (Phase 2) +- Templates IA personnalisés (Phase 4) +- Transcription audio (Phase 4) +- Admin dashboard avancé (Phase 2) +- Analytics d'utilisation IA (Phase 2) + +--- + +### Post-MVP Features + +**Phase 2 (Post-MVP - Enhancement & Scale):** + +**Timeframe:** 3-6 months post-MVP launch + +**Additional User Types:** +- Journey 3: Léa (Admin Système) avec dashboard IA +- Power Users avec plus de 1000 notes + +**Enhanced IA Features:** +- **Description Images + OCR** + - Bouton IA sur images dans notes + - Génération description automatique + - Extraction texte (OCR) + +- **Résumé URLs** + - Détection automatique URLs dans notes + - Bouton "Résumer" pour extraire points clés + - Choix: résumé court vs. analyse détaillée + +- **Suggestions Suites Logiques** + - Après chaque note, IA suggère "Idées de suite" + - Basé sur le contenu de la note actuelle + +- **AI Settings Avancés** + - Paramètres configurables par feature (température, max tokens, etc.) + - Ajustement par utilisateur (langue force, créativité) + +- **Admin Dashboard IA** + - Métriques temps réel (usage today, avg response time) + - Surveillance coûts IA (OpenAI billing estimation) + - Ajustement settings par utilisateur (admin overrides) + +- **Onboarding IA** + - Tour guidé pour nouveaux utilisateurs + - Discovery progressif des features IA + +**Success Criteria Phase 2:** +- 500+ GitHub stars +- 200+ WAU (Weekly Active Users) +- Week 1-4 retention > 40% + +--- + +**Phase 3 (Expansion - Trust & Intelligence):** + +**Timeframe:** 6-12 months post-MVP + +**Trust & Transparency:** +- **Score de Confiance Visible** + - Pourcentage affiché pour chaque génération IA + - >90% = ✅ Solide (auto-application) + - 70-89% = ⚠️ Moyen (à vérifier) + - <70% = ❌ Faible (pas d'auto-génération) + +- **Système Feedback Généralisé** + - Boutons 👍👎 sur TOUTES les générations IA + - Modal explicatif pour feedback 👎 ("Pourquoi c'est faux?") + - Apprentissage automatique (patterns utilisateur) + +- **Mode Conservateur (Safety First)** + - Générations auto seulement si confiance >90% + - Si doute: IA demande confirmation utilisateur + - Réduction fausses positives < 5% + +**Advanced Capabilities:** +- **Détection Langue Améliorée** + - Plus de langues supportées (JA, ZH, IT, PT, NL, etc.) + - Language switching automatique (notes multilingues) + +- **Memory Echo V2** + - Graph visualization des connexions + - Insights multiples par jour avec priorisation + - Clustering thématique des notes + +**Business Model:** +- Lancement freemium avec "Buy me a coffee" +- Features avancées payantes (Phase 4) +- Monétisation éthique sans lock-in + +**Success Criteria Phase 3:** +- 1000+ GitHub stars +- 500+ WAU +- Week 1-4 retention > 50% + +--- + +**Phase 4 (Future - Advanced Features):** + +**Timeframe:** 12+ months post-MVP + +**Advanced Features:** +- **Transcription Audio** + - Notes vocales avec transcription IA + - Commandes vocales ("Crée une note sur X") + +- **Organisation Auto** + - IA propose dossiers/catégories + - Tags automatiques hiérarchiques + +- **Templates IA Personnalisés** + - IA génère templates selon patterns utilisateur + - "Meeting notes", "Brainstorming", "Project planning" + +- **Mode "Super IA"** + - Optimisation complète note (titre + tags + reformulation) + - One-click enhancement + +--- + +### Risk Mitigation Strategy + +**Technical Risks:** + +**Risk 1: Performance embeddings avec 1000+ notes** +- **Mitigation:** Caching agressif (embeddings stockés en DB), background processing +- **Fallback:** Pagination pour gros volumes de notes +- **Monitoring:** Alertes si > 500ms pour recherche sémantique + +**Risk 2: Ollama local lent ou instable** +- **Mitigation:** Support multi-provider (fallback OpenAI automatique) +- **User Control:** Utilisateur peut switcher manuellement +- **Performance:** Mode local optionnel, pas obligatoire + +**Risk 3: Memory Echo fait des connexions aléatoires** +- **Mitigation:** Cosine threshold > 0.75, time diversity filter +- **Feedback:** 👎 ajuste le système, apprentissage continu +- **User Control:** Fréquence configurable 0-3/jour, OFF toggle + +**Market Risks:** + +**Risk 1: Utilisateurs ne voient pas la valeur de Memory Echo** +- **Mitigation:** Fréquence conservative (1/jour max), ne pas spam +- **Onboarding:** Tour guidé met en avant Memory Echo +- **Validation:** Beta testing avec early adopters pour ajuster threshold + +**Risk 2: Google Keep ou Notion copient Memory Echo** +- **Mitigation:** First-mover advantage, open source community +- **Moat:** Difficile à copier sans embeddings existants + feedback learning +- **Innovation:** Continuer à innover (Phase 2, 3, 4) + +**Risk 3: Adoption IA lente (résistance utilisateur)** +- **Mitigation:** Pattern "Zéro Prise de Tête" - non-intrusif par défaut +- **Control:** ON/OFF granulaire pour chaque feature +- **Education:** Documentation claire, exemples d'utilisation + +**Resource Risks:** + +**Risk 1: Équipe trop petite (1 dev seul)** +- **Mitigation:** Scope minimal viable, pas de features "nice-to-have" +- **Contingency:** Si ressources limitées, couler Memory Echo (garder pour Phase 2) +- **Priority:** Titres auto + Recherche sémantique = valeur core + +**Risk 2: Coûts OpenAI explosent** +- **Mitigation:** Support Ollama local (zero coût marginal) +- **User Choice:** Utilisateur peut choisir provider selon budget +- **Optimization:** Caching, rate limiting par utilisateur + +**Risk 3: Timeline plus longue que prévue** +- **Mitigation:** MVP scoping flexible - features peuvent être déplacées +- **Contingency:** Si 8 semaines insuffisantes, étendre à 12 semaines +- **MVP Definition:** Pas besoin de toutes les features parfaites - "good enough" pour launch + +**Overall Risk Posture:** +- **Philosophy:** Conservative par défaut, optimiser pour apprentissage +- **Validation:** Beta testing rapide, feedback continu +- **Flexibilité:** Scope adaptable selon contraintes ressources/temps + +## Functional Requirements + +### AI-Powered Content Enhancement + +- FR1: Users can receive AI-generated title suggestions when writing notes without titles +- FR2: Users can view multiple title suggestion options before selecting one +- FR3: Users can apply AI-generated titles to their notes with a single action +- FR4: Users can defer title suggestions to view later +- FR5: Users can dismiss title suggestions for specific notes permanently +- FR6: Users can request AI-powered reformulation of selected paragraph content +- FR7: Users can select different reformulation approaches (clarify, shorten, improve style) +- FR8: Users can replace original content with AI-reformulated versions +- FR9: Users can cancel reformulation actions and retain original content +- FR10: Users can provide positive or negative feedback on AI-generated content + +### Intelligent Search & Discovery + +- FR11: Users can search notes using keyword queries that match exact text +- FR12: Users can search notes using natural language queries that match semantic meaning +- FR13: Users can view combined search results from both keyword and semantic matching +- FR14: Users can see visual indicators distinguishing exact matches from semantic matches +- FR15: Users can receive proactive insights about connections between related notes +- FR16: Users can view the specific content and context of suggested note connections +- FR17: Users can link related notes together when accepting connection suggestions +- FR18: Users can dismiss proactive connection insights +- FR19: Users can provide feedback on the relevance of suggested note connections + +### User Control & Preferences + +- FR20: Users can access AI settings to configure individual feature availability +- FR21: Users can enable or disable title suggestions independently +- FR22: Users can enable or disable semantic search independently +- FR23: Users can enable or disable paragraph reformulation independently +- FR24: Users can enable or disable proactive connection insights independently +- FR25: Users can adjust the frequency limit for proactive connection insights +- FR26: Users can customize AI trigger thresholds (e.g., word count for title suggestions) +- FR27: Users can set time period constraints for proactive connection analysis +- FR28: Users can temporarily disable all proactive AI features during focused work sessions +- FR29: Users can re-enable disabled AI features through settings interface + +### Privacy & Multi-Provider AI Architecture + +- FR30: Users can select between local AI processing (Ollama) and cloud AI processing (OpenAI) +- FR31: Users can verify that local AI processing does not send data external to their device +- FR32: Users can view connection status indicators for AI providers +- FR33: Users can switch between AI providers without losing functionality +- FR34: The system can automatically fallback to alternative AI providers if primary provider fails +- FR35: Users can configure API keys for cloud AI providers +- FR36: Users can remove stored API credentials from the system +- FR37: The system can detect and support multiple languages in user-generated content +- FR38: The system can process AI requests using user's content language while maintaining system prompts in English + +### Administration & Operations + +- FR39: Administrators can configure default AI provider settings for all users +- FR40: Administrators can set rate limits on AI usage per user +- FR41: Administrators can override individual user AI settings +- FR42: Administrators can monitor real-time AI usage metrics across the system +- FR43: Administrators can view AI processing costs and consumption statistics +- FR44: Administrators can adjust AI model parameters (temperature, max tokens, etc.) +- FR45: Administrators can configure team-wide AI feature availability +- FR46: The system can encrypt and securely store AI provider API keys + +### Accessibility & Responsive Design + +- FR47: Users can access all AI features using keyboard navigation without mouse input +- FR48: Users can receive screen reader announcements for AI-generated content and suggestions +- FR49: Users can dismiss AI notifications and suggestions using keyboard shortcuts +- FR50: Users can view and interact with AI features on mobile devices (320px-639px) +- FR51: Users can view and interact with AI features on tablet devices (640px-1023px) +- FR52: Users can view and interact with AI features on desktop devices (1024px+) +- FR53: Users can perceive visual focus indicators on all interactive AI elements +- FR54: Users can access AI features with touch targets meeting minimum size requirements (44x44px on mobile) + +## Non-Functional Requirements + +### Performance + +**AI Feature Response Times:** + +- NFR-PERF-001: Title suggestions generate within 2 seconds of trigger detection +- NFR-PERF-002: Semantic search results return within 300 milliseconds for databases up to 1,000 notes +- NFR-PERF-003: Memory Echo background analysis completes with less than 100 milliseconds of UI thread blocking +- NFR-PERF-004: Paragraph reformulation completes within 5 seconds for content up to 500 words + +**System Performance:** + +- NFR-PERF-005: Initial page load achieves First Contentful Paint (FCP) in under 3 seconds on 4G connections +- NFR-PERF-006: Application reaches Time to Interactive (TTI) within 5 seconds on modern browsers +- NFR-PERF-007: JavaScript bundle remains under 200KB gzipped (excluding AI provider libraries) +- NFR-PERF-008: AI features load on-demand without affecting initial application bundle size + +**Performance Under Load:** + +- NFR-PERF-009: System supports 50 concurrent users with less than 10% performance degradation +- NFR-PERF-010: Search response time remains under 500ms with 10,000 notes in database + +--- + +### Security + +**Data Protection:** + +- NFR-SEC-001: All user notes are encrypted at rest in the database +- NFR-SEC-002: All data transmitted between client and server uses HTTPS/TLS 1.3+ +- NFR-SEC-003: User passwords are hashed using bcrypt with minimum 12 salt rounds +- NFR-SEC-004: AI provider API keys are encrypted when stored in database + +**Privacy-First Architecture:** + +- NFR-SEC-005: Local AI processing (Ollama) sends zero data to external services +- NFR-SEC-006: Users can verify local processing mode through network inspection tools +- NFR-SEC-007: User content language detection and processing occurs server-side without exposing raw content to external AI providers when using local mode +- NFR-SEC-008: System does not log or store user note content beyond database persistence + +**Authentication & Authorization:** + +- NFR-SEC-009: User sessions expire after 30 days of inactivity +- NFR-SEC-010: Password reset tokens expire within 1 hour of generation +- NFR-SEC-011: Administrator access requires explicit role assignment (default role is USER) +- NFR-SEC-012: Users can only access their own notes, labels, and AI settings unless explicitly granted admin privileges + +**API Security:** + +- NFR-SEC-013: All API routes validate user authentication before processing requests +- NFR-SEC-014: Rate limiting prevents abuse of AI endpoints (maximum 100 requests per minute per user) + +--- + +### Accessibility + +**WCAG 2.1 Level AA Compliance:** + +- NFR-A11Y-001: All AI features are fully operable using keyboard-only navigation +- NFR-A11Y-002: Screen readers announce AI-generated content and suggestions with descriptive text +- NFR-A11Y-003: All interactive AI elements have visible focus indicators with minimum 3:1 contrast ratio +- NFR-A11Y-004: Color alone is not used to convey information; visual indicators include text labels or icons + +**Touch Targets (Mobile):** + +- NFR-A11Y-005: All interactive AI elements on mobile devices meet minimum tap target size of 44×44 pixels +- NFR-A11Y-006: Touch targets have minimum 8 pixels spacing between adjacent interactive elements + +**Responsive Design:** + +- NFR-A11Y-007: AI features function correctly on mobile devices (320px-639px viewport width) +- NFR-A11Y-008: AI features function correctly on tablet devices (640px-1023px viewport width) +- NFR-A11Y-009: AI features function correctly on desktop devices (1024px+ viewport width) + +**Notification Accessibility:** + +- NFR-A11Y-010: AI toast notifications use `role="status"` (not `role="alert"`) to avoid interrupting screen reader navigation +- NFR-A11Y-011: Notifications can be dismissed using keyboard ESC key + +--- + +### Reliability + +**System Availability:** + +- NFR-REL-001: Application achieves 99% uptime during business hours (9 AM - 6 PM user local time) +- NFR-REL-002: Graceful degradation occurs if AI providers are unavailable (core note-taking features remain functional) + +**Error Handling:** + +- NFR-REL-003: AI feature failures display user-friendly error messages without technical jargon +- NFR-REL-004: Failed AI requests automatically retry with exponential backoff (maximum 3 attempts) +- NFR-REL-005: System provides fallback to alternative AI provider if primary provider fails + +**Data Integrity:** + +- NFR-REL-006: All user actions maintain ACID properties (Atomic, Consistent, Isolated, Durable) +- NFR-REL-007: Vector embeddings are cached after generation to prevent redundant processing + +**Background Processing:** + +- NFR-REL-008: Memory Echo analysis runs asynchronously without blocking user interactions +- NFR-REL-009: Background jobs log failures for administrator review without exposing errors to end users + +--- + +### Integration + +**AI Provider Integration:** + +- NFR-INT-001: System supports OpenAI API for cloud AI processing +- NFR-INT-002: System supports Ollama API for local AI processing +- NFR-INT-003: Factory pattern allows adding new AI providers without modifying existing code + +**Multi-Provider Architecture:** + +- NFR-INT-004: Users can switch between AI providers without losing data or functionality +- NFR-INT-005: System automatically detects available AI providers during startup +- NFR-INT-006: Provider connection status indicators display current operational state + +**API Compatibility:** + +- NFR-INT-007: System maintains compatibility with OpenAI API versions through abstraction layer +- NFR-INT-008: Ollama integration supports all models compatible with `/api/tags` and `/api/embeddings` endpoints + +**Extensibility:** + +- NFR-INT-009: New AI models can be added through configuration without code changes for supported providers +- NFR-INT-010: Custom OpenAI-compatible endpoints can be configured through settings + +--- + +### Scalability (MVP Scope) + +**Phase 1 Capacity:** + +- NFR-SCA-001: System supports 50-200 concurrent users with acceptable performance +- NFR-SCA-002: Database performs acceptably with up to 10,000 notes per user +- NFR-SCA-003: Embedding generation throughput supports 100 notes per minute per user + +**Resource Efficiency:** + +- NFR-SCA-004: SQLite database size remains under 2GB for 100,000 notes with embeddings +- NFR-SCA-005: Memory consumption per user session remains under 100MB + +**Post-MVP Consideration:** + +- NFR-SCA-006: Architecture supports migration to PostgreSQL for Phase 2 if needed for larger scale + + diff --git a/_bmad-output/planning-artifacts/ux-design-specification.md b/_bmad-output/planning-artifacts/ux-design-specification.md new file mode 100644 index 0000000..eea8561 --- /dev/null +++ b/_bmad-output/planning-artifacts/ux-design-specification.md @@ -0,0 +1,2634 @@ +--- +stepsCompleted: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] +inputDocuments: + - _bmad-output/planning-artifacts/prd-phase1-mvp-ai.md + - docs/component-inventory.md + - docs/project-overview.md +workflowType: 'ux-design' +lastStep: 11 +documentTitle: 'UX Design Specification - Phase 1 MVP AI' +focusArea: 'AI-Powered Note Taking Features' +status: 'in-progress' +createdAt: '2026-01-10' +--- + +# UX Design Specification - Phase 1 MVP AI + +**Project:** Memento +**Author:** Ramez +**Date:** 2026-01-10 +**Focus:** UX Design for AI-Powered Note Taking Features + +--- + +## Executive Summary + +### Project Vision + +**Memento Phase 1 MVP AI** transforms the existing note-taking application into a **proactive cognitive partner** with the philosophy **"Zéro Prise de Tête"** (Zero-Friction Intelligence). + +**Core Philosophy:** "Suggest and facilitate, never impose" + +**What Makes It Special:** +- **Contextual Smart Assistance**: AI features appear only when relevant, not overwhelming +- **Hybrid Semantic Discovery**: Unified search that "just works" - users don't distinguish keyword vs semantic +- **Memory Echo** ⭐: Proactive connections between notes that users hadn't seen (the "Aha!" moment) +- **Privacy-First Multi-Provider**: Ollama (100% local) OR OpenAI (cloud) - user choice + +**The "Aha!" Moment:** +> *"I didn't search, it found me"* +> +> 💡 *"I noticed something..."* +> *"You noted `[Node.js performance tips]` in January and `[Next.js optimization]` this week. These notes are connected - want me to link them?"* + +### Target Users + +**Primary Personas (from PRD User Journeys):** + +**1. Alex - Creative Developer (Success Path)** +- **Profile:** Freelance Creative & Developer, 32, Paris +- **Problem:** 300+ notes, can't find anything, spends 20min searching +- **Goals:** Instant capture, intelligent organization +- **Discovery:** Toast title suggestions → Memory Echo reveals invisible connections → "Hooked!" + +**2. Max - Privacy Advocate** +- **Profile:** Privacy Advocate & Software Engineer, 28, Berlin +- **Problem:** Wants AI but refuses to let data leave his laptop +- **Goals:** Total control + verifiable (checks DevTools for 0 external calls) +- **Discovery:** Verifies Ollama = 0 external API calls → Builds trust + +**3. Léa - System Admin** (Phase 2, not MVP) +- **Profile:** DevOps Engineer, 35, Lyon - Team admin +- **Problem:** Configure AI for 15 devs, monitor costs +- **Goals:** Admin dashboard + AI analytics + +**4. Sophie - Skeptic to Trust** +- **Profile:** Content Marketing Manager, 29, Bordeaux +- **Problem:** AI makes mistakes, learns to trust through customization +- **Goals:** Personalizable AI settings, feedback learning + +**User Characteristics:** +- **Tech-savvy**: Developers, knowledge workers, creatives +- **Devices**: Desktop (laptop) + Mobile (smartphone/tablet) +- **Context**: Async work, quick capture in subway, meetings + +### Key Design Challenges + +**1. Contextual Smart Assistance Pattern** +- **Challenge:** Make AI features appear only when relevant +- **Example:** Title suggestions AFTER 50+ words without title +- **Question:** How to avoid overwhelming users with too many AI features? + +**2. Memory Echo - "I Didn't Search, It Found Me"** +- **Challenge:** Surface proactive connections without appearing spammy +- **Constraint:** Max 1 insight/day (configurable 0-3) +- **Question:** How to make every insight feel valuable? + +**3. Privacy-First Multi-Provider** +- **Challenge:** Communicate that Ollama = 100% local processing +- **Solution:** Connection status indicators, verifiable in DevTools +- **Question:** How to clearly communicate local vs cloud difference? + +**4. Feedback & Learning** +- **Challenge:** AI makes mistakes, how to recover user trust? +- **Solution:** 👍👎 buttons, "Why is this wrong?" modal, customizable settings +- **Question:** How to make feedback learning visible and reassuring? + +### Design Opportunities + +**1. Toast Notification Pattern - Natural Discovery** +- Instead of hiding features in menus, discover them when relevant +- Example: "I have 3 title ideas for your note, view them?" +- **Benefit:** Users discover features without tutorial + +**2. "Exact Match | Semantic Match" Badges** +- Hybrid search that "just works" - users don't know how it works +- Visual badges to distinguish keyword vs semantic results +- **Benefit:** Educates users without confusing them + +**3. Memory Echo Card - The "Aha!" Moment** +- Proactive notification: "I noticed something..." +- Display 2 connected notes side-by-side +- 👍👎 buttons for learning +- **Benefit:** Creates unique emotional moment ("Wow, that's clever!") + +**4. Granular AI Settings - Total Control** +- ON/OFF checkboxes for each AI feature +- Memory Echo frequency slider (0-3/day) +- **Benefit:** User feels in control, not "spied on by AI" + +--- + +## Core User Experience + +### Defining Experience + +**Core Experience:** "Fast Capture + Intelligent Discovery" + +Memento Phase 1 MVP AI combines two fundamental experiences: + +1. **Fast Capture** (Primary - Existing Enhanced) + - Instant note creation with zero friction + - Content first, title comes later (or AI-suggested) + - Markdown supported but not required + - Capture anywhere: desktop (laptop), mobile (subway, meetings), tablet + +2. **Intelligent Discovery** (New - Phase 1) + - AI organizes silently in background + - Title suggestions appear contextually (after 50+ words without title) + - Semantic search that "just works" + - Memory Echo reveals invisible connections between notes + +**Core User Loop:** +``` +Capture → AI Organizes → Discover → Capture → ... + ↑_____________↓ + Seamless Flow +``` + +The critical insight: Capture must remain instant (no AI friction), while AI enhances organization in the background. + +### Platform Strategy + +**Primary Platform:** Web Application (Responsive) + +No native mobile apps - modern browsers provide sufficient capabilities. + +**Device Breakdown:** + +| Platform | Viewport | Usage | Interaction Style | +|----------|----------|-------|-------------------| +| **Desktop** | 1024px+ | Primary - serious work, content creation | Mouse + Keyboard (shortcuts, power users) | +| **Tablet** | 640px-1023px | Intermediate - comfortable reading | Touch + Keyboard (hybrid) | +| **Mobile** | 320px-639px | Quick capture on-the-go | Touch-first (44x44px tap targets) | + +**Technical Stack:** +- Next.js 16.1.1 (SSR + App Router) +- React 19.2.3 (Server + Client Components) +- Tailwind CSS 4 (utility-first styling) +- Radix UI (accessible primitives) + +**Responsive Design Strategy:** +- Mobile-first approach +- Progressive enhancement +- Touch-optimized on mobile, keyboard-optimized on desktop + +**Offline Requirements:** None for MVP (Phase 2: PWA with offline mode) + +### Effortless Interactions + +**1. Zero-Friction Capture** +- Opening Memento → Type immediately (no login friction after first session) +- No "choose a title first" → Content comes first +- Optional markdown formatting (not required) +- Auto-save as you type + +**2. Natural Feature Discovery** +- Toast notification: "I have 3 title ideas for your note, view them?" +- Options: "View | Not now | Don't ask for this note" +- User discovers AI features when relevant, not via tutorial +- Non-intrusive, respectful of user's flow + +**3. Memory Echo "Aha!" Moment** +- Subtle notification: "I noticed something..." +- Max 1 insight/day (configurable 0-3) +- When relevant → User thinks: "That's clever!" +- Not spammy, each insight feels valuable + +**4. Search That "Just Works"** +- User types naturally: "how to optimize React performance" +- Results show with badges: "Exact Match | Semantic Match" +- User doesn't know how it works, but it finds the note +- Hybrid search = keywords + semantic mixed, no user configuration needed + +**5. Privacy-First Transparency** +- Clear indicators: "✅ Connected to local Ollama" vs "✅ Connected to OpenAI Cloud" +- Verifiable in DevTools (Max checks for 0 external API calls) +- Users can see and trust where their data goes + +### Critical Success Moments + +**Moment 1: First Title Suggestion Accepted** +- **Trigger:** User writes 50+ words without title +- **Interaction:** Toast appears → User clicks "View" → Sees 3 relevant suggestions +- **Success Metric:** User accepts suggestion (>60% acceptance target) +- **User Thought:** "Wow, that saved me time!" +- **Failure:** Suggestions irrelevant → User dismisses permanently + +**Moment 2: Memory Echo "Aha!" Discovery** +- **Trigger:** Background analysis finds strong connection (cosine >0.75) +- **Interaction:** Notification shows 2 connected notes side-by-side +- **Success Metric:** User clicks "View Connection" (>40% CTR target) +- **User Thought:** "I hadn't seen that link before!" +- **Failure:** Connection feels random → User clicks 👎 or disables feature + +**Moment 3: Semantic Search Finds the Unfindable** +- **Trigger:** User searches naturally (not exact keywords) +- **Interaction:** Results show with "Semantic Match" badge +- **Success Metric:** Semantic result in top 3 (>30% of complex searches) +- **User Thought:** "How did it find that? I searched for X, not Y!" +- **Failure:** Doesn't find what exists → User returns to Ctrl+F + +**Moment 4: Privacy Verification (Max's Journey)** +- **Trigger:** Privacy-conscious user selects Ollama +- **Interaction:** Checks DevTools → Confirms 0 external API calls +- **Success Metric:** Trust established, continues using AI features +- **User Thought:** "Good, they kept their word. My data stays local." +- **Failure:** Any data leak → Uninstalls immediately + +### Experience Principles + +**Guiding Principles for All UX Decisions:** + +**1. Capture First, Organize Later** +- Content comes before title +- AI organizes in background, never intrusive during capture +- "Zero friction" for creation +- **Implication:** No AI processing blocks note creation + +**2. Contextual, Not Constant** +- AI features appear only when relevant +- No permanent AI toolbar (overwhelming) +- Temporary toast notifications with "Not now" option +- Single-interaction rule (only one AI prompt at a time) +- **Implication:** Prioritize which AI feature to show if multiple triggered + +**3. Hybrid by Design** +- Keywords AND semantic mixed (user doesn't distinguish) +- Local AND cloud providers (user chooses) +- Manual AND auto (user controls automation level) +- **Implication:** Don't expose complexity, blend approaches seamlessly + +**4. Transparent Control** +- Every AI feature has granular ON/OFF +- Connection status indicators (local vs cloud) +- Feedback 👍👎 visible and impactful +- Settings explain what's happening +- **Implication:** Users feel in control, not "spied on by AI" + +**5. Progressive Disclosure** +- Simple by default, powerful when needed +- Basic usage: Just capture notes +- Advanced usage: Customize AI thresholds, frequency, providers +- **Implication:** Don't overwhelm new users with settings + +**6. Graceful Degradation** +- If AI fails, core note-taking still works +- Fallback to alternative provider automatically +- User-friendly error messages (no technical jargon) +- **Implication:** AI enhances, doesn't block core functionality + +--- + +## Desired Emotional Response + +### Primary Emotional Goals + +**Core Emotional Reaction:** "Wow, Memento understands my knowledge better than I do!" + +The defining emotional moment occurs when Memory Echo reveals an invisible connection: +> 💡 *"I noticed something..."* +> *"You noted `[Node.js performance tips]` in January and `[Next.js optimization]` this week. These notes are connected."* + +**User's Internal Monologue:** +- "I hadn't made that connection!" (Surprise) +- "That's brilliant!" (Admiration) +- "Memento is smarter than me!" (Trust in AI) + +**This is THE differentiator** from Google Keep/Notion which lack proactive intelligence. + +**Primary Emotional Goal:** Create recurring "Aha!" moments where users feel the AI is genuinely helpful, not intrusive. + +### Emotional Journey Mapping + +Based on the 4 User Journeys from the PRD, the emotional progression: + +**Stage 1: First Discovery - Curiosity** +- *Opening Memento:* "Ok, a notes app. Standard." +- *First capture:* "Fast, it works. Good." +- *No surprise or wow yet* - Just solid functionality + +**Stage 2: First AI Interaction - Interest** +- *Toast "I have 3 title ideas...":* "Oh? What's this?" +- *Relevant suggestions:* "Hey, that's actually pretty good!" (Positive) +- *Applying title:* "Cool, saved time." + +**Stage 3: Memory Echo - THE "Aha!" Moment** ⭐ +- *Notification "I noticed something...":* "What's this about?" +- *Seeing 2 connected notes:* "WOAH! I never saw that link!" (Surprise) +- *Click "View Connection":* "Memento understands my knowledge better than I do!" (Trust) + +**Stage 4: Trust Building - Confidence** +- *Granular AI Settings:* "I can control everything. Nice." +- *Ollama Local (Max):* "Zero external calls. Perfect!" +- *Feedback 👍👎:* "My opinion matters. The AI learns." + +**Stage 5: Long-term - Satisfaction** +- *Finding the unfindable:* "Thanks Memento, you saved me." +- *Less mental load:* "Finally, I'm organized without effort." + +### Micro-Emotions + +Subtle but critical emotional states that determine success: + +**1. Trust vs. Skepticism** ✅ CRITICAL +- **Sophie (Skeptic):** "AI will spam me or get things wrong." +- **Transformation:** 👎 feedback → "Why?" modal → AI learns → "Ok, it listens to me." +- **Target Micro-emotion:** **Trust building through transparency** + +**2. Control vs. Overwhelm** ✅ CRITICAL +- **Risk:** Too many AI features = overwhelming +- **Solution:** Toast "Not now" option, granular ON/OFF settings +- **Target Micro-emotion:** **"I'm in control, not the AI"** + +**3. Efficiency vs. Frustration** ✅ CRITICAL +- **Alex before Memento:** "I spend 20min finding this note!" (Frustration) +- **After Memory Echo:** "Found in 2 seconds!" (Efficiency) +- **Target Micro-emotion:** **"I'm smarter with Memento"** + +**4. Surprise vs. Annoyance** +- **Risk:** Toast notifications = perceived as spam +- **Solution:** Contextual triggers (50+ words), "Don't ask for this note" +- **Target Micro-emotion:** **"Oh, that's useful!" not "Another notification..."** + +**5. Privacy vs. Anxiety** +- **Max:** "Will my personal data go to the cloud?" +- **Solution:** Status indicators (✅ 100% Local Ollama), DevTools verifiable +- **Target Micro-emotion:** **"My data is safe, I'm in control"** + +### Design Implications + +Connecting desired emotions to specific UX design choices: + +**1. Trust → Transparency** +- **UX Choice:** Visual status indicators (✅ Local Ollama | ✅ OpenAI Cloud) +- **UX Choice:** 👍👎 buttons with visible feedback ("Thanks, we're learning!") +- **UX Choice:** Settings explain WHAT the AI does (no black box) +- **Implementation:** Tooltip/badge explaining "I analyzed 150 notes to find this connection" + +**2. Control → Granular Settings** +- **UX Choice:** Individual ON/OFF checkboxes for EACH AI feature +- **UX Choice:** Memory Echo frequency slider (0-3/day) +- **UX Choice:** "Don't ask for this note" respected immediately +- **Implementation:** `/settings/ai` page as most important page in product + +**3. Efficiency → Instant Results** +- **UX Choice:** Semantic search < 300ms (no slow loading spinner) +- **UX Choice:** Title generation < 2s (feels instant) +- **UX Choice:** Memory Echo background processing (< 100ms UI freeze) +- **Implementation:** Skeleton screens, optimistic UI updates + +**4. Positive Surprise → Contextual Triggers** +- **UX Choice:** Toast ONLY after 50+ words (not at first word) +- **UX Choice:** Memory Echo max 1/day (not spammy) +- **UX Choice:** "Exact Match | Semantic Match" badges to educate without confusing +- **Implementation:** Single-interaction rule (prioritize which AI feature to show) + +**5. Security → Privacy Indicators** +- **UX Choice:** Lock icon 🔒 for Ollama local +- **UX Choice:** Clear message "Your data never leaves your device" for Ollama +- **UX Choice:** "100% Local" badge visible in Settings +- **Implementation:** Provider selection screen with clear visual distinction + +### Emotional Design Principles + +**Guiding Principles for Creating Desired Emotional Responses:** + +**1. "Aha!" Moments Over Features** +- Prioritize discovery moments (Memory Echo) over feature quantity +- Create 1-2 memorable "Wow" moments rather than 10 mediocre features +- **Design Implication:** Invest UX effort in Memory Echo = maximum emotional ROI + +**2. Trust Through Transparency** +- Never hide what the AI is doing +- Show the work ("I analyzed 150 notes to find this connection") +- **Design Implication:** Loading states, badges, tooltips explain the "why" + +**3. Control Reduces Anxiety** +- Every AI feature can be disabled independently +- User chooses automation level +- **Design Implication:** AI Settings page = most important product page + +**4. Speed = Intelligence** +- If it's fast, AI seems smart +- If it's slow, AI seems "dumb" or "heavy" +- **Design Implication:** Optimize performance (< 2s titles, < 300ms search) = emotional UX + +**5. Fail Gracefully, Recover Quickly** +- When AI errs, UX says "Sorry, I'm learning!" not "System error" +- 👎 feedback = trust-building opportunity (not failure) +- **Design Implication:** "Why is this wrong?" modal + "Thanks for teaching me!" + +**6. Contextual > Constant** +- AI features appear only when relevant +- No permanent AI toolbar (overwhelming) +- **Design Implication:** Temporary toast notifications with dismissal options + +--- + +## UX Pattern Analysis & Inspiration + +### Inspiring Products Analysis + +Based on the personas (Alex, Max, Léa, Sophie) and competitive landscape, here are the key inspiring products: + +**1. Google Keep** (Direct Competitor) +- **What they do well:** Ultra-fast capture, clean interface, masonry grid layout +- **What's missing:** Proactive AI, semantic search, connections between notes +- **Pattern to learn:** Simplicity of capture, Masonry layout optimization +- **Already in Memento:** MasonryGrid component exists (from component inventory) + +**2. Notion** (Indirect Competitor) +- **What they do well:** Power features, databases, on-demand AI +- **What's missing:** Contextual (too complex), no proactive insights +- **Pattern to learn:** Rich text editor, slash commands +- **Not applicable:** Too complex for Memento's "zero-friction" philosophy + +**3. GitHub Copilot** (AI Reference - Developers) +- **What they do well:** Non-intrusive contextual suggestions +- **Pattern inspiration:** AI appears when relevant, no permanent toolbar +- **Connection to Memento:** Contextual Smart Assistance for title suggestions +- **Key insight:** Single-interaction rule (don't overwhelm with multiple AI prompts at once) + +**4. Linear** (UX Reference - Tech-Savvy Users) +- **What they do well:** Speed = intelligence perception, keyboard-first, native dark mode +- **Pattern inspiration:** Performance creates perceived intelligence +- **Connection to Memento:** < 2s title generation, < 300ms semantic search +- **Key insight:** If AI is fast, users think it's smart. If slow, it seems "dumb" + +**5. Obsidian** (Notes Reference - Power Users) +- **What they do well:** Graph view (visual connections), plugin ecosystem +- **What's missing:** Proactive AI (connections are manual) +- **Pattern inspiration:** Connections between notes +- **Memento innovation:** Memory Echo = PROACTIVE connections (AI finds them, not user) + +**6. Slack/Notion AI** (Anti-Pattern Reference) +- **What they do poorly:** Too frequent AI notifications = perceived as spam +- **Anti-pattern to avoid:** Insufficient contextualization +- **Connection to Memento:** Max 1 insight/day to avoid annoyance +- **Key lesson:** Restrictive frequency limits build trust + +### Transferable UX Patterns + +**Pattern 1: Contextual Triggers (from GitHub Copilot)** +- **Source:** Copilot suggests only when relevant, not permanently +- **Memento application:** Toast titles after 50+ words (not at first word) +- **Why it works:** Natural discovery, not overwhelming +- **Design implication:** Single-interaction rule (only one AI feature at a time) +- **Implementation:** Priority queue if multiple AI triggers fire simultaneously + +**Pattern 2: Masonry Layout (from Google Keep)** +- **Source:** Google Keep uses masonry grid for notes +- **Memento application:** Already implemented in component inventory (MasonryGrid) +- **Why it works:** Space optimization, visually pleasing +- **Design implication:** Reuse existing MasonryGrid, add AI badges +- **Implementation:** AI badges on NoteCard ("Title Suggested", "Semantic Match") + +**Pattern 3: Speed = Intelligence (from Linear)** +- **Source:** Linear feels "smart" because it's ultra-fast +- **Memento application:** < 2s titles, < 300ms semantic search +- **Why it works:** Fast AI = perceived intelligence +- **Design implication:** Optimistic UI, skeleton screens, background processing +- **Implementation:** Show "Generating..." only if > 1s (otherwise appears instant) + +**Pattern 4: Graph Connections → Memory Echo (from Obsidian)** +- **Source:** Obsidian shows manual graph view of connections +- **Memento application:** Memory Echo PROACTIVELY reveals connections +- **Innovation:** AI finds connections, not user +- **Design implication:** Subtle notification, max 1/day, 👍👎 feedback +- **Implementation:** Background cosine similarity analysis, user-triggered dismissal + +**Pattern 5: Slash Commands → Contextual Menu (from Notion)** +- **Source:** Notion uses `/` for commands +- **Memento application:** Reformulation via "..." menu on NoteCard (not slash) +- **Why different:** Slash commands too intrusive for simple notes +- **Design implication:** Contextual menu, not memorized commands +- **Implementation:** NoteCard overflow menu → "Reformulate with AI" option + +### Anti-Patterns to Avoid + +**Anti-Pattern 1: Too Frequent AI Notifications (Slack AI, Notion AI)** +- **Problem:** "Hey! Try this feature!" every day = spam +- **Consequence:** Users disable all AI notifications +- **Memento solution:** Contextual triggers (50+ words), max 1 insight/day +- **Design implication:** Respect "Don't ask for this note" immediately + +**Anti-Pattern 2: Permanent AI Toolbar (Too Many Apps)** +- **Problem:** Toolbar with 10 AI features = overwhelming +- **Consequence:** Users ignore everything, "analysis paralysis" +- **Memento solution:** Temporary toasts, features appear when relevant +- **Design implication:** No permanent "AI Features" badge in header + +**Anti-Pattern 3: Black Box AI (ChatGPT, Claude UI)** +- **Problem:** Users don't know what AI is doing with their data +- **Consequence:** Skepticism, trust erosion (Sophie persona) +- **Memento solution:** Transparency ("I analyzed 150 notes"), explanatory badges +- **Design implication:** Tooltips, badges, status indicators explain "why" + +**Anti-Pattern 4: Slow Loading Spinners (Legacy Apps)** +- **Problem:** 5+ second spinner = AI seems "slow" or "dumb" +- **Consequence:** Users think "not better than manual" +- **Memento solution:** < 2s titles, < 300ms search = perceived intelligence +- **Design implication:** Skeleton screens, optimistic UI, background jobs + +**Anti-Pattern 5: Hidden AI Settings (Too Many SaaS)** +- **Problem:** AI settings buried 3 levels deep in obscure menu +- **Consequence:** Users don't know how to disable, frustration +- **Memento solution:** `/settings/ai` page visible, link in header +- **Design implication:** AI Settings = most important page in product + +### Design Inspiration Strategy + +**ADOPT (Take as-is):** + +1. **Masonry Layout (Google Keep)** + - **Why:** Already implemented, works well + - **Usage:** Reuse existing MasonryGrid component + - **Addition:** AI badges on NoteCard ("Title Suggested", "Semantic Match") + +2. **Contextual Triggers (GitHub Copilot)** + - **Why:** Non-intrusive, natural discovery + - **Usage:** Toast after 50+ words without title + - **Design:** Same pattern as Copilot - appear when relevant, not constant + +3. **Speed Perception (Linear)** + - **Why:** Fast = smart + - **Usage:** < 2s title generation, < 300ms semantic search + - **Implementation:** Optimistic UI, skeleton screens, background processing + +**ADAPT (Modify for Memento):** + +1. **Graph View (Obsidian) → Memory Echo Card** + - **Obsidian:** Manual graph view, see all connections + - **Memento:** Proactive notification, 1 connection at a time + - **Adaptation:** Subtle vs. visual, proactive vs. manual + +2. **Slash Commands (Notion) → Contextual Menu** + - **Notion:** `/` to access all features + - **Memento:** "..." menu on NoteCard for reformulation + - **Adaptation:** No commands to memorize, discovery via UI + +3. **AI Sidebar (ChatGPT) → Toast + Settings** + - **ChatGPT:** Permanent sidebar with AI chat + - **Memento:** Temporary toasts + granular Settings page + - **Adaptation:** Non-intrusive vs. always-visible, contextual vs. general + +**AVOID (Anti-patterns to NOT reproduce):** + +1. ❌ **Frequent AI notifications** (Slack/Notion AI) → Max 1 insight/day +2. ❌ **Permanent AI toolbar** (Too many apps) → Temporary toasts +3. ❌ **Black box** (ChatGPT) → Full transparency +4. ❌ **Slow spinners** (Legacy) → Optimistic UI +5. ❌ **Hidden settings** (Obscure SaaS) → Visible `/settings/ai` page + +**Summary Strategy:** +- **Learn** from Google Keep's simplicity + Copilot's proactivity +- **Innovate** with Memory Echo (no one has proactive connections) +- **Avoid** Slack/Notion AI mistakes (too intrusive) +- **Prioritize** speed (Linear) for perceived intelligence + +--- + +## Design System Foundation + +### Design System Choice + +**Existing Design System:** Radix UI + Tailwind CSS 4 + +Memento already has a proven design system in place. No need to change - we'll extend it for Phase 1 AI features. + +**Current Stack:** +- **UI Primitives:** Radix UI (accessible, unstyled components) +- **Styling:** Tailwind CSS 4 (utility-first framework) +- **Icons:** Lucide React +- **Layout:** Muuri (masonry), @dnd-kit (drag & drop) + +**This is a "Themeable System" approach** - maximum flexibility with proven foundation. + +### Rationale for Selection + +**1. Development Speed** ⚡ +- **Timeline constraint:** 8-12 weeks for MVP +- **20+ existing components:** NoteCard, LabelSelector, MasonryGrid already built +- **Focus on AI logic:** Don't waste time on basic UI components +- **Result:** Ship Phase 1 faster, concentrate on innovation (Memory Echo) + +**2. Accessibility-First** ♿ +- **WCAG 2.1 AA compliance:** Radix UI provides this out-of-the-box +- **11 accessibility NFRs:** Keyboard nav, ARIA, focus management included +- **Screen reader support:** Critical for "Announce AI-generated content" (NFR-A11Y-002) +- **Result:** Meet legal requirements without custom ARIA work + +**3. Customization Flexibility** 🎨 +- **Tailwind utilities:** Rapid styling for new AI components +- **Radix primitives:** Unstyled = full control over appearance +- **Consistent + unique:** Match existing look while differentiating AI features +- **Result:** Coherent UX, AI features feel integrated (not bolted-on) + +**4. Long-Term Maintenance** 🔧 +- **Active communities:** Radix & Tailwind have excellent maintenance +- **Industry standards:** Not risking abandoned libraries +- **Future-proof:** Compatible with Next.js 16, React 19, TypeScript 5 +- **Result:** Safe technical choice for years to come + +**5. Performance** 🚀 +- **Tree-shakeable:** Import only used components (NFR-PERF-007: < 200KB bundle) +- **Tailwind purge:** Automatic CSS removal (only used styles in bundle) +- **RSC compatible:** Works with React Server Components (Next.js App Router) +- **Result:** Fast load times = perceived AI intelligence + +### Implementation Approach + +**Strategy: Extended Design System** + +**1. Reuse 100% of Existing Components** +- NoteCard, MasonryGrid, LabelSelector, Header, Sidebar - all stay +- **No redesign:** Maintain visual consistency for current users +- **AI enhancements:** Add badges, indicators, states to existing components + +**2. Create 7 New AI-Specific Components** + +| Component | Purpose | Radix Primitive | Timeline | +|-----------|---------|-----------------|----------| +| **AIToast** | Contextual notification for title suggestions | `Toast` | Week 2 | +| **TitleSuggestions** | Dropdown with 3 AI title options | `DropdownMenu` | Week 2 | +| **MemoryEchoCard** | Card displaying 2 connected notes | Custom + `Dialog` | Week 4 | +| **ReformulationModal** | Paragraph selection + reformulation UI | `Dialog` | Week 3 | +| **AISettingsPanel** | Granular ON/OFF switches for AI features | Form + `Switch` | Week 5 | +| **SemanticBadge** | "Exact Match \| Semantic Match" indicator | Custom | Week 3 | +| **ProviderIndicator** | "✅ Local Ollama \| ✅ OpenAI Cloud" status | Custom | Week 1 | + +**3. Define AI Design Tokens** + +```css +/* AI-specific colors (Tailwind config extension) */ +--ai-primary: #8B5CF6; /* Purple - AI intelligence */ +--ai-accent: #3B82F6; /* Blue - semantic matches */ +--ai-success: #10B981; /* Green - positive feedback */ +--ai-warning: #F59E0B; /* Yellow - processing states */ +--ai-error: #EF4444; /* Red - errors, negative feedback */ + +/* AI-specific spacing */ +--ai-toast-margin: 1rem; /* Toast positioning */ +--ai-card-gap: 1.5rem; /* Gap between Memory Echo notes */ + +/* AI-specific animations */ +@keyframes ai-fade-in { + from { opacity: 0; transform: translateY(8px); } + to { opacity: 1; transform: translateY(0); } +} + +@keyframes ai-scale-up { + from { opacity: 0; transform: scale(0.98); } + to { opacity: 1; transform: scale(1); } +} +``` + +**4. Component Hierarchy (Extended)** + +``` +Existing Components (Keep) +├── Layout +│ ├── Header → HeaderWrapper → UserNav +│ │ └── ADD: ProviderIndicator (new) +│ ├── Sidebar +│ └── MasonryGrid +│ └── NoteCard (enhanced) +│ ├── ADD: SemanticBadge (new) +│ └── ADD: ReformulationMenu (new) +│ +New AI Components +├── AIToast (contextual notification) +├── TitleSuggestions (dropdown) +├── MemoryEchoCard (proactive insights) +├── ReformulationModal (paragraph AI) +└── AISettingsPanel (granular control) +``` + +### Customization Strategy + +**Brand Differentiation (Phase 1 - Minimal):** + +**1. Color Strategy** +- **Purple (#8B5CF6)** = Primary AI color (intelligence, differentiation) +- **Keep existing note colors:** Red, orange, yellow, green, teal, blue, purple, pink, gray +- **AI badge color:** Blue gradient (#3B82F6 → #60A5FA) for semantic matches +- **Rationale:** Purple = "AI is special but not alienating" + +**2. Typography (No Change)** +- **System font stack** (Tailwind default) +- **Reason:** Fast loading, familiar to users, zero-config +- **AI text:** Same fonts, semantic meaning via color + icon + +**3. Spacing (No Change)** +- **Tailwind spacing scale:** 4px base unit (4, 8, 12, 16, 24, 32...) +- **AI components:** Use existing scale for consistency +- **Rationale:** Maintain visual rhythm, not "another design language" + +**4. Component Shape (Consistent)** +- **Border radius:** Match NoteCard (likely `rounded-md`) +- **Shadows:** Match existing cards (elevation system) +- **AI components:** Same shape language = feeling of integration + +**5. Animation Standards** + +| Animation | Duration | Easing | Use Case | +|-----------|----------|--------|----------| +| **ai-fade-in** | 200ms | ease-out | Toast appearance | +| **ai-slide-up** | 250ms | ease-out | Suggestions dropdown | +| **ai-scale-up** | 150ms | ease-out | Memory Echo card | +| **ai-pulse** | 2s | ease-in-out | Provider connection status | + +**Rationale:** Subtle, fast animations = "AI is snappy and responsive" + +--- + +## Core User Experience with Notebooks + +### Defining Experience: Memory Echo in Notebook Context + +**The Core Interaction that Makes Memento Special:** + +> **"Memento reveals connections between my notes (within notebooks) that I hadn't seen"** + +Every successful product has a defining experience - the interaction that, if nailed, makes everything else follow. + +**Famous examples:** +- Tinder: "Swipe to match with people" +- Snapchat: "Share photos that disappear" +- Instagram: "Share perfect moments with filters" +- Spotify: "Discover and play any song instantly" + +**For Memento Phase 1, the defining experience is:** + +**Memory Echo:** "I noticed something..." - The AI proactively reveals a connection between notes within the user's current notebook context that they hadn't discovered. + +This is THE moment users will describe to their friends: +> *"You have to see this! Memento showed me that I had two related notes from January and this week that I hadn't connected!"* + +This is the "Aha!" moment that creates the emotion: "Wow, that's clever!" (from Emotional Response analysis). + +**Critical Innovation:** Memory Echo operates within **Notebook context** by default, making connections more relevant and scoped to the user's current work area. + +### User Mental Model + +**How users currently think about note-taking:** + +**Current Mental Model (Before Memento Phase 1):** +``` +My notes = Disconnected silos +├── I capture ideas +├── I try to remember them later +└── I lose connections between ideas (human = limited) +``` + +**Problems:** +- "I noted that somewhere, but I don't remember where" +- "I know I thought about that, but I can't find the note" +- "My ideas are connected, but my notes don't show it" + +**Enhanced Mental Model (With Memento Notebooks + Memory Echo):** +``` +My Notes = Organized Network +├── I organize into Notebooks (Work, Personal, Projects...) +├── Memento organizes within each Notebook in background +└── Memento reveals invisible connections (Notebook-scoped) +``` + +**Transformation:** +- **Before:** "I search my notes" (active, effort) +- **After:** "Memento finds what I forgot" (proactive, surprise) +- **Notebooks provide:** Contextual scope = more relevant connections + +**Notebook Mental Model:** +- **Physical analogy:** Real notebooks (Work, Personal, Ideas...) +- **Clear separation:** Work vs. Personal = mental boundaries +- **Scalability:** 1000+ notes distributed across notebooks = manageable +- **Natural organization:** Like having different physical notebooks for different purposes + +**User Expectations:** +1. **Fast capture** = Instant (Google Keep style) +2. **Organized structure** = Notebooks provide organization +3. **Proactive discovery** = Memory Echo within current notebook context +4. **Control** = Can switch notebooks, view global connections optionally + +**Potential Confusions:** +- "Does Memento read all my notes?" → Yes, but locally (privacy-first, Ollama) +- "How does it know they're connected?" → Explanation: Semantic embeddings +- "Is it always accurate?" → No, hence 👎 feedback learning system +- "Are connections across notebooks or within?" → Within by default, optional global view + +### Success Criteria + +**When does the defining experience "just work"?** + +**1. "It Just Works" - Magic Happens** +- **Trigger:** Background analysis finds cosine similarity > 0.75 within current notebook +- **Interaction:** "I noticed something..." notification appears +- **Success:** User clicks "View Connection" (> 40% CTR target from PRD) +- **Feedback:** Two connected notes clearly show semantic link +- **User thought:** "Oh wow! I hadn't seen that connection!" +- **Notebook context:** Connection within current notebook = more relevant + +**2. Perceived Intelligence - AI Feels Smart** +- **Trigger:** Memory Echo notification appears +- **Success:** < 100ms UI freeze (feels instantaneous) +- **Feedback:** No slow loading spinner (perceived as "dumb") +- **User thought:** "Wow, that's instant, Memento is smart!" +- **Notebook enhancement:** Scoped context = appears more intelligent + +**3. Relevant, Not Spammy - Right Moment, Right Place** +- **Trigger:** Max 1 insight/day (configurable 0-3) +- **Success:** User thinks "That's useful" not "Another notification..." +- **Feedback:** User doesn't disable Memory Echo feature +- **User thought:** "Interesting, thanks Memento!" +- **Notebook relevance:** "This helps with my current work in this notebook" + +**4. Trust Building - Confidence Establishes** +- **Trigger:** First Memory Echo connection +- **Success:** Connection IS relevant (not hallucination) +- **Feedback:** 👍👎 buttons available and respected +- **User thought:** "I'm in control, no problem if it's wrong" +- **Notebook control:** User can switch notebooks to find different connections + +**5. Notebook Organization - Structure Feels Natural** +- **Trigger:** User creates/accesses notes in specific notebooks +- **Success:** Notes automatically organized by notebook context +- **Feedback:** Sidebar shows notebook hierarchy clearly +- **User thought:** "Finally, my work is organized!" +- **Inbox concept:** Unassigned notes go to "Inbox" notebook (default) + +**Success Indicators:** +- ✅ > 40% CTR on "View Connection" (PRD requirement) +- ✅ > 3:1 👎 ratio (quality threshold) +- ✅ < 1% users disable Memory Echo (not frustrating) +- ✅ User quote: "Memento surprised me by finding X in my Work notes!" +- ✅ Notebook adoption: > 80% users create custom notebooks beyond "Inbox" + +### Novel UX Patterns + +**Pattern Analysis:** + +**Memory Echo = Novel Pattern in Note-Taking** + +**Current Market State:** +- **Google Keep:** No AI proactive features at all +- **Notion:** On-demand AI (slash commands), not proactive +- **Obsidian:** Manual graph view (no AI) +- **Roam Research:** Graph view, no proactive insights +- **Evernote:** Notebook organization exists, but no AI connections + +**Memento Innovation:** +- **FIRST** to combine: + - **Notebook organization** (familiar structure) + - **Semantic search** (embeddings) + - **Proactive notifications** (Memory Echo) + - **Feedback learning** (👎 system) + - **Privacy-first** (local processing option) + - **Notebook-scoped insights** (contextual relevance) + +**This is HYBRID innovation:** +- **Base:** Notebook organization (Evernote-like) → **Established** +- **Base:** Graph connections (Obsidian-like) → **Established** +- **Innovation:** AI proactive + feedback loop + notebook scope → **Novel** + +**User Education:** + +**Familiar Metaphors:** +- "Like an assistant thinking about your notes while you sleep" +- "Like Google Photos grouping photos, but for your ideas" +- "Like Spotify Discover Weekly, but for your notes within each notebook" + +**Progressive Onboarding:** +1. User captures notes in "Inbox" (familiar, single notebook) +2. Title suggestions toast (discovery of AI) +3. Create custom "Work" notebook (structure discovery) +4. Memory Echo appears in "Work" context (surprise "Aha!") +5. Granular settings (control discovery) + +**Notebook-Specific Education:** +- "Each notebook is like a separate world - Memento finds connections within it" +- "Switch notebooks to discover connections in different contexts" +- "Use 'Inbox' for quick capture, organize into notebooks later" + +### Experience Mechanics + +**Detailed breakdown of Memory Echo interaction within Notebook context:** + +#### 1. Initiation (Trigger) + +**Backend (Silent, Invisible):** +- **Timing:** Every hour (cron job) +- **Scope:** Analyze embeddings within **current notebook** +- **Process:** + 1. Fetch all note embeddings from **current notebook** + 2. Calculate cosine similarity matrix (notebook-scoped) + 3. Filter: similarity > 0.75 (threshold) + 4. Sort by score descending + 5. Fetch top 1 connection +- **Duration:** < 100ms UI freeze (background job) +- **Notebook isolation:** Each notebook has independent similarity analysis + +**Frontend (User-Visible):** +- **Trigger:** Notification appears (no "Run Memory Echo" button) +- **Timing:** Max 1 time/day (configurable 0-3) +- **Condition:** At least 2 notes with embeddings in **current notebook** +- **Notebook indicator:** Notification shows which notebook: "💡 I noticed something in your **Work** notes..." + +**Visual:** +``` +┌─────────────────────────────────────┐ +│ 💡 I noticed something... │ +│ │ +│ In your "Work" notes: │ +│ │ +│ You noted "Node.js performance" │ +│ and "Next.js optimization". These │ +│ notes are connected. │ +│ │ +│ [View Connection] [Dismiss] [×] │ +└─────────────────────────────────────┘ +``` + +#### 2. Interaction (User Actions) + +**Option A: "View Connection" (Success Path)** +1. **Click** → MemoryEchoCard modal/panel opens +2. **Display:** 2 notes side-by-side (desktop) or stacked (mobile) +3. **Visualization:** + - Note A: "Node.js performance tips" + - Note B: "Next.js optimization" + - Highlight: Connected words/phrases emphasized + - Badge: "93% match" (cosine similarity) + - **Notebook context:** "From: Work notebook" +4. **Available actions:** + - "Link these notes" (create shared label?) + - 👍 "This is helpful" (positive feedback) + - 👎 "Not relevant" (negative feedback) + - [×] Close + +**Option B: "Dismiss" (Neutral Path)** +1. **Click** → Notification disappears +2. **Feedback:** "Ok, maybe next time" +3. **No data stored** (no learning) + +**Option C: [×] Close (Same as Dismiss)** +1. **Click** → Notification disappears +2. **No feedback** + +#### 3. Feedback (Learning Loop) + +**Positive Feedback (👍):** +- **Action:** User clicks 👎 after "View Connection" +- **System response:** + - Toast: "Thanks! We'll show more insights like this in **Work** notes." + - Data: Store +1 score for this connection type within notebook context + - Learning: Increase cosine threshold for this connection type in this notebook +- **Future:** More of this connection type in this notebook + +**Negative Feedback (👎):** +- **Action:** User clicks 👎 after "View Connection" +- **System response:** + - Modal: "Why wasn't this relevant?" (optional) + - "Wrong connection" + - "Not useful right now" + - "Too many notifications" + - "Wrong notebook context" + - Toast: "Thanks for teaching us! We'll improve." + - Data: Store -1 score for this connection type in this notebook + - Learning: Decrease cosine threshold for this connection type in this notebook +- **Future:** Less of this connection type in this notebook + +**No Feedback (Dismiss/Close):** +- **No learning** (neutral) +- **Counts as "non-action"** in analytics + +#### 4. Completion & Notebook Context + +**Success Path Completed:** +- **Outcome:** User discovered invisible connection within notebook +- **Next steps:** + - Can link notes (action: create shared label) + - Can continue work in current notebook + - **Option:** "See connections in other notebooks" (toggle global) + - Next Memory Echo: Tomorrow (max 1/day) + +**Switching Notebooks:** +- **User action:** Click different notebook in sidebar +- **System response:** + - Switch view to that notebook's masonry grid + - Update Memory Echo context to new notebook + - Background analysis now scopes to new notebook + - **Notification:** "💡 Switched to **Personal** notebook" + +**Global Connections (Optional Feature):** +- **User action:** Toggle "Show connections across all notebooks" +- **System response:** + - Memory Echo scope expands beyond current notebook + - Notification: "💡 I noticed something **across your notes**..." + - Badge: "Global connection" vs. "Notebook connection" +- **Use case:** User wants serendipitous cross-notebook discoveries + +**Dismiss Path Completed:** +- **Outcome:** Notification closed, no learning +- **Next steps:** + - Continue normal capture in current notebook + - Next Memory Echo: Tomorrow (frequency unchanged) + +**Settings Path (Control):** +- **User navigates:** `/settings/ai` +- **Actions:** + - Change "Memory Echo frequency" (1 → 0 to disable) + - "Notebook scope" toggle: Current notebook vs. All notebooks + - Per-notebook frequency: Work = daily, Personal = weekly +- **Respect:** Immediate, no "are you sure?" + +--- + +## Visual Design Foundation + +### Color System + +#### Philosophy: Intelligence + Clarté + +The color palette balances **AI modernity** (violet/bleu) with **content-first design** (blanc pur), ensuring user notes remain the focal point while AI interactions are clearly visible and trustworthy. + +#### Core Palette + +```css +/* Brand Colors */ +--primary: #8B5CF6; /* Violet - IA Intelligence */ +--primary-light: #A78BFA; +--primary-dark: #7C3AED; + +--secondary: #3B82F6; /* Bleu - Confiance */ +--secondary-light: #60A5FA; +--secondary-dark: #2563EB; + +--accent: #10B981; /* Vert émeraude - Success, Positive Feedback */ +``` + +**Rationale:** +- **Violet (#8B5CF6)**: Evokes AI creativity and intelligence, modern and tech-forward +- **Bleu (#3B82F6)**: Builds trust for privacy-conscious users, stable and professional +- **Vert (#10B981)**: Positive reinforcement for AI feedback system (👍👎), encourages engagement + +#### Semantic Colors + +```css +/* Functional Colors */ +--success: #10B981; /* Green - Success, accepted suggestions */ +--warning: #F59E0B; /* Amber - Processing states, caution */ +--error: #EF4444; /* Red - Errors, rejected suggestions */ +--info: #3B82F6; /* Blue - Informational */ +``` + +#### AI-Specific Colors + +```css +/* AI Feature Colors */ +--ai-primary: #8B5CF6; /* Primary AI interactions */ +--ai-accent: #3B82F6; /* Semantic search matches */ +--ai-processing: #F59E0B; /* Background processing state */ +--ai-connection: #8B5CF6; /* Memory Echo link highlights */ +--ai-suggestion: #A78BFA; /* Suggested titles, reformulations */ +``` + +**Usage:** +- **Memory Echo cards**: Purple border (`--ai-connection`) + subtle purple background +- **Title suggestions**: Purple text (`--ai-suggestion`) for AI-generated options +- **Semantic search badges**: Blue (`--ai-accent`) for "Semantic Match" indicators +- **Processing states**: Amber spinner (`--ai-processing`) during embedding generation + +#### Neutral Colors + +```css +/* Background & Surface */ +--background: #FFFFFF; /* Pure white - content focus */ +--surface: #F9FAFB; /* Very light gray - subtle separation */ +--surface-elevated: #FFFFFF; /* Cards, modals (elevated on white) */ + +/* Text Colors */ +--text-primary: #111827; /* Nearly black - main content */ +--text-secondary: #6B7280; /* Medium gray - metadata, secondary */ +--text-muted: #9CA3AF; /* Light gray - timestamps, hints */ + +/* Borders & Dividers */ +--border: #E5E7EB; /* Light gray - subtle separation */ +--border-hover: #D1D5DB; /* Medium gray - interactive states */ +``` + +**Design Philosophy:** +- **Blanc pur background**: Ensures notes are the hero, not the interface +- **Subtle surfaces**: Light grays (#F9FAFB) provide visual hierarchy without distraction +- **High contrast text**: Meets WCAG AA standards (4.5:1 minimum contrast ratio) + +#### Accessibility Compliance + +✅ **WCAG 2.1 Level AA**: +- All text-to-background contrast ratios ≥ 4.5:1 +- Large text (18px+) contrast ≥ 3:1 +- Interactive elements (buttons, links) have visible focus states +- Color not used as the only visual means of conveying information + +✅ **Color Independence**: +- AI features use color + icon + text label (triple coding) +- Memory Echo: Purple + 💡 icon + "I noticed..." text +- Semantic badges: Blue + "Semantic Match" label + dashed underline + +--- + +### Typography System + +#### Philosophy: Performance + Lisibilité + +Using **system fonts** eliminates external font loading (zero DevOps, maximum performance) while ensuring native OS optimization and multilingual support (French accents, emojis). + +#### Font Family Stack + +```css +--font-sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', + 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue', + sans-serif; +``` + +**Rationale:** +- **Performance**: No external HTTP requests, instant rendering +- **Native feel**: Each OS shows its optimized font (San Francisco on Mac, Segoe UI on Windows) +- **Multilingual**: Native support for French accents, emojis, special characters +- **Accessibility**: System fonts are designed for screen readers and zoom + +#### Type Scale (Perfect Fourth - 1.333) + +```css +/* Font Sizes */ +--text-xs: 0.75rem; /* 12px - Captions, metadata */ +--text-sm: 0.875rem; /* 14px - Secondary text, labels, helper text */ +--text-base: 1rem; /* 16px - Body content (WCAG recommended minimum) */ +--text-lg: 1.125rem; /* 18px - Lead paragraphs, emphasized content */ +--text-xl: 1.25rem; /* 20px - Note titles in cards */ +--text-2xl: 1.5rem; /* 24px - Cahier (notebook) titles in sidebar */ +--text-3xl: 1.875rem; /* 30px - Page headings */ +--text-4xl: 2.25rem; /* 36px - Hero text, empty states */ +``` + +**Scale Choice**: Perfect Fourth (1.333 ratio) provides harmonious progression while maintaining distinct hierarchy levels. + +#### Line Heights + +```css +/* Line Spacing */ +--leading-tight: 1.25; /* Headings - compact, impactful */ +--leading-normal: 1.5; /* UI text, labels - standard readability */ +--leading-relaxed: 1.75; /* Body content - optimal for long-form */ +``` + +#### Font Weights + +```css +--font-normal: 400; /* Body text, standard content */ +--font-medium: 500; /* UI emphasis, button text */ +--font-semibold: 600; /* Headings, important labels */ +--font-bold: 700; /* Strong emphasis, CTAs */ +``` + +#### Typographic Usage Guidelines + +| Element | Size | Weight | Line Height | Use Case | +|---------|------|--------|-------------|----------| +| Page Headings | `text-3xl` (30px) | Semibold (600) | Tight (1.25) | Page titles, empty state headers | +| Cahier Titles | `text-2xl` (24px) | Semibold (600) | Normal (1.5) | Sidebar notebook names | +| Note Card Titles | `text-xl` (20px) | Semibold (600) | Normal (1.5) | Main note title in masonry grid | +| Lead Paragraphs | `text-lg` (18px) | Normal (400) | Relaxed (1.75) | Emphasized intro text | +| Body Content | `text-base` (16px) | Normal (400) | Relaxed (1.75) | Note content, long-form text | +| Secondary Text | `text-sm` (14px) | Normal (400) | Normal (1.5) | Metadata, timestamps, hints | +| Captions | `text-xs` (12px) | Medium (500) | Normal (1.5) | AI badges, helper text | + +#### Responsive Typography + +Typography scales with viewport width for optimal readability: + +```css +/* Mobile-first approach */ +@media (min-width: 768px) { + /* Tablet+: Increase base size slightly */ + :root { + --text-base: 1.125rem; /* 18px on larger screens */ + } +} +``` + +#### Accessibility Features + +✅ **Text Zoom Support**: +- Layout supports up to 200% text zoom without horizontal scrolling +- Flexible units (rem) ensure proportional scaling + +✅ **Readability**: +- Minimum body text: 16px (WCAG recommended) +- Line height: 1.75 for body content (prevents walls of text) +- Max line length: 65-75 characters for optimal reading speed + +✅ **Screen Reader Optimization**: +- Semantic HTML heading hierarchy (h1 → h2 → h3) +- System fonts render consistently across assistive technologies + +--- + +### Spacing & Layout Foundation + +#### Philosophy: Balanced Density + +Using an **8px grid system** provides industry-standard spacing that balances content visibility with breathing room, ensuring the interface feels neither cluttered nor wasteful. + +#### Spacing Scale (8px Base Unit) + +```css +/* 8px Grid Scale */ +--space-0: 0; /* No spacing */ +--space-1: 0.25rem; /* 4px - Micro spacing between related elements */ +--space-2: 0.5rem; /* 8px - Base unit, tight grouping */ +--space-3: 0.75rem; /* 12px - Compact separation */ +--space-4: 1rem; /* 16px - Comfortable spacing (most common) */ +--space-5: 1.25rem; /* 20px - Section separation */ +--space-6: 1.5rem; /* 24px - Major component gaps */ +--space-8: 2rem; /* 32px - Component grouping */ +--space-10: 2.5rem; /* 40px - Page margins */ +--space-12: 3rem; /* 48px - Large section separation */ +--space-16: 4rem; /* 64px - Hero sections, empty states */ +``` + +**Why 8px?** +- Industry standard (Bootstrap, Material Design, Tailwind) +- Highly divisible (16, 24, 32, 40, 48 are all multiples) +- Natural visual rhythm +- Tailwind CSS native support (spacing-2 = 8px) + +#### Layout Component Spacing + +**Masonry Grid (Notes within Cahiers):** +- Gap between cards: `--space-4` (16px) - comfortable separation +- Padding within cards: `--space-4` (16px) - content breathing room +- Card corner radius: `8px` (rounded-lg) - modern but not distracting + +**Sidebar (Cahiers Navigation):** +- Width: `256px` (w-64) on desktop, full width on mobile +- Padding vertical: `--space-4` (16px) +- Padding horizontal: `--space-3` (12px) +- Gap between cahier items: `--space-2` (8px) + +**Header (Top Bar):** +- Height: `64px` (h-16) +- Padding horizontal: `--space-4` (16px) +- Gap between search and user menu: `--space-4` (16px) + +**AI Toast/Notifications:** +- Padding: `--space-4` (16px) all around +- Margin from viewport edge: `--space-4` (16px) +- Gap between toasts: `--space-3` (12px) + +**Memory Echo Card:** +- Padding: `--space-6` (24px) +- Border: 2px solid `--ai-connection` (#8B5CF6) +- Corner radius: `12px` (rounded-xl) - distinctive from note cards + +#### Grid System: 12 Columns (Adaptive) + +**Why 12 Columns?** +- Highly flexible (divisible by 2, 3, 4, 6) +- Supports multiple layout patterns (2-col, 3-col, 4-col, 6-col) +- Industry standard (Bootstrap, Foundation, Tailwind) + +**Breakpoints:** + +```css +/* Tailwind Standard Breakpoints */ +--breakpoint-sm: 640px; /* Mobile large */ +--breakpoint-md: 768px; /* Tablet portrait */ +--breakpoint-lg: 1024px; /* Desktop, laptop */ +--breakpoint-xl: 1280px; /* Desktop large */ +``` + +**Responsive Masonry Layout:** + +| Screen Size | Columns | Column Width | Notes Visible | +|-------------|---------|--------------|---------------| +| Mobile (< 768px) | 1 | 100% | Single column stack | +| Tablet (768-1024px) | 2 | ~48% each | 2-column grid | +| Desktop (1024-1280px) | 3 | ~32% each | 3-column grid | +| Desktop XL (> 1280px) | 4 | ~24% each | 4-column grid | + +**Notebook Sidebar Layout:** +- **Desktop (> 1024px)**: Fixed 256px sidebar on left, main content fills remaining width +- **Tablet/Mobile (< 1024px)**: Collapsible sidebar (hamburger menu) to maximize content space + +#### Layout Principles + +1. **Content-First Hierarchy**: + - Pure white background (`#FFFFFF`) ensures notes are focal point + - Subtle surface colors (`#F9FAFB`) separate sections without distraction + +2. **Visual Rhythm**: + - Consistent 16px padding inside cards and components + - 16px gaps between masonry items for consistent whitespace + +3. **Responsive Flexibility**: + - Masonry grid adapts column count based on viewport width + - Sidebar collapses on mobile to preserve screen real estate + +4. **AI Feature Prominence**: + - Memory Echo cards use 24px padding (larger than note cards' 16px) for emphasis + - AI toasts float 16px from edges to ensure visibility without blocking content + +5. **Accessibility Spacing**: + - Minimum touch target size: 44×44px (WCAG 2.5.5) + - Focus indicators have 2px outline with sufficient contrast + +--- + +### Accessibility Considerations + +#### Visual Accessibility + +✅ **Color Contrast** (WCAG 2.1 Level AA): +- All normal text: Minimum 4.5:1 contrast ratio +- Large text (18px+): Minimum 3:1 contrast ratio +- Interactive elements: Minimum 3:1 contrast ratio + +✅ **Text Scaling**: +- Layout supports 200% text zoom without horizontal scrolling +- Rem-based units ensure proportional scaling +- No fixed-width containers that break on zoom + +✅ **Focus Indicators**: +- All interactive elements have visible focus states +- 2px solid outline in primary color (`#8B5CF6`) +- Focus outline offset: 2px from element + +#### Color Independence + +✅ **Triple Coding for AI Features**: +- **Color**: Purple/blue for AI interactions +- **Icon**: 💡 for Memory Echo, 🔍 for search, ✨ for suggestions +- **Text**: Clear labels ("I noticed something...", "Semantic Match") + +✅ **Example - Memory Echo**: +- Color: Purple border + purple tint background +- Icon: 💡 lightbulb icon +- Text: "I noticed something..." headline + explanation + +#### Screen Reader Support + +✅ **Semantic HTML**: +- Proper heading hierarchy (h1 → h2 → h3) +- ARIA labels for custom components (Memory Echo cards, AI toasts) +- Live regions for dynamic content (AI notifications) + +✅ **Example - Memory Echo Card**: +```html +
+
+ +

I noticed something...

+
+ +
+``` + +#### Keyboard Navigation + +✅ **Full Keyboard Support**: +- Tab: Navigate through interactive elements +- Enter/Space: Activate buttons, links +- Escape: Close modals, dismiss toasts +- Arrow keys: Navigate within lists (cahiers, tags) + +✅ **Visible Focus**: +- 2px purple outline on focused elements +- High contrast (4.5:1 minimum) against backgrounds +- No outline removal on focus (`outline-none` only for mouse users via `:focus-visible`) + +#### Motion Sensitivity + +✅ **Respects `prefers-reduced-motion`**: +- Animations disabled for users who prefer reduced motion +- Transitions: `0.2s ease-out` (gentle, not jarring) +- Memory Echo appearance: Fade-in (no slide/bounce for motion-sensitive users) + +--- + +### Visual Foundation Strategy Summary + +**Color System:** +- Intelligence-focused palette (violet/bleu) with pure white background +- AI features clearly distinguished with semantic colors +- WCAG AA compliant contrast ratios + +**Typography:** +- System fonts for maximum performance and native feel +- Perfect Fourth scale (1.333) for harmonious hierarchy +- 16px base with 1.75 line height for optimal readability +- Supports French accents, emojis, and special characters + +**Spacing & Layout:** +- 8px grid system for consistent visual rhythm +- 12-column adaptive layout for responsive masonry grid +- 16px component padding/gaps for balanced density +- Cahiers sidebar: 256px desktop, collapsible on mobile + +**Accessibility:** +- Color independence (triple coding for AI features) +- 200% text zoom support +- Full keyboard navigation +- Screen reader optimization with semantic HTML + ARIA + +This foundation ensures **consistency across all design decisions** while maintaining the "Zéro Prise de Tête" philosophy - the design system is invisible, letting users focus on their notes and AI-powered insights. + +--- + +## Design Direction Decision + +### Design Directions Explored + +Three distinct design directions were evaluated for Memento Phase 1 MVP AI: + +**Direction A: "Invisible IA"** (Chosen) +- Philosophy: AI is present but never intrusive - appears when needed, then recedes +- Layout: Full-screen masonry grid with minimal sidebar (256px, collapsible) +- AI Presentation: Contextual elements (toasts, hover states, dropdowns) only +- Visual Density: High (maximize note visibility) +- Color Dominance: Pure white with violet/blue accents for AI only + +**Direction B: "IA Partenaire"** (Evaluated) +- Philosophy: AI as visible copilot, always present to assist +- Layout: Masonry grid + sidebar + permanent AI Panel (320px right) +- AI Presentation: Always-visible suggestions, connections, insights +- Visual Density: Medium (balance content and AI context) +- Color Dominance: White with AI-colored zones (light purple backgrounds) + +**Direction C: "Hydra Contextuelle"** (Evaluated) +- Philosophy: Interface adapts dynamically to user intent +- Layout: Adaptive modes (Capture, Discovery, Focus) +- AI Presentation: Mode-specific interfaces with animated transitions +- Visual Density: Variable per mode +- Color Dominance: Adaptive white → blue → purple based on mode + +### Chosen Direction + +**Direction A: "Invisible IA" with Direction B Enhancement** + +The chosen direction combines the **content-first minimalism** of Direction A with the **AI visibility** element from Direction B: + +**Core Principles:** +1. **Content is King**: Pure white background, masonry grid fills viewport +2. **AI Contextual**: AI features appear only at relevant moments +3. **Non-Intrusive Discovery**: Memory Echo creates "Aha!" without permanent UI +4. **Progressive Enhancement**: Users discover AI features naturally through use + +**Key Design Elements:** + +**Layout Structure:** +``` +┌─────────────────────────────────────────────────┐ +│ Header (64px) │ +│ [Logo] [Search] [✨ AI: On ▼] [User] │ +└─────────────────────────────────────────────────┘ +┌──────────┬──────────────────────────────────────┐ +│ Cahiers │ Masonry Grid (Notes) │ +│ Sidebar │ │ +│ (256px) │ [Note Card] [Note Card] [Note Card]│ +│ │ [Note Card] [Note Card] │ +│ Inbox │ │ +│ Work │ │ +│ Personal │ │ +│ + New │ │ +└──────────┴──────────────────────────────────────┘ +``` + +**AI Feature Integration:** + +1. **Memory Echo** ⭐ (Defining "Aha!" Experience) + - **Presentation**: Floating toast notification (bottom-right) + - **Appearance**: Fade-in with subtle purple border + - **Content**: "💡 I noticed something in your **Work** notes..." + - **Interaction**: Dismissible card with 👍👎 feedback + - **Persistence**: Auto-dismiss after 30s, or manual close + - **No permanent space**: Appears, delivers value, recedes + +2. **Title Suggestions** (Feature 1) + - **Trigger**: On note title focus/blur after content entry + - **Presentation**: Dropdown menu below title field + - **Content**: 3 AI-generated title options with ✨ indicator + - **Interaction**: Click to select, ESC to dismiss + - **Visual**: Purple text for AI suggestions, hover state with bg-purple-50 + +3. **Semantic Search** (Feature 2) + - **Presentation**: Unified search bar (no visible keyword/semantic toggle) + - **Result Indication**: Blue badge "Semantic Match" next to relevant results + - **Visual**: Dashed blue underline for semantic match terms + - **No separation**: Users don't distinguish keyword vs semantic - "it just works" + +4. **Paragraph Reformulation** (Feature 3) + - **Trigger**: Manual "✨ Reformulate" button appears on paragraph hover + - **Presentation**: Modal dialog with comparison (original | AI suggestion) + - **Interaction**: Accept/Reject/Retry options + - **Visual**: Purple border for modal, green checkmark for accepted text + +5. **AI Status Badge** (Direction B Enhancement) + - **Location**: Header, right side (before user menu) + - **Content**: "✨ AI: On" with dropdown access to settings + - **Purpose**: Permanent AI visibility without occupying UI space + - **Dropdown**: Quick access to AI features status, settings, provider info + +**Color Strategy (Direction A):** +- **Background**: Pure white (#FFFFFF) - content focus +- **Cards**: White with subtle gray border (#E5E7EB) + shadow-sm +- **AI Elements**: Violet (#8B5CF6) and Blue (#3B82F6) ONLY for AI interactions +- **No permanent AI zones**: No dedicated AI panel backgrounds or colored sections + +**Spacing Strategy:** +- **Masonry Gap**: 16px (space-4) - comfortable breathing room +- **Card Padding**: 16px (space-4) - consistent with 8px grid +- **Sidebar Width**: 256px (w-64) - sufficient for cahier names +- **Header Height**: 64px (h-16) - compact but functional + +**Typography Strategy:** +- **Cahier Titles**: 24px semibold (text-2xl font-semibold) - clear navigation +- **Note Card Titles**: 20px semibold (text-xl font-semibold) - scannable +- **Body Content**: 16px normal (text-base font-normal) - optimal readability +- **AI Text**: System fonts, purple color for AI-generated content + +### Design Rationale + +**Why "Invisible IA" with AI Badge?** + +**1. Alignment with "Zéro Prise de Tête" Philosophy** +- Users focus on **capturing notes**, not managing AI features +- AI appears **contextually** (toasts, hover states) without cluttering the interface +- No permanent AI panel means **maximum space for content** +- Progressive discovery: Users encounter AI features **naturally** through use + +**2. Optimal for Cahiers Structure** +- Masonry grid maximizes **note visibility** within each notebook +- Sidebar Cahiers + full-screen grid = **clear mental model** +- Switching notebooks shows **different note collections** instantly +- Memory Echo scoped to current Cahier = **relevant, not overwhelming** connections + +**3. Creates Strong "Aha!" Emotional Response** +- Memory Echo toast appearing from "nowhere" = **surprise and delight** +- "I didn't search, it found me" = **proactive intelligence** +- No permanent AI UI means the AI feels **magical, not mechanical** +- Purple/blue accents make AI moments **visually distinctive** + +**4. MVP Simplicity** +- Fewer components to build (no permanent AI panel, no mode switching) +- Focus on **4 core features** without complex UI state management +- Easier to test and iterate on **individual AI interactions** +- Faster to implement with **existing Radix UI primitives** (Toast, Dropdown, Dialog) + +**5. Scalability** +- Can add AI Panel later if users request more visibility +- Badge AI provides **hook for future AI features** (chat, commands) +- Invisible IA foundation means **new features can be added** without redesign +- User behavior analytics will inform **which AI features need more visibility** + +**Why the AI Badge Element?** + +**From Direction B Evaluation:** +- Users need **assurance AI is working** (especially Ollama local users) +- Badge provides **quick access to AI settings** without hunting +- Dropdown menu enables **future AI feature discovery** (as features are added) +- Balances **invisibility with visibility** - AI is present but not intrusive + +**Badge Placement Strategy:** +- Header right = **standard location** for status indicators +- Before user menu = **associates AI with user identity** +- Purple sparkle emoji ✨ = **clear visual marker** of AI presence +- Dropdown reveals **AI feature status** (e.g., "Memory Echo: Daily", "Provider: Ollama") + +### Implementation Approach + +**Phase 1: Core Layout (Week 1-2)** + +1. **Sidebar (Cahiers Navigation)** + - Use existing Radix UI `NavigationMenu` or custom sidebar + - 256px width (w-64), collapsible on mobile (hamburger menu) + - Cahier items: Icon + Name + Note count badge + - Active state: Purple left border + purple text + - "Inbox" as default cahier (first item) + +2. **Masonry Grid (Note Display)** + - Use existing `MasonryGrid` component from component inventory + - Responsive: 1 col (mobile) → 2 col (tablet) → 3-4 col (desktop) + - Gap: 16px (space-4) + - Note cards: White bg, border gray-200, shadow-sm, hover:shadow-md + +3. **Header (Top Bar)** + - 64px height (h-16) + - Left: Logo + Cahier name (breadcrumb) + - Center: Search bar (unified keyword + semantic) + - Right: ✨ AI Badge (dropdown) + User menu + +**Phase 2: AI Feature Components (Week 2-4)** + +4. **Memory Echo Toast** + - Radix UI `Toast` primitive with custom styling + - Position: bottom-right, 16px from edges + - Animation: fade-in (0.2s ease-out), respects `prefers-reduced-motion` + - Purple border (2px solid #8B5CF6), white bg with purple-50 tint + - Content: 💡 icon + "I noticed something..." + connection details + - Actions: Link notes button, 👍👎 feedback, dismiss (X) + - Accessibility: `role="alert"`, `aria-live="polite"` + +5. **Title Suggestions Dropdown** + - Radix UI `DropdownMenu` triggered on title focus/blur + - Content: 3 title options with ✨ prefix + - Visual: Purple text (text-purple-600), hover:bg-purple-50 + - Interaction: Click to accept, ESC to close + - Trigger logic: Show after user types content, then focuses title + +6. **Semantic Search Badges** + - Component: Small badge next to search results + - Content: "Semantic Match" in blue (text-blue-600) + - Position: Below note title, above content preview + - Visual: Blue border, dashed underline for matched terms + - Logic: Show when cosine similarity > 0.75 + +7. **Reformulation Modal** + - Radix UI `Dialog` with comparison view + - Layout: Two-column (original | AI suggestion) + - Visual: Purple border (2px), gray-50 background for comparison + - Actions: Accept (green button), Reject (gray button), Retry (purple button) + - Trigger: "✨ Reformulate" button on paragraph hover + +8. **AI Badge Dropdown (Direction B Element)** + - Radix UI `DropdownMenu` in header + - Trigger: "✨ AI: On" button + - Content: + - Feature status (Memory Echo: Daily, Provider: Ollama) + - Quick settings links (Configure AI, Privacy) + - Provider indicator (Local 🏠 | Cloud ☁️) + - Visual: Purple text, hover:bg-purple-50 + +**Phase 3: Responsive Behavior (Week 4)** + +9. **Mobile Adaptations** + - Sidebar: Hamburger menu (collapse to off-canvas) + - Masonry: Single column, full-width cards + - Memory Echo: Full-width toast at bottom + - Search: Expand on focus (compact icon → full bar) + - AI Badge: Compact on mobile (✨ icon only, tap for menu) + +10. **Tablet Optimizations** + - Sidebar: 200px width or collapsible + - Masonry: 2 columns + - Memory Echo: Bottom-right toast (same as desktop) + - Touch targets: Minimum 44×44px (WCAG) + +**Phase 4: Polish & Micro-interactions (Week 5)** + +11. **Animations** + - Masonry: Fade-in cards (0.2s ease-out) + - Memory Echo: Slide-up fade-in (0.3s ease-out) + - Hover states: 0.15s transitions + - Respect `prefers-reduced-motion` for all animations + +12. **Accessibility** + - Focus indicators: 2px purple outline + - Keyboard navigation: Tab through all interactive elements + - Screen reader: ARIA labels for AI components + - Color contrast: 4.5:1 minimum (WCAG AA) + +13. **Loading States** + - AI processing: Amber spinner (#F59E0B) with "AI thinking..." text + - Semantic search: Skeleton cards while computing embeddings + - Provider status: Green check (Ollama running) or red X (offline) + +**Component Timeline Summary:** + +| Component | Radix Primitive | Week | Priority | +|-----------|-----------------|------|----------| +| Sidebar Cahiers | NavigationMenu | 1 | P0 | +| Masonry Grid | Custom (existing) | 1 | P0 | +| Header | Flex layout | 1 | P0 | +| AI Badge Dropdown | DropdownMenu | 1 | P0 | +| Memory Echo Toast | Toast | 2 | P0 (Defining) | +| Title Suggestions | DropdownMenu | 2 | P1 | +| Semantic Search Badge | Custom | 3 | P1 | +| Reformulation Modal | Dialog | 3 | P1 | +| Mobile Responsive | Media queries | 4 | P1 | + +**Design Tokens Implementation (Tailwind Config):** + +```javascript +// tailwind.config.js extension +module.exports = { + theme: { + extend: { + colors: { + ai: { + primary: '#8B5CF6', // Violet + accent: '#3B82F6', // Blue + success: '#10B981', // Green + warning: '#F59E0B', // Amber + light: '#F5F3FF', // Purple-50 + } + }, + spacing: { + '18': '4.5rem', // 72px - card gap large + } + } + } +} +``` + +**Success Criteria for Direction A:** + +✅ **Masonry grid fills ≥70% of viewport** (content-first metric) +✅ **AI features appear in ≤200ms** (responsive feel) +✅ **Memory Echo creates "Aha!" moment** (user testing) +✅ **Users discover ≥2 AI features organically** (no tutorial needed) +✅ **Cahier switching takes ≤100ms** (instant mental model) +✅ **Mobile single-column works without horizontal scroll** (responsive) +✅ **WCAG AA compliance** (accessibility) + +**What This Direction Avoids (from other directions):** + +❌ No permanent AI panel (Direction B) - maximizes content space +❌ No mode switching (Direction C) - reduces cognitive load +❌ No colored background zones - maintains clean white aesthetic +❌ No complex transitions - faster to implement, less to go wrong + +--- + +## User Journey Flows + +### Journey 1: Fast Capture avec Cahiers & Title Suggestions + +**Persona:** Alex - Creative Developer qui veut capturer vite + +**Parcours:** Capturer une idée dans un Cahier → Recevoir suggestions de titres → Accepter/refuser + +**Flow Diagram:** + +```mermaid +flowchart TD + Start([Alex ouvre Memento]) --> SelectCahier{Sélectionne Cahier} + SelectCahier -->|Inbox par défaut| ViewGrid[Voir grille masonry Inbox] + SelectCahier -->|Cahier existant| ViewGrid + SelectCahier -->|Nouveau Cahier| CreateCahier[Créer nouveau Cahier] + CreateCahier --> ViewGrid + + ViewGrid --> ClickNew[Click '+ New Note'] + ClickNew --> NoteEditor[Note Editor: Focus sur contenu] + NoteEditor --> TypeContent[Alex tape frénétiquement
50+ mots en 2min] + + TypeContent --> CheckTitle{Titre présent?} + CheckTitle -->|Oui| SaveNote[Sauvegarder note] + CheckTitle -->|Non| TriggerAI[AI Trigger: 50+ mots sans titre] + + TriggerAI --> ShowToast[🔔 Toast subtil:
💭 '3 idées de titres?'] + ShowToast --> UserDecision{Action Alex?} + + UserDecision -->|Ignore Continue| AutoDismiss[Auto-dismiss 30s] + UserDecision -->|Click 'Voir'| ShowDropdown[Dropdown avec 3 titres
✨ Titre 1
✨ Titre 2
✨ Titre 3] + UserDecision -->|Click 'Ne plus demander'| DismissPerm[Dismiss pour cette note] + + ShowDropdown --> SelectTitle{Alex choisit?} + SelectTitle -->|Click Titre 1| ApplyTitle1[Appliquer Titre 1] + SelectTitle -->|Click Titre 2| ApplyTitle2[Appliquer Titre 2] + SelectTitle -->|Click Titre 3| ApplyTitle3[Appliquer Titre 3] + SelectTitle -->|ESC/Click outside| DismissDropdown[Fermer dropdown] + + ApplyTitle1 --> SaveNote + ApplyTitle2 --> SaveNote + ApplyTitle3 --> SaveNote + DismissDropdown --> ManualTitle[Alex tape titre manuel] + DismissPerm --> ManualTitle + AutoDismiss --> ManualTitle + + ManualTitle --> SaveNote + SaveNote --> ShowInCard[Note apparaît dans masonry
avec titre appliqué] + ShowInCard --> EmbedAsync[Background: Générer embedding
pour semantic search] + EmbedAsync --> End([Fin: Note capturée]) + + style TriggerAI fill:#8B5CF6,color:#fff + style ShowToast fill:#F5F3FF + style ShowDropdown fill:#8B5CF6,color:#fff + style EmbedAsync fill:#3B82F6,color:#fff +``` + +**Optimizations "Zéro Prise de Tête":** +- ✅ **No interruption:** Toast appears without blocking typing +- ✅ **Default value:** Inbox = default Cahier for ultra-fast capture +- ✅ **Respect choice:** "Don't ask again" = immediate, no confirmation +- ✅ **Background processing:** Embedding generated without blocking UI + +**Moments of Delight:** +- 💜 **Positive surprise:** "Wow, the first one captures exactly the essence!" +- ⚡ **Performance:** Instant dropdown (< 200ms) + +--- + +### Journey 2: Semantic Search Discovery + +**Persona:** Alex - Cherche une note mais se souvient du sens, pas des mots + +**Parcours:** Rechercher avec intention naturelle → Voir résultats sémantiques → Découvrir la bonne note + +**Flow Diagram:** + +```mermaid +flowchart TD + Start([Alex veut retrouver
sa note React]) --> ClickSearch[Click barre de recherche
header center] + ClickSearch --> SearchExpand[Search bar s'agrandit
placeholder: 'Rechercher...'] + SearchExpand --> TypeQuery[Alex tape naturellement:
'comment optimiser les performances des hooks'] + + TypeQuery --> Debounce[Debounce 300ms] + Debounce --> SearchHybrid[Hybrid Search:
1. Keyword Search
2. Semantic Search] + + SearchHybrid --> KeywordResults[Keyword Search:
Résultats avec mots exacts] + SearchHybrid --> SemanticResults[Semantic Search:
Vector embeddings] + + KeywordResults --> CombineResults[Combiner & Ranker] + SemanticResults --> SimilarityThreshold{Cosine Similarity
> 0.75?} + + SimilarityThreshold -->|Oui| AddSemantic[Ajouter badge 'Semantic Match'
Score: 0.82] + SimilarityThreshold -->|Non| KeywordOnly[Résultats keyword uniquement] + + AddSemantic --> CombineResults + KeywordOnly --> CombineResults + + CombineResults --> ShowResults[Afficher 10 résultats
masonry style] + ShowResults --> ResultBadges[Badges sur résultats:
🎯 Correspondance exacte
🎯 Correspondance sémantique] + + ResultBadges --> AlexScans[Alex scanne les résultats] + AlexScans --> TopResult[1er résultat:
Titre: 'React State Management'
Badge: 🎯 Correspondance sémantique
Score: 0.82] + + TopResult --> AlexRealize{Alex réalise} + AlexRealize -->|Wow!| NoteNoKeywords[Note ne contient PAS
'hook' ou 'performance'] + AlexRealize -->|Click| OpenNote[Ouvrir la note] + + NoteNoKeywords --> ConceptMatch[IA a compris le CONCEPT,
pas juste les mots-clés] + ConceptMatch --> AhaMoment[Alex: 'C'est exactement
ce que je cherchais!'] + + OpenNote --> NoteFull[Alex voit note complète:
Content parle de useMemo
pour optimiser les performances] + NoteFull --> Success([Succès: Note retrouvée]) + + AhaMoment --> Success + + style SearchHybrid fill:#3B82F6,color:#fff + style SemanticResults fill:#8B5CF6,color:#fff + style AddSemantic fill:#3B82F6,color:#fff + style AhaMoment fill:#10B981,color:#fff +``` + +**Optimizations "Zéro Prise de Tête":** +- ✅ **Unified search:** No visible keyword/semantic toggle - "it just works" +- ✅ **Explicit badges:** User understands WHY this result appears +- ✅ **Confidence score:** Cosine similarity > 0.75 = false positive filtering + +**Moments of Delight:** +- 🎯 **Intention understood:** "It understood what I meant, not what I typed!" +- ⚡ **Instant:** Results < 500ms + +--- + +### Journey 3: Memory Echo "Aha!" Moment + +**Persona:** Alex/Max - Découverte proactive de connexions invisibles + +**Parcours:** Recevoir notification inattendue → Voir connexion → Feedback 👍👎 + +**Flow Diagram:** + +```mermaid +flowchart TD + Start([Alex utilise Memento
normalement]) --> BackgroundProcess[Background Daily:
Analyser embeddings
du Cahier actuel] + + BackgroundProcess --> FindSimilar{Cosine Similarity
> 0.75 entre notes?} + FindSimilar -->|Non| NoInsight[Pas d'insight aujourd'hui] + FindSimilar -->|Oui| TimeFilter{Notes de
périodes différentes?} + + TimeFilter -->|Non| NoInsight + TimeFilter -->|Oui| CheckFrequency{Frequency setting
OK? (max 1/jour)} + + CheckFrequency -->|Non| NoInsight + CheckFrequency -->|Oui| CheckLastShown{Déjà montré
cette connexion?} + + CheckLastShown -->|Oui| NoInsight + CheckLastShown -->|Non| PrepareEcho[Préparer Memory Echo] + + PrepareEcho --> GetNoteA[Récupérer Note A:
'Node.js performance tips'] + PrepareEcho --> GetNoteB[Récupérer Note B:
'Next.js optimization'] + PrepareEcho --> Connection[Connexion identifiée:
Server-side rendering optimization] + + GetNoteA --> ShowToast + GetNoteB --> ShowToast + Connection --> ShowToast + + ShowToast[💡 Toast Notification:
'J'ai remarqué quelque chose
dans tes notes Work...'] + ShowToast --> AlexReaction{Réaction d'Alex?} + + AlexReaction -->|Ignore/Dismiss| AutoDismiss[Auto-dismiss 30s] + AlexReaction -->|Click 'Voir la connexion'| ShowModal[Modal Memory Echo Card] + + ShowModal[Modal: 2 notes côte à côte
Note A | Note B
'Toutes deux traitent de
server-side rendering optimization'] + ShowModal --> AlexReads[Alex lit les deux notes] + AlexReads --> AlexRealizes{Alex réalise la connexion} + + AlexRealizes -->|Wow!| ClickLink[Click 'Lier les notes'] + AlexRealizes -->|Faux| ClickReject[Click 👎 'Faux'] + + ClickLink --> ApplyTag[Ajouter tag commun
'SSR optimization'] + ApplyTag --> ShowSuccess[✅ Notes liées!] + ShowSuccess --> FeedbackPrompt[Prompt feedback:
👍 'Clever!' | 👎 'Faux'] + + ClickReject --> FeedbackModal[Modal:
'Pourquoi pas pertinent?'] + FeedbackModal --> UserExplanation[Alex explique:
LearnSystem[Système apprend:
Réduire poids similarité] + + FeedbackPrompt --> FeedbackChoice{Alex choisit?} + FeedbackChoice -->|👍| LearnGood[Apprendre:
Augmenter poids ce type connexion] + FeedbackChoice -->|👎| LearnBad[Apprendre:
Réduire poids] + FeedbackChoice -->|Skip| NoLearn + + LearnGood --> End([Fin: Insight mémorisé]) + LearnBad --> End + LearnSystem --> End + NoLearn --> End + AutoDismiss --> End + NoInsight --> End([Fin: Pas d'insight]) + + style BackgroundProcess fill:#3B82F6,color:#fff + style ShowToast fill:#8B5CF6,color:#fff + style ShowModal fill:#F5F3FF + style ClickLink fill:#10B981,color:#fff + style LearnGood fill:#10B981,color:#fff + style LearnBad fill:#EF4444,color:#fff +``` + +**Optimizations "Zéro Prise de Tête":** +- ✅ **Non-intrusive:** Max 1 insight/day, no overwhelm +- ✅ **Cahier scope:** Analysis only in current Cahier (relevant connections) +- ✅ **Immediate feedback:** 👍👎 trains the system, no confirmation +- ✅ **Global toggle:** Option for cross-Cahier connections + +**"Aha!" Moment:** +- 💡 **Surprise & Discovery:** "I never made the connection!" +- 🎯 **Serendipity:** "I didn't search, it found me!" + +--- + +### Journey 4: AI Error Recovery & Control + +**Persona:** Sophie - L'IA se trompe, elle ajuste les settings + +**Parcours:** Recevoir mauvaise suggestion → Feedback négatif → Ajuster settings → Retrouver la confiance + +**Flow Diagram:** + +```mermaid +flowchart TD + Start([Sophie crée une note]) --> WriteContent[Sophie écrit 70 mots
sur stratégie contenu] + WriteContent --> TriggerAI[AI Trigger:
Title Suggestions] + TriggerAI --> ShowSuggestions[Affiche 3 titres:
1. 'Stratégie B2B'
2. 'Marketing 2025'
3. 'Idées Articles'] + + ShowSuggestions --> SophieReaction{Sophie réagit} + SophieReaction -->|Déçue| ClickDismiss[Click 'Ne plus demander'] + SophieReaction -->|Choisit| SelectTitle[Sélectionne titre] + + ClickDismiss --> DismissNote[Toast: 'Pas de soucis,
je ne te redemanderai pas
pour cette note'] + DismissNote --> SophieManual[Sophie tape titre manuel] + SophieManual --> SaveNote[Sauvegarder] + + SaveNote --> NextDay[Jour suivant:] + NextDay --> MemoryEcho[Memory Echo:
Recettes smoothies + SEO] + MemoryEcho --> SophieConfused{Sophie confuse} + + SophieConfused -->|Pas de rapport!| ClickThumbsDown[Click 👎 'Faux'] + ClickThumbsDown --> FeedbackModal[Modal:
'Pourquoi pas pertinent?'] + + FeedbackModal --> SophieExplains[Sophie explique:
'Smoothies = personnel
SEO = pro'] + SophieExplains --> SystemLearn[Système apprend:
Contexte personnel vs pro] + SystemLearn --> DismissToast[Toast: 'Merci!
Je ferai mieux next time'] + + DismissToast --> SophieSettings[Sophie va dans Settings > AI] + SophieSettings --> SeeCurrent[Voit settings actuels:
☑ Title Suggestions: 50+ mots
☑ Memory Echo: Max 1/jour] + + SeeCurrent --> SophieAdjusts{Sophie ajuste} + SophieAdjusts -->|Title Suggestions| AdjustTitle[Ajuster:
'Me demander seulement
si > 100 mots'] + SophieAdjusts -->|Memory Echo| AdjustEcho[Ajuster:
'Seulement notes des
30 derniers jours'] + SophieAdjusts -->|Language| AdjustLang[Forcer langue = FR
pour éviter titres EN] + + AdjustTitle --> SaveSettings[Sauvegarder settings] + AdjustEcho --> SaveSettings + AdjustLang --> SaveSettings + + SaveSettings --> WeekLater[Une semaine plus tard:] + WeekLater --> NewNote[Sophie écrit 200 mots] + NewNote --> BetterSuggestions[Meilleures suggestions:
1. 'Content Marketing: Comment créer...'
2. 'Guide Marketing: De la stratégie...'
3. 'Stratégie: Les 5 piliers B2B'] + + BetterSuggestions --> SophieHappy[Sophie: 'Number 3 is perfect!'] + SophieHappy --> ApplyTitre3[Appliquer Titre 3] + ApplyTitre3 --> TrustRestored[Confiance restaurée!] + + TrustRestored --> MemoryEcho2[Memory Echo:
Deux notes marketing
30 derniers jours] + MemoryEcho2 --> SophieClickThumbsUp[Sophie clique 👍] + SophieClickThumbsUp --> LearnPositive[Système apprend:
Connexions pertinentes] + + LearnPositive --> Success([Fin: Sophie personnalisé
son expérience IA]) + + style ClickDismiss fill:#F59E0B + style ClickThumbsDown fill:#EF4444,color:#fff + style FeedbackModal fill:#FEE2E2 + style SophieSettings fill:#3B82F6,color:#fff + style SophieHappy fill:#10B981,color:#fff + style TrustRestored fill:#10B981,color:#fff + style Success fill:#10B981,color:#fff +``` + +**Optimizations "Zéro Prise de Tête":** +- ✅ **Granular control:** Each feature has independent settings +- ✅ **Immediate respect:** "Don't ask again" = no confirmation +- ✅ **Explanatory feedback:** Modal explains why system is asking +- ✅ **Learning curve:** System improves over time + +**Trust Recovery:** +- 🔄 **User control:** Sophie can customize EVERYTHING +- 📈 **Progression:** 55% acceptance → trust restored + +--- + +### Journey Patterns + +Based on the 4 flows above, here are the **reusable patterns**: + +#### Navigation Patterns + +**Pattern 1: Cahier-First Navigation** +- **Entry:** Always in a Cahier (Inbox default) +- **Switching:** Click Cahier in sidebar → instant switch (< 100ms) +- **Breadcrumb:** Header shows "Memento > Work > [Current note]" +- **Mental Model:** 1 Cahier = 1 work context + +**Pattern 2: Contextual AI Appearance** +- **Principle:** AI appears at the right moment, not before +- **Triggers:** Titles (50+ words), Memory Echo (daily), Reformulation (hover) +- **Dismiss:** One-click dismiss, immediate respect +- **Reappear:** Only if criteria met again + +#### Decision Patterns + +**Pattern 1: Progressive Disclosure** +- **Show:** Information revealed progressively +- **Dropdown:** 3 options (not more, reduced overwhelm) +- **Modal:** For complex decisions (Memory Echo) +- **Inline:** For simple feedback (👍👎) + +**Pattern 2: Default + Override** +- **Default:** Inbox Cahier for fast capture +- **Override:** User can choose different Cahier +- **AI Settings:** Team defaults + user overrides +- **Frequency:** Max limits, user can lower + +#### Feedback Patterns + +**Pattern 1: Triple Coding Feedback** +- **Visual:** Color (purple/blue for AI) +- **Icon:** 💡 for Memory Echo, ✨ for suggestions +- **Text:** Explicit labels ("Correspondance sémantique") + +**Pattern 2: Learning Loop** +- **User Action:** 👍 or 👎 +- **System Response:** "Thanks!" toast +- **Explanation:** Modal explains why (if 👎) +- **Adaptation:** Next suggestions improved + +--- + +### Flow Optimization Principles + +**1. Minimize Steps to Value** +- **Fast Capture:** Inbox → Type → Save (3 steps) +- **Semantic Search:** Type → Results (no extra clicks) +- **Cahier switching:** 1 click = instant switch + +**2. Reduce Cognitive Load** +- **Unified Search:** No keyword/semantic choice +- **Cahier Context:** Memory Echo scoped = relevant connections +- **Smart Defaults:** Inbox = default, no thinking required + +**3. Clear Feedback & Progress** +- **Toast Notifications:** "💡 I noticed something..." +- **Badges:** "🎯 Semantic Match" with score +- **Loading States:** Spinner + "AI thinking..." text + +**4. Moments of Delight** +- **Title Suggestions:** "Wow, the first one captures exactly the essence!" +- **Semantic Search:** "It understood what I meant, not what I typed!" +- **Memory Echo:** "I never made the connection!" + +**5. Graceful Error Recovery** +- **"Don't ask again":** Immediate dismiss, no confirmation +- **👎 Feedback:** Explanatory modal for learning +- **Settings Access:** Quick access via AI Badge dropdown + +--- + +## Component Strategy + +### Design System Components + +**Available from Radix UI:** + +Memento's chosen design system (Radix UI + Tailwind CSS) provides comprehensive primitive components: + +- ✅ **Dialog** - Modal overlays (Reformulation comparison) +- ✅ **Dropdown Menu** - Menus and dropdowns (Title suggestions, AI Badge) +- ✅ **Toast** - Temporary notifications (Memory Echo base) +- ✅ **Switch** - Toggle controls (AI settings ON/OFF) +- ✅ **Navigation Menu** - Sidebar navigation (Cahiers) +- ✅ **Scroll Area** - Scrollable containers (Masonry grid) +- ✅ **Tooltip** - Help text and icon explanations +- ✅ **Separator** - Visual dividers and borders + +**Available from Component Inventory (Existing Memento):** + +Based on component inventory analysis, these components are already built: + +- ✅ **NoteCard** - Note cards in masonry grid +- ✅ **MasonryGrid** - Responsive masonry layout +- ✅ **Header** - Top bar with logo, search, user menu +- ✅ **Sidebar** - Side navigation (adapt for Cahiers) +- ✅ **LabelSelector** - Tag selection component +- ✅ **NoteEditor** - Rich text note editor +- ✅ **LoginForm** - Authentication UI + +**Gap Analysis:** + +AI features require **7 custom components** not available in Radix UI or existing inventory: + +1. ❌ **MemoryEchoCard** - Specialized toast with 2 notes side-by-side +2. ❌ **SemanticSearchBadge** - "Semantic Match" badge with confidence score +3. ❌ **TitleSuggestionsDropdown** - Dropdown with 3 AI-generated titles +4. ❌ **ReformulationModal** - Comparison modal (original | AI suggestion) +5. ❌ **ProviderIndicator** - AI provider status (Local/Cloud + connection) +6. ❌ **AIToast** - AI-styled toast with purple border +7. ❌ **ProcessingIndicator** - "AI thinking..." spinner with text + +--- + +### Custom Components + +#### Component 1: MemoryEchoCard + +**Purpose:** Proactively display a connection between 2 notes (defining "Aha!" experience) + +**Anatomy:** +``` +┌─────────────────────────────────────────────────┐ +│ 💡 I noticed something in your **Work** notes... │ +├─────────────────────┬───────────────────────────┤ +│ Note A │ Note B │ +│ "Node.js tips" │ "Next.js optimization" │ +│ Preview: 50 chars │ Preview: 50 chars │ +├─────────────────────┴───────────────────────────┤ +│ Connection: Server-side rendering optimization │ +│ [Dismiss] [View] │ +└─────────────────────────────────────────────────┘ +``` + +**Usage:** +- Appears as toast notification (bottom-right, 16px from edges) +- Shows 2 notes with semantic similarity > 0.75 +- Displays connection explanation (AI-generated context) + +**States:** +- **Appearing:** Fade-in slide-up (0.3s ease-out) +- **Visible:** Subtle border pulse (purple) +- **Hover:** Shadow increase (shadow-lg), solid border +- **Dismissed:** Fade-out slide-down (0.2s) + +**Accessibility:** +- `role="alert"` - Important notification +- `aria-live="polite"` - Non-interruptive +- `aria-label="AI notification: Note connection discovered"` +- Keyboard: ESC to dismiss, Tab to "View Connection" button + +**Content Guidelines:** +- Headline: "💡 I noticed something in your **[Cahier name]** notes..." +- Connection: 1-2 sentence explanation of semantic link +- Note previews: 50 characters max, truncation with "..." + +**Interaction Behavior:** +- Auto-dismiss after 30 seconds +- Dismissible with X button (top-right) +- "View Connection" → Opens link notes action or modal +- 👍👎 feedback buttons after viewing + +**Design Tokens:** +- Border: `2px solid var(--ai-connection)` (#8B5CF6) +- Background: `var(--background)` (#FFFFFF) with `var(--ai-light)` tint (#F5F3FF) +- Shadow: `shadow-lg` on hover +- Corner radius: `rounded-xl` (12px) + +--- + +#### Component 2: SemanticSearchBadge + +**Purpose:** Indicate that a search result is a semantic match (not keyword match) + +**Anatomy:** +``` +┌─────────────────────────────────────┐ +│ Note Title: "React State..." │ +│ 🎯 Semantic Match (Score: 0.82) │ ← Badge here +│ Content preview... │ +└─────────────────────────────────────┘ +``` + +**Usage:** +- Appears below note title in search results +- Only shows when cosine similarity > 0.75 +- Indicates semantic understanding vs exact keyword match + +**States:** +- **Default:** Blue background (bg-blue-50), blue text (text-blue-600) +- **Hover:** Blue-100 background, underline +- **Focus:** 2px blue outline (focus-visible) + +**Accessibility:** +- `aria-label="Semantic match with 82% confidence"` +- Screen reader: "Semantic Match, 82 percent confidence" + +**Content Guidelines:** +- Text: "🎯 Semantic Match (Score: X.XX)" +- Score format: 2 decimal places (0.82, not 0.823456) +- Tooltip on hover: "This result matches the meaning, not exact words" + +**Variants:** +- **Exact Match:** No badge (default keyword search result) +- **Semantic Match:** Blue badge with score + +--- + +#### Component 3: TitleSuggestionsDropdown + +**Purpose:** Display 3 AI-generated title suggestions + +**Anatomy:** +``` +┌──────────────────────────────────────┐ +│ ✨ 3 Title Suggestions │ +├──────────────────────────────────────┤ +│ ✨ React State Management: useMemo... │ ← Hover state +│ ✨ Performance Hook Pattern pour... │ +│ ✨ Astuce React: mémoisation avec... │ +└──────────────────────────────────────┘ +``` + +**Usage:** +- Triggered when user types 50+ words without title +- Appears below title field in note editor +- Shows 3 AI-generated title options + +**States:** +- **Closed:** Hidden +- **Opening:** Fade-in (0.2s ease-out) +- **Open:** List visible, items hoverable +- **ItemSelected:** Green checkmark, background green-50 + +**Accessibility:** +- `role="listbox"` - Selectable list +- `aria-label="AI-generated title suggestions"` +- Keyboard: ↑↓ to navigate, Enter to select, ESC to close + +**Content Guidelines:** +- Icon: ✨ (sparkle) for each suggestion +- Max 3 items (no scroll) +- Title length: 60-80 characters optimal +- Truncate long titles with "..." + +**Interaction Behavior:** +- Trigger: 50+ words without title, focus on title field +- Position: Below title field (DropdownMenu positioning) +- Selection: Click to apply, replaces empty title +- ESC or click outside: Dismiss (user can type manual title) + +**Design Tokens:** +- Item text: `text-purple-600` (AI suggestion color) +- Item hover: `hover:bg-purple-50` +- Selected: `bg-green-50` with ✓ checkmark + +--- + +#### Component 4: ReformulationModal + +**Purpose:** Compare original text with AI reformulation side-by-side + +**Anatomy:** +``` +┌────────────────────────────────────────────────────┐ +│ ✨ Reformulate this Paragraph │ +├──────────────────────┬─────────────────────────────┤ +│ Original │ AI Suggestion │ +│ "This is bad text" │ "This text needs improve..." │ +│ │ │ +│ [Keep Original] │ [Apply Suggestion] │ +├──────────────────────┴─────────────────────────────┤ +│ [Retry] [Cancel] │ +└────────────────────────────────────────────────────┘ +``` + +**Usage:** +- Triggered by "✨ Reformulate" button on paragraph hover +- Shows original text vs AI reformulation +- User chooses to keep or replace + +**States:** +- **Opening:** Fade-in scale (0.2s) +- **Comparing:** Two-column view, 50% width each +- **Applied:** Green checkmark, modal closes (0.1s) +- **Cancelled:** Fade-out (0.1s) + +**Accessibility:** +- `role="dialog"` - Interactive modal +- `aria-labelledby="reformulation-modal-title"` +- `aria-describedby="reformulation-modal-desc"` +- Focus trap within modal +- ESC to close + +**Content Guidelines:** +- Header: "✨ Reformulate this Paragraph" +- Left column: "Original" (gray-500 label) +- Right column: "AI Suggestion" (purple-600 label) +- Buttons: "Keep Original" (gray), "Apply" (green), "Retry" (purple) + +**Interaction Behavior:** +- Trigger: Hover paragraph → "✨ Reformulate" button appears (top-right) +- Apply: Replaces paragraph text, green checkmark (0.5s), modal closes +- Keep: Returns to original text, modal closes +- Retry: Generates new suggestion (show ProcessingIndicator) + +**Design Tokens:** +- Modal border: `2px solid var(--ai-primary)` (#8B5CF6) +- Background: `var(--surface-elevated)` (#FFFFFF) +- Button primary (Apply): `bg-green-600 hover:bg-green-700` + +--- + +#### Component 5: ProviderIndicator + +**Purpose:** Indicate AI provider status (Local Ollama / Cloud OpenAI / Custom) + +**Anatomy:** +``` +In AI Badge Dropdown: +┌────────────────────────────────────┐ +│ AI Status │ +│ 🏠 Local (Ollama) │ ← Indicator +│ ✅ Connected: localhost:11434 │ +└────────────────────────────────────┘ +``` + +**Usage:** +- Displayed in AI Badge dropdown menu +- Shows current provider and connection status +- Critical for user trust (Max's privacy journey) + +**States:** +- **Local:** 🏠 icon + "Local (Ollama)" +- **Cloud:** ☁️ icon + "Cloud (OpenAI)" +- **Custom:** ⚙️ icon + "Custom (OpenAI-compatible)" +- **Connected:** ✅ green + URL/host +- **Disconnected:** ❌ red + "Not available" +- **Loading:** 🔄 spinner + "Connecting..." + +**Accessibility:** +- `aria-label="AI provider status: Local Ollama, Connected"` +- Screen reader: "AI provider: Local Ollama, Connected to localhost port 11434" + +**Content Guidelines:** +- Local: "🏠 Local (Ollama)" +- Cloud: "☁️ Cloud (OpenAI)" +- Custom: "⚙️ Custom (OpenAI-compatible)" +- Status: "✅ Connected: [URL]" or "❌ Disconnected" + +**Variants:** +- **Compact:** Icon only (for mobile) +- **Full:** Icon + label + status (desktop) + +--- + +#### Component 6: AIToast + +**Purpose:** Custom toast for AI notifications (Memory Echo, suggestions, feedback) + +**Anatomy:** +``` +┌──────────────────────────────────────────┐ +│ 💡 I noticed something... [X] │ +│ │ +│ Connection details... │ +│ [View Connection] [Dismiss] │ +└──────────────────────────────────────────┘ +``` + +**Usage:** +- Base component for all AI notifications +- Extends Radix UI Toast with AI-specific styling +- Used by MemoryEchoCard, TitleSuggestions, etc. + +**States:** +- **Entering:** Slide-up fade-in (0.3s ease-out) +- **Visible:** Purple border (2px solid #8B5CF6) +- **Hover:** Shadow-lg, border 3px +- **Exiting:** Slide-down fade-out (0.2s) + +**Accessibility:** +- `role="alert"` - Important notification +- `aria-live="polite"` - Non-interruptive +- `aria-label="AI notification"` +- Auto-dismiss respects `prefers-reduced-motion` + +**Design Tokens:** +- Border: `2px solid var(--ai-connection)` (#8B5CF6) +- Background: `var(--background)` (#FFFFFF) with `var(--ai-light)` tint (#F5F3FF) +- Shadow: `shadow-lg` on hover +- Corner radius: `rounded-xl` (12px) +- Padding: `space-4` (16px) all around + +**Interaction Behavior:** +- Position: Bottom-right, 16px from edges (desktop) +- Position: Bottom-center, full-width on mobile +- Auto-dismiss: Configurable (10-60s default 30s) +- Dismissible: X button (top-right) or ESC key + +--- + +#### Component 7: ProcessingIndicator + +**Purpose:** Indicate that AI is processing a request + +**Anatomy:** +``` +┌────────────────────────────┐ +│ [Spinner] AI thinking... │ +│ Generating embeddings │ +└────────────────────────────┘ +``` + +**Usage:** +- Shows during AI operations (embedding generation, reformulation) +- Provides feedback during long-running operations (> 500ms) + +**States:** +- **Idle:** Hidden +- **Processing:** Amber spinner + "AI thinking..." text +- **Success:** Green checkmark (0.5s display) → fade +- **Error:** Red X + error message + +**Accessibility:** +- `role="status"` - Status indicator +- `aria-live="polite"` - Status updates +- `aria-busy="true"` during processing + +**Design Tokens:** +- Spinner color: `var(--ai-processing)` (#F59E0B) +- Text: `text-sm text-secondary` (#6B7280) +- Animation: Spin 1s linear infinite +- Respects `prefers-reduced-motion` + +**Content Guidelines:** +- Default text: "AI thinking..." +- Contextual text: "Generating embeddings...", "Reformulating..." +- Error text: "AI unavailable. Try again later." + +--- + +### Component Implementation Strategy + +**Foundation Components (from Radix UI):** + +Leverage Radix UI primitives with Tailwind styling: + +| Radix Primitive | Usage in Memento | Custom Styling | +|----------------|------------------|----------------| +| Dialog | Reformulation modal, Memory Echo details | Purple border, AI-specific padding | +| DropdownMenu | Title suggestions, AI Badge menu | Purple text on hover, ✨ icons | +| Toast | Base for AIToast | Extended with purple border, custom positioning | +| Switch | AI settings toggles | Default Radix + labels | +| NavigationMenu | Cahiers sidebar | Active state = purple left border | + +**Custom Components (IA-specific):** + +Build 7 custom components on top of Radix primitives: + +1. **MemoryEchoCard** - Extended AIToast with 2-column note comparison +2. **SemanticSearchBadge** - Custom badge component (blue styling) +3. **TitleSuggestionsDropdown** - Radix DropdownMenu + ✨ icons + purple text +4. **ReformulationModal** - Radix Dialog with 2-column layout +5. **ProviderIndicator** - Custom status indicator (icon + text + status) +6. **AIToast** - Extended Radix Toast (purple border, positioning) +7. **ProcessingIndicator** - Custom spinner + status text + +**Implementation Approach:** + +1. **Create IA-specific component variants** + - Extend Radix components with AI styling + - Use composition over inheritance + - Share design tokens (colors, spacing) + +2. **Use design tokens for consistency** + - All AI components use `--ai-*` color tokens + - Spacing from 8px grid (space-2, space-4, etc.) + - Typography from system fonts scale + +3. **Follow accessibility patterns** + - Leverage Radix's built-in ARIA attributes + - Add custom ARIA for AI-specific content + - Ensure keyboard navigation (ESC, Tab, Enter) + - Test with screen readers + +4. **Create reusable patterns** + - AIToast wrapper around Radix Toast + - BaseModal component (extends Dialog) for all modals + - AIBadge base component (purple border, common props) + +--- + +### Implementation Roadmap + +**Phase 1 - Core Components (Week 1-2) - P0** + +| Component | Priority | User Journey | Rationale | +|-----------|----------|--------------|-----------| +| ProviderIndicator | P0 | Max (Privacy) | Essential for user trust, shows AI status | +| AIToast | P0 | All journeys | Base component for all AI notifications | +| TitleSuggestionsDropdown | P0 | Alex (Fast Capture) | Most-used AI feature, high user value | + +**Deliverables:** +- ✅ ProviderIndicator with local/cloud states +- ✅ AIToast base component with purple styling +- ✅ TitleSuggestionsDropdown with 3 options +- ✅ Design tokens extension (AI colors) + +**Week 1:** ProviderIndicator, AIToast +**Week 2:** TitleSuggestionsDropdown + testing + +--- + +**Phase 2 - AI Features (Week 3-4) - P1** + +| Component | Priority | User Journey | Rationale | +|-----------|----------|--------------|-----------| +| SemanticSearchBadge | P1 | Alex (Search) | Feature 2 (Semantic Search) | +| ReformulationModal | P1 | Alex (Enhancement) | Feature 3 (Reformulation) | +| ProcessingIndicator | P1 | All journeys | Feedback during AI operations | + +**Deliverables:** +- ✅ SemanticSearchBadge with confidence scores +- ✅ ReformulationModal with 2-column comparison +- ✅ ProcessingIndicator with loading/success/error states + +**Week 3:** SemanticSearchBadge, ProcessingIndicator +**Week 4:** ReformulationModal + integration + +--- + +**Phase 3 - Advanced (Week 5) - P2** + +| Component | Priority | User Journey | Rationale | +|-----------|----------|--------------|-----------| +| MemoryEchoCard | P2 | Alex/Max (Aha!) | Feature 4 (Memory Echo) - defining experience but complex | + +**Deliverables:** +- ✅ MemoryEchoCard with 2-note comparison +- ✅ Background processing (cosine similarity) +- ✅ 👍👎 feedback system + +**Week 5:** MemoryEchoCard + testing + refinement + +--- + +**Prioritization Rationale:** + +**P0 (Critical Path):** +- **ProviderIndicator:** Trust blocker - Max won't use AI without status visibility +- **AIToast:** Foundation for all AI notifications +- **TitleSuggestions:** Highest user value (80% acceptance rate in PRD) + +**P1 (High Value):** +- **SemanticSearchBadge:** Key differentiator vs keyword search +- **ReformulationModal:** Enhancement feature, improves writing quality +- **ProcessingIndicator:** UX requirement - users need feedback during AI ops + +**P2 (Strategic):** +- **MemoryEchoCard:** Defining "Aha!" experience but most complex (background processing, embeddings, feedback learning) + +--- diff --git a/keep-notes/app/(main)/admin/ai-test/ai-tester.tsx b/keep-notes/app/(main)/admin/ai-test/ai-tester.tsx new file mode 100644 index 0000000..877e705 --- /dev/null +++ b/keep-notes/app/(main)/admin/ai-test/ai-tester.tsx @@ -0,0 +1,258 @@ +'use client' + +import { Button } from '@/components/ui/button' +import { Card, CardContent } from '@/components/ui/card' +import { Badge } from '@/components/ui/badge' +import { useState, useEffect } from 'react' +import { toast } from 'sonner' +import { Loader2, CheckCircle2, XCircle, Clock, Zap, Info } from 'lucide-react' + +interface TestResult { + success: boolean + provider?: string + model?: string + responseTime?: number + tags?: Array<{ tag: string; confidence: number }> + embeddingLength?: number + firstValues?: number[] + error?: string + details?: any +} + +export function AI_TESTER({ type }: { type: 'tags' | 'embeddings' }) { + const [isLoading, setIsLoading] = useState(false) + const [result, setResult] = useState(null) + const [config, setConfig] = useState(null) + + useEffect(() => { + fetchConfig() + }, []) + + const fetchConfig = async () => { + try { + const response = await fetch('/api/ai/config') + const data = await response.json() + setConfig(data) + + // Set previous result if available + if (data.previousTest) { + setResult(data.previousTest[type] || null) + } + } catch (error) { + console.error('Failed to fetch config:', error) + } + } + + const runTest = async () => { + setIsLoading(true) + const startTime = Date.now() + + try { + const response = await fetch(`/api/ai/test-${type}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' } + }) + + const endTime = Date.now() + const data = await response.json() + + setResult({ + ...data, + responseTime: endTime - startTime + }) + + if (data.success) { + toast.success( + `✅ ${type === 'tags' ? 'Tags' : 'Embeddings'} Test Successful!`, + { + description: `Provider: ${data.provider} | Time: ${endTime - startTime}ms` + } + ) + } else { + toast.error( + `❌ ${type === 'tags' ? 'Tags' : 'Embeddings'} Test Failed`, + { + description: data.error || 'Unknown error' + } + ) + } + } catch (error: any) { + const endTime = Date.now() + const errorResult = { + success: false, + error: error.message || 'Network error', + responseTime: endTime - startTime + } + setResult(errorResult) + toast.error(`❌ Test Error: ${error.message}`) + } finally { + setIsLoading(false) + } + } + + const getProviderInfo = () => { + if (!config) return { provider: 'Loading...', model: 'Loading...' } + + if (type === 'tags') { + return { + provider: config.AI_PROVIDER_TAGS || 'ollama', + model: config.AI_MODEL_TAGS || 'granite4:latest' + } + } else { + return { + provider: config.AI_PROVIDER_EMBEDDING || 'ollama', + model: config.AI_MODEL_EMBEDDING || 'embeddinggemma:latest' + } + } + } + + const providerInfo = getProviderInfo() + + return ( +
+ {/* Provider Info */} +
+
+ Provider: + + {providerInfo.provider.toUpperCase()} + +
+
+ Model: + + {providerInfo.model} + +
+
+ + {/* Test Button */} + + + {/* Results */} + {result && ( + + + {/* Status */} +
+ {result.success ? ( + <> + + Test Passed + + ) : ( + <> + + Test Failed + + )} +
+ + {/* Response Time */} + {result.responseTime && ( +
+ + Response time: {result.responseTime}ms +
+ )} + + {/* Tags Results */} + {type === 'tags' && result.success && result.tags && ( +
+
+ + Generated Tags: +
+
+ {result.tags.map((tag, idx) => ( + + {tag.tag} + + ({Math.round(tag.confidence * 100)}%) + + + ))} +
+
+ )} + + {/* Embeddings Results */} + {type === 'embeddings' && result.success && result.embeddingLength && ( +
+
+ + Embedding Dimensions: +
+
+
+ {result.embeddingLength} +
+
+ vector dimensions +
+
+ {result.firstValues && result.firstValues.length > 0 && ( +
+ First 5 values: +
+ [{result.firstValues.slice(0, 5).map((v, i) => v.toFixed(4)).join(', ')}] +
+
+ )} +
+ )} + + {/* Error Details */} + {!result.success && result.error && ( +
+

Error:

+

{result.error}

+ {result.details && ( +
+ + Technical details + +
+                      {JSON.stringify(result.details, null, 2)}
+                    
+
+ )} +
+ )} +
+
+ )} + + {/* Loading State */} + {isLoading && ( +
+ +

+ Testing {type === 'tags' ? 'tags generation' : 'embeddings'}... +

+
+ )} +
+ ) +} diff --git a/keep-notes/app/(main)/admin/ai-test/page.tsx b/keep-notes/app/(main)/admin/ai-test/page.tsx new file mode 100644 index 0000000..b0ef5a2 --- /dev/null +++ b/keep-notes/app/(main)/admin/ai-test/page.tsx @@ -0,0 +1,106 @@ +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card' +import { Button } from '@/components/ui/button' +import { auth } from '@/auth' +import { redirect } from 'next/navigation' +import Link from 'next/link' +import { ArrowLeft, TestTube } from 'lucide-react' +import { AI_TESTER } from './ai-tester' + +export default async function AITestPage() { + const session = await auth() + + if ((session?.user as any)?.role !== 'ADMIN') { + redirect('/') + } + + return ( +
+
+
+ + + +
+

+ + AI Provider Testing +

+

+ Test your AI providers for tag generation and semantic search embeddings +

+
+
+
+ +
+ {/* Tags Provider Test */} + + + + 🏷️ + Tags Generation Test + + + Test the AI provider responsible for automatic tag suggestions + + + + + + + + {/* Embeddings Provider Test */} + + + + 🔍 + Embeddings Test + + + Test the AI provider responsible for semantic search embeddings + + + + + + +
+ + {/* Info Section */} + + + ℹ️ How Testing Works + + +
+

🏷️ Tags Generation Test:

+
    +
  • Sends a sample note to the AI provider
  • +
  • Requests 3-5 relevant tags based on the content
  • +
  • Displays the generated tags with confidence scores
  • +
  • Measures response time
  • +
+
+
+

🔍 Embeddings Test:

+
    +
  • Sends a sample text to the embedding provider
  • +
  • Generates a vector representation (list of numbers)
  • +
  • Displays embedding dimensions and sample values
  • +
  • Verifies the vector is valid and properly formatted
  • +
+
+
+

💡 Tip:

+

+ You can use different providers for tags and embeddings! For example, use Ollama (free) for tags + and OpenAI (best quality) for embeddings to optimize costs and performance. +

+
+
+
+
+ ) +} diff --git a/keep-notes/app/(main)/admin/settings/admin-settings-form.tsx b/keep-notes/app/(main)/admin/settings/admin-settings-form.tsx index ccec44b..211b869 100644 --- a/keep-notes/app/(main)/admin/settings/admin-settings-form.tsx +++ b/keep-notes/app/(main)/admin/settings/admin-settings-form.tsx @@ -4,36 +4,66 @@ import { Button } from '@/components/ui/button' import { Input } from '@/components/ui/input' import { Checkbox } from '@/components/ui/checkbox' import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card' +import { Label } from '@/components/ui/label' import { updateSystemConfig, testSMTP } from '@/app/actions/admin-settings' import { toast } from 'sonner' import { useState, useEffect } from 'react' +import Link from 'next/link' +import { TestTube, ExternalLink } from 'lucide-react' + +type AIProvider = 'ollama' | 'openai' | 'custom' + +interface AvailableModels { + tags: string[] + embeddings: string[] +} + +const MODELS_2026 = { + ollama: { + tags: ['llama3:latest', 'llama3.2:latest', 'granite4:latest', 'mistral:latest', 'mixtral:latest', 'phi3:latest', 'gemma2:latest', 'qwen2:latest'], + embeddings: ['embeddinggemma:latest', 'mxbai-embed-large:latest', 'nomic-embed-text:latest'] + }, + openai: { + tags: ['gpt-4o', 'gpt-4o-mini', 'gpt-4-turbo', 'gpt-4', 'gpt-3.5-turbo'], + embeddings: ['text-embedding-3-small', 'text-embedding-3-large', 'text-embedding-ada-002'] + }, + custom: { + tags: ['gpt-4o-mini', 'gpt-4o', 'claude-3-haiku', 'claude-3-sonnet', 'llama-3.1-8b'], + embeddings: ['text-embedding-3-small', 'text-embedding-3-large', 'text-embedding-ada-002'] + } +} export function AdminSettingsForm({ config }: { config: Record }) { const [isSaving, setIsSaving] = useState(false) const [isTesting, setIsTesting] = useState(false) - + // Local state for Checkbox const [allowRegister, setAllowRegister] = useState(config.ALLOW_REGISTRATION !== 'false') const [smtpSecure, setSmtpSecure] = useState(config.SMTP_SECURE === 'true') const [smtpIgnoreCert, setSmtpIgnoreCert] = useState(config.SMTP_IGNORE_CERT === 'true') + // AI Provider state - separated for tags and embeddings + const [tagsProvider, setTagsProvider] = useState((config.AI_PROVIDER_TAGS as AIProvider) || 'ollama') + const [embeddingsProvider, setEmbeddingsProvider] = useState((config.AI_PROVIDER_EMBEDDING as AIProvider) || 'ollama') + // Sync state with config when server revalidates useEffect(() => { setAllowRegister(config.ALLOW_REGISTRATION !== 'false') setSmtpSecure(config.SMTP_SECURE === 'true') setSmtpIgnoreCert(config.SMTP_IGNORE_CERT === 'true') + setTagsProvider((config.AI_PROVIDER_TAGS as AIProvider) || 'ollama') + setEmbeddingsProvider((config.AI_PROVIDER_EMBEDDING as AIProvider) || 'ollama') }, [config]) const handleSaveSecurity = async (formData: FormData) => { setIsSaving(true) - // We override the formData get because the hidden input might be tricky const data = { ALLOW_REGISTRATION: allowRegister ? 'true' : 'false', } - + const result = await updateSystemConfig(data) setIsSaving(false) - + if (result.error) { toast.error('Failed to update security settings') } else { @@ -43,20 +73,45 @@ export function AdminSettingsForm({ config }: { config: Record } const handleSaveAI = async (formData: FormData) => { setIsSaving(true) - const data = { - AI_PROVIDER: formData.get('AI_PROVIDER') as string, - OLLAMA_BASE_URL: formData.get('OLLAMA_BASE_URL') as string, - AI_MODEL_EMBEDDING: formData.get('AI_MODEL_EMBEDDING') as string, - OPENAI_API_KEY: formData.get('OPENAI_API_KEY') as string, + const data: Record = {} + + // Tags provider configuration + const tagsProv = formData.get('AI_PROVIDER_TAGS') as AIProvider + data.AI_PROVIDER_TAGS = tagsProv + data.AI_MODEL_TAGS = formData.get('AI_MODEL_TAGS') as string + + if (tagsProv === 'ollama') { + data.OLLAMA_BASE_URL = formData.get('OLLAMA_BASE_URL_TAGS') as string + } else if (tagsProv === 'openai') { + data.OPENAI_API_KEY = formData.get('OPENAI_API_KEY') as string + } else if (tagsProv === 'custom') { + data.CUSTOM_OPENAI_API_KEY = formData.get('CUSTOM_OPENAI_API_KEY_TAGS') as string + data.CUSTOM_OPENAI_BASE_URL = formData.get('CUSTOM_OPENAI_BASE_URL_TAGS') as string } - + + // Embeddings provider configuration + const embedProv = formData.get('AI_PROVIDER_EMBEDDING') as AIProvider + data.AI_PROVIDER_EMBEDDING = embedProv + data.AI_MODEL_EMBEDDING = formData.get('AI_MODEL_EMBEDDING') as string + + if (embedProv === 'ollama') { + data.OLLAMA_BASE_URL = formData.get('OLLAMA_BASE_URL_EMBEDDING') as string + } else if (embedProv === 'openai') { + data.OPENAI_API_KEY = formData.get('OPENAI_API_KEY') as string + } else if (embedProv === 'custom') { + data.CUSTOM_OPENAI_API_KEY = formData.get('CUSTOM_OPENAI_API_KEY_EMBEDDING') as string + data.CUSTOM_OPENAI_BASE_URL = formData.get('CUSTOM_OPENAI_BASE_URL_EMBEDDING') as string + } + const result = await updateSystemConfig(data) setIsSaving(false) - + if (result.error) { toast.error('Failed to update AI settings') } else { toast.success('AI Settings updated') + setTagsProvider(tagsProv) + setEmbeddingsProvider(embedProv) } } @@ -71,10 +126,10 @@ export function AdminSettingsForm({ config }: { config: Record } SMTP_IGNORE_CERT: smtpIgnoreCert ? 'true' : 'false', SMTP_SECURE: smtpSecure ? 'true' : 'false', } - + const result = await updateSystemConfig(data) setIsSaving(false) - + if (result.error) { toast.error('Failed to update SMTP settings') } else { @@ -108,8 +163,8 @@ export function AdminSettingsForm({ config }: { config: Record }
- setAllowRegister(!!c)} /> @@ -133,40 +188,219 @@ export function AdminSettingsForm({ config }: { config: Record } AI Configuration - Configure the AI provider for auto-tagging and semantic search. + Configure AI providers for auto-tagging and semantic search. Use different providers for optimal performance. - -
- - -
- -
- - + + {/* Tags Generation Section */} +
+

+ 🏷️ Tags Generation Provider +

+

AI provider for automatic tag suggestions. Recommended: Ollama (free, local).

+ +
+ + +
+ + {/* Ollama Tags Config */} + {tagsProvider === 'ollama' && ( +
+
+ + +
+
+ + +

Select an Ollama model installed on your system

+
+
+ )} + + {/* OpenAI Tags Config */} + {tagsProvider === 'openai' && ( +
+
+ + +

Your OpenAI API key from platform.openai.com

+
+
+ + +

gpt-4o-mini = Best value • gpt-4o = Best quality

+
+
+ )} + + {/* Custom OpenAI Tags Config */} + {tagsProvider === 'custom' && ( +
+
+ + +
+
+ + +
+
+ + +

Common models for OpenAI-compatible APIs

+
+
+ )}
-
- - -
+ {/* Embeddings Section */} +
+

+ 🔍 Embeddings Provider +

+

AI provider for semantic search embeddings. Recommended: OpenAI (best quality).

-
- - +
+ + +
+ + {/* Ollama Embeddings Config */} + {embeddingsProvider === 'ollama' && ( +
+
+ + +
+
+ + +

Select an embedding model installed on your system

+
+
+ )} + + {/* OpenAI Embeddings Config */} + {embeddingsProvider === 'openai' && ( +
+
+ + +

Your OpenAI API key from platform.openai.com

+
+
+ + +

text-embedding-3-small = Best value • text-embedding-3-large = Best quality

+
+
+ )} + + {/* Custom OpenAI Embeddings Config */} + {embeddingsProvider === 'custom' && ( +
+
+ + +
+
+ + +
+
+ + +

Common embedding models for OpenAI-compatible APIs

+
+
+ )}
- - + + + + + @@ -188,12 +422,12 @@ export function AdminSettingsForm({ config }: { config: Record }
- +
- +
@@ -205,10 +439,10 @@ export function AdminSettingsForm({ config }: { config: Record }
- setSmtpSecure(!!c)} + setSmtpSecure(!!c)} />
- setSmtpIgnoreCert(!!c)} /> diff --git a/keep-notes/app/(main)/layout.tsx b/keep-notes/app/(main)/layout.tsx index 3ebb38f..4ad2fdf 100644 --- a/keep-notes/app/(main)/layout.tsx +++ b/keep-notes/app/(main)/layout.tsx @@ -10,11 +10,11 @@ export default async function MainLayout({ const session = await auth(); return ( -
+
-
- -
+
+ +
{children}
diff --git a/keep-notes/app/api/ai/config/route.ts b/keep-notes/app/api/ai/config/route.ts new file mode 100644 index 0000000..a525ca5 --- /dev/null +++ b/keep-notes/app/api/ai/config/route.ts @@ -0,0 +1,27 @@ +import { NextRequest, NextResponse } from 'next/server' +import { getSystemConfig } from '@/lib/config' + +export async function GET(request: NextRequest) { + try { + const config = await getSystemConfig() + + return NextResponse.json({ + AI_PROVIDER_TAGS: config.AI_PROVIDER_TAGS || 'ollama', + AI_MODEL_TAGS: config.AI_MODEL_TAGS || 'granite4:latest', + AI_PROVIDER_EMBEDDING: config.AI_PROVIDER_EMBEDDING || 'ollama', + AI_MODEL_EMBEDDING: config.AI_MODEL_EMBEDDING || 'embeddinggemma:latest', + OPENAI_API_KEY: config.OPENAI_API_KEY ? '***configured***' : '', + CUSTOM_OPENAI_API_KEY: config.CUSTOM_OPENAI_API_KEY ? '***configured***' : '', + CUSTOM_OPENAI_BASE_URL: config.CUSTOM_OPENAI_BASE_URL || '', + OLLAMA_BASE_URL: config.OLLAMA_BASE_URL || 'http://localhost:11434' + }) + } catch (error: any) { + console.error('Error fetching AI config:', error) + return NextResponse.json( + { + error: error.message || 'Failed to fetch config' + }, + { status: 500 } + ) + } +} diff --git a/keep-notes/app/api/ai/models/route.ts b/keep-notes/app/api/ai/models/route.ts new file mode 100644 index 0000000..3543ee3 --- /dev/null +++ b/keep-notes/app/api/ai/models/route.ts @@ -0,0 +1,98 @@ +import { NextRequest, NextResponse } from 'next/server' +import { getSystemConfig } from '@/lib/config' + +// Modèles populaires pour chaque provider (2025) +const PROVIDER_MODELS = { + ollama: { + tags: [ + 'llama3:latest', + 'llama3.2:latest', + 'granite4:latest', + 'mistral:latest', + 'mixtral:latest', + 'phi3:latest', + 'gemma2:latest', + 'qwen2:latest' + ], + embeddings: [ + 'embeddinggemma:latest', + 'mxbai-embed-large:latest', + 'nomic-embed-text:latest' + ] + }, + openai: { + tags: [ + 'gpt-4o', + 'gpt-4o-mini', + 'gpt-4-turbo', + 'gpt-4', + 'gpt-3.5-turbo' + ], + embeddings: [ + 'text-embedding-3-small', + 'text-embedding-3-large', + 'text-embedding-ada-002' + ] + }, + custom: { + tags: [], // Will be loaded dynamically + embeddings: [] // Will be loaded dynamically + } +} + +export async function GET(request: NextRequest) { + try { + const config = await getSystemConfig() + const provider = (config.AI_PROVIDER || 'ollama').toLowerCase() + + let models = PROVIDER_MODELS[provider as keyof typeof PROVIDER_MODELS] || { tags: [], embeddings: [] } + + // Pour Ollama, essayer de récupérer la liste réelle depuis l'API locale + if (provider === 'ollama') { + try { + const ollamaBaseUrl = config.OLLAMA_BASE_URL || process.env.OLLAMA_BASE_URL || 'http://localhost:11434' + const response = await fetch(`${ollamaBaseUrl}/api/tags`, { + method: 'GET', + headers: { 'Content-Type': 'application/json' } + }) + + if (response.ok) { + const data = await response.json() + const allModels = data.models || [] + + // Séparer les modèles de tags et d'embeddings + const tagModels = allModels + .filter((m: any) => !m.name.includes('embed') && !m.name.includes('Embedding')) + .map((m: any) => m.name) + .slice(0, 20) // Limiter à 20 modèles + + const embeddingModels = allModels + .filter((m: any) => m.name.includes('embed') || m.name.includes('Embedding')) + .map((m: any) => m.name) + + models = { + tags: tagModels.length > 0 ? tagModels : models.tags, + embeddings: embeddingModels.length > 0 ? embeddingModels : models.embeddings + } + } + } catch (error) { + console.warn('Could not fetch Ollama models, using defaults:', error) + // Garder les modèles par défaut + } + } + + return NextResponse.json({ + provider, + models: models || { tags: [], embeddings: [] } + }) + } catch (error: any) { + console.error('Error fetching models:', error) + return NextResponse.json( + { + error: error.message || 'Failed to fetch models', + models: { tags: [], embeddings: [] } + }, + { status: 500 } + ) + } +} diff --git a/keep-notes/app/api/ai/test-embeddings/route.ts b/keep-notes/app/api/ai/test-embeddings/route.ts new file mode 100644 index 0000000..1bae7d5 --- /dev/null +++ b/keep-notes/app/api/ai/test-embeddings/route.ts @@ -0,0 +1,91 @@ +import { NextRequest, NextResponse } from 'next/server' +import { getEmbeddingsProvider } from '@/lib/ai/factory' +import { getSystemConfig } from '@/lib/config' + +function getProviderDetails(config: Record, providerType: string) { + const provider = providerType.toLowerCase() + + switch (provider) { + case 'ollama': + return { + provider: 'Ollama', + baseUrl: config.OLLAMA_BASE_URL || 'http://localhost:11434', + model: config.AI_MODEL_EMBEDDING || 'embeddinggemma:latest' + } + case 'openai': + return { + provider: 'OpenAI', + baseUrl: 'https://api.openai.com/v1', + model: config.AI_MODEL_EMBEDDING || 'text-embedding-3-small' + } + case 'custom': + return { + provider: 'Custom OpenAI', + baseUrl: config.CUSTOM_OPENAI_BASE_URL || 'Not configured', + model: config.AI_MODEL_EMBEDDING || 'text-embedding-3-small' + } + default: + return { + provider: provider, + baseUrl: 'unknown', + model: config.AI_MODEL_EMBEDDING || 'unknown' + } + } +} + +export async function POST(request: NextRequest) { + try { + const config = await getSystemConfig() + const provider = getEmbeddingsProvider(config) + + const testText = 'test' + const startTime = Date.now() + const embeddings = await provider.getEmbeddings(testText) + const endTime = Date.now() + + if (!embeddings || embeddings.length === 0) { + const providerType = config.AI_PROVIDER_EMBEDDING || 'ollama' + const details = getProviderDetails(config, providerType) + return NextResponse.json( + { + success: false, + error: 'No embeddings returned', + provider: providerType, + model: config.AI_MODEL_EMBEDDING || 'embeddinggemma:latest', + details + }, + { status: 500 } + ) + } + + const providerType = config.AI_PROVIDER_EMBEDDING || 'ollama' + const details = getProviderDetails(config, providerType) + + return NextResponse.json({ + success: true, + provider: providerType, + model: config.AI_MODEL_EMBEDDING || 'embeddinggemma:latest', + embeddingLength: embeddings.length, + firstValues: embeddings.slice(0, 5), + responseTime: endTime - startTime, + details + }) + } catch (error: any) { + console.error('AI embeddings test error:', error) + const config = await getSystemConfig() + const providerType = config.AI_PROVIDER_EMBEDDING || 'ollama' + const details = getProviderDetails(config, providerType) + + return NextResponse.json( + { + success: false, + error: error.message || 'Unknown error', + provider: providerType, + model: config.AI_MODEL_EMBEDDING || 'embeddinggemma:latest', + details, + stack: process.env.NODE_ENV === 'development' ? error.stack : undefined + }, + { status: 500 } + ) + } +} diff --git a/keep-notes/app/api/ai/test-tags/route.ts b/keep-notes/app/api/ai/test-tags/route.ts new file mode 100644 index 0000000..f6f2b00 --- /dev/null +++ b/keep-notes/app/api/ai/test-tags/route.ts @@ -0,0 +1,50 @@ +import { NextRequest, NextResponse } from 'next/server' +import { getTagsProvider } from '@/lib/ai/factory' +import { getSystemConfig } from '@/lib/config' + +export async function POST(request: NextRequest) { + try { + const config = await getSystemConfig() + const provider = getTagsProvider(config) + + const testContent = "This is a test note about artificial intelligence and machine learning. It contains keywords like AI, ML, neural networks, and deep learning." + + const startTime = Date.now() + const tags = await provider.generateTags(testContent) + const endTime = Date.now() + + if (!tags || tags.length === 0) { + return NextResponse.json( + { + success: false, + error: 'No tags generated', + provider: config.AI_PROVIDER_TAGS || 'ollama', + model: config.AI_MODEL_TAGS || 'granite4:latest' + }, + { status: 500 } + ) + } + + return NextResponse.json({ + success: true, + provider: config.AI_PROVIDER_TAGS || 'ollama', + model: config.AI_MODEL_TAGS || 'granite4:latest', + tags: tags, + responseTime: endTime - startTime + }) + } catch (error: any) { + console.error('AI tags test error:', error) + const config = await getSystemConfig() + + return NextResponse.json( + { + success: false, + error: error.message || 'Unknown error', + provider: config.AI_PROVIDER_TAGS || 'ollama', + model: config.AI_MODEL_TAGS || 'granite4:latest', + stack: process.env.NODE_ENV === 'development' ? error.stack : undefined + }, + { status: 500 } + ) + } +} diff --git a/keep-notes/app/api/ai/test/route.ts b/keep-notes/app/api/ai/test/route.ts index 1c47b5b..3a5a389 100644 --- a/keep-notes/app/api/ai/test/route.ts +++ b/keep-notes/app/api/ai/test/route.ts @@ -1,55 +1,88 @@ import { NextRequest, NextResponse } from 'next/server' -import { getAIProvider } from '@/lib/ai/factory' +import { getTagsProvider, getEmbeddingsProvider } from '@/lib/ai/factory' import { getSystemConfig } from '@/lib/config' +function getProviderDetails(config: Record, providerType: string) { + const provider = providerType.toLowerCase() + + switch (provider) { + case 'ollama': + return { + provider: 'Ollama', + baseUrl: config.OLLAMA_BASE_URL || process.env.OLLAMA_BASE_URL || 'http://localhost:11434', + model: config.AI_MODEL_EMBEDDING || 'embeddinggemma:latest' + } + case 'openai': + return { + provider: 'OpenAI', + baseUrl: 'https://api.openai.com/v1', + model: config.AI_MODEL_EMBEDDING || 'text-embedding-3-small' + } + case 'custom': + return { + provider: 'Custom OpenAI', + baseUrl: config.CUSTOM_OPENAI_BASE_URL || process.env.CUSTOM_OPENAI_BASE_URL || 'Not configured', + model: config.AI_MODEL_EMBEDDING || 'text-embedding-3-small' + } + default: + return { + provider: provider, + baseUrl: 'unknown', + model: config.AI_MODEL_EMBEDDING || 'unknown' + } + } +} + export async function GET(request: NextRequest) { try { const config = await getSystemConfig() - const provider = getAIProvider(config) + const tagsProvider = getTagsProvider(config) + const embeddingsProvider = getEmbeddingsProvider(config) - // Test with a simple embedding request const testText = 'test' - const embeddings = await provider.getEmbeddings(testText) + + // Test embeddings provider + const embeddings = await embeddingsProvider.getEmbeddings(testText) if (!embeddings || embeddings.length === 0) { + const providerType = config.AI_PROVIDER_EMBEDDING || 'ollama' + const details = getProviderDetails(config, providerType) return NextResponse.json( { success: false, - provider: config.AI_PROVIDER || 'ollama', + tagsProvider: config.AI_PROVIDER_TAGS || 'ollama', + embeddingsProvider: providerType, error: 'No embeddings returned', - details: { - provider: config.AI_PROVIDER || 'ollama', - baseUrl: config.OLLAMA_BASE_URL || process.env.OLLAMA_BASE_URL || 'http://localhost:11434', - model: config.AI_MODEL_EMBEDDING || process.env.OLLAMA_EMBEDDING_MODEL || 'embeddinggemma:latest' - } + details }, { status: 500 } ) } + const tagsProviderType = config.AI_PROVIDER_TAGS || 'ollama' + const embeddingsProviderType = config.AI_PROVIDER_EMBEDDING || 'ollama' + const details = getProviderDetails(config, embeddingsProviderType) + return NextResponse.json({ success: true, - provider: config.AI_PROVIDER || 'ollama', + tagsProvider: tagsProviderType, + embeddingsProvider: embeddingsProviderType, embeddingLength: embeddings.length, firstValues: embeddings.slice(0, 5), - details: { - provider: config.AI_PROVIDER || 'ollama', - baseUrl: config.OLLAMA_BASE_URL || process.env.OLLAMA_BASE_URL || 'http://localhost:11434', - model: config.AI_MODEL_EMBEDDING || process.env.OLLAMA_EMBEDDING_MODEL || 'embeddinggemma:latest' - } + details }) } catch (error: any) { console.error('AI test error:', error) + const config = await getSystemConfig() + const providerType = config.AI_PROVIDER_EMBEDDING || 'ollama' + const details = getProviderDetails(config, providerType) + return NextResponse.json( { success: false, error: error.message || 'Unknown error', stack: process.env.NODE_ENV === 'development' ? error.stack : undefined, - details: { - provider: process.env.AI_PROVIDER || 'ollama', - baseUrl: process.env.OLLAMA_BASE_URL || 'http://localhost:11434', - model: process.env.OLLAMA_EMBEDDING_MODEL || 'embeddinggemma:latest' - } + details }, { status: 500 } ) diff --git a/keep-notes/components/header.tsx b/keep-notes/components/header.tsx index 3d1039c..cee9f82 100644 --- a/keep-notes/components/header.tsx +++ b/keep-notes/components/header.tsx @@ -25,7 +25,6 @@ import { useLabels } from '@/context/LabelContext' import { LabelManagementDialog } from './label-management-dialog' import { LabelFilter } from './label-filter' import { NotificationPanel } from './notification-panel' -import { UserNav } from './user-nav' import { updateTheme } from '@/app/actions/profile' interface HeaderProps { @@ -316,7 +315,6 @@ export function Header({ -
diff --git a/keep-notes/components/sidebar.tsx b/keep-notes/components/sidebar.tsx index 7993902..511f8f6 100644 --- a/keep-notes/components/sidebar.tsx +++ b/keep-notes/components/sidebar.tsx @@ -1,19 +1,32 @@ 'use client' -import { useState, useEffect } from 'react' +import { useState } from 'react' import Link from 'next/link' import { usePathname, useSearchParams } from 'next/navigation' import { cn } from '@/lib/utils' -import { StickyNote, Bell, Archive, Trash2, Tag, ChevronDown, ChevronUp, Settings, User, Shield, Coffee } from 'lucide-react' +import { StickyNote, Bell, Archive, Trash2, Tag, ChevronDown, ChevronUp, Settings, User, Shield, Coffee, LogOut } from 'lucide-react' import { useLabels } from '@/context/LabelContext' import { LabelManagementDialog } from './label-management-dialog' -import { useSession } from 'next-auth/react' +import { useSession, signOut } from 'next-auth/react' +import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar' +import { useRouter } from 'next/navigation' +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuLabel, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from '@/components/ui/dropdown-menu' +import { Button } from '@/components/ui/button' import { LABEL_COLORS } from '@/lib/types' export function Sidebar({ className, user }: { className?: string, user?: any }) { const pathname = usePathname() const searchParams = useSearchParams() + const router = useRouter() const { labels, getLabelColor } = useLabels() const [isLabelsExpanded, setIsLabelsExpanded] = useState(false) const { data: session } = useSession() @@ -27,6 +40,11 @@ export function Sidebar({ className, user }: { className?: string, user?: any }) const displayedLabels = isLabelsExpanded ? labels : labels.slice(0, 5) const hasMoreLabels = labels.length > 5 + const userRole = (currentUser as any)?.role || 'USER' + const userInitials = currentUser?.name + ? currentUser.name.split(' ').map((n: string) => n[0]).join('').toUpperCase().substring(0, 2) + : 'U' + const NavItem = ({ href, icon: Icon, label, active, onClick, iconColorClass }: any) => ( -