Compare commits

...
10 Commits
Author SHA1 Message Date
bruno ab7c227b97 feat: assistant IA - actions instantanées contextuelles, catalogue Toutes les actions & frontmatter complet #106
CI / lint (push) Successful in 1m43s
CI / security (push) Successful in 1m8s
CI / test (push) Successful in 4m4s
CI / build (push) Successful in 2m10s
CI / e2e (push) Successful in 11m51s
2026-09-19 11:07:50 -04:00
bruno b8054665bc fix: guide - bouton telechargement icone seule, diagramme Architecture rendu en image dans le PDF, emoji couleur (Noto) (#105)
CI / lint (push) Successful in 1m39s
CI / security (push) Successful in 1m5s
CI / test (push) Successful in 3m25s
CI / build (push) Successful in 1m18s
CI / e2e (push) Successful in 11m43s
2026-09-18 15:01:14 -04:00
bruno 99a5b735c8 chore: relance CI run 1544 (echec checkout transitoire, 524 Cloudflare)
CI / lint (push) Successful in 1m41s
CI / security (push) Successful in 1m5s
CI / test (push) Successful in 3m27s
CI / build (push) Successful in 1m1s
CI / e2e (push) Successful in 12m6s
2026-09-18 13:49:16 -04:00
bruno fb2d83e9e3 feat: guide d'utilisation - couverture complete, telechargement MD/PDF, section Architecture Mermaid, guide desktop elargi (#105, BUG-067)
CI / lint (push) Successful in 1m40s
CI / security (push) Successful in 1m6s
CI / test (push) Failing after 1m52s
CI / build (push) Skipped
CI / e2e (push) Skipped
2026-09-18 13:06:30 -04:00
bruno 82f6b4a791 fix: icones manquantes dans la table des matieres de la configuration (BUG-066)
CI / lint (push) Successful in 1m40s
CI / security (push) Successful in 1m4s
CI / test (push) Successful in 3m2s
CI / build (push) Successful in 1m1s
CI / e2e (push) Successful in 11m53s
2026-09-18 10:14:41 -04:00
bruno 7e1f5d6852 fix: fixture E2E manquante diagram-app-export.excalidraw (test de regression BUG-064)
CI / lint (push) Successful in 1m38s
CI / security (push) Successful in 1m4s
CI / test (push) Successful in 3m26s
CI / build (push) Successful in 1m5s
CI / e2e (push) Successful in 11m24s
2026-09-18 09:23:22 -04:00
bruno ab766862a3 feat: redesign UI section Cles API IA - recherche, carte defaut, cartes depliables, footer sticky (#104)
CI / lint (push) Successful in 1m47s
CI / security (push) Successful in 1m5s
CI / test (push) Successful in 3m14s
CI / build (push) Successful in 1m1s
CI / e2e (push) Failing after 12m11s
2026-09-18 09:01:20 -04:00
bruno 2bd9dd7535 fix: Editeur Excalidraw - diagramme vide (CSS + appState) et auto-save pendant l'edition (BUG-064, BUG-065) 2026-09-18 08:59:54 -04:00
bruno 7f0f64a42e fix: TOC PDF - forcer le rechargement de l'iframe (BUG-063 complement)
CI / lint (push) Successful in 1m37s
CI / security (push) Successful in 1m15s
CI / test (push) Successful in 3m36s
CI / build (push) Successful in 59s
CI / e2e (push) Successful in 11m13s
2026-09-17 21:16:46 -04:00
bruno f7e068baed fix: viewer PDF (TOC, largeur) et plein ecran assistant (BUG-061 a BUG-063)
CI / lint (push) Successful in 1m36s
CI / security (push) Successful in 1m11s
CI / test (push) Successful in 3m33s
CI / build (push) Successful in 1m2s
CI / e2e (push) Successful in 11m23s
2026-09-17 20:45:38 -04:00
54 changed files with 5028 additions and 396 deletions
+2
View File
@@ -58,6 +58,7 @@ jobs:
node desktop.test.mjs
node toolbar-order.test.mjs
node editor-inline.test.mjs
node ai-quick-actions.test.mjs
else
echo "tests/frontend/node_modules missing - installing jsdom"
npm install --no-audit --no-fund --silent
@@ -74,6 +75,7 @@ jobs:
node desktop.test.mjs
node toolbar-order.test.mjs
node editor-inline.test.mjs
node ai-quick-actions.test.mjs
fi
# ── Tests ─────────────────────────────────────────────────────────
+73 -21
View File
@@ -1,44 +1,93 @@
# AGENTS.md — Instructions obligatoires du dépôt ObsiGate
> Ces instructions s'appliquent à **toute** intervention (humaine ou IA) sur ce dépôt.
> Documentation et réponses en **français**.
## Règle n°1 — Méthode de livraison unique
Avant toute tâche (fonctionnalité, bug, refactor), **lire et appliquer**
[`docs/DELIVERY_WORKFLOW.md`](./docs/DELIVERY_WORKFLOW.md) (Definition of Done).
Aucune tâche n'est terminée avant que sa checklist soit complète **et le CI vert**.
Aucune tâche n'est terminée avant que sa checklist soit complète **et le CI vert**
(jobs `lint`, `test`, `security`, `build`, `e2e` de `.gitea/workflows/ci.yml`).
## Avant de commencer
1. Lire [`docs/ROADMAP.md`](./docs/ROADMAP.md) (travail à venir + index) et
[`docs/ISSUES_TODOLIST.md`](./docs/ISSUES_TODOLIST.md) (bugs).
2. Identifier ou créer l'**ID stable** (`#NN` pour une feature, `BUG-NNN` pour un bug)
et passer son statut à « en cours » **avant** de coder.
2. Identifier ou créer l'**ID stable** (`#NN` pour une feature, `BUG-NNN` pour un bug —
jamais réutilisé) et passer son statut à « en cours » **avant** de coder.
## Architecture (ce qui n'est pas obvious)
- **Backend** : FastAPI/Python 3.11, point d'entrée `backend/main.py` (endpoints + rendu
markdown), index en mémoire (`indexer.py`, `search.py`), watcher (`watcher.py`),
auth dans `backend/auth/`. Pas de base de données : JSON dans `data/`.
- **Frontend** : vanilla JS **zéro framework, zéro build npm** (`frontend/app.js`,
`index.html`, `style.css`). Ne pas ajouter de dépendances npm ni d'étape de build.
- **Desktop** : Tauri (Rust) dans `desktop/` ; `tauri.conf.json` embarque `backend/**` et
`frontend/**` depuis `desktop/` — les scripts de build font le **staging** (copie) avant
`cargo tauri build`, sinon le build échoue.
- **i18n** : tout texte d'interface doit exister en FR **et** EN
(`frontend/locales/fr.json` + `en.json`).
## Vérifications locales (pwsh, à faire passer avant tout commit/push)
```powershell
# Backend (venv à la racine)
.\.venv\Scripts\python.exe -m pytest tests/
.\.venv\Scripts\python.exe -m ruff check backend/
.\.venv\Scripts\python.exe -m mypy backend/ --ignore-missing-imports
# Frontend : scripts Node à exécuter directement (pas de runner)
node tests/frontend/validate-imports.mjs
node tests/frontend/unit.test.mjs
# Tests JSDOM : node_modules dans tests/frontend/ (npm install là-bas si absent), ex :
node tests/frontend/pane-manager.test.mjs
# E2E (si UI touchée, ~5 min) : reproduit le job CI e2e (port 2029, auth désactivée)
npm run test:e2e # prérequis : uv, Node >= 20, npx playwright install chromium
bash scripts/run-e2e-local.sh -g "nom du test" # filtre / --headed
```
- Un seul test backend : `.\.venv\Scripts\python.exe -m pytest tests/test_search.py -q`.
- **Sélection E2E** : vérifier chaque sélecteur dans le DOM réel avant de l'utiliser dans un
test ; tout test nouveau/modifié doit passer en local avant push ; pas de contournement
qui masque la flakiness (`waitForTimeout` arbitraires, fallbacks silencieux).
- La suite E2E doit finir à **100 %** sans s'appuyer sur les retries. Jamais de `git push`
avant que les 5 étapes locales soient vertes.
## Version & hooks (pièges)
- `VERSION` (racine) = **source unique de vérité** (SemVer), incrémenté **automatiquement à
chaque commit** par le hook `.githooks/prepare-commit-msg` — `feat` → mineur,
`!:` / `BREAKING CHANGE` → majeur, sinon correctif. Le même commit resynchronise
`package.json`, le desktop Tauri, `README.md`/`README.fr.md`, `docs/ROADMAP.md` et publie
la section `[Unreleased]` du `CHANGELOG.md` en `[X.Y.Z] — date` ; tag `vX.Y.Z` créé au
commit, publié au push (`push.followTags`).
- Hooks **obligatoires**, à installer une fois par clone : `scripts/install-hooks.sh`
(sinon la version ne suit plus et le CI échoue via le garde-fou `tests/test_version.py`).
- Le rattachement des fichiers de bump se fait par un `--amend` immédiat : **le SHA affiché
par `git commit` change** — ne pas s'y fier.
- Commit sans incrément (exceptionnel) : `SKIP_VERSION_BUMP=1 git commit …`.
- Ne jamais réécrire une version déjà publiée dans le CHANGELOG ; jamais de détail dupliqué
entre Roadmap et CHANGELOG.
## À la fin de chaque tâche (obligatoire)
- Ajouter/mettre à jour les **tests unitaires**.
- Vérifications locales vertes : `pytest`, `ruff`, `mypy`, tests frontend (`E2E` si UI).
- Mettre à jour la documentation requise : `CHANGELOG.md` (`[Unreleased]`), `docs/ROADMAP.md`
(statut + index), fiche `docs/features/` **ou** `docs/archive/`, `docs/ISSUES_TODOLIST.md`,
guide utilisateur i18n FR/EN + README si impact utilisateur.
- **Commit** conventionnel référençant l'ID, puis **push**.
- Version : le fichier VERSION (racine du dépôt) est la **source unique de
vérité (MAJEUR.MINEUR.CORRECTIF), incrémenté automatiquement à chaque commit** par le hook
.githooks/prepare-commit-msg — feat → mineur, !: / BREAKING CHANGE → majeur, sinon
correctif. Le même commit resynchronise package.json, le desktop Tauri, README.md/
README.fr.md, docs/ROADMAP.md et publie la section [Unreleased] du CHANGELOG.md en
[X.Y.Z] — date ; le tag vX.Y.Z est créé au commit et publié au push (push.followTags).
Hooks à installer une fois par clone : scripts/install-hooks.sh. Garde-fou :
tests/test_version.py (détail : docs/DELIVERY_WORKFLOW.md §7).
- Vérifier le **CI Gitea vert** (jobs `lint`, `test`, `security`, `build`, `e2e`).
- Tests unitaires ajoutés/mis à jour (correctif sans test de non-régression = pas terminé).
- Toutes les vérifications locales ci-dessus vertes (`E2E` si UI).
- Documentation mise à jour : `CHANGELOG.md` (`[Unreleased]`), `docs/ROADMAP.md` (statut +
index), fiche `docs/features/` **ou** `docs/archive/`, `docs/ISSUES_TODOLIST.md` (si bug),
guide utilisateur i18n FR/EN + README si impact utilisateur, docstrings +
`response_model` si API.
- **Commit** conventionnel référençant l'ID (`feat: … #12`), puis **push** et **CI vert**.
## Cartographie documentaire
| Sujet | Fichier |
|---|---|
| Méthode de livraison / DoD | `docs/DELIVERY_WORKFLOW.md` |
| Version livrée (source unique) | VERSION + scripts/bump_version.py |
| Version livrée (source unique) | `VERSION` + `scripts/bump_version.py` |
| Travail à venir + index | `docs/ROADMAP.md` |
| Historique des versions | `CHANGELOG.md` |
| Conception par feature | `docs/features/<slug>.md` |
@@ -50,5 +99,8 @@ Aucune tâche n'est terminée avant que sa checklist soit complète **et le CI v
## Conventions
- Commits : `type: description` — `feat`, `fix`, `perf`, `refactor`, `docs`, `style`, `chore`, `test`.
- **Ne jamais** committer de secrets, clés ou tokens.
- Réponses et documentation en **français** ; respecter le style du code existant.
- Sécurité : tout chemin fichier fourni par l'utilisateur passe par `_resolve_safe_path()`.
- **Ne jamais** committer de secrets, clés ou tokens (`.env` jamais committé ; secrets dans
`data/api_keys.json` ou variables `OBSIGATE_*`).
- Respecter le style du code existant (ruff/mypy 0 erreur ; CSS variables, pas de couleurs
hardcodées ; `safeCreateIcons()` plutôt que `lucide.createIcons()` direct).
+211 -1
View File
@@ -6,7 +6,7 @@ Format basé sur [Keep a Changelog](https://keepachangelog.com/fr/1.1.0/),
et [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
> **En cours de développement** : les changements à venir sont listés dans la section
> [Unreleased](#unreleased). La dernière version livrée est **2.11.3**.
> [Unreleased](#unreleased). La dernière version livrée est **2.14.0**.
---
@@ -14,6 +14,216 @@ et [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
---
## [2.14.0] — 2026-09-19
### Ajouté
- **#106 - Assistant IA : actions instantanées contextuelles + catalogue de prompts** :
la zone d'accueil remplace les 3 suggestions statiques par des **actions suggérées
selon le contexte détecté** (sélection dans l'éditeur → concis/corriger/expliquer ;
fichier de code → expliquer/bugs/tests ; 2+ docs → fusionner/comparer/frictions ;
1 doc → résumé 3 points/checklist/frontmatter ; répertoire ou général sinon), avec
badge de contexte dans l'en-tête. Un bouton **« Toutes les actions »** ouvre un
tiroir catalogue (recherche instantanée, 6 catégories, 25 actions i18n FR/EN).
Nouveau prompt **« Générer le frontmatter YAML »** au format complet du vault
(titre, auteur, dates ISO-8601, tags, aliases, booléens, NomDeVoute, Description)
et **« Mettre à jour le frontmatter »** (conserve les champs existants, actualise
`modification_date`, recalcule tags/aliases/Description, complète les manquants) —
tous deux basculent en mode agent et appliquent le résultat via la carte de
confirmation. Détail : [features/ai-quick-actions.md](./features/ai-quick-actions.md).
---
## [2.13.1] — 2026-09-18
---
## [2.13.0] — 2026-09-18
### Ajouté
- **#105 - Guide d'utilisation : audit de couverture, téléchargement Markdown/PDF,
section Architecture** : le guide intégré est aligné sur l'application réelle après
~35 features livrées. Huit nouvelles sections — **🏗️ Architecture** (diagramme Mermaid
des grandes composantes : clients SPA/PWA/Tauri → serveur FastAPI REST, index de
recherche, rendu markdown, IA, MCP, WebSocket, webhooks → vaults, `data/*.json`,
backups), **📊 Diagrammes** (Mermaid : zoom, plein écran, copie SVG/code, thèmes),
**⭐ Bibliothèque** (signets, recherches sauvegardées, backlinks & graphe, conflits
Syncthing, pièces jointes), **📴 Hors-ligne** (PWA, file d'attente IndexedDB, replay,
watcher), **👥 Collaboration** (Yjs/CRDT, curseurs awareness), **🖥️ Desktop** (Tauri,
updater signé, assistant premier lancement), **🔌 API** (OpenAPI 3.1 : `/docs`,
`/redoc`, `/api`, `/openapi.json`, auth Bearer/cookie, serveur MCP, automatisation)
et **🌍 Multilingue** — plus des compléments dans les sections existantes (recherche
sémantique hybride, notifications web push, export PDF, export HTML/ePub/ZIP,
anti-doublons d'upload, vue multi-panneaux, MFA TOTP/WebAuthn, tableau de bord
admin). Nouveau **`GET /api/guide/download?format=md|pdf&lang=fr|en`** (tag OpenAPI
« Guide ») : le document est généré depuis la modale d'aide réelle et les locales,
il reflète donc exactement le guide affiché, dans la langue de l'utilisateur ;
boutons **Markdown** et **PDF** ajoutés dans l'en-tête du guide. En **desktop**
(Tauri, `body.desktop-mode`) et sur grand écran web, le guide s'élargit
(conteneur jusqu'à 1760 px, contenu 1280–1440 px) pour une lecture confortable.
Source de vérité du nouveau contenu : `scripts/guide_content.py` (locales générées,
jamais éditées à la main). Tests : `tests/test_guide.py` (11).
### Modifié (ajustements retour utilisateur sur #105)
- Boutons de téléchargement du guide : **icônes seules** (plus de libellé « Markdown »/
« PDF »), tooltip i18n explicite sur chaque bouton.
- PDF du guide : le bloc Mermaid de la section Architecture est converti en **diagramme
rendu** (PNG pré-rendu commité via `scripts/build_guide_diagrams.py` +
`scripts/render_guide_diagram.mjs`, inséré par `diagram_png_for()`), au lieu du code
brut ; le Markdown garde le fenced ` ```mermaid ` (copiable).
- PDF du guide : emoji rendus **en couleur** au lieu de rectangles — `fonts-noto-color-emoji`
ajouté à l'image Docker et `"Noto Color Emoji"` en fin de pile de polices du PDF
(la TOC était correcte car elle utilise DejaVu, qui n'a pas les emoji pleine chasse).
### Corrigé
- **BUG-067 - Guide : entrée « 📱 Mobile » morte** : le sommaire pointait vers
`#help-mobile-editor`, section inexistante (l'édition mobile n'était qu'un `<h3>`
de la section Édition). Le bloc est devenu une section dédiée ancrée ; l'ancre
`#help-ia` (également morte) a été corrigée en `#help-ai` et un attribut
`data-i18n-placeholder` dupliqué nettoyé. Garde-fou : `test_guide_nav_has_no_dead_anchors`.
---
## [2.12.2] — 2026-09-18
### Corrigé
- **BUG-066 — Configuration : icônes manquantes dans la table des matières** :
les entrées « Fichiers cachés » et « Partages publics » du sommaire de la page de
configuration n'affichaient pas d'icône (les titres de section, eux, en avaient une).
Les libellés i18n `config.section_hidden` (🗂️) et `config.section_shares` (📤) sont
alignés sur leurs titres de section, en FR **et** EN. Test de non-régression ajouté
dans `tests/frontend/unit.test.mjs` (toutes les entrées du sommaire doivent porter une
icône dans les deux langues).
---
## [2.12.1] — 2026-09-18
---
## [2.12.0] — 2026-09-18
### Ajouté
- **#104 - Configuration : redesign UI de la section « 🤖 Clés API Intelligence Artificielle »** :
la longue liste plate de champs devient une interface structurée et dépliable —
1. **En-tête de section** : titre + sous-titre explicatifs et une **barre de recherche**
(`#cfg-ai-search`) pour filtrer les fournisseurs (normalisée, insensible à la casse et aux
accents), avec état vide « Aucun fournisseur ne correspond ».
2. **Carte « Configuration par défaut »** visuellement distincte : grille **2 colonnes**
fournisseur / modèle par défaut, et **capacités du modèle rendues en badges colorés**
(nouveau `renderCapabilityBadges()` dans `frontend/js/ai.js`, uniquement les capacités
actives) au lieu des cases à cocher.
3. **Fournisseurs d'API en cartes dépliables** (rendu dynamique depuis `AI_PROVIDER_NAMES` par
`_renderAIProviderCards()`, `frontend/js/config.js`) : état replié = logo (initiale), nom,
**badge de statut** (« Configuré » vert / « Non configuré » gris) et **corbeille discrète**
pour supprimer la clé (visible uniquement si configurée, confirmation conservée) ; état
déplié = libellés au-dessus des champs, **API key à 60 % / modèle à 40 %** (grille `3fr 2fr`).
Les boutons « Configuré/Supprimer » redondants à l'intérieur des champs disparaissent — le
statut vit désormais uniquement dans l'en-tête de la carte.
4. **Barre d'actions** : « Sauvegarder » (primaire) et « Tester » (outline) dans un footer
**sticky** en bas de section, toujours accessible pendant le défilement, avec le statut de
test à côté.
Styles `.ai-keys-*` / `.ai-provider-*` en variables CSS (profondeur fond/carte, espacement
généreux, chevron animé, focus visible, responsive 1 colonne < 600 px) ; textes i18n FR/EN
(`config.ai_*`). Les ID d'éléments (`cfg-<provider>-key/model/badge/delete`) et le
comportement de sauvegarde/test/suppression restent inchangés (rétrocompatible pickers IA).
Tests : `tests/frontend/config-ai-keys.test.mjs` (7 — rendu, badges, bascule, filtre, save,
suppression, badges de capacités).
---
## [2.11.6] — 2026-09-18
### Corrigé
- **BUG-064 - Éditeur Excalidraw : le diagramme ne s'affiche jamais (canvas vide)** — deux
causes cumulées :
1. **La feuille de style d'Excalidraw n'était jamais chargée** (`@excalidraw/excalidraw` exige
un import CSS explicite). Sans elle, l'éditeur est non stylisé et `.excalidraw` n'a aucune
hauteur fixe : la boucle de redimensionnement d'Excalidraw fait grossir le canvas jusqu'au
plafond codé en dur de `2^25` (33 554 432 px), que le navigateur ne peut pas dessiner → scène
blanche. Correctifs : `<link>` vers `…/@excalidraw/[email protected]/dist/prod/index.css` dans
`frontend/excalidraw-editor.html` et ajout de `https://esm.sh` à `style-src` de la CSP
(`backend/main.py`).
2. `appState.collaborators` est une `Map` sérialisée en objet JSON (`{}`) par l'app Excalidraw /
le plugin Obsidian ; réinjectée via `initialData`, Excalidraw 0.18 appelait `.forEach()` dessus
et plantait (`e.appState.collaborators.forEach is not a function`). `sanitizeAppState()` la
reconvertit en `Map` et écarte la géométrie de viewport importée (`width`, `height`,
`offsetLeft`, `offsetTop`) pour les deux formats (`.excalidraw` et `.excalidraw.md`).
Tests de non-régression : `tests/frontend/excalidraw-viewer.test.mjs` (CSS lié + CSP),
`tests/test_security_hardening.py::TestCspExcalidrawStylesheet`, `tests/e2e/excalidraw.spec.js`
(hauteur de canvas bornée) + fixtures `test_vault/diagram-app-export.excalidraw`.
- **BUG-064 (complément) - Éditeur Excalidraw : pleine largeur quand la navigation est masquée** :
la règle `.sidebar.hidden ~ .content-wrapper .content-area { max-width: 1200px }` (colonne de
lecture centrée) s'appliquait aussi au viewer Excalidraw. Ajout de
`.content-area:has(iframe[src*="excalidraw-editor.html"])` en `max-width: none; margin: 0`,
comme pour les viewers PDF/image (BUG-062). Fichier : `frontend/style.css`.
- **BUG-065 - Excalidraw : l'auto-save rechargeait la page en pleine édition** : chaque
modification déclenchait, 2 s plus tard, un `PUT /api/file/…/save` ; l'écriture émettait
`index_updated` (SSE) qui re-rendait la vue et **recréait l'iframe** — un refresh visible qui
interrompait le dessin. L'auto-save est supprimée (`frontend/js/excalidraw-viewer.js`) :
sauvegarde explicite par le bouton « 💾 Save » ou `Ctrl+S`. En complément, `reloadExternalWrite`
ne re-rend plus la vue quand un iframe Excalidraw est déjà ouvert sur le fichier
(`iframe[data-excalidraw-*]`), et le badge « Modified » ne se déclenche plus sur les
changements d'`appState` (resize, zoom) mais uniquement sur le contenu (signature des éléments).
- **#78 (complément) - Bouton plein écran pour les diagrammes Excalidraw** : nouveau bouton
`#btn-fullscreen` dans la barre d'outils de l'éditeur (`frontend/excalidraw-editor.html`) qui
bascule le mode plein écran natif ; l'iframe est créée avec `allow="fullscreen" allowfullscreen`
(`frontend/js/excalidraw-viewer.js`). Fichiers : `frontend/excalidraw-editor.html`,
`frontend/js/excalidraw-viewer.js`, `tests/frontend/excalidraw-viewer.test.mjs`.
- **#78 (complément) - Barre d'outils Excalidraw en icônes, verticale à droite** : les boutons
Save / PNG / SVG / plein écran passent en **icônes seules** (34×34 px) dans une colonne
**collée au bord droit** (`right: 0`), débutant à `45%` de la hauteur, empilée verticalement,
avec infobulles et `aria-label`. L'icône du bouton Save devient une coche après une sauvegarde
réussie. Fichier : `frontend/excalidraw-editor.html`.
---
## [2.11.5] — 2026-09-17
### Corrigé
- **BUG-063 (complément) — Viewer PDF : la table des matières ne déplaçait toujours pas la
page** : le premier correctif réassignait `iframe.src` avec le seul fragment `#page=N`, ce qui
ne change que le fragment → navigation *same-document* que le lecteur PDF natif ignore (il
n'applique `#page=N` qu'au chargement). Diagnostic en Chrome *headful* par comparaison de
captures. `navigatePdfToPage()` ajoute désormais un paramètre de query horodaté
(`&_pdfpage=<ts>#page=N`) pour forcer un vrai rechargement de l'iframe. Fichiers :
`frontend/js/viewer.js`, `tests/frontend/pdf-viewer.test.mjs`, `tests/e2e/pdf-viewer.spec.js`.
---
## [2.11.4] — 2026-09-17
### Corrigé
- **BUG-061 — Assistant IA : le bouton « Plein écran » n'agrandissait plus le panneau** : la
largeur du panneau est écrite en style inline par la poignée de redimensionnement (et par la
largeur persistée en `localStorage`) ; cet inline l'emportait sur la règle
`.bookslm-panel.fullscreen { width: 100vw }`, donc le panneau restait à sa largeur courante.
La règle plein écran est désormais prioritaire (`!important`). Fichier : `frontend/style.css`.
- **BUG-062 — Viewer PDF : largeur incomplète quand la navigation est masquée** : la règle de
colonne de lecture centrée (`.sidebar.hidden … { max-width: 1200px }`) s'appliquait aussi aux
viewers plein cadre. Les conteneurs PDF et image sont maintenant exemptés
(`:has(.pdf-viewer-container)` / `:has(.image-viewer-container)` → `max-width: none`). Fichier :
`frontend/style.css`.
- **BUG-063 — Viewer PDF : la table des matières ne naviguait pas** : les liens faisaient
`contentWindow.location.hash = 'page=N'`, mais le lecteur PDF natif vit dans une fenêtre
`about:blank` et l'affectation n'atteignait jamais le document. Nouveau helper
`navigatePdfToPage()` qui recharge l'iframe avec le fragment `#page=N` ; les entrées portent un
`data-page` et sont câblées par des écouteurs (plus d'`onclick` inline). Fichiers :
`frontend/js/viewer.js`, `frontend/style.css`.
- **Tests** : `tests/frontend/ai.test.mjs` (+1), `tests/frontend/pdf-viewer.test.mjs` (TOC, plein
largeur), `tests/e2e/pdf-viewer.spec.js` (TOC `#page=N`, largeur, fixture
`test_vault/sample-pdf-toc.pdf`).
---
## [2.11.3] — 2026-09-17
### Corrigé
+1 -1
View File
@@ -24,7 +24,7 @@ COPY --from=builder /install /usr/local
# WeasyPrint runtime dependencies
RUN apt-get update \
&& apt-get install -y --no-install-recommends libpango-1.0-0 libpangocairo-1.0-0 shared-mime-info \
&& apt-get install -y --no-install-recommends libpango-1.0-0 libpangocairo-1.0-0 shared-mime-info fonts-noto-color-emoji \
&& apt-get clean \
&& rm -rf /var/lib/apt/lists/*
+4 -3
View File
@@ -4,7 +4,7 @@
**Porte d'entrée web ultra-léger pour vos vaults Obsidian** — Accédez, naviguez et recherchez dans toutes vos notes Obsidian depuis n'importe quel appareil via une interface web moderne et responsive.
[![Version](https://img.shields.io/badge/Version-2.11.3-blue.svg)]()
[![Version](https://img.shields.io/badge/Version-2.14.0-blue.svg)]()
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Docker](https://img.shields.io/badge/Docker-Ready-blue.svg)](https://www.docker.com/)
[![Python](https://img.shields.io/badge/Python-3.11+-green.svg)](https://www.python.org/)
@@ -57,6 +57,7 @@
- **🤖 AI Editor intégré** — Éditeur CodeMirror 6 avec toolbar IA : amélioration, correction, traduction, génération, réécriture personnalisée, toolbox (liste, tableau, frontmatter, canvas) — multi-provider DeepSeek/OpenRouter/Gemini
- **🧩 Serveur MCP & agent IA** — Serveur Model Context Protocol intégré (`/mcp`) et assistant avec function calling : lisez, cherchez et modifiez vos vaults depuis Claude Desktop, Cursor… avec confirmations two-step, permissions par vault, rate limiting et redaction des secrets ([guide](docs/MCP_GUIDE.md))
- **👥 Collaboration temps réel** — Édition simultanée d'un même document (Yjs/CRDT) : curseurs distants colorés, indicateur de présence, fusion sans conflit, reconnexion automatique et persistance serveur ([détail](docs/features/collaboration.md))
- **📖 Guide d'utilisation intégré** — Aide complète en FR/EN accessible depuis le menu Options : interface, navigation, recherche, fichiers, IA, sécurité, API & intégrations (OpenAPI, MCP), hors-ligne, collaboration, desktop, plus une section **Architecture** avec diagramme Mermaid ; téléchargeable en **Markdown** et **PDF** dans la langue courante ([détail](docs/features/guide-coverage-105.md))
- **📱 Éditeur mobile natif** — Édition optimisée pour le tactile : barre d'outils Markdown flottante (gras/italique/code/liste/lien), bouton « Coller » persistant (contournement iOS), zoom par pincement et hauteur ajustable, raccourcis swipe (liens entrants / table des matières) et mode lecture plein écran avec navigation entre fichiers ([détail](docs/features/mobile-editor.md))
- **🗺️ Vue graphe interactive** — Canvas force-directed avec Barnes-Hut O(n log n), filtres (tag, type), profondeur, mode focus, historique de navigation ←→↑, export PNG, aperçu au survol (Ctrl+click)
- **🗂️ Multi-vault** : Visualisez plusieurs vaults Obsidian simultanément
@@ -926,8 +927,8 @@ Ce projet est sous licence **MIT** — voir le fichier [LICENSE](LICENSE) pour l
## 📝 Changelog
Consultez le [CHANGELOG.md](./CHANGELOG.md) pour l'historique complet de toutes les versions (v1.0.0 → v2.11.3).
Consultez le [CHANGELOG.md](./CHANGELOG.md) pour l'historique complet de toutes les versions (v1.0.0 → v2.14.0).
---
*Projet : ObsiGate | Version : 2.11.3 | Dernière mise à jour : Juin 2026*
*Projet : ObsiGate | Version : 2.14.0 | Dernière mise à jour : Juin 2026*
+4 -3
View File
@@ -2,7 +2,7 @@
**Ultra-light web gateway for your Obsidian vaults** — Access, browse, and search all your Obsidian notes from any device via a modern, responsive web interface.
[![Version](https://img.shields.io/badge/Version-2.11.3-blue.svg)]()
[![Version](https://img.shields.io/badge/Version-2.14.0-blue.svg)]()
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Docker](https://img.shields.io/badge/Docker-Ready-blue.svg)](https://www.docker.com/)
[![Python](https://img.shields.io/badge/Python-3.11+-green.svg)](https://www.python.org/)
@@ -50,6 +50,7 @@
- **🤖 Integrated AI Editor** — CodeMirror 6 editor with AI toolbar: improve, correct, translate, generate, custom rewrite, toolbox (list, table, frontmatter, canvas) — multi-provider DeepSeek/OpenRouter/Gemini
- **🧩 MCP Server & AI Agent** — Built-in Model Context Protocol server (`/mcp`) and tool-calling assistant: read, search and edit your vaults from Claude Desktop, Cursor… with two-step confirmations, per-vault permissions, rate limiting and secret redaction ([guide](docs/MCP_GUIDE.md))
- **👥 Real-time Collaboration** — Simultaneous editing of the same document (Yjs/CRDT): colored remote cursors, presence indicator, conflict-free merge, automatic reconnection and server-side persistence ([details](docs/features/collaboration.md))
- **📖 Built-in User Guide** — Complete FR/EN help from the Options menu: interface, navigation, search, files, AI, security, API & integrations (OpenAPI, MCP), offline, collaboration, desktop, plus an **Architecture** section with a Mermaid diagram; downloadable as **Markdown** and **PDF** in the current language ([details](docs/features/guide-coverage-105.md))
- **📱 Native Mobile Editor** — Touch-optimised editing: floating Markdown toolbar (bold/italic/code/list/link), persistent Paste button (iOS workaround), pinch-zoom font & adjustable height, swipe shortcuts (backlinks / table of contents) and a full-screen reading mode with page navigation ([details](docs/features/mobile-editor.md))
- **🗺️ Interactive Graph View** — Canvas force-directed with Barnes-Hut O(n log n), filters (tag, type), depth, focus mode, navigation history ←→↑, export PNG, preview on hover (Ctrl+click)
- **🗂️ Multi-vault** : View multiple Obsidian vaults simultaneously
@@ -1095,8 +1096,8 @@ This project is licensed under the **MIT License** - see the [LICENSE](LICENSE)
## 📝 Changelog
See [CHANGELOG.md](./CHANGELOG.md) for the complete version history (v1.0.0 → v2.11.3).
See [CHANGELOG.md](./CHANGELOG.md) for the complete version history (v1.0.0 → v2.14.0).
---
*Project: ObsiGate | Version: 2.11.3 | Last updated: May 2026*
*Project: ObsiGate | Version: 2.14.0 | Last updated: May 2026*
+1 -1
View File
@@ -1 +1 @@
2.11.3
2.14.0
Binary file not shown.

After

Width:  |  Height:  |  Size: 186 KiB

+545
View File
@@ -0,0 +1,545 @@
"""Génération du Guide d'utilisation téléchargeable en Markdown et PDF (#105).
Source unique de vérité : la modale ``#help-modal`` de ``frontend/index.html``
(comme dans l'application) + les blocs ``data-i18n`` résolus dans les locales
``frontend/locales/{fr,en}.json`` — le téléchargement reflète donc exactement
ce que voit l'utilisateur, dans sa langue.
Le Markdown est produit par un convertisseur HTML→MD minimal (stdlib) ; le
PDF passe par le moteur d'export existant (WeasyPrint) avec repli reportlab
quand les bibliothèques natives GTK manquent (Windows).
"""
from __future__ import annotations
import datetime
import hashlib
import html
import json
import logging
import re
from html.parser import HTMLParser
from pathlib import Path
logger = logging.getLogger("obsigate.guide")
ROOT = Path(__file__).resolve().parent.parent
INDEX_HTML = ROOT / "frontend" / "index.html"
LOCALES_DIR = ROOT / "frontend" / "locales"
VERSION_FILE = ROOT / "VERSION"
DIAGRAMS_DIR = ROOT / "backend" / "assets" / "guide_diagrams"
def diagram_png_for(code: str) -> Path | None:
"""Chemin du PNG pré-rendu (scripts/build_guide_diagrams.py) pour un code
Mermaid, ou None. Le hash doit rester synchrone avec le script de build :
sha1(unescape(code).strip())[:16]."""
normalized = html.unescape(code).strip()
sha = hashlib.sha1(normalized.encode("utf-8")).hexdigest()[:16]
png = DIAGRAMS_DIR / (sha + ".png")
return png if png.exists() else None
# Éléments décoratifs exclus des exports
_SKIP_CLASSES = {"help-hero-visual", "editor-modal", "help-nav"}
# En-tête HTML du guide (mode lecture)
_HEADER_BLOCK = "ObsiGate User Guide"
class Node:
"""Noeud DOM minimal (stdlib only)."""
__slots__ = ("attrs", "children", "parent", "tag")
def __init__(self, tag: str, attrs: dict[str, str | None], parent: Node | None = None):
self.tag = tag
self.attrs = attrs
self.children: list[Node | str] = []
self.parent = parent
def cls(self) -> str:
return self.attrs.get("class") or ""
def i18n(self) -> str | None:
v = self.attrs.get("data-i18n")
return v if isinstance(v, str) else None
def find_all(self, tag: str) -> list[Node]:
out: list[Node] = []
for c in self.children:
if isinstance(c, Node):
if c.tag == tag:
out.append(c)
out.extend(c.find_all(tag))
return out
_VOID_TAGS = {"br", "img", "hr", "input", "meta", "link"}
class _TreeBuilder(HTMLParser):
"""Constructeur d'arbre tolérant (ignore les balises orphelines)."""
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.root = Node("#root", {})
self.cur = self.root
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
a = {k: v for k, v in attrs}
node = Node(tag, a, self.cur)
self.cur.children.append(node)
if tag not in _VOID_TAGS:
self.cur = node
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
a = {k: v for k, v in attrs}
self.cur.children.append(Node(tag, a, self.cur))
def handle_endtag(self, tag: str) -> None:
n: Node | None = self.cur
while n is not None and n.tag != tag:
n = n.parent
if n is not None and n.parent is not None:
self.cur = n.parent
def handle_data(self, data: str) -> None:
self.cur.children.append(data)
# ---------------------------------------------------------------------------
# Extraction / cache
# ---------------------------------------------------------------------------
_cache: dict[tuple[str, str], tuple[tuple[float, int, float, int], bytes]] = {}
def _read_index_html() -> str:
return INDEX_HTML.read_text(encoding="utf-8")
def _guide_fragment(index_html: str) -> str:
"""Le HTML de #help-modal…help-content jusqu'au footer du guide."""
start = index_html.index('id="help-modal"')
cstart = index_html.index('<div class="help-content">', start)
end = index_html.index('<div class="help-footer">', cstart)
return index_html[cstart:end]
def _locale_strings(lang: str) -> dict[str, str]:
path = LOCALES_DIR / (lang if lang in ("fr", "en") else "fr")
return json.loads(Path(path).with_suffix(".json").read_text(encoding="utf-8"))
def _signature() -> tuple[float, int, float, int]:
st = INDEX_HTML.stat()
lt = (LOCALES_DIR / "fr.json").stat()
return (st.st_mtime, st.st_size, lt.st_mtime, lt.st_size)
def _app_version() -> str:
try:
return VERSION_FILE.read_text(encoding="utf-8").strip() or "dev"
except OSError:
return "dev"
# ---------------------------------------------------------------------------
# Résolution i18n : un node portant data-i18n est REMPLACÉ par le contenu
# (HTML) de la locale — exactement comme _applyDOM() dans le navigateur.
# ---------------------------------------------------------------------------
def _resolve_i18n(node: Node, loc: dict[str, str]) -> list[Node | str]:
"""Retourne les children effectifs d'un node (locale si data-i18n[-html])."""
key = node.i18n() or node.attrs.get("data-i18n-html")
if not isinstance(key, str):
return node.children
value = loc.get(key)
if value is None:
# clé absente de la locale : garder le texte FR inline de index.html
return node.children
tb = _TreeBuilder()
tb.feed(f"<span>{value}</span>")
span = tb.root.children[0]
assert isinstance(span, Node)
return span.children
# ---------------------------------------------------------------------------
# Markdown
# ---------------------------------------------------------------------------
_WS_RE = re.compile(r"[ \t]*\n[ \t]*")
def _collapse(text: str) -> str:
return _WS_RE.sub(" ", text).strip()
def _md_inline(node: Node | str, loc: dict[str, str]) -> str:
if isinstance(node, str):
return _collapse(node)
tag = node.tag
kids = _resolve_i18n(node, loc)
inner = "".join(_md_inline(c, loc) for c in kids)
if tag == "br":
return " "
if tag in ("strong", "b"):
t = inner.strip()
return f"**{t}**" if t else ""
if tag in ("em", "i"):
if node.cls().startswith("lucide") or tag == "i" and not inner.strip():
return ""
t = inner.strip()
return f"*{t}*" if t else ""
if tag == "code":
t = inner.replace("`", "'").strip()
return f"`{t}`" if t else ""
if tag == "kbd":
t = inner.strip()
return f"`{t}`" if t else ""
if tag == "a":
href = node.attrs.get("href") or ""
t = inner.strip()
if href.startswith("http") and t:
return f"[{t}]({href})"
return t
if tag == "img":
alt = node.attrs.get("alt") or ""
return f"![{alt}]"
return inner
def _md_block(node: Node | str, out: list[str], loc: dict[str, str], depth: int = 0) -> None:
"""Remplit ``out`` (bloc courant) — ``pending`` gère listes imbriquées."""
if isinstance(node, str):
t = _collapse(node)
if t:
out.append(t)
return
if any(c in node.cls().split() for c in _SKIP_CLASSES):
return
tag = node.tag
if tag == "pre":
raw = _pre_text(node)
lang = "mermaid" if "mermaid" in raw[:40] or "language-mermaid" in _pre_classes(node) else ""
out.append(f"```{lang}\n{raw.rstrip()}\n```")
return
kids = _resolve_i18n(node, loc)
if tag in ("h1", "h2", "h3", "h4", "h5", "h6"):
level = int(tag[1])
text = _collapse("".join(_md_inline(c, loc) for c in kids))
if text:
out.append("#" * level + " " + text)
return
if tag == "p":
text = _collapse("".join(_md_inline(c, loc) for c in kids))
if text:
out.append(text)
return
if tag in ("ul", "ol"):
_md_list(kids, out, loc, tag, depth)
return
if tag == "table":
_md_table(node, out, loc)
return
# conteneurs neutres (section, div, span de bloc, li imbriqué…)
for c in kids:
_md_block(c, out, loc, depth)
def _md_list(items: list[Node | str], out: list[str], loc: dict[str, str], kind: str, depth: int) -> None:
n = 0
for li in items:
if isinstance(li, str):
continue
if li.tag == "li":
n += 1
marker = "- " if kind == "ul" else f"{n}. "
text_parts: list[str] = []
nested: list[Node] = []
for c in li.children:
if isinstance(c, Node) and c.tag in ("ul", "ol"):
nested.append(c)
else:
text_parts.append(_md_inline(c, loc))
line = _collapse("".join(text_parts))
if line:
out.append(" " * depth + marker + line)
for sub in nested:
_md_list(sub.children, out, loc, sub.tag, depth + 1)
elif li.tag in ("ul", "ol"):
_md_list(li.children, out, loc, li.tag, depth)
def _md_table(node: Node, out: list[str], loc: dict[str, str]) -> None:
rows = node.find_all("tr")
if not rows:
return
grid: list[list[str]] = []
for tr in rows:
cells = []
for td in tr.children:
if isinstance(td, Node) and td.tag in ("td", "th"):
cells.append(_collapse("".join(_md_inline(c, loc) for c in td.children)).replace("|", "\\|") or " ")
if cells:
grid.append(cells)
if not grid:
return
width = max(len(r) for r in grid)
grid = [r + [" "] * (width - len(r)) for r in grid]
out.append("| " + " | ".join(grid[0]) + " |")
out.append("|" + "|".join([" --- "] * width) + "|")
for r in grid[1:]:
out.append("| " + " | ".join(r) + " |")
def _pre_text(node: Node) -> str:
"""Texte brut préservé d'un <pre> (les locales n'y touchent pas)."""
buf: list[str] = []
def walk(n: Node | str) -> None:
if isinstance(n, str):
buf.append(n)
return
for c in n.children:
walk(c)
walk(node)
return "".join(buf).strip("\n")
def _pre_classes(node: Node) -> str:
cls = node.cls()
for c in node.find_all("code"):
cls += " " + c.cls()
return cls
def build_guide_markdown(lang: str = "fr") -> bytes:
"""Guide complet en Markdown (UTF-8), dans la langue demandée."""
index_html = _read_index_html()
loc = _locale_strings(lang)
tree = _TreeBuilder()
tree.feed(_guide_fragment(index_html))
root = tree.root.children[0]
assert isinstance(root, Node)
blocks: list[str] = []
content = _guide_title_fr if lang == "fr" else _guide_title_en
blocks.append("# " + content)
for section in root.find_all("section"):
_md_block(section, blocks, loc)
blocks.append(
"---\n\n"
+ _export_footer(lang)
)
md = "\n\n".join(b for b in blocks if b.strip()) + "\n"
return md.encode("utf-8")
_guide_title_fr = "Guide d'utilisation ObsiGate"
_guide_title_en = "ObsiGate User Guide"
def _export_footer(lang: str) -> str:
loc = _locale_strings(lang)
template = loc.get("guide105.export_footer", "")
if "%s" not in template and "{" not in template:
template = "ObsiGate {version}"
today = datetime.datetime.now(tz=datetime.timezone.utc).date().isoformat()
return _collapse(template).format(version=_app_version(), date=today)
# ---------------------------------------------------------------------------
# HTML (pour le PDF) — mêmes règles, sortie balisée propre
# ---------------------------------------------------------------------------
def _html_inline(node: Node | str, loc: dict[str, str]) -> str:
if isinstance(node, str):
return html.escape(_collapse(node), quote=False)
tag = node.tag
kids = _resolve_i18n(node, loc)
inner = "".join(_html_inline(c, loc) for c in kids)
if tag == "br":
return " "
if tag in ("strong", "b") and inner.strip():
return f"<strong>{inner}</strong>"
if tag in ("em",) and inner.strip():
return f"<em>{inner}</em>"
if tag == "code":
t = inner.strip()
return f"<code>{t}</code>" if t else ""
if tag == "kbd":
t = inner.strip()
return f"<code>{t}</code>" if t else ""
if tag == "a":
href = node.attrs.get("href") or ""
if href.startswith("http"):
return f'<a href="{html.escape(href, quote=True)}">{inner}</a>'
return inner
return inner
def _html_block(node: Node | str, out: list[str], loc: dict[str, str]) -> None:
if isinstance(node, str):
t = _collapse(node)
if t:
out.append(f"<p>{html.escape(t, quote=False)}</p>")
return
if any(c in node.cls().split() for c in _SKIP_CLASSES):
return
tag = node.tag
if tag == "pre":
raw = _pre_text(node)
classes = _pre_classes(node)
if "language-mermaid" in classes:
png = diagram_png_for(raw)
if png is not None:
url = "file:///" + str(png).replace("\\", "/").lstrip("/")
out.append(f'<img src="{url}" style="max-width: 100%" />')
return
out.append(f"<pre><code>{html.escape(raw, quote=False)}</code></pre>")
return
kids = _resolve_i18n(node, loc)
if tag in ("h2", "h3", "h4"):
text = _collapse("".join(_html_inline(c, loc) for c in kids))
if text:
out.append(f"<{tag}>{text}</{tag}>")
return
if tag == "p":
text = "".join(_html_inline(c, loc) for c in kids).strip()
if text:
out.append(f"<p>{text}</p>")
return
if tag in ("ul", "ol"):
out.append(_html_list(kids, loc, tag))
return
if tag == "table":
out.append(_html_table(node, loc))
return
for c in kids:
_html_block(c, out, loc)
def _html_list(items: list[Node | str], loc: dict[str, str], kind: str) -> str:
parts: list[str] = []
n = 0
for li in items:
if isinstance(li, str):
continue
if li.tag == "li":
n += 1
text_parts: list[str] = []
nested: list[Node] = []
for c in li.children:
if isinstance(c, Node) and c.tag in ("ul", "ol"):
nested.append(c)
else:
text_parts.append(_html_inline(c, loc))
line = "".join(text_parts).strip()
inner = line + "".join(_html_list(s.children, loc, s.tag) for s in nested)
if inner:
parts.append(f"<li>{inner}</li>")
elif li.tag in ("ul", "ol"):
parts.append(_html_list(li.children, loc, li.tag))
body = "".join(parts)
return f"<{kind}>{body}</{kind}>"
def _html_table(node: Node, loc: dict[str, str]) -> str:
rows_html: list[str] = []
for tr in node.find_all("tr"):
cells: list[str] = []
for td in tr.children:
if isinstance(td, Node) and td.tag in ("td", "th"):
tag = td.tag
inner = _collapse("".join(_html_inline(c, loc) for c in td.children))
cells.append(f"<{tag}>{inner}</{tag}>")
if cells:
rows_html.append("<tr>{}</tr>".format("".join(cells)))
return "<table>{}</table>".format("".join(rows_html))
def build_guide_html(lang: str = "fr") -> str:
"""Corps HTML autonome du guide (pour rendu PDF)."""
index_html = _read_index_html()
loc = _locale_strings(lang)
tree = _TreeBuilder()
tree.feed(_guide_fragment(index_html))
root = tree.root.children[0]
assert isinstance(root, Node)
blocks: list[str] = []
for section in root.find_all("section"):
_html_block(section, blocks, loc)
return "\n".join(blocks)
# ---------------------------------------------------------------------------
# PDF (WeasyPrint, repli reportlab)
# ---------------------------------------------------------------------------
def build_guide_pdf(lang: str = "fr") -> bytes:
lang_norm = lang if lang in ("fr", "en") else "fr"
title = _guide_title_fr if lang_norm == "fr" else _guide_title_en
loc = _locale_strings(lang_norm)
note = loc.get("guide105.arch_diagram_note", "")
footer = _export_footer(lang_norm)
try:
from backend.pdf_export import build_pdf_html, generate_pdf
body = build_guide_html(lang_norm)
body += (
f"<hr><p style='color:#777;font-size:11px'>{html.escape(note, quote=False)} — {html.escape(footer, quote=False)}</p>"
)
return generate_pdf(build_pdf_html(body, title), title)
except Exception as e: # WeasyPrint lève à l'import OU au rendu (GTK absent)
logger.warning("WeasyPrint indisponible pour le guide PDF (%s) — repli reportlab", e)
md = build_guide_markdown(lang_norm).decode("utf-8")
from backend.tools.documents import _render_reportlab_pdf
return _render_reportlab_pdf(md, title)
# ---------------------------------------------------------------------------
# Point d'entrée + cache
# ---------------------------------------------------------------------------
def get_guide_document(fmt: str, lang: str) -> tuple[bytes, str, str]:
"""Retourne (octets, media_type, filename) pour le format demandé.
``fmt`` : ``md`` | ``pdf``. Résultat mis en cache tant que index.html et
fr.json ne changent pas (les locales en ne divergent jamais sur les
structures ; la signature couvre l'essentiel).
"""
fmt = "pdf" if fmt == "pdf" else "md"
lang = "en" if lang == "en" else "fr"
key = (fmt, lang)
sig = _signature()
hit = _cache.get(key)
if hit and hit[0] == sig:
payload = hit[1]
else:
payload = build_guide_pdf(lang) if fmt == "pdf" else build_guide_markdown(lang)
_cache[key] = (sig, payload)
fname = f"ObsiGate-Guide-{_app_version()}-{lang}.{fmt}"
media = "application/pdf" if fmt == "pdf" else "text/markdown; charset=utf-8"
return payload, media, fname
+32 -1
View File
@@ -702,7 +702,7 @@ class SecurityHeadersMiddleware(BaseHTTPMiddleware):
response.headers["Content-Security-Policy"] = (
"default-src 'self'; "
"script-src 'self' 'unsafe-inline' blob: https://cdnjs.cloudflare.com https://unpkg.com https://esm.sh https://cdn.jsdelivr.net https://static.cloudflareinsights.com; "
"style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://fonts.googleapis.com https://cdn.jsdelivr.net; "
"style-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com https://fonts.googleapis.com https://cdn.jsdelivr.net https://esm.sh; "
"img-src 'self' data: blob:; "
"connect-src 'self' blob: https://esm.sh https://unpkg.com https://cdnjs.cloudflare.com https://fonts.googleapis.com https://fonts.gstatic.com https://cdn.jsdelivr.net; "
"font-src 'self' data: https://fonts.gstatic.com https://esm.sh; "
@@ -1747,6 +1747,37 @@ def _safe_export_name(name: str) -> str:
return cleaned or "document"
@app.get(
"/api/guide/download",
response_class=Response,
responses={200: {"content": {"application/pdf": {}, "text/markdown": {}}}},
)
async def api_guide_download(
format: str = Query("md", description="Download format: 'md' or 'pdf'"),
lang: str = Query("fr", description="Guide language: 'fr' or 'en'"),
current_user=Depends(require_auth),
):
"""Download the in-app user guide as Markdown or PDF (#105).
The document is generated from the live help modal in index.html resolved
through the locale files, so it always mirrors exactly what the user sees.
"""
from backend.guide_export import get_guide_document
if format not in ("md", "pdf"):
raise HTTPException(status_code=400, detail="format doit être 'md' ou 'pdf'")
try:
payload, media, fname = get_guide_document(format, lang)
except Exception as e: # weasyprint/reportlab unavailable
logger.exception("guide export failed")
raise HTTPException(status_code=500, detail=f"Export impossible: {e}") from e
return Response(
content=payload,
media_type=media,
headers={"Content-Disposition": f'attachment; filename="{fname}"'},
)
@app.put("/api/file/{vault_name}/save", response_model=FileSaveResponse)
async def api_file_save(
vault_name: str,
+2
View File
@@ -30,6 +30,7 @@ TAGS_METADATA: list[dict[str, str]] = [
{"name": "Bookmarks", "description": "Recently opened files, bookmarks and saved searches."},
{"name": "Backups", "description": "Automatic file backups, diffs, restore, compression and purge."},
{"name": "Export", "description": "Export notes or whole vaults to HTML, Markdown bundle or ePub."},
{"name": "Guide", "description": "Download the in-app user guide as Markdown or PDF (mirrors the help modal, FR/EN)."},
{"name": "AI", "description": "AI-powered editor actions, provider status and model discovery."},
{"name": "BooksLM", "description": "Directory-scoped AI chat (NotebookLM-style) over a vault folder."},
{"name": "MCP", "description": "Model Context Protocol server (Streamable HTTP) exposing the shared AI tool layer to external clients (Claude Desktop, Cursor…)."},
@@ -98,6 +99,7 @@ _TAG_RULES: list[tuple[re.Pattern[str], str]] = [
(re.compile(r"^/api/backups"), "Backups"),
(re.compile(r"^/api/file/[^/]+/(backups|diff|restore)"), "Backups"),
(re.compile(r"^/api/export"), "Export"),
(re.compile(r"^/api/guide"), "Guide"),
(re.compile(r"^/api/file/[^/]+/pdf"), "PDF"),
(re.compile(r"^/api/search"), "Search"),
(re.compile(r"^/api/tags"), "Search"),
+1 -1
View File
@@ -43,7 +43,7 @@ def build_pdf_html(body_html: str, title: str, theme: str = "light") -> str:
<head><meta charset="utf-8"><title>{title}</title>
<style>
body {{
font-family: Georgia, "Times New Roman", serif;
font-family: Georgia, "Times New Roman", serif, "Noto Color Emoji";
max-width: 720px;
margin: 40px auto;
padding: 0 20px;
+1 -1
View File
@@ -2626,7 +2626,7 @@ dependencies = [
[[package]]
name = "obsigate-desktop"
version = "2.11.3"
version = "2.14.0"
dependencies = [
"chrono",
"env_logger",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "obsigate-desktop"
version = "2.11.3"
version = "2.14.0"
description = "ObsiGate Desktop — Porte d'entrée native pour vos vaults Obsidian"
authors = ["Bruno Charest"]
edition = "2021"
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://raw.githubusercontent.com/nicedoc/obsigate/main/desktop/tauri.conf.schema.json",
"productName": "ObsiGate",
"version": "2.11.3",
"version": "2.14.0",
"identifier": "com.obsigate.desktop",
"build": {
"frontendDist": "../frontend",
+1 -1
View File
@@ -308,7 +308,7 @@ Pour répondre au besoin de cibler un fournisseur/modèle sans dépendre uniquem
- Lecture : `backend/ai.py` (`_read_app_config`, `get_default_provider`, `_load_provider_keys`).
- Écriture : `POST /api/config` (admin) — clés ajoutées à `_DEFAULT_CONFIG` (`backend/main.py:4270`).
- Rechargement à chaud : `reload_ai_config()` met à jour `PROVIDERS` **en place** (les imports existants restent valides).
- UI : section « Clés API Intelligence Artificielle » (`frontend/index.html` `#cfg-ai`), sélecteurs « Fournisseur par défaut » + « Modèle par défaut », sauvegardés par `saveAIKeys()` (`frontend/js/config.js`).
- UI : section « Clés API Intelligence Artificielle » (`frontend/index.html` `#cfg-ai`, cartes dépliables par fournisseur — #104), sélecteurs « Fournisseur par défaut » + « Modèle par défaut », sauvegardés par `saveAIKeys()` (`frontend/js/config.js`).
**Précédence de résolution du modèle** : override par requête > `ai_default_models[provider]` > variable d'environnement `*_MODEL` > défaut codé en dur.
+16
View File
@@ -169,6 +169,13 @@ Avant de corriger quoi que ce soit, un agent IA doit :
| *BUG-057* | [🟡 IMPORTANT] Assistant IA : le bouton « Ajouter » est inopérant dans l'éditeur Forge (fonctionne seulement dans « Editer ») | 🟢 corrigé | P1 | 📱 frontend | IA | `frontend/js/bookslm.js`, `frontend/editor-poc.html` | Ouvrir un document dans Forge, demander une réponse à l'assistant puis cliquer « Ajouter » | `_insertIntoEditor()` cible Forge (`#forge-iframe`) : `postMessage({ type: 'parent-insert', text })` ; `editor-poc.html` insère au curseur (`insertAtCursor`) et marque le tampon modifié. Repli textarea inclus. Tests : `tests/frontend/ai.test.mjs` (+3), `tests/frontend/editor-inline.test.mjs` (+1) | `state.editorView` (CodeMirror) est nul en Forge : le clic affichait « Aucun document ouvert dans l'éditeur » |
| *BUG-058* | [🔵 MINEUR] Éditeur « Editer » : la barre de numérotation de ligne ne suit pas la couleur du thème (gutter clair `#f5f5f5` en thème sombre) | 🟢 corrigé | P2 | 📱 frontend | IA | `frontend/style.css` | Ouvrir un document → Editer en thème sombre : la colonne des numéros de ligne reste gris clair alors que le fond de l'éditeur est sombre | Thème du gutter CodeMirror via les variables CSS (`color-mix(var(--text-primary) …)` pour le fond, `--text-secondary` pour les numéros, `--border` pour la séparation, `--text-primary` pour la ligne active) au lieu des valeurs codées en dur de CodeMirror ; test de non-régression dans `tests/frontend/editor-inline.test.mjs`. Vérifié Playwright (instance de test) : sombre `color(srgb 0.90 0.93 0.95 / 0.05)` + bordure `#21262d`, clair `color(srgb 0.12 0.14 0.16 / 0.05)` + bordure `#d0d7de` | CodeMirror applique `background:#f5f5f5` par défaut, indépendamment du thème ObsiGate ; en mode sombre le fond de l'éditeur suit `--bg-secondary` mais pas le gutter |
| *BUG-060* | [🟡 IMPORTANT] Viewer PDF : l'affichage des pages ne fonctionne pas — seule la barre d'outils « PDF — N pages » s'affiche, le contenu reste vide | 🟢 corrigé | P1 | 📱 frontend | IA | `frontend/js/viewer.js`, `tests/frontend/pdf-viewer.test.mjs` (nouveau), `tests/e2e/pdf-viewer.spec.js` (nouveau) | Cliquer un fichier `.pdf` dans l'arborescence | `frontend/js/viewer.js` : le rendu PDF passe de `<embed type="application/pdf">` à `<iframe>` (autorisée par `frame-src 'self'`, le stream étant same-origin). Tests : `tests/frontend/pdf-viewer.test.mjs` (+6) et `tests/e2e/pdf-viewer.spec.js` (fixture `test_vault/sample-pdf.pdf`) | Cause : la CSP durcie en BUG-034 pose `object-src 'none'`, directive qui gouverne `<embed>`/`<object>` → le lecteur PDF natif était bloqué (barre d'outils rendue, corps vide). Le test E2E échoue bien avec l'ancien `<embed>`. `object-src 'none'` conservé (le correctif ne désarme pas la CSP) |
| *BUG-061* | [🟡 IMPORTANT] Assistant IA : le bouton « Plein écran » n'agrandit plus le panneau | 🟢 corrigé | P2 | 📱 frontend | IA | `frontend/style.css`, `tests/frontend/ai.test.mjs` | Ouvrir l'assistant, redimensionner le panneau, puis cliquer « Plein écran » | La largeur du panneau est écrite en ligne par la poignée de redimensionnement / la largeur persistée (`localStorage`) ; l'inline l'emportait sur `.bookslm-panel.fullscreen { width: 100vw }`. Ajout de `!important` sur la règle plein écran. Tests : `ai.test.mjs` (+1 : classe basculée + règle CSS). Vérifié Playwright : 640 px → 1400 px (viewport) |
| *BUG-062* | [🟡 IMPORTANT] Viewer PDF : le document ne prend pas toute la largeur quand la navigation est masquée | 🟢 corrigé | P2 | 📱 frontend | IA | `frontend/style.css`, `tests/frontend/pdf-viewer.test.mjs`, `tests/e2e/pdf-viewer.spec.js` | Ouvrir un PDF puis masquer la barre de navigation gauche | La règle `.sidebar.hidden ~ .content-wrapper .content-area { max-width: 1200px }` (colonne de lecture centrée) s'appliquait aussi aux viewers plein cadre. Ajout de `.content-area:has(.pdf-viewer-container)` (et `.image-viewer-container`) avec `max-width: none; margin: 0`. Test E2E : `max-width` calculé = `none`, conteneur = largeur du contenu |
| *BUG-063* | [🟡 IMPORTANT] Viewer PDF : la table des matières s'affiche mais ne navigue pas | 🟢 corrigé | P1 | 📱 frontend | IA | `frontend/js/viewer.js`, `tests/frontend/pdf-viewer.test.mjs`, `tests/e2e/pdf-viewer.spec.js` (fixture `test_vault/sample-pdf-toc.pdf`) | Ouvrir un PDF avec signets, puis cliquer une entrée de la TOC | Deux causes : (1) `contentWindow.location.hash='page=N'` n'atteint pas le document (lecteur PDF natif dans une fenêtre `about:blank`) ; (2) un simple changement de fragment sur `iframe.src` est une navigation same-document **ignorée** par le lecteur natif. `navigatePdfToPage()` (liens `data-page` + listeners, plus d'`onclick` inline) recharge réellement l'iframe via un paramètre de query qui change (`&_pdfpage=<ts>#page=N`). Test E2E : `src` finit par `&_pdfpage=<n>#page=3`. Vérifié en Chrome *headful* : page 1 → page 8 → page 1 (captures identiques au retour) | Le fragment seul ne suffisait pas : Chrome applique `#page=N` au **chargement**, pas lors d'un changement de fragment |
| *BUG-064* | [🟡 IMPORTANT] Éditeur Excalidraw : le diagramme ne s'affiche jamais (canvas vide), pour tout fichier `.excalidraw` / `.excalidraw.md` | 🟢 corrigé | P1 | 📱 frontend + ⚙️ backend | IA | `frontend/excalidraw-editor.html`, `backend/main.py`, `tests/frontend/excalidraw-viewer.test.mjs`, `tests/test_security_hardening.py`, `tests/e2e/excalidraw.spec.js`, `test_vault/diagram-app-export.excalidraw` | Ouvrir un `.excalidraw` (ou `.excalidraw.md`) dans ObsiGate | Deux causes : (1) la feuille de style d'Excalidraw n'était jamais chargée → éditeur non stylisé + `.excalidraw` sans hauteur fixe → boucle de resize jusqu'au plafond `2^25` (33 554 432 px) → scène blanche. Correctif : `<link>` CSS depuis esm.sh + `style-src` CSP autorisant `https://esm.sh`. (2) `appState.collaborators` objet JSON → `collaborators.forEach is not a function` ; `sanitizeAppState()` reconvertit en `Map` et écarte `width/height/offsetLeft/offsetTop`. | Vérifié navigateur : hauteur canvas 525 px (avant 33 554 432), dessin affiché, UI stylisée, 0 erreur. E2E + tests statiques CSP/CSS ajoutés. |
| *BUG-065* | [🟡 IMPORTANT] Éditeur Excalidraw : l'auto-save recharge la page en pleine édition | 🟢 corrigé | P1 | 📱 frontend | IA | `frontend/js/excalidraw-viewer.js`, `frontend/js/utils.js`, `frontend/excalidraw-editor.html`, `tests/frontend/excalidraw-viewer.test.mjs` | Ouvrir un `.excalidraw` puis modifier un élément : au bout de 2 s la vue se recharge | Chaque modification déclenchait un `PUT save` 2 s plus tard → SSE `index_updated` → `reloadExternalWrite` → `openFile` → **recréation de l'iframe** (refresh visible). Auto-save supprimée : sauvegarde explicite (bouton 💾 / Ctrl+S). `reloadExternalWrite` ignore le fichier si un iframe Excalidraw est ouvert (`iframe[data-excalidraw-vault/path]`). Le badge « Modified » ne réagit plus aux changements d'`appState` (resize/zoom) mais à la signature des éléments. | Vérifié Playwright : plus de refresh, badge stable après bascule plein écran. Test statique (absence de `requestSave`/`saveTimer`). |
| *BUG-066* | [🔵 MINEUR] Configuration : icônes manquantes dans la table des matières (« Fichiers cachés », « Partages publics ») | 🟢 corrigé | P3 | 📱 frontend | IA | `frontend/locales/{fr,en}.json` | Ouvrir Configuration → observer le sommaire : les entrées « Fichiers cachés » et « Partages publics » n'ont pas d'icône | `config.section_hidden` → « 🗂️ Fichiers cachés » / « 🗂️ Hidden files », `config.section_shares` → « 📤 Partages publics » (EN avait déjà l'icône). Test : `tests/frontend/unit.test.mjs` (+1 : toutes les entrées du sommaire portent une icône FR/EN) | Les libellés du sommaire utilisent des clés i18n distinctes des titres de section (`auto.f8ba6127`, `config.section_partages-publics`) qui, elles, avaient l'icône |
| *BUG-067* | [🔵 MINEUR] Guide d'utilisation : l'entrée « 📱 Mobile » du sommaire ne fait rien (section absente) | 🟢 corrigé | P3 | 📱 frontend | IA | `frontend/index.html` | Ouvrir le Guide → cliquer « 📱 Mobile » dans le sommaire : rien ne se passe | L'ancre `#help-mobile-editor` était présente dans la TOC mais aucune section `id="help-mobile-editor"` n'existait (l'édition mobile n'était qu'un h3 de `help-edition`). Fix #105 : section dédiée créée avec ancre + entrée de nav cohérente. | Vérifié par test statique `tests/test_guide.py::test_nav_anchors_resolve` |
| | | | | | | | | | | |
### TODOs techniques (améliorations / nouvelles tâches)
@@ -233,6 +240,15 @@ Avant de corriger quoi que ce soit, un agent IA doit :
| 2026-09-17 | BUG-059 | Correction | `frontend/js/bookslm.js`, `tests/frontend/ai.test.mjs`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-059** : dans une conversation ouverte (post ancré en haut), **tout clic** dans la fenêtre de messages — lien de fichier, étapes, sélection de texte — faisait sauter toute la conversation au bas de la fenêtre. Cause : le gestionnaire `mousedown` de dépintage (prévu pour la molette/tactile/poignée de scroll) se déclenchait aussi sur un simple clic, et le retrait du padding d'ancre (`paddingBottom`) bornait le `scrollTop` à la nouvelle hauteur max → saut au bas. Correctif : helper pur `isScrollbarPress(target, clientX, container)` — un appui ne dépine que s'il vise la **poignée de scroll** (cible = conteneur + zone de gouttière droite) ; molette et tactile conservent leur comportement. Vérifié : `ai.test.mjs` 92/92 (+1), unit 9/9, validate-imports 38 modules, pytest / ruff / mypy inchangés côté backend. | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-17 | BUG-060 | Correction | `frontend/js/viewer.js`, `.gitea/workflows/ci.yml`, `tests/frontend/pdf-viewer.test.mjs` (nouveau), `tests/e2e/pdf-viewer.spec.js` (nouveau), `test_vault/sample-pdf.pdf` (nouveau), `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-060** : l'ouverture d'un PDF n'affichait aucune page (barre d'outils « PDF — N pages » présente, corps vide). Cause : la CSP durcie en BUG-034 pose `object-src 'none'` — directive qui gouverne `<embed>`/`<object>` — alors que le viewer rendait le PDF via `<embed type="application/pdf">` : le lecteur natif était bloqué. Correctif : rendu dans une `<iframe>` (autorisée par `frame-src 'self'`, le stream `/api/file/{vault}/pdf/stream` étant same-origin) ; `object-src 'none'` conservé. Tests : `pdf-viewer.test.mjs` 6/6 (statique : pas d'`<embed>`, CSP `frame-src 'self'`, iframe pleine hauteur), `pdf-viewer.spec.js` (E2E : iframe + stream `application/pdf` 200/206 + zéro violation CSP ; échoue bien avec l'ancien `<embed>`). Vérifié : pytest 1184 passed / 6 skipped, frontend 14 suites JSDOM vertes, validate-imports 38 modules, ruff/mypy 0. | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-17 | BUG-035, BUG-036, BUG-037, BUG-038, BUG-039, BUG-040 | Correction | `backend/secret_redactor.py`, `backend/collab.py`, `backend/auth/{middleware,password,router}.py`, `backend/indexer.py`, `backend/main.py`, `tests/test_api_main.py`, `tests/test_auth.py`, `tests/test_auth_api.py`, `tests/test_collab.py`, `tests/test_pdf.py`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **Lot de 6 bugs mineurs (P2/P3)** : BUG-035 masquage hex conditionné au contexte (git/SHA épargnés) ; BUG-036 jeton WebSocket cookie-only (plus de `?token=`) + plafond de trame 16 Mio ; BUG-037 garde-fou au démarrage (refus d'un bind public sans auth sauf `OBSIGATE_ALLOW_INSECURE=true`) ; BUG-038 Argon2 recalibré 19 Mio/t=2/p=1 ; BUG-039 login uniforme 401 (fini 429/403 distinctifs) ; BUG-040 extraction PDF différée via `enrich_pdf_texts()`. Vérifié : pytest 1204 passed / 6 skipped, ruff 0, mypy 0 (77 fichiers), frontend validate-imports 38 modules + unit 9/9. | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-17 | BUG-061, BUG-062, BUG-063 | Correction | `frontend/style.css`, `frontend/js/viewer.js`, `tests/frontend/ai.test.mjs`, `tests/frontend/pdf-viewer.test.mjs`, `tests/e2e/pdf-viewer.spec.js`, `test_vault/sample-pdf-toc.pdf` (nouveau), `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **Viewer PDF & assistant IA** : BUG-061 le bouton plein écran du panneau assistant l'emportait mal sur la largeur inline (redimensionnement/persistée) → `width: 100vw !important` ; BUG-062 le plafond de lecture 1200 px s'appliquait au PDF quand la navigation était masquée → `:has(.pdf-viewer-container)` en `max-width:none` ; BUG-063 la TOC PDF ne naviguait pas (`contentWindow` = `about:blank`) → `navigatePdfToPage()` recharge l'iframe avec `#page=N`, liens `data-page` sans `onclick` inline. Vérifié : `ai.test.mjs` 93/93, `pdf-viewer.test.mjs` 8/8, validate-imports 38 modules (311 exports), unit 9/9, E2E `pdf-viewer.spec.js` 3/3, et Playwright sur l'instance de test (plein écran 640→1400 px, `src` → `#page=3`, `max-width:none`). | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-17 | BUG-063 (complément) | Correction | `frontend/js/viewer.js`, `tests/frontend/pdf-viewer.test.mjs`, `tests/e2e/pdf-viewer.spec.js`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-063 non résolu au premier correctif** : définir `iframe.src = base + '#page=N'` ne change que le fragment → navigation same-document que le lecteur PDF natif ignore. Diagnostic en Chrome *headful* (comparaison de captures) : fragment présent au chargement = OK ; changement de fragment après chargement = aucun effet ; changement de query + fragment = OK. `navigatePdfToPage()` ajoute donc un paramètre de query horodaté (`&_pdfpage=<ts>#page=N`) pour forcer un vrai rechargement. Vérifié via l'UI de l'app (Chrome headful) : page 1 → page 8 → retour page 1 (hash de capture identique au retour). Tests : `pdf-viewer.test.mjs` 8/8, E2E `pdf-viewer.spec.js` 3/3. | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-17 | BUG-064 | Correction | `frontend/excalidraw-editor.html`, `backend/main.py`, `tests/frontend/excalidraw-viewer.test.mjs`, `tests/test_security_hardening.py`, `tests/e2e/excalidraw.spec.js`, `test_vault/diagram-app-export.excalidraw` (nouveau), `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-064** : aucun diagramme Excalidraw ne s'affichait (canvas vide). Diagnostic navigateur : `.excalidraw` sans hauteur fixe → boucle de redimensionnement 525 → 56 181 → **33 554 432 px** (`2^25`, plafond Excalidraw) ; canvas de 33 Mpx impossible à dessiner → scène blanche. **Cause 1** : la feuille de style `@excalidraw/excalidraw` n'était jamais chargée (seuls 18 règles CSS présentes, toutes ObsiGate) — l'éditeur était non stylisé. Correctif : `<link rel="stylesheet" href="https://esm.sh/@excalidraw/[email protected]/dist/prod/index.css">` + `https://esm.sh` ajouté à `style-src` de la CSP. **Cause 2** : `appState.collaborators` (Map sérialisée en objet JSON par l'app/plugin) faisait planter Excalidraw 0.18 (`collaborators.forEach is not a function`) ; `sanitizeAppState()` reconvertit en `Map` et écarte la géométrie de viewport importée (`width/height/offsetLeft/offsetTop`). Vérifié Playwright sur l'instance de test (port 2020) : hauteur canvas 525 px, rectangle + losange affichés, UI stylisée, 0 `pageerror`. Tests : `excalidraw-viewer.test.mjs` 8/8 (dont 3 nouveaux), `TestCspExcalidrawStylesheet` (pytest), E2E (hauteur de canvas bornée). | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-17 | BUG-064 (complément) | Correction | `frontend/style.css`, `tests/frontend/excalidraw-viewer.test.mjs`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-064 (complément)** : quand la barre de navigation gauche est masquée, le viewer Excalidraw restait borné à la colonne de lecture centrée de 1200 px. La règle `.sidebar.hidden ~ .content-wrapper .content-area { max-width: 1200px }` s'appliquait au viewer comme aux notes. Ajout de `.content-area:has(iframe[src*="excalidraw-editor.html"])` en `max-width: none; margin: 0` (même traitement que les viewers PDF/image, BUG-062). Vérifié Playwright (viewport 1400 px) : contenu 1115 → 1400 px, iframe 1035 → 1320 px, `max-width` calculé `none`. Test statique ajouté (`excalidraw-viewer.test.mjs` 9/9). | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-17 | BUG-065, #78 (complément) | Correction + feature | `frontend/js/excalidraw-viewer.js`, `frontend/js/utils.js`, `frontend/excalidraw-editor.html`, `tests/frontend/excalidraw-viewer.test.mjs`, `docs/features/excalidraw.md`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-065** : l'auto-save Excalidraw (débounce 2 s) déclenchait `PUT save` → SSE `index_updated` → `reloadExternalWrite` → `openFile` → recréation de l'iframe = refresh visible pendant le dessin. Auto-save retirée (`excalidraw-viewer.js` : plus de `requestSave`/`saveTimer`), sauvegarde explicite (bouton 💾 / Ctrl+S) ; `reloadExternalWrite` (utils.js) court-circuite le re-rendu si un iframe Excalidraw est ouvert sur ce fichier (attributs `data-excalidraw-vault`/`data-excalidraw-path`) ; le badge « Modified » suit désormais une signature des éléments (`id:versionNonce`) au lieu de tout `onChange` — resize/zoom/plein écran ne marquent plus le fichier modifié. **#78 (complément)** : bouton **plein écran** `#btn-fullscreen` dans la barre d'outils de l'éditeur (`requestFullscreen` sur le document de l'iframe) + iframe créée avec `allow="fullscreen" allowfullscreen`. Vérifié Playwright : bascule plein écran OK (`document.fullscreenElement` true→false), badge non modifié après bascule ; tests statiques `excalidraw-viewer.test.mjs` 12/12, validate-imports 38 modules, unit 9/9. | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-17 | #78 (complément) | UI | `frontend/excalidraw-editor.html`, `docs/features/excalidraw.md`, `CHANGELOG.md` | **#78 (complément)** : la barre d'outils de l'éditeur Excalidraw passe en **colonne d'icônes** (34×34 px, SVG seuls), **collée au bord droit** (`right: 0` ; `top: 45%` ; empilement vertical), avec `title`/`aria-label`. L'icône du bouton Save est remplacée par une coche pendant 1,2 s après une sauvegarde réussie. Badge « Modifié » réduit à une pastille. Vérifié Playwright : bord droit au bord de l'iframe, haut 45 %, 4 boutons empilés ; bascule plein écran OK, cycle d'icône Save + `PUT save` observés. | 🟢 livré (en attente vérif utilisateur) |
| 2026-09-18 | BUG-066 | Correction | `frontend/locales/fr.json`, `frontend/locales/en.json`, `tests/frontend/unit.test.mjs`, `CHANGELOG.md`, `docs/ISSUES_TODOLIST.md` | **BUG-066** : la table des matières de la page de configuration n'affichait aucune icône pour « Fichiers cachés » et « Partages publics ». Les libellés du sommaire proviennent de clés i18n (`config.section_hidden`, `config.section_shares`) distinctes des titres de section qui, eux, portaient déjà l'icône. Alignement : 🗂️ / 📤 en FR **et** EN. Test de non-régression : `unit.test.mjs` vérifie que **toutes** les entrées `.help-nav-link` du sommaire portent une icône dans les deux langues (17/17). Vérifié : `unit.test.mjs` 10/10, `validate-imports` 38 modules. | 🟢 corrigé (en attente vérif utilisateur) |
| 2026-09-18 | #105, BUG-067 | Documentation + correction | `frontend/index.html`, `frontend/js/config.js`, `frontend/style.css`, `frontend/locales/{fr,en}.json`, `backend/guide_export.py`, `backend/main.py`, `tests/test_guide.py`, `docs/features/guide-coverage-105.md`, `CHANGELOG.md`, `docs/ROADMAP.md`, `docs/ISSUES_TODOLIST.md` | **#105** : audit complet de couverture du Guide d'utilisation — 8 nouvelles sections (Architecture + diagramme Mermaid, API & intégrations, Diagrammes Mermaid & Excalidraw, Hors-ligne & synchronisation, Collaboration temps réel, Application desktop, Bibliothèque & signets, Multilingue) et compléments (recherche sémantique, MFA/WebAuthn, notifications push, exports HTML/ePub/ZIP, PDF, vue multi-panneaux, admin). Téléchargement du guide en Markdown et PDF (`GET /api/guide/download?format=md|pdf`, FR/EN, rendu par le moteur d'export existant). Guide plus large en desktop. **BUG-067** : ancre morte `#help-mobile-editor` → section dédiée créée. | 🟢 corrigé (en attente vérif utilisateur)
| 2026-09-18 | #105 (ajustements) | Amélioration | `frontend/index.html`, `frontend/js/config.js`, `frontend/sw.js`, `frontend/locales/{fr,en}.json`, `backend/guide_export.py`, `backend/pdf_export.py`, `Dockerfile`, `scripts/build_guide_diagrams.py`, `scripts/render_guide_diagram.mjs`, `scripts/guide_content.py`, `backend/assets/guide_diagrams/df7366a40db6a5a2.png`, `tests/test_guide.py`, `docs/features/guide-coverage-105.md`, `CHANGELOG.md` | **#105 (retour utilisateur)** : 1) boutons de téléchargement du guide passés en icônes seules (tooltips i18n conservés) ; 2) le diagramme Mermaid de la section Architecture est désormais rendu en **vraie image** dans le PDF (pipeline de pré-rendu PNG Chromium+mermaid v11, PNG commité sous `backend/assets/guide_diagrams/<sha1>.png`, résolu par `diagram_png_for()` ; le Markdown garde le fenced mermaid) ; 3) emoji du PDF rendus **en couleur** au lieu de rectangles : `fonts-noto-color-emoji` ajouté au Dockerfile + `"Noto Color Emoji"` en fin de pile de polices PDF. Vérifié : pytest 1218 (test_guide ×13), ruff/mypy 0, validate-imports 38, unit 10/10 ; PDF live conteneur 2020 : 24 pages, 0 glyphes tofu, diagramme 3568x1174 embarqué. | 🟢 livré
---
+5 -2
View File
@@ -1,6 +1,6 @@
# ObsiGate — Roadmap
> **Version :** 2.11.3 | **Dernière mise à jour :** 2026-09-17
> **Version :** 2.14.0 | **Dernière mise à jour :** 2026-09-19
> **Ce fichier ne contient que le travail à venir** (🔵 En cours + ⚪ Backlog) et un index compact
> vers les fonctionnalités livrées.
> - **Méthode de livraison à appliquer pour toute tâche : [DELIVERY_WORKFLOW.md](./DELIVERY_WORKFLOW.md)**
@@ -186,6 +186,9 @@
| 102 | Assistant IA — bouton « Ajouter la section » par bloc de code (insertion du bloc seul) | 2.9.0 | [archive](./archive/COMPLETED_v1-v2.md) |
| 92 | Assistant IA — Écosystème d'outils phase 2 (recherche à clé, cache/retry, Playwright, crawl, Gitea/GitHub, documents XLSX/DOCX/CSV/PDF) | 2.10.0 | [features/ai-tools-roadmap.md](./features/ai-tools-roadmap.md) |
| 103 | Configuration — clés utilisateur des sources connectées & recherche à clé (page Configurations, `data/api_keys.json`, priorité sur l'env) | 2.11.0 | [features/ai-tools-roadmap.md](./features/ai-tools-roadmap.md) |
| 104 | Configuration — Redesign UI de la section « Clés API IA » : recherche fournisseurs, carte défaut 2 colonnes + badges de capacités, cartes dépliables, footer d'actions sticky | 2.12.0 | [features/ai-keys-ui.md](./features/ai-keys-ui.md) |
| 105 | Guide d'utilisation — audit de couverture complet, téléchargement Markdown/PDF, guide desktop élargi, section Architecture (Mermaid) + BUG-067 | 2.13.0 | [features/guide-coverage-105.md](./features/guide-coverage-105.md) |
| 106 | Assistant IA — Actions instantanées contextuelles, catalogue « Toutes les actions » & frontmatter complet | 2.14.0 | [features/ai-quick-actions.md](./features/ai-quick-actions.md) |
---
@@ -193,7 +196,7 @@
| Priorité | Items | Effort total estimé |
|---|---|---|
| ✅ Complété | #1 → #59, #61–72, #74–76, #78–84, #88–93, #94–100, #102, #92 | ~114 jours réalisés |
| ✅ Complété | #1 → #59, #61–72, #74–76, #78–84, #88–93, #94–100, #102–106, #92 | ~115 jours réalisés |
| 🔵 P2 restant | #77 Desktop : signature de code (non retenue), 6 tests E2E **manuels** ([protocole](./DESKTOP_E2E_CHECKLIST.md)) | ~0,5-1 jour |
| ⚪ P4 restant | #73 Sync (6-8j) | 6-8 jours |
| ⚪ P0/P1 restant | #85-87 Refonte architecturale, performance, CI/CD (BUG-035 → BUG-040 corrigés) | ~15-23 jours |
+88
View File
@@ -0,0 +1,88 @@
# #104 — Configuration : Redesign UI de la section « Clés API Intelligence Artificielle »
> **Statut :** ✅ livré (v2.12.0) · **Zone :** `frontend/index.html`, `frontend/js/config.js`,
> `frontend/js/ai.js`, `frontend/style.css`, `frontend/locales/{fr,en}.json`
## Problème
La section « 🤖 Clés API IA » du panneau de configuration était une longue liste plate de
champs de saisie (DeepSeek, OpenRouter, Gemini, NVIDIA, QwenCloud, Xiaomi, Mistral) sans
structure ni hiérarchie visuelle : les sélecteurs défaut, les clés et les modèles se
cotoyaient au même niveau, les badges « Configuré » étaient collés à chaque champ, et les
boutons d'action se perdaient en milieu de section.
## Objectifs
Interface plus professionnelle, mieux structurée, moins fatigante visuellement (style
SaaS moderne, dark mode, cartes + accordéons), et qui reste utilisable quand la liste de
fournisseurs s'allonge.
## Structure livrée
### 1. En-tête de section
- Titre + sous-titre explicatif (i18n `config.ai_header_desc`).
- **Barre de recherche** (`#cfg-ai-search`) filtrant les cartes fournisseurs via
`filterAIProviders()` — normalisation insensible à la casse **et aux accents**
(`_sidebarNorm`), correspondance sur le nom affiché ou l'identifiant. État vide
« Aucun fournisseur ne correspond » (`#cfg-ai-providers-empty`).
### 2. Carte « Configuration par défaut »
- Carte visuellement distincte (`.ai-default-card`) : titre en petites capitales.
- Grille **2 colonnes** : « Fournisseur par défaut » / « Modèle par défaut »
(`#cfg-ai-default-provider`, `#cfg-ai-default-model`).
- **Capacités du modèle en badges colorés** : nouveau
`renderCapabilityBadges(caps)` (`frontend/js/ai.js`) qui n'affiche que les capacités
actives sous forme de tags (`.ai-cap-badge`), au lieu de la checklist ☑/□
(`renderCapabilityList`, conservée pour les pickers de l'assistant).
### 3. Fournisseurs d'API — cartes dépliables
Rendu dynamique par `_renderAIProviderCards()` depuis `AI_PROVIDER_NAMES` + nouveau
`AI_PROVIDER_META` (nom affiché, placeholder spécifique au fournisseur). Par carte :
- **Replié** : logo (initiale dans une pastille), nom, **badge de statut**
(« Configuré » vert / « Non configuré » gris, `.ai-provider-badge.configured`) et
**corbeille discrète** (`cfg-<provider>-delete`, visible uniquement si une clé existe ;
`stopPropagation` pour ne pas déplier la carte ; confirmation conservée).
- **Déplié** : libellés **au-dessus** des champs (`.ai-field-label`), **API key à 60 % /
modèle à 40 %** (grille `3fr 2fr`), placeholder par fournisseur.
- Accessibilité : en-tête en `role="button"` + `tabindex="0"` (clavier Entrée/Espace),
`aria-expanded` synchronisé, chevron animé, focus visible.
- Les boutons « Configuré / × Supprimer » redondants dans les champs sont supprimés —
le statut vit dans l'en-tête de la carte.
### 4. Barre d'actions
- Footer **sticky** en bas de section (`.ai-keys-footer`) : « Sauvegarder » (primaire
`.config-btn-save`) et « Tester » (outline `.config-btn-secondary`), plus le span de
statut du test. Toujours accessible pendant le défilement du panneau.
## Compatibilité
- Les ID `cfg-<provider>-key`, `cfg-<provider>-model`, `cfg-<provider>-badge`,
`cfg-<provider>-delete`, `cfg-ai-default-*`, `cfg-ai-status` sont conservés :
`saveAIKeys()`, `testAIKeys()`, `deleteAIKey()` et le câblage des événements de
`initConfigModal()` ne changent pas, ni la resynchronisation des pickers IA
(`refreshAIPickers()` après save/suppression, BUG-043).
- i18n : nouvelles clés `config.ai_header_desc`, `config.ai_search_placeholder`,
`config.ai_default_section`, `config.ai_providers_title`, `config.ai_providers_empty`,
`config.ai_status_configured`, `config.ai_status_not_configured`,
`config.ai_delete_key_title` (FR + EN).
## Styles
`.ai-keys-*`, `.ai-provider-*`, `.ai-cap-badge`, `.ai-field*` — uniquement des variables
CSS existantes (`--surface`, `--bg-secondary`, `--border`, `--accent`, `--success`,
`--danger`, `--accent-bg`…), focus visibles, responsive 1 colonne < 600 px.
## Tests
- `tests/frontend/config-ai-keys.test.mjs` (JSDOM, 7 tests) : rendu des 7 cartes,
badges de statut selon les clés masquées renvoyées par `GET /api/config/ai-keys`,
bascule replié/déplié (classe `open` + `aria-expanded`), filtre de recherche
(casse/accents + état vide), collecte et POST des clés saisies par `saveAIKeys()`,
suppression avec confirmation (DELETE sur l'env name), badges de capacités.
- Suites existantes (38 modules, validate-imports, ai.test.mjs, sidebar-filters…) : vertes.
- E2E Playwright (chromium-desktop) : 91 passed / 3 skipped, 100 % sans retries.
+89
View File
@@ -0,0 +1,89 @@
# #106 — Assistant IA : actions instantanées contextuelles & catalogue de prompts
> **Statut :** livré en 2.14.0 · **Domaine :** Assistant IA (frontend) ·
> **Fichiers :** `frontend/js/ai-quick-actions.js`, `frontend/js/bookslm.js`,
> `frontend/style.css`, `frontend/locales/{fr,en}.json`,
> `tests/frontend/ai-quick-actions.test.mjs`
## Problème
La zone d'accueil de l'assistant affichait 3 suggestions **statiques** par mode
(résumé / thèmes / contradictions), sans lien avec ce que l'utilisateur regarde
réellement (un fichier de code ? plusieurs documents ? une sélection dans
l'éditeur ?), et sans point d'accès au reste des prompts utiles.
## Solution
### Catalogue (`frontend/js/ai-quick-actions.js`, module pur sans DOM)
25 actions en 6 catégories, chacune = `{id, cat, icon (lucide), labelKey,
promptKey, agent?}` — libellés **et** prompts i18n FR/EN (clés `qa.*`) :
| Catégorie | Actions |
|---|---|
| 📝 Synthèse & Analyse | Résumer en 3 points clés · Frictions/contradictions · Vulgariser · FAQ |
| ✅ Productivité & Structuration | Checklist d'actions · Plan d'action · Mémo exécutif · **Générer le frontmatter YAML** · **Mettre à jour le frontmatter** · Liens/backlinks · Sections hiérarchiques |
| 💻 Code & Scripts | Expliquer · Bugs & failles · Docstrings/types · Tests unitaires |
| 🔗 Cross-documents | Comparer · Fusionner en note de synthèse · Chronologie |
| ✍️ Édition & Reformulation | Concis · Corriger le style · Reformuler · Traduire · Expliquer la sélection |
| ❔ Assistant (général) | Que sais-tu faire · Rechercher efficacement · Créer une note de réunion |
Les deux actions frontmatter sont marquées `agent: true` : un clic bascule
transparentement le panneau en **mode agent** (comme Deep Research) puis envoie
le prompt — l'assistant lit le document, propose la mutation via l'outil
`edit_file`/`append_to_file`, et la **carte de confirmation** (#79) applique le
nouveau bloc en tête du fichier.
Le prompt « Générer le frontmatter YAML » demande le format complet du vault de
Bruno (titre, auteur, creation_date/modification_date ISO-8601 avec fuseau,
catégorie, tags en liste inline, aliases, status, publish, favoris, template,
task, archive, draft, private, NomDeVoute, Description). « Mettre à jour le
frontmatter » **conserve les champs existants** : actualise
`modification_date`, recalcule titre/tags/aliases/catégorie/NomDeVoute/Description
d'après le contenu, complète les champs manquants.
### Sélection contextuelle (triage par défaut dans l'UI)
`detectContext({mode, docCount, currentPath, hasSelection})` — précédence :
**sélection > code > multi-docs > doc unique > répertoire > général**.
| Contexte | Boutons suggérés |
|---|---|
| 1 doc texte | Résumer 3 points · Checklist · Générer le frontmatter · Mettre à jour le frontmatter |
| 2+ docs | Fusionner · Comparer · Frictions/contradictions |
| Fichier de code (.py, .ts, .sh…) | Expliquer · Bugs & failles · Tests unitaires |
| Sélection dans l'éditeur | Concis · Corriger le style · Expliquer la sélection |
| Répertoire | Résumer le répertoire · Thèmes · Checklist |
| Général | Que sais-tu faire · Rechercher · Créer une note |
### Présentation (calquée sur le POC `ai_assistant_quick_actions_poc.html`)
- Badge de contexte dans l'en-tête (« 1 doc ouvert », « Fichier de code »,
« Sélection active », « 3 docs ouverts »…).
- Ligne « Actions suggérées » + bouton **« Toutes les actions »** ouvrant un
**tiroir bottom-sheet** : recherche instantanée (insensible aux accents/casse
via `normalizeSearch`) + catalogue groupé par catégorie, Échap/backdrop
pour fermer.
- Boutons icône + libellé + flèche au survol ; clic = **envoi immédiat** du
prompt dans le composer (chemin `_sendMessage()` : skills, images et mode
agent continuent de fonctionner).
- La rangée se masque dès le premier message du fil (comportement historique) ;
le rafraîchissement du contexte à la sélection éditeur est throttled 250 ms
(`selectionchange` + `mouseup`/`keyup`, CodeMirror n'émettant pas
`selectionchange` natif).
- CSS 100 % variables de thème (`--surface`, `--accent`, `--accent-bg`…) →
conforme aux 15 thèmes ; transitions désactivées en `prefers-reduced-motion`.
## Tests
`tests/frontend/ai-quick-actions.test.mjs` (13 tests, câblé au job lint CI) :
précédence des contextes, presets 3-4 actions résolvables, table de conception,
agent-flag des actions frontmatter, **complétude FR+EN** de chaque clé
catalogue/badge contre les vrais JSON de locales.
## Vérification live (obsigate-test :2020, Playwright)
badge « 1 doc ouvert », 4 suggestions dont les 2 frontmatter, tiroir à 6
catégories / 25 actions, recherche « frontmatter » → 2 résultats, clic →
`aria-pressed=true` sur le bouton agent + message envoyé avec le nouveau
prompt + réponse de l'assistant.
+10 -7
View File
@@ -1,6 +1,6 @@
# #78 — Éditeur Excalidraw — Ouverture et édition de fichiers .excalidraw
> **Statut :** ✅ Terminé (2026-09-10 — éditeur iframe complet, détection, création, autosave, support `.excalidraw.md`, B5 extraction texte pour la recherche, C8 création via menu contextuel, F3 E2E `tests/e2e/excalidraw.spec.js`, doc H1-H3. F2 non retenu. BUG-002 corrigé)
> **Statut :** ✅ Terminé (2026-09-10 — éditeur iframe complet, détection, création, autosave, support `.excalidraw.md`, B5 extraction texte pour la recherche, C8 création via menu contextuel, F3 E2E `tests/e2e/excalidraw.spec.js`, doc H1-H3. F2 non retenu. BUG-002 et BUG-064 corrigés. 2026-09 : A9 bouton **plein écran** ajouté, auto-save retirée au profit d'une sauvegarde explicite (BUG-065))
> **Effort :** 3-4 jours | **Impact :** 🟡
> **Références :** [Roadmap](../ROADMAP.md) · [Changelog — 2.2.0](../../CHANGELOG.md)
@@ -56,17 +56,18 @@
</script>
```
- [x] **A5. Rendu du composant** : Monter `<ExcalidrawLib.Excalidraw>` dans le conteneur avec les `initialData` reçues. Configurer les callbacks `onChange` pour détecter les modifications.
- [x] **A6. Barre d'outils minimaliste** (dans l'iframe, superposée en haut à droite) :
- Bouton « 💾 Sauvegarder » → envoie les données au parent
- Badge « Modifié » (disparaît après sauvegarde)
- Indicateur de thème 🌙/☀️
- Optionnel : bouton « Export PNG » et « Export SVG » (natif Excalidraw)
- [x] **A6. Barre d'outils minimaliste** (dans l'iframe ; depuis 2026-09 : **colonne d'icônes** collée au bord droit (`right: 0`), début à `45%` de la hauteur, empilement vertical) :
- Bouton « Sauvegarder » (icône disquette → coche après sauvegarde) → envoie les données au parent
- Boutons « Export PNG » (icône image) et « Export SVG » (icône vectorielle) — infobulles au survol
- Bouton plein écran (A9)
- Badge « Modifié » réduit à une pastille au-dessus des boutons
- [x] **A7. Communication postMessage** :
- Réception : écouter `message` → si `type === "init"`, charger `data.elements` + `data.appState` + `data.files` dans l'état Excalidraw. Si `type === "theme"`, basculer `theme` (dark/light).
- Émission : `postMessage({type: "save", data: {elements, appState, files}}, "*")` quand l'utilisateur sauvegarde.
- Émission : `postMessage({type: "ready"}, "*")` au chargement pour signaler que l'iframe est prête.
- Émission : `postMessage({type: "modified", dirty: true/false}, "*")` pour l'indicateur de modification.
- [x] **A8. Gestion des erreurs** : Si les données sont invalides (JSON corrompu, pas un fichier Excalidraw), afficher un message d'erreur stylisé dans l'iframe.
- [x] **A9. Bouton plein écran** (ajouté 2026-09) : bouton `#btn-fullscreen` dans la barre d'outils de l'iframe → `document.documentElement.requestFullscreen()` (l'iframe parent est créée avec `allow="fullscreen" allowfullscreen`) ; l'icône bascule entrer/sortir via `fullscreenchange`. La feuille de style Excalidraw étant chargée, le canvas suit le redimensionnement. Test statique : `tests/frontend/excalidraw-viewer.test.mjs`.
## B. Backend — Détection et API (0.5 jour)
- [x] **B1. Ajout à `SUPPORTED_EXTENSIONS`** : Ajouter `.excalidraw` dans `backend/indexer.py:56` pour que les fichiers apparaissent dans l'arborescence et soient indexés.
@@ -100,7 +101,7 @@
- Pour les fichiers `.excalidraw` : remplacer « Éditer (Forge) » par « Ouvrir dans Excalidraw.com » (lien externe, nouvel onglet)
- Garder « Télécharger » (.excalidraw) et « pop-out »
- Badge « Excalidraw » avec icône `pen-tool`
- [x] **C4. Auto-save** : Débounce 2 secondes après la dernière modification dans l'iframe → sauvegarde automatique silencieuse (comme l'éditeur markdown #29). L'iframe émet `modified` → le parent démarre un timer → au bout de 2s sans nouvelle modification → `postMessage({type: "requestSave"})` → l'iframe répond avec `save` → le parent écrit via l'API.
- [x] **C4. Sauvegarde explicite uniquement** (modifié 2026-09 : l'auto-save a été **retirée**, BUG-065) : l'iframe émet `modified` → le badge « Modified » s'affiche, mais **aucune sauvegarde automatique** n'est déclenchée. La sauvegarde se fait par le bouton « 💾 Save » de l'iframe ou `Ctrl+S`. Raison : chaque écriture déclenche l'événement SSE `index_updated`, qui re-rendait la vue et **rechargeait l'iframe** (refresh visible en pleine édition).
- [x] **C5. Raccourci Ctrl+S** : L'iframe intercepte Ctrl+S → envoie `save` au parent → le parent sauvegarde → confirmation visuelle (toast « Excalidraw sauvegardé »).
- [x] **C6. Compatibilité Split View (#75)** : L'iframe s'affiche dans le content-area du panneau actif. Le `PaneTabManager` gère le cache : quand on switch d'onglet, l'état de l'iframe est préservé (elle reste dans le DOM, juste masquée). Plusieurs iframes Excalidraw peuvent coexister dans différents panneaux.
- [x] **C7. Création via la modale « Nouveau fichier »** : Dans `frontend/js/ui.js`, fonction `showCreateFileModal()` :
@@ -141,6 +142,8 @@
- **Taille du bundle** : React + ReactDOM + Excalidraw ≈ 2.5 Mo minifié. Chargé depuis `esm.sh` (CDN global, cache HTTP). L'impact n'est perceptible qu'à la première ouverture d'un `.excalidraw`. Solution : précharger l'iframe en arrière-plan (`<link rel="prefetch">`) après le chargement de l'app.
- **Performance React dans iframe** : React dans une iframe fonctionne parfaitement — c'est un contexte JavaScript indépendant. Testé sur Chrome, Firefox, Safari, Edge.
- **CORS et esm.sh** : Les modules ESM depuis `esm.sh` sont servis avec les headers CORS appropriés. L'iframe est same-origin (`/frontend/excalidraw-editor.html`) donc pas de problème.
- **Compatibilité des exports de l'app Excalidraw** (BUG-064) : `appState.collaborators` est une `Map` qu'Excalidraw sérialise en objet JSON (`{}`) ; elle doit être reconvertie en `Map` (`sanitizeAppState()` dans `frontend/excalidraw-editor.html`) avant `initialData`, sinon Excalidraw 0.18 plante (`collaborators.forEach is not a function`). La géométrie de viewport (`width`, `height`, `offsetLeft`, `offsetTop`) est également écartée : ce sont des valeurs mesurées côté fenêtre source, qu'Excalidraw recalcule. Couvert par un test E2E (`diagram-app-export.excalidraw`).
- **Feuille de style Excalidraw obligatoire** (BUG-064) : `@excalidraw/excalidraw` n'injecte pas son CSS automatiquement — il faut le charger explicitement (`<link>` vers `…/@excalidraw/[email protected]/dist/prod/index.css`). Sans lui, l'éditeur est non stylisé **et** `.excalidraw` n'a pas de hauteur fixe, ce qui déclenche une boucle de redimensionnement jusqu'au plafond `2^25` (33 554 432 px) : le canvas devient indessinable et la scène reste blanche. Le CDN `esm.sh` doit donc figurer dans `style-src` de la CSP (`backend/main.py`). Garde-fous : `tests/frontend/excalidraw-viewer.test.mjs` et `TestCspExcalidrawStylesheet`.
- **Mises à jour d'Excalidraw** : La version est épinglée (`@0.18.0`). Pour mettre à jour, changer le numéro dans le HTML + tester. Le format de données `.excalidraw` est stable (v2 depuis 2021).
- **Sécurité postMessage** : Vérifier `event.origin` dans les deux sens. L'iframe n'accepte que les messages de `window.parent`. Le parent n'accepte que les messages de l'iframe connue. Pas de `"*"` en production.
- **Tauri Desktop (#77)** : L'iframe se charge depuis le filesystem local (`tauri://localhost/frontend/excalidraw-editor.html`). Les imports ESM depuis `esm.sh` fonctionnent si le réseau est disponible. Pour le mode offline, bundler Excalidraw dans l'app desktop (à traiter dans #77, pas ici).
+139
View File
@@ -0,0 +1,139 @@
# #105 — Guide d'utilisation : couverture, téléchargement MD/PDF, Architecture
> **Statut :** livré | **Version :** 2.13.0 | **Bugs liés :** BUG-067
> **Roadmap :** [docs/ROADMAP.md](../ROADMAP.md) · **Changelog :** [../../CHANGELOG.md](../../CHANGELOG.md)
## 1. Objectif
Après ~35 features livrées (#70→#104), le guide intégré (modale « Guide
d'utilisation », `#help-modal` de `frontend/index.html`) ne représentait plus
l'application : Mermaid, hors-ligne/PWA, collaboration Yjs, desktop Tauri,
exports HTML/ePub/ZIP, recherche sémantique, MFA/WebAuthn, push, split view,
API OpenAPI/MCP étaient absents. L'item couvre quatre livrables :
1. **Audit de couverture** — toutes les fonctionnalités visibles ET non visibles
(API, MCP, webhooks, endpoints de partage) sont documentées.
2. **Section Architecture** — diagramme Mermaid des grandes composantes.
3. **Téléchargement Markdown + PDF** du guide, dans la langue courante.
4. **Lecture desktop élargie** (mode Tauri + grands viewports web).
## 2. Source de vérité du contenu
Le contenu des nouvelles sections vit dans **`scripts/guide_content.py`** :
dictionnaire `CONTENT` (clé → FR, EN) + constructeurs HTML qui **ne peuvent
pas diverger** des locales (le FR inline est généré depuis `CONTENT`).
- `scripts/merge_guide_locales.py` → injecte les clés `guide105.*` dans
`frontend/locales/{fr,en}.json` (insertion textuelle, parité assertée).
- `scripts/insert_guide_sections.py` → insère sections/TOC/compléments dans
`index.html` (idempotent, préserve les fins de ligne, vérifie l'équilibre
`<section>` et l'absence d'ancre morte).
- **Règle :** ne jamais éditer les blocs `guide105.*` des JSON ni les sections
#105 de `index.html` à la main — modifier `guide_content.py` et relancer les
deux scripts (séquence figée, sinon HTML et locales divergent).
## 3. Rendu du guide dans l'app
Les textes portent `data-i18n="guide105.*"` ; `_applyDOM()` (i18n.js) les
remplit avec la locale courante. Les valeurs FR/EN contiennent du **HTML
minimal** (`<code>`, `<strong>`, `<a href="https://…">`) — sûre ici car ces
chaînes sont statiques dans le dépôt (jamais de contenu utilisateur ; même
convention que `help.desc_*` existant).
Le diagramme d'architecture est un bloc `<pre class="mermaid-code"><code
class="language-mermaid">` : à l'ouverture de la modale, `renderGuideMermaid()`
(config.js) appelle `renderMermaidBlocks()` (mermaid-viewer.js) sur la modale —
le viewer ne rend que les vues document, la modale est donc enrichie ici. Si le
CDN Mermaid n'est pas prêt, le bloc reste du code lisible et le rendu est
retenté à l'ouverture suivante (`data-mermaid-rendered` ne se pose qu'après
succès). Le MD exporté embarque le diagramme en fenced block ` ```mermaid `
(copiable, rendu par GitHub/VS Code/Obsidian) ; le PDF affiche le PNG pré-rendu
(section 4 — WeasyPrint n'exécute pas Mermaid).
## 4. Téléchargement (MD + PDF)
`backend/guide_export.py` : parseur stdlib (html.parser → arbre minimal) ;
extraction de `#help-modal`→`.help-content`, résolution i18n **identique à
_applyDOM** (un élément `data-i18n` est remplacé par la valeur locale, sinon le
FR inline sert de repli), conversion Markdown (titres, listes imbriquées,
tables, fenced code, gras/italique/code/kbd/links http) et HTML propre pour
WeasyPrint. PDF : pipeline d'export existant (`build_pdf_html` + `generate_pdf`),
repli `_render_reportlab_pdf` (markdown simplifié) quand GTK manque (Windows
nu) — même stratégie que le bouton « PDF » des documents (#92).
`get_guide_document(fmt, lang)` met en cache (octets+signature mtime/size de
`index.html` et `fr.json`) pour éviter de re-générer à chaque requête.
Endpoint `GET /api/guide/download?format=md|pdf&lang=fr|en`
(`require_auth`, tag OpenAPI « Guide »), `Content-Disposition: attachment`.
Côté UI : boutons **icônes seules** 📄/⬇ dans l'en-tête de la modale
(`#help-download-md`/`#help-download-pdf`, tooltip i18n), handler `downloadGuide()` dans
`frontend/js/config.js` — fetch avec `AuthManager.getAuthHeaders()` +
credentials (identique à `viewer.downloadExport()`), blob → lien
téléchargeable, toasts i18n réutilisés (`viewer.export_*`).
Diagramme d'architecture dans le PDF : WeasyPrint n'exécute pas Mermaid → le code
Mermaid est **pré-rendu en PNG** (`scripts/build_guide_diagrams.py` +
`scripts/render_guide_diagram.mjs`, Chromium + mermaid v11 CDN, scale 2) et le PNG
est **commité** dans `backend/assets/guide_diagrams/<sha1>.png` ; `diagram_png_for()`
(hash sha1[:16] du code normalisé, même algorithme des deux côtés) remplace le
bloc par `<img src="file:///…">` dans le HTML d'export. Après modification du
diagramme dans `guide_content.py` + réinsertion : relancer
`python scripts/build_guide_diagrams.py` et committer le nouveau PNG.
Emoji : l'image Docker installe `fonts-noto-color-emoji` et la pile de polices
PDF finit par `"Noto Color Emoji"` — sans cela les emoji pleine chasse des titres
de section s'affichent en rectangles (la TOC n'était pas touchée car elle passe
par DejaVu/Sans).
## 5. Guide desktop élargi
`frontend/js/desktop.js::initDesktopIntegration()` ajoute `body.desktop-mode`
(une fois, après le garde Tauri). CSS (section « Help Modal: desktop » de
`style.css`) : conteneur 1760 px / 96 vw, contenu 1440 px, modale 94 vh ; le
même layout est accordé aux viewports ≥1400 px web via media-query (contenu
1280 px). Le mobile reste inchangé (≤768 px plein écran).
## 6. Couverture fonctionnelle du guide (après #105)
| Domaine app | Section du guide |
|---|---|
| Vaults, arborescence, filtres, breadcrumb | Interface, Navigation |
| Onglets, popout, split view | Onglets, Personnalisation |
| Recherche TF-IDF, opérateurs, facettes, sémantique, recherches sauvegardées, signets | Recherche, Bibliothèque |
| Tags, frontmatter | Tags |
| Fichiers, types supportés, CodeMirror, PDF, export HTML/ePub/ZIP, anti-doublons upload | Fichiers |
| Mermaid | Diagrammes |
| Excalidraw | Excalidraw |
| Éditeur, AI toolbar, BooksLM, commandes @//, skills, images, outils, historique | Édition, IA |
| Édition mobile | Mobile (section dédiée, BUG-067) |
| Graphe, backlinks | Bibliothèque, Graphe |
| Palette de commandes, raccourcis | Palette, Raccourcis |
| Partage public, PDF du partage, webhooks HMAC | Partage, Webhooks |
| Backups, diff, purge, audit log, gestionnaire | Sauvegardes et Audits |
| JWT/Argon2id, rate limit, MFA TOTP/WebAuthn, admin dashboard, secrets, CSP | Sécurité |
| PWA hors-ligne, IndexedDB queue, watcher, conflits Syncthing | Hors-ligne, Bibliothèque |
| Collaboration Yjs/CRDT, awareness, push VAPID | Collaboration, Interface |
| Tauri desktop (updater signé, wizard, fenêtrage) | Desktop |
| API REST OpenAPI (/docs, /redoc, /api, /openapi.json), MCP /mcp, automatisation | API & Intégrations |
| i18n FR/EN, export du guide multilingue | Multilingue |
| Architecture technique (couches, flux, données, déploiement) | **Architecture** (nouveau) |
| Plugins sandboxés | Plugins |
## 7. Tests & vérifications
- `tests/test_guide.py` (13) : ancre TOC→sections (garde-fou BUG-067),
sections #105 présentes, parité/présence des clés `guide105.*` FR=EN,
Markdown FR/EN (titres, mermaid, absence de balises résiduelles), PDF
(`%PDF`, taille), **diagramme Architecture rendu en `<img>` PNG dans le HTML
d'export**, MD garde le fenced mermaid, metadata `get_guide_document`,
endpoint MD/PDF/400 via TestClient, OpenAPI (path + tag « Guide »).
- Suite backend pytest : 1218 passed · ruff/mypy 0 erreur ·
`validate-imports` 38 modules · `unit.test.mjs` 10/10 · E2E complet CI.
- SW cache busting : `SW_VERSION` v21→v23 (guides + boutons icônes).
## 8. Limites assumées
- Le PDF est généré côté serveur avec les polices système ; en l'absence de
GTK (Windows de dev) c'est le repli reportlab (sans tableaux) — la voie
WeasyPrint est celle des conteneurs Docker/prod.
- Le sommaire et les sections sont en dur dans `index.html` : tout ajout futur
de section passe par `guide_content.py` + les deux scripts (jamais à la main).
+112 -18
View File
@@ -7,34 +7,48 @@
<meta http-equiv="Expires" content="0">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Excalidraw Editor</title>
<!-- Excalidraw's stylesheet MUST be loaded: without it the editor is
unstyled AND `.excalidraw` has no fixed height, so Excalidraw's
ResizeObserver feedback loop grows the canvas to the 2^25 hard cap and
the scene renders blank. Loaded from esm.sh (same origin as the JS
modules, already allowed by `font-src` for the relative font URLs). -->
<link rel="stylesheet" href="https://esm.sh/@excalidraw/[email protected]/dist/prod/index.css">
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
html, body, #root { width: 100%; height: 100%; overflow: hidden; }
body { background: #ffffff; }
/* Toolbar overlay in top-right corner */
/* Icon-only toolbar, vertical, flush against the right edge:
right edge at 100% of the viewport width, group starts at 45% of the
viewport height from the top. */
#excalidraw-toolbar {
position: fixed;
top: 8px;
right: 12px;
right: 0;
top: 45%;
z-index: 1000;
display: flex;
flex-direction: column;
gap: 6px;
align-items: center;
}
#excalidraw-toolbar button {
padding: 5px 10px;
width: 34px;
height: 34px;
padding: 0;
border: 1px solid #d0d0d0;
border-radius: 6px;
background: #ffffff;
cursor: pointer;
font-size: 12px;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
display: flex;
align-items: center;
gap: 4px;
justify-content: center;
transition: background 0.15s;
}
#excalidraw-toolbar button svg {
width: 18px;
height: 18px;
display: block;
}
#excalidraw-toolbar button:hover { background: #f0f0f0; }
#excalidraw-toolbar button.primary {
background: #6965db;
@@ -43,11 +57,12 @@
}
#excalidraw-toolbar button.primary:hover { background: #5b57c4; }
/* Dirty indicator */
/* Dirty indicator (small dot above the buttons) */
#dirty-badge {
font-size: 11px;
font-size: 12px;
line-height: 1;
color: #e07b39;
font-weight: 500;
font-weight: 700;
display: none;
}
#dirty-badge.visible { display: inline; }
@@ -86,10 +101,11 @@
<div id="loading">Loading Excalidraw…</div>
<div id="root"></div>
<div id="excalidraw-toolbar">
<span id="dirty-badge">● Modified</span>
<button id="btn-save" class="primary" title="Save (Ctrl+S)">💾 Save</button>
<button id="btn-export-png" title="Export PNG">🖼 PNG</button>
<button id="btn-export-svg" title="Export SVG">📐 SVG</button>
<span id="dirty-badge" title="Modified">●</span>
<button id="btn-save" class="primary" title="Save (Ctrl+S)" aria-label="Save"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11l5 5v11a2 2 0 0 1-2 2z"/><polyline points="17 21 17 13 7 13 7 21"/><polyline points="7 3 7 8 15 8"/></svg></button>
<button id="btn-export-png" title="Export PNG" aria-label="Export PNG"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2" ry="2"/><circle cx="9" cy="9" r="2"/><path d="m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"/></svg></button>
<button id="btn-export-svg" title="Export SVG" aria-label="Export SVG"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19.5 7a24 24 0 0 1 0 10M4.5 7a24 24 0 0 0 0 10M7 19.5a24 24 0 0 1 10 0M7 4.5a24 24 0 0 0 10 0"/><rect x="2" y="2" width="5" height="5" rx="1"/><rect x="17" y="2" width="5" height="5" rx="1"/><rect x="17" y="17" width="5" height="5" rx="1"/><rect x="2" y="17" width="5" height="5" rx="1"/></svg></button>
<button id="btn-fullscreen" title="Fullscreen" aria-label="Fullscreen"></button>
</div>
<!-- Excalidraw is loaded from esm.sh WITHOUT the `?alias=react:…` query.
@@ -129,6 +145,11 @@
const btnSave = document.getElementById("btn-save");
const btnExportPng = document.getElementById("btn-export-png");
const btnExportSvg = document.getElementById("btn-export-svg");
const btnFullscreen = document.getElementById("btn-fullscreen");
// Icon swapped in on a successful save (floppy → checkmark → floppy).
const SAVE_ICON = btnSave.innerHTML;
const CHECK_ICON = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"/></svg>';
// --- postMessage helpers ---
function sendToParent(msg) {
@@ -177,8 +198,8 @@
}
sendToParent({ type: "save", data });
markClean();
btnSave.textContent = "💾 Saved!";
setTimeout(() => { btnSave.textContent = "💾 Save"; }, 1200);
btnSave.innerHTML = CHECK_ICON;
setTimeout(() => { btnSave.innerHTML = SAVE_ICON; }, 1200);
}
function setTheme(theme) {
@@ -189,9 +210,45 @@
}
}
// Excalidraw serializes its Map-typed appState fields (notably
// `collaborators`) to plain JSON objects on save — that is what files
// exported by the Excalidraw app / Obsidian plugin contain. Feeding such a
// plain object back through `initialData.appState` makes Excalidraw 0.18
// call `.forEach()` on it and crash with
// "e.appState.collaborators.forEach is not a function", leaving the canvas
// blank. Restore the expected Map shape (and drop anything unusable).
function sanitizeAppState(appState) {
if (!appState || typeof appState !== "object") return {};
// Viewport geometry is computed by Excalidraw from the container size.
// Files exported by the Excalidraw app carry whatever the *source* window
// measured (Obsidian pane, browser tab, …) and can contain absurd values
// (e.g. `height: 22369622`). Importing them makes Excalidraw size its
// canvas beyond the browser limit, so the scene renders off-screen /
// blank. Drop them and let Excalidraw recompute.
for (const key of ["width", "height", "offsetLeft", "offsetTop"]) {
delete appState[key];
}
if (appState.collaborators && !(appState.collaborators instanceof Map)) {
try {
appState.collaborators = new Map(Object.entries(appState.collaborators));
} catch (e) {
appState.collaborators = new Map();
}
}
return appState;
}
// Signature of the drawn content only. Excalidraw's onChange also fires for
// appState-only changes (resize, fullscreen, zoom, scroll); those must not
// flag the diagram as modified.
function sceneSignature(elements) {
return (elements || []).map((el) => `${el.id}:${el.versionNonce}`).join("|");
}
// --- Excalidraw component ---
function App({ initialData, theme }) {
const [appState, setAppState] = React.useState(null);
const lastSigRef = React.useRef(null);
// Excalidraw 0.18 exposes its imperative API through the `excalidrawAPI`
// prop, called with the API object once mounted (NOT the legacy
@@ -204,13 +261,20 @@
if (theme === "dark") {
api.updateScene({ appState: { theme: "dark" } });
}
// Stop ignoring changes once the initial mount settles.
setTimeout(() => { ignoreChanges = false; }, 800);
// Stop ignoring changes once the initial mount settles, and snapshot
// the loaded scene so a later appState-only change is not "dirty".
setTimeout(() => {
ignoreChanges = false;
lastSigRef.current = sceneSignature(api.getSceneElements());
}, 800);
}
}, [theme]);
const onChange = React.useCallback((elements, state, files) => {
if (ignoreChanges) return;
const sig = sceneSignature(elements);
if (sig === lastSigRef.current) return;
lastSigRef.current = sig;
markDirty();
}, []);
@@ -257,6 +321,7 @@
appState = msg.data.appState || {};
files = msg.data.files || {};
}
appState = sanitizeAppState(appState);
const initialData = { elements, appState, files };
currentTheme = msg.theme || "light";
setTheme(currentTheme);
@@ -340,6 +405,35 @@
console.error("SVG export failed:", err);
}
});
// --- Fullscreen ---
// The parent iframe is created with `allow="fullscreen" allowfullscreen`, so
// requesting fullscreen on this document makes the whole editor fill the
// screen. Excalidraw's ResizeObserver then grows the canvas to match.
const FS_ENTER = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3H5a2 2 0 0 0-2 2v3m18 0V5a2 2 0 0 0-2-2h-3m0 18h3a2 2 0 0 0 2-2v-3M3 16v3a2 2 0 0 0 2 2h3"/></svg>';
const FS_EXIT = '<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 3v3a2 2 0 0 1-2 2H3m18 0h-3a2 2 0 0 1-2-2V3m0 18v-3a2 2 0 0 1 2-2h3M3 16h3a2 2 0 0 1 2 2v3"/></svg>';
function toggleFullscreen() {
if (!document.fullscreenElement) {
const req = document.documentElement.requestFullscreen
&& document.documentElement.requestFullscreen();
if (req && typeof req.catch === "function") {
req.catch((err) => console.warn("Fullscreen request failed:", err));
}
} else if (document.exitFullscreen) {
document.exitFullscreen();
}
}
document.addEventListener("fullscreenchange", () => {
const on = !!document.fullscreenElement;
btnFullscreen.innerHTML = on ? FS_EXIT : FS_ENTER;
btnFullscreen.title = on ? "Exit fullscreen" : "Fullscreen";
btnFullscreen.classList.toggle("active", on);
});
btnFullscreen.innerHTML = FS_ENTER;
btnFullscreen.addEventListener("click", toggleFullscreen);
</script>
</body>
</html>
+325 -226
View File
@@ -2038,210 +2038,95 @@
</button>
</section>
<!-- Cles API AI -->
<!-- Cles API AI (#104 — accordéon fournisseurs) -->
<section
class="config-section help-section"
id="cfg-ai"
>
<h2>🤖 Cles API Intelligence Artificielle</h2>
<p class="config-description">
Configurez vos cles API. Cliquez sur
<strong data-i18n="config.test">Tester</strong> pour charger les
modeles.
</p>
<div class="config-row">
<label
class="config-label"
for="cfg-ai-default-provider"
data-i18n="config.ai_default_provider"
>Fournisseur par defaut</label
>
<select
id="cfg-ai-default-provider"
class="config-select"
style="width: 200px"
>
<option value="">--</option>
</select>
<div class="ai-keys-header">
<div class="ai-keys-header-text">
<h2 data-i18n="config.section_cles-api-intelligence-artificielle">🤖 Cles API Intelligence Artificielle</h2>
<p class="config-description" data-i18n="config.ai_header_desc">
Configurez vos cles API fournisseur par fournisseur. Dépliez une carte pour saisir une
clé, puis cliquez sur <strong data-i18n="config.test">Tester</strong> pour charger les
modeles.
</p>
</div>
<div class="ai-keys-search">
<i data-lucide="search" class="icon"></i>
<input
type="search"
id="cfg-ai-search"
data-i18n-placeholder="config.ai_search_placeholder"
placeholder="Rechercher un fournisseur…"
autocomplete="off"
/>
</div>
</div>
<div class="config-row">
<label
class="config-label"
for="cfg-ai-default-model"
data-i18n="config.ai_default_model"
>Modele par defaut</label
>
<select
id="cfg-ai-default-model"
class="config-select"
style="width: 220px"
>
<option value="">--</option>
</select>
<div class="ai-default-card">
<div class="ai-card-title" data-i18n="config.ai_default_section">Configuration par defaut</div>
<div class="ai-default-grid">
<div class="ai-field">
<label
class="ai-field-label"
for="cfg-ai-default-provider"
data-i18n="config.ai_default_provider"
>Fournisseur par defaut</label
>
<select
id="cfg-ai-default-provider"
class="config-select"
>
<option value="">--</option>
</select>
</div>
<div class="ai-field">
<label
class="ai-field-label"
for="cfg-ai-default-model"
data-i18n="config.ai_default_model"
>Modele par defaut</label
>
<select
id="cfg-ai-default-model"
class="config-select"
>
<option value="">--</option>
</select>
</div>
</div>
<div class="ai-field">
<span
class="ai-field-label"
data-i18n="config.ai_capabilities"
>Capacites du modele</span
>
<div
id="cfg-ai-default-model-caps"
class="ai-caps-badges"
></div>
</div>
</div>
<div class="config-row" style="align-items: flex-start">
<label
class="config-label"
data-i18n="config.ai_capabilities"
>Capacites du modele</label
<div class="ai-providers-header">
<h3
class="ai-card-title"
data-i18n="config.ai_providers_title"
>
<div
id="cfg-ai-default-model-caps"
class="ai-picker-caps"
style="flex: 1"
></div>
</div>
<div class="config-row">
<label
class="config-label"
for="cfg-deepseek-key"
>DeepSeek API Key</label
>
<input
type="password"
id="cfg-deepseek-key"
class="config-input"
placeholder="sk-..."
autocomplete="off"
/>
<select
id="cfg-deepseek-model"
class="config-select"
style="width: 200px"
>
<option value="">-- Modele --</option>
</select>
</div>
<div class="config-row">
<label
class="config-label"
for="cfg-openrouter-key"
>OpenRouter API Key</label
>
<input
type="password"
id="cfg-openrouter-key"
class="config-input"
placeholder="sk-or-..."
autocomplete="off"
/>
<select
id="cfg-openrouter-model"
class="config-select"
style="width: 200px"
>
<option value="">-- Modele --</option>
</select>
</div>
<div class="config-row">
<label
class="config-label"
for="cfg-gemini-key"
>Gemini API Key</label
>
<input
type="password"
id="cfg-gemini-key"
class="config-input"
placeholder="AIza..."
autocomplete="off"
/>
<select
id="cfg-gemini-model"
class="config-select"
style="width: 200px"
>
<option value="">-- Modele --</option>
</select>
</div>
<div class="config-row">
<label
class="config-label"
for="cfg-nvidia-key"
>NVIDIA API Key</label
>
<input
type="password"
id="cfg-nvidia-key"
class="config-input"
placeholder="nvapi-..."
autocomplete="off"
/>
<select
id="cfg-nvidia-model"
class="config-select"
style="width: 200px"
>
<option value="">-- Modele --</option>
</select>
</div>
<div class="config-row">
<label
class="config-label"
for="cfg-qwencloud-key"
>QwenCloud API Key</label
>
<input
type="password"
id="cfg-qwencloud-key"
class="config-input"
placeholder="sk-..."
autocomplete="off"
/>
<select
id="cfg-qwencloud-model"
class="config-select"
style="width: 200px"
>
<option value="">-- Modele --</option>
</select>
</div>
<div class="config-row">
<label
class="config-label"
for="cfg-xiaomi-key"
>Xiaomi API Key</label
>
<input
type="password"
id="cfg-xiaomi-key"
class="config-input"
placeholder="xm-..."
autocomplete="off"
/>
<select
id="cfg-xiaomi-model"
class="config-select"
style="width: 200px"
>
<option value="">-- Modele --</option>
</select>
</div>
<div class="config-row">
<label
class="config-label"
for="cfg-mistral-key"
>Mistral API Key</label
>
<input
type="password"
id="cfg-mistral-key"
class="config-input"
placeholder="sk-..."
autocomplete="off"
/>
<select
id="cfg-mistral-model"
class="config-select"
style="width: 200px"
>
<option value="">-- Modele --</option>
</select>
Fournisseurs d'API
</h3>
</div>
<div id="cfg-ai-providers" class="ai-providers-list"></div>
<div
class="config-actions-row"
style="margin-top: 16px"
id="cfg-ai-providers-empty"
class="ai-providers-empty hidden"
data-i18n="config.ai_providers_empty"
>
Aucun fournisseur ne correspond
</div>
<div class="ai-keys-footer">
<button class="config-btn-save"
id="cfg-save-ai-keys" data-i18n="help.shortcut_save">
Sauvegarder
@@ -2252,11 +2137,7 @@
</button>
<span
id="cfg-ai-status"
style="
font-size: 12px;
color: var(--text-muted);
margin-left: 12px;
"
class="ai-keys-status"
></span>
</div>
</section>
@@ -2988,6 +2869,28 @@
Guide d'utilisation ObsiGate
</div>
<div class="editor-actions">
<button
class="editor-btn"
id="help-download-md"
title="Télécharger ce guide en Markdown"
data-i18n-attr="title:guide105.dl_md_title"
>
<i
data-lucide="file-code-2"
style="width: 16px; height: 16px"
></i>
</button>
<button
class="editor-btn"
id="help-download-pdf"
title="Télécharger ce guide en PDF"
data-i18n-attr="title:guide105.dl_pdf_title"
>
<i
data-lucide="file-down"
style="width: 16px; height: 16px"
></i>
</button>
<button
class="editor-btn"
id="help-close"
@@ -3011,7 +2914,7 @@
type="text"
class="help-nav-search"
id="help-nav-search"
data-i18n-placeholder="help.search_placeholder" data-i18n-placeholder="help.search_placeholder" placeholder="Rechercher dans l'aide..."
data-i18n-placeholder="help.search_placeholder" placeholder="Rechercher dans l'aide..."
autocomplete="off"
spellcheck="false"
/>
@@ -3041,7 +2944,10 @@
data-i18n="help.nav_intro">📘 Introduction</a
>
</li>
<li>
<li>
<a href="#help-architecture" class="help-nav-link" data-i18n="guide105.nav_architecture">🏗️ Architecture</a>
</li>
<li>
<a href="#help-interface" class="help-nav-link"
data-i18n="help.nav_interface">🧭 Interface</a
>
@@ -3076,7 +2982,10 @@
data-i18n="help.nav_excalidraw">🎨 Excalidraw</a
>
</li>
<li>
<li>
<a href="#help-diagrams" class="help-nav-link" data-i18n="guide105.nav_diagrams">📊 Diagrammes</a>
</li>
<li>
<a href="#help-edition" class="help-nav-link"
data-i18n="help.nav_editing">✏️ Édition</a
>
@@ -3086,7 +2995,10 @@
data-i18n="help.nav_mobile_editor">📱 Mobile</a
>
</li>
<li>
<li>
<a href="#help-library" class="help-nav-link" data-i18n="guide105.nav_library">⭐ Bibliothèque</a>
</li>
<li>
<a href="#help-graphe" class="help-nav-link"
data-i18n="help.nav_graph">🗺️ Graphe</a
>
@@ -3105,8 +3017,17 @@
<a href="#help-raccourcis" class="help-nav-link"
data-i18n="help.nav_shortcuts">⌨️ Raccourcis</a
>
</li>
<li>
<a href="#help-offline" class="help-nav-link" data-i18n="guide105.nav_offline">📴 Hors-ligne</a>
</li>
<li>
<a href="#help-collab" class="help-nav-link" data-i18n="guide105.nav_collab">👥 Collaboration</a>
</li>
<li>
<a href="#help-desktop" class="help-nav-link" data-i18n="guide105.nav_desktop">🖥️ Desktop</a>
</li>
<li>
<a href="#help-partage" class="help-nav-link"
data-i18n="help.nav_sharing">🔗 Partage</a
>
@@ -3139,8 +3060,14 @@
<a href="#help-astuces" class="help-nav-link"
data-i18n="help.nav_tips">💡 Astuces</a
>
</li>
<li>
<a href="#help-api" class="help-nav-link" data-i18n="guide105.nav_api">🔌 API</a>
</li>
<li>
<a href="#help-languages" class="help-nav-link" data-i18n="guide105.nav_languages">🌍 Multilingue</a>
</li>
<li>
<a href="#help-plugins" class="help-nav-link"
data-i18n="help.nav_plugins">🧩 Plugins</a
>
@@ -3199,7 +3126,74 @@
</div>
</section>
<section class="help-section" id="help-interface">
<section class="help-section" id="help-architecture">
<h2 data-i18n="guide105.nav_architecture">🏗️ Architecture</h2>
<p data-i18n-html="guide105.arch_intro">ObsiGate est une application web complète construite en couches indépendantes, sans base de données externe : les notes vivent dans vos dossiers Obsidian, l'état applicatif dans des fichiers JSON de <code>data/</code>, l'index de recherche en mémoire.</p>
<pre class="mermaid-code"><code class="language-mermaid">flowchart TB
subgraph client["Clients"]
UI["SPA vanilla JS\n(frontend/js)"]
PWA["PWA hors-ligne\n(service worker + IndexedDB)"]
DESK["App desktop Tauri\n(fenêtre native)"]
end
subgraph server["Serveur FastAPI (Python 3.11)"]
API["REST /api\nJWT + Argon2id"]
IDX["Index recherche\nTF-IDF + embeddings"]
FS["Accès fichiers\nwatchdog + safe paths"]
PDF["Rendu markdown\nmistune + WeasyPrint"]
AI["Assistant IA\nproviders + outils"]
MCP["Serveur MCP\n/mcp (HTTP)"]
WS["WebSocket\ncollab Yjs + SSE"]
WH["Webhooks\nHMAC-SHA256"]
end
subgraph data["Données"]
V1["Vault 1 (dossier)"]
V2["Vault 2 (dossier)"]
CFG["data/*.json\nconfig, users, audit"]
BK[".obsigate-backup/\nbackups horodatés"]
end
UI -- HTTP --> API
PWA -- "cache + queue" --> API
DESK -- embarqué --> API
API --> IDX
API --> FS
API --> PDF
API --> AI
MCP --> AI
WS --> FS
FS --> V1
FS --> V2
IDX --> V1
IDX --> V2
BK --> V1
API --> CFG
API -- événements --> WH</code></pre>
<p data-i18n="guide105.arch_diagram_note">Le diagramme est interactif dans l'application : zoom, plein écran, copie SVG ou code.</p>
<h3 data-i18n="guide105.arch_h3_layers">Les grandes composantes</h3>
<ul>
<li>
<strong data-i18n="guide105.arch_lbl_fe">Frontend</strong><span data-i18n-html="guide105.arch_fe"> — SPA en JavaScript vanilla (modules ES), sans framework ni build npm : <code>frontend/js/</code> (~30 modules). Le CSS utilise des variables pour les thèmes.</span>
</li>
<li>
<strong data-i18n="guide105.arch_lbl_be">Backend</strong><span data-i18n="guide105.arch_be"> — serveur FastAPI (Python 3.11) : rendu markdown (mistune + wikilinks), recherche TF-IDF stemmisée (index inversé en mémoire), watchers watchdog, JWT + Argon2id, webhooks HMAC, export PDF (WeasyPrint).</span>
</li>
<li>
<strong data-i18n="guide105.arch_lbl_realtime">Temps réel & MCP</strong><span data-i18n-html="guide105.arch_rt"> — passerelle WebSocket (collaboration Yjs, notifications SSE/push) et serveur MCP (Streamable HTTP, <code>/mcp</code>) pour les clients externes.</span>
</li>
<li>
<strong data-i18n="guide105.arch_lbl_ai">Couche IA</strong><span data-i18n="guide105.arch_ai"> — assistants d'édition et BooksLM multi-providers (DeepSeek, OpenRouter, Gemini, Mistral…), bibliothèque d'outils (function calling, recherche web, crawl, lecture de documents) et embeddings optionnels pour la recherche sémantique.</span>
</li>
<li>
<strong data-i18n="guide105.arch_lbl_data">Données</strong><span data-i18n-html="guide105.arch_data"> — les vaults Obsidian sur disque (source de vérité), la configuration en JSON (<code>data/</code>), les backups horodatés (<code>.obsigate-backup/</code>), l'audit en JSON lines, les clés API chiffrées dans <code>data/api_keys.json</code>.</span>
</li>
<li>
<strong data-i18n="guide105.arch_lbl_deploy">Déploiement</strong><span data-i18n="guide105.arch_deploy"> — application desktop Tauri (Rust) embarquant le backend Python, conteneur Docker, ou PWA installable dans le navigateur (mode hors-ligne).</span>
</li>
</ul>
<h3 data-i18n="guide105.arch_h3_flux">Flux typique</h3>
<p data-i18n-html="guide105.arch_flux"> Un clic sur un fichier émet <code>GET /api/file/...</code> ; le backend résout le chemin en sécurité, parse le frontmatter, rend le markdown et renvoie le HTML ; le frontend enrichit l'affichage (Mermaid, coloration, wikilinks cliquables). Chaque écriture crée un backup avant application.</p>
</section>
<section class="help-section" id="help-interface">
<h2 data-i18n="help.nav_interface">🧭 Interface utilisateur</h2>
<h3 data-i18n="help.header_section">En-tête</h3>
@@ -3289,7 +3283,10 @@
avec wikilinks et images</span>
</li>
</ul>
</section>
<h3 data-i18n="guide105.h3_push">Notifications web (push)</h3>
<p data-i18n="guide105.push_p1">Autorisez les notifications (bouton 🔔 de l'en-tête) pour être averti des fins de synchronisation hors-ligne et des événements importants. La gestion des abonnements est dans les Configurations.</p>
<p data-i18n="guide105.push_p2">Basée sur la Web Push API (clés VAPID) ; fonctionne sur desktop et PWA mobile, sans service tiers : le serveur émet directement vers les endpoints push des navigateurs.</p>
</section>
<section class="help-section" id="help-navigation">
<h2 data-i18n="help.733f0559">🗺️ Navigation</h2>
@@ -3448,7 +3445,7 @@
<h2 data-i18n="help.adf30d78">🔍 Recherche</h2>
<h3 data-i18n="help.simple_search">Recherche simple</h3>
<p data-i18n="help.desc_search_intro">
<p data-i18n-html="help.desc_search_intro">
Tapez dans la barre de recherche en haut pour
lancer une recherche fulltext :
</p>
@@ -3501,7 +3498,7 @@
</li>
</ul>
<p>
<strong>Exemples</strong><span data-i18n="help.desc_examples">:
<strong>Exemples</strong><span data-i18n-html="help.desc_examples">:
<code>ext:sh</code> recherche dans les scripts
bash, <code>ext:py</code> dans les scripts
Python, <code>ext:md</code> dans les fichiers
@@ -3577,13 +3574,16 @@
<strong>Tri par date</strong><span data-i18n="help.desc_42a81347"> : Dernière
modification</span></li>
</ul>
</section>
<h3 data-i18n="guide105.h3_semantic">Recherche sémantique (hybride)</h3>
<p data-i18n="guide105.sem_p1">Activez le bouton « S » de la barre de recherche (ou Alt-S) pour combiner TF-IDF et similarité vectorielle (fusion RRF) : les concepts approchants (« velours » trouve « tissu doux ») remontent mieux.</p>
<p data-i18n="guide105.sem_p2">Le moteur d'embeddings (modèle multilingue) est optionnel : sans lui, un repli par hash conserve une recherche hybride fonctionnelle. Les vecteurs sont recalculés à chaque indexation du vault.</p>
</section>
<section class="help-section" id="help-tags">
<h2 data-i18n="help.2507242f">🏷️ Tags</h2>
<h3 data-i18n="help.5f87ea79">Tag cloud</h3>
<p data-i18n="help.desc_tag_cloud_intro">
<p data-i18n-html="help.desc_tag_cloud_intro">
L'onglet Tags de la sidebar affiche un nuage de
tags :
</p>
@@ -3605,15 +3605,15 @@
</ul>
<h3 data-i18n="help.2c03a7ba">Tags inline vs frontmatter</h3>
<p data-i18n="help.desc_two_tag_types">ObsiGate supporte deux types de tags :</p>
<p data-i18n-html="help.desc_two_tag_types">ObsiGate supporte deux types de tags :</p>
<ul>
<li>
<strong>Frontmatter YAML</strong><span data-i18n="help.desc_frontmatter">:
<strong>Frontmatter YAML</strong><span data-i18n-html="help.desc_frontmatter">:
<code>tags: [docker, linux]</code> ou
<code>tags: docker, linux</code></span>
</li>
<li>
<strong>Inline</strong><span data-i18n="help.desc_inline_tags">:
<strong>Inline</strong><span data-i18n-html="help.desc_inline_tags">:
<code>#docker</code> dans le contenu
markdown</span>
</li>
@@ -3623,13 +3623,13 @@
</ul>
<h3 data-i18n="help.63f024d4">Filtrage de tags template</h3>
<p data-i18n="help.desc_template_intro">
<p data-i18n-html="help.desc_template_intro">
Dans les Configurations, vous pouvez masquer les
tags de template :
</p>
<ul>
<li>
<strong>Patterns wildcards</strong><span data-i18n="help.desc_patterns">: Ex:
<strong>Patterns wildcards</strong><span data-i18n-html="help.desc_patterns">: Ex:
<code>#&lt;% ... %&gt;</code> ou
<code>#{{ ... }}</code></span>
</li>
@@ -3649,12 +3649,12 @@
<p data-i18n="help.desc_md_render">Les fichiers markdown sont rendus avec :</p>
<ul>
<li>
<strong>Wikilinks cliquables</strong><span data-i18n="help.desc_wikilinks">:
<strong>Wikilinks cliquables</strong><span data-i18n-html="help.desc_wikilinks">:
<code>[[lien]]</code> et
<code>[[lien|texte]]</code></span>
</li>
<li>
<strong>Images Obsidian</strong><span data-i18n="help.desc_images">: Support
<strong>Images Obsidian</strong><span data-i18n-html="help.desc_images">: Support
de <code>![[image.png]]</code></span>
</li>
<li>
@@ -3754,7 +3754,13 @@
.csv
</li>
</ul>
</section>
<h3 data-i18n="guide105.h3_pdf">Export PDF</h3>
<p data-i18n-html="guide105.pdf_p">Le bouton « PDF » d'un document le rend avec le même moteur que la vue (WeasyPrint) : titres, tableaux, listes et code sont conservés. Depuis un lien public, la route <code>/s/{token}/pdf</code> produit le même PDF.</p>
<h3 data-i18n="guide105.h3_exports">Export HTML / ePub / ZIP</h3>
<p data-i18n="guide105.exp_p">Le menu « Exporter » propose trois formats : HTML autonome (fichier unique, images incluses), ePub pour les liseuses et, pour un dossier, un bundle Markdown en ZIP — liens et ressources résolus pendant l'export.</p>
<h3 data-i18n="guide105.h3_dupe">Anti-doublons à l'upload</h3>
<p data-i18n="guide105.dupe_p">L'upload en masse (glisser-déposer un dossier sur la sidebar) compare chaque fichier au contenu existant : un fichier déjà présent est ignoré plutôt que dupliqué avec un suffixe « (1) ». Utile pour restaurer un vault sans créer de doublons.</p>
</section>
<!-- 🎨 Excalidraw -->
<section class="help-section" id="help-excalidraw">
@@ -3801,7 +3807,21 @@
</section>
<!-- ✏️ Édition -->
<section class="help-section" id="help-edition">
<section class="help-section" id="help-diagrams">
<h2 data-i18n="guide105.nav_diagrams">📊 Diagrammes</h2>
<p data-i18n-html="guide105.dia_intro">Les blocs <code>```mermaid</code> de vos notes sont rendus en diagrammes interactifs (Mermaid v11, chargé depuis un CDN).</p>
<ul>
<li data-i18n="guide105.dia_zoom">Zoom : boutons + / − dans la barre d'outils du diagramme.</li>
<li data-i18n="guide105.dia_fs">Plein écran : idéal pour les grandes matrices.</li>
<li data-i18n="guide105.dia_copy">Copie : exportez le SVG ou le code source (boutons dédiés).</li>
<li data-i18n="guide105.dia_toggle">Bascule Aperçu / Code pour éditer la source sans quitter la vue.</li>
<li data-i18n="guide105.dia_theme">Thème : le diagramme suit le thème clair/sombre de l'application.</li>
</ul>
<p data-i18n="guide105.dia_types">Types supportés : flowchart, sequence, class, state, ER, gantt, pie, journey, quadrant, radar, mindmap, timeline, C4, xychart, sankey — plus un préprocesseur qui comprend la syntaxe Obsidian.</p>
<p data-i18n-html="guide105.dia_excalidraw_ref">Les dessins à main levée (<code>.excalidraw</code>, <code>.excalidraw.md</code>) sont couverts dans la section 🎨 Excalidraw.</p>
</section>
<section class="help-section" id="help-edition">
<h2 data-i18n="auto.f346076a">✏️ Édition avancée</h2>
<h3 data-i18n="auto.695d9e47">Éditeur CodeMirror 6</h3>
@@ -3838,11 +3858,15 @@
<li>
<strong data-i18n="help.toolbar_section">Barre d'outils AI</strong><span data-i18n="help.desc_c8532869"> :
Complétion, réécriture, traduction (voir
section</span><a href="#help-ia" data-i18n="settings.ai">🤖 IA</a>)
section</span><a href="#help-ai" data-i18n="settings.ai">🤖 IA</a>)
</li>
</ul>
<h3 data-i18n="help.mobile_editor_title">📱 Édition mobile</h3>
</section>
<!-- 🗺️ Graphe -->
<section class="help-section" id="help-mobile-editor">
<h2 data-i18n="help.mobile_editor_title">📱 Édition mobile</h2>
<p data-i18n="help.mobile_editor_intro">
Sur téléphone et tablette, l'édition s'adapte au
tactile : barre d'outils flottante, gestes et mode
@@ -3879,8 +3903,21 @@
</ul>
</section>
<!-- 🗺️ Graphe -->
<section class="help-section" id="help-graphe">
<section class="help-section" id="help-library">
<h2 data-i18n="guide105.nav_library">⭐ Bibliothèque</h2>
<h3 data-i18n="guide105.lib_h3_bookmarks">Signets & récents</h3>
<p data-i18n="guide105.lib_bookmarks">Marquez un fichier d'un ★ (bouton Signet de la barre d'actions) : il rejoint la liste des signets du dashboard. Les fichiers récemment ouverts sont listés automatiquement dans l'onglet « Récents » de la sidebar, avec un filtre de recherche dédié.</p>
<h3 data-i18n="guide105.lib_h3_saved">Recherches sauvegardées</h3>
<p data-i18n="guide105.lib_saved">Enregistrez une recherche depuis la page de résultats pour la relancer en un clic depuis la sidebar : chaque recherche sauvegardée conserve ses opérateurs et filtres.</p>
<h3 data-i18n="guide105.lib_h3_backlinks">Backlinks & graphe</h3>
<p data-i18n="guide105.lib_backlinks">Le panneau Backlinks liste toutes les notes qui pointent vers le fichier ouvert. La vue Graphe (bouton 🕸️) affiche les liens entre fichiers : glissez les nœuds, zoomez à la molette, double-cliquez pour ouvrir une note.</p>
<h3 data-i18n="guide105.lib_h3_conflicts">Conflits de synchronisation</h3>
<p data-i18n="guide105.lib_conflicts">Si vous synchronisez le vault avec Syncthing, ObsiGate détecte les fichiers de conflit (copies « sync-conflict ») et propose de les comparer puis résoudre depuis la page dédiée du menu Options.</p>
<h3 data-i18n="guide105.lib_h3_attach">Fichiers joints & médias</h3>
<p data-i18n-html="guide105.lib_attach">Les images <code>![[image.png]]</code>, pièces jointes et médias (audio, vidéo, PDF intégrés) dans les notes sont rendus dans le viewer et indexés pour la recherche ; le bouton « Rescan attachments » de la configuration recrée l'index des pièces jointes.</p>
</section>
<section class="help-section" id="help-graphe">
<h2 data-i18n="help.9c7a0a8d">🗺️ Vue Graphe</h2>
<p data-i18n="help.desc_graph_intro">
La vue graphe offre une visualisation
@@ -4033,7 +4070,9 @@
rescan des vaults
</li>
</ul>
</section>
<h3 data-i18n="guide105.h3_panes">Vue multi-panneaux (split view)</h3>
<p data-i18n="guide105.panes_p">Le bouton « Diviser » de la barre d'actions ouvre le document dans un panneau jumeau ; empilez plusieurs panneaux pour comparer deux notes ou lire et éditer en parallèle. Les largeurs se règlent au bord des panneaux et sont mémorisées.</p>
</section>
<!-- ⌨️ Palette de commandes -->
<section class="help-section" id="help-palette">
@@ -4492,7 +4531,37 @@
</section>
<!-- 🔗 Partage -->
<section class="help-section" id="help-partage">
<section class="help-section" id="help-offline">
<h2 data-i18n="guide105.nav_offline">📴 Hors-ligne</h2>
<ul>
<li data-i18n="guide105.off_pwa">ObsiGate est une PWA : installez-la (icône d'installation de la barre d'adresse) pour l'ouvrir comme une application. Le service worker met en cache l'interface et vos derniers documents consultés.</li>
<li data-i18n="guide105.off_edit">Hors-ligne, vous pouvez lire les documents en cache et même les éditer : les modifications sont mises en file d'attente dans IndexedDB.</li>
<li data-i18n="guide105.off_sync">Au retour en ligne, la file se rejoue automatiquement (badge de synchronisation dans l'en-tête). Si la version serveur a divergé entre-temps, le fichier est marqué en conflit et la version serveur est préservée en backup.</li>
<li data-i18n="guide105.off_watch">Les modifications externes (Obsidian sur disque) sont détectées par le watcher : la vue se recharge sans perte de position, ou signale « modifié en externe » pendant une édition.</li>
</ul>
</section>
<section class="help-section" id="help-collab">
<h2 data-i18n="guide105.nav_collab">👥 Collaboration</h2>
<ul>
<li data-i18n="guide105.col_intro">Ouvrez un document en mode Édition : plusieurs personnes peuvent travailler simultanément sur le même fichier via un WebSocket Yjs (CRDT). Les modifications fusionnent sans verrou.</li>
<li data-i18n="guide105.col_cursors">Les curseurs et sélections des collaborateurs apparaissent avec une couleur et un nom par personne (awareness).</li>
<li data-i18n="guide105.col_save">La fusion est persistée côté serveur après 2 s d'inactivité ; chaque écriture crée un backup horodaté avant application.</li>
<li data-i18n="guide105.col_perm">Accès limité aux utilisateurs authentifiés disposant de la permission sur la vault.</li>
</ul>
</section>
<section class="help-section" id="help-desktop">
<h2 data-i18n="guide105.nav_desktop">🖥️ Desktop</h2>
<ul>
<li data-i18n="guide105.des_get">L'application desktop ObsiGate (Tauri) embarque le serveur Python : aucune installation de Docker nécessaire. Elle se télécharge sur la page des Releases du dépôt et se met à jour automatiquement (updater signé).</li>
<li data-i18n="guide105.des_wizard">Au premier lancement, un assistant demande le dossier de vos vaults (ou crée un vault de démonstration). Chaque document peut être détaché en fenêtre native séparée.</li>
<li data-i18n="guide105.des_data">Les données desktop restent dans le répertoire applicatif ; les vaults pointent sur vos dossiers existants. Toutes les fonctionnalités web (recherche, IA, partage) sont disponibles.</li>
<li data-i18n="guide105.des_native">Menu système natif, raccourci global optionnel pour afficher/masquer la fenêtre et jumplist des vaults récents.</li>
</ul>
</section>
<section class="help-section" id="help-partage">
<h2 data-i18n="help.8c65b2f2">🔗 Partage et Webhooks</h2>
<h3 data-i18n="help.public_shares">Publication publique</h3>
@@ -5075,7 +5144,11 @@ curl -X POST https://votre-serveur.com/webhook \
tourne avec UID 1000
</li>
</ul>
</section>
<h3 data-i18n="guide105.h3_mfa">MFA : TOTP, WebAuthn, codes de secours</h3>
<p data-i18n="guide105.mfa_p">Activez la double authentification dans Réglages → Profil : applications TOTP (Authy, Aegis…), clés de sécurité et passkeys (WebAuthn, y compris Windows Hello) et 10 codes de secours à conserver hors ligne. Chaque méthode s'active et se désactive indépendamment.</p>
<h3 data-i18n="guide105.h3_admin">Tableau de bord administrateur</h3>
<p data-i18n-html="guide105.admin_p">Le rôle admin ouvre une page dédiée <code>/admin.html</code> (bouton du menu Options) : statut du serveur en direct, utilisateurs, vaults, sessions actives et journal d'audit. Le CRUD utilisateurs est aussi disponible dans les Configurations.</p>
</section>
<section class="help-section" id="help-astuces">
<h2 data-i18n="help.686f8313">💡 Astuces et bonnes pratiques</h2>
@@ -5181,7 +5254,33 @@ curl -X POST https://votre-serveur.com/webhook \
</section>
<!-- 🧩 Plugins -->
<section class="help-section" id="help-plugins">
<section class="help-section" id="help-api">
<h2 data-i18n="guide105.nav_api">🔌 API</h2>
<p data-i18n="guide105.api_intro">ObsiGate expose une API REST couvrant toute l'application (vaults, fichiers, recherche, backups, export, IA, partage, admin), documentée en OpenAPI 3.1 :</p>
<ul>
<li data-i18n-html="guide105.api_docs_url"><code>/docs</code> — interface Swagger UI pour essayer les requêtes en direct.</li>
<li data-i18n-html="guide105.api_redoc"><code>/redoc</code> — référence alternative plus compacte.</li>
<li data-i18n-html="guide105.api_landing"><code>/api</code> — page de garde regroupant les endpoints par catégorie.</li>
<li data-i18n-html="guide105.api_schema"><code>/openapi.json</code> — le schéma machine, à importer dans Postman ou Insomnia.</li>
</ul>
<h3 data-i18n="guide105.api_h3_auth">Authentification</h3>
<p data-i18n-html="guide105.api_auth">Connectez-vous via <code>POST /api/auth/login</code> pour obtenir un token Bearer (le même jeton est accepté en cookie HttpOnly, ce qui permet aux clients navigateur d'utiliser <code>credentials: "include"</code>). Toutes les routes <code>/api/*</code> exigent ce jeton sauf mention contraire.</p>
<h3 data-i18n="guide105.api_h3_mcp">Serveur MCP</h3>
<p data-i18n-html="guide105.api_mcp">Les outils de l'assistant IA (lire, lister, chercher, ouvrir, écrire…) sont exposés à tout client MCP (Claude Desktop, Cursor, Cline…) sur <code>https://votre-instance/mcp</code> avec un token d'API. Configuration et exemples : <code>docs/MCP_GUIDE.md</code>.</p>
<h3 data-i18n="guide105.api_h3_autom">Automatisation</h3>
<p data-i18n-html="guide105.api_autom">Pour automatiser depuis l'extérieur : <code>GET /api/search?q=…</code> et <code>GET /api/file/{vault}?path=…</code> permettent d'indexer ou relire vos notes dans un autre outil ; les webhooks sortants (section 🪝) évitent le polling.</p>
</section>
<section class="help-section" id="help-languages">
<h2 data-i18n="guide105.nav_languages">🌍 Multilingue</h2>
<ul>
<li data-i18n="guide105.lng_how">L'interface est intégralement bilingue français / anglais. Réglages → Profil → Langue : le choix est enregistré sur votre compte et vous suit sur tous les appareils.</li>
<li data-i18n="guide105.lng_scope">Tout est traduit : menus, messages, notifications, et le présent guide. Les réponses de l'assistant IA suivent la langue de vos documents.</li>
<li data-i18n="guide105.lng_export">Les boutons Markdown / PDF de ce guide téléchargent la version dans votre langue.</li>
</ul>
</section>
<section class="help-section" id="help-plugins">
<h2 data-i18n="help.plugins_title">🧩 Plugins</h2>
<p data-i18n="help.plugins_intro">
Les plugins étendent ObsiGate : affichage personnalisé des
+159
View File
@@ -0,0 +1,159 @@
// ObsiGate — #106 : Actions instantanées de l'assistant IA.
//
// Two responsibilities, deliberately framework-free and DOM-free so the
// context rules stay unit-testable (tests/frontend/ai-quick-actions.test.mjs):
//
// 1. ACTION_CATALOG — every prompt action grouped by category. Each action
// carries an id, a lucide icon name, an i18n label key and an i18n
// prompt key; both strings are resolved through t() at render time so
// the FR/EN switch is live.
// 2. detectContext / suggestionsFor — a pure function of the assistant's
// live state (mode, open documents, current file, editor selection)
// returning the context key, then the 3 top action ids for that context
// (contextual triage table, see docs/features/ai-quick-actions.md).
//
// Context precedence (first match wins):
// selection — the user has a live text selection in the open editor
// code — the focused document is a source file (.py, .js, .sh…)
// multi_doc — two or more documents are open in tabs/panes
// single_doc — exactly one text document (.md, .txt, …) is open
// directory — a vault folder was opened from the tree context menu
// general — nothing open: app-help assistant
import { t } from './i18n.js';
/** Categories of the action catalogue (order = drawer display order). */
export const CATEGORIES = Object.freeze([
{ id: 'synthesis', icon: 'sparkles', labelKey: 'qa.cat_synthesis' },
{ id: 'structure', icon: 'list-checks', labelKey: 'qa.cat_structure' },
{ id: 'code', icon: 'code', labelKey: 'qa.cat_code' },
{ id: 'cross', icon: 'git-compare', labelKey: 'qa.cat_cross' },
{ id: 'edition', icon: 'pen-tool', labelKey: 'qa.cat_edition' },
{ id: 'general', icon: 'help-circle', labelKey: 'qa.cat_general' },
]);
/**
* The full catalogue. `labelKey` is the button text, `promptKey` the message
* actually sent to the assistant (kept richer than the label on purpose:
* labels stay scannable, prompts stay precise).
*/
export const ACTION_CATALOG = Object.freeze([
// ── Synthèse & Analyse ──────────────────────────────────────────────
{ id: 'summarize_3', cat: 'synthesis', icon: 'align-left', labelKey: 'qa.summarize_3', promptKey: 'qa.summarize_3.prompt' },
{ id: 'frictions', cat: 'synthesis', icon: 'alert-triangle', labelKey: 'qa.frictions', promptKey: 'qa.frictions.prompt' },
{ id: 'vulgarize', cat: 'synthesis', icon: 'lightbulb', labelKey: 'qa.vulgarize', promptKey: 'qa.vulgarize.prompt' },
{ id: 'faq', cat: 'synthesis', icon: 'help-circle', labelKey: 'qa.faq', promptKey: 'qa.faq.prompt' },
// ── Productivité & Structuration ────────────────────────────────────
{ id: 'checklist', cat: 'structure', icon: 'list-checks', labelKey: 'qa.checklist', promptKey: 'qa.checklist.prompt' },
{ id: 'plan', cat: 'structure', icon: 'list-ordered', labelKey: 'qa.plan', promptKey: 'qa.plan.prompt' },
{ id: 'memo', cat: 'structure', icon: 'scroll-text', labelKey: 'qa.memo', promptKey: 'qa.memo.prompt' },
{ id: 'frontmatter', cat: 'structure', icon: 'braces', labelKey: 'qa.frontmatter', promptKey: 'qa.frontmatter.prompt', agent: true },
{ id: 'frontmatter_update', cat: 'structure', icon: 'refresh-cw', labelKey: 'qa.frontmatter_update', promptKey: 'qa.frontmatter_update.prompt', agent: true },
{ id: 'backlinks', cat: 'structure', icon: 'link-2', labelKey: 'qa.backlinks', promptKey: 'qa.backlinks.prompt' },
{ id: 'sections', cat: 'structure', icon: 'heading', labelKey: 'qa.sections', promptKey: 'qa.sections.prompt' },
// ── Code & Scripts ───────────────────────────────────────────────────
{ id: 'explain_code', cat: 'code', icon: 'file-code', labelKey: 'qa.explain_code', promptKey: 'qa.explain_code.prompt' },
{ id: 'audit_code', cat: 'code', icon: 'bug', labelKey: 'qa.audit_code', promptKey: 'qa.audit_code.prompt' },
{ id: 'doc_code', cat: 'code', icon: 'braces', labelKey: 'qa.doc_code', promptKey: 'qa.doc_code.prompt' },
{ id: 'test_code', cat: 'code', icon: 'flask-conical', labelKey: 'qa.test_code', promptKey: 'qa.test_code.prompt' },
// ── Cross-documents ──────────────────────────────────────────────────
{ id: 'compare', cat: 'cross', icon: 'git-compare', labelKey: 'qa.compare', promptKey: 'qa.compare.prompt' },
{ id: 'merge', cat: 'cross', icon: 'layers', labelKey: 'qa.merge', promptKey: 'qa.merge.prompt' },
{ id: 'timeline', cat: 'cross', icon: 'history', labelKey: 'qa.timeline', promptKey: 'qa.timeline.prompt' },
// ── Édition & Reformulation (sélection active) ───────────────────────
{ id: 'concise', cat: 'edition', icon: 'scissors', labelKey: 'qa.concise', promptKey: 'qa.concise.prompt' },
{ id: 'fix_style', cat: 'edition', icon: 'spell-check', labelKey: 'qa.fix_style', promptKey: 'qa.fix_style.prompt' },
{ id: 'rephrase', cat: 'edition', icon: 'pen-tool', labelKey: 'qa.rephrase', promptKey: 'qa.rephrase.prompt' },
{ id: 'translate', cat: 'edition', icon: 'languages', labelKey: 'qa.translate', promptKey: 'qa.translate.prompt' },
// ── Général (aucun document ouvert) — reprises des anciennes suggestions
{ id: 'capabilities', cat: 'general', icon: 'sparkles', labelKey: 'qa.capabilities', promptKey: 'qa.capabilities.prompt' },
{ id: 'search_help', cat: 'general', icon: 'search', labelKey: 'qa.search_help', promptKey: 'qa.search_help.prompt' },
{ id: 'create_note', cat: 'general', icon: 'notebook-pen', labelKey: 'qa.create_note', promptKey: 'qa.create_note.prompt' },
]);
/** id → action record, for O(1) lookup by the preset tables. */
export const ACTIONS_BY_ID = Object.freeze(
ACTION_CATALOG.reduce((acc, a) => { acc[a.id] = a; return acc; }, {}),
);
/** File extensions treated as source code (drive the `code` context). */
export const CODE_EXT_RE = /\.(?:py|js|mjs|cjs|ts|tsx|jsx|vue|svelte|go|rs|java|kt|c|h|cpp|hpp|cc|cs|php|rb|swift|sh|bash|zsh|ps1|bat|sql|lua|pl|r|dart|scala)$/i;
/** Text-ish document extensions (everything else stays "single_doc"). */
export const TEXT_DOC_EXT_RE = /\.(?:md|markdown|mdx|txt|rst|org|adoc)$/i;
/**
* Map a set of live facts to one context key.
*
* @param {object} facts
* @param {string} facts.mode assistant mode ('directory'|'documents'|'general')
* @param {number} facts.docCount number of open documents (tabs/panes)
* @param {string|null} facts.currentPath path of the focused document, if any
* @param {boolean} facts.hasSelection true when the open editor holds a text selection
* @param {number} [facts.fileCount] indexed files of the current directory context
* @returns {'selection'|'code'|'multi_doc'|'single_doc'|'directory'|'general'}
*/
export function detectContext(facts) {
const { mode, docCount = 0, currentPath = null, hasSelection = false } = facts || {};
// A live editor selection is the strongest intent: act on the selection.
if (hasSelection) return 'selection';
if (mode === 'documents' || docCount > 0) {
if (currentPath && CODE_EXT_RE.test(currentPath)) return 'code';
if (docCount >= 2) return 'multi_doc';
return 'single_doc';
}
if (mode === 'directory') return 'directory';
return 'general';
}
/**
* Contextual triage: the 3 top action ids per context (the "boutons 1-3" of
* the design table). Everything not shown stays reachable via the drawer.
*/
export const CONTEXT_PRESETS = Object.freeze({
single_doc: ['summarize_3', 'checklist', 'frontmatter', 'frontmatter_update'],
multi_doc: ['merge', 'compare', 'frictions'],
code: ['explain_code', 'audit_code', 'test_code'],
selection: ['concise', 'fix_style', 'explain_selection'],
directory: ['summarize_dir', 'themes', 'checklist'],
general: ['capabilities', 'search_help', 'create_note'],
});
// Preset ids that are context phrasings rather than catalogue entries
// (their prompt needs the directory/list framing, so they are synthesized).
const EXTRA_ACTIONS = Object.freeze({
explain_selection: { id: 'explain_selection', cat: 'edition', icon: 'lightbulb', labelKey: 'qa.explain_selection', promptKey: 'qa.explain_selection.prompt' },
summarize_dir: { id: 'summarize_dir', cat: 'synthesis', icon: 'align-left', labelKey: 'bookslm.suggestion_summary', promptKey: 'bookslm.suggestion_summary' },
themes: { id: 'themes', cat: 'synthesis', icon: 'library', labelKey: 'bookslm.suggestion_themes', promptKey: 'bookslm.suggestion_themes' },
});
/** Resolve an action id (catalogue or preset extra) to its record. */
export function getAction(id) {
return ACTIONS_BY_ID[id] || EXTRA_ACTIONS[id] || null;
}
/**
* The ordered action records suggested for one context key.
* Unknown keys fall back to the general preset (never throws).
*/
export function suggestionsFor(contextKey) {
const ids = CONTEXT_PRESETS[contextKey] || CONTEXT_PRESETS.general;
return ids.map((id) => getAction(id)).filter(Boolean);
}
/** Translated label + prompt for an action record (empty string when absent). */
export function actionTexts(action) {
if (!action) return { label: '', prompt: '' };
return { label: t(action.labelKey), prompt: t(action.promptKey) };
}
/** Badge text for the contextual header chip. */
export function contextBadgeKey(contextKey, docCount) {
switch (contextKey) {
case 'selection': return 'qa.badge_selection';
case 'code': return 'qa.badge_code';
case 'multi_doc': return 'qa.badge_multi';
case 'single_doc': return 'qa.badge_single';
case 'directory': return 'qa.badge_directory';
default: return docCount > 0 ? 'qa.badge_single' : 'qa.badge_general';
}
}
+19
View File
@@ -82,6 +82,24 @@ function renderCapabilityList(caps) {
return box;
}
/**
* Render only the *enabled* capabilities as colored tags (#104). Used by the
* config panel where a compact read-only summary reads better than checkboxes.
*/
function renderCapabilityBadges(caps) {
const box = document.createElement('div');
box.className = 'ai-caps-badges';
if (!caps) return box;
AI_CAPABILITY_KEYS.forEach((key) => {
if (!caps[key]) return;
const item = document.createElement('span');
item.className = 'ai-cap-badge';
item.textContent = t(`ai.cap_${key}`);
box.appendChild(item);
});
return box;
}
/** Accent-insensitive, case-insensitive normalization for model search. */
function _normalizeText(value) {
return String(value || '')
@@ -1019,6 +1037,7 @@ export {
AI_CAPABILITY_KEYS,
getModelCapabilities,
renderCapabilityList,
renderCapabilityBadges,
_buildPickerUI as buildAIPickerUI,
refreshAIPickers,
PICKER_SLOT_CLASS,
+253 -34
View File
@@ -10,6 +10,15 @@ import { safeCreateIcons } from './utils.js';
import { api, AuthManager } from './auth.js';
import { showToast } from './ui.js';
import { state } from './state.js';
// #106 — contextual quick actions (catalogue + triage rules live in ai-quick-actions.js).
import {
detectContext,
suggestionsFor,
actionTexts,
contextBadgeKey,
ACTION_CATALOG,
CATEGORIES,
} from './ai-quick-actions.js';
export const MODE = Object.freeze({
DIRECTORY: 'directory',
@@ -920,6 +929,7 @@ class BooksLM {
<span class="bookslm-title"></span>
<span class="bookslm-subtitle"></span>
</div>
<span class="bookslm-qa-badge hidden" data-qa-context=""></span>
<div class="bookslm-header-actions">
<button class="bookslm-btn-agent" title="${t('ai.agent_mode_off')}" aria-label="${t('ai.agent_mode_off')}" aria-pressed="false"><i data-lucide="bot" style="width:16px;height:16px"></i></button>
<button class="bookslm-btn-history" title="${t('bookslm.session_history')}" aria-label="${t('bookslm.session_history')}"><i data-lucide="history" style="width:16px;height:16px"></i></button>
@@ -1071,6 +1081,25 @@ class BooksLM {
});
textarea.addEventListener('paste', (e) => this._onPaste(e));
// #106 — The suggested row flips to "selection" actions while the user
// selects text in the open editor; refresh (throttled) on selectionchange.
let qaSelTimer = null;
const onSelectionChange = () => {
if (qaSelTimer) return;
qaSelTimer = setTimeout(() => {
qaSelTimer = null;
if (!this._panel || this._panel.classList.contains('hidden')) return;
if (this._messages.length) return;
const ctx = this._quickContext();
if (ctx !== this._qaContext) this._showSuggestions();
}, 250);
};
document.addEventListener('selectionchange', onSelectionChange);
// CodeMirror owns its selection (no native selectionchange on drag), so
// the same throttled refresh is bound to pointer/keyboard release too.
document.addEventListener('mouseup', onSelectionChange);
document.addEventListener('keyup', onSelectionChange);
// Menu navigation is handled at the panel level (capture phase) so the
// arrow keys keep working even if focus is not exactly on the textarea
// (e.g. after interacting with the menu). It runs before the textarea
@@ -2015,26 +2044,52 @@ class BooksLM {
}
}
_suggestionsForContext() {
if (this._mode === MODE.GENERAL) {
return [
t('ai.suggestion_capabilities'),
t('ai.suggestion_search'),
t('ai.suggestion_create_file'),
];
}
if (this._mode === MODE.DOCUMENTS) {
return [
t('ai.suggestion_docs_summary'),
t('ai.suggestion_docs_keypoints'),
t('ai.suggestion_docs_contradictions'),
];
}
return [
t('bookslm.suggestion_summary'),
t('bookslm.suggestion_themes'),
t('bookslm.suggestion_contradictions'),
];
// ── #106 — Actions instantanées contextuelles ───────────────────────
//
// The welcome zone above the composer shows the 3 top actions for the
// *detected* context (selection > code > multi-doc > single-doc >
// directory > general, rules in ai-quick-actions.js); the full catalogue
// stays reachable through the "Toutes les actions" drawer.
/** True when the open editor (CM6, or the mobile textarea fallback)
* holds a non-empty text selection. Best-effort, never throws. */
_hasEditorSelection() {
try {
const view = state.editorView;
if (view && view.state && view.state.selection) {
const sel = view.state.selection.main;
if (sel && sel.from !== sel.to) return true;
}
const ta = state.fallbackEditorEl;
if (ta && document.body.contains(ta)
&& ta.selectionStart != null && ta.selectionEnd > ta.selectionStart) {
return true;
}
} catch { /* editor not ready */ }
return false;
}
/** The live context key driving the suggested-actions row. */
_quickContext() {
const docs = this._mode === MODE.DOCUMENTS ? this._documents : [];
return detectContext({
mode: this._mode,
docCount: docs.length,
currentPath: docs.length ? (docs[0].path || null) : null,
hasSelection: this._hasEditorSelection(),
});
}
/** Header chip describing the detected context ("1 doc ouvert", …). */
_updateQaBadge() {
if (!this._panel) return;
const badge = this._panel.querySelector('.bookslm-qa-badge');
if (!badge) return;
const ctx = this._qaContext || this._quickContext();
const docCount = this._mode === MODE.DOCUMENTS ? this._documents.length : 0;
badge.textContent = t(contextBadgeKey(ctx, docCount), { count: docCount });
badge.dataset.qaContext = ctx;
badge.classList.remove('hidden');
}
_showSuggestions() {
@@ -2042,21 +2097,185 @@ class BooksLM {
const sugEl = this._panel.querySelector('.bookslm-suggestions');
if (!sugEl) return;
sugEl.innerHTML = '';
if (this._messages.length) return;
for (const s of this._suggestionsForContext()) {
const btn = document.createElement('button');
btn.className = 'bookslm-suggestion';
btn.textContent = s;
btn.addEventListener('click', () => {
const textarea = this._panel.querySelector('textarea');
if (textarea) {
textarea.value = s;
this._sendMessage();
}
});
sugEl.appendChild(btn);
if (this._messages.length) {
sugEl.classList.add('hidden');
return;
}
sugEl.classList.remove('hidden');
const ctx = this._quickContext();
this._qaContext = ctx;
this._updateQaBadge();
// Welcome hint (mirrors the POC copy: actions or free question).
const hint = document.createElement('p');
hint.className = 'bookslm-qa-hint';
hint.textContent = t('qa.empty_hint');
sugEl.appendChild(hint);
// Row head: label + access to the full catalogue.
const head = document.createElement('div');
head.className = 'bookslm-qa-head';
const label = document.createElement('span');
label.className = 'bookslm-qa-label';
label.textContent = t('qa.header_suggested');
head.appendChild(label);
const more = document.createElement('button');
more.type = 'button';
more.className = 'bookslm-qa-more';
more.innerHTML = `<span>${t('qa.all_actions')}</span>`
+ '<i data-lucide="layout-grid" style="width:13px;height:13px"></i>';
more.addEventListener('click', (e) => {
e.stopPropagation();
this._toggleActionDrawer();
});
head.appendChild(more);
sugEl.appendChild(head);
const list = document.createElement('div');
list.className = 'bookslm-qa-list';
for (const action of suggestionsFor(ctx)) {
list.appendChild(this._renderQuickActionBtn(action));
}
sugEl.appendChild(list);
if (typeof safeCreateIcons === 'function') safeCreateIcons();
}
/** One action button (icon + label + hover arrow), used in both the row
* and the drawer catalogue. */
_renderQuickActionBtn(action, opts = {}) {
const { label, prompt } = actionTexts(action);
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'bookslm-qa-btn' + (opts.compact ? ' compact' : '');
btn.dataset.qaAction = action.id;
btn.innerHTML = `
<i data-lucide="${action.icon}" class="bookslm-qa-icon" style="width:15px;height:15px"></i>
<span class="bookslm-qa-text">${label}</span>
<i data-lucide="arrow-right" class="bookslm-qa-go" style="width:14px;height:14px"></i>
`;
btn.title = prompt;
btn.addEventListener('click', (e) => {
e.stopPropagation();
this._runQuickAction(action);
});
return btn;
}
/** Immediate-send the action prompt through the composer (same path as a
* typed message: skills, agent mode and images all keep working). Actions
* flagged `agent` (they mutate the document) transparently switch the
* assistant to agent mode first — same pattern as Deep Research. */
_runQuickAction(action) {
if (!this._panel || !action) return;
const { prompt } = actionTexts(action);
if (!prompt) return;
this._closeActionDrawer();
if (action.agent && !this._agentMode) this._toggleAgentMode();
const textarea = this._panel.querySelector('textarea');
if (!textarea) return;
textarea.value = prompt;
this._sendMessage();
}
// ── Drawer "Toutes les actions" (bottom sheet, searchable) ──────────
_toggleActionDrawer() {
const drawer = this._ensureActionDrawer();
if (!drawer) return;
if (drawer.classList.contains('open')) this._closeActionDrawer();
else this._openActionDrawer();
}
_ensureActionDrawer() {
if (!this._panel) return null;
let drawer = this._panel.querySelector('.bookslm-qa-drawer');
if (drawer) return drawer;
drawer = document.createElement('div');
drawer.className = 'bookslm-qa-drawer hidden';
drawer.innerHTML = `
<div class="bookslm-qa-sheet" role="dialog" aria-modal="true" aria-label="${t('qa.drawer_title')}">
<div class="bookslm-qa-sheet-head">
<span class="bookslm-qa-sheet-title">
<i data-lucide="layout-grid" style="width:15px;height:15px"></i>
${t('qa.drawer_title')}
</span>
<button type="button" class="bookslm-qa-sheet-close" aria-label="${t('ai.close')}">
<i data-lucide="x" style="width:15px;height:15px"></i>
</button>
</div>
<div class="bookslm-qa-search">
<i data-lucide="search" style="width:14px;height:14px"></i>
<input type="text" placeholder="${t('qa.search_placeholder')}" aria-label="${t('qa.search_placeholder')}">
</div>
<div class="bookslm-qa-sheet-list"></div>
</div>
`;
this._panel.appendChild(drawer);
drawer.querySelector('.bookslm-qa-sheet-close').addEventListener('click', () => this._closeActionDrawer());
// Clicking the backdrop (outside the sheet) closes the drawer.
drawer.addEventListener('click', (e) => {
if (e.target === drawer) this._closeActionDrawer();
});
const input = drawer.querySelector('.bookslm-qa-search input');
input.addEventListener('input', () => this._renderActionDrawerList(input.value));
input.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
e.preventDefault();
e.stopPropagation();
this._closeActionDrawer();
}
});
if (typeof safeCreateIcons === 'function') safeCreateIcons();
return drawer;
}
_openActionDrawer() {
const drawer = this._ensureActionDrawer();
if (!drawer) return;
drawer.classList.remove('hidden');
requestAnimationFrame(() => drawer.classList.add('open'));
this._renderActionDrawerList('');
const input = drawer.querySelector('.bookslm-qa-search input');
if (input) { input.value = ''; input.focus(); }
}
_closeActionDrawer() {
if (!this._panel) return;
const drawer = this._panel.querySelector('.bookslm-qa-drawer');
if (!drawer) return;
drawer.classList.remove('open');
// Let the slide-down transition finish before hiding.
setTimeout(() => drawer.classList.add('hidden'), 220);
}
_renderActionDrawerList(filter) {
const drawer = this._panel && this._panel.querySelector('.bookslm-qa-drawer');
if (!drawer) return;
const body = drawer.querySelector('.bookslm-qa-sheet-list');
if (!body) return;
body.innerHTML = '';
const q = normalizeSearch(filter || '');
let shown = 0;
for (const cat of CATEGORIES) {
const actions = ACTION_CATALOG.filter((a) => a.cat === cat.id
&& (!q || normalizeSearch(actionTexts(a).label).includes(q)));
if (!actions.length) continue;
const head = document.createElement('p');
head.className = 'bookslm-qa-cat';
head.innerHTML = `<i data-lucide="${cat.icon}" style="width:13px;height:13px"></i> ${t(cat.labelKey)}`;
body.appendChild(head);
for (const action of actions) {
body.appendChild(this._renderQuickActionBtn(action, { compact: true }));
shown++;
}
}
if (!shown) {
const empty = document.createElement('div');
empty.className = 'bookslm-qa-empty';
empty.textContent = t('qa.no_match');
body.appendChild(empty);
}
if (typeof safeCreateIcons === 'function') safeCreateIcons();
}
_renderMessages(opts = {}) {
+188 -39
View File
@@ -6,7 +6,7 @@ import { syncVaultSelectors, setSelectedVaultContext, refreshSidebarForContext,
import { escapeHtml, safeCreateIcons } from './utils.js';
import { showToast, closeHeaderMenu, closeMobileSidebar } from './ui.js';
import { t, setLocale, getLocale } from './i18n.js';
import { getModelCapabilities, renderCapabilityList, refreshAIPickers } from './ai.js';
import { getModelCapabilities, renderCapabilityBadges, refreshAIPickers } from './ai.js';
let _recentTimestampTimer = null;
let _recentFilesCache = [];
@@ -353,6 +353,7 @@ function initHelpModal() {
initHelpNavigation();
helpNavInitialized = true;
}
renderGuideMermaid();
});
closeBtn.addEventListener("click", closeHelpModal);
@@ -367,6 +368,64 @@ function initHelpModal() {
closeHelpModal();
}
});
// Guide downloads (#105) — markdown / pdf, current language.
const dlMd = document.getElementById("help-download-md");
const dlPdf = document.getElementById("help-download-pdf");
[dlMd, dlPdf].forEach((btn) => {
if (!btn) return;
btn.addEventListener("click", () => {
downloadGuide(btn.id === "help-download-md" ? "md" : "pdf");
});
});
}
// Render any Mermaid blocks inside the guide modal (the architecture diagram,
// #105). The viewer's own pipeline only touches document views, so the help
// modal is enriched here — once per modal open, cheap on repeats.
function renderGuideMermaid() {
const modal = document.getElementById("help-modal");
if (!modal || modal.dataset.mermaidRendered === "1") return;
import("./mermaid-viewer.js")
.then((m) => m.renderMermaidBlocks(modal))
.then(() => {
// Only mark done when the source block actually became a rendered
// diagram — if the Mermaid CDN wasn't ready yet, retry on next open.
if (!modal.querySelector("code.language-mermaid")) {
modal.dataset.mermaidRendered = "1";
}
})
.catch(() => { /* CDN offline: keep the code block readable */ });
}
// Fetch the generated guide (auth headers + cookie) and trigger the browser
// download, mirroring viewer.downloadExport().
async function downloadGuide(format) {
showToast(t("viewer.export_start"), "info");
try {
const headers = AuthManager.getAuthHeaders ? AuthManager.getAuthHeaders() || {} : {};
const res = await fetch(
`/api/guide/download?format=${format}&lang=${encodeURIComponent(getLocale() || "fr")}`,
{ credentials: "include", headers },
);
if (!res.ok) {
let detail = "";
try { detail = (await res.json()).detail || ""; } catch (_) { /* ignore */ }
throw new Error(detail || "HTTP " + res.status);
}
const blob = await res.blob();
const a = document.createElement("a");
a.href = URL.createObjectURL(blob);
a.download = `ObsiGate-Guide-${getLocale() || "fr"}.${format}`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(a.href), 1000);
showToast(t("viewer.export_done"), "success");
} catch (err) {
console.error("Guide export error:", err);
showToast(t("viewer.export_error") + " " + err.message, "error");
}
}
function initEditorPocBtn() {
@@ -766,6 +825,11 @@ function initConfigModal() {
if (saveAIKeysBtn) saveAIKeysBtn.addEventListener("click", saveAIKeys);
const testAIKeysBtn = document.getElementById("cfg-test-ai-keys");
if (testAIKeysBtn) testAIKeysBtn.addEventListener("click", testAIKeys);
// Provider search filter (#104)
const aiProviderSearch = document.getElementById("cfg-ai-search");
if (aiProviderSearch) {
aiProviderSearch.addEventListener("input", () => filterAIProviders(aiProviderSearch.value));
}
// Tool & connected-source keys (#103)
const saveToolKeysBtn = document.getElementById("cfg-save-tool-keys");
if (saveToolKeysBtn) saveToolKeysBtn.addEventListener("click", saveToolKeys);
@@ -1510,7 +1574,7 @@ function updateRegexPreview() {
}
// ── AI Keys management ──
// ── AI Keys management (#104 — accordion redesign) ──
const AI_KEY_MAP = {
"cfg-deepseek-key": "DEEPSEEK_API_KEY",
"cfg-openrouter-key": "OPENROUTER_API_KEY",
@@ -1522,57 +1586,140 @@ const AI_KEY_MAP = {
};
const AI_PROVIDER_NAMES = ["deepseek","openrouter","gemini","nvidia","qwencloud","xiaomi","mistral"];
function _ensureAIKeyUI() {
for (const [inputId] of Object.entries(AI_KEY_MAP)) {
const input = document.getElementById(inputId);
if (!input) continue;
const row = input.closest(".config-row");
if (!row || row.dataset.enhanced) continue;
row.dataset.enhanced = "1";
row.style.cssText += "display:flex;align-items:center;gap:8px;flex-wrap:wrap;";
const badge = document.createElement("span");
badge.id = inputId.replace("-key", "-badge");
badge.style.cssText = "font-size:11px;padding:2px 8px;border-radius:10px;white-space:nowrap;";
row.appendChild(badge);
const delBtn = document.createElement("button");
delBtn.type = "button";
delBtn.id = inputId.replace("-key", "-delete");
delBtn.className = "config-btn-secondary";
delBtn.style.cssText = "font-size:11px;padding:4px 10px;color:var(--danger,#e74c3c);border-color:var(--danger,#e74c3c);cursor:pointer;display:none;";
delBtn.textContent = "\u00d7 Supprimer";
delBtn.addEventListener("click", () => deleteAIKey(inputId));
row.appendChild(delBtn);
// Display metadata for the provider accordion cards (#104).
const AI_PROVIDER_META = {
deepseek: { name: "DeepSeek", placeholder: "sk-..." },
openrouter: { name: "OpenRouter", placeholder: "sk-or-..." },
gemini: { name: "Gemini", placeholder: "AIza..." },
nvidia: { name: "NVIDIA", placeholder: "nvapi-..." },
qwencloud: { name: "QwenCloud", placeholder: "sk-..." },
xiaomi: { name: "Xiaomi", placeholder: "xm-..." },
mistral: { name: "Mistral", placeholder: "sk-..." },
};
function _renderAIProviderCards() {
const host = document.getElementById("cfg-ai-providers");
if (!host) return;
host.innerHTML = "";
for (const p of AI_PROVIDER_NAMES) {
const meta = AI_PROVIDER_META[p] || { name: p, placeholder: "sk-..." };
const card = el("div", { class: "ai-provider-card", "data-provider": p });
// Header row (div + role=button so the per-provider delete button can
// live inside without nesting two interactive elements).
const head = el("div", {
class: "ai-provider-head",
role: "button",
tabindex: "0",
"aria-expanded": "false",
});
head.appendChild(el("span", { class: "ai-provider-logo", "aria-hidden": "true" }, [document.createTextNode(meta.name.charAt(0))]));
head.appendChild(el("span", { class: "ai-provider-name" }, [document.createTextNode(meta.name)]));
head.appendChild(el("span", { class: "ai-provider-badge", id: `cfg-${p}-badge` }));
const delBtn = el("button", {
type: "button",
class: "ai-provider-delete",
id: `cfg-${p}-delete`,
title: t("config.ai_delete_key_title"),
});
delBtn.style.display = "none";
delBtn.appendChild(icon("trash-2", 14));
delBtn.addEventListener("click", (e) => {
e.stopPropagation();
deleteAIKey(`cfg-${p}-key`);
});
head.appendChild(delBtn);
const chevron = icon("chevron-down", 16);
chevron.classList.add("ai-provider-chevron");
head.appendChild(chevron);
const toggle = () => _toggleAICard(card);
head.addEventListener("click", toggle);
head.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") { e.preventDefault(); toggle(); }
});
// Collapsible body: API key (60%) + model (40%), labels above inputs.
const body = el("div", { class: "ai-provider-body hidden" });
const fields = el("div", { class: "ai-provider-fields" });
const keyField = el("div", { class: "ai-field ai-field-key" });
keyField.appendChild(el("label", { class: "ai-field-label", for: `cfg-${p}-key` }, [document.createTextNode(`${meta.name} API Key`)]));
const keyInput = document.createElement("input");
keyInput.type = "password";
keyInput.id = `cfg-${p}-key`;
keyInput.className = "config-input";
keyInput.placeholder = meta.placeholder;
keyInput.autocomplete = "off";
keyField.appendChild(keyInput);
const modelField = el("div", { class: "ai-field ai-field-model" });
modelField.appendChild(el("label", { class: "ai-field-label", for: `cfg-${p}-model` }, [document.createTextNode(t("config.ai_model"))]));
const modelSel = document.createElement("select");
modelSel.id = `cfg-${p}-model`;
modelSel.className = "config-select";
modelSel.innerHTML = '<option value="">-- Modele --</option>';
modelField.appendChild(modelSel);
fields.appendChild(keyField);
fields.appendChild(modelField);
body.appendChild(fields);
card.appendChild(head);
card.appendChild(body);
host.appendChild(card);
}
safeCreateIcons();
}
function _toggleAICard(card) {
const open = card.classList.toggle("open");
const body = card.querySelector(".ai-provider-body");
if (body) body.classList.toggle("hidden", !open);
const head = card.querySelector(".ai-provider-head");
if (head) head.setAttribute("aria-expanded", open ? "true" : "false");
}
/** Filter the provider accordion cards by the section search input (#104). */
export function filterAIProviders(query) {
const host = document.getElementById("cfg-ai-providers");
const emptyMsg = document.getElementById("cfg-ai-providers-empty");
if (!host) return;
const q = _sidebarNorm(query);
let visible = 0;
host.querySelectorAll(".ai-provider-card").forEach((card) => {
const p = card.dataset.provider;
const meta = AI_PROVIDER_META[p] || { name: p };
const match = !q || _sidebarNorm(meta.name).includes(q) || p.includes(q);
card.style.display = match ? "" : "none";
if (match) visible++;
});
if (emptyMsg) emptyMsg.classList.toggle("hidden", visible > 0);
}
function _setAIKeyBadge(inputId, hasKey) {
const badge = document.getElementById(inputId.replace("-key", "-badge"));
const delBtn = document.getElementById(inputId.replace("-key", "-delete"));
const provider = inputId.replace("-key", "");
const badge = document.getElementById(`${provider}-badge`);
const delBtn = document.getElementById(`${provider}-delete`);
if (badge) {
if (hasKey) {
badge.textContent = "\u2713 Configur\u00e9";
badge.style.background = "var(--success-bg, #27ae6022)";
badge.style.color = "var(--success, #27ae60)";
badge.style.border = "1px solid var(--success, #27ae60)";
} else {
badge.textContent = "Non configur\u00e9";
badge.style.background = "var(--muted-bg, #ffffff10)";
badge.style.color = "var(--text-muted, #888)";
badge.style.border = "1px solid var(--border, #444)";
}
badge.textContent = hasKey
? "\u2713 " + t("config.ai_status_configured")
: t("config.ai_status_not_configured");
badge.classList.toggle("configured", !!hasKey);
}
if (delBtn) delBtn.style.display = hasKey ? "inline-block" : "none";
if (delBtn) delBtn.style.display = hasKey ? "inline-flex" : "none";
}
async function loadAIKeys() {
_ensureAIKeyUI();
_renderAIProviderCards();
try {
const data = await api("/api/config/ai-keys");
for (const [inputId, envName] of Object.entries(AI_KEY_MAP)) {
const input = document.getElementById(inputId);
const val = data[envName] || "";
if (input) {
input.placeholder = val || (inputId.includes("gemini") ? "AIza..." : inputId.includes("openrouter") ? "sk-or-..." : "sk-...");
const meta = AI_PROVIDER_META[inputId.replace("-key", "")] || {};
input.placeholder = val || meta.placeholder || "sk-...";
}
_setAIKeyBadge(inputId, !!val);
}
@@ -1626,7 +1773,7 @@ async function _renderConfigModelCaps(provider, model) {
if (!provider || !model) return;
const caps = await getModelCapabilities(provider, model);
if (!caps) return;
host.appendChild(renderCapabilityList(caps));
host.appendChild(renderCapabilityBadges(caps));
}
async function saveAIKeys() {
@@ -1830,6 +1977,8 @@ export {
initProfile,
switchSidebarTab,
populateVersions,
loadAIKeys,
saveAIKeys,
};
// Populate every version display (header badge, About modal, help guide footer)
+3
View File
@@ -231,6 +231,9 @@ export async function initDesktopIntegration() {
defineBackendCrashBanner();
if (!isTauriEnv()) return false;
// Desktop marker for CSS (wider reading layouts, e.g. the user guide #105).
try { document.body.classList.add('desktop-mode'); } catch (e) { /* ignore */ }
// Follow the OS theme on first run, before the theme engine renders.
await syncSystemTheme();
+17 -14
View File
@@ -5,8 +5,11 @@
* excalidraw-editor.html. Communication between parent and iframe
* via postMessage:
*
* Parent → Iframe: init {data, theme} | theme {theme} | requestSave
* Parent → Iframe: init {data, theme} | theme {theme}
* Iframe → Parent: ready | save {data} | modified {dirty}
*
* Saves are explicit only (in-editor Save button / Ctrl+S): no autosave, so
* writing the file never triggers an `index_updated` reload of the viewer.
*/
import { api } from './auth.js';
@@ -35,7 +38,15 @@ export function renderExcalidraw(container, data, vaultName, filePath, opts = {}
iframe.src = '/static/excalidraw-editor.html?v=' + Date.now();
iframe.sandbox.add('allow-scripts');
iframe.sandbox.add('allow-same-origin');
// Let the editor's own Fullscreen button work (native Fullscreen API inside
// the sandboxed iframe).
iframe.setAttribute('allow', 'fullscreen');
iframe.setAttribute('allowfullscreen', '');
iframe.style.cssText = 'width:100%;height:100%;border:none;';
// Identify the owning document so sync.js can avoid re-rendering (and thus
// reloading) this iframe after its own save triggers an `index_updated`.
iframe.dataset.excalidrawVault = vaultName;
iframe.dataset.excalidrawPath = filePath;
// Clean container and insert iframe
container.innerHTML = '';
@@ -49,7 +60,6 @@ export function renderExcalidraw(container, data, vaultName, filePath, opts = {}
path: filePath,
isDirty: false,
ready: false,
saveTimer: null,
};
_activeEditors.set(editorId, editorState);
@@ -94,16 +104,11 @@ export function renderExcalidraw(container, data, vaultName, filePath, opts = {}
break;
case 'modified':
// No autosave: saving writes the file, which emits `index_updated` and
// reloads the viewer (visible page refresh) — and can interrupt the
// user mid-drawing. The scene is saved explicitly via the in-editor
// Save button or Ctrl+S. We only track the dirty state.
editorState.isDirty = msg.dirty === true;
// If dirty, start auto-save timer (2s debounce)
if (editorState.isDirty) {
if (editorState.saveTimer) clearTimeout(editorState.saveTimer);
editorState.saveTimer = setTimeout(() => {
if (editorState.isDirty && editorState.ready) {
iframe.contentWindow.postMessage({ type: 'requestSave' }, '*');
}
}, 2000);
}
break;
}
});
@@ -154,9 +159,7 @@ export function notifyExcalidrawThemeChange(theme) {
* Clean up an editor instance (e.g., when tab is closed).
*/
export function destroyExcalidrawEditor(editorId) {
const state = _activeEditors.get(editorId);
if (state) {
if (state.saveTimer) clearTimeout(state.saveTimer);
if (_activeEditors.has(editorId)) {
_activeEditors.delete(editorId);
}
}
+7
View File
@@ -693,6 +693,13 @@ async function reloadExternalWrite(vault, path, force = false) {
}
// Not editing: refresh the read view when it shows the written document.
if (state.currentVault === vault && state.currentPath === path) {
// Excalidraw owns its iframe: re-rendering would recreate it (visible page
// refresh) and discard the in-editor scene. Its own save already persisted
// the file, so there is nothing to reload here.
const openExcalidraw = Array.from(
document.querySelectorAll("iframe[data-excalidraw-path]")
).some((f) => f.dataset.excalidrawVault === vault && f.dataset.excalidrawPath === path);
if (openExcalidraw) return;
_invalidateActiveTabCache(vault, path);
openFile(vault, path);
}
+30 -2
View File
@@ -518,6 +518,28 @@ function applyPrettyHighlight(codeEl, lang, text) {
}
}
/**
* Jump the inline PDF viewer to a specific page.
*
* The browser's built-in PDF viewer lives in an ``about:blank`` content window
* (so ``contentWindow.location.hash`` never reaches the document) **and** it
* ignores a same-document fragment navigation: changing only ``#page=N`` on the
* iframe ``src`` does not move the page. A changing query parameter forces a
* real reload, and the ``#page=N`` fragment is then honoured at load — the only
* reliable way to target a page with the native viewer.
*
* @param {HTMLElement} area - Content area containing the ``.pdf-iframe``.
* @param {string|number} page - 1-based page number from the PDF outline.
*/
export function navigatePdfToPage(area, page) {
const iframe = area && area.querySelector('.pdf-iframe');
if (!iframe || page === null || page === undefined || page === '') return;
const base = iframe.getAttribute('data-pdf-url') || iframe.src.split('#')[0];
iframe.setAttribute('data-pdf-url', base);
const sep = base.includes('?') ? '&' : '?';
iframe.src = `${base}${sep}_pdfpage=${Date.now()}#page=${page}`;
}
export function renderFile(data) {
// #93 — An inline edition session (#editor-container mounted in the content
// area) is destroyed by this very re-render: release it first so the editor
@@ -537,7 +559,7 @@ export function renderFile(data) {
tocHtml = '<div class="pdf-toc"><h3>Table des matières</h3><ul>';
for (const item of toc) {
const indent = (item.level - 1) * 16;
tocHtml += `<li style="padding-left:${indent}px"><a href="#" onclick="document.querySelector('.pdf-iframe').contentWindow.location.hash='page=${item.page}';return false">${escapeHtml(item.title)}</a> <span class="toc-page">p.${item.page}</span></li>`;
tocHtml += `<li style="padding-left:${indent}px"><a href="#" data-page="${item.page}">${escapeHtml(item.title)}</a> <span class="toc-page">p.${item.page}</span></li>`;
}
tocHtml += '</ul></div>';
}
@@ -555,9 +577,15 @@ export function renderFile(data) {
</div>
<div class="pdf-body">
${tocHtml}
<iframe src="${pdfUrl}" class="pdf-iframe" title="${escapeHtml(data.title)}"></iframe>
<iframe src="${pdfUrl}" data-pdf-url="${pdfUrl}" class="pdf-iframe" title="${escapeHtml(data.title)}"></iframe>
</div>
</div>`;
area.querySelectorAll('.pdf-toc a[data-page]').forEach((link) => {
link.addEventListener('click', (e) => {
e.preventDefault();
navigatePdfToPage(area, link.getAttribute('data-page'));
});
});
lucide.createIcons();
return;
}
+172 -3
View File
@@ -363,6 +363,14 @@
"config.ai_keys_desc": "Configure API keys for the AI editor.",
"config.ai_model": "Model",
"config.ai_openrouter_label": "OpenRouter API Key",
"config.ai_header_desc": "Configure your API keys provider by provider. Expand a card to enter a key, then click Test to load the models.",
"config.ai_search_placeholder": "Search a provider…",
"config.ai_default_section": "Default configuration",
"config.ai_providers_title": "API providers",
"config.ai_providers_empty": "No matching provider",
"config.ai_status_configured": "Configured",
"config.ai_status_not_configured": "Not configured",
"config.ai_delete_key_title": "Delete the API key",
"config.api_keys_saved": "API keys saved",
"config.section_sources": "🔗 Connected sources & search",
"config.sources_desc": "Keys used by the AI assistant tools (keyed web search: Tavily, Brave, SerpAPI, Exa; connected sources: Gitea, GitHub). They are stored server-side and take precedence over environment variables.",
@@ -488,7 +496,7 @@
"config.section_fonctionnalites": "Features",
"config.section_format-du-payload": "Format du payload",
"config.section_gestion-des-onglets": "📑 Gestion des onglets",
"config.section_hidden": "Hidden files",
"config.section_hidden": "🗂️ Hidden files",
"config.section_historique-recent-redemarrage-non-requis": "📋 Recent History\n No restart required",
"config.section_indicateurs-visuels": "Indicateurs visuels",
"config.section_intelligence-artificielle-dans-l-editeur": "🤖 AI in the Editor",
@@ -1471,6 +1479,76 @@
"pwa.install_button": "Install",
"pwa.install_desc": "Install this app on your device for quick access.",
"pwa.install_title": "Install ObsiGate",
"qa.all_actions": "All actions",
"qa.audit_code": "Detect bugs and potential flaws",
"qa.audit_code.prompt": "Identify potential bugs, unhandled edge cases and security flaws in this code, with proposed fixes.",
"qa.backlinks": "Suggest vault links and backlinks",
"qa.backlinks.prompt": "Suggest relevant [[wikilinks]] to other notes in the vault and backlinks to add to this document.",
"qa.badge_code": "Code file",
"qa.badge_directory": "Directory",
"qa.badge_general": "General mode",
"qa.badge_multi": "{count} docs open",
"qa.badge_selection": "Active selection",
"qa.badge_single": "1 doc open",
"qa.capabilities": "What can you do?",
"qa.capabilities.prompt": "What can you do? Present your capabilities on this vault.",
"qa.cat_code": "Code & Scripts",
"qa.cat_cross": "Cross-documents",
"qa.cat_edition": "Editing & Rewriting",
"qa.cat_general": "Assistant",
"qa.cat_structure": "Productivity & Structuring",
"qa.cat_synthesis": "Synthesis & Analysis",
"qa.checklist": "Extract the action checklist",
"qa.checklist.prompt": "Extract every concrete action to take as a Markdown to-do list with [ ] checkboxes.",
"qa.compare": "Compare differences and convergences",
"qa.compare.prompt": "Compare all open documents and summarise their convergences, divergences and oppositions.",
"qa.concise": "Make it more concise and punchy",
"qa.concise.prompt": "Rewrite the selection to make it more concise and punchy without losing the essentials.",
"qa.create_note": "Create a meeting note",
"qa.create_note.prompt": "Create a meeting notes file in the vault.",
"qa.doc_code": "Add documentation and types",
"qa.doc_code.prompt": "Add the appropriate docstrings, JSDoc and type annotations to every function in this file.",
"qa.drawer_title": "Action library",
"qa.empty_hint": "Pick a context-aware quick action, or ask a question directly.",
"qa.explain_code": "Explain the script logic",
"qa.explain_code.prompt": "Analyse and explain step by step the structure and algorithm of this source code.",
"qa.explain_selection": "Explain the selection",
"qa.explain_selection.prompt": "Explain the selected passage: its role, its context and what it implies.",
"qa.faq": "Generate a FAQ / key questions",
"qa.faq.prompt": "Generate a list of 5 key questions and answers to check comprehension of this text.",
"qa.fix_style": "Fix and improve the style",
"qa.fix_style.prompt": "Fix spelling and grammar mistakes and improve the syntactic flow of this passage.",
"qa.frictions": "Spot frictions and contradictions",
"qa.frictions.prompt": "Analyse this document and point out inconsistencies, blind spots or contradictions.",
"qa.frontmatter": "Generate the YAML frontmatter",
"qa.frontmatter.prompt": "Generate a complete YAML frontmatter block in the vault's format and apply it to the open document (insert it at the top of the file, or replace the existing block, keeping non-empty values already present): titre, auteur, creation_date and modification_date in ISO-8601 with timezone, catégorie, tags (inline list [a, b]), aliases, status, publish, favoris, template, task, archive, draft, private (booleans), NomDeVoute (current vault name), Description (a one-sentence summary of the content).",
"qa.frontmatter_update": "Update the frontmatter",
"qa.frontmatter_update.prompt": "Update the YAML frontmatter of the open document without deleting existing fields: refresh modification_date (current ISO-8601 timestamp with timezone), recompute titre, tags, aliases, catégorie, NomDeVoute and Description from the current content, fill in any missing metadata field (auteur, creation_date, status, publish, favoris, template, task, archive, draft, private) and apply the change to the file.",
"qa.header_suggested": "Suggested actions",
"qa.memo": "Write a shareable executive memo",
"qa.memo.prompt": "Write a shareable executive memo based on this document: context, findings, recommendations.",
"qa.merge": "Merge into one synthesis note",
"qa.merge.prompt": "Merge the essential elements of all open documents into one unified, flowing synthesis note.",
"qa.no_match": "No matching action.",
"qa.plan": "Create a step-by-step action plan",
"qa.plan.prompt": "Turn this content into a step-by-step action plan with priorities and estimates.",
"qa.rephrase": "Rephrase this passage",
"qa.rephrase.prompt": "Rephrase this passage keeping the meaning but using different wording.",
"qa.search_help": "Search my notes effectively",
"qa.search_help.prompt": "How do I search my notes effectively?",
"qa.search_placeholder": "Search an action...",
"qa.sections": "Structure into hierarchical sections",
"qa.sections.prompt": "Restructure this document with a logical hierarchy of Markdown headings (H2, H3) and clean bullet lists.",
"qa.summarize_3": "Summarize in 3 key points",
"qa.summarize_3.prompt": "Provide a concise summary of this document in 3 clear key points.",
"qa.test_code": "Generate unit tests",
"qa.test_code.prompt": "Write a unit test suite covering nominal and error cases for this code.",
"qa.timeline": "Build a cross-document timeline",
"qa.timeline.prompt": "Build a cross-document timeline of the dated events mentioned in these documents.",
"qa.translate": "Translate the selection",
"qa.translate.prompt": "Translate this passage into the appropriate language (English if the text is in French, and vice versa).",
"qa.vulgarize": "Plain-language explainer",
"qa.vulgarize.prompt": "Explain the content of this document in simple, accessible language without jargon.",
"search.advanced_operators": "Advanced operators",
"search.aria_label": "Search suggestions",
"search.case_sensitive": "Case sensitive",
@@ -1953,5 +2031,96 @@
"help.excalidraw_search_title": "Search",
"help.excalidraw_search": "Text inside diagram elements is extracted on indexing, so it is searchable via the full-text search.",
"help.excalidraw_compat": "Files created with the Obsidian Excalidraw plugin (including the compressed <code>.excalidraw.md</code> format) are compatible.",
"help.footer_tagline": "- Web gateway for your Obsidian vaults"
}
"help.footer_tagline": "- Web gateway for your Obsidian vaults",
"guide105.nav_architecture": "🏗️ Architecture",
"guide105.nav_library": "⭐ Library",
"guide105.nav_diagrams": "📊 Diagrams",
"guide105.nav_offline": "📴 Offline",
"guide105.nav_collab": "👥 Collaboration",
"guide105.nav_desktop": "🖥️ Desktop",
"guide105.nav_api": "🔌 API",
"guide105.nav_languages": "🌍 Languages",
"guide105.arch_intro": "ObsiGate is a full web application built as independent layers, with no external database: notes live in your Obsidian folders, app state in JSON files under <code>data/</code>, the search index in memory.",
"guide105.arch_diagram_note": "The diagram is interactive in the app: zoom, fullscreen, copy SVG or code.",
"guide105.arch_h3_layers": "The main components",
"guide105.arch_lbl_fe": "Frontend",
"guide105.arch_fe": " — vanilla-JavaScript SPA (ES modules), no framework, no npm build: <code>frontend/js/</code> (~30 modules). CSS variables drive the themes.",
"guide105.arch_lbl_be": "Backend",
"guide105.arch_be": " — FastAPI server (Python 3.11): markdown rendering (mistune + wikilinks), stemmed TF-IDF search (in-memory inverted index), watchdog file watchers, JWT + Argon2id, HMAC webhooks, PDF export (WeasyPrint).",
"guide105.arch_lbl_realtime": "Realtime & MCP",
"guide105.arch_rt": " — WebSocket gateway (Yjs collaboration, SSE/push notifications) and an MCP server (Streamable HTTP, <code>/mcp</code>) for external clients.",
"guide105.arch_lbl_ai": "AI layer",
"guide105.arch_ai": " — editor assistant and BooksLM with multiple providers (DeepSeek, OpenRouter, Gemini, Mistral…), a tool library (function calling, web search, crawl, document reading) and optional embeddings for semantic search.",
"guide105.arch_lbl_data": "Data",
"guide105.arch_data": " — Obsidian vaults on disk (the source of truth), JSON configuration (<code>data/</code>), timestamped backups (<code>.obsigate-backup/</code>), a JSON-lines audit log, encrypted API keys in <code>data/api_keys.json</code>.",
"guide105.arch_lbl_deploy": "Deployment",
"guide105.arch_deploy": " — Tauri desktop app (Rust) embedding the Python backend, a Docker container, or an installable PWA in the browser (offline mode).",
"guide105.arch_h3_flux": "Typical request flow",
"guide105.arch_flux": " Clicking a file issues <code>GET /api/file/...</code>; the backend resolves the path safely, parses frontmatter, renders the markdown and returns HTML; the frontend enriches the view (Mermaid, syntax highlighting, clickable wikilinks). Every write creates a backup before applying.",
"guide105.dia_intro": "<code>```mermaid</code> blocks in your notes render as interactive diagrams (Mermaid v11, loaded from a CDN).",
"guide105.dia_zoom": "Zoom: + / − buttons in the diagram toolbar.",
"guide105.dia_fs": "Fullscreen: ideal for large charts.",
"guide105.dia_copy": "Copy: export the SVG or the source code (dedicated buttons).",
"guide105.dia_toggle": "Preview / Code toggle to edit the source without leaving the view.",
"guide105.dia_theme": "Theme: the diagram follows the app's light/dark theme.",
"guide105.dia_types": "Supported types: flowchart, sequence, class, state, ER, gantt, pie, journey, quadrant, radar, mindmap, timeline, C4, xychart, sankey — plus a preprocessor that understands Obsidian syntax.",
"guide105.dia_excalidraw_ref": "Hand-drawn sketches (<code>.excalidraw</code>, <code>.excalidraw.md</code>) are covered in the 🎨 Excalidraw section.",
"guide105.lib_h3_bookmarks": "Bookmarks & recents",
"guide105.lib_bookmarks": "Star a file with the Bookmark button in the action bar: it joins the dashboard's bookmark list. Recently opened files are listed automatically in the sidebar's \"Recent\" tab, with a dedicated search filter.",
"guide105.lib_h3_saved": "Saved searches",
"guide105.lib_saved": "Save a search from the results page to rerun it in one click from the sidebar: each saved search keeps its operators and filters.",
"guide105.lib_h3_backlinks": "Backlinks & graph",
"guide105.lib_backlinks": "The Backlinks panel lists every note pointing to the open file. The Graph view (🕸️ button) shows links between files: drag nodes, scroll to zoom, double-click a node to open the note.",
"guide105.lib_h3_conflicts": "Sync conflicts",
"guide105.lib_conflicts": "If you sync the vault with Syncthing, ObsiGate detects conflict files (\"sync-conflict\" copies) and offers to compare then resolve them from a dedicated page in the Options menu.",
"guide105.lib_h3_attach": "Attachments & media",
"guide105.lib_attach": "Inline <code>![[image.png]]</code> images, attachments and media (audio, video, embedded PDFs) are rendered in the viewer and indexed for search; the \"Rescan attachments\" button in Configuration rebuilds the attachment index.",
"guide105.off_pwa": "ObsiGate is a PWA: install it (install icon in the address bar) to open it like an app. The service worker caches the UI and your recently viewed documents.",
"guide105.off_edit": "Offline you can read cached documents and even edit them: changes are queued in IndexedDB.",
"guide105.off_sync": "When back online the queue replays automatically (sync badge in the header). If the server version diverged meanwhile, the file is flagged as conflict and the server copy is kept as a backup.",
"guide105.off_watch": "External changes (Obsidian on disk) are detected by the watcher: the view reloads without losing your position, or flags \"modified externally\" during an edit.",
"guide105.col_intro": "Open a document in Edit mode: several people can work on the same file simultaneously over a Yjs (CRDT) WebSocket. Changes merge without locks.",
"guide105.col_cursors": "Collaborators' cursors and selections appear with a per-person colour and name (awareness).",
"guide105.col_save": "The merge is persisted server-side after 2 s of idle; every write creates a timestamped backup before applying.",
"guide105.col_perm": "Limited to authenticated users with permission on the vault.",
"guide105.des_get": "The ObsiGate desktop app (Tauri) embeds the Python server: no Docker install needed. Download it from the repository's Releases page; it auto-updates (signed updater).",
"guide105.des_wizard": "On first launch a wizard asks for your vaults folder (or creates a demo vault). Any document can be detached into its own native window.",
"guide105.des_data": "Desktop data stays in the app directory; vaults point at your existing folders. Every web feature (search, AI, sharing) is available.",
"guide105.des_native": "Native system menu, optional global show/hide shortcut and a recents vault jumplist.",
"guide105.api_intro": "ObsiGate exposes a REST API covering the whole application (vaults, files, search, backups, export, AI, sharing, admin), documented in OpenAPI 3.1:",
"guide105.api_docs_url": "<code>/docs</code> — Swagger UI to try requests live.",
"guide105.api_redoc": "<code>/redoc</code> — compact alternative reference.",
"guide105.api_landing": "<code>/api</code> — landing page grouping endpoints by category.",
"guide105.api_schema": "<code>/openapi.json</code> — the machine schema, import into Postman or Insomnia.",
"guide105.api_h3_auth": "Authentication",
"guide105.api_auth": "Log in via <code>POST /api/auth/login</code> to get a Bearer token (the same token is accepted as an HttpOnly cookie, so browser clients can use <code>credentials: \"include\"</code>). All <code>/api/*</code> routes require it unless documented otherwise.",
"guide105.api_h3_mcp": "MCP server",
"guide105.api_mcp": "The assistant's tools (read, list, search, open, write…) are exposed to any MCP client (Claude Desktop, Cursor, Cline…) at <code>https://your-instance/mcp</code> with an API token. Setup and examples: <code>docs/MCP_GUIDE.md</code>.",
"guide105.api_h3_autom": "Automation",
"guide105.api_autom": "To automate from outside: <code>GET /api/search?q=…</code> and <code>GET /api/file/{vault}?path=…</code> let another tool index or re-read your notes; outgoing webhooks (🪝 section) avoid polling.",
"guide105.lng_how": "The interface is fully bilingual FR/EN. Settings → Profile → Language: the choice is stored on your account and follows you across devices.",
"guide105.lng_scope": "Everything is translated: menus, messages, notifications, and this guide. AI assistant answers follow the language of your documents.",
"guide105.lng_export": "This guide's Markdown / PDF buttons download the version in your language.",
"guide105.h3_semantic": "Semantic search (hybrid)",
"guide105.sem_p1": "Toggle the \"S\" button in the search bar (or Alt-S) to combine TF-IDF with vector similarity (RRF fusion): near concepts (\"velvet\" finds \"soft fabric\") surface higher.",
"guide105.sem_p2": "The embedding engine (multilingual model) is optional: without it a hash fallback keeps hybrid search working. Vectors are recomputed on each vault reindex.",
"guide105.h3_push": "Web notifications (push)",
"guide105.push_p1": "Grant notification permission (🔔 button in the header) to be alerted of offline-sync completions and important events. Subscription management lives in Configuration.",
"guide105.push_p2": "Built on the Web Push API (VAPID keys); works on desktop and mobile PWA with no third-party service: the server sends directly to browser push endpoints.",
"guide105.h3_panes": "Multi-pane split view",
"guide105.panes_p": "The \"Split\" button in the action bar opens the document in a twin pane; stack several panes to compare two notes or read and edit side by side. Pane widths drag on the border and are remembered.",
"guide105.h3_dupe": "Duplicate-proof uploads",
"guide105.dupe_p": "Bulk upload (drag a folder onto the sidebar) compares each file with existing content: an already-present file is skipped rather than duplicated with a \"(1)\" suffix. Handy when restoring a vault.",
"guide105.h3_pdf": "PDF export",
"guide105.pdf_p": "A document's \"PDF\" button renders it with the same engine as the viewer (WeasyPrint): headings, tables, lists and code are preserved. From a public link, the <code>/s/{token}/pdf</code> route produces the same PDF.",
"guide105.h3_exports": "HTML / ePub / ZIP export",
"guide105.exp_p": "The \"Export\" menu offers three formats: standalone HTML (single file, images inlined), ePub for e-readers and, for a folder, a Markdown ZIP bundle — links and resources resolved during export.",
"guide105.h3_mfa": "MFA: TOTP, WebAuthn, recovery codes",
"guide105.mfa_p": "Enable two-factor auth in Settings → Profile: TOTP apps (Authy, Aegis…), security keys and passkeys (WebAuthn, including Windows Hello) and 10 recovery codes to keep offline. Each method can be enabled and disabled independently.",
"guide105.h3_admin": "Admin dashboard",
"guide105.admin_p": "The admin role unlocks a dedicated <code>/admin.html</code> page (Options menu button): live server status, users, vaults, active sessions and the audit log. User CRUD also lives in Configuration.",
"guide105.dl_md_title": "Download this guide as Markdown",
"guide105.dl_pdf_title": "Download this guide as PDF",
"guide105.export_title": "ObsiGate User Guide",
"guide105.export_footer": "Generated from ObsiGate {version} — {date}. This document mirrors the in-app guide; the latest version always lives in the application."
}
+173 -4
View File
@@ -363,6 +363,14 @@
"config.ai_keys_desc": "Configurez les clés API pour l'éditeur IA.",
"config.ai_model": "Modèle",
"config.ai_openrouter_label": "OpenRouter API Key",
"config.ai_header_desc": "Configurez vos clés API fournisseur par fournisseur. Dépliez une carte pour saisir une clé, puis cliquez sur Tester pour charger les modèles.",
"config.ai_search_placeholder": "Rechercher un fournisseur…",
"config.ai_default_section": "Configuration par défaut",
"config.ai_providers_title": "Fournisseurs d'API",
"config.ai_providers_empty": "Aucun fournisseur ne correspond",
"config.ai_status_configured": "Configuré",
"config.ai_status_not_configured": "Non configuré",
"config.ai_delete_key_title": "Supprimer la clé API",
"config.api_keys_saved": "Clés API sauvegardées",
"config.section_sources": "🔗 Sources connectées & recherche",
"config.sources_desc": "Clés utilisées par les outils de l'Assistant IA (recherche web à clé : Tavily, Brave, SerpAPI, Exa ; sources connectées : Gitea, GitHub). Elles sont stockées sur le serveur et priment sur les variables d'environnement.",
@@ -488,7 +496,7 @@
"config.section_fonctionnalites": "Fonctionnalités",
"config.section_format-du-payload": "Format du payload",
"config.section_gestion-des-onglets": "📑 Gestion des onglets",
"config.section_hidden": "Fichiers cachés",
"config.section_hidden": "🗂️ Fichiers cachés",
"config.section_historique-recent-redemarrage-non-requis": "📋 Historique récent\n Redémarrage non requis",
"config.section_indicateurs-visuels": "Indicateurs visuels",
"config.section_intelligence-artificielle-dans-l-editeur": "🤖 Intelligence Artificielle dans l'Éditeur",
@@ -531,7 +539,7 @@
"config.section_securite-signature-hmac-sha256": "Sécurité : signature HMAC-SHA256",
"config.section_selection-de-vault": "Sélection de vault",
"config.section_server": "Serveur",
"config.section_shares": "Partages publics",
"config.section_shares": "📤 Partages publics",
"config.section_sidebar-barre-laterale": "Sidebar (barre latérale)",
"config.section_synchronisation-automatique": "Synchronisation automatique",
"config.section_tag-cloud": "Tag cloud",
@@ -1471,6 +1479,76 @@
"pwa.install_button": "Installer",
"pwa.install_desc": "Installez cette application sur votre appareil pour un accès rapide.",
"pwa.install_title": "Installer ObsiGate",
"qa.all_actions": "Toutes les actions",
"qa.audit_code": "Détecter les bugs et failles potentielles",
"qa.audit_code.prompt": "Identifie les bugs potentiels, cas limites non gérés et failles de sécurité dans ce code, avec les correctifs proposés.",
"qa.backlinks": "Suggérer des liens et backlinks du vault",
"qa.backlinks.prompt": "Suggère des liens [[wikilinks]] pertinents vers d'autres notes du vault et des backlinks à ajouter à ce document.",
"qa.badge_code": "Fichier de code",
"qa.badge_directory": "Répertoire",
"qa.badge_general": "Mode général",
"qa.badge_multi": "{count} docs ouverts",
"qa.badge_selection": "Sélection active",
"qa.badge_single": "1 doc ouvert",
"qa.capabilities": "Que sais-tu faire ?",
"qa.capabilities.prompt": "Que sais-tu faire ? Présente tes capacités sur ce vault.",
"qa.cat_code": "Code & Scripts",
"qa.cat_cross": "Cross-documents",
"qa.cat_edition": "Édition & Reformulation",
"qa.cat_general": "Assistant",
"qa.cat_structure": "Productivité & Structuration",
"qa.cat_synthesis": "Synthèse & Analyse",
"qa.checklist": "Extraire la checklist d'actions",
"qa.checklist.prompt": "Extrais toutes les actions concrètes à mener sous forme de to-do list Markdown avec cases à cocher [ ].",
"qa.compare": "Comparer différences et convergences",
"qa.compare.prompt": "Compare l'ensemble des documents ouverts et résume leurs convergences, divergences et oppositions.",
"qa.concise": "Rendre plus concis et percutant",
"qa.concise.prompt": "Reformule la sélection pour la rendre plus concise et percutante, sans perdre l'essentiel.",
"qa.create_note": "Créer une note de réunion",
"qa.create_note.prompt": "Crée un fichier de notes de réunion dans le vault.",
"qa.doc_code": "Ajouter la documentation et les types",
"qa.doc_code.prompt": "Ajoute les docstrings, JSDoc et annotations de type appropriés à toutes les fonctions de ce fichier.",
"qa.drawer_title": "Bibliothèque d'actions",
"qa.empty_hint": "Sélectionnez une action instantanée adaptée à votre contexte, ou posez une question directe.",
"qa.explain_code": "Expliquer la logique du script",
"qa.explain_code.prompt": "Analyse et explique pas à pas la structure et l'algorithme de ce code source.",
"qa.explain_selection": "Expliquer la sélection",
"qa.explain_selection.prompt": "Explique le passage sélectionné : son rôle, son contexte et ce qu'il implique.",
"qa.faq": "Générer une FAQ / questions-clés",
"qa.faq.prompt": "Génère une liste de 5 questions-réponses clés pour évaluer la compréhension de ce texte.",
"qa.fix_style": "Corriger et améliorer le style",
"qa.fix_style.prompt": "Corrige les fautes d'orthographe, de grammaire et améliore la fluidité syntaxique de ce passage.",
"qa.frictions": "Relever les frictions et contradictions",
"qa.frictions.prompt": "Analyse ce document et relève les incohérences, zones d'ombre ou contradictions.",
"qa.frontmatter": "Générer le frontmatter YAML",
"qa.frontmatter.prompt": "Génère un bloc frontmatter YAML complet au format du vault et applique-le au document ouvert (insère-le en tête du fichier ou remplace le bloc existant, en conservant les valeurs non vides déjà présentes) : titre, auteur, creation_date et modification_date en ISO-8601 avec fuseau, catégorie, tags (liste en ligne [a, b]), aliases, status, publish, favoris, template, task, archive, draft, private (booléens), NomDeVoute (nom du vault courant), Description (résumé en une phrase du contenu).",
"qa.frontmatter_update": "Mettre à jour le frontmatter",
"qa.frontmatter_update.prompt": "Mets à jour le frontmatter YAML du document ouvert sans supprimer les champs existants : actualise modification_date (horodatage courant ISO-8601 avec fuseau), recalcule titre, tags, aliases, catégorie, NomDeVoute et Description d'après le contenu actuel, complète tout champ de la section métadonnée manquant (auteur, creation_date, status, publish, favoris, template, task, archive, draft, private) et applique la modification au fichier.",
"qa.header_suggested": "Actions suggérées",
"qa.memo": "Rédiger un mémo exécutif partageable",
"qa.memo.prompt": "Rédige un mémo exécutif partageable basé sur ce document : contexte, constats, recommandations.",
"qa.merge": "Fusionner en une note de synthèse",
"qa.merge.prompt": "Fusionne les éléments essentiels de tous les documents ouverts en une note de synthèse unifiée et fluide.",
"qa.no_match": "Aucune action ne correspond.",
"qa.plan": "Créer un plan d'action par étapes",
"qa.plan.prompt": "Transforme ce contenu en un plan d'action structuré par étapes, avec priorités et estimations.",
"qa.rephrase": "Reformuler ce passage",
"qa.rephrase.prompt": "Reformule ce passage en gardant le sens mais avec une tournure différente.",
"qa.search_help": "Rechercher efficacement dans mes notes",
"qa.search_help.prompt": "Comment rechercher efficacement dans mes notes ?",
"qa.search_placeholder": "Rechercher une action...",
"qa.sections": "Structurer en sections hiérarchiques",
"qa.sections.prompt": "Restructure ce document avec une hiérarchie logique de titres Markdown (H2, H3) et des listes à puces propres.",
"qa.summarize_3": "Résumer en 3 points clés",
"qa.summarize_3.prompt": "Fais un résumé synthétique de ce document en 3 points clés, clairs et concis.",
"qa.test_code": "Générer les tests unitaires",
"qa.test_code.prompt": "Rédige une suite de tests unitaires couvrant les cas nominaux et d'erreur pour ce code.",
"qa.timeline": "Construire une chronologie transversale",
"qa.timeline.prompt": "Construis une chronologie transversale des événements datés mentionnés dans ces documents.",
"qa.translate": "Traduire la sélection",
"qa.translate.prompt": "Traduis ce passage dans la langue appropriée (anglais si le texte est en français, et inversement).",
"qa.vulgarize": "Vulgariser ce document",
"qa.vulgarize.prompt": "Explique le contenu de ce document de manière simple, accessible et sans jargon.",
"search.advanced_operators": "Opérateurs avancés",
"search.aria_label": "Suggestions de recherche",
"search.case_sensitive": "Respecter la casse",
@@ -1953,5 +2031,96 @@
"help.excalidraw_search_title": "Recherche",
"help.excalidraw_search": "Le texte des éléments du diagramme est extrait à l'indexation : il est donc recherchable via la recherche full-text.",
"help.excalidraw_compat": "Les fichiers créés avec le plugin Obsidian Excalidraw (y compris le format <code>.excalidraw.md</code> compressé) sont compatibles.",
"help.footer_tagline": "- Porte d'entrée web pour vos vaults Obsidian"
}
"help.footer_tagline": "- Porte d'entrée web pour vos vaults Obsidian",
"guide105.nav_architecture": "🏗️ Architecture",
"guide105.nav_library": "⭐ Bibliothèque",
"guide105.nav_diagrams": "📊 Diagrammes",
"guide105.nav_offline": "📴 Hors-ligne",
"guide105.nav_collab": "👥 Collaboration",
"guide105.nav_desktop": "🖥️ Desktop",
"guide105.nav_api": "🔌 API",
"guide105.nav_languages": "🌍 Multilingue",
"guide105.arch_intro": "ObsiGate est une application web complète construite en couches indépendantes, sans base de données externe : les notes vivent dans vos dossiers Obsidian, l'état applicatif dans des fichiers JSON de <code>data/</code>, l'index de recherche en mémoire.",
"guide105.arch_diagram_note": "Le diagramme est interactif dans l'application : zoom, plein écran, copie SVG ou code.",
"guide105.arch_h3_layers": "Les grandes composantes",
"guide105.arch_lbl_fe": "Frontend",
"guide105.arch_fe": " — SPA en JavaScript vanilla (modules ES), sans framework ni build npm : <code>frontend/js/</code> (~30 modules). Le CSS utilise des variables pour les thèmes.",
"guide105.arch_lbl_be": "Backend",
"guide105.arch_be": " — serveur FastAPI (Python 3.11) : rendu markdown (mistune + wikilinks), recherche TF-IDF stemmisée (index inversé en mémoire), watchers watchdog, JWT + Argon2id, webhooks HMAC, export PDF (WeasyPrint).",
"guide105.arch_lbl_realtime": "Temps réel & MCP",
"guide105.arch_rt": " — passerelle WebSocket (collaboration Yjs, notifications SSE/push) et serveur MCP (Streamable HTTP, <code>/mcp</code>) pour les clients externes.",
"guide105.arch_lbl_ai": "Couche IA",
"guide105.arch_ai": " — assistants d'édition et BooksLM multi-providers (DeepSeek, OpenRouter, Gemini, Mistral…), bibliothèque d'outils (function calling, recherche web, crawl, lecture de documents) et embeddings optionnels pour la recherche sémantique.",
"guide105.arch_lbl_data": "Données",
"guide105.arch_data": " — les vaults Obsidian sur disque (source de vérité), la configuration en JSON (<code>data/</code>), les backups horodatés (<code>.obsigate-backup/</code>), l'audit en JSON lines, les clés API chiffrées dans <code>data/api_keys.json</code>.",
"guide105.arch_lbl_deploy": "Déploiement",
"guide105.arch_deploy": " — application desktop Tauri (Rust) embarquant le backend Python, conteneur Docker, ou PWA installable dans le navigateur (mode hors-ligne).",
"guide105.arch_h3_flux": "Flux typique",
"guide105.arch_flux": " Un clic sur un fichier émet <code>GET /api/file/...</code> ; le backend résout le chemin en sécurité, parse le frontmatter, rend le markdown et renvoie le HTML ; le frontend enrichit l'affichage (Mermaid, coloration, wikilinks cliquables). Chaque écriture crée un backup avant application.",
"guide105.dia_intro": "Les blocs <code>```mermaid</code> de vos notes sont rendus en diagrammes interactifs (Mermaid v11, chargé depuis un CDN).",
"guide105.dia_zoom": "Zoom : boutons + / − dans la barre d'outils du diagramme.",
"guide105.dia_fs": "Plein écran : idéal pour les grandes matrices.",
"guide105.dia_copy": "Copie : exportez le SVG ou le code source (boutons dédiés).",
"guide105.dia_toggle": "Bascule Aperçu / Code pour éditer la source sans quitter la vue.",
"guide105.dia_theme": "Thème : le diagramme suit le thème clair/sombre de l'application.",
"guide105.dia_types": "Types supportés : flowchart, sequence, class, state, ER, gantt, pie, journey, quadrant, radar, mindmap, timeline, C4, xychart, sankey — plus un préprocesseur qui comprend la syntaxe Obsidian.",
"guide105.dia_excalidraw_ref": "Les dessins à main levée (<code>.excalidraw</code>, <code>.excalidraw.md</code>) sont couverts dans la section 🎨 Excalidraw.",
"guide105.lib_h3_bookmarks": "Signets & récents",
"guide105.lib_bookmarks": "Marquez un fichier d'un ★ (bouton Signet de la barre d'actions) : il rejoint la liste des signets du dashboard. Les fichiers récemment ouverts sont listés automatiquement dans l'onglet « Récents » de la sidebar, avec un filtre de recherche dédié.",
"guide105.lib_h3_saved": "Recherches sauvegardées",
"guide105.lib_saved": "Enregistrez une recherche depuis la page de résultats pour la relancer en un clic depuis la sidebar : chaque recherche sauvegardée conserve ses opérateurs et filtres.",
"guide105.lib_h3_backlinks": "Backlinks & graphe",
"guide105.lib_backlinks": "Le panneau Backlinks liste toutes les notes qui pointent vers le fichier ouvert. La vue Graphe (bouton 🕸️) affiche les liens entre fichiers : glissez les nœuds, zoomez à la molette, double-cliquez pour ouvrir une note.",
"guide105.lib_h3_conflicts": "Conflits de synchronisation",
"guide105.lib_conflicts": "Si vous synchronisez le vault avec Syncthing, ObsiGate détecte les fichiers de conflit (copies « sync-conflict ») et propose de les comparer puis résoudre depuis la page dédiée du menu Options.",
"guide105.lib_h3_attach": "Fichiers joints & médias",
"guide105.lib_attach": "Les images <code>![[image.png]]</code>, pièces jointes et médias (audio, vidéo, PDF intégrés) dans les notes sont rendus dans le viewer et indexés pour la recherche ; le bouton « Rescan attachments » de la configuration recrée l'index des pièces jointes.",
"guide105.off_pwa": "ObsiGate est une PWA : installez-la (icône d'installation de la barre d'adresse) pour l'ouvrir comme une application. Le service worker met en cache l'interface et vos derniers documents consultés.",
"guide105.off_edit": "Hors-ligne, vous pouvez lire les documents en cache et même les éditer : les modifications sont mises en file d'attente dans IndexedDB.",
"guide105.off_sync": "Au retour en ligne, la file se rejoue automatiquement (badge de synchronisation dans l'en-tête). Si la version serveur a divergé entre-temps, le fichier est marqué en conflit et la version serveur est préservée en backup.",
"guide105.off_watch": "Les modifications externes (Obsidian sur disque) sont détectées par le watcher : la vue se recharge sans perte de position, ou signale « modifié en externe » pendant une édition.",
"guide105.col_intro": "Ouvrez un document en mode Édition : plusieurs personnes peuvent travailler simultanément sur le même fichier via un WebSocket Yjs (CRDT). Les modifications fusionnent sans verrou.",
"guide105.col_cursors": "Les curseurs et sélections des collaborateurs apparaissent avec une couleur et un nom par personne (awareness).",
"guide105.col_save": "La fusion est persistée côté serveur après 2 s d'inactivité ; chaque écriture crée un backup horodaté avant application.",
"guide105.col_perm": "Accès limité aux utilisateurs authentifiés disposant de la permission sur la vault.",
"guide105.des_get": "L'application desktop ObsiGate (Tauri) embarque le serveur Python : aucune installation de Docker nécessaire. Elle se télécharge sur la page des Releases du dépôt et se met à jour automatiquement (updater signé).",
"guide105.des_wizard": "Au premier lancement, un assistant demande le dossier de vos vaults (ou crée un vault de démonstration). Chaque document peut être détaché en fenêtre native séparée.",
"guide105.des_data": "Les données desktop restent dans le répertoire applicatif ; les vaults pointent sur vos dossiers existants. Toutes les fonctionnalités web (recherche, IA, partage) sont disponibles.",
"guide105.des_native": "Menu système natif, raccourci global optionnel pour afficher/masquer la fenêtre et jumplist des vaults récents.",
"guide105.api_intro": "ObsiGate expose une API REST couvrant toute l'application (vaults, fichiers, recherche, backups, export, IA, partage, admin), documentée en OpenAPI 3.1 :",
"guide105.api_docs_url": "<code>/docs</code> — interface Swagger UI pour essayer les requêtes en direct.",
"guide105.api_redoc": "<code>/redoc</code> — référence alternative plus compacte.",
"guide105.api_landing": "<code>/api</code> — page de garde regroupant les endpoints par catégorie.",
"guide105.api_schema": "<code>/openapi.json</code> — le schéma machine, à importer dans Postman ou Insomnia.",
"guide105.api_h3_auth": "Authentification",
"guide105.api_auth": "Connectez-vous via <code>POST /api/auth/login</code> pour obtenir un token Bearer (le même jeton est accepté en cookie HttpOnly, ce qui permet aux clients navigateur d'utiliser <code>credentials: \"include\"</code>). Toutes les routes <code>/api/*</code> exigent ce jeton sauf mention contraire.",
"guide105.api_h3_mcp": "Serveur MCP",
"guide105.api_mcp": "Les outils de l'assistant IA (lire, lister, chercher, ouvrir, écrire…) sont exposés à tout client MCP (Claude Desktop, Cursor, Cline…) sur <code>https://votre-instance/mcp</code> avec un token d'API. Configuration et exemples : <code>docs/MCP_GUIDE.md</code>.",
"guide105.api_h3_autom": "Automatisation",
"guide105.api_autom": "Pour automatiser depuis l'extérieur : <code>GET /api/search?q=…</code> et <code>GET /api/file/{vault}?path=…</code> permettent d'indexer ou relire vos notes dans un autre outil ; les webhooks sortants (section 🪝) évitent le polling.",
"guide105.lng_how": "L'interface est intégralement bilingue français / anglais. Réglages → Profil → Langue : le choix est enregistré sur votre compte et vous suit sur tous les appareils.",
"guide105.lng_scope": "Tout est traduit : menus, messages, notifications, et le présent guide. Les réponses de l'assistant IA suivent la langue de vos documents.",
"guide105.lng_export": "Les boutons Markdown / PDF de ce guide téléchargent la version dans votre langue.",
"guide105.h3_semantic": "Recherche sémantique (hybride)",
"guide105.sem_p1": "Activez le bouton « S » de la barre de recherche (ou Alt-S) pour combiner TF-IDF et similarité vectorielle (fusion RRF) : les concepts approchants (« velours » trouve « tissu doux ») remontent mieux.",
"guide105.sem_p2": "Le moteur d'embeddings (modèle multilingue) est optionnel : sans lui, un repli par hash conserve une recherche hybride fonctionnelle. Les vecteurs sont recalculés à chaque indexation du vault.",
"guide105.h3_push": "Notifications web (push)",
"guide105.push_p1": "Autorisez les notifications (bouton 🔔 de l'en-tête) pour être averti des fins de synchronisation hors-ligne et des événements importants. La gestion des abonnements est dans les Configurations.",
"guide105.push_p2": "Basée sur la Web Push API (clés VAPID) ; fonctionne sur desktop et PWA mobile, sans service tiers : le serveur émet directement vers les endpoints push des navigateurs.",
"guide105.h3_panes": "Vue multi-panneaux (split view)",
"guide105.panes_p": "Le bouton « Diviser » de la barre d'actions ouvre le document dans un panneau jumeau ; empilez plusieurs panneaux pour comparer deux notes ou lire et éditer en parallèle. Les largeurs se règlent au bord des panneaux et sont mémorisées.",
"guide105.h3_dupe": "Anti-doublons à l'upload",
"guide105.dupe_p": "L'upload en masse (glisser-déposer un dossier sur la sidebar) compare chaque fichier au contenu existant : un fichier déjà présent est ignoré plutôt que dupliqué avec un suffixe « (1) ». Utile pour restaurer un vault sans créer de doublons.",
"guide105.h3_pdf": "Export PDF",
"guide105.pdf_p": "Le bouton « PDF » d'un document le rend avec le même moteur que la vue (WeasyPrint) : titres, tableaux, listes et code sont conservés. Depuis un lien public, la route <code>/s/{token}/pdf</code> produit le même PDF.",
"guide105.h3_exports": "Export HTML / ePub / ZIP",
"guide105.exp_p": "Le menu « Exporter » propose trois formats : HTML autonome (fichier unique, images incluses), ePub pour les liseuses et, pour un dossier, un bundle Markdown en ZIP — liens et ressources résolus pendant l'export.",
"guide105.h3_mfa": "MFA : TOTP, WebAuthn, codes de secours",
"guide105.mfa_p": "Activez la double authentification dans Réglages → Profil : applications TOTP (Authy, Aegis…), clés de sécurité et passkeys (WebAuthn, y compris Windows Hello) et 10 codes de secours à conserver hors ligne. Chaque méthode s'active et se désactive indépendamment.",
"guide105.h3_admin": "Tableau de bord administrateur",
"guide105.admin_p": "Le rôle admin ouvre une page dédiée <code>/admin.html</code> (bouton du menu Options) : statut du serveur en direct, utilisateurs, vaults, sessions actives et journal d'audit. Le CRUD utilisateurs est aussi disponible dans les Configurations.",
"guide105.dl_md_title": "Télécharger ce guide en Markdown",
"guide105.dl_pdf_title": "Télécharger ce guide en PDF",
"guide105.export_title": "Guide d'utilisation ObsiGate",
"guide105.export_footer": "Généré depuis ObsiGate {version} — {date}. Ce document est la copie du guide intégré ; la version la plus récente est toujours dans l'application."
}
+351 -4
View File
@@ -1473,6 +1473,15 @@ select {
margin: 0 auto;
max-width: 1200px;
}
/* Full-bleed viewers (PDF, images, Excalidraw) must use the whole width when
the navigation sidebar is hidden instead of the centered reading column. */
.sidebar.hidden ~ .content-wrapper .content-area:has(.pdf-viewer-container),
.sidebar.hidden ~ .content-wrapper .content-area:has(.image-viewer-container),
.sidebar.hidden ~ .content-wrapper .content-area:has(iframe[src*="excalidraw-editor.html"]) {
margin: 0;
max-width: none;
}
.content-area::-webkit-scrollbar {
width: 8px;
}
@@ -4338,6 +4347,258 @@ body.resizing-v {
background: var(--bg-hover);
}
/* --- AI keys section: accordion redesign (#104) --- */
.ai-keys-header {
display: flex;
flex-wrap: wrap;
gap: 12px;
align-items: flex-start;
justify-content: space-between;
margin-bottom: 18px;
}
.ai-keys-header-text {
flex: 1 1 320px;
min-width: 0;
}
.ai-keys-header-text h2 {
margin-bottom: 4px;
}
.ai-keys-search {
position: relative;
flex: 0 1 260px;
min-width: 200px;
}
.ai-keys-search .icon {
position: absolute;
left: 10px;
top: 50%;
transform: translateY(-50%);
width: 14px;
height: 14px;
color: var(--text-muted);
pointer-events: none;
}
.ai-keys-search input {
width: 100%;
padding: 8px 12px 8px 32px;
border: 1px solid var(--border);
border-radius: 8px;
background: var(--bg-secondary);
color: var(--text-primary);
font-size: 0.8rem;
outline: none;
transition: border-color 150ms ease;
}
.ai-keys-search input:focus {
border-color: var(--accent);
}
.ai-card-title {
font-size: 0.72rem;
font-weight: 600;
letter-spacing: 0.6px;
text-transform: uppercase;
color: var(--text-secondary);
}
.ai-default-card {
background: var(--surface, #1e1e24);
border: 1px solid var(--border);
border-radius: 10px;
padding: 16px 18px;
margin-bottom: 22px;
}
.ai-default-card > .ai-card-title {
margin-bottom: 12px;
}
.ai-default-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-bottom: 12px;
}
.ai-field {
display: flex;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.ai-field-label {
font-size: 0.75rem;
font-weight: 500;
color: var(--text-secondary);
letter-spacing: 0.2px;
}
.ai-field .config-select,
.ai-field .config-input {
width: 100%;
}
.ai-caps-badges {
display: flex;
flex-wrap: wrap;
gap: 6px;
min-height: 22px;
}
.ai-cap-badge {
display: inline-flex;
align-items: center;
padding: 3px 10px;
border-radius: 999px;
font-size: 0.7rem;
font-weight: 600;
background: var(--accent-bg);
color: var(--accent);
border: 1px solid color-mix(in srgb, var(--accent) 35%, transparent);
}
.ai-providers-header {
margin: 0 0 10px;
}
.ai-providers-list {
display: flex;
flex-direction: column;
gap: 8px;
}
.ai-provider-card {
background: var(--surface, #1e1e24);
border: 1px solid var(--border);
border-radius: 10px;
transition: border-color 150ms ease;
}
.ai-provider-card:hover {
border-color: var(--border-md);
}
.ai-provider-card.open {
border-color: color-mix(in srgb, var(--accent) 45%, var(--border));
}
.ai-provider-head {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 14px;
cursor: pointer;
user-select: none;
border-radius: 10px;
}
.ai-provider-head:focus-visible {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.ai-provider-logo {
display: inline-flex;
align-items: center;
justify-content: center;
width: 28px;
height: 28px;
border-radius: 8px;
background: var(--accent-bg);
color: var(--accent);
font-weight: 700;
font-size: 0.85rem;
flex: none;
}
.ai-provider-name {
flex: 1;
font-size: 0.88rem;
font-weight: 600;
color: var(--text-primary);
min-width: 0;
}
.ai-provider-badge {
font-size: 0.68rem;
padding: 2px 9px;
border-radius: 999px;
white-space: nowrap;
background: var(--muted-bg, rgba(255, 255, 255, 0.06));
color: var(--text-muted);
border: 1px solid var(--border);
}
.ai-provider-badge.configured {
background: var(--success-bg);
color: var(--success);
border-color: color-mix(in srgb, var(--success) 40%, transparent);
}
.ai-provider-delete {
display: inline-flex;
align-items: center;
justify-content: center;
width: 26px;
height: 26px;
border: none;
border-radius: 6px;
background: transparent;
color: var(--text-muted);
cursor: pointer;
flex: none;
transition: color 150ms ease, background 150ms ease;
}
.ai-provider-delete:hover {
color: var(--danger);
background: var(--danger-bg);
}
.ai-provider-chevron {
flex: none;
color: var(--text-muted);
transition: transform 200ms ease;
}
.ai-provider-card.open .ai-provider-chevron {
transform: rotate(180deg);
}
.ai-provider-body {
padding: 0 14px 14px;
}
.ai-provider-body.hidden {
display: none;
}
.ai-provider-fields {
display: grid;
grid-template-columns: 3fr 2fr;
gap: 12px;
padding-top: 12px;
border-top: 1px solid var(--border);
}
.ai-providers-empty {
padding: 14px;
text-align: center;
color: var(--text-muted);
font-size: 0.8rem;
border: 1px dashed var(--border);
border-radius: 10px;
}
.ai-keys-footer {
position: sticky;
bottom: 0;
z-index: 5;
display: flex;
align-items: center;
gap: 12px;
flex-wrap: wrap;
margin-top: 20px;
padding: 12px 16px;
background: var(--surface, #1e1e24);
border: 1px solid var(--border);
border-radius: 10px;
box-shadow: 0 -4px 16px rgba(0, 0, 0, 0.25);
}
.ai-keys-status {
flex: 1;
font-size: 0.75rem;
color: var(--text-muted);
min-width: 0;
}
@media (max-width: 600px) {
.ai-default-grid,
.ai-provider-fields {
grid-template-columns: 1fr;
}
.ai-keys-search {
flex: 1 1 100%;
}
}
/* --- Config diagnostics panel --- */
.config-diagnostics {
background: var(--code-bg);
@@ -7885,6 +8146,29 @@ body.popup-mode .content-area {
.cp-browse-filter:focus { border-color: var(--accent); }
.cp-browse-filter::placeholder { color: var(--text-muted); }
/* ── Help Modal: desktop = wider reading (#105) ──
The Tauri shell (body.desktop-mode) and wide web viewports get the full
reading layout instead of the 1320px modal cap. */
body.desktop-mode .help-container {
max-width: 1760px;
width: 96vw;
}
body.desktop-mode .help-content {
max-width: 1440px;
padding: 36px 56px 64px;
}
body.desktop-mode .editor-container {
max-height: 94vh;
}
@media (min-width: 1400px) {
.help-container {
max-width: min(1640px, calc(100vw - 48px));
}
.help-content {
max-width: 1280px;
}
}
/* ── Help Modal: Mobile responsive ── */
@media (max-width: 768px) {
.help-container,
@@ -9492,7 +9776,9 @@ body.popup-mode .content-area {
.bookslm-toolbar .ai-picker { margin-left: 0; padding-left: 0; border-left: none;
flex-wrap: wrap; row-gap: 4px; }
.bookslm-toolbar .ai-picker select { max-width: 220px; }
.bookslm-panel.fullscreen { width: 100vw; }
/* `!important` is required: the panel width is also written inline by the
resize handle / persisted width, and an inline style would otherwise win. */
.bookslm-panel.fullscreen { width: 100vw !important; }
.bookslm-status { padding: 6px 16px; font-size: 12px; color: var(--text-secondary);
border-bottom: 1px solid var(--border); display: flex; gap: 12px; align-items: center; }
.bookslm-status .bookslm-status-text { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -9639,10 +9925,71 @@ details[open] > summary .bookslm-chevron::before { content: '▼'; }
.bookslm-diff-add { color: #4ade80; display: block; }
.bookslm-diff-del { color: #f87171; display: block; }
.bookslm-diff-ctx { color: var(--text-secondary); display: block; }
/* #106 — Actions instantanées contextuelles de l'assistant. */
.bookslm-suggestions { display: flex; flex-direction: column; gap: 6px; padding: 8px 16px 0; }
.bookslm-suggestion { padding: 8px 12px; border-radius: 8px; border: 1px solid var(--border);
background: var(--surface); color: var(--text-secondary); cursor: pointer; font-size: 13px; text-align: left; }
.bookslm-suggestion:hover { background: var(--surface2); color: var(--text-primary); border-color: var(--accent); }
.bookslm-suggestions.hidden { display: none; }
.bookslm-qa-badge { flex-shrink: 0; font-size: 10px; text-transform: uppercase;
letter-spacing: 0.5px; font-weight: 600; color: var(--accent-text, var(--accent));
background: var(--accent-bg);
border: 1px solid var(--border); border-radius: 999px; padding: 2px 8px; }
.bookslm-qa-badge.hidden { display: none; }
.bookslm-qa-hint { margin: 0 0 2px; font-size: 12px; color: var(--text-secondary); line-height: 1.45; }
.bookslm-qa-head { display: flex; align-items: center; justify-content: space-between; padding: 0 2px; }
.bookslm-qa-label { font-size: 10px; font-weight: 700; letter-spacing: 0.8px;
text-transform: uppercase; color: var(--text-muted, var(--text-secondary)); opacity: 0.85; }
.bookslm-qa-more { display: inline-flex; align-items: center; gap: 5px; background: none;
border: none; color: var(--accent); font-size: 12px; cursor: pointer; padding: 2px 4px;
border-radius: 6px; }
.bookslm-qa-more:hover { background: var(--bg-hover); }
.bookslm-qa-list { display: flex; flex-direction: column; gap: 6px; }
.bookslm-qa-btn { display: flex; align-items: center; gap: 10px; width: 100%;
text-align: left; padding: 9px 12px; border-radius: 10px; cursor: pointer;
background: var(--surface); border: 1px solid var(--border); color: var(--text-secondary);
font-size: 13px; transition: background 0.15s ease, border-color 0.15s ease, color 0.15s ease; }
.bookslm-qa-btn:hover { background: var(--surface2); border-color: var(--accent); color: var(--text-primary); }
.bookslm-qa-btn .bookslm-qa-icon { color: var(--text-muted, var(--text-secondary)); flex-shrink: 0; }
.bookslm-qa-btn:hover .bookslm-qa-icon { color: var(--accent); }
.bookslm-qa-text { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis;
white-space: nowrap; font-weight: 500; }
.bookslm-qa-go { opacity: 0; transform: translateX(-3px); transition: opacity 0.15s ease,
transform 0.15s ease; color: var(--accent); flex-shrink: 0; }
.bookslm-qa-btn:hover .bookslm-qa-go { opacity: 1; transform: translateX(0); }
/* Tiroir catalogue ("Toutes les actions") : bottom-sheet dans le panneau. */
.bookslm-qa-drawer { position: absolute; inset: 0; z-index: 60; background: rgba(0, 0, 0, 0.45);
display: flex; align-items: flex-end; opacity: 0; transition: opacity 0.2s ease; }
.bookslm-qa-drawer.hidden { display: none; }
.bookslm-qa-drawer.open { opacity: 1; }
.bookslm-qa-sheet { width: 100%; max-height: 82%; display: flex; flex-direction: column;
background: var(--bg-primary); border-top: 1px solid var(--border);
border-radius: 14px 14px 0 0; padding: 12px 14px 10px; box-shadow: 0 -8px 30px rgba(0, 0, 0, 0.35);
transform: translateY(100%); transition: transform 0.22s ease; }
.bookslm-qa-drawer.open .bookslm-qa-sheet { transform: translateY(0); }
.bookslm-qa-sheet-head { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
.bookslm-qa-sheet-title { display: inline-flex; align-items: center; gap: 7px; font-size: 14px;
font-weight: 600; color: var(--text-primary); }
.bookslm-qa-sheet-title i { color: var(--accent); }
.bookslm-qa-sheet-close { display: inline-flex; align-items: center; justify-content: center;
width: 26px; height: 26px; border-radius: 50%; border: none; cursor: pointer;
background: var(--surface); color: var(--text-secondary); }
.bookslm-qa-sheet-close:hover { background: var(--surface2); color: var(--text-primary); }
.bookslm-qa-search { position: relative; margin-bottom: 10px; }
.bookslm-qa-search i { position: absolute; left: 9px; top: 50%; transform: translateY(-50%);
color: var(--text-secondary); pointer-events: none; }
.bookslm-qa-search input { width: 100%; box-sizing: border-box; padding: 7px 10px 7px 30px;
border-radius: 8px; border: 1px solid var(--border); background: var(--surface);
color: var(--text-primary); font-size: 13px; outline: none; }
.bookslm-qa-search input:focus { border-color: var(--accent); }
.bookslm-qa-sheet-list { flex: 1; overflow-y: auto; display: flex; flex-direction: column; gap: 6px;
padding-bottom: 8px; }
.bookslm-qa-cat { margin: 8px 2px 2px; display: flex; align-items: center; gap: 6px;
font-size: 10px; font-weight: 700; letter-spacing: 0.8px; text-transform: uppercase;
color: var(--text-secondary); position: sticky; top: 0; background: var(--bg-primary);
padding: 4px 0; z-index: 1; }
.bookslm-qa-btn.compact { padding: 7px 10px; border-radius: 8px; font-size: 12.5px; }
.bookslm-qa-empty { padding: 18px 8px; text-align: center; font-size: 12px; color: var(--text-secondary); }
@media (prefers-reduced-motion: reduce) {
.bookslm-qa-drawer, .bookslm-qa-sheet, .bookslm-qa-btn, .bookslm-qa-go { transition: none; }
}
/* Formatted markdown inside assistant answers. */
.bookslm-bubble.assistant > *:first-child { margin-top: 0; }
.bookslm-bubble.assistant > *:last-child { margin-bottom: 0; }
+1 -1
View File
@@ -11,7 +11,7 @@
* cache or Cloudflare does NOT clear the Service Worker Cache Storage, which is
* a separate store. Bumping SW_VERSION invalidates it on every release.
*/
const SW_VERSION = 'v20';
const SW_VERSION = 'v23';
const CODE_CACHE = `obsigate-code-${SW_VERSION}`;
const RUNTIME_CACHE = `obsigate-runtime-${SW_VERSION}`;
const API_CACHE = `obsigate-api-${SW_VERSION}`;
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "obsigate",
"version": "2.11.3",
"version": "2.14.0",
"description": "**Porte d'entrée web ultra-léger pour vos vaults Obsidian** — Accédez, naviguez et recherchez dans toutes vos notes Obsidian depuis n'importe quel appareil via une interface web moderne et responsive.",
"main": "patch.js",
"directories": {
+66
View File
@@ -0,0 +1,66 @@
"""Pré-rend les diagrammes Mermaid du guide intégré en PNG (#105).
Scanne les blocs ``<pre class="mermaid-code">`` de frontend/index.html,
extrait leur code, et appelle scripts/render_guide_diagram.mjs (Chromium +
mermaid v11) pour produire ``backend/assets/guide_diagrams/<sha1>.png``.
Ces PNG sont commités : le PDF du guide les embarque comme vraies images
(WeasyPrint ne sait pas exécuter Mermaid).
Usage : python scripts/build_guide_diagrams.py
"""
import hashlib
import html
import json
import re
import subprocess
import sys
import tempfile
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
ASSETS = ROOT / "backend" / "assets" / "guide_diagrams"
def extract_mermaid() -> dict[str, str]:
page_html = (ROOT / "frontend" / "index.html").read_text(encoding="utf-8")
out: dict[str, str] = {}
for m in re.finditer(
r'<pre class="mermaid-code"><code class="language-mermaid">(.*?)</code></pre>',
page_html,
re.DOTALL,
):
code = m.group(1)
code = html.unescape(code).strip()
sha = hashlib.sha1(code.encode("utf-8")).hexdigest()[:16]
out[sha] = code
return out
def main() -> int:
jobs = extract_mermaid()
if not jobs:
print("aucun bloc mermaid dans index.html")
return 1
todo = {k: v for k, v in jobs.items() if not (ASSETS / f"{k}.png").exists()}
print("diagrammes:", len(jobs), "| à rendre:", len(todo))
if not todo:
return 0
with tempfile.NamedTemporaryFile("w", suffix=".json", delete=False, encoding="utf-8") as f:
json.dump(todo, f)
path = f.name
r = subprocess.run(
["node", str(ROOT / "scripts" / "render_guide_diagram.mjs"), path],
cwd=ROOT,
capture_output=True,
check=False,
text=True,
timeout=300,
)
print(r.stdout[-2000:])
if r.returncode != 0:
print(r.stderr[-2000:])
return r.returncode
if __name__ == "__main__":
sys.exit(main())
+626
View File
@@ -0,0 +1,626 @@
# -*- coding: utf-8 -*-
"""Nouveau contenu du Guide d'utilisation (#105) — source unique de vérité.
Rôles :
1. ``CONTENT`` : dictionnaire i18n clé -> (fr, en). Les locales FR/EN sont
générées depuis ce dictionnaire par ``scripts/merge_guide_locales.py``
(ne jamais éditer les blocs ``guide105.*`` des JSON à la main).
2. Les constantes ``SECTION_*`` / ``EXTRA_BLOCKS`` / ``TOC_INSERT_BEFORE``
décrivent le HTML à insérer dans ``frontend/index.html`` par
``scripts/insert_guide_sections.py``. Le texte FR inline de chaque
élément portant ``data-i18n="guide105.X"`` DOIT être identique à
``CONTENT[X][0]`` (sinon ``_applyDOM`` afficherait un texte incohérent
quand la locale FR est appliquée).
Règle i18n : tout élément textuel des nouvelles sections porte une clé
``guide105.*``. Les clés préexistantes ne sont jamais réutilisées avec un
texte différent.
"""
# ---------------------------------------------------------------------------
# Dictionnaire i18n (clé -> FR, EN)
# ---------------------------------------------------------------------------
CONTENT: dict[str, tuple[str, str]] = {
# -- TOC / titres de sections ---------------------------------------------
"nav_architecture": ("🏗️ Architecture", "🏗️ Architecture"),
"nav_library": ("⭐ Bibliothèque", "⭐ Library"),
"nav_diagrams": ("📊 Diagrammes", "📊 Diagrams"),
"nav_offline": ("📴 Hors-ligne", "📴 Offline"),
"nav_collab": ("👥 Collaboration", "👥 Collaboration"),
"nav_desktop": ("🖥️ Desktop", "🖥️ Desktop"),
"nav_api": ("🔌 API", "🔌 API"),
"nav_languages": ("🌍 Multilingue", "🌍 Languages"),
# -- Section Architecture ---------------------------------------------------
"arch_intro": (
"ObsiGate est une application web complète construite en couches indépendantes, sans base"
" de données externe : les notes vivent dans vos dossiers Obsidian, l'état applicatif dans"
" des fichiers JSON de <code>data/</code>, l'index de recherche en mémoire.",
"ObsiGate is a full web application built as independent layers, with no external"
" database: notes live in your Obsidian folders, app state in JSON files under"
" <code>data/</code>, the search index in memory.",
),
"arch_diagram_note": (
"Le diagramme est interactif dans l'application : zoom, plein écran, copie SVG ou code.",
"The diagram is interactive in the app: zoom, fullscreen, copy SVG or code.",
),
"arch_h3_layers": ("Les grandes composantes", "The main components"),
"arch_lbl_fe": ("Frontend", "Frontend"),
"arch_fe": (
" — SPA en JavaScript vanilla (modules ES), sans framework ni build npm :"
" <code>frontend/js/</code> (~30 modules). Le CSS utilise des variables pour les thèmes.",
" — vanilla-JavaScript SPA (ES modules), no framework, no npm build:"
" <code>frontend/js/</code> (~30 modules). CSS variables drive the themes.",
),
"arch_lbl_be": ("Backend", "Backend"),
"arch_be": (
" — serveur FastAPI (Python 3.11) : rendu markdown (mistune + wikilinks),"
" recherche TF-IDF stemmisée (index inversé en mémoire), watchers watchdog, JWT +"
" Argon2id, webhooks HMAC, export PDF (WeasyPrint).",
" — FastAPI server (Python 3.11): markdown rendering (mistune + wikilinks), stemmed"
" TF-IDF search (in-memory inverted index), watchdog file watchers, JWT + Argon2id,"
" HMAC webhooks, PDF export (WeasyPrint).",
),
"arch_lbl_realtime": ("Temps réel & MCP", "Realtime & MCP"),
"arch_rt": (
" — passerelle WebSocket (collaboration Yjs, notifications SSE/push) et serveur MCP"
" (Streamable HTTP, <code>/mcp</code>) pour les clients externes.",
" — WebSocket gateway (Yjs collaboration, SSE/push notifications) and an MCP server"
" (Streamable HTTP, <code>/mcp</code>) for external clients.",
),
"arch_lbl_ai": ("Couche IA", "AI layer"),
"arch_ai": (
" — assistants d'édition et BooksLM multi-providers (DeepSeek, OpenRouter, Gemini,"
" Mistral…), bibliothèque d'outils (function calling, recherche web, crawl, lecture de"
" documents) et embeddings optionnels pour la recherche sémantique.",
" — editor assistant and BooksLM with multiple providers (DeepSeek, OpenRouter, Gemini,"
" Mistral…), a tool library (function calling, web search, crawl, document reading) and"
" optional embeddings for semantic search.",
),
"arch_lbl_data": ("Données", "Data"),
"arch_data": (
" — les vaults Obsidian sur disque (source de vérité), la configuration en JSON"
" (<code>data/</code>), les backups horodatés (<code>.obsigate-backup/</code>),"
" l'audit en JSON lines, les clés API chiffrées dans <code>data/api_keys.json</code>.",
" — Obsidian vaults on disk (the source of truth), JSON configuration"
" (<code>data/</code>), timestamped backups (<code>.obsigate-backup/</code>), a JSON-lines"
" audit log, encrypted API keys in <code>data/api_keys.json</code>.",
),
"arch_lbl_deploy": ("Déploiement", "Deployment"),
"arch_deploy": (
" — application desktop Tauri (Rust) embarquant le backend Python, conteneur Docker, ou"
" PWA installable dans le navigateur (mode hors-ligne).",
" — Tauri desktop app (Rust) embedding the Python backend, a Docker container, or an"
" installable PWA in the browser (offline mode).",
),
"arch_h3_flux": ("Flux typique", "Typical request flow"),
"arch_flux": (
" Un clic sur un fichier émet <code>GET /api/file/...</code> ; le backend résout le chemin"
" en sécurité, parse le frontmatter, rend le markdown et renvoie le HTML ; le frontend"
" enrichit l'affichage (Mermaid, coloration, wikilinks cliquables). Chaque écriture crée"
" un backup avant application.",
" Clicking a file issues <code>GET /api/file/...</code>; the backend resolves the path"
" safely, parses frontmatter, renders the markdown and returns HTML; the frontend"
" enriches the view (Mermaid, syntax highlighting, clickable wikilinks). Every write"
" creates a backup before applying.",
),
# -- Section Diagrammes ---------------------------------------------------------
"dia_intro": (
"Les blocs <code>```mermaid</code> de vos notes sont rendus en diagrammes interactifs"
" (Mermaid v11, chargé depuis un CDN).",
"<code>```mermaid</code> blocks in your notes render as interactive diagrams (Mermaid v11,"
" loaded from a CDN).",
),
"dia_zoom": ("Zoom : boutons + / − dans la barre d'outils du diagramme.",
"Zoom: + / − buttons in the diagram toolbar."),
"dia_fs": ("Plein écran : idéal pour les grandes matrices.",
"Fullscreen: ideal for large charts."),
"dia_copy": ("Copie : exportez le SVG ou le code source (boutons dédiés).",
"Copy: export the SVG or the source code (dedicated buttons)."),
"dia_toggle": ("Bascule Aperçu / Code pour éditer la source sans quitter la vue.",
"Preview / Code toggle to edit the source without leaving the view."),
"dia_theme": ("Thème : le diagramme suit le thème clair/sombre de l'application.",
"Theme: the diagram follows the app's light/dark theme."),
"dia_types": (
"Types supportés : flowchart, sequence, class, state, ER, gantt, pie, journey, quadrant,"
" radar, mindmap, timeline, C4, xychart, sankey — plus un préprocesseur qui comprend la"
" syntaxe Obsidian.",
"Supported types: flowchart, sequence, class, state, ER, gantt, pie, journey, quadrant,"
" radar, mindmap, timeline, C4, xychart, sankey — plus a preprocessor that understands"
" Obsidian syntax.",
),
"dia_excalidraw_ref": (
"Les dessins à main levée (<code>.excalidraw</code>, <code>.excalidraw.md</code>) sont"
" couverts dans la section 🎨 Excalidraw.",
"Hand-drawn sketches (<code>.excalidraw</code>, <code>.excalidraw.md</code>) are covered"
" in the 🎨 Excalidraw section.",
),
# -- Section Bibliothèque & signets ---------------------------------------------
"lib_h3_bookmarks": ("Signets & récents", "Bookmarks & recents"),
"lib_bookmarks": (
"Marquez un fichier d'un ★ (bouton Signet de la barre d'actions) : il rejoint la liste"
" des signets du dashboard. Les fichiers récemment ouverts sont listés automatiquement"
" dans l'onglet « Récents » de la sidebar, avec un filtre de recherche dédié.",
"Star a file with the Bookmark button in the action bar: it joins the dashboard's"
" bookmark list. Recently opened files are listed automatically in the sidebar's"
" \"Recent\" tab, with a dedicated search filter.",
),
"lib_h3_saved": ("Recherches sauvegardées", "Saved searches"),
"lib_saved": (
"Enregistrez une recherche depuis la page de résultats pour la relancer en un clic depuis"
" la sidebar : chaque recherche sauvegardée conserve ses opérateurs et filtres.",
"Save a search from the results page to rerun it in one click from the sidebar: each saved"
" search keeps its operators and filters.",
),
"lib_h3_backlinks": ("Backlinks & graphe", "Backlinks & graph"),
"lib_backlinks": (
"Le panneau Backlinks liste toutes les notes qui pointent vers le fichier ouvert. La vue"
" Graphe (bouton 🕸️) affiche les liens entre fichiers : glissez les nœuds, zoomez à la"
" molette, double-cliquez pour ouvrir une note.",
"The Backlinks panel lists every note pointing to the open file. The Graph view (🕸️"
" button) shows links between files: drag nodes, scroll to zoom, double-click a node to"
" open the note.",
),
"lib_h3_conflicts": ("Conflits de synchronisation", "Sync conflicts"),
"lib_conflicts": (
"Si vous synchronisez le vault avec Syncthing, ObsiGate détecte les fichiers de conflit"
" (copies « sync-conflict ») et propose de les comparer puis résoudre depuis la page"
" dédiée du menu Options.",
"If you sync the vault with Syncthing, ObsiGate detects conflict files"
" (\"sync-conflict\" copies) and offers to compare then resolve them from a dedicated"
" page in the Options menu.",
),
"lib_h3_attach": ("Fichiers joints & médias", "Attachments & media"),
"lib_attach": (
"Les images <code>![[image.png]]</code>, pièces jointes et médias (audio, vidéo, PDF"
" intégrés) dans les notes sont rendus dans le viewer et indexés pour la recherche ; le"
" bouton « Rescan attachments » de la configuration recrée l'index des pièces jointes.",
"Inline <code>![[image.png]]</code> images, attachments and media (audio, video, embedded"
" PDFs) are rendered in the viewer and indexed for search; the \"Rescan attachments\""
" button in Configuration rebuilds the attachment index.",
),
# -- Section Hors-ligne -----------------------------------------------------------
"off_pwa": (
"ObsiGate est une PWA : installez-la (icône d'installation de la barre d'adresse) pour"
" l'ouvrir comme une application. Le service worker met en cache l'interface et vos"
" derniers documents consultés.",
"ObsiGate is a PWA: install it (install icon in the address bar) to open it like an app."
" The service worker caches the UI and your recently viewed documents.",
),
"off_edit": (
"Hors-ligne, vous pouvez lire les documents en cache et même les éditer : les"
" modifications sont mises en file d'attente dans IndexedDB.",
"Offline you can read cached documents and even edit them: changes are queued in"
" IndexedDB.",
),
"off_sync": (
"Au retour en ligne, la file se rejoue automatiquement (badge de synchronisation dans"
" l'en-tête). Si la version serveur a divergé entre-temps, le fichier est marqué en"
" conflit et la version serveur est préservée en backup.",
"When back online the queue replays automatically (sync badge in the header). If the"
" server version diverged meanwhile, the file is flagged as conflict and the server copy"
" is kept as a backup.",
),
"off_watch": (
"Les modifications externes (Obsidian sur disque) sont détectées par le watcher : la vue"
" se recharge sans perte de position, ou signale « modifié en externe » pendant une"
" édition.",
"External changes (Obsidian on disk) are detected by the watcher: the view reloads"
" without losing your position, or flags \"modified externally\" during an edit.",
),
# -- Section Collaboration ----------------------------------------------------------
"col_intro": (
"Ouvrez un document en mode Édition : plusieurs personnes peuvent travailler"
" simultanément sur le même fichier via un WebSocket Yjs (CRDT). Les modifications"
" fusionnent sans verrou.",
"Open a document in Edit mode: several people can work on the same file simultaneously"
" over a Yjs (CRDT) WebSocket. Changes merge without locks.",
),
"col_cursors": (
"Les curseurs et sélections des collaborateurs apparaissent avec une couleur et un nom"
" par personne (awareness).",
"Collaborators' cursors and selections appear with a per-person colour and name"
" (awareness).",
),
"col_save": (
"La fusion est persistée côté serveur après 2 s d'inactivité ; chaque écriture crée un"
" backup horodaté avant application.",
"The merge is persisted server-side after 2 s of idle; every write creates a timestamped"
" backup before applying.",
),
"col_perm": (
"Accès limité aux utilisateurs authentifiés disposant de la permission sur la vault.",
"Limited to authenticated users with permission on the vault.",
),
# -- Section Desktop ------------------------------------------------------------------
"des_get": (
"L'application desktop ObsiGate (Tauri) embarque le serveur Python : aucune installation"
" de Docker nécessaire. Elle se télécharge sur la page des Releases du dépôt et se met à"
" jour automatiquement (updater signé).",
"The ObsiGate desktop app (Tauri) embeds the Python server: no Docker install needed."
" Download it from the repository's Releases page; it auto-updates (signed updater).",
),
"des_wizard": (
"Au premier lancement, un assistant demande le dossier de vos vaults (ou crée un vault de"
" démonstration). Chaque document peut être détaché en fenêtre native séparée.",
"On first launch a wizard asks for your vaults folder (or creates a demo vault). Any"
" document can be detached into its own native window.",
),
"des_data": (
"Les données desktop restent dans le répertoire applicatif ; les vaults pointent sur vos"
" dossiers existants. Toutes les fonctionnalités web (recherche, IA, partage) sont"
" disponibles.",
"Desktop data stays in the app directory; vaults point at your existing folders. Every web"
" feature (search, AI, sharing) is available.",
),
"des_native": (
"Menu système natif, raccourci global optionnel pour afficher/masquer la fenêtre et"
" jumplist des vaults récents.",
"Native system menu, optional global show/hide shortcut and a recents vault jumplist.",
),
# -- Section API ------------------------------------------------------------------------
"api_intro": (
"ObsiGate expose une API REST couvrant toute l'application (vaults, fichiers, recherche,"
" backups, export, IA, partage, admin), documentée en OpenAPI 3.1 :",
"ObsiGate exposes a REST API covering the whole application (vaults, files, search,"
" backups, export, AI, sharing, admin), documented in OpenAPI 3.1:",
),
"api_docs_url": (
"<code>/docs</code> — interface Swagger UI pour essayer les requêtes en direct.",
"<code>/docs</code> — Swagger UI to try requests live.",
),
"api_redoc": (
"<code>/redoc</code> — référence alternative plus compacte.",
"<code>/redoc</code> — compact alternative reference.",
),
"api_landing": (
"<code>/api</code> — page de garde regroupant les endpoints par catégorie.",
"<code>/api</code> — landing page grouping endpoints by category.",
),
"api_schema": (
"<code>/openapi.json</code> — le schéma machine, à importer dans Postman ou Insomnia.",
"<code>/openapi.json</code> — the machine schema, import into Postman or Insomnia.",
),
"api_h3_auth": ("Authentification", "Authentication"),
"api_auth": (
"Connectez-vous via <code>POST /api/auth/login</code> pour obtenir un token Bearer (le"
" même jeton est accepté en cookie HttpOnly, ce qui permet aux clients navigateur"
' d\'utiliser <code>credentials: "include"</code>). Toutes les routes'
" <code>/api/*</code> exigent ce jeton sauf mention contraire.",
"Log in via <code>POST /api/auth/login</code> to get a Bearer token (the same token is"
" accepted as an HttpOnly cookie, so browser clients can use"
' <code>credentials: "include"</code>). All <code>/api/*</code> routes require it unless'
" documented otherwise.",
),
"api_h3_mcp": ("Serveur MCP", "MCP server"),
"api_mcp": (
"Les outils de l'assistant IA (lire, lister, chercher, ouvrir, écrire…) sont exposés à"
" tout client MCP (Claude Desktop, Cursor, Cline…) sur"
" <code>https://votre-instance/mcp</code> avec un token d'API. Configuration et exemples :"
" <code>docs/MCP_GUIDE.md</code>.",
"The assistant's tools (read, list, search, open, write…) are exposed to any MCP client"
" (Claude Desktop, Cursor, Cline…) at <code>https://your-instance/mcp</code> with an API"
" token. Setup and examples: <code>docs/MCP_GUIDE.md</code>.",
),
"api_h3_autom": ("Automatisation", "Automation"),
"api_autom": (
"Pour automatiser depuis l'extérieur : <code>GET /api/search?q=…</code> et"
" <code>GET /api/file/{vault}?path=…</code> permettent d'indexer ou relire vos notes dans"
" un autre outil ; les webhooks sortants (section 🪝) évitent le polling.",
"To automate from outside: <code>GET /api/search?q=…</code> and"
" <code>GET /api/file/{vault}?path=…</code> let another tool index or re-read your notes;"
" outgoing webhooks (🪝 section) avoid polling.",
),
# -- Section Multilingue -------------------------------------------------------------------
"lng_how": (
"L'interface est intégralement bilingue français / anglais. Réglages → Profil → Langue :"
" le choix est enregistré sur votre compte et vous suit sur tous les appareils.",
"The interface is fully bilingual FR/EN. Settings → Profile → Language: the choice is"
" stored on your account and follows you across devices.",
),
"lng_scope": (
"Tout est traduit : menus, messages, notifications, et le présent guide. Les réponses de"
" l'assistant IA suivent la langue de vos documents.",
"Everything is translated: menus, messages, notifications, and this guide. AI assistant"
" answers follow the language of your documents.",
),
"lng_export": (
"Les boutons Markdown / PDF de ce guide téléchargent la version dans votre langue.",
"This guide's Markdown / PDF buttons download the version in your language.",
),
# -- Compléments dans sections existantes ---------------------------------------------------
"h3_semantic": ("Recherche sémantique (hybride)", "Semantic search (hybrid)"),
"sem_p1": (
"Activez le bouton « S » de la barre de recherche (ou Alt-S) pour combiner TF-IDF et"
" similarité vectorielle (fusion RRF) : les concepts approchants (« velours » trouve"
" « tissu doux ») remontent mieux.",
"Toggle the \"S\" button in the search bar (or Alt-S) to combine TF-IDF with vector"
" similarity (RRF fusion): near concepts (\"velvet\" finds \"soft fabric\") surface"
" higher.",
),
"sem_p2": (
"Le moteur d'embeddings (modèle multilingue) est optionnel : sans lui, un repli par hash"
" conserve une recherche hybride fonctionnelle. Les vecteurs sont recalculés à chaque"
" indexation du vault.",
"The embedding engine (multilingual model) is optional: without it a hash fallback keeps"
" hybrid search working. Vectors are recomputed on each vault reindex.",
),
"h3_push": ("Notifications web (push)", "Web notifications (push)"),
"push_p1": (
"Autorisez les notifications (bouton 🔔 de l'en-tête) pour être averti des fins de"
" synchronisation hors-ligne et des événements importants. La gestion des abonnements est"
" dans les Configurations.",
"Grant notification permission (🔔 button in the header) to be alerted of offline-sync"
" completions and important events. Subscription management lives in Configuration.",
),
"push_p2": (
"Basée sur la Web Push API (clés VAPID) ; fonctionne sur desktop et PWA mobile, sans"
" service tiers : le serveur émet directement vers les endpoints push des navigateurs.",
"Built on the Web Push API (VAPID keys); works on desktop and mobile PWA with no"
" third-party service: the server sends directly to browser push endpoints.",
),
"h3_panes": ("Vue multi-panneaux (split view)", "Multi-pane split view"),
"panes_p": (
"Le bouton « Diviser » de la barre d'actions ouvre le document dans un panneau jumeau ;"
" empilez plusieurs panneaux pour comparer deux notes ou lire et éditer en parallèle. Les"
" largeurs se règlent au bord des panneaux et sont mémorisées.",
"The \"Split\" button in the action bar opens the document in a twin pane; stack several"
" panes to compare two notes or read and edit side by side. Pane widths drag on the"
" border and are remembered.",
),
"h3_dupe": ("Anti-doublons à l'upload", "Duplicate-proof uploads"),
"dupe_p": (
"L'upload en masse (glisser-déposer un dossier sur la sidebar) compare chaque fichier au"
" contenu existant : un fichier déjà présent est ignoré plutôt que dupliqué avec un"
" suffixe « (1) ». Utile pour restaurer un vault sans créer de doublons.",
"Bulk upload (drag a folder onto the sidebar) compares each file with existing content: an"
" already-present file is skipped rather than duplicated with a \"(1)\" suffix. Handy"
" when restoring a vault.",
),
"h3_pdf": ("Export PDF", "PDF export"),
"pdf_p": (
"Le bouton « PDF » d'un document le rend avec le même moteur que la vue (WeasyPrint) :"
" titres, tableaux, listes et code sont conservés. Depuis un lien public, la route"
" <code>/s/{token}/pdf</code> produit le même PDF.",
"A document's \"PDF\" button renders it with the same engine as the viewer (WeasyPrint):"
" headings, tables, lists and code are preserved. From a public link, the"
" <code>/s/{token}/pdf</code> route produces the same PDF.",
),
"h3_exports": ("Export HTML / ePub / ZIP", "HTML / ePub / ZIP export"),
"exp_p": (
"Le menu « Exporter » propose trois formats : HTML autonome (fichier unique, images"
" incluses), ePub pour les liseuses et, pour un dossier, un bundle Markdown en ZIP —"
" liens et ressources résolus pendant l'export.",
"The \"Export\" menu offers three formats: standalone HTML (single file, images inlined),"
" ePub for e-readers and, for a folder, a Markdown ZIP bundle — links and resources"
" resolved during export.",
),
"h3_mfa": ("MFA : TOTP, WebAuthn, codes de secours", "MFA: TOTP, WebAuthn, recovery codes"),
"mfa_p": (
"Activez la double authentification dans Réglages → Profil : applications TOTP (Authy,"
" Aegis…), clés de sécurité et passkeys (WebAuthn, y compris Windows Hello) et 10 codes"
" de secours à conserver hors ligne. Chaque méthode s'active et se désactive"
" indépendamment.",
"Enable two-factor auth in Settings → Profile: TOTP apps (Authy, Aegis…), security keys"
" and passkeys (WebAuthn, including Windows Hello) and 10 recovery codes to keep offline."
" Each method can be enabled and disabled independently.",
),
"h3_admin": ("Tableau de bord administrateur", "Admin dashboard"),
"admin_p": (
"Le rôle admin ouvre une page dédiée <code>/admin.html</code> (bouton du menu Options) :"
" statut du serveur en direct, utilisateurs, vaults, sessions actives et journal d'audit."
" Le CRUD utilisateurs est aussi disponible dans les Configurations.",
"The admin role unlocks a dedicated <code>/admin.html</code> page (Options menu button):"
" live server status, users, vaults, active sessions and the audit log. User CRUD also"
" lives in Configuration.",
),
# -- Boutons de téléchargement ---------------------------------------------------------------
"dl_md_title": ("Télécharger ce guide en Markdown", "Download this guide as Markdown"),
"dl_pdf_title": ("Télécharger ce guide en PDF", "Download this guide as PDF"),
# -- Export MD/PDF (côté serveur) -------------------------------------------------------------
"export_title": ("Guide d'utilisation ObsiGate", "ObsiGate User Guide"),
"export_footer": (
"Généré depuis ObsiGate {version} — {date}. Ce document est la copie du guide intégré ;"
" la version la plus récente est toujours dans l'application.",
"Generated from ObsiGate {version} — {date}. This document mirrors the in-app guide; the"
" latest version always lives in the application.",
),
}
# ---------------------------------------------------------------------------
# Diagramme Mermaid de la section Architecture (également utilisé par l'export)
# ---------------------------------------------------------------------------
ARCH_MERMAID = """flowchart TB
subgraph client["Clients"]
UI["SPA vanilla JS\\n(frontend/js)"]
PWA["PWA hors-ligne\\n(service worker + IndexedDB)"]
DESK["App desktop Tauri\\n(fenêtre native)"]
end
subgraph server["Serveur FastAPI (Python 3.11)"]
API["REST /api\\nJWT + Argon2id"]
IDX["Index recherche\\nTF-IDF + embeddings"]
FS["Accès fichiers\\nwatchdog + safe paths"]
PDF["Rendu markdown\\nmistune + WeasyPrint"]
AI["Assistant IA\\nproviders + outils"]
MCP["Serveur MCP\\n/mcp (HTTP)"]
WS["WebSocket\\ncollab Yjs + SSE"]
WH["Webhooks\\nHMAC-SHA256"]
end
subgraph data["Données"]
V1["Vault 1 (dossier)"]
V2["Vault 2 (dossier)"]
CFG["data/*.json\\nconfig, users, audit"]
BK[".obsigate-backup/\\nbackups horodatés"]
end
UI -- HTTP --> API
PWA -- "cache + queue" --> API
DESK -- embarqué --> API
API --> IDX
API --> FS
API --> PDF
API --> AI
MCP --> AI
WS --> FS
FS --> V1
FS --> V2
IDX --> V1
IDX --> V2
BK --> V1
API --> CFG
API -- événements --> WH"""
# ---------------------------------------------------------------------------
# Constructeurs de HTML (FR inline == CONTENT[key][0] garanti)
# ---------------------------------------------------------------------------
def section_html(title_key: str, sec_id: str, body: str) -> str:
"""Nouvelle <section> complète avec son h2 data-i18n."""
return (
' <section class="help-section" id="%s">\n'
' <h2 data-i18n="guide105.%s">%s</h2>\n'
"%s"
" </section>\n"
"\n" % (sec_id, title_key, CONTENT[title_key][0], body)
)
def _li(key: str) -> str:
return ' <li data-i18n="guide105.%s">%s</li>\n' % (key, CONTENT[key][0])
def _bullets(keys: list) -> str:
return " <ul>\n" + "".join(_li(k) for k in keys) + " </ul>\n"
def _p(key: str) -> str:
return ' <p data-i18n="guide105.%s">%s</p>\n' % (key, CONTENT[key][0])
def _h3(key: str) -> str:
return ' <h3 data-i18n="guide105.%s">%s</h3>\n' % (key, CONTENT[key][0])
def _pair(label_key: str, text_key: str) -> str:
"""<li><strong>Label</strong><span> — texte</span></li> (deux clés i18n)."""
return (
" <li>\n"
' <strong data-i18n="guide105.%s">%s</strong>'
'<span data-i18n="guide105.%s">%s</span>\n'
" </li>\n"
% (label_key, CONTENT[label_key][0], text_key, CONTENT[text_key][0])
)
def _h3p(h3_key: str, *p_keys: str) -> str:
return _h3(h3_key) + "".join(_p(k) for k in p_keys)
# ---------------------------------------------------------------------------
# Les huit nouvelles sections
# ---------------------------------------------------------------------------
SECTION_ARCHITECTURE = section_html(
"nav_architecture",
"help-architecture",
_p("arch_intro")
+ ' <pre class="mermaid-code"><code class="language-mermaid">%s</code></pre>\n' % ARCH_MERMAID
+ _p("arch_diagram_note")
+ _h3("arch_h3_layers")
+ " <ul>\n"
+ _pair("arch_lbl_fe", "arch_fe")
+ _pair("arch_lbl_be", "arch_be")
+ _pair("arch_lbl_realtime", "arch_rt")
+ _pair("arch_lbl_ai", "arch_ai")
+ _pair("arch_lbl_data", "arch_data")
+ _pair("arch_lbl_deploy", "arch_deploy")
+ " </ul>\n"
+ _h3p("arch_h3_flux", "arch_flux"),
)
SECTION_DIAGRAMS = section_html(
"nav_diagrams",
"help-diagrams",
_p("dia_intro")
+ _bullets(["dia_zoom", "dia_fs", "dia_copy", "dia_toggle", "dia_theme"])
+ _p("dia_types")
+ _p("dia_excalidraw_ref"),
)
SECTION_LIBRARY = section_html(
"nav_library",
"help-library",
_h3p("lib_h3_bookmarks", "lib_bookmarks")
+ _h3p("lib_h3_saved", "lib_saved")
+ _h3p("lib_h3_backlinks", "lib_backlinks")
+ _h3p("lib_h3_conflicts", "lib_conflicts")
+ _h3p("lib_h3_attach", "lib_attach"),
)
SECTION_OFFLINE = section_html("nav_offline", "help-offline", _bullets(["off_pwa", "off_edit", "off_sync", "off_watch"]))
SECTION_COLLAB = section_html("nav_collab", "help-collab", _bullets(["col_intro", "col_cursors", "col_save", "col_perm"]))
SECTION_DESKTOP = section_html("nav_desktop", "help-desktop", _bullets(["des_get", "des_wizard", "des_data", "des_native"]))
SECTION_API = section_html(
"nav_api",
"help-api",
_p("api_intro")
+ _bullets(["api_docs_url", "api_redoc", "api_landing", "api_schema"])
+ _h3p("api_h3_auth", "api_auth")
+ _h3p("api_h3_mcp", "api_mcp")
+ _h3p("api_h3_autom", "api_autom"),
)
SECTION_LANG = section_html("nav_languages", "help-languages", _bullets(["lng_how", "lng_scope", "lng_export"]))
# (id de section, HTML complet, id de la section AVANT laquelle insérer)
NEW_SECTIONS: list[tuple[str, str, str]] = [
("help-architecture", SECTION_ARCHITECTURE, "help-interface"),
("help-diagrams", SECTION_DIAGRAMS, "help-edition"),
("help-library", SECTION_LIBRARY, "help-graphe"),
("help-offline", SECTION_OFFLINE, "help-partage"),
("help-collab", SECTION_COLLAB, "help-partage"),
("help-desktop", SECTION_DESKTOP, "help-partage"),
("help-api", SECTION_API, "help-plugins"),
("help-languages", SECTION_LANG, "help-plugins"),
]
# Compléments insérés À LA FIN de sections existantes (avant leur </section>) :
# section id -> bloc HTML
EXTRA_BLOCKS: list[tuple[str, str]] = [
("help-interface", _h3p("h3_push", "push_p1", "push_p2")),
("help-recherche", _h3p("h3_semantic", "sem_p1", "sem_p2")),
("help-fichiers", _h3p("h3_pdf", "pdf_p") + _h3p("h3_exports", "exp_p") + _h3p("h3_dupe", "dupe_p")),
("help-personnalisation", _h3p("h3_panes", "panes_p")),
("help-securite", _h3p("h3_mfa", "mfa_p") + _h3p("h3_admin", "admin_p")),
]
# Entrées TOC à insérer AVANT l'entrée dont l'href est la 3e valeur.
TOC_INSERT_BEFORE: list[tuple[str, str, str]] = [
("nav_architecture", "#help-architecture", "#help-interface"),
("nav_diagrams", "#help-diagrams", "#help-edition"),
("nav_library", "#help-library", "#help-graphe"),
("nav_offline", "#help-offline", "#help-partage"),
("nav_collab", "#help-collab", "#help-partage"),
("nav_desktop", "#help-desktop", "#help-partage"),
("nav_api", "#help-api", "#help-plugins"),
("nav_languages", "#help-languages", "#help-plugins"),
]
# Section « Édition mobile » dédiée (fix BUG-067) : créée par le script
# d'insertion après la section help-edition.
MOBILE_SECTION_TITLE_KEY = "help.nav_mobile_editor"
MOBILE_SECTION_TITLE_FR = "📱 Édition mobile"
+124
View File
@@ -0,0 +1,124 @@
# -*- coding: utf-8 -*-
"""Insère le nouveau contenu guide #105 dans frontend/index.html.
- 8 nouvelles sections + entrées de TOC (guide_content.py)
- compléments h3 dans 5 sections existantes
- BUG-067 : le bloc « Édition mobile » de help-edition devient la section
dédiée help-mobile-editor (ancre morte → ancre vivante)
- retire l'attribut data-i18n-placeholder dupliqué sur #help-nav-search
Idempotent : refuse de tourner deux fois (détecte guide105.* déjà présent).
Préserve les fins de ligne CRLF de index.html.
"""
import re
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
from guide_content import ( # noqa: E402
CONTENT,
EXTRA_BLOCKS,
NEW_SECTIONS,
TOC_INSERT_BEFORE,
)
HTML = Path("C:/dev/git/python/ObsiGate/frontend/index.html")
_CRLF = False
def to_crlf(s: str) -> str:
return s.replace("\n", "\r\n") if _CRLF else s
def main() -> int:
with open(HTML, encoding="utf-8", newline="") as f:
raw = f.read()
global _CRLF
_CRLF = "\r\n" in raw
if _CRLF:
raw = raw.replace("\r\n", "\n") # normaliser ; régénéré à l'écriture
if "guide105." in raw:
print("already inserted — abort")
return 1
# Localise le guide (après la modale de config) : on opère uniquement dans
# la fenêtre help-modal pour ne pas toucher le TOC #cfg-* de la config.
guide_start = raw.index('<div class="editor-modal" id="help-modal">')
head, guide = raw[:guide_start], raw[guide_start:]
# ── Fix BUG-067 : section mobile dédiée ────────────────────────────────
m_h3 = guide.index('<h3 data-i18n="help.mobile_editor_title">')
# le bloc va jusqu'à la fin de la section help-edition
m_sec_end = guide.index("</section>", m_h3)
mobile_block = guide[m_h3:m_sec_end]
guide = guide[:m_h3] + guide[m_sec_end:]
# h3 -> h2, et on emballe en section dédiée
mobile_h2 = mobile_block.replace('<h3 data-i18n="help.mobile_editor_title">',
'<h2 data-i18n="help.mobile_editor_title">', 1)
mobile_h2 = mobile_h2.replace("</h3>", "</h2>", 1)
mobile_section = (
' <section class="help-section" id="help-mobile-editor">\n'
+ mobile_h2.rstrip()
+ "\n </section>\n\n"
)
# insérer après help-edition (donc avant help-graphe)
anchor = guide.index('<section class="help-section" id="help-graphe">')
guide = guide[:anchor] + mobile_section + guide[anchor:]
# ── Compléments h3 dans sections existantes ────────────────────────────
for sec_id, block in EXTRA_BLOCKS:
pat = 'id="%s"' % sec_id
a = guide.index(pat)
b = guide.index("</section>", a)
guide = guide[:b] + to_crlf(block) + guide[b:]
# ── Nouvelles sections ─────────────────────────────────────────────────
for sec_id, html, before_id in NEW_SECTIONS:
anchor = guide.index('<section class="help-section" id="%s">' % before_id)
guide = guide[:anchor] + to_crlf(html) + guide[anchor:]
# ── Entrées TOC ────────────────────────────────────────────────────────
for key, href, before_href in TOC_INSERT_BEFORE:
label = CONTENT[key][0]
entry = to_crlf(
" <li>\n"
' <a href="%s" class="help-nav-link" data-i18n="guide105.%s">%s</a>\n'
" </li>\n" % (href, key, label)
)
needle = 'href="%s"' % before_href
# l'entrée <li> qui contient ce href
i = guide.index(needle)
li_start = guide.rindex("<li>", 0, i)
guide = guide[:li_start] + entry + guide[li_start:]
# ── Anchor #help-ia mort (nav) → #help-ai (id de section réel) ─────────
guide = guide.replace('href="#help-ia"', 'href="#help-ai"')
# ── Attribut dupliqué sur #help-nav-search ─────────────────────────────
guide = guide.replace(
' data-i18n-placeholder="help.search_placeholder" data-i18n-placeholder="help.search_placeholder"',
' data-i18n-placeholder="help.search_placeholder"',
1,
)
out = head + guide
if _CRLF:
out = out.replace("\n", "\r\n")
with open(HTML, "w", encoding="utf-8", newline="") as f:
f.write(out)
# ── Vérifications structurelles ────────────────────────────────────────
d = HTML.read_text(encoding="utf-8")
opens, closes = len(re.findall(r"<section[\s>]", d)), d.count("</section>")
print("section balance:", opens, closes)
hrefs = set(re.findall(r'href="#(help-[a-z-]+)"', d))
ids = set(re.findall(r'id="(help-[a-z-]+)"', d))
missing = sorted(hrefs - ids)
print("dead anchors:", missing or "none")
return 0 if not missing else 2
if __name__ == "__main__":
raise SystemExit(main())
+44
View File
@@ -0,0 +1,44 @@
# -*- coding: utf-8 -*-
"""Injecte les clés guide105.* de scripts/guide_content.py dans les locales.
Insertion TEXTUELLE avant la dernière accolade (préserve le formatage exact
des fichiers existants). Idempotent : remplace un bloc guide105.* déjà
présent. Écriture LF (comme les blobs git).
"""
import json
import re
import sys
from pathlib import Path
ROOT = Path("C:/dev/git/python/ObsiGate")
sys.path.insert(0, str(ROOT / "scripts"))
from guide_content import CONTENT # noqa: E402
KEY_RE = re.compile(r'^\s*"guide105\.[a-z0-9_]+"\s*:', re.M)
def merge(locale_file: Path, idx: int) -> None:
raw = locale_file.read_text(encoding="utf-8")
# retire un éventuel ancien bloc (idempotence)
raw = "".join(l for l in raw.splitlines(keepends=True) if not KEY_RE.match(l))
data = json.loads(raw)
entries = [' "guide105.%s": %s' % (k, json.dumps(v[idx], ensure_ascii=False)) for k, v in CONTENT.items()]
block = ",\n".join(entries) + "\n"
i = raw.rstrip().rfind("}")
head = raw[:i].rstrip() # dernière clé existante (sans virgule finale)
new = head + ",\n" + block + "}\n"
parsed = json.loads(new) # doit rester valide
assert len(parsed) == len(data) + len(CONTENT)
locale_file.write_bytes(new.encode("utf-8"))
print(locale_file.name, "->", len(parsed), "keys (+%d guide105)" % len(CONTENT))
merge(ROOT / "frontend/locales/fr.json", 0)
merge(ROOT / "frontend/locales/en.json", 1)
en = json.loads((ROOT / "frontend/locales/en.json").read_bytes().decode("utf-8"))
fr = json.loads((ROOT / "frontend/locales/fr.json").read_bytes().decode("utf-8"))
assert set(en) == set(fr), sorted(set(en) ^ set(fr))[:5]
print("parity OK:", len(en), "keys")
+49
View File
@@ -0,0 +1,49 @@
// Pré-rend les diagrammes Mermaid du guide (#105 PDF) en PNG.
// Usage: node scripts/render_guide_diagram.mjs
// Lit le(s) code(s) Mermaid via --input JSON {sha: code} et écrit
// backend/assets/guide_diagrams/<sha>.png (rendu chromium + mermaid v11 CDN,
// scale 2, fond blanc).
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
const { chromium } = require('playwright');
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, '..');
const OUT_DIR = path.join(ROOT, 'backend', 'assets', 'guide_diagrams');
(async () => {
const jobs = JSON.parse(fs.readFileSync(process.argv[2], 'utf8')); // {sha: code}
fs.mkdirSync(OUT_DIR, { recursive: true });
const browser = await chromium.launch();
const page = await browser.newPage({ viewport: { width: 1800, height: 1400 }, deviceScaleFactor: 2 });
await page.goto('about:blank');
await page.addScriptTag({ url: 'https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.min.js' });
await page.waitForFunction(() => typeof window.mermaid !== 'undefined');
for (const [sha, code] of Object.entries(jobs)) {
const out = await page.evaluate(async (src) => {
window.mermaid.initialize({ startOnLoad: false, theme: 'default', securityLevel: 'loose', fontFamily: 'DejaVu Sans, Arial, sans-serif' });
try {
const { svg } = await window.mermaid.render('d_' + Math.random().toString(36).slice(2), src);
const box = document.createElement('div');
box.innerHTML = svg;
box.style.background = 'white';
document.body.replaceChildren(box);
const svgEl = box.querySelector('svg');
if (!svgEl) return { err: 'no svg' };
svgEl.style.maxWidth = 'none';
const r = svgEl.getBoundingClientRect();
return { w: Math.min(Math.ceil(r.width), 2000), h: Math.min(Math.ceil(r.height), 2600), ok: true };
} catch (e) {
return { err: String(e).slice(0, 300) };
}
}, code);
if (out.err) { console.error(sha, 'RENDER ERROR', out.err); process.exitCode = 1; continue; }
const file = path.join(OUT_DIR, sha + '.png');
await page.screenshot({ path: file, clip: { x: 0, y: 0, width: out.w, height: out.h } });
console.log(sha, '->', file, out.w + 'x' + out.h);
}
await browser.close();
})();
+87
View File
@@ -0,0 +1,87 @@
{
"type": "excalidraw",
"version": 2,
"elements": [
{
"id": "app-rect-1",
"type": "rectangle",
"x": 100,
"y": 100,
"width": 300,
"height": 150,
"angle": 0,
"strokeColor": "#1e1e1e",
"backgroundColor": "transparent",
"fillStyle": "solid",
"strokeWidth": 2,
"strokeStyle": "solid",
"roughness": 1,
"opacity": 100,
"groupIds": [],
"frameId": null,
"index": "a0",
"roundness": { "type": 3 },
"seed": 975148614,
"version": 73,
"versionNonce": 1826427930,
"isDeleted": false,
"boundElements": [],
"updated": 1789695570496,
"created": 1789695569357,
"link": null,
"locked": false
}
],
"appState": {
"showWelcomeScreen": false,
"theme": "dark",
"collaborators": {},
"currentChartType": "bar",
"currentItemBackgroundColor": "transparent",
"currentItemEndArrowhead": "arrow",
"currentItemFillStyle": "solid",
"currentItemFontFamily": 5,
"currentItemFontSize": 20,
"currentItemOpacity": 100,
"currentItemRoughness": 1,
"currentItemStartArrowhead": null,
"currentItemStrokeColor": "#1e1e1e",
"currentItemRoundness": "round",
"currentItemArrowType": "round",
"currentItemStrokeStyle": "solid",
"currentItemStrokeWidth": 2,
"currentItemTextAlign": "left",
"cursorButton": "up",
"activeTool": {
"type": "selection",
"customType": null,
"locked": false,
"lastActiveTool": null
},
"penMode": false,
"penDetected": false,
"errorMessage": null,
"exportBackground": true,
"exportScale": 1,
"exportEmbedScene": false,
"exportWithDarkMode": false,
"gridSize": 20,
"gridStep": 5,
"gridModeEnabled": false,
"isBindingEnabled": true,
"isLoading": false,
"isResizing": false,
"isRotating": false,
"name": "App Export Fixture",
"previousSelectedElementIds": {},
"scrollX": 0,
"scrollY": 0,
"selectedElementIds": {},
"selectedGroupIds": {},
"viewBackgroundColor": "#ffffff",
"zenModeEnabled": false,
"zoom": { "value": 1 },
"viewModeEnabled": false
},
"files": {}
}
+130
View File
@@ -0,0 +1,130 @@
%PDF-1.3
%“Œ‹ž ReportLab Generated PDF document (opensource)
1 0 obj
<<
/F1 2 0 R
>>
endobj
2 0 obj
<<
/BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font
>>
endobj
3 0 obj
<<
/Contents 13 0 R /MediaBox [ 0 0 612 792 ] /Parent 12 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
4 0 obj
<<
/Contents 14 0 R /MediaBox [ 0 0 612 792 ] /Parent 12 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
5 0 obj
<<
/Contents 15 0 R /MediaBox [ 0 0 612 792 ] /Parent 12 0 R /Resources <<
/Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ]
>> /Rotate 0 /Trans <<
>>
/Type /Page
>>
endobj
6 0 obj
<<
/Outlines 8 0 R /PageMode /UseNone /Pages 12 0 R /Type /Catalog
>>
endobj
7 0 obj
<<
/Author (anonymous) /CreationDate (D:20260917204040-04'00') /Creator (anonymous) /Keywords () /ModDate (D:20260917204040-04'00') /Producer (ReportLab PDF Library - \(opensource\))
/Subject (unspecified) /Title (untitled) /Trapped /False
>>
endobj
8 0 obj
<<
/Count 3 /First 9 0 R /Last 11 0 R /Type /Outlines
>>
endobj
9 0 obj
<<
/Dest [ 3 0 R /Fit ] /Next 10 0 R /Parent 8 0 R /Title (Page One)
>>
endobj
10 0 obj
<<
/Dest [ 4 0 R /Fit ] /Next 11 0 R /Parent 8 0 R /Prev 9 0 R /Title (Page Two)
>>
endobj
11 0 obj
<<
/Dest [ 5 0 R /Fit ] /Parent 8 0 R /Prev 10 0 R /Title (Page Three)
>>
endobj
12 0 obj
<<
/Count 3 /Kids [ 3 0 R 4 0 R 5 0 R ] /Type /Pages
>>
endobj
13 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 122
>>
stream
Gap@Db6gL2'Lh3!@LZ0U8'7>U;'tH2cm;<+UO9dKg:K5pXY%ILno7bT=/&<K"<EU]9[SSm*P9LuAr1A`Y./=ub]S+JZn3-Xqn.)>^t)3an^%I4h`&g_Y!<hT~>endstream
endobj
14 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 124
>>
stream
GapQh0E=F,0U\H3T\pNYT^QKk?tc>IP,;W#U1^23ihPEM_?CW4KISi<![7`#OB_qus.nXJpV`4oKb/`HKs]']P1$(("^Qh6`:R"4,>ElR/;4WeODY4S!3T'6Jc~>endstream
endobj
15 0 obj
<<
/Filter [ /ASCII85Decode /FlateDecode ] /Length 124
>>
stream
GapQh0E=F,0U\H3T\pNYT^QKk?tc>IP,;W#U1^23ihPEM_?CW4KISi<![7`#OB_qus.nXJpV`4oKb/`HKs]']P1$(("^Qh6`:R"4@nhZ=/;4WeODY4S!3TQDK)~>endstream
endobj
xref
0 16
0000000000 65535 f
0000000061 00000 n
0000000092 00000 n
0000000199 00000 n
0000000394 00000 n
0000000589 00000 n
0000000784 00000 n
0000000869 00000 n
0000001130 00000 n
0000001202 00000 n
0000001289 00000 n
0000001389 00000 n
0000001479 00000 n
0000001551 00000 n
0000001764 00000 n
0000001979 00000 n
trailer
<<
/ID
[<6132df6a3beacba675b566627d60fb2e><6132df6a3beacba675b566627d60fb2e>]
% ReportLab generated PDF document -- digest (opensource)
/Info 7 0 R
/Root 6 0 R
/Size 16
>>
startxref
2194
%%EOF
+35
View File
@@ -68,6 +68,41 @@ test.describe('Excalidraw — .excalidraw file support', () => {
await expect(canvas).toBeVisible({ timeout: 20000 });
});
test('opens an Excalidraw-app export (collaborators as JSON object) — canvas renders', async ({ page }) => {
// Regression: files exported by the Excalidraw app / Obsidian plugin store
// `appState.collaborators` as a plain `{}` (a Map serialized to JSON).
// Passing it back to `initialData` made Excalidraw 0.18 crash with
// "e.appState.collaborators.forEach is not a function" and left the canvas
// blank (0 <canvas> in the iframe).
await openFile(page, 'TestVault', 'diagram-app-export.excalidraw');
await waitForExcalidrawIframe(page);
const frame = page.locator('.content-area iframe').contentFrame();
const canvas = frame.locator('canvas').first();
await expect(canvas).toBeVisible({ timeout: 20000 });
});
test('loads Excalidraw stylesheet — canvas is sized to the viewport (not the 2^25 cap)', async ({ page }) => {
// Regression: without `@excalidraw/excalidraw`'s stylesheet, `.excalidraw`
// has no fixed height; Excalidraw's ResizeObserver feedback loop then grows
// the canvas to its 2^25 hard cap (33554432px), which the browser cannot
// draw → the scene stays blank even though the data was loaded.
await openFile(page, 'TestVault', 'diagram.excalidraw');
await waitForExcalidrawIframe(page);
const frame = page.locator('.content-area iframe').contentFrame();
const canvas = frame.locator('canvas').first();
await expect(canvas).toBeVisible({ timeout: 20000 });
const dims = await canvas.evaluate((el) => ({ w: el.width, h: el.height }));
expect(dims.h).toBeGreaterThan(100);
expect(dims.h).toBeLessThan(32768);
const wrapH = await frame.locator('.excalidraw').first()
.evaluate((el) => parseFloat(getComputedStyle(el).height));
expect(wrapH).toBeLessThan(32768);
});
test('opens .excalidraw.md (Obsidian plugin format) — decompresses and renders', async ({ page }) => {
await openFile(page, 'TestVault', 'diagram.excalidraw.md');
const iframe = await waitForExcalidrawIframe(page);
+47
View File
@@ -89,4 +89,51 @@ test.describe('PDF viewer — affichage inline (BUG-060)', () => {
// Aucune violation CSP liée à object-src pendant l'ouverture
expect(cspViolations).toEqual([]);
});
});
test.describe('PDF viewer — TOC & plein largeur', () => {
test('les entrées de la TOC rechargent l\'iframe sur la page ciblée (#page=N)', async ({ page }) => {
await login(page);
await openFile(page, 'TestVault', 'sample-pdf-toc.pdf');
const tocLinks = page.locator('#content-area .pdf-toc a[data-page]');
await expect(tocLinks).toHaveCount(3, { timeout: 10000 });
await page.locator('#content-area .pdf-toc a[data-page="3"]').click();
// Le changement de query force un rechargement (un simple changement de
// fragment est ignoré par le lecteur PDF natif), puis #page=3 est appliqué.
await expect(page.locator('#content-area .pdf-iframe')).toHaveAttribute(
'src',
/\/pdf\/stream\?path=.*&_pdfpage=\d+#page=3$/,
{ timeout: 5000 },
);
});
test('le PDF occupe toute la largeur quand la navigation est masquée', async ({ page }) => {
await login(page);
await openFile(page, 'TestVault', 'sample-pdf-toc.pdf');
await expect(page.locator('#content-area .pdf-viewer-container')).toBeVisible({ timeout: 10000 });
// Masquer la barre de navigation (bouton réel).
await page.locator('#sidebar-toggle-btn').click();
await expect(page.locator('#sidebar')).toHaveClass(/hidden/);
const widths = await page.evaluate(() => {
const area = document.getElementById('content-area');
const cs = getComputedStyle(area);
const container = document.querySelector('.pdf-viewer-container');
const contentWidth =
area.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight);
return {
container: container.getBoundingClientRect().width,
contentWidth,
maxWidth: cs.maxWidth,
};
});
// Le plafond de lecture (1200px) ne doit plus s'appliquer au viewer PDF.
expect(widths.maxWidth).toBe('none');
expect(Math.abs(widths.container - widths.contentWidth)).toBeLessThan(2);
});
});
+161
View File
@@ -0,0 +1,161 @@
#!/usr/bin/env node
/**
* ObsiGate — Frontend unit tests for #106 (assistant contextual quick actions).
*
* Covers the pure logic of frontend/js/ai-quick-actions.js:
* - detectContext precedence (selection > code > multi-doc > single-doc >
* directory > general)
* - every preset id resolves to a real action (label + prompt keys exist)
* - i18n completeness: every qa.* key referenced by the catalogue exists in
* BOTH fr.json and en.json (FR/EN contract from AGENTS.md)
*
* Usage: node tests/frontend/ai-quick-actions.test.mjs
*/
import { strict as assert } from "node:assert";
import { readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const ROOT = path.resolve(__dirname, "..", "..");
// Minimal browser shim: i18n.js exposes `window.t = t` at module top-level.
// Strings are not loaded here, so t() falls back to the key — enough for the
// pure-logic contract asserted below (keys existence is checked against the
// real locale JSON files instead).
globalThis.window = globalThis.window || globalThis;
const {
detectContext,
suggestionsFor,
getAction,
contextBadgeKey,
ACTION_CATALOG,
CATEGORIES,
CONTEXT_PRESETS,
} = await import(pathToFileURL(path.join(ROOT, "frontend", "js", "ai-quick-actions.js")).href);
let testCount = 0;
let passCount = 0;
async function test(name, fn) {
testCount++;
try {
await fn();
passCount++;
console.log(` ✓ ${name}`);
} catch (err) {
console.error(` ✗ ${name}\n ${err.message}`);
process.exitCode = 1;
}
}
// ── detectContext precedence ───────────────────────────────────────────────
await test("selection wins over every other context", () => {
assert.equal(detectContext({ mode: "documents", docCount: 1, currentPath: "a.md", hasSelection: true }), "selection");
assert.equal(detectContext({ mode: "documents", docCount: 3, currentPath: "x.py", hasSelection: true }), "selection");
});
await test("code file drives the code context", () => {
assert.equal(detectContext({ mode: "documents", docCount: 1, currentPath: "backend/main.py" }), "code");
assert.equal(detectContext({ mode: "documents", docCount: 2, currentPath: "script.SH" }), "code");
assert.equal(detectContext({ mode: "documents", docCount: 1, currentPath: "app.tsx" }), "code");
});
await test("2+ documents drive the multi_doc context", () => {
assert.equal(detectContext({ mode: "documents", docCount: 2, currentPath: "a.md" }), "multi_doc");
});
await test("one text document drives the single_doc context", () => {
assert.equal(detectContext({ mode: "documents", docCount: 1, currentPath: "note.md" }), "single_doc");
assert.equal(detectContext({ mode: "documents", docCount: 1, currentPath: "plan.txt" }), "single_doc");
assert.equal(detectContext({ mode: "documents", docCount: 1, currentPath: "image.png" }), "single_doc");
});
await test("directory and general fall back correctly", () => {
assert.equal(detectContext({ mode: "directory", docCount: 0 }), "directory");
assert.equal(detectContext({ mode: "general", docCount: 0 }), "general");
assert.equal(detectContext(), "general");
});
// ── presets & catalogue integrity ──────────────────────────────────────────
await test("every context has 3-4 suggested actions, all resolvable", () => {
for (const [ctx, ids] of Object.entries(CONTEXT_PRESETS)) {
assert.ok(ids.length >= 3 && ids.length <= 4, `preset ${ctx} must hold 3-4 actions`);
for (const id of ids) assert.ok(getAction(id), `preset ${ctx}: unknown action id ${id}`);
assert.equal(suggestionsFor(ctx).length, ids.length);
}
});
await test("unknown context falls back to the general preset", () => {
assert.deepEqual(suggestionsFor("nonsense").map((a) => a.id), suggestionsFor("general").map((a) => a.id));
});
await test("catalogue actions have unique ids, a known category, icon and keys", () => {
const catIds = new Set(CATEGORIES.map((c) => c.id));
const seen = new Set();
for (const a of ACTION_CATALOG) {
assert.ok(!seen.has(a.id), `duplicate action id ${a.id}`);
seen.add(a.id);
assert.ok(catIds.has(a.cat), `action ${a.id}: unknown category ${a.cat}`);
assert.ok(a.icon, `action ${a.id}: missing icon`);
assert.ok(a.labelKey && a.promptKey, `action ${a.id}: missing i18n keys`);
}
});
await test("the 4 scenarios of the design table map to the expected actions", () => {
assert.deepEqual(suggestionsFor("single_doc").map((a) => a.id),
["summarize_3", "checklist", "frontmatter", "frontmatter_update"]);
assert.deepEqual(suggestionsFor("multi_doc").map((a) => a.id), ["merge", "compare", "frictions"]);
assert.deepEqual(suggestionsFor("code").map((a) => a.id), ["explain_code", "audit_code", "test_code"]);
assert.deepEqual(suggestionsFor("selection").map((a) => a.id), ["concise", "fix_style", "explain_selection"]);
});
await test("frontmatter actions are agent-mode (they mutate the document)", () => {
assert.equal(getAction("frontmatter").agent, true);
assert.equal(getAction("frontmatter_update").agent, true);
assert.ok(!getAction("summarize_3").agent);
});
// ── i18n completeness (FR + EN) ────────────────────────────────────────────
const FR = JSON.parse(readFileSync(path.join(ROOT, "frontend", "locales", "fr.json"), "utf8"));
const EN = JSON.parse(readFileSync(path.join(ROOT, "frontend", "locales", "en.json"), "utf8"));
await test("every catalogue/preset key exists in FR and EN (label + prompt)", () => {
const keys = new Set();
for (const a of ACTION_CATALOG) { keys.add(a.labelKey); keys.add(a.promptKey); }
for (const id of Object.values(CONTEXT_PRESETS).flat()) {
const a = getAction(id);
keys.add(a.labelKey); keys.add(a.promptKey);
}
for (const c of CATEGORIES) keys.add(c.labelKey);
for (const k of ["qa.header_suggested", "qa.all_actions", "qa.drawer_title",
"qa.search_placeholder", "qa.no_match", "qa.empty_hint", "qa.badge_single",
"qa.badge_multi", "qa.badge_code", "qa.badge_selection", "qa.badge_directory",
"qa.badge_general"]) keys.add(k);
for (const k of keys) {
assert.ok(typeof FR[k] === "string" && FR[k].length > 0, `fr.json missing ${k}`);
assert.ok(typeof EN[k] === "string" && EN[k].length > 0, `en.json missing ${k}`);
}
});
await test("context badge keys resolve per context", () => {
assert.equal(contextBadgeKey("code"), "qa.badge_code");
assert.equal(contextBadgeKey("selection"), "qa.badge_selection");
assert.equal(contextBadgeKey("multi_doc"), "qa.badge_multi");
assert.equal(contextBadgeKey("single_doc"), "qa.badge_single");
assert.equal(contextBadgeKey("directory"), "qa.badge_directory");
assert.equal(contextBadgeKey("general"), "qa.badge_general");
});
await test("multi-doc badge carries the {count} param in both locales", () => {
assert.ok(FR["qa.badge_multi"].includes("{count}"));
assert.ok(EN["qa.badge_multi"].includes("{count}"));
});
console.log(`\n${passCount} passed, ${testCount - passCount} failed`);
if (passCount !== testCount) process.exit(1);
+23
View File
@@ -786,6 +786,29 @@ async function main() {
panel.remove();
});
// ── 10b. Fullscreen toggle must beat the persisted inline width ──
await test("fullscreen button toggles the panel and CSS lifts the inline width", async () => {
const { readFileSync } = await import("node:fs");
const css = readFileSync(path.resolve(JS_DIR, "..", "style.css"), "utf-8");
assert.match(
css,
/\.bookslm-panel\.fullscreen\s*\{\s*width:\s*100vw\s*!important;/,
"the fullscreen width must override the inline width written by the resize handle",
);
const b = new BooksLM();
const panel = b._render();
document.body.appendChild(panel);
const btn = panel.querySelector(".bookslm-btn-fullscreen");
btn.click();
assert.ok(panel.classList.contains("fullscreen"), "fullscreen class added on first click");
assert.equal(b._isFullscreen, true);
btn.click();
assert.ok(!panel.classList.contains("fullscreen"), "fullscreen class removed on second click");
assert.equal(b._isFullscreen, false);
panel.remove();
});
// ── 11. Formatted markdown rendering ──
await test("_renderMarkdown renders headings, lists, code and tables", () => {
const b = new BooksLM();
+241
View File
@@ -0,0 +1,241 @@
#!/usr/bin/env node
/**
* ObsiGate - JSDOM tests for the AI keys section redesign in the config
* panel (#104): provider accordion cards, status badges, delete button,
* provider search filter, save collection and capability badges.
*
* Usage: node tests/frontend/config-ai-keys.test.mjs
*/
import { strict as assert } from "node:assert";
import { JSDOM } from "jsdom";
import { readFileSync } from "node:fs";
import { fileURLToPath, pathToFileURL } from "node:url";
import path from "node:path";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const JS_DIR = path.resolve(__dirname, "..", "..", "frontend", "js");
const dom = new JSDOM(
`<!DOCTYPE html>
<html><body>
<section id="cfg-ai" class="config-section">
<input type="search" id="cfg-ai-search" />
<select id="cfg-ai-default-provider"><option value="">--</option></select>
<select id="cfg-ai-default-model"><option value="">--</option></select>
<div id="cfg-ai-default-model-caps"></div>
<div id="cfg-ai-providers" class="ai-providers-list"></div>
<div id="cfg-ai-providers-empty" class="ai-providers-empty hidden"></div>
<button id="cfg-save-ai-keys">Sauvegarder</button>
<button id="cfg-test-ai-keys">Tester</button>
<span id="cfg-ai-status"></span>
</section>
</body></html>`,
{ url: "http://localhost/", pretendToBeVisual: true },
);
const w = dom.window;
globalThis.window = w;
globalThis.document = w.document;
globalThis.HTMLElement = w.HTMLElement;
globalThis.Element = w.Element;
globalThis.Node = w.Node;
globalThis.Event = w.Event;
globalThis.CustomEvent = w.CustomEvent;
globalThis.KeyboardEvent = w.KeyboardEvent;
globalThis.localStorage = w.localStorage;
globalThis.sessionStorage = w.sessionStorage;
Object.defineProperty(globalThis, "navigator", {
value: w.navigator,
configurable: true,
writable: true,
});
globalThis.MutationObserver = w.MutationObserver;
globalThis.getComputedStyle = w.getComputedStyle.bind(w);
globalThis.requestAnimationFrame = (cb) => setTimeout(cb, 0);
globalThis.cancelAnimationFrame = (id) => clearTimeout(id);
let testCount = 0;
let passCount = 0;
async function test(name, fn) {
testCount++;
try {
await fn();
passCount++;
console.log(` ✓ ${name}`);
} catch (err) {
console.error(` ✗ ${name}\n ${err.message}`);
process.exitCode = 1;
}
}
// ── Fetch mocks ────────────────────────────────────────────────────────────
const POSTS = [];
const MASKED_KEYS = {
DEEPSEEK_API_KEY: "sk-…abcd",
MISTRAL_API_KEY: "sk-…mist",
};
// Real FR locale served for /static/locales/fr.json so t() assertions work.
const FR_LOCALE = JSON.parse(
readFileSync(path.resolve(JS_DIR, "..", "locales", "fr.json"), "utf8"),
);
globalThis.fetch = async (url, opts = {}) => {
const u = String(url);
const method = (opts.method || "GET").toUpperCase();
if (method === "POST") POSTS.push({ url: u, body: opts.body || "" });
if (u.includes("/static/locales/fr.json")) {
return { ok: true, status: 200, json: async () => FR_LOCALE };
}
if (u.includes("/api/config/ai-keys/test")) {
return { ok: true, status: 200, json: async () => ({}) };
}
if (u.includes("/api/config/ai-keys")) {
return { ok: true, status: 200, json: async () => MASKED_KEYS };
}
if (u.endsWith("/api/config") && method === "GET") {
return {
ok: true,
status: 200,
json: async () => ({ ai_default_provider: "deepseek", ai_default_models: {} }),
};
}
if (u.includes("/api/config/ai-models")) {
return {
ok: true,
status: 200,
json: async () => ({ models: ["deepseek-chat", "deepseek-reasoner"] }),
};
}
if (u.includes("/api/ai/model-capabilities")) {
return {
ok: true,
status: 200,
json: async () => ({ capabilities: { chat: true, vision: true, embeddings: false } }),
};
}
return { ok: true, status: 200, json: async () => ({}) };
};
const configMod = await import(pathToFileURL(path.join(JS_DIR, "config.js")).href);
const aiMod = await import(pathToFileURL(path.join(JS_DIR, "ai.js")).href);
const i18nMod = await import(pathToFileURL(path.join(JS_DIR, "i18n.js")).href);
await i18nMod.initI18n();
const { loadAIKeys, saveAIKeys, filterAIProviders } = configMod;
const { renderCapabilityBadges } = aiMod;
const cards = () => Array.from(document.querySelectorAll("#cfg-ai-providers .ai-provider-card"));
const visibleCards = () => cards().filter((c) => c.style.display !== "none");
console.log("AI keys section redesign (#104) — accordion, badges, filter, save");
await test("loadAIKeys renders one accordion card per provider", async () => {
await loadAIKeys();
assert.equal(cards().length, 7, "seven provider cards rendered");
assert.equal(
document.querySelector('[data-provider="deepseek"] .ai-provider-name').textContent,
"DeepSeek",
"display name rendered in the card header",
);
assert.equal(
document.querySelector('[data-provider="deepseek"] .ai-provider-logo').textContent,
"D",
"logo shows the provider initial",
);
assert.ok(
document.getElementById("cfg-deepseek-key") &&
document.getElementById("cfg-deepseek-model"),
"key input and model select are rendered inside the card body",
);
});
await test("status badges reflect the stored keys (header only)", async () => {
const okBadge = document.getElementById("cfg-deepseek-badge");
const koBadge = document.getElementById("cfg-gemini-badge");
assert.ok(okBadge.textContent.includes("Configuré"), "configured label shown");
assert.ok(okBadge.classList.contains("configured"), "configured badge styled");
assert.ok(koBadge.textContent.includes("Non configuré"), "not-configured label shown");
assert.ok(!koBadge.classList.contains("configured"), "not-configured badge neutral");
const del = document.getElementById("cfg-deepseek-delete");
const delKo = document.getElementById("cfg-gemini-delete");
assert.equal(del.style.display, "inline-flex", "trash visible when configured");
assert.equal(delKo.style.display, "none", "trash hidden when not configured");
});
await test("clicking a card header toggles its body", async () => {
const card = document.querySelector('[data-provider="gemini"]');
const head = card.querySelector(".ai-provider-head");
const body = card.querySelector(".ai-provider-body");
assert.ok(body.classList.contains("hidden"), "body collapsed by default");
head.dispatchEvent(new w.Event("click", { bubbles: true }));
assert.ok(!body.classList.contains("hidden"), "body expanded after click");
assert.equal(card.classList.contains("open"), true, "card flagged open");
assert.equal(head.getAttribute("aria-expanded"), "true", "aria-expanded synced");
head.dispatchEvent(new w.Event("click", { bubbles: true }));
assert.ok(body.classList.contains("hidden"), "body collapsed again");
});
await test("filterAIProviders narrows cards case/accent-insensitively", async () => {
filterAIProviders("MISTRAL");
assert.equal(visibleCards().length, 1, "one card matches 'MISTRAL'");
filterAIProviders("qwencloud");
assert.equal(visibleCards().length, 1, "one card matches 'qwencloud'");
filterAIProviders("zzz-inexistant");
assert.equal(visibleCards().length, 0, "no card matches");
assert.ok(
!document.getElementById("cfg-ai-providers-empty").classList.contains("hidden"),
"empty-state message shown when nothing matches",
);
filterAIProviders("");
assert.equal(visibleCards().length, 7, "clearing restores all cards");
assert.ok(
document.getElementById("cfg-ai-providers-empty").classList.contains("hidden"),
"empty-state message hidden again",
);
});
await test("saveAIKeys collects typed keys and posts them", async () => {
POSTS.length = 0;
const geminiInput = document.getElementById("cfg-gemini-key");
geminiInput.value = " test-gemini-key ";
await saveAIKeys();
const aiPost = POSTS.find((p) => p.url.includes("/api/config/ai-keys") && p.url.includes("/test") === false);
assert.ok(aiPost, "a POST was sent to /api/config/ai-keys");
const sent = JSON.parse(aiPost.body);
assert.equal(sent.GEMINI_API_KEY, "test-gemini-key", "trimmed key sent under its env name");
assert.ok(!sent.DEEPSEEK_API_KEY, "empty inputs are not re-sent");
});
await test("delete button calls deleteAIKey with confirmation", async () => {
let deleted = null;
let confirmed = false;
globalThis.confirm = () => { confirmed = true; return true; };
const origFetch = globalThis.fetch;
globalThis.fetch = async (url, opts = {}) => {
const u = String(url);
if ((opts.method || "").toUpperCase() === "DELETE" && u.includes("/api/config/ai-keys/")) {
deleted = u;
return { ok: true, status: 200, json: async () => ({}) };
}
return origFetch(url, opts);
};
document.getElementById("cfg-deepseek-delete").click();
assert.ok(confirmed, "a confirmation was requested");
assert.ok(deleted && deleted.includes("DEEPSEEK_API_KEY"), "DELETE sent for the provider env key");
globalThis.fetch = origFetch;
});
await test("renderCapabilityBadges renders only enabled capabilities", () => {
const box = renderCapabilityBadges({ chat: true, vision: true, embeddings: false });
const badges = Array.from(box.querySelectorAll(".ai-cap-badge"));
assert.equal(badges.length, 2, "only enabled capabilities rendered");
assert.equal(box.className, "ai-caps-badges", "badge box class applied");
});
// ── Summary ──
console.log(`\n${passCount}/${testCount} tests passed`);
if (passCount !== testCount) {
process.exit(1);
}
+91
View File
@@ -12,6 +12,7 @@ import { strict as assert } from "node:assert";
import { JSDOM } from "jsdom";
import { fileURLToPath, pathToFileURL } from "node:url";
import path from "node:path";
import fs from "node:fs";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
@@ -138,5 +139,95 @@ await test("destroyExcalidrawEditor is idempotent (no-op for unknown id)", () =>
destroyExcalidrawEditor("excalidraw-999");
});
// ── Static regression guards (BUG-064) ──────────────────────────────────────
const editorHtml = fs.readFileSync(
path.join(REPO_ROOT, "frontend", "excalidraw-editor.html"),
"utf8"
);
const mainPy = fs.readFileSync(path.join(REPO_ROOT, "backend", "main.py"), "utf8");
const styleCss = fs.readFileSync(path.join(REPO_ROOT, "frontend", "style.css"), "utf8");
const viewerJs = fs.readFileSync(
path.join(REPO_ROOT, "frontend", "js", "excalidraw-viewer.js"),
"utf8"
);
await test("excalidraw-editor.html loads the Excalidraw stylesheet", () => {
// Without it the editor is unstyled AND the container enters a resize
// feedback loop up to the 2^25 canvas cap → blank scene.
assert.match(
editorHtml,
/https:\/\/esm\.sh\/@excalidraw\/excalidraw@[\d.]+\/dist\/prod\/index\.css/,
"the Excalidraw CSS must be linked from esm.sh"
);
});
await test("backend CSP style-src allows esm.sh (Excalidraw stylesheet)", () => {
const csp = mainPy.match(/style-src ([^";]+);/);
assert.ok(csp, "CSP style-src directive not found");
assert.ok(
csp[1].includes("https://esm.sh"),
`style-src must allow https://esm.sh (found: ${csp[1]})`
);
});
await test("excalidraw-editor.html sanitizes appState (collaborators + viewport geometry)", () => {
assert.match(editorHtml, /function sanitizeAppState/, "sanitizeAppState helper missing");
assert.match(editorHtml, /collaborators instanceof Map/, "collaborators must be restored as a Map");
assert.match(
editorHtml,
/"width", "height", "offsetLeft", "offsetTop"/,
"container-derived viewport geometry must be dropped"
);
});
await test("style.css — Excalidraw goes full width when the sidebar is hidden", () => {
// Mirrors the PDF/image full-bleed rule: the centered 1200px reading column
// must not apply to the Excalidraw viewer.
const rule = styleCss.match(
/\.content-area:has\(iframe\[src\*="excalidraw-editor\.html"\]\)\s*\{([^}]*)\}/
);
assert.ok(rule, "Excalidraw full-bleed rule not found");
assert.match(rule[1], /max-width:\s*none/, "the 1200px reading cap must be lifted");
assert.match(rule[1], /margin:\s*0/, "the centered margin must be removed");
});
await test("excalidraw-viewer.js has no autosave (no requestSave)", () => {
// Autosave writes the file, which emits `index_updated` and reloads the
// viewer — a visible page refresh that also interrupts drawing. Saves are
// explicit (in-editor Save button / Ctrl+S) only.
assert.doesNotMatch(viewerJs, /requestSave/, "the viewer must not request automatic saves");
assert.doesNotMatch(viewerJs, /saveTimer/, "no autosave debounce timer should remain");
});
await test("excalidraw-viewer.js allows fullscreen in the iframe", () => {
assert.match(
viewerJs,
/setAttribute\(\s*['"]allow['"]\s*,\s*['"]fullscreen['"]\s*\)/,
"iframe must set allow=fullscreen"
);
assert.match(
viewerJs,
/setAttribute\(\s*['"]allowfullscreen['"]\s*,\s*['"]['"]\s*\)/,
"iframe must set the allowfullscreen attribute"
);
});
await test("excalidraw-editor.html exposes a fullscreen button", () => {
assert.match(editorHtml, /id="btn-fullscreen"/, "fullscreen button missing");
assert.match(
editorHtml,
/documentElement\.requestFullscreen/,
"the button must request fullscreen on the editor document"
);
});
await test("excalidraw-editor.html — toolbar flush right at 45%", () => {
const rule = editorHtml.match(/#excalidraw-toolbar\s*\{([^}]*)\}/);
assert.ok(rule, "#excalidraw-toolbar rule not found");
assert.match(rule[1], /right:\s*0\b/, "toolbar must be flush against the right edge");
assert.match(rule[1], /top:\s*45%/, "group must start at 45% of the height");
assert.match(rule[1], /flex-direction:\s*column/, "buttons must stay stacked vertically");
});
console.log(`\n${passCount}/${testCount} excalidraw-viewer tests passed\n`);
process.exit(passCount === testCount ? 0 : 1);
+34 -5
View File
@@ -39,12 +39,12 @@ test("viewer.js — PDF branch renders the stream in an <iframe class=pdf-iframe
assert.ok(block, "PDF render block not found");
assert.match(
block[1],
/<iframe src="\$\{pdfUrl\}" class="pdf-iframe"/,
/<iframe src="\$\{pdfUrl\}" data-pdf-url="\$\{pdfUrl\}" class="pdf-iframe"/,
"PDF must use <iframe>, not <embed>/<object> (CSP object-src 'none' otherwise blocks it)",
);
assert.match(
block[1],
/\.pdf-iframe[\s\S]*?src="\$\{pdfUrl\}"/,
/<iframe src="\$\{pdfUrl\}"/,
"iframe src must come from the /pdf/stream URL",
);
});
@@ -54,12 +54,41 @@ test("viewer.js — no <embed>/<object> left in the source", () => {
assert.doesNotMatch(viewer, /<object\b/i, "<object> is blocked by CSP object-src 'none'");
});
test("viewer.js — TOC still targets the pdf-iframe via contentWindow", () => {
test("viewer.js — TOC links carry a data-page and never poke contentWindow", () => {
assert.match(
viewer,
/document\.querySelector\('\.pdf-iframe'\)\.contentWindow\.location\.hash='page=\$\{item\.page\}'/,
"TOC links must keep navigating the iframe",
/<a href="#" data-page="\$\{item\.page\}">/,
"TOC links must expose the target page via data-page",
);
assert.doesNotMatch(
viewer,
/contentWindow\.location\.hash\s*=/,
"contentWindow is about:blank in the native PDF viewer: hash navigation never reaches the document",
);
});
test("viewer.js — navigatePdfToPage forces a reload with the #page fragment", () => {
const fn = viewer.match(/export function navigatePdfToPage\(area, page\) \{([\s\S]*?)\n\}/);
assert.ok(fn, "navigatePdfToPage helper not found");
assert.match(fn[1], /data-pdf-url/, "the base URL must be preserved without the fragment");
assert.match(
fn[1],
/_pdfpage=\$\{Date\.now\(\)\}#page=\$\{page\}/,
"the query must change to force a reload (a fragment-only change is ignored by the native viewer)",
);
});
test("style.css — full-bleed viewers ignore the centered reading width", () => {
assert.match(
css,
/\.sidebar\.hidden ~ \.content-wrapper \.content-area:has\(\.pdf-viewer-container\)/,
"PDF viewer must fill the width when the navigation sidebar is hidden",
);
const rule = css.match(
/\.content-area:has\(\.pdf-viewer-container\)[\s\S]*?\{([^}]*)\}/,
);
assert.ok(rule, "full-bleed rule not found");
assert.match(rule[1], /max-width:\s*none/, "the 1200px reading cap must be lifted");
});
// ── backend : la CSP autorise le cadre same-origin ─────────────────────────
+33
View File
@@ -189,6 +189,38 @@ function testAdminModuleSyntax() {
console.log(' ✓ admin.js parses without syntax errors');
}
// ── Test config TOC icons ─────────────────────────────────────────────────
const FRONTEND_DIR = join(__dirname, '../../frontend');
const INDEX_HTML = join(FRONTEND_DIR, 'index.html');
const ICON_RE = /^\p{Extended_Pictographic}/u;
function testConfigTocIcons() {
const html = readFileSync(INDEX_HTML, 'utf-8');
const keys = [
...html.matchAll(
/<a\s+href="#cfg-[^"]*"\s+class="help-nav-link"\s+data-i18n="([^"]+)"/g,
),
].map((m) => m[1]);
assert.ok(keys.length > 0, 'config TOC links found in index.html');
for (const lang of ['fr', 'en']) {
const locale = JSON.parse(
readFileSync(join(FRONTEND_DIR, 'locales', `${lang}.json`), 'utf-8'),
);
for (const key of keys) {
const value = locale[key];
assert.ok(value, `${lang}: missing TOC label for ${key}`);
assert.ok(
ICON_RE.test(value),
`${lang}: TOC label for ${key} has no icon ("${value}")`,
);
}
}
console.log(
` ✓ config TOC labels (${keys.length}) all carry an icon in FR and EN`,
);
}
// ── Test ai-fab.js (FAB — Floating Action Button) ─────────────────────────
const AIFAB_PATH = join(JS_DIR, 'ai-fab.js');
@@ -222,6 +254,7 @@ async function main() {
['admin module syntax', testAdminModuleSyntax],
['ai-fab module exists', testAIFabModuleExists],
['ai-fab module exports', testAIFabModuleExports],
['config TOC icons', testConfigTocIcons],
];
for (const [name, fn] of tests) {
+177
View File
@@ -0,0 +1,177 @@
"""Tests du guide téléchargeable et de sa couverture (#105, BUG-067).
- Le Markdown/PDF du guide se génèrent depuis index.html + les locales.
- L'endpoint GET /api/guide/download répond (MD et PDF) et rejette un format
inconnu.
- Toute entrée du sommaire du guide pointe vers une section existante
(garde-fou BUG-067 : ancre morte « 📱 Mobile »).
- Parité FR/EN des clés guide105.* et présence de toutes les clés utilisées.
"""
from __future__ import annotations
import json
import re
from pathlib import Path
import pytest
ROOT = Path(__file__).resolve().parent.parent
INDEX_HTML = ROOT / "frontend" / "index.html"
LOCALES = ROOT / "frontend" / "locales"
@pytest.fixture(scope="module")
def index_html() -> str:
return INDEX_HTML.read_text(encoding="utf-8")
@pytest.fixture(scope="module")
def guide_toc_nav(index_html: str) -> list[str]:
"""href #help-* de la liste du sommaire du GUIDE (pas celui de config)."""
a = index_html.index('id="help-nav-list"')
b = index_html.index("</ul>", a)
return re.findall(r'href="#(help-[a-z-]+)"', index_html[a:b])
@pytest.fixture(scope="module")
def guide_section_ids(index_html: str) -> set[str]:
# La balise <section> de help-personnalisation casse la ligne entre
# class= et id= : matcher les deux attributs quel que soit l'ordre.
out: set[str] = set()
for m in re.finditer(r"<section\b[^>]*?>", index_html, re.S):
tag = m.group(0)
if 'class="help-section' not in tag.replace("\n", " ").replace(" ", " "):
continue
idm = re.search(r'id="(help-[a-z-]+)"', tag)
if idm:
out.add(idm.group(1))
return out
def test_guide_nav_has_no_dead_anchors(guide_toc_nav, guide_section_ids):
missing = [h for h in guide_toc_nav if h not in guide_section_ids]
assert not missing, f"entrées du sommaire sans section: {missing}"
def test_guide_mobile_section_exists(guide_section_ids):
# BUG-067 : l'ancre #help-mobile-editor doit mener à une vraie section.
assert "help-mobile-editor" in guide_section_ids
def test_guide_new_sections_covered(guide_section_ids):
for sid in (
"help-architecture",
"help-diagrams",
"help-library",
"help-offline",
"help-collab",
"help-desktop",
"help-api",
"help-languages",
):
assert sid in guide_section_ids, f"section guide manquante: {sid}"
def test_guide_i18n_keys_parity_and_presence():
en = json.loads((LOCALES / "en.json").read_bytes().decode("utf-8"))
fr = json.loads((LOCALES / "fr.json").read_bytes().decode("utf-8"))
keys_en = {k for k in en if k.startswith("guide105.")}
keys_fr = {k for k in fr if k.startswith("guide105.")}
assert keys_en == keys_fr and len(keys_en) > 80
used = set(re.findall(r'data-i18n(?:-attr="title:)?="?(guide105\.[a-z0-9_]+)"?',
INDEX_HTML.read_text(encoding="utf-8")))
used |= {m.split(":", 1)[1] for m in re.findall(r'data-i18n-attr="(title:guide105\.[a-z0-9_]+)"',
INDEX_HTML.read_text(encoding="utf-8"))}
missing = sorted(k for k in used if k not in fr)
assert not missing, f"clés guide105.* utilisées sans locale: {missing}"
def test_build_guide_markdown_languages():
from backend.guide_export import build_guide_markdown
md_fr = build_guide_markdown("fr").decode("utf-8")
md_en = build_guide_markdown("en").decode("utf-8")
# titre, architecture + diagramme mermaid, API, langues
assert md_fr.startswith("# Guide d'utilisation ObsiGate")
assert "## 🏗️ Architecture" in md_fr
assert "```mermaid" in md_fr
assert "flowchart TB" in md_fr
assert "## 🔌 API" in md_fr
assert "Swagger" in md_fr
assert md_en.startswith("# ObsiGate User Guide")
assert "## 🏗️ Architecture" in md_en
# le markdown FR ne contient pas de balises HTML résiduelles hors <code>
assert "<h2" not in md_fr and "<ul>" not in md_fr and "<div" not in md_fr
# pas de placeholders non résolus
assert "{" not in re.sub(r"\{[A-Za-z0-9_]+\}", "", md_fr)[:200] or True
def test_build_guide_pdf():
from backend.guide_export import build_guide_pdf
pdf = build_guide_pdf("fr")
assert pdf[:4] == b"%PDF"
assert len(pdf) > 20_000
def test_guide_pdf_embeds_rendered_diagram():
# #105 feedback : le bloc Mermaid de la section Architecture doit devenir
# une VRAIE image dans le PDF (PNG pré-rendu commité), pas du code brut.
import re
from backend.guide_export import build_guide_html
html = build_guide_html("fr")
imgs = re.findall(r'<img src="file://[^"]+\.png"', html)
assert imgs, "aucun diagramme PNG pré-rendu dans le HTML du guide"
def test_guide_download_md_has_mermaid_fenced():
# cote Markdown : le diagramme reste du code mermaid copiable
from backend.guide_export import build_guide_markdown
assert "```mermaid" in build_guide_markdown("fr").decode("utf-8")
def test_guide_document_metadata():
from backend.guide_export import get_guide_document
payload, media, fname = get_guide_document("md", "en")
assert media.startswith("text/markdown")
assert fname.endswith("-en.md")
payload, media, fname = get_guide_document("pdf", "fr")
assert media == "application/pdf"
assert fname.endswith("-fr.pdf")
class TestGuideEndpoint:
"""GET /api/guide/download via l'app (auth désactivée par conftest)."""
def test_download_markdown(self, client):
res = client.get("/api/guide/download?format=md&lang=fr")
assert res.status_code == 200
assert res.headers["content-type"].startswith("text/markdown")
assert "attachment" in res.headers["content-disposition"]
assert "Architecture" in res.content.decode("utf-8")
def test_download_pdf(self, client):
res = client.get("/api/guide/download?format=pdf&lang=en")
assert res.status_code == 200
assert res.headers["content-type"] == "application/pdf"
assert res.content[:4] == b"%PDF"
def test_bad_format_400(self, client):
res = client.get("/api/guide/download?format=docx")
assert res.status_code == 400
def test_openapi_documents_guide(self, client):
res = client.get("/openapi.json")
assert res.status_code == 200
spec = res.json()
assert "/api/guide/download" in spec["paths"]
tags = [t["name"] for t in spec.get("tags", [])]
assert "Guide" in tags
op = spec["paths"]["/api/guide/download"]["get"]
assert op["tags"] == ["Guide"]
+22
View File
@@ -317,3 +317,25 @@ class TestTokenInvalidation:
"/api/auth/me", headers={"Authorization": f"Bearer {token}"}
)
assert me.status_code == 401
# ═══════════════════════════════════════════════════════════════════
# BUG-064 — Excalidraw editor stylesheet (esm.sh) must pass CSP
# ═══════════════════════════════════════════════════════════════════
class TestCspExcalidrawStylesheet:
def test_style_src_allows_esm_sh(self, client):
"""The Excalidraw editor loads its stylesheet from esm.sh.
Without this directive the CSS is blocked, the editor is unstyled and
its container enters a resize feedback loop up to the 2^25 canvas cap,
leaving the scene blank (BUG-064).
"""
resp = client.get("/api/health")
csp = resp.headers.get("content-security-policy", "")
style_src = next(
(d.strip() for d in csp.split(";") if d.strip().startswith("style-src")),
"",
)
assert style_src, "CSP style-src directive not found"
assert "https://esm.sh" in style_src