diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs new file mode 100644 index 00000000..d30081a2 --- /dev/null +++ b/.git-blame-ignore-revs @@ -0,0 +1,5 @@ +# Commits that only reformat or re-header files; `git config blame.ignoreRevsFile .git-blame-ignore-revs` makes git blame skip them. +# Reformat the C++ sources with clang-format (#653) +48eea66d540c4921c447bebab1811f40ed177cd5 +# Reformat with clang-format 23.1.5, the reference version (#653) +32b8d55a732e6333de9537fa6b73b4bc30321a58 diff --git a/.gitattributes b/.gitattributes index 6efadabb..8c6bf328 100644 --- a/.gitattributes +++ b/.gitattributes @@ -37,6 +37,7 @@ # Exclude files from exporting .gitattributes export-ignore .gitignore export-ignore +.git-blame-ignore-revs export-ignore .gitkeep export-ignore # Embedded headers hold the exact bytes of their text sources. Freshness tests diff --git a/.github/CONTRIBUTING.md b/.github/CONTRIBUTING.md index 9e19c234..a4108eef 100644 --- a/.github/CONTRIBUTING.md +++ b/.github/CONTRIBUTING.md @@ -110,6 +110,36 @@ To ensure consistency, we use `.clang-format` and `clang-tidy` to enforce our co Please run these tools on your code before submitting a pull request. +CI runs `.github/scripts/check-clang-format.sh` weekly, on pull requests into `master` and on manual dispatch (not on every pull request into `develop`), on every tracked C++ source (`clang-format --dry-run --Werror`) with a pinned version of `clang-format` +(`.github/workflows/SourceFormat.yml`); the reference version is **clang-format 23.1.5** (`python3 -m pip install clang-format==23.1.5`, or any 23.x: a patch release does not change the output, another major version may); run the script locally with it before you push, and never run `clang-format -i` with another major version. Generated headers (the embedded assets) and the gzip +fixtures are exempt. The commit that reformatted the whole code base is listed in `.git-blame-ignore-revs`; to make `git blame` skip it, run +`git config blame.ignoreRevsFile .git-blame-ignore-revs` once (GitHub applies the file by itself). + +## File header + +Every tracked C++ source (`.hpp`, `.cpp`, `.h`, `.cu`, `.cuh`, `.mm`) starts with this header, before `#pragma once` or the first `#include`: + +```cpp +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: AAAA-MM-JJ +// +// WebFront — +// Role: . +// Thread: | Alloc: +// LLM: +``` + +- **Author** is the author of the file; **Created** is the date of its first commit, in ISO format. +- **Thread** tells where the code may run: `ui-loop` (the thread of `show()` or of the frontend's interface loop), `bridge-io` (the server's I/O context thread), + `worker-safe` (a pure or self-contained unit that any thread may use on its own objects) or `thread-safe` (shared objects synchronized inside). +- **Alloc** tells what the code may allocate: `zero-hot-path` (nothing on the hot path), `heap-init` (heap allocation at construction or setup only) or `unrestricted`. +- **Role** and **LLM** are written for the file, from its content and the invariants of `AGENTS.md` and the ADRs; never copy a generic value. An agent reads them + first, so keep them true when the file changes. +- Files with another license (third-party code) and generated files (the embedded asset headers, the gzip fixtures) keep their own header; they are listed in + `test/cmake/CheckSourceHeaders.cmake`, which fails the `SourceHeaders` CTest case for a tracked source whose header is missing or malformed. +- Build files (`CMakeLists.txt`, `*.cmake`) and the TypeScript under `js/` do not need the header. + ## Changelog format [`docs/CHANGELOG.md`](../docs/CHANGELOG.md) answers three questions quickly: what changes for me, is anything breaking, and diff --git a/.github/scripts/check-clang-format.sh b/.github/scripts/check-clang-format.sh new file mode 100755 index 00000000..518169ad --- /dev/null +++ b/.github/scripts/check-clang-format.sh @@ -0,0 +1,39 @@ +#!/usr/bin/env bash +# Fails when a tracked C++ source differs from what its clang-format configuration produces (#653). +# .github/scripts/check-clang-format.sh [clang-format] the executable defaults to clang-format +# Each source uses the .clang-format of its directory (include/webfront/, test/, examples/); cmake/ has none and follows include/webfront/. +# Generated or fixed data is exempt; the list matches test/cmake/CheckSourceHeaders.cmake. The reference version is the one pinned in +# .github/workflows/SourceFormat.yml (clang-format 23.1.5): another major version may format differently. +set -euo pipefail + +clang_format="${1:-clang-format}" +cd "$(git rev-parse --show-toplevel)" + +reference_major=23 +version="$("$clang_format" --version)" +if ! grep -Eq "version ${reference_major}\." <<< "$version"; then + echo "warning: the reference is clang-format ${reference_major}.x, this is: $version" >&2 +fi + +exempt='^(include/webfront/system/(DeveloperBootstrapData|DeveloperIndexHtmlData|DeveloperReleaseData|DomInterpreterData|FallbackIndexHtmlData|FallbackModuleData|FaviconData|WebFrontJsData)\.hpp|test/unit/GzipFixtures\.hpp)$' + +status=0 +count=0 +while IFS= read -r file; do + style=file + case "$file" in + cmake/*) style=file:include/webfront/.clang-format ;; + esac + count=$((count + 1)) + if ! "$clang_format" --dry-run --Werror --style="$style" "$file" 2> /dev/null; then + echo "not formatted: $file" + status=1 + fi +done < <(git ls-files '*.hpp' '*.cpp' '*.h' '*.cu' '*.cuh' '*.mm' | grep -Ev "$exempt") + +if [ "$status" -ne 0 ]; then + echo "Run clang-format -i on the files above (version: $("$clang_format" --version))." >&2 +else + echo "$count files formatted" +fi +exit "$status" diff --git a/.github/workflows/BuildAndTest.yml b/.github/workflows/BuildAndTest.yml index 0c978ccc..c4b53030 100644 --- a/.github/workflows/BuildAndTest.yml +++ b/.github/workflows/BuildAndTest.yml @@ -119,7 +119,7 @@ jobs: # Only Linux waits for its image. Native desktops below start immediately and reuse these steps. if: ${{ !cancelled() && (github.event_name != 'workflow_dispatch' || inputs.repeat_desktop_tests) }} # No `name:` expression: a skipped matrix job would display it unevaluated. - timeout-minutes: ${{ github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests && (inputs.desktop_passes > 3 && 300 || 90) || 25 }} + timeout-minutes: ${{ github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests && (inputs.desktop_passes > 3 && 300 || 90) || 60 }} strategy: fail-fast: false matrix: @@ -329,7 +329,7 @@ jobs: permissions: contents: read # The explicit qualification includes a cold analysis build and desktop_passes complete graphs. - timeout-minutes: ${{ github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests && (inputs.desktop_passes > 3 && 300 || 90) || 25 }} + timeout-minutes: ${{ github.event_name == 'workflow_dispatch' && inputs.repeat_desktop_tests && (inputs.desktop_passes > 3 && 300 || 90) || 60 }} strategy: fail-fast: false matrix: diff --git a/.github/workflows/SourceFormat.yml b/.github/workflows/SourceFormat.yml new file mode 100644 index 00000000..3c76e1a9 --- /dev/null +++ b/.github/workflows/SourceFormat.yml @@ -0,0 +1,28 @@ +name: Source Format + +# Rare on purpose (#653): the advanced tier only, like the other weekly and release-branch checks. A pull request into develop is not checked. +on: + pull_request: + branches: [ master ] + schedule: + - cron: '23 4 * * 1' + workflow_dispatch: + +permissions: + contents: read + +jobs: + clang-format: + name: clang-format + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v7 + with: + persist-credentials: false + + # The version is pinned: clang-format changes its output from one release to the next. + - name: Install clang-format + run: python3 -m pip install --user clang-format==23.1.5 + + - name: Check the tracked sources + run: .github/scripts/check-clang-format.sh "$HOME/.local/bin/clang-format" diff --git a/AGENTS.md b/AGENTS.md index 8058affa..a7b60aa7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,7 +28,7 @@ The README introduces WebFront through the Game of Life walkthrough, demonstrati - `js/pty/`: optional `@webfront/pty` adapter for native pseudoterminals. `wf run pty-package` assembles the archive used by the browser tests. See `docs/PTY.md`. - `js/react/`: optional `@webfront/react` package (`createStore`, `useStore`, `Island`), declarations and package-local license. `wf run react-package` assembles it; tests verify the exact archive installed by the registry. It is outside the core's embedded resource list. - `test/fixtures/`, `test/web/fixtures/`: retained regression fixtures, not public example applications. -- `test/unit/`: C++ unit tests, written with `test/unit/Bdd.hpp` (a single-header BDD framework); `test/web/`: real-browser integration (`suite/` is the WebFront project of the Jasmine specs, run by `webtest` through `wf test`); `test/driver/`: `webfront-wf`, the non-interactive `wf` driver for tests; `test/fuzz/`, `test/fixtures/`; `test/cmake/`: CMake test scripts and sub-projects. The `RepositoryLayout` CTest case pins the tracked root. +- `test/unit/`: C++ unit tests, written with `include/webfront/testing/Bdd.hpp` (a single-header BDD framework, a public maintained interface with the `WebFront::Bdd` target and `webfront_bdd_discover_tests`, `docs/BDD.md`; `cmake/WebFrontBdd*.cmake`); `test/web/`: real-browser integration (`suite/` is the WebFront project of the Jasmine specs, run by `webtest` through `wf test`); `test/driver/`: `webfront-wf`, the non-interactive `wf` driver for tests; `test/fuzz/`, `test/fixtures/`; `test/cmake/`: CMake test scripts and sub-projects. The `RepositoryLayout` CTest case pins the tracked root. - `cmake/`: build modules (frontends, CEF, CPM, compiler options); `.github/`: workflows, `.github/CONTRIBUTING.md`. - `docs/`: current reference guides, architecture decisions and `docs/CHANGELOG.md`. - `docs/PROJECT_STATUS.md`: current supported paths, validation scope and known limitations; completed work belongs in the changelog and Git history. @@ -117,9 +117,10 @@ Exception: a purely C++ change that reuses an existing encoding, introduces no n ## Coding and testing conventions - Use C++23, four-space indentation, the `.clang-format` of the directory (`include/webfront/`, `test/`, `examples/`), and the naming rules in `.github/CONTRIBUTING.md`. +- Every tracked C++ source starts with the normalized file header (SPDX, Author, Created, subsystem, Role, Thread, Alloc, LLM) described in `.github/CONTRIBUTING.md`; read it first, keep it true when you change the file, and give a new file one. The `SourceHeaders` CTest case checks it, and CI checks the format with `.github/scripts/check-clang-format.sh` (pinned `clang-format`); generated headers are exempt. - Keep production implementation header-only under `include/`; browser resources live in `js/`. - Prefer standard-library facilities and explicit ownership. Keep public headers ODR-safe (`inline`/templates as appropriate). -- Unit tests are named `const Scenario` objects whose `given`/`when`/`then` sections are lambdas, checked with `require`/`check` (`test/unit/Bdd.hpp`), and use deterministic mocks. +- Unit tests are named `const Scenario` objects whose `given`/`when`/`then` sections are lambdas, checked with `require`/`check` (`include/webfront/testing/Bdd.hpp`), and use deterministic mocks. - Jasmine specs are the project `test/web/suite/`, built by esbuild-wasm and run by `wf test` under the locked `jasmine-core` (installed from the local registry by `WebSuiteInstall`); `webtest` is the `webfront-wf` driver plus the C++ callbacks of the specs. The specs tell C++ they are done (`specsFinished`), the process status is that of `wf test` (or 1 when C++ did not observe every call), and the CTest case has a timeout. The registry the suite installs from is built by `wf run test-registry` (the `TestRegistry` case), from the packages that configure downloaded. - Every bug fix needs a failing regression test at the lowest useful level. Bridge changes also need the browser integration test. - Tests must not require user input, a fixed pre-existing browser session, or public network access after dependencies are configured. diff --git a/CMakeLists.txt b/CMakeLists.txt index 7bb06543..231a489c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,7 +16,6 @@ else() endif() option(BUILD_SHARED_LIBS "Enable compilation of shared libraries" OFF) -option(WEBFRONT_BUILD_AUTOMATION "Build the optional local developer CLI/MCP launcher" OFF) option(WEBFRONT_BUILD_EXAMPLES "Build the example applications" ${WEBFRONT_IS_TOP_LEVEL}) option(WEBFRONT_DISTRIBUTION "Require WebKitGTK sandboxing for distribution (development disables it by default)" OFF) option(WEBFRONT_GZIP_DIFFERENTIAL "Build test-only gzip/zlib differential checks" OFF) @@ -55,6 +54,8 @@ find_package(Threads REQUIRED) add_library(WebFront INTERFACE) add_library(WebFront::WebFront ALIAS WebFront) +# The public test framework (WebFront::Bdd, webfront_bdd_discover_tests), which WebFront's own tests use. +include(cmake/WebFrontBddTarget.cmake) if(WEBFRONT_DISTRIBUTION) target_compile_definitions(WebFront INTERFACE WEBFRONT_DISTRIBUTION=1) endif() @@ -148,24 +149,11 @@ webfront_add_embedded_assets() # Opt-in consumer test registration; inclusion alone downloads nothing and registers no tests. include(WebFrontJasmine) -if(WEBFRONT_BUILD_AUTOMATION OR (WEBFRONT_ENABLE_TESTING AND - (WEBFRONT_EMBED_CEF OR WEBFRONT_EMBED_WKWEBVIEW OR WEBFRONT_EMBED_WEBVIEW2 OR WEBFRONT_EMBED_WEBKITGTK))) - webfront_default_embedded_frontend(_automation_default FALLBACK CEF) - webfront_select_frontend(WEBFRONT_AUTOMATION_FRONTEND "${_automation_default}" - "Developer automation frontend" EMBEDDED_ONLY REQUIRE_AVAILABLE) - if(NOT ${WEBFRONT_FRONTEND_${WEBFRONT_AUTOMATION_FRONTEND}_OPTION}) - message(FATAL_ERROR "Automation needs an explicitly enabled embedded frontend") - endif() - add_executable(webfront-agent js/developer/tools/WebFrontAgent.cpp) - target_link_libraries(webfront-agent PRIVATE WebFront WebFront_options WebFront_warnings) - if(WIN32) - target_link_libraries(webfront-agent PRIVATE ws2_32 bcrypt advapi32) - endif() - target_compile_definitions(webfront-agent PRIVATE WEBFRONT_AUTOMATION_FRONTEND_TYPE=${WEBFRONT_AUTOMATION_FRONTEND_TYPE}) - webfront_setup_frontends_for_target(webfront-agent) +# The webfront-agent launcher is gone (ADR-025): an application that enables automation serves MCP itself. +if(DEFINED WEBFRONT_BUILD_AUTOMATION OR DEFINED WEBFRONT_AUTOMATION_FRONTEND) + message(WARNING "WEBFRONT_BUILD_AUTOMATION and WEBFRONT_AUTOMATION_FRONTEND no longer build anything: webfront-agent was removed. " + "An application that calls webfront::automation::enableAutomation serves MCP itself (docs/AUTOMATION.md).") endif() -# Public helper for a parent project: checks the launcher target and optionally installs it. -include(WebFrontAgent) # What an agent configuring a project must learn at once: the development model, and how it runs wf itself. include(WebFrontAgentGuide) webfront_announce_agent_support() diff --git a/README.fr.md b/README.fr.md index 71fe0b4c..e3e8cf05 100644 --- a/README.fr.md +++ b/README.fr.md @@ -10,24 +10,25 @@ [![C++23](https://img.shields.io/badge/C%2B%2B-23-00599C)](CMakeLists.txt) [![Header-only](https://img.shields.io/badge/library-header--only-2EA043)](include/) -[English](README.md) · [Français](README.fr.md) +[English](README.md) · [Français](README.fr.md) · [简体中文](README.zh-CN.md) -WebFront est une **bibliothèque C++23 header-only pour créer des interfaces utilisateur riches et modernes.** Conservez la logique applicative en C++ et créez des interfaces réactives avec TypeScript, React et les paquets de l’écosystème JavaScript. WebFront intègre les outils de développement d’interfaces à votre application : aucun environnement de développement TypeScript séparé n’est à installer. +WebFront est un framework d’interface utilisateur C++ qui produit des interfaces modernes et réactives. C’est une bibliothèque C++23 distribuée sous forme d’en-têtes : la logique de votre application reste en C++, l’interface se construit avec TypeScript, React et les paquets compatibles avec les navigateurs, et l’application terminée se distribue dans un seul exécutable. -WebFront n’a aucune dépendance et peut être déployé sur tout appareil disposant d’une bibliothèque standard C++ récente. +Avec `app.bootstrap("developer")`, l’application ouvre son propre environnement de développement. Dans cette fenêtre, `wf` compile l’interface, affiche un aperçu, vérifie les types et lance les tests Jasmine. Vous pouvez utiliser le terminal ou confier les mêmes opérations à un agent de programmation via MCP. Tout cela fonctionne sans Node.js ni npm. + +Une fois l’interface prête, embarquez ses ressources dans l’exécutable. Vous obtenez une application compacte et autonome qui fonctionne hors ligne, dans une fenêtre native ou, sur les systèmes embarqués et sans écran, via un navigateur web. Parcours du jeu de la vie : application C++, terminal wf, installation des dépendances et aperçu React L'animation présente le programme C++ et l'interface ; les temps d'attente sont condensés et l'aperçu agrandi pour la lisibilité. Le [parcours ci-dessous](#jeu-de-la-vie--du-calcul-c-à-lapplication-native) utilise les sources compilées du dépôt. -- **Intégrez WebFront à une application existante.** Conservez votre simulation, le contrôle de vos appareils, vos calculs SIMD, vos noyaux CUDA… et vos threads de travail en C++. Utilisez une fenêtre native ou même un navigateur web tout en gardant la maîtrise de votre boucle d’événements. [Intégration à l’application hôte →](docs/HOST_INTEGRATION.md) -- **Équipez les développeurs et les agents de programmation.** Les outils `wf` intégrés compilent l’interface, vérifient les types, exécutent les tests et embarquent ses ressources. Un serveur MCP activable à la demande et une interface en ligne de commande JSON permettent aux agents de piloter la fenêtre de votre application et d’exécuter les vérifications et les fonctions de rappel autorisées. [Développer avec un agent →](#développer-avec-un-agent) +- **Développez avec un agent.** Via MCP, il peut créer l’interface, installer les paquets, afficher un aperçu, lancer les tests et embarquer les ressources. Selon les droits que vous lui accordez, il peut aussi inspecter l’application en cours d’exécution, interagir avec son interface et appeler les fonctions C++ de votre choix. [Développer avec un agent →](#développer-avec-un-agent) · [Automatisation →](#laisser-un-agent-piloter-votre-application) +- **Retrouvez les mêmes dépendances sur chaque poste.** La version de l’environnement de développement est épinglée. Son intégrité est vérifiée par SHA-512 et il est mis en cache au premier lancement. Le manifeste et le fichier de verrouillage fixent les dépendances pour toute l’équipe et ses agents. [Environnement de développement →](docs/DEVELOPER_ENVIRONMENT.md) +- **Ajoutez une interface à un logiciel C++ existant.** Gardez la maîtrise de votre boucle d’événements, de vos threads de travail, de vos appareils et de vos calculs SIMD ou CUDA. Ouvrez une fenêtre native ou utilisez le navigateur du système, et faites tourner plusieurs applications ou fenêtres côte à côte. [Intégration à l’application hôte →](docs/HOST_INTEGRATION.md) - **Transférez directement les données numériques.** Les tableaux typés et les ensembles de bits compactés transitent par une passerelle WebSocket binaire, sans conversion en JSON ou en base64. Coroutines, futures et senders relient les appels asynchrones de l’interface aux traitements natifs. [Modèle d’exécution →](docs/ASYNC_EXECUTION.md) -- **Préparez votre application pour la distribution.** Embarquez les ressources, verrouillez les versions des paquets et vérifiez les téléchargements ; l’application obtenue fonctionne hors ligne. Les cibles CMake destinées aux projets utilisateurs et les tests dans le navigateur facilitent les compilations reproductibles et l’intégration continue. [Intégration →](#intégrer-webfront-dans-votre-projet) · [Tests →](#tester-votre-application) +- **Testez et préparez la distribution.** Le lanceur de tests dans le navigateur et le framework public `webfront::bdd` complètent votre projet CMake. Embarquez l’interface finale pour une utilisation hors ligne. [Intégration →](#intégrer-webfront-dans-votre-projet) · [Tests →](#tester-votre-application) - **Choisissez vos technologies d’interface.** Utilisez TypeScript, React et des paquets compatibles avec les navigateurs, ou créez des îlots DOM directement en C++. Des composants optionnels permettent de générer des formulaires et des inspecteurs à partir de descripteurs de types C++. [DOM →](docs/DOM.md) · [React →](docs/REACT.md) · [Formulaires →](docs/FORMS.md) - - **Site et livre : [webfront.fr](https://webfront.fr/fr/)** · [Le livre WebFront](https://webfront.fr/fr/book/) · [Documentation](docs/) · [Historique des versions](docs/CHANGELOG.md) ## Plateformes et déploiement @@ -83,9 +84,9 @@ Scène de 960 × 720, quatre rayons par pixel ; fenêtre de 800 × 600 pixels CS ## Par où commencer ? +- **Travailler avec un agent :** [parcours de développement](#développer-avec-un-agent) et [automation de l'application](#laisser-un-agent-piloter-votre-application). - **Évaluer la bibliothèque :** [Hello World](#hello-world), puis le [parcours du jeu de la vie](#jeu-de-la-vie--du-calcul-c-à-lapplication-native). - **Ajouter une interface à un logiciel existant :** [intégration CMake](#intégrer-webfront-dans-votre-projet) et [exemple de boucle hôte](examples/host-loop/HostLoop.cpp). -- **Travailler avec un agent :** [parcours de développement](#développer-avec-un-agent) et [automation de l'application](#laisser-un-agent-piloter-votre-application). - **Préparer la production :** [tests](#tester-votre-application), [contrats et limites](#contrats-et-limites) et [état du support](docs/PROJECT_STATUS.md). ## Développer avec un agent @@ -94,21 +95,18 @@ Une application WebFront est un programme C++ dont l'interface TypeScript/TSX se Avec l'environnement épinglé, l'ordre est : `wf create app` (nom du starter, pas du projet), `wf init`, `wf install ` pour les dépendances navigateur, puis `wf dev ui/main.ts`. Terminez par `wf check`, `wf test` et `wf embed` selon la configuration du projet. `wf create life` fournit le starter React du parcours ci-dessous ; `wf help agents` décrit la marche à suivre. -**L'agent exécute les commandes lui-même**, sans demander à l'utilisateur de les saisir. Configurez avec `-DWEBFRONT_BUILD_AUTOMATION=ON` pour construire `webfront-agent`. L'application partage sa session explicitement avec `webfront::automation::enableAutomation(app, {.grants = {...}, .listen = directory})` ; les autorisations restent choisies par son propriétaire. +**L'agent exécute les commandes lui-même**, par MCP, sans demander à l'utilisateur de les saisir. Dans une build de développement, l'application active l'automatisation avec `webfront::automation::enableAutomation(app, {.grants = {...}})` ; les autorisations restent choisies par son propriétaire. L'application devient alors le serveur MCP : aucun autre programme n'est construit ni lancé. Elle affiche son URL et le chemin d'une configuration cliente privée (`mcp.json`, avec l'URL et un jeton Bearer, hors du projet) : -```sh -webfront-agent --list -webfront-agent --attach DIRECTORY --operation create --starter app -webfront-agent --attach DIRECTORY --operation preview --entry ui/main.ts -webfront-agent --print-mcp-config --attach DIRECTORY > .mcp.json +```text +WebFront MCP (grants: check, build, preview): http://127.0.0.1:PORT/mcp - client configuration: .../sessions/SESSION/mcp.json ``` -Après chaque modification, l'agent utilise `preview` à la place de la session interactive `wf dev`. La même interface est disponible en MCP : - ```json -{"mcpServers": {"webfront": {"command": "/path/to/webfront-agent", "args": ["--attach", "/path/to/directory", "--mcp"]}}} +{"mcpServers": {"webfront": {"type": "http", "url": "http://127.0.0.1:PORT/mcp", "headers": {"Authorization": "Bearer TOKEN"}}}} ``` +Donnez ce fichier au client MCP (`claude --mcp-config PATH/mcp.json`) et ne copiez jamais le jeton dans le projet. L'agent appelle ensuite `webfront.start` avec `create`, `preview` (après chaque modification, à la place de `wf dev`), `check`, `test` ou `embed`, et suit chaque exécution avec `webfront.result`. + Dans un projet consommateur, `webfront_write_agent_guide()` écrit un `AGENTS.md` à la racine ; `wf create` le place à côté des sources du starter. Le [guide des agents](docs/DEVELOPING_WITH_AGENTS.md) détaille ce contrat. ## Du C++ à une interface réactive @@ -346,7 +344,7 @@ La recompilation est explicite. L'application fonctionne ensuite hors ligne, san Un agent peut vérifier les types, construire, prévisualiser, inspecter et cliquer l'interface de **votre application**, dans sa fenêtre et avec ses callbacks C++. Rien n'est activé par défaut. -Transcription animée : découverte de session, vérification, compilation, aperçu, clic et appel d'un callback autorisé ; refus d'un callback privé +Transcription animée : connexion à l'URL MCP de l'application, vérification, compilation, aperçu, clic et appel d'un callback autorisé ; refus d'un callback privé *Transcription abrégée du test de régression `AutomationConsumerWindow`, exécuté sur une application réelle.* @@ -360,17 +358,16 @@ app.bootstrap("developer"); app.cppFunction("bf.render", render); auto automation = webfront::automation::enableAutomation( app, {.grants = {"check", "build", "preview", "inspect", "interact", "call"}, - .callbacks = {"bf.render"}, - .listen = privateEndpointDirectory}); + .callbacks = {"bf.render"}}); app.show(automation->launchPage()); automation->close(); app.shutdown(); ``` -- **Visible.** Le terminal annonce les autorisations et la manière de se connecter. -- **Découvrable.** `webfront-agent --list` liste les sessions partagées sans exposer leur secret de connexion ; `--print-mcp-config --attach ` génère la configuration du client MCP. `--schema` et `--agent-help` décrivent le contrat. +- **Visible.** L'application affiche son URL MCP, et le terminal annonce les autorisations. +- **Découvrable.** Chaque instance en cours publie son URL et le chemin de son `mcp.json` privé dans un enregistrement par utilisateur, jamais le jeton ; `claude --mcp-config PATH/mcp.json` ou tout client MCP s'y connecte. - **Borné.** Chaque opération demande son autorisation ; seuls les callbacks nommément déclarés sont appelables. Des délais natifs arrêtent un renderer bloqué. Le code du projet conserve les droits de l'utilisateur : ce n'est pas un sandbox. -- **Optionnel.** Sans `enableAutomation`, aucun endpoint n'est enregistré. `webfront_add_agent()` construit et installe le lanceur pour les consommateurs CMake. +- **Optionnel.** Sans `enableAutomation`, rien n'est enregistré et aucun port n'est ouvert ; une build de distribution (`WEBFRONT_DISTRIBUTION`) refuse de le compiler. Le [guide d'automation](docs/AUTOMATION.md#automating-your-own-application) décrit permissions, découverte, délais et profil MCP. diff --git a/README.md b/README.md index 33bbc334..011c7535 100644 --- a/README.md +++ b/README.md @@ -9,24 +9,25 @@ [![C++23](https://img.shields.io/badge/C%2B%2B-23-00599C)](CMakeLists.txt) [![Header-only](https://img.shields.io/badge/library-header--only-2EA043)](include/) -[English](README.md) · [Français](README.fr.md) +[English](README.md) · [Français](README.fr.md) · [简体中文](README.zh-CN.md) -WebFront is a **header-only C++23 library for building rich, modern user interfaces.** Keep application logic in C++ and create reactive interfaces with TypeScript, React and the existing JavaScript package ecosystem. WebFront brings UI development tools into your application: there is no separate TypeScript development environment to install. +WebFront is a C++ UI framework that produces modern, reactive interfaces. It is a header-only C++23 library: your application logic stays in C++, the UI is built with TypeScript, React and browser-compatible packages, and the finished application ships as a single executable. -WebFront has no dependencies and can be deployed on any device with a recent C++ standard library. +Your application can open its own development environment with `app.bootstrap("developer")`. In that window, `wf` builds and previews the UI, checks types and runs Jasmine tests. You can work in the terminal or let a coding agent drive the same workflow over MCP. Node.js and npm are unnecessary. + +When the UI is ready, embed its assets in the executable. This produces a compact, self-contained app that runs offline in a native window or via a web browser on embedded and headless systems. Game of Life walkthrough: the C++ application beside the WebFront window, where wf create life, dependency installation and wf preview bring the React interface up below the terminal The animation shows the C++ application and the Game of Life example, with terminal output and timing condensed and the preview expanded for readability. [Follow the walkthrough below ↓](#game-of-life-from-console-to-native-application) -- **Integrate into an existing application.** Keep your simulation, device control, SIMD computations, CUDA kernels... and worker threads in C++. Use a native window or even a web browser without surrendering your event loop. [Host integration →](docs/HOST_INTEGRATION.md) -- **Support human developers and coding agents.** The integrated `wf` tools compile, type-check, test and embed the UI. An opt-in MCP server and JSON CLI let coding agents operate your application's own window and run permitted checks and callbacks. [Agent workflow →](#developing-with-an-agent) +- **Develop with a coding agent.** Let it create the UI, install packages, preview, test and embed through MCP. With the permissions you grant, it can inspect the running application, interact with its interface and call selected C++ functions. [Agent workflow →](#developing-with-an-agent) · [Automation →](#let-an-agent-drive-your-application) +- **Build with locked dependencies.** The pinned developer environment is verified with SHA-512 and cached on first use. The project manifest and lockfile record the dependencies for your team and your agents. [Developer environment →](docs/DEVELOPER_ENVIRONMENT.md) +- **Give existing C++ software a UI.** Keep your event loop, worker threads, device control and SIMD or CUDA workloads. Open a native window or use the system browser, and run multiple applications or windows side by side. [Host integration →](docs/HOST_INTEGRATION.md) - **Move numerical data directly.** Typed arrays and packed bitsets cross a binary WebSocket bridge without JSON or base64 conversion. Coroutines, futures and senders connect asynchronous UI calls to native work. [Execution model →](docs/ASYNC_EXECUTION.md) -- **Build for distribution.** Embed assets, pin package versions and verify downloads; run the resulting application offline. CMake consumer targets and browser tests support repeatable builds and CI. [Integrate →](#use-webfront-in-your-project) · [Test →](#test-your-application) +- **Test and package your application.** Use the browser test runner and the public `webfront::bdd` framework alongside your CMake build. Embed the finished UI for offline distribution. [Integrate →](#use-webfront-in-your-project) · [Test →](#test-your-application) - **Choose your UI stack.** Use TypeScript, React and browser-compatible packages, or build DOM islands directly from C++. Optional forms and inspectors derive from C++ type descriptors. [DOM →](docs/DOM.md) · [React →](docs/REACT.md) · [Forms →](docs/FORMS.md) - - **Website and book: [webfront.fr](https://webfront.fr/en/)** · [The WebFront Book](https://webfront.fr/en/book/) · [Documentation](docs/) · [Changelog](docs/CHANGELOG.md) ## Platforms and deployment @@ -82,9 +83,9 @@ Scene: 960 × 720, four rays per pixel; window: 800 × 600 CSS pixels. Release b ## Find your starting point +- **Work with a coding agent:** [developer workflow](#developing-with-an-agent) and [application automation](#let-an-agent-drive-your-application). - **Evaluate the library:** [Hello World](#hello-world), then the [Game of Life walkthrough](#game-of-life-from-console-to-native-application). - **Add a UI to existing software:** [CMake integration](#use-webfront-in-your-project) and the [host loop example](examples/host-loop/HostLoop.cpp). -- **Work with a coding agent:** [developer workflow](#developing-with-an-agent) and [application automation](#let-an-agent-drive-your-application). - **Plan production:** [testing](#test-your-application), [contracts and limitations](#contracts-and-limitations) and [support status](docs/PROJECT_STATUS.md). ## Developing with an agent @@ -93,19 +94,18 @@ If you are a coding agent, or work with one, read this before anything else. The - **The model.** A WebFront application is a C++ program whose interface is TypeScript/TSX. The interface lives in **`ui/`** of the project directory (`ui/main.ts` or `ui/main.tsx`) and is developed with **`wf dev`**, in the terminal that `app.bootstrap("developer")` opens in the application's window. Pages of hand-written HTML and classic JavaScript served through `documentRoot` are not the development path: none of the tools apply to them. - **The sequence.** With the pinned developer environment: `wf create app` (the starter name, not your project's name), `wf init`, `wf install ` for browser dependencies, then `wf dev ui/main.ts`. Finish with `wf check`, `wf test` and `wf embed` using the project's configuration. Use `wf create life` for the React walkthrough. `wf help agents` prints the workflow. -- **An agent runs `wf` itself, in JSON or MCP.** Do not ask a person to type the commands. Configure with `-DWEBFRONT_BUILD_AUTOMATION=ON` to build `webfront-agent`; the application opts in with `webfront::automation::enableAutomation(app, {.grants = {...}, .listen = directory})`, whose grants stay the owner's; then: +- **An agent runs `wf` itself, through MCP.** Do not ask a person to type the commands. In a development build, the application opts in with `webfront::automation::enableAutomation(app, {.grants = {...}})`, whose grants stay the owner's, and becomes the MCP server: no other program is built or launched. It prints its URL and the path of a private client configuration (`mcp.json`, URL and Bearer token, outside the project): -```sh -webfront-agent --list # the sessions shared with agents -webfront-agent --attach DIRECTORY --operation create --starter app -webfront-agent --attach DIRECTORY --operation preview --entry ui/main.ts # after each edit, in place of wf dev -webfront-agent --print-mcp-config --attach DIRECTORY > .mcp.json # the same operations as an MCP server +```text +WebFront MCP (grants: check, build, preview): http://127.0.0.1:PORT/mcp - client configuration: .../sessions/SESSION/mcp.json ``` ```json -{"mcpServers": {"webfront": {"command": "/path/to/webfront-agent", "args": ["--attach", "/path/to/directory", "--mcp"]}}} +{"mcpServers": {"webfront": {"type": "http", "url": "http://127.0.0.1:PORT/mcp", "headers": {"Authorization": "Bearer TOKEN"}}}} ``` +Pass that file to the MCP client (`claude --mcp-config PATH/mcp.json`) and never copy the token into the project. The agent then calls `webfront.start` with `create`, `preview` (after each edit, in place of `wf dev`), `check`, `test` or `embed`, and reads each run with `webfront.result`. + In a project that embeds WebFront, `webfront_write_agent_guide()` writes these rules as `AGENTS.md` at its root, and `wf create` writes them beside the starter's sources. ## From C++ to a reactive UI @@ -386,7 +386,7 @@ Your own application can select `webfront::NativeApp` or `webfront::NativeAppWit Your coding agent can type-check, build, preview, inspect and click the interface of **your own application**, in its own window and with its own C++ callbacks, while you keep the window and decide what the agent may do. Nothing is on by default. -Animated transcript. On the left, an agent lists the shared session, checks, builds and previews the interface, clicks a button, calls the allow-listed C++ callback bf.render and is refused bf.secret. On the right, the application window shows the interface updating, and the C++ process logs only the callbacks that ran. +Animated transcript. On the left, an agent connects to the application's MCP URL, checks, builds and previews the interface, clicks a button, calls the allow-listed C++ callback bf.render and is refused bf.secret. On the right, the application window shows the interface updating, and the C++ process logs only the callbacks that ran. *Abridged transcript of the `AutomationConsumerWindow` regression test, which runs these steps against a real application.* @@ -400,17 +400,16 @@ app.bootstrap("developer"); app.cppFunction("bf.render", render); // your callbacks stay yours auto automation = webfront::automation::enableAutomation( app, {.grants = {"check", "build", "preview", "inspect", "interact", "call"}, - .callbacks = {"bf.render"}, // the only callback an agent may call - .listen = privateEndpointDirectory}); + .callbacks = {"bf.render"}}); // the only callback an agent may call app.show(automation->launchPage()); automation->close(); app.shutdown(); ``` -- **Visible to you.** The window's terminal prints the grants and how to attach, `wf help` says so, and the window title can carry a marker. -- **Found without being told.** `webfront-agent --list` shows the sessions their owners shared (never the capability), and `webfront-agent --print-mcp-config --attach ` writes the `.mcp.json` for Claude Code or any MCP client. `wf create` adds an `AGENTS.md` that tells the agent how to attach. +- **Visible to you.** The application prints its MCP URL, the window's terminal prints the grants, `wf help` says so, and the window title can carry a marker. +- **Found without being told.** Each running instance writes its URL and the path of its private `mcp.json` (URL and token) to a per-user record, never the token itself; `claude --mcp-config PATH/mcp.json` or any MCP client connects to it. `wf create` adds an `AGENTS.md` that tells the agent how to connect. - **Bounded.** Each operation is a separate grant; a callback is reachable only by an exact name you listed; a stuck renderer is stopped by native deadlines; project code still runs with your rights (this is not a sandbox). -- **Optional.** It lives in a separate launcher and one header; applications that do not call `enableAutomation` register nothing. `webfront_add_agent()` builds and installs the launcher for `add_subdirectory` and `FetchContent` consumers. +- **Optional.** It lives in one header; applications that do not call `enableAutomation` register nothing and open no listener, and a distribution build (`WEBFRONT_DISTRIBUTION`) refuses to compile it. The [automation guide](docs/AUTOMATION.md#automating-your-own-application) covers grants, callbacks, discovery, deadlines and the MCP profile. @@ -498,6 +497,8 @@ For explicit engine selection, `webfront_native_frontend_option(out)` and `webfr The optional [Jasmine and CTest integration](docs/CONSUMER_TESTING.md) runs browser specs against your application's page. Specs can capture PNG screenshots and image sequences, and can run native programs explicitly authorized by the test owner with `PROGRAMS`, using private temporary spaces for test files. The native-program browser integration is validated on Linux with CEF; see the guide for platform coverage and limitations. Authorized programs run with the user's permissions, so use trusted test code. +Your own C++ tests can use the framework of WebFront's tests: the public [`webfront::bdd`](docs/BDD.md) header, the `WebFront::Bdd` CMake target and `webfront_bdd_discover_tests()`, which registers one CTest case per scenario. + To select an embedded engine explicitly, `webfront::embeddedFrontendAvailable` reports whether one is compiled in and `webfront::EmbeddedWebFront` selects it. See [frontend selection](docs/FRONTENDS.md). ## Build and test @@ -526,7 +527,7 @@ CI exercises C++ and native-browser paths on Windows, macOS and Linux. Extended - Development project access is explicit and intended for trusted local code. Downloaded tools run with the application's bridge authority, and script permissions frame only the `context` API: neither is a sandbox. Only packages that run in a browser are supported; installation scripts and native add-ons are not executed. Builds transform TypeScript without type checking; `wf check` type-checks with the compiler the project locks. - An opt-in [native pseudoterminal](docs/PTY.md) connects an application-selected program to xterm.js on Linux, macOS and Windows. - The optional [`@webfront/react` adapter](docs/REACT.md) supplies coalesced C++ stores and empty React islands. `WebFrontLifeReact` demonstrates a C++ panel within the Game of Life React UI; its package archive is prepared locally for registry publication. -- Embedded Linux has ARM64 CI coverage and specific Orin Nano board evidence; other boards, bare-metal targets and microcontrollers are not generally qualified. Check C++23, memory, networking and browser requirements for your target. The default local transport supplies neither TLS nor client authentication; remote deployment needs an application-specific security design. +- Embedded Linux has ARM64 CI coverage and specific Orin Nano board evidence; other boards, bare-metal targets and microcontrollers are not generally qualified. Check C++23, memory, networking and browser requirements for your target. For HTTPS and WSS, see the [optional TLS listener and remote deployment recipe](docs/TLS.md). Client authentication is an application responsibility. - Packaging, accessibility and native-engine deployment still need application-specific work. The optional [`ui.document()` API](docs/DOM.md) provides DOM islands, automatically batched writes, event callbacks and grouped sender reads. See [project status](docs/PROJECT_STATUS.md) for known limitations. ## License diff --git a/README.zh-CN.md b/README.zh-CN.md new file mode 100644 index 00000000..af9b220b --- /dev/null +++ b/README.zh-CN.md @@ -0,0 +1,531 @@ +# WebFront + +[![CI](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml/badge.svg?branch=develop)](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml) +[![Windows · MSVC](https://img.shields.io/badge/CI-Windows%20%C2%B7%20MSVC-0078D4)](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml) +[![macOS · Apple Clang](https://img.shields.io/badge/CI-macOS%20%C2%B7%20Apple%20Clang-555555)](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml) +[![Linux · GCC](https://img.shields.io/badge/CI-Linux%20%C2%B7%20GCC-E95420)](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml) +[![Linux · aarch64](https://img.shields.io/badge/CI-Linux%20%C2%B7%20aarch64%20%C2%B7%20GCC%2013-E95420)](https://github.com/ambroise-leclerc/WebFront/actions/workflows/BuildAndTest.yml) +[![Jetson Orin](https://img.shields.io/badge/CI-Jetson%20Orin-76B900)](docs/JETSON.md) +[![C++23](https://img.shields.io/badge/C%2B%2B-23-00599C)](CMakeLists.txt) +[![Header-only](https://img.shields.io/badge/library-header--only-2EA043)](include/) + +[English](README.md) · [Français](README.fr.md) · [简体中文](README.zh-CN.md) + +WebFront 是一个 C++ UI 框架,用来构建现代、响应式的界面。它是纯头文件的 C++23 库:应用逻辑留在 C++ 中,界面使用 TypeScript、React 和兼容浏览器的第三方包构建,完成后的应用可以打包成一个可执行文件。 + +调用 `app.bootstrap("developer")`,应用就能打开自己的开发环境。在应用窗口中,`wf` 可以编译和预览界面、检查类型,并运行 Jasmine 测试。你可以在终端里操作,也可以让编程智能体通过 MCP 执行同样的流程。无需安装 Node.js 或 npm。 + +界面准备就绪后,将资源嵌入可执行文件。这样就能得到一个紧凑、自包含的应用,可在原生窗口中离线运行,也可在嵌入式系统和无图形会话的系统上通过 Web 浏览器离线使用。 + +[![生命游戏演示:在应用窗口里创建项目、安装依赖并预览 React 界面](docs/images/life-bootstrap.gif)](#从-c-模拟到可分发的生命游戏) + +动画展示 C++ 应用和生命游戏示例。为了便于阅读,终端输出和等待时间有所压缩,预览画面有所放大。[查看下方教程](#从-c-模拟到可分发的生命游戏)。 + +- **让编程智能体参与开发。** 智能体可通过 MCP 创建界面、安装依赖、预览、测试并嵌入资源。在你授予的权限范围内,它还可以检查正在运行的应用、操作界面并调用指定的 C++ 函数。 +- **锁定开发依赖。** 开发环境固定版本,经 SHA-512 校验后在首次使用时缓存。项目清单和锁文件记录团队与智能体共同使用的依赖。 +- **为现有 C++ 软件添加界面。** 保留事件循环、工作线程、设备控制和 SIMD 或 CUDA 计算。界面可以打开在原生窗口或系统浏览器中,也可以同时运行多个应用或窗口。见[宿主集成指南](docs/HOST_INTEGRATION.md)。 +- **直接传输数值数据。** 类型化数组和压缩位集通过二进制 WebSocket 桥接传输,无需转换成 JSON 或 Base64。见[异步执行模型](docs/ASYNC_EXECUTION.md)。 +- **测试并打包应用。** 在 CMake 构建之外,可使用浏览器测试运行器和公开的 `webfront::bdd` 框架。嵌入最终的界面资源后即可离线分发。见[项目集成](#集成到现有项目)和[应用测试](#测试你的应用)。 +- **自由选择界面技术。** 可以使用 React,也可直接用 C++ 创建 [DOM 岛](docs/DOM.md),或根据 C++ 类型描述生成[表单和检查器](docs/FORMS.md)。 + +**网站与书籍** · [webfront.fr](https://webfront.fr/en/) · [WebFront 一书](https://webfront.fr/en/book/) · [文档](docs/) · [更新记录](docs/CHANGELOG.md) + +## 平台与部署 + +| 目标平台 | 界面选项 | 验证范围 | +| --- | --- | --- | +| Windows | 系统浏览器、原生 WebView2、可选 CEF | MSVC 桌面 CI。WebView2 需要 Evergreen 运行时 | +| macOS 13.3 及以上(原生窗口) | 系统浏览器、系统 WKWebView、可选 CEF | AppleClang 桌面 CI | +| Linux | 系统浏览器、原生 WebKitGTK 6.0、可选 CEF | GCC 桌面 CI,另有 Clang 扩展验证 | +| Linux ARM64 / NVIDIA Jetson | 系统浏览器,以及平台支持的 WebKitGTK 或 CEF | GCC 13 ARM64 CI,并在 **Orin Nano Super 8 GB** 真机上验证。见 [Jetson 指南](docs/JETSON.md) | + +核心采用标准 C++ 设施和可替换的网络实现。使用默认的系统浏览器时,无需链接原生 GUI 工具包或 WebView 引擎。目标平台需要合适的 **C++23 编译器和标准库、操作系统提供的网络与线程支持,以及浏览器**。GCC 13 是尽力支持的最低版本。已验证的工具链和支持级别见[支持策略](docs/adr/ADR-022-profils-et-niveaux-de-support.md)。 + +**无需单独安装 WebFront 运行时。** 核心遵循标准 C++ 的网络与执行模型。在相关设施逐步标准化并由标准库实现的过程中,CMake 在构建时提供固定版本的替代实现,包括持续维护的网络层 `stdnet`,以及按需提供 sender 支持的 `stdexec`。WebFront 本身以头文件形式提供。原生 WebView 仍需满足各平台的要求,CEF 可选。开发工具和软件包首次使用时经验证后存入缓存,嵌入了界面的发行版无需该缓存和界面源码。 + +### CUDA 与嵌入式应用 + +在 NVIDIA Jetson Orin Nano 等设备上,可以继续用 C++ 编写 CUDA 计算代码。宿主循环或工作线程负责在 CPU 或 CUDA 上计算,Web 界面调整参数,并通过类型化数组接收和显示结果。如果 CUDA 编译器有此要求,请将 `.cu` 编译单元与用到 WebFront C++23 头文件的编译单元分开。纯 CPU 应用无需 CUDA 工具包。 + +内置的 [Boing Ball 示例](docs/HOST_LOOP_EXAMPLE.md)同时支持 CPU 和 CUDA。棋盘格球在可反射的地面上方弹跳,切换到有色玻璃材质后,可以看到反射、折射和彩色光束。C++ 宿主逐像素计算,页面在 Canvas 上显示结果。原生窗口和系统浏览器共用同一宿主循环。 + +![Jetson Orin Nano 原生窗口中的 CUDA Boing Ball 动画,从棋盘格球切换为透光玻璃球](docs/images/host-loop-boing.gif) + +```bash +cmake --build build --target WebFrontHostLoop --parallel 2 +build/examples/WebFrontHostLoop --quality 0 +# On a CUDA-equipped build and device: +build/examples/WebFrontHostLoop --engine cuda --glass --stats +``` + +从仓库根目录运行以上命令。Visual Studio 等多配置生成器的产物位于 `build/examples/Debug/`,以 `--config Release` 构建时则位于 `build/examples/Release/`。Windows 下的文件名是 `WebFrontHostLoop.exe`。 + +构建时会自动检测 CUDA。使用 `-DWEBFRONT_HOST_LOOP_CUDA=OFF` 可以在没有 CUDA 工具包时构建完整的 CPU 示例。运行时加上 `--browser` 可选择系统浏览器。质量选项、基准测试和单独的 CUDA 编译器配置见[示例指南](docs/HOST_LOOP_EXAMPLE.md)。 + +**Orin Nano Super 8 GB 真机验证**包括构建、CPU/CUDA 渲染、原生窗口和桥接测试,以及在沙箱中运行发行版的检查。受信任的[硬件验证工作流](docs/JETSON_RUNNER.md)补充了托管的 ARM64 CI。参阅[开发板验证](docs/JETSON.md)及[渲染测量](docs/HOST_LOOP_EXAMPLE.md)了解软件栈和覆盖范围。NX/AGX 和其他 JetPack 版本需要单独验证。上述结果未验证 WebKit 沙箱内的加速渲染。 + +Linux 上的 WebKitGTK 默认使用开发模式,沙箱处于关闭状态。分发时启用 `-DWEBFRONT_DISTRIBUTION=ON`,并在需要时随应用打包沙箱配置。见[开发与分发](docs/WEBKITGTK.md#development-and-distribution)。 + +## 性能设计 + +重计算留在原生代码中,界面只接收所需数据。数值缓冲区保留具体类型,位集保持压缩格式,桥接调用以异步方式执行。服务使用独立线程,计算循环和工作线程可以独立运行。可选的 React 适配器按浏览器合并 C++ 状态快照,DOM API 则批量提交写入。 + +这些机制有助于控制序列化、更新频率和界面开销。端到端性能仍取决于消息大小、渲染方式和目标硬件。应分别测量计算、传输和显示。关于各项工作所在的线程以及如何保持回调及时响应,见[执行指南](docs/ASYNC_EXECUTION.md)。 + +在 **25 W 的 Orin Nano Super 8 GB** 上,使用启用沙箱的 WebKitGTK 2.52.6 窗口,Boing Ball 的实测结果如下。 + +| 场景 | CPU(6 线程) | CUDA | +| --- | ---: | ---: | +| 不透明球 | 12 帧/秒 | 21 帧/秒 | +| 玻璃球和光束 | 约 0.6 帧/秒 | 12 帧/秒 | + +场景为 960 × 720,每像素四条光线,窗口为 800 × 600 CSS 像素。使用 Release 构建、GCC 13.3、CUDA 13.2.86 和 L4T R39.2.1。这些是该开发板上的实测值。[测量报告](docs/HOST_LOOP_EXAMPLE.md#system-browser-and-distribution-follow-up)分别统计计算、复制、传输和显示耗时,并比较系统浏览器与原生窗口。 + +## 从哪里开始 + +- **与编程智能体一起工作**。参阅[开发流程](#与编程智能体协作)和[应用自动化](#让智能体操作你的应用)。 +- **试用 WebFront**。从 [Hello World](#hello-world)开始,再体验[生命游戏教程](#从-c-模拟到可分发的生命游戏)。 +- **为现有软件添加界面**。参阅 [CMake 集成](#集成到现有项目)和[宿主循环示例](examples/host-loop/HostLoop.cpp)。 +- **准备投入生产**。参阅[测试](#测试你的应用)、[接口约定与限制](#接口约定与限制)和[支持状态](docs/PROJECT_STATUS.md)。 + +## 与编程智能体协作 + +使用编程智能体时,请先了解下面的开发流程。详细说明见[智能体开发指南](docs/DEVELOPING_WITH_AGENTS.md)。 + +- **项目结构。** WebFront 应用是带有 TypeScript/TSX 界面的 C++ 程序。将入口 `ui/main.ts` 或 `ui/main.tsx` 放在项目的 **`ui/`** 目录中。通过 `app.bootstrap("developer")` 打开应用内终端,再用 **`wf dev`** 开发界面。直接由 `documentRoot` 提供的手写 HTML 和普通 JavaScript 页面不在此工具链的处理范围内。 +- **开发步骤。** 在固定版本的开发环境中,运行 `wf create app`(`app` 是模板名)、`wf init` 和 `wf install `,再运行 `wf dev ui/main.ts`。准备交付时,按项目配置执行 `wf check`、`wf test` 和 `wf embed`。React 教程使用 `wf create life`。运行 `wf help agents` 可查看流程。 +- **智能体通过 MCP 自行运行 `wf`。** 在开发版中调用 `webfront::automation::enableAutomation(app, {.grants = {...}})` 后,应用即成为 MCP 服务端。应用所有者决定授权范围,无需另启程序。应用会输出地址和私有客户端配置 `mcp.json` 的路径。文件含地址和 Bearer 令牌,存放在项目之外。 + +```text +WebFront MCP (grants: check, build, preview): http://127.0.0.1:PORT/mcp - client configuration: .../sessions/SESSION/mcp.json +``` + +```json +{"mcpServers": {"webfront": {"type": "http", "url": "http://127.0.0.1:PORT/mcp", "headers": {"Authorization": "Bearer TOKEN"}}}} +``` + +把配置文件交给 MCP 客户端,例如运行 `claude --mcp-config PATH/mcp.json`。请勿把令牌复制到项目中。智能体通过 `webfront.start` 发起 `create`、`preview`、`check`、`test` 或 `embed`,再用 `webfront.result` 读取结果。每次修改后用 `preview` 代替终端中的 `wf dev`。 + +在集成 WebFront 的项目中,`webfront_write_agent_guide()` 将这些规则写入项目根目录的 `AGENTS.md`。`wf create` 也会在生成的源码旁写入这份指南。 + +## 从 C++ 到响应式界面 + +先注册模拟函数,再启动开发环境,最后在应用内终端中构建界面。`life-project` 是存放界面源码的工作目录。 + +
+动画中的 C++ 应用源码 + +```cpp +#include +#include + +using namespace std; +constexpr int N = 32; +using Grid = bitset; + +Grid nextLife(const Grid& cells) { + Grid next; + auto index = [](int x, int y) { + return size_t((y + N) % N * N + (x + N) % N); + }; + for (int y = 0; y < N; ++y) + for (int x = 0; x < N; ++x) { + int n = 0; + for (int dy = -1; dy <= 1; ++dy) + for (int dx = -1; dx <= 1; ++dx) + if (dx || dy) + n += cells[index(x + dx, y + dy)]; + auto i = index(x, y); + next[i] = n == 3 || (cells[i] && n == 2); + } + return next; +} + +int main() { + webfront::NativeApp app{"life-project"}; + app.cppFunction("life.step", &nextLife); + app.bootstrap("developer"); + app.show(); +} +``` + +
+ +## Hello World + +最小示例会提供内置页面,并用系统浏览器打开它。见 [HelloWorld.cpp](examples/hello-world/HelloWorld.cpp)。 + +```cpp +#include + +int main() { + webfront::WebFront app; + app.show(); +} +``` + +需要 Git、CMake **3.31+** 和支持 C++23 的编译器。首次配置、首次启动开发环境和首次安装包需要联网。下载完成后,开发环境和依赖会保留在缓存中。见[编译器支持策略](docs/adr/ADR-022-profils-et-niveaux-de-support.md)及 [LTS 发行版构建工具](#lts-发行版上的构建工具)。 + +```bash +mkdir build +cd build +cmake .. +cmake --build . +examples/HelloWorld +``` + +使用 Visual Studio 的多配置生成器时,运行 `examples\Debug\HelloWorld.exe`。如需 Release 版本,构建时传入 `--config Release`,再从 `examples\Release\` 启动。 + +在终端按 Enter 停止服务器。 + +同一个应用也能通过 [DOM API](docs/DOM.md) 直接在 C++ 中构建页面,无需另备界面文件。先注册处理函数,再调用 `show()`。服务器停止后,`show()` 才返回。 + +```cpp +#include + +int main() { + webfront::WebFront app; + app.onUIStarted([](auto ui) { + auto doc = ui.document(); + auto root = doc.island(); // default: "root" + auto button = doc.element("button"); + auto label = doc.text("Click me"); + button.append(label); + button.listen("click", [label](std::string) { label.setText("Clicked"); }); + root.append(button); + }); + app.show(); +} +``` + +## 从 C++ 模拟到可分发的生命游戏 + +生命游戏示例先用 C++ 计算,再添加 React 界面,最后将界面嵌入可执行文件。以下命令从上一步的 `build` 目录运行。 + +```bash +git clone https://github.com/ambroise-leclerc/WebFront.git +cd WebFront +mkdir build +cd build +cmake .. +cmake --build . +``` + +上面的构建无需额外选项。配置时如果找到本平台的原生窗口依赖,就会启用相应引擎。见[第 2 步](#2-打开应用内的开发环境)。使用 Visual Studio 等多配置生成器时,示例位于 `examples\Debug\`,传入 `--config Release` 后则位于 `examples\Release\`。 + +### 1. 运行 C++ 模拟 + +[Life.hpp](examples/life/Life.hpp) 在首尾相接的 32 × 32 网格上实现 Conway 生命游戏。每一代都用一个 `std::bitset<1024>` 表示。[LifeConsole.cpp](examples/life/LifeConsole.cpp) 可在终端中直接运行模拟。 + +```bash +examples/WebFrontLifeConsole +``` + +### 2. 打开应用内的开发环境 + +[LifeDeveloper.cpp](examples/life/LifeDeveloper.cpp) 注册模拟函数,并启动应用内的开发环境。 + +```cpp +#include "LifeFrontend.hpp" + +webfront::demo::LifeApp app{"life-project"}; +app.cppFunction("life.step", &webfront::demo::nextLife); +app.bootstrap("developer"); +app.show(); +``` + +```bash +examples/WebFrontLifeDeveloper +``` + +默认工作目录为 `build/life-project`。目录不存在时会创建,已存在时会原样复用。以下 `life-project/...` 路径都以该项目目录为基准。启动失败时示例返回非零退出状态。 + +`bootstrap("developer")` 打开集成终端,加载固定版本的开发环境并校验 SHA-512。下载内容会保留在缓存中,后续可离线启动。终端提供面向项目的 `wf` 命令,以及用于查看项目的 `ls`、`cat`、`tree` 和 `mounts`。终端不提供系统 Shell,宿主机也无需安装 JavaScript 工具链。 + +**原生窗口。** 配置时,CMake 会自动检测当前平台的原生引擎。 + +| 平台 | 引擎 | 检测条件 | +| --- | --- | --- | +| Windows | Microsoft Edge WebView2 Evergreen | 使用兼容 MSVC 的编译器。构建时下载 SDK,启动时检查 Evergreen 运行时 | +| macOS 13.3+ | 系统 Cocoa / WebKit | 使用 Clang,部署目标至少为 13.3 | +| Linux | WebKitGTK 6.0 | `pkg-config webkitgtk-6.0` 成功。见[安装说明](docs/WEBKITGTK.md) | + +macOS 使用系统 Cocoa 和 WebKit 框架打开 WKWebView,无需下载引擎。应用在主线程构造并调用 `show()`,HTTP/WebSocket 服务在独立线程上运行。关闭窗口后,服务停止,示例退出。显式选择低于 13.3 的部署目标会关闭 WKWebView 自动检测。在这种情况下手动启用 WKWebView 会导致配置失败。见 [macOS 指南](docs/WKWEBVIEW.md)。 + +找不到原生引擎时,配置仍会成功,并提示应安装哪些依赖。示例会使用系统浏览器打开同一个应用。安装所需依赖后重新运行 `cmake ..` 即可构建原生窗口版。设定 `-DWEBFRONT_EMBED_CEF=ON` 可以为自己的应用启用 `CEFFrontend`。这些示例使用平台原生引擎或系统浏览器。 + +
+原生引擎和开发环境的高级选项 + +- 用 `-DWEBFRONT_EMBED_WEBVIEW2=ON|OFF`、`-DWEBFRONT_EMBED_WKWEBVIEW=ON|OFF` 或 `-DWEBFRONT_EMBED_WEBKITGTK=ON|OFF` 手动选择。显式设置优先,`-DWEBFRONT_AUTODETECT_NATIVE=OFF` 可禁用自动检测。测试构建(`-DWEBFRONT_ENABLE_TESTING=ON`)保留显式选择。 +- 每次配置都会重新检测,自动检测的结果不会写入缓存中的引擎选项。要在 macOS 上恢复自动检测,请运行 `cmake .. -UWEBFRONT_EMBED_WKWEBVIEW`。其他平台可清除对应的引擎选项。 +- 也可用 `examples/WebFrontLifeDeveloper [ ]` 传入其他项目目录和环境归档,例如[从源码构建的环境](docs/DEVELOPER_ENVIRONMENT.md#environment-distribution-and-offline-tests-maintainers)。 + +
+ +Visual Studio 的示例可执行文件位于 `examples\Debug\`,Release 版本位于 `examples\Release\`。 + +### 3. 创建项目并安装依赖 + +在应用内终端中运行以下命令。 + +```text +wf create life +wf init +wf install react@19.3.1 react-dom@19.3.1 +wf dev ui/main.tsx +``` + +- `wf create life` 将可编辑的 [TSX 和 CSS 模板](examples/life/ui)写入 `ui/`,已有目录会保留。参数是模板名。`wf create app` 可为新项目生成最小的 TypeScript 界面。 +- `wf init` 写入 `webfront.project.json`。其他命令从该清单读取依赖、入口、资源提供器、脚本和权限。 +- `wf install` 从包仓库解析依赖,校验完整性,并将确切版本写入 `webfront-packages.lock.json`。安装过程不会执行软件包的安装脚本。`wf restore` 可在其他机器上按锁文件重建缓存,`wf restore --offline` 可离线验证缓存。 +- `wf dev` 用 esbuild-wasm 编译 TSX,在应用中打开界面,并在保存源码后重新构建。构建错误会显示在终端和预览上,预览保留最近一次成功的版本。按 Ctrl+C 停止。若只需编译一次,可运行 `wf build`。 + +用常用编辑器修改 `life-project/ui/main.tsx` 和 `style.css`。React 绘制网格和控件,每一代的计算都等待 C++ 回调完成。 + +```js +await webFront.ready; +const step = webFront.cppFunction('life.step'); +const next = await step(cells); +``` + +`cells` 和 `next` 都是 128 字节的 `Uint8Array`,对应 C++ 的 `std::bitset<1024>`,每字节从最低有效位开始。JavaScript 调用 C++ 始终返回 Promise,需等待结果或处理拒绝。生命游戏的规则由 C++ 执行。 + +### 4. 运行测试并检查类型 + +`wf test` 用锁文件指定的 `jasmine-core` 版本在应用窗口中运行 [Jasmine](https://jasmine.github.io/) 测试。安装依赖,创建 `life-project/tests/life.spec.js`,并在 `webfront.project.json` 中列出该文件。`wf init` 不会复制模板的测试配置。 + +```js +describe('the Life grid', () => { + it('packs 32 by 32 cells into 128 bytes, least significant bit first', () => { + const cells = new Uint8Array(32 * 32 / 8); + for (const i of [330, 331, 332]) cells[i >> 3] |= 1 << (i & 7); + expect(cells.length).toBe(128); + expect(cells[41]).toBe(0b00011100); + }); +}); +``` + +```text +wf install jasmine-core@7.0.2 +``` + +```json +"test": {"specs": ["tests/life.spec.js"]} +``` + +```text +wf test +``` + +测试失败时,命令返回非零退出状态。 + +构建时会移除 TypeScript 类型,但不会进行类型检查。`wf check` 在浏览器中运行项目锁定版本的 TypeScript 编译器。它需要 `tsconfig.json` 和导入项的类型声明包。模板和集成测试使用以下配置。 + +```json +{ + "compilerOptions": { + "strict": true, + "target": "ES2022", + "module": "ESNext", + "moduleResolution": "Bundler", + "jsx": "react-jsx", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "noEmit": true + }, + "include": ["ui"] +} +``` + +运行 `wf install typescript@5.9.3 @types/react@19.3.0 @types/react-dom@19.3.0` 安装类型相关依赖,然后运行 `wf check`。见[开发环境参考](docs/DEVELOPER_ENVIRONMENT.md)。 + +### 5. 体验界面 + +![原生窗口中的生命游戏](docs/images/life-preview.jpg) + +可以播放、暂停、单步演进、绘制细胞、切换图案、调整速度或切换到俯视图。代数和活细胞计数来自 C++ 模拟。同一时刻最多有一个演进请求。请求失败时,播放停止,界面显示错误。 + +### 6. 嵌入界面以供分发 + +在 `webfront.project.json` 中声明入口和资源提供器(`"entries": {"main": "ui/main.tsx"}` 和 `"providers": {"LifeUI": {"entry": "main", "output": "generated/LifeUI.hpp"}}`),也可以在应用内终端中直接传入参数。 + +```text +wf embed ui/main.tsx --output generated/LifeUI.hpp +``` + +此命令构建界面,并将资源和依赖许可声明打包到压缩的 C++ 头文件中。关闭开发窗口,然后在原来的 `build` 目录中重新配置。此前选择的引擎会保留。 + +```bash +cmake .. -DWEBFRONT_LIFE_ASSETS="$PWD/life-project/generated/LifeUI.hpp" +cmake --build . --target WebFrontLifeEmbedded +examples/WebFrontLifeEmbedded +``` + +使用 Visual Studio 时,运行 `examples\Debug\WebFrontLifeEmbedded.exe`。 + +[LifeEmbedded.cpp](examples/life/LifeEmbedded.cpp) 用生成的资源提供器替代开发项目和 bootstrap 调用。 + +```cpp +#include "LifeFrontend.hpp" + +webfront::demo::LifeAppWithAssets app; +app.cppFunction("life.step", &webfront::demo::nextLife); +app.show(); +``` + +重新生成资源后需重新编译。最终应用可以离线运行,无需项目目录、开发回调或已下载的工具缓存,仍需满足所选原生引擎的部署要求。安装包由应用自行制作。 + +两个阶段均由 [LifeFrontend.hpp](examples/life/LifeFrontend.hpp) 选择 `NativeOrBrowserFrontend`。构建中包含原生引擎且存在可用的图形会话时,使用原生窗口,否则使用默认浏览器。需要明确使用原生窗口时,自己的应用可以选择 `webfront::NativeApp` 或 `webfront::NativeAppWithAssets`。 + +## 让智能体操作你的应用 + +编程智能体可以在**你的应用**自己的窗口中检查类型、构建、预览和检查界面,点击控件,并调用你授权的 C++ 回调。你保留对窗口和权限的控制。自动化默认关闭。 + +左侧智能体通过应用的 MCP 地址检查、构建和预览界面,点击按钮,调用已授权的 bf.render,随后被拒绝调用 bf.secret。右侧应用窗口更新,C++ 进程只记录实际执行的回调。 + +*这是 `AutomationConsumerWindow` 回归测试的节选。测试在真实应用中执行这些步骤。* + +在 C++ 中调用以下接口启用自动化,权限由你在原生代码中设定。 + +```cpp +#include + +webfront::NativeApp app{project}; +app.bootstrap("developer"); +app.cppFunction("bf.render", render); // your callbacks stay yours +auto automation = webfront::automation::enableAutomation( + app, {.grants = {"check", "build", "preview", "inspect", "interact", "call"}, + .callbacks = {"bf.render"}}); // the only callback an agent may call +app.show(automation->launchPage()); +automation->close(); +app.shutdown(); +``` + +- **可见。** 应用输出 MCP 地址,窗口中的终端显示授权信息,`wf help` 也会提示。还可以在窗口标题中加上标记。 +- **可发现。** 各运行实例将地址和私有 `mcp.json` 的路径写入用户级记录。令牌存于配置文件,不出现在发现记录里。可用 `claude --mcp-config PATH/mcp.json` 或兼容的 MCP 客户端连接。`wf create` 生成的 `AGENTS.md` 会说明连接方法。 +- **有明确边界。** 每项操作单独授权,回调只可通过列出的确切名称调用。原生代码用超时机制停止卡住的渲染器。项目代码仍以用户权限执行,自动化不提供沙箱。 +- **按需启用。** 接口集中在一个头文件中。未调用 `enableAutomation` 的应用不会注册自动化功能或监听连接。发行构建(`WEBFRONT_DISTRIBUTION`)禁止编译此功能。 + +权限、回调、发现机制、超时和 MCP 配置见[自动化指南](docs/AUTOMATION.md#automating-your-own-application)。 + +## 生产项目功能 + +除基本桥接外,WebFront 还提供[由应用管理生命周期的协程及取消机制](docs/ASYNC_EXECUTION.md)、向已连接浏览器广播消息、[C++ DOM 岛](docs/DOM.md)、[表单及 TypeScript 声明](docs/FORMS.md),以及可选的 [React store 和 `Island` 适配器](docs/REACT.md)。各组件可独立采用,核心无需 React。 + +版本历史、迁移说明和破坏性变更见[更新记录](docs/CHANGELOG.md)。为生产环境选择平台或前端前,可查看[项目状态](docs/PROJECT_STATUS.md)中的验证范围和限制。 + +## LTS 发行版上的构建工具 + +独立构建和通过 `add_subdirectory` 或 CPM 集成都要求 CMake **3.31+**,即使关闭测试也是如此。Ubuntu 22.04 自带 CMake 3.22.1,Ubuntu 24.04 自带 3.28.3,请先升级 CMake。Ubuntu 22.04 自带的 Git 2.34.1 可以运行仓库的提交检查。统一最低版本的依据见[工具链决策与审查](docs/adr/ADR-022-profils-et-niveaux-de-support.md#outils-de-construction-distributions-lts-527)。可选的 mddlog 有[独立要求](docs/mddlog-integration.md)。 + +可以使用隔离的 Python 环境。Ubuntu 上如有需要,请先运行 `sudo apt-get install python3-venv`,然后执行以下命令。 + +```bash +python3 -m venv "$HOME/.local/share/webfront-tools" +"$HOME/.local/share/webfront-tools/bin/python" -m pip install 'cmake>=3.31,<4' +export PATH="$HOME/.local/share/webfront-tools/bin:$PATH" +cmake --version +ctest --version +``` + +安装这份 CMake 不需要 root 权限。每次打开构建 Shell 时运行 `export PATH=...`,或将其加入 Shell 配置,以选用配套的 `cmake` 和 `ctest`。也可按 Ubuntu 版本使用 [Kitware APT 仓库](https://apt.kitware.com/)安装。升级 CMake 后,Ubuntu 22.04 默认的 GCC 11 仍需换成支持策略列出的工具链。 + +## 集成到现有项目 + +WebFront 的实现位于 `include/`。CMake 提供所需的 C++ 依赖和平台配置。WebFront 以头文件提供,无需生成库二进制文件。 + +```cmake +add_subdirectory(path/to/WebFront) +add_executable(MyApp main.cpp) +target_link_libraries(MyApp PRIVATE WebFront::WebFront) +``` + +作为子项目使用时,示例和测试默认关闭,WebFront 的编译选项不会影响你的目标。独立构建也可通过 `WEBFRONT_BUILD_EXAMPLES=OFF` 关闭示例。 + +
+GCC 16 与 C++ 模块扫描 + +在 CMake 扫描 C++ 模块并添加 `-fmodules-ts` 时,GCC 16 会在 stdexec 的 `__query.hpp` 中发生内部编译器错误(段错误)。对于 Ninja 上的 C++20 及更高版本目标,CMake 默认会扫描模块(CMP0155)。WebFront 仅使用头文件,不需要模块扫描。对链接 WebFront 且不使用 C++ 模块的目标,可在创建目标后关闭模块扫描。 + +```cmake +add_executable(MyApp main.cpp) +target_link_libraries(MyApp PRIVATE WebFront::WebFront) +webfront_disable_module_scan(MyApp) +``` + +如果项目中的所有目标都不使用 C++ 模块,也可以在创建目标前设置 `set(CMAKE_CXX_SCAN_FOR_MODULES OFF)`。否则 CMake 无法确定模块的编译顺序。显式设置源文件扫描属性或包含 `CXX_MODULES` 文件集的目标仍会被扫描。 + +用 GCC 16 将 WebFront 配置为子项目并保留扫描时,CMake 会列出受影响的目标及相应的解决方法。 + +
+ +`webfront::WebFront` 始终使用系统浏览器。若要和生命游戏示例一样使用原生窗口并保留浏览器回退,可在链接目标后添加以下调用。它也适用于 `CPMAddPackage`。 + +```cmake +webfront_use_native_window(MyApp) +``` + +在 `main.cpp` 中根据辅助函数定义的宏选择应用类型。 + +```cpp +#include + +#if defined(WEBFRONT_NATIVE_WINDOW) +using App = webfront::WebFrontWithFrontend; +#else +using App = webfront::WebFront; +#endif + +int main() { + App app; + app.show(); +} +``` + +若要在有图形会话时打开原生窗口,并在没有可用显示环境时(例如 SSH、容器或 CI)回退到系统浏览器,可使用 `WebFrontWithFrontend`。这个类型无需 `#if`,回退原因只输出一次。见[前端选择](docs/FRONTENDS.md)。 + +除了 WebFront 自身的测试和模糊测试构建(`WEBFRONT_ENABLE_TESTING=ON` 或 `WEBFRONT_ENABLE_FUZZING=ON`),CMake 默认自动检测原生引擎。父项目的 `ENABLE_TESTING` 和 `ENABLE_FUZZING` 不影响检测或 WebFront 的测试。启用引擎后,辅助函数为目标配置引擎并定义 `WEBFRONT_NATIVE_WINDOW`。否则,CMake 会给出安装提示,应用使用默认浏览器。Windows 需要兼容 MSVC 的编译器,CMake 会下载固定版本的 WebView2 SDK。Evergreen 运行时需单独安装。Linux 需要 WebKitGTK 6.0 开发文件,macOS 需要 Clang 和 macOS 13.3 或更高版本。显式设置的 `WEBFRONT_EMBED_=ON|OFF` 优先,`WEBFRONT_AUTODETECT_NATIVE=OFF` 可禁用自动检测。默认流程无需在 `add_subdirectory` 或 CPM 之前设置选项。 + +父项目或其他目录也可以调用 `webfront_native_frontend_option(out)` 和 `webfront_setup_frontends_for_target(MyApp)` 来显式配置引擎。后者为目标配置所有已启用的引擎,原生窗口辅助函数只选择当前平台的原生引擎。见 [WKWebView](docs/WKWEBVIEW.md)、[WebKitGTK](docs/WEBKITGTK.md) 和[架构决策](docs/adr/README.md)。 + +## 测试你的应用 + +可选的 [Jasmine 与 CTest 集成](docs/CONSUMER_TESTING.md)在浏览器中针对应用页面运行测试。测试可以捕获 PNG 截图和图像序列,也可通过 `PROGRAMS` 运行测试所有者明确授权的原生程序,并用私有临时目录存放测试文件。运行原生程序的浏览器集成在 Linux CEF 上验证,平台范围和限制见指南。授权程序以用户权限运行,请使用可信的测试代码。 + +C++ 测试可以使用 WebFront 自己采用的公开框架 [`webfront::bdd`](docs/BDD.md)。链接 `WebFront::Bdd` CMake 目标,并调用 `webfront_bdd_discover_tests()`,可为每个场景注册一项 CTest 测试。 + +要显式选择嵌入式引擎,可用 `webfront::embeddedFrontendAvailable` 判断构建是否包含这类引擎,并用 `webfront::EmbeddedWebFront` 选择它。见[前端选择](docs/FRONTENDS.md)。 + +## 构建和测试 + +```bash +cmake -S . -B build -DCMAKE_BUILD_TYPE=Release \ + -DWEBFRONT_EMBED_CEF=OFF -DWEBFRONT_ENABLE_TESTING=ON +cmake --build build --parallel 2 +ctest --test-dir build --output-on-failure --parallel 4 +``` + +启用测试时,配置步骤会下载固定版本的 bootstrap 环境和测试包仓库的包,并校验 SHA-512。嵌入资源仅用 CMake 生成和检查,可通过 `webfront-embedded-assets` 目标重新生成。常规 C++ 构建使用版本库中的头文件。浏览器测试需要启用引擎,Linux 上的 CEF 测试使用 Xvfb。见 [AGENTS.md](AGENTS.md) 和[开发环境测试](docs/DEVELOPER_ENVIRONMENT.md#environment-distribution-and-offline-tests-maintainers)。 + +上面的 CTest 命令最多并行运行四项任务。独立的驱动会话使用操作系统分配的端口,共享项目与嵌套构建使用资源锁。见[测试耗时与并行](docs/TEST_PERFORMANCE.md)。`ctest -L fast` 约一秒内运行快速单元测试。[测试分层](docs/TEST_TIERS.md)说明了每次拉取请求、每周以及合并到 `master` 前运行的检查。 + +CI 在 Windows、macOS 和 Linux 上验证 C++ 与原生浏览器路径。扩展任务覆盖 Clang、sanitizer、模糊测试、CEF 和 Linux ARM64,包括 ARM64 上的 CEF 与 WebKitGTK 浏览器测试。具体调度、工具链及选项见[测试分层](docs/TEST_TIERS.md)和 [CI 工作流](.github/workflows/BuildAndTest.yml)。托管的 ARM64 验证与 [Jetson 真机验证](docs/JETSON.md)分别进行。各平台徽章标明验证矩阵,CI 徽章反映总体状态。 + +## 接口约定与限制 + +- WebFront 在后台线程运行 HTTP/WebSocket 服务,回调在该线程逐个执行,避免在回调中阻塞线程。从任意线程都可以调用浏览器函数(`jsFunction`、`app.broadcast(name)(...)`),这些调用不会等待服务器线程。WKWebView、WebKitGTK 和 CEF 等前端通常要求在主线程创建并显示窗口,WebView2 可使用次线程。保留自身循环的应用可使用 `app.start()`(打开系统浏览器并立即返回)、`app.requestClose()` 或 `webfront::UIThread`。应用协程使用 `app.spawn(task)` 或 `ui.spawn(task)`。见[线程规则](docs/ASYNC_EXECUTION.md#threads)、[宿主集成](docs/HOST_INTEGRATION.md)及[异步执行与取消](docs/ASYNC_EXECUTION.md)。 +- JavaScript 调用 C++ 始终返回 Promise。C++ 调用 JavaScript 时,`ui.jsFunction(name)(...)` 只发出调用,`ui.jsFunction(name)(...)` 则返回 `std::future`。函数不存在、异常、答复格式错误或连接断开都会使带返回类型的调用失败。 +- 二进制桥接支持标量、字符串、元组、数值类型化数组、压缩位集及受支持的复合值的同构列表。任意对象不能通过桥接传输。字符串和消息受消息大小策略限制,默认上限为 64 MiB。达到 65,536 字节的字符串使用长字符串编码。见[二进制桥接约定](docs/adr/ADR-003-protocole-binaire-et-bornes.md)。 +- 开发项目需显式开放访问,适用于可信本地代码。下载的工具拥有应用的桥接权限,脚本授权仅约束 `context` API,两者均不提供沙箱。只支持能在浏览器中运行的包,安装脚本和原生扩展不会执行。编译 TypeScript 时只转换代码,类型检查由 `wf check` 使用项目锁定版本的编译器单独运行。 +- 可选的[原生伪终端](docs/PTY.md)在 Linux、macOS 和 Windows 上将应用指定的程序连接到 xterm.js。 +- 可选的 [`@webfront/react` 适配器](docs/REACT.md)提供合并更新的 C++ store 和空的 React 岛。`WebFrontLifeReact` 演示了在生命游戏的 React 界面中嵌入 C++ 面板。用于发布到包仓库的归档在本地生成。 +- 嵌入式 Linux 有 ARM64 CI 和特定 Orin Nano 真机验证。其他开发板、裸机和微控制器没有通用的验证覆盖。请确认目标的 C++23、内存、网络和浏览器要求。HTTPS 和 WSS 见[可选 TLS 监听器及远程部署说明](docs/TLS.md)。客户端身份验证由应用负责。 +- 打包、无障碍和原生引擎部署仍需按应用处理。可选的 [`ui.document()` API](docs/DOM.md)提供 DOM 岛、自动批量写入、事件回调,以及使用 sender 的分组读取。已知限制见[项目状态](docs/PROJECT_STATUS.md)。 + +## 许可证 + +WebFront 采用 **Apache-2.0 或 CECILL-B** 双许可证,可任选其一使用、修改和再分发。[LICENSE](LICENSE) 包含 Apache 2.0 和 CeCILL-B 第 1 版全文,后者提供英语和法语版本。 + +第三方组件保留各自的许可证和声明。WebFront 的许可选择不改变其依赖项或随附第三方代码的许可。 + +[网站](https://webfront.fr/en/) · [书籍](https://webfront.fr/en/book/) · [开发环境参考](docs/DEVELOPER_ENVIRONMENT.md) · [架构决策](docs/adr/README.md) · [贡献指南](.github/CONTRIBUTING.md) diff --git a/cmake/CompilerWarnings.cmake b/cmake/CompilerWarnings.cmake index dee493ad..b7b86734 100644 --- a/cmake/CompilerWarnings.cmake +++ b/cmake/CompilerWarnings.cmake @@ -31,6 +31,7 @@ function(set_project_warnings project_name) /w14906 # string literal cast to 'LPWSTR' /w14928 # illegal copy-initialization; more than one user-defined conversion has been implicitly applied /wd4714 # '__forceinline' function not inlined: stdexec's coroutine helpers, which are not ours to change + /wd4737 # 'Unable to perform required tail call': MSVC cannot chain the long awaits of the TLS handshake coroutines; a performance note only /analyze # Enable Code Analysis /analyze:external- # Disable Code Analysis for external headers /analyze:stacksize65536 # Raise C6262 stack warning threshold to 64KB (policy buffers can reach 32KB); one argument, as sccache reads a separate "65536" as a second source file and refuses to cache the compilation diff --git a/cmake/Frontends.cmake b/cmake/Frontends.cmake index 158a1491..e3be7621 100644 --- a/cmake/Frontends.cmake +++ b/cmake/Frontends.cmake @@ -439,7 +439,7 @@ function(webfront_add_browser_tests target frontend assets_directory lifecycle_t set(lifecycle_command "${XVFB_RUN_EXECUTABLE}" -a ${lifecycle_command}) endif() set(lifecycle_modes no-bridge early-close rejected-ready navigation-failure path-encoding content-policy navigation-allow-list view-association stage-report) - list(APPEND lifecycle_modes ui-executor native-window second-open host-close) + list(APPEND lifecycle_modes ui-executor native-window second-open host-close second-window) # CEF neither supports nor checks a secondary thread: nothing to observe there (docs/HOST_INTEGRATION.md). if(NOT frontend STREQUAL "CEF") list(APPEND lifecycle_modes host-thread) diff --git a/cmake/WKWebViewSupport.cmake b/cmake/WKWebViewSupport.cmake index 7daf2dbc..1ddeb91f 100644 --- a/cmake/WKWebViewSupport.cmake +++ b/cmake/WKWebViewSupport.cmake @@ -18,7 +18,7 @@ function(webfront_add_wkwebview_tests) add_executable(wkwebview_lifecycle "${webtest_source_dir}/WKWebViewLifecycle.cpp" "${webtest_source_dir}/WKWebViewHeaderConsumer.cpp") target_link_libraries(wkwebview_lifecycle PRIVATE WebFront WebFront_warnings WebFront_options) - foreach(mode repeated-show main-thread native-close quit navigation-diagnostic startup-timeout settings translucent-background hidden-scheduling redirect-policy missing-response committed-navigation agent-application download choose-file cancel-choose replaced-download choose-in-blank choose-in-srcdoc close-with-open-panel close-with-save-panel script-dialogs close-with-script-dialog sandboxed-script-dialog load-reveal present-timeout) + foreach(mode repeated-show main-thread native-close quit navigation-diagnostic startup-timeout settings translucent-background hidden-scheduling hidden-secondary redirect-policy missing-response committed-navigation agent-application download choose-file cancel-choose replaced-download choose-in-blank choose-in-srcdoc close-with-open-panel close-with-save-panel script-dialogs close-with-script-dialog sandboxed-script-dialog load-reveal present-timeout) add_test(NAME WKWebViewLifecycle-${mode} COMMAND wkwebview_lifecycle ${mode}) webfront_set_browser_test_properties("WKWebViewLifecycle-${mode}" "${webtest_source_dir}" 90) endforeach() diff --git a/cmake/WebFrontAgent.cmake b/cmake/WebFrontAgent.cmake deleted file mode 100644 index 73f5107f..00000000 --- a/cmake/WebFrontAgent.cmake +++ /dev/null @@ -1,36 +0,0 @@ -# Public helper for a project that embeds WebFront with add_subdirectory() or FetchContent. -include_guard(GLOBAL) - -# webfront_add_agent([INSTALL] [DESTINATION dir]) -# -# The optional `webfront-agent` launcher is built by WebFront itself, from the same sources and with the engine the -# parent chose, when WEBFRONT_BUILD_AUTOMATION is ON and an embedded frontend is enabled. Set both before WebFront is -# added: -# -# set(WEBFRONT_BUILD_AUTOMATION ON) -# set(WEBFRONT_EMBED_WEBVIEW2 ON) # or WKWEBVIEW, CEF, WEBKITGTK -# FetchContent_MakeAvailable(WebFront) -# webfront_add_agent(INSTALL) -# -# This function then checks that the target exists, with an explicit error otherwise (no engine is ever chosen -# silently), and with INSTALL installs the executable (default DESTINATION: bin). An installed CEF launcher still needs -# the engine's runtime files beside it, which this helper does not install. The agent drives an application that -# enables automation itself (webfront::automation::enableAutomation, docs/AUTOMATION.md); it grants nothing alone. -function(webfront_add_agent) - cmake_parse_arguments(ARG "INSTALL" "DESTINATION" "" ${ARGN}) - if(ARG_UNPARSED_ARGUMENTS OR ARG_KEYWORDS_MISSING_VALUES) - message(FATAL_ERROR "webfront_add_agent: invalid arguments (unknown: ${ARG_UNPARSED_ARGUMENTS}; keywords without a value: ${ARG_KEYWORDS_MISSING_VALUES})") - endif() - if(NOT TARGET webfront-agent) - message(FATAL_ERROR - "webfront_add_agent: the webfront-agent target does not exist. Set WEBFRONT_BUILD_AUTOMATION=ON and enable " - "one embedded frontend (WEBFRONT_EMBED_WEBVIEW2, WEBFRONT_EMBED_WKWEBVIEW, WEBFRONT_EMBED_CEF or " - "WEBFRONT_EMBED_WEBKITGTK) before adding WebFront.") - endif() - if(ARG_INSTALL) - if(NOT ARG_DESTINATION) - set(ARG_DESTINATION bin) - endif() - install(TARGETS webfront-agent RUNTIME DESTINATION "${ARG_DESTINATION}") - endif() -endfunction() diff --git a/cmake/WebFrontAgentGuide.cmake b/cmake/WebFrontAgentGuide.cmake index 45593716..b73d3dff 100644 --- a/cmake/WebFrontAgentGuide.cmake +++ b/cmake/WebFrontAgentGuide.cmake @@ -8,7 +8,7 @@ include_guard(GLOBAL) # # Writes the agent guide of a WebFront application (the same text `wf create` puts beside a starter's sources) as # AGENTS.md at the root of the calling project: the model (C++ with a TypeScript/TSX interface in ui/, developed with -# `wf dev`) and how an agent runs wf itself in JSON or MCP. Coding agents read that file before anything else. +# `wf dev`) and how an agent runs wf itself through the MCP URL of the application. Coding agents read that file first. # # add_subdirectory(WebFront) # or FetchContent / CPM # webfront_write_agent_guide() # /AGENTS.md, once @@ -47,8 +47,8 @@ function(webfront_write_agent_guide) message(STATUS "WebFront: wrote the agent guide ${destination}") endfunction() -# One notice per configuration, for whoever reads the configure output first: the development model, the guide, and -# either how to attach to the launcher that is built or the option that builds it. +# One notice per configuration, for whoever reads the configure output first: the development model, the guide, and how an +# application serves MCP to an agent. function(webfront_announce_agent_support) get_property(announced GLOBAL PROPERTY WEBFRONT_AGENT_SUPPORT_ANNOUNCED) if(announced) @@ -57,14 +57,8 @@ function(webfront_announce_agent_support) set_property(GLOBAL PROPERTY WEBFRONT_AGENT_SUPPORT_ANNOUNCED ON) set(guide "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/../docs/DEVELOPING_WITH_AGENTS.md") cmake_path(NORMAL_PATH guide) - if(TARGET webfront-agent) - set(launcher "the webfront-agent target runs wf for an agent in JSON or MCP (webfront-agent --agent-help)") - else() - set(launcher "webfront-agent, which runs wf for an agent in JSON or MCP, is not built: " - "configure with -DWEBFRONT_BUILD_AUTOMATION=ON") - string(JOIN "" launcher ${launcher}) - endif() message(STATUS "WebFront for agents: an application is C++ with a TypeScript/TSX interface in ui/, developed with `wf dev` " - "(not pages served from documentRoot); ${launcher}. Guide: ${guide}" + "(not pages served from documentRoot); an application that calls webfront::automation::enableAutomation serves MCP " + "itself and prints its URL. Guide: ${guide}" "; webfront_write_agent_guide() writes it as AGENTS.md in your project.") endfunction() diff --git a/cmake/WebFrontBdd.cmake b/cmake/WebFrontBdd.cmake new file mode 100644 index 00000000..f585645e --- /dev/null +++ b/cmake/WebFrontBdd.cmake @@ -0,0 +1,241 @@ +# SPDX-License-Identifier: Apache-2.0 OR CECILL-B +# Registers the scenarios of a webfront::bdd test executable in CTest, one case per scenario, named "Scenario: ". +# This is the public counterpart of Catch2's catch_discover_tests (docs/BDD.md); its name and options follow WebFront's +# versions (docs/CHANGELOG.md). Obtain it with the WebFront::Bdd target: +# +# find_package(WebFrontBdd REQUIRED) # an installed WebFront +# # or add_subdirectory()/CPM/FetchContent of WebFront, which defines WebFront::Bdd and includes this file +# target_link_libraries(my_tests PRIVATE WebFront::Bdd) +# webfront_bdd_discover_tests(my_tests [TEST_PREFIX <prefix>] [PROPERTIES <name> <value>...] +# [SHARDS <n> [SHARD_NAME <name>] [JUNIT_PREFIX <path>]]) +# +# TEST_PREFIX text put before "Scenario: " in each case name; refused with SHARDS (use SHARD_NAME). +# PROPERTIES properties of every case (TIMEOUT, LABELS, ENVIRONMENT...). A skipped scenario exits with 4, which the +# cases treat as SKIP_RETURN_CODE; a SKIP_RETURN_CODE of yours replaces it. +# SHARDS registers <n> cases instead, each running a share of the scenarios in declaration order in one process +# (`--order decl --shard-count <n> --shard-index <i>`), which saves the start of one process per scenario. +# They are named <SHARD_NAME>-<i> (default "<target>Shards") and write a JUnit report to +# <JUNIT_PREFIX>-<i>.xml (default "${CMAKE_CURRENT_BINARY_DIR}/<target>-results"). +# +# After each build of the target, the executable lists its scenarios (`--list`) and this file, run as a script, writes the +# add_test() calls that CTest includes. Each case runs `<target> --exact <title>`, through the CROSSCOMPILING_EMULATOR of the +# target when it has one (which also lists the scenarios at build time). + +# A bracket argument whose delimiter occurs neither in the value nor at the junction with its own closing bracket. +function(bdd_quote out value) + set(equals "==") + string(LENGTH "${value}" length) + while(TRUE) + string(FIND "${value}]${equals}]" "]${equals}]" position) + if(position EQUAL length) + break() + endif() + string(APPEND equals "=") + endwhile() + set(${out} "[${equals}[${value}]${equals}]" PARENT_SCOPE) +endfunction() + +# Values travel in CMake lists, which a ';', a backslash before the next ';', or an unpaired bracket would split or join +# wrongly: they are escaped as percent codes, "%" first so that a value which holds a code of its own comes back unchanged. +function(bdd_escape out value) + string(REPLACE "%" "%25" value "${value}") + string(REPLACE ";" "%3B" value "${value}") + string(REPLACE "\\" "%5C" value "${value}") + string(REPLACE "[" "%5B" value "${value}") + string(REPLACE "]" "%5D" value "${value}") + set(${out} "${value}" PARENT_SCOPE) +endfunction() +function(bdd_unescape out value) + string(REPLACE "%3B" ";" value "${value}") + string(REPLACE "%5C" "\\" value "${value}") + string(REPLACE "%5B" "[" value "${value}") + string(REPLACE "%5D" "]" value "${value}") + string(REPLACE "%25" "%" value "${value}") + set(${out} "${value}" PARENT_SCOPE) +endfunction() + +if(CMAKE_SCRIPT_MODE_FILE) + # The generated file holds the properties and, once escaped where needed, what the build knows (the executable, its + # emulator, the output and the prefix): on a command line, a ';' in any of them would split the argument. + # Keep properties in a generated file too: passing shell metacharacters through a Windows post-build command is unreliable. + include("${PROPERTIES_FILE}") + if(DEFINED bdd_executable_file) + # Those two hold nothing but the value, written by file(GENERATE): a path may hold any text, brackets included. + file(READ "${bdd_executable_file}" EXECUTABLE) + file(READ "${bdd_emulator_file}" EMULATOR) + set(OUTPUT "${bdd_output}") + bdd_unescape(PREFIX "${bdd_prefix}") + endif() + # With CMAKE_CROSSCOMPILING_EMULATOR the executable cannot run alone: the emulator lists the scenarios and runs each case. + execute_process(COMMAND ${EMULATOR} "${EXECUTABLE}" --list OUTPUT_VARIABLE titles ERROR_VARIABLE errors RESULT_VARIABLE result) + if(NOT result EQUAL 0) + message(FATAL_ERROR "${EMULATOR} ${EXECUTABLE} --list failed (${result}): ${errors}") + endif() + set(command_prefix) + # The emulator is a list of words; the executable is one value, whatever its path holds (a ';' included). + foreach(word IN LISTS EMULATOR) + bdd_quote(quoted "${word}") + string(APPEND command_prefix " ${quoted}") + endforeach() + bdd_quote(quoted "${EXECUTABLE}") + string(APPEND command_prefix " ${quoted}") + set(quoted_properties) + foreach(property IN LISTS properties) + bdd_unescape(property "${property}") + bdd_quote(quoted "${property}") + string(APPEND quoted_properties " ${quoted}") + endforeach() + bdd_escape(titles "${titles}") + string(REPLACE "\n" ";" titles "${titles}") + set(content "") + foreach(title IN LISTS titles) + if(title STREQUAL "") + continue() + endif() + bdd_unescape(title "${title}") + bdd_quote(quoted_name "${PREFIX}Scenario: ${title}") + bdd_quote(quoted_title "${title}") + string(APPEND content "add_test(${quoted_name}${command_prefix} --exact ${quoted_title})\n" + "set_tests_properties(${quoted_name} PROPERTIES SKIP_RETURN_CODE 4${quoted_properties})\n") + endforeach() + file(WRITE "${OUTPUT}" "${content}") + return() +endif() + +function(webfront_bdd_discover_tests target) + # The arguments are read here, not by cmake_parse_arguments, which keeps the values of PROPERTIES in a list: there a value + # that ends with a backslash merges with its neighbour, one that equals a keyword ends the list. PROPERTIES takes pairs, so + # a keyword is one only where a name is expected; each value is kept escaped (bdd_escape) from here on. + set(keywords "TEST_PREFIX|SHARDS|SHARD_NAME|JUNIT_PREFIX|PROPERTIES") + set(escaped_properties) + set(index 1) + while(index LESS ARGC) + set(word "${ARGV${index}}") + math(EXPR value_index "${index} + 1") + if(word MATCHES "^(TEST_PREFIX|SHARDS|SHARD_NAME|JUNIT_PREFIX)$") + if(value_index GREATER_EQUAL ARGC) + message(FATAL_ERROR "webfront_bdd_discover_tests: ${word} needs a value") + endif() + set(arg_${word} "${ARGV${value_index}}") + set(index ${value_index}) + math(EXPR index "${index} + 1") + elseif(word STREQUAL "PROPERTIES") + set(index ${value_index}) + while(index LESS ARGC) + set(word "${ARGV${index}}") + if(word MATCHES "^(${keywords})$") + break() + endif() + math(EXPR value_index "${index} + 1") + if(value_index GREATER_EQUAL ARGC) + message(FATAL_ERROR "webfront_bdd_discover_tests: PROPERTIES takes pairs of a name and a value, '${word}' has none") + endif() + bdd_escape(name "${word}") + bdd_escape(value "${ARGV${value_index}}") + list(APPEND escaped_properties "${name}" "${value}") + math(EXPR index "${index} + 2") + endwhile() + else() + message(FATAL_ERROR "webfront_bdd_discover_tests: unknown argument: ${word}") + endif() + endwhile() + list(LENGTH escaped_properties property_count) + if(NOT TARGET ${target}) + message(FATAL_ERROR "webfront_bdd_discover_tests: ${target} is not a target") + endif() + if(NOT DEFINED arg_SHARDS AND (arg_SHARD_NAME OR arg_JUNIT_PREFIX)) + message(FATAL_ERROR "webfront_bdd_discover_tests: SHARD_NAME and JUNIT_PREFIX apply only with SHARDS") + endif() + if(DEFINED arg_SHARDS) + if(arg_TEST_PREFIX) + message(FATAL_ERROR "webfront_bdd_discover_tests: TEST_PREFIX does not apply to SHARDS; name the shards with SHARD_NAME") + endif() + if(NOT arg_SHARDS MATCHES "^[1-9][0-9]*$") + message(FATAL_ERROR "webfront_bdd_discover_tests: SHARDS must be a positive integer, not '${arg_SHARDS}'") + endif() + if(NOT arg_SHARD_NAME) + set(arg_SHARD_NAME "${target}Shards") + endif() + if(NOT arg_JUNIT_PREFIX) + set(arg_JUNIT_PREFIX "${CMAKE_CURRENT_BINARY_DIR}/${target}-results") + endif() + math(EXPR last_shard "${arg_SHARDS} - 1") + foreach(shard RANGE ${last_shard}) + add_test(NAME ${arg_SHARD_NAME}-${shard} + COMMAND ${target} --order decl --shard-count ${arg_SHARDS} --shard-index ${shard} + --junit "${arg_JUNIT_PREFIX}-${shard}.xml") + # A shard whose every scenario is skipped exits with 4, as a single scenario does; a SKIP_RETURN_CODE of + # PROPERTIES, listed after this one, takes precedence. + set_tests_properties(${arg_SHARD_NAME}-${shard} PROPERTIES SKIP_RETURN_CODE 4) + if(property_count GREATER 0) + math(EXPR last_property "${property_count} - 2") + foreach(position RANGE 0 ${last_property} 2) + math(EXPR value_position "${position} + 1") + list(GET escaped_properties ${position} property_name) + list(GET escaped_properties ${value_position} property_value) + bdd_unescape(property_name "${property_name}") + bdd_unescape(property_value "${property_value}") + set_tests_properties(${arg_SHARD_NAME}-${shard} PROPERTIES "${property_name}" "${property_value}") + endforeach() + endif() + endforeach() + return() + endif() + get_property(already TARGET ${target} PROPERTY WEBFRONT_BDD_DISCOVERED) + if(already) + message(FATAL_ERROR "webfront_bdd_discover_tests: ${target} is already registered; a second call would overwrite the first one's cases (SHARDS calls can accompany it)") + endif() + set_property(TARGET ${target} PROPERTY WEBFRONT_BDD_DISCOVERED TRUE) + set(base "${CMAKE_CURRENT_BINARY_DIR}/${target}") + set(properties_file "${base}_properties-$<CONFIG>.cmake") + get_property(multi_config GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) + if(multi_config) + set(output "${base}_tests-$<CONFIG>.cmake") + string(CONCAT include_content "if(EXISTS \"${base}_tests-\${CTEST_CONFIGURATION_TYPE}.cmake\")\n" + " include(\"${base}_tests-\${CTEST_CONFIGURATION_TYPE}.cmake\")\n" + "else()\n" + " add_test([==[${target}_NOT_BUILT]==] [==[${target}_NOT_BUILT]==])\n" + "endif()\n") + else() + set(output "${base}_tests.cmake") + string(CONCAT include_content "if(EXISTS \"${output}\")\n include(\"${output}\")\n" + "else()\n add_test([==[${target}_NOT_BUILT]==] [==[${target}_NOT_BUILT]==])\nendif()\n") + endif() + # The properties and the prefix go into the file escaped (no bracket, backslash or ';' of theirs can change how CMake reads + # it) and the script that discovers the cases unescapes them. A change of any of them makes the file newer than the cases + # generated from it. + bdd_escape(escaped_prefix "${arg_TEST_PREFIX}") + # The executable and its emulator are only known when the build system is generated, and may hold any text: each is alone + # in a file that the script reads, rather than inside an argument with a delimiter that its value could close. + set(executable_file "${base}_executable-$<CONFIG>.txt") + set(emulator_file "${base}_emulator-$<CONFIG>.txt") + file(GENERATE OUTPUT "${executable_file}" CONTENT "$<TARGET_FILE:${target}>") + file(GENERATE OUTPUT "${emulator_file}" CONTENT "$<TARGET_PROPERTY:${target},CROSSCOMPILING_EMULATOR>") + bdd_quote(quoted_executable_file "${executable_file}") + bdd_quote(quoted_emulator_file "${emulator_file}") + bdd_quote(quoted_output "${output}") + string(CONCAT properties_content + "set(properties [==[${escaped_properties}]==])\n" + "set(bdd_executable_file ${quoted_executable_file})\n" + "set(bdd_emulator_file ${quoted_emulator_file})\n" + "set(bdd_output ${quoted_output})\n" + "set(bdd_prefix [==[${escaped_prefix}]==])\n") + file(GENERATE OUTPUT "${properties_file}" CONTENT "${properties_content}") + set(discovery_command "${CMAKE_COMMAND}" "-DPROPERTIES_FILE=${properties_file}" -P "${CMAKE_CURRENT_FUNCTION_LIST_FILE}") + # Right after each build of the target, so that building it alone registers its cases... + add_custom_command(TARGET ${target} POST_BUILD COMMAND ${discovery_command} VERBATIM) + # ...and when only the properties, the prefix or the emulator changed, the executable is linked again (Makefile and Ninja + # generators) so that this command runs when the target alone is built. The target below does the same for a complete + # build with any generator, unless the executable is excluded from it: discovery must not bring it back (the property is + # read here, so set EXCLUDE_FROM_ALL before this call). + set_property(TARGET ${target} APPEND PROPERTY LINK_DEPENDS "${properties_file}" "${emulator_file}") + add_custom_command(OUTPUT "${output}" COMMAND ${discovery_command} DEPENDS ${target} "${properties_file}" "${emulator_file}" VERBATIM) + get_property(excluded TARGET ${target} PROPERTY EXCLUDE_FROM_ALL) + set(with_all) + if(NOT excluded) + set(with_all ALL) + endif() + add_custom_target(${target}_bdd_discovery ${with_all} DEPENDS "${output}") + file(WRITE "${base}_include.cmake" "${include_content}") + set_property(DIRECTORY APPEND PROPERTY TEST_INCLUDE_FILES "${base}_include.cmake") +endfunction() diff --git a/cmake/WebFrontBddConfig.cmake.in b/cmake/WebFrontBddConfig.cmake.in new file mode 100644 index 00000000..d36c6de8 --- /dev/null +++ b/cmake/WebFrontBddConfig.cmake.in @@ -0,0 +1,7 @@ +@PACKAGE_INIT@ + +# WebFront::Bdd, the BDD test framework of WebFront (docs/BDD.md), and webfront_bdd_discover_tests(). +include(CMakeFindDependencyMacro) +find_dependency(Threads) +include("${CMAKE_CURRENT_LIST_DIR}/WebFrontBddTargets.cmake") +include("${CMAKE_CURRENT_LIST_DIR}/WebFrontBdd.cmake") diff --git a/cmake/WebFrontBddTarget.cmake b/cmake/WebFrontBddTarget.cmake new file mode 100644 index 00000000..25d21ce9 --- /dev/null +++ b/cmake/WebFrontBddTarget.cmake @@ -0,0 +1,34 @@ +# SPDX-License-Identifier: Apache-2.0 OR CECILL-B +# WebFront::Bdd, the public test framework (include/webfront/testing/Bdd.hpp, docs/BDD.md), and its installation as the +# WebFrontBdd package. The target needs neither WebFront nor stdnet: a project can test with it alone. +include(GNUInstallDirs) +include(CMakePackageConfigHelpers) + +# Threads: Bdd.hpp runs the waits of requireEventually and uses <thread>. +find_package(Threads REQUIRED) +add_library(WebFront_Bdd INTERFACE) +add_library(WebFront::Bdd ALIAS WebFront_Bdd) +set_target_properties(WebFront_Bdd PROPERTIES EXPORT_NAME Bdd) +target_compile_features(WebFront_Bdd INTERFACE cxx_std_23) +target_link_libraries(WebFront_Bdd INTERFACE Threads::Threads) +target_include_directories(WebFront_Bdd INTERFACE + $<BUILD_INTERFACE:${CMAKE_CURRENT_LIST_DIR}/../include> + $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>) +# Defines webfront_bdd_discover_tests() for the parent project as well. The function reads no variable of this directory +# (it locates its script with CMAKE_CURRENT_FUNCTION_LIST_FILE): it runs with the variables of its caller. +include("${CMAKE_CURRENT_LIST_DIR}/WebFrontBdd.cmake") + +# A project that embeds WebFront owns its own installation: only the top-level project installs the package. +if(WEBFRONT_IS_TOP_LEVEL) + set(_bdd_cmake_dir "${CMAKE_INSTALL_LIBDIR}/cmake/WebFrontBdd") + install(TARGETS WebFront_Bdd EXPORT WebFrontBddTargets COMPONENT WebFrontBdd) + install(FILES "${CMAKE_CURRENT_LIST_DIR}/../include/webfront/testing/Bdd.hpp" + DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}/webfront/testing" COMPONENT WebFrontBdd) + install(EXPORT WebFrontBddTargets NAMESPACE WebFront:: DESTINATION "${_bdd_cmake_dir}" COMPONENT WebFrontBdd) + configure_package_config_file("${CMAKE_CURRENT_LIST_DIR}/WebFrontBddConfig.cmake.in" + "${CMAKE_CURRENT_BINARY_DIR}/WebFrontBddConfig.cmake" INSTALL_DESTINATION "${_bdd_cmake_dir}") + write_basic_package_version_file("${CMAKE_CURRENT_BINARY_DIR}/WebFrontBddConfigVersion.cmake" + VERSION ${PROJECT_VERSION} COMPATIBILITY SameMajorVersion ARCH_INDEPENDENT) + install(FILES "${CMAKE_CURRENT_BINARY_DIR}/WebFrontBddConfig.cmake" "${CMAKE_CURRENT_BINARY_DIR}/WebFrontBddConfigVersion.cmake" + "${CMAKE_CURRENT_LIST_DIR}/WebFrontBdd.cmake" DESTINATION "${_bdd_cmake_dir}" COMPONENT WebFrontBdd) +endif() diff --git a/cmake/WebView2Support.cmake b/cmake/WebView2Support.cmake index 2229dbd1..81e76eaf 100644 --- a/cmake/WebView2Support.cmake +++ b/cmake/WebView2Support.cmake @@ -66,7 +66,8 @@ function(webfront_add_webview2_tests) target_link_libraries(webview2_lifecycle PRIVATE WebFront WebFront_warnings WebFront_options) foreach(mode repeated-show native-early-close navigation-diagnostic mta missing-runtime closed-startup-timeout failed-startup-timeout late-navigation-failure runtime-ready - file-choose file-cancel file-download script-dialogs first-frame present-timeout) + file-choose file-cancel file-download script-dialogs first-frame present-timeout + secondary-startup-timeout) add_test(NAME WebView2Lifecycle-${mode} COMMAND webview2_lifecycle ${mode}) webfront_set_browser_test_properties("WebView2Lifecycle-${mode}" "${webtest_source_dir}" 45) endforeach() diff --git a/cmake/mddlog/Logger.cpp b/cmake/mddlog/Logger.cpp index 96123a70..addc7f6c 100644 --- a/cmake/mddlog/Logger.cpp +++ b/cmake/mddlog/Logger.cpp @@ -1,4 +1,12 @@ -/** @brief WebFront-owned module-consuming TU; the facade header remains independent of modules. */ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-01 +// +// WebFront — build/mddlog +// Role: WebFront-owned module-consuming translation unit implementing the logger facade over mddlog; the facade header stays independent of modules. +// Thread: thread-safe | Alloc: unrestricted +// LLM: compiled only when modules are available; keep module types out of LoggerApi.hpp + import std; import mddlog.core.loglevel; import mddlog.adapter.textlogger; @@ -307,7 +315,7 @@ RingClaim::~RingClaim() { /** @brief Stops the consumer during static destruction, before the text adapter it may use. */ struct LaneShutdown { - explicit LaneShutdown(TransportLane& value) : lane(&value) {} + explicit LaneShutdown(TransportLane& value) : lane(&value) { } LaneShutdown(const LaneShutdown&) = delete; LaneShutdown& operator=(const LaneShutdown&) = delete; LaneShutdown(LaneShutdown&&) = delete; @@ -503,15 +511,15 @@ TransportHandle addTransport(std::function<void(const TransportRecord&)> write) const auto text = renderTransportText(record); try { write({.level = facadeLevel(record.level), - .timeAvailable = record.timeAvailable, - .time = std::chrono::time_point_cast<std::chrono::nanoseconds>(record.timestamp), - .location = record.location, - .message = record.message, - .messageTruncated = record.messageTruncated, - .component = record.category, - .operationId = record.operationId, - .correlationId = record.correlationId, - .text = text}); + .timeAvailable = record.timeAvailable, + .time = std::chrono::time_point_cast<std::chrono::nanoseconds>(record.timestamp), + .location = record.location, + .message = record.message, + .messageTruncated = record.messageTruncated, + .component = record.category, + .operationId = record.operationId, + .correlationId = record.correlationId, + .text = text}); } catch (...) { // TransportConsumer detaches this transport and counts the failure. static_cast<void>(lane.detach(*attached)); diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index 82f1893d..1b2fae73 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -1,208 +1,113 @@ -# Developer automation and local MCP +# Developer automation and MCP -WebFront's optional `webfront-agent` opens a developer window and exposes a bounded native -controller through either a JSON CLI operation or MCP on stdio. The terminal remains available -in the window. Both interfaces use the same wf dispatcher and reject overlapping commands. -Normal applications and embedded distributions acquire no automation callbacks or listener. +An application that opts in with `enableAutomation` exposes a bounded native controller of its own developer window and +serves it over MCP itself, with Streamable HTTP on a loopback listener of its own +([ADR-025](adr/ADR-025-mcp-http-dans-l-application.md)). There is no other program: the application is the MCP server, and +an MCP client connects to the URL it prints. The terminal remains available in the window; the agent and the person use the +same wf dispatcher, which rejects overlapping commands. Applications that do not call `enableAutomation` register nothing and +open no listener, and automation does not compile in a distribution build. -The launcher can own a window or attach to a human-owned developer window explicitly opened for -sharing. It does not discover arbitrary running applications, open an HTTP endpoint, or export the -bridge as MCP. Applications can explicitly integrate `automation::Binding` with their own controller. -A session ID routes operations and prevents accidental cross-session requests; it is not an -authentication secret. The opt-in native attachment channel uses a separate OS-generated capability. +A session ID routes operations and prevents accidental cross-session requests; it is not an authentication secret. The MCP +listener is authenticated by a separate Bearer token generated by the OS. New to WebFront, or an agent about to write an application? Start with [developing with an agent](DEVELOPING_WITH_AGENTS.md): -the model (C++ with a TypeScript/TSX interface in `ui/`), the development loop and the JSON and MCP form of each `wf` command. +the model (C++ with a TypeScript/TSX interface in `ui/`), the development loop and the MCP form of each `wf` command. This page is the reference. For testing a consumer's own page through CTest, see [consumer testing](CONSUMER_TESTING.md). That independent API is available in this tree; MCP is unnecessary for CI to run Jasmine. -## Building and provisioning +## Enabling automation -Enable an embedded frontend and the launcher. An application build needs only `-DWEBFRONT_BUILD_AUTOMATION=ON`: the native -engine of the platform is detected. Each configuration prints one `WebFront for agents:` line that says whether the launcher -is built, and `webfront_write_agent_guide()` writes the agent guide as `AGENTS.md` in a project that embeds WebFront -(never replacing an existing file). A test build selects its engine explicitly; for example, on macOS: +An application that wants to be driven opts in explicitly; it keeps its callbacks, and check/build/test/preview/inspect/ +interact run in **its** window. It must have called `bootstrap("developer")` (the developer environment is hosted in its +page), and it needs an environment with automation API v1 (0.6.3 or later; the setup operations `init`, `create`, `install`, +`restore` and `embed` need 0.6.4, `call` needs 0.6.6). The environment the library pins has all of them. -```sh -cmake -S . -B build-agent -DCMAKE_BUILD_TYPE=Release \ - -DWEBFRONT_EMBED_WKWEBVIEW=ON -DWEBFRONT_BUILD_AUTOMATION=ON -DWEBFRONT_ENABLE_TESTING=ON -cmake --build build-agent --target webfront-agent webfront-wf --parallel 2 -``` +```cpp +#include <webfront/automation/Enable.hpp> -Select WebView2 on Windows or CEF/WebKitGTK on Linux with their existing CMake options. -`WEBFRONT_AUTOMATION_FRONTEND` chooses the enabled engine when several are available. Browser -test configurations also build the launcher for their regression tests. Without an enabled -embedded engine, requesting the launcher fails configure instead of opening a system browser. -The implementation is native C++23; no Node.js, npm or Python is required to run the launcher. - -Provision an environment containing automation API v1 (0.6.3 or later). The setup operations (`init`, `create`, `install`, -`restore`, `embed`) need environment **0.6.4 or later**, which must be published (see the [0.6.4 publication gate](validation/developer-0.6.4-release.md)) before anything depending on this pin is merged: the launcher checks this at startup, and granting one of them to an -older environment fails with a bootstrap error (status 70) naming the operation, instead of failing each run. -`create` needs the starter archives (`<name>-starter.tgz`, such as `app-starter.tgz` and `life-starter.tgz` of a distribution build) in the same -directory as the `--environment` archive: the launcher serves only files of that name from there, and the environment's -manifest pins their SHA-512, so the directory is not trusted for content. Environment 0.6.2 -predates that API; passing an older environment produces a bootstrap error with status 70. -The launcher takes an explicit archive and its independently trusted SHA-512 SRI. Use a verified -published distribution or build one in this repository: - -```sh -build-agent/test/web/webfront-wf --project "$PWD" --manifest-dir js/developer -- restore -build-agent/test/web/webfront-wf --project "$PWD" --manifest-dir js/developer -- run build build-distribution +webfront::NativeApp app{project}; +app.bootstrap("developer"); +app.cppFunction("bf.render", render); // stays available to the previewed page +auto automation = webfront::automation::enableAutomation(app, {.grants = {"check", "build", "inspect", "interact"}}); +app.show(automation->launchPage()); // the single-use claim selects this window +automation->close(); // revokes the session, closes the listener, removes the files +app.shutdown(); ``` -`build-distribution/provision.json` gives the resulting integrity. Project packages must also be -installed/restored beforehand through wf, or by an agent granted `install`/`restore`. Tests use configure-provisioned packages and a local registry, with no public network -after provisioning. This source build does not publish a release or change the pinned bootstrap. +The call prints one line on stderr (disable it with `announce = false`), and the window's terminal shows it too: -## Invocation and authority +```text +WebFront MCP (grants: check, build, inspect, interact): http://127.0.0.1:PORT/mcp - client configuration: <private directory>/mcp.json +``` -`webfront-agent --schema` prints the trusted JSON Schema contract v1 without opening a browser. -`webfront-agent --agent-help` prints small, on-demand instructions for CLI agents, including local -models that do not need a tool catalogue in every prompt. `automation/Contract.hpp` contains the -single versioned contract for argument definitions, per-operation permissions/required fields, -result/error vocabulary and limits. Native validation, CLI argument discovery and MCP's start -schema project that contract; transport choice cannot grant additional operations. The native -validator enforces the documented schema subset plus path containment and byte limits. +`automation->mcpUrl()`, `automation->clientConfiguration()` and `automation->directory()` give the same information to the +code, and `automation->windowTitle(base)` returns a title marked as shared. Nothing is registered unless `enableAutomation` is +called, and the grants and project are fixed there by the native owner: the agent, the page and the project manifest cannot +change them. -```sh -webfront-agent --project /absolute/project \ - --environment /absolute/environment.tgz --integrity sha512-TRUSTED_DIGEST \ - --allow check --allow build --allow test --allow preview --allow inspect --allow interact --mcp -``` +| Option | Default | Meaning | +| --- | --- | --- | +| `grants` | none | The granted operations: `check`, `build`, `test`, `preview`, `inspect`, `interact` (click/fill), `call`, and the setup grants `init`, `create`, `install`, `restore`, `embed`. None leaves only session discovery. | +| `callbacks` | none | The application callbacks `call` may invoke, by exact name (see below). | +| `mcpPort` | 0 | The port of the listener; 0 lets the OS choose. A chosen port is never replaced: when it is taken the activation throws a `std::system_error` that names the address, the port and the cause. | +| `mcpToken` | absent | An application-supplied Bearer token, retained across launches if the application supplies the same value. Absent selects a fresh random token per session. Use a long random secret outside the project. | +| `disableMcpAuthentication` | false | Explicitly allow local clients without a Bearer token. Cannot be combined with `mcpToken`. | +| `directory` | a new directory named after the session in the discovery directory | A new private directory outside the project for `mcp.json`. | +| `discovery` | the per-user sessions directory | Where the record goes (tests use their own). | +| `timeout` | 120 s | The native deadline of one operation. | +| `startupTimeout` | 120 s | How long the window may take to claim the session. | +| `closeGrace` | 5 s | How long a revoked window may take to close before `onUnresponsive`. | +| `onUnresponsive` | ends the process with status 72 | What to do with a window that did not close. | + +For a client configured once, set `mcpPort` to a fixed nonzero port and supply the same `mcpToken` on every launch, for example from a private environment variable read by the application. Copy the URL and Authorization header from the first `mcp.json` into the client's **user** configuration, outside the project. Start the application before connecting; retry after starting it if the connection is refused. Rotate the token by changing the application-supplied value and updating the client. A second instance can use the default options; a second listener on the chosen port fails explicitly. -All executable operations are denied unless granted by the process owner using `--allow`. -Valid grants are `check`, `build`, `test`, `preview`, `inspect`, `interact` (click/fill) and the project setup -grants `init`, `create`, `install`, `restore` and `embed`. The setup grants write the manifest, the lock, the cache, a new -starter directory or the generated provider header; grant them only for a project whose registry you trust. -The project, environment, manifest directory and grants cannot be changed by MCP or the manifest. -Omit grants to expose session discovery only. In particular, there is no agent tool for shell, -JavaScript evaluation, arbitrary callback calls, `wf run`, `exec` or arbitrary -native file reads/writes. `install` and `restore` use the registry already configured by the owner, the manifest or the -default; the operation cannot choose another one. An agent edits project files through its separately authorized workspace -tools, then asks WebFront to verify them. - -`--manifest-dir` selects a project-relative manifest directory. `--registry-dir` serves an -explicit local registry for bootstrap/project tooling. `--timeout` sets the native per-operation limit and `--startup-timeout` separately bounds -bootstrap (both default to 120 seconds, 1–3600); progress does not extend either deadline. Each process owns -an automation session, but browser storage isolation depends on the frontend: - -| Frontend | Browser storage used by the launcher | -| --- | --- | -| CEF on Linux | Separate temporary profile directory | -| WebView2 on Windows | Separate temporary user-data directory | -| WKWebView on macOS | Engine's default shared website data store; no per-process storage isolation | -| WebKitGTK on Linux | Default WebFront XDG data/cache directories; shared between launches | - -The launcher's temporary directory is used as a profile only by CEF/WebView2. Cleanup is attempted -on normal and watchdog exits; this does not erase WKWebView/WebKitGTK's shared stores. An independent -process is not a browser-storage or hostile-code sandbox. Use `xvfb-run -a` on headless Linux. - -## Sharing a window already open for a human - -The human first launches the window with a new private endpoint directory and explicit grants: - -```sh -webfront-agent --project /absolute/project \ - --environment /absolute/environment.tgz --integrity sha512-TRUSTED_DIGEST \ - --allow check --allow build --allow test --allow preview --allow inspect --allow interact \ - --serve --listen /absolute/private-session +```cpp +const char* token = std::getenv("MY_APP_MCP_TOKEN"); +if (!token || !*token) + throw std::runtime_error("Set MY_APP_MCP_TOKEN to a private random token"); +auto automation = webfront::automation::enableAutomation( + app, {.grants = {"check", "build"}, .mcpPort = 19002, .mcpToken = std::string{token}}); ``` -The window and its terminal stay open independently of an agent. To connect later: +The application includes `<cstdlib>`, `<stdexcept>` and `<string>` for this example; MSVC reports `std::getenv` as deprecated (C4996), so use `_dupenv_s` or define `_CRT_SECURE_NO_WARNINGS` there. A configured token must be 32–1024 visible ASCII characters without spaces; length alone does not guarantee randomness. To opt in to an unauthenticated listener instead, use `.disableMcpAuthentication = true` and omit `mcpToken`; its client configuration has no Authorization header. In that mode any Authorization header, including an incorrect Bearer, is ignored. -```sh -webfront-agent --attach /absolute/private-session --mcp -webfront-agent --attach /absolute/private-session --operation check -webfront-agent --attach /absolute/private-session --operation test --pattern passing -``` +The startup banner warns when authentication is disabled. It appears on stderr and, once the window connects, in the developer terminal. With `announce = false` there is no stderr warning; the terminal still receives the banner when it connects, and `automation->banner()` still returns it. -The attached CLI and MCP clients operate on that same native controller and existing window. -They cannot replace the project or change its grants. Multiple attached clients share the run -history and busy/cancel rules. Closing an attached client's stdin detaches it and leaves the human -window open. The owner can close its window normally, or explicitly run -`webfront-agent --attach /absolute/private-session --shutdown` to revoke the session and close it. - -Native attachment is an opt-in JSON-line channel over an OS-assigned **127.0.0.1-only TCP port**, -not MCP over HTTP/WebSocket. The endpoint directory must be new and outside the project, so the developer file bridge cannot read its capability. POSIX creates it atomically with -mode 0700 and the endpoint file with mode 0600; Windows uses an owner-only inheritable ACL. -On POSIX the client opens the directory with `O_DIRECTORY|O_NOFOLLOW`, checks its uid and private -mode, then opens `endpoint.json` relative to that pinned descriptor with `openat` and verifies the -file's uid, regular-file type and private mode. A pathname swap cannot redirect that read. The Windows reader rejects reparse points but does not independently verify the -file's owner or ACL: it relies on the private directory ACL established by the owner. Only attach -to an endpoint in a trusted location; do not substitute a copied or externally created directory. -Session IDs also use OS entropy and constant-time comparison; start authorization precedes -operation/argument validation and refusals enter the authorization audit. -Its `endpoint.json` holds the port and a 256-bit capability generated by the OS. The capability is -never placed in page content, URLs, command-line arguments or logs. Each native request must prove -it before any operation executes. Web requests and incorrect capabilities are refused. Do not copy -this file to a shared location. The server removes its file/directory on normal closure and catchable SIGINT/SIGTERM, without -recursively deleting caller-owned content. Independent processes without a shared endpoint file -remain inaccessible to the attachment client. Catchable interrupts also remove the temporary -native profile. The CEF launcher disables ContentMain signal handlers and restores the native SIGINT/SIGTERM -actions after browser initialization; Windows retries transient browser file locks for up to two seconds. SIGKILL, forced OS termination and power loss cannot run cleanup. Same-user compromise remains outside this boundary. -Unauthenticated peers are multiplexed in a bounded queue (64, with oldest-peer eviction and a -two-second handshake deadline); they do not consume the 32 authenticated request worker slots. -This prevents silent connections from exhausting that worker pool. A sustained local flood can -still deny service through OS or CPU resource exhaustion. Attached clients wait up to 30 seconds -for each response; `--request-timeout 1..3600` changes this independently of the operation and -startup deadlines. CLI result polling backs off from 50 ms to one second. There is no TLS or remote/multi-user authentication promise. -Listening, accepted and client sockets are non-inheritable; POSIX closes them on exec. The page -capability uses the same OS cryptographic generator and comparison as the attachment channel. - -Stdout contains only one JSON-RPC message per line in MCP mode. Diagnostics go to stderr. -The client owns the stdio adapter and closes stdin to end its connection. In owned-window mode -this also closes the window; attached mode leaves its owner running. No native attachment socket -is created unless `--listen` is explicit. A blocked renderer is revoked at its native deadline; the -supervisor requests window closure, then exits forcibly after a five-second grace period. It first -stops the attachment worker, closes its listener and removes the endpoint files and empty private -directory. Active attachment IO may take up to its two-second deadline to join. Once a session -closes, its listener is revoked instead of accepting clients that nobody will serve. Attached CLI -startup discovery backs off from 100 ms to one second, rather than opening a connection every 20 ms. - -For a single CLI operation, replace `--mcp` with `--operation build [--entry main]` or -`--operation test [--pattern text]`. Check, build, test, preview and inspect use the same -controller and permissions. The CLI waits, emits one final JSON run snapshot and returns 0 -on success, 1 on operation failure, 64 on configuration errors, 69 when an attachment is unavailable -(the outcome of an in-flight mutation may be unknown), 70 on bootstrap failure, -71 on the native deadline. Bootstrap failure stays 70 whether the transport observes the closed -session before or after the main thread; specific native deadline and signal statuses retain priority. -Closing a window without a command result does not imply success. -MCP operation failures are returned as tool errors or failed run states; clients must inspect -the result instead of interpreting successful JSON-RPC delivery as a successful build. - -## Automating your own application - -`webfront-agent` owns its window, so it cannot exercise an application's own `cppFunction` callbacks. An application that -wants to be driven opts in explicitly; it then keeps its callbacks, and check/build/test/preview/inspect/interact run in -**its** window. It must have called `bootstrap("developer")` (the developer environment is hosted in its page). +These options are for trusted development environments. A different local user can occupy the fixed port while the application is stopped and receive a durable Bearer sent by the client, then reuse it when the application starts. Without authentication, any local process that reaches the listener can exercise its grants. A fake server can also send misleading responses. Loopback, strict Host, Origin and Sec-Fetch checks remain enabled in both modes; they do not authenticate the server to the client. -```cpp -#include <webfront/automation/Enable.hpp> +After a crash or forced termination, the private `mcp.json` can remain on disk with the durable token. Session discovery prunes known files in default session directories when it detects a dead process, but cleanup can be delayed or fail; an explicitly supplied `directory` is not pruned by discovery. Inspect and remove stale private files as needed, and rotate a token if it may have been exposed. -webfront::NativeApp app{project}; -app.bootstrap("developer"); -app.cppFunction("bf.render", render); // stays available to the previewed page -auto automation = webfront::automation::enableAutomation( - app, {.grants = {"check", "build", "inspect", "interact"}, .listen = privateEndpointDirectory}); -app.show(automation->launchPage()); // the single-use claim selects this window -automation->close(); // revokes the session and removes record and endpoint -app.shutdown(); -``` +All executable operations are denied unless granted. The setup grants write the manifest, the lock, the cache, a new starter +directory or the generated provider header; grant them only for a project whose registry you trust. `install` and `restore` +use the registry already configured by the owner, the manifest or the default; the operation cannot choose another one. +There is no operation for a shell, JavaScript evaluation, arbitrary callbacks, `wf run`, `exec` or arbitrary native file +reads/writes: an agent edits project files through its separately authorized workspace tools, then asks WebFront to verify +them. -Nothing is registered unless `enableAutomation` is called, and the grants, project and endpoint are fixed there by the -native owner, as with `--allow`/`--listen`. `listen` must be a new directory outside the project. The call prints one line on -stderr (grants and how to attach; no secret, disable with `announce = false`), `automation->windowTitle(base)` returns a title -marked as shared, and the terminal's own `wf` keeps working. Then, from another process: +A lost WebSocket does not prove the native window is gone (a navigation or a broken connection can leave it open, with +`show()` still blocked): the record and the listener are withdrawn at once, but the grace still runs until the application +calls `close()` after `show()` returns, so call it promptly. A window that never claims the session (`startupTimeout`) is +revoked the same way, since no operation exists for the deadline to expire. The native deadline of an operation revokes the +session and asks the window to close. A renderer stuck in a loop never runs that request, and `show()` cannot be interrupted +from another thread: after `closeGrace` the listener, the files and the record are removed and `onUnresponsive` is called, +which by default ends the process with status 72. An application that prefers another way to stop sets `onUnresponsive`. -```sh -webfront-agent --list -webfront-agent --attach /absolute/private-endpoint --operation check -``` +Automation does not exist in a distribution build: `Enable.hpp` and `McpHttp.hpp` stop the compilation with an `#error` when +`WEBFRONT_DISTRIBUTION` is 1, on purpose, so that no listener can ship. Gating the call alone is not enough: put the +`#include <webfront/automation/Enable.hpp>`, the `enableAutomation` call and any code that uses automation under the same +condition, for example: -A lost WebSocket does not prove the native window is gone (a navigation or a broken connection can leave it open, with `show()` still blocked): the record and endpoint are withdrawn at once, but the grace still runs until the application calls `close()` after `show()` returns, so call it promptly. A window that never claims the session (`startupTimeout`, 120 s from the activation) is revoked the same way, since no operation exists for the deadline to expire. The native deadline of an operation revokes the session and asks the window to close. A renderer stuck in a loop never runs that request, and `show()` cannot be interrupted from another thread: after `closeGrace` (five seconds) the endpoint and record are removed and `onUnresponsive` is called, which by default ends the process with status 72, as `webfront-agent` does. An application that prefers another way to stop sets `onUnresponsive`. Enabling automation in a -distribution build is an application choice: gate the call (for example behind a macro) so that shipped binaries have none. +```cpp +#if !WEBFRONT_DISTRIBUTION +#include <webfront/automation/Enable.hpp> +#endif +// ... +#if !WEBFRONT_DISTRIBUTION + auto automation = webfront::automation::enableAutomation(app, {.grants = {"check", "test"}}); +#endif +``` ### Calling the application's own callbacks @@ -211,51 +116,81 @@ default: the owner names the ones an agent may call and grants `call`. ```cpp auto automation = webfront::automation::enableAutomation( - app, {.grants = {"check", "build", "preview", "inspect", "interact", "call"}, .callbacks = {"bf.render"}, - .listen = privateEndpointDirectory}); + app, {.grants = {"check", "build", "preview", "inspect", "interact", "call"}, .callbacks = {"bf.render"}}); ``` -```sh -webfront-agent --attach /absolute/private-endpoint --operation call --callback bf.render --value "glider" -``` +The agent then starts `call` with `{"callback": "bf.render", "value": "glider"}`. `call` takes the `callback` name and at most one string `value`; its result is `data: {callback, result}`, where `result` is a string, a number, a boolean, `null` or a list of at most 1000 of those (typed arrays included), and at most 40,000 bytes once serialized; a larger answer fails the run with that reason instead of succeeding without its value. Anything else, a `webfront.*` name, a name that is not in the list (matched exactly, never as a pattern) and a session without the grant are refused natively and audited, whatever the page or the agent asks; the list cannot come from the project manifest or from -the agent. The names are visible in the session (`callbacks`), in `--list` and in the terminal notice. The callback runs in +the agent. The names are visible in the session (`callbacks`), in the discovery record and in the terminal notice. The callback runs in the application's own process with the application's authority: allow-list only callbacks that are safe to trigger. An environment older than 0.6.6 cannot run `call`, and the native owner refuses the grant rather than ignore it. `call` is an operation of `webfront.start`, not one MCP tool per callback, so the tool list stays at four. A callback in progress cannot be interrupted: cancelling a `call` keeps the run, the session's lock and the native deadline until the callback returns, then reports it cancelled (its effect is not undone); a callback that never returns ends with the native deadline, which revokes the session. -## Discovering shared sessions - -A session with an endpoint (`--serve --listen`, or `enableAutomation`) publishes `<session>.json` in a private per-user -directory: `%LOCALAPPDATA%\WebFront\sessions` on Windows, `~/Library/Application Support/WebFront/sessions` on macOS, -`$XDG_STATE_HOME/webfront/sessions` or `~/.local/state/webfront/sessions` elsewhere (`--sessions-dir` overrides it for the -launcher and for `--list`). On POSIX it must be owned by the user and closed to others, otherwise it is not read. A missing directory is created private (0700); an existing one that others can read is refused and left untouched. The record has -the project, grants, process identifier, API version and the endpoint directory, **never the capability**, which stays in the -private endpoint: listing a session does not let anyone operate it. It is removed on closure and on catchable signals; one -whose process is gone is dropped by the next `--list`. A recycled process identifier can keep a dead record for a while. Discovery is a convenience: if the directory cannot be used (no home, read-only, shared or owned by someone else), `webfront-agent --serve --listen` says so on stderr and serves the session unlisted, while `enableAutomation` throws, so that an application never believes it is listed when it is not. - -```sh -webfront-agent --list # {"version":1,"sessions":[{"session":...,"allow":[...],"endpoint":...}]} -webfront-agent --print-mcp-config --attach /absolute/private-endpoint [--name app] > .mcp.json -``` - -The generated configuration is one stdio server `webfront-agent --attach <dir> --mcp`; it carries no grant (the owner's -process fixes them) and no secret. It is never written into the project manifest. - -`--print-mcp-config` is the client configuration generator (there is no `wf agent init`: the file belongs to the agent's client, not to the -project, and `wf` cannot know where that client keeps it). Automation is also visible to the person at the window: once connected, the -terminal prints the grants, the callbacks and the attach path in yellow, `wf help` ends with an `Automation:` line while it lasts, and -`automation->windowTitle(base)` marks the title. `wf create` writes an `AGENTS.md` beside the starter's sources that tells an agent -these commands, and the errors that ask for a package (`wf check` without typescript, `wf test` without jasmine-core) name the `install` -operation. These need environment 0.6.6; an older one shows none of them and still works. +## The MCP listener + +- **Address.** The listener binds `127.0.0.1` only, on a port the OS chooses, distinct from the page's port and never + served with TLS, whatever the application's own address and TLS listener. `mcpPort` chooses a port; a chosen port is never + replaced: when it is taken the activation throws a `std::system_error` that names the address, the port and the cause. + Each instance has its own URL, so several applications run side by side and the agent picks one by its URL. +- **Token.** By default every request carries `Authorization: Bearer <token>`, a 256-bit value from the OS. Before parsing the + body, the listener compares equal-length tokens in constant time and rejects a length mismatch immediately; a failed check gets + 401 with `WWW-Authenticate: Bearer` (no OAuth server is announced). The token lives as + long as the session by default: closing it, a deadline or a lost window closes the listener and removes the file. A supplied + `mcpToken` remains valid across launches until the application changes it; authentication can be explicitly disabled. +- **Client configuration.** `mcp.json` (mode 0600 in a 0700 directory on POSIX, owner-only ACL on Windows) holds the URL and + the header, ready for a client that takes a configuration file (`claude --mcp-config PATH/mcp.json`). The token appears in + no page, URL, command line, log, banner or discovery record. Never copy it into the project, its `.mcp.json` included: the + developer file bridge can read the project. +- **Web pages.** A request whose `Host` is not exactly `127.0.0.1:PORT` or `localhost:PORT` gets 421 (DNS rebinding); any + `Origin`, the application's own included, or any `Sec-Fetch-*` header gets 403; a body that is not `application/json` gets + 415, and a CORS preflight gets 405 without any `Access-Control-*` header. Only `/mcp` is served: every other path, the + page's files and the OAuth discovery paths included, is 404. +- **Protocol.** MCP 2025-11-25 Streamable HTTP, reduced: `POST /mcp` with one JSON-RPC message (a batch is refused), + answered with `application/json`, never a server stream (`GET` is 405); `Accept` must include `application/json`. A + notification or a client response gets 202. `initialize` assigns `Mcp-Session-Id`, which routes and does not authenticate; + without it other requests get 400, an unknown or terminated one 404, and `DELETE /mcp` terminates the MCP session only, + not the window. 16 MCP sessions at most, the least recently used evicted. `MCP-Protocol-Version`, when sent, must be + 2025-11-25 (400 otherwise). The body is bounded by `Content-Length` to 60,000 bytes (413), chunked bodies get 501, an + unannounced length 411, and `Expect: 100-continue` is answered once the headers are accepted, never before a refusal. +- **Admission.** At most 64 unauthenticated peers, oldest evicted, each with two seconds + to send its headers and body; 32 workers for authenticated requests, which silent peers never hold; 30 seconds to send an + answer. Each connection carries one request (`Connection: close`). + + +Listening, accepted and client sockets are non-inheritable; POSIX closes them on exec. The application must be running +before a client connects: an MCP client cannot start it as it starts a stdio server. An agent with a shell starts the +application, then waits for its `mcp.json` or its discovery record. + +## Discovering running applications + +An application that enabled automation publishes `<session>.json` in a private per-user directory: `%LOCALAPPDATA%\WebFront\sessions` +on Windows, `~/Library/Application Support/WebFront/sessions` on macOS, `$XDG_STATE_HOME/webfront/sessions` or +`~/.local/state/webfront/sessions` elsewhere (`discovery` overrides it). On POSIX it must be owned by the user and closed to +others, otherwise it is not read. A missing directory is created private (0700); an existing one that others can read is +refused and left untouched, and `enableAutomation` throws, so that an application never believes it is listed when it is not. + +The record has the project, grants, allow-listed callbacks, process identifier, API version, the private directory +(`endpoint`), the MCP URL (`mcp`) and the path of the client configuration (`configuration`); **never the token**, which +stays in `mcp.json`: reading a record does not let anyone operate the session. With hundreds of instances, each has its own +record and private directory, named after its session identifier (OS entropy), and its own port. The record and the +directory are removed on closure (`close()`), and by the unresponsive-window path. An application that wants them removed on +SIGINT/SIGTERM ends `show()` on those signals with `app.requestClose()`, then calls `close()`; after a forced end, the next +activation removes the records whose process is gone, with the private directory named after them. A recycled process +identifier can keep a dead record for a while. + +Automation is also visible to the person at the window: once connected, the terminal prints the grants, the callbacks and +the URL in yellow, `wf help` ends with an `Automation:` line while it lasts, and `automation->windowTitle(base)` marks the +title. `wf create` writes an `AGENTS.md` beside the starter's sources that tells an agent how to connect, and the errors that +ask for a package (`wf check` without typescript, `wf test` without jasmine-core) name the `install` operation. ## MCP profile and results -The server supports protocol revision **2025-11-25**, initialization, ping and tools. It advertises +The server supports protocol revision **2025-11-25**, initialization (with short `instructions`), ping and tools, over +Streamable HTTP. It advertises no prompts, resources, sampling, logging or experimental task capability. A client requesting another revision receives the supported revision and must decide whether it can continue, as specified by [MCP version negotiation](https://modelcontextprotocol.io/specification/2025-11-25/basic/lifecycle#version-negotiation). @@ -285,6 +220,7 @@ Operations and their arguments: | `embed` | `{provider}` or `{entry, output}` | `embed` | | `click` | `{pageId, elementId}` | `interact` | | `fill` | `{pageId, elementId, value}` | `interact` | +| `call` | `{callback, value?}` | `call` | `name`, `starter`, `package` and `provider` refuse a leading `-`, a backslash and spaces; `directory` and `output` must be project-relative paths: `create` never replaces an existing directory (`wf` refuses it), while `embed` **replaces** its output header, as @@ -303,7 +239,9 @@ its bounded cancellation/cleanup before releasing ownership. A human `wf dev` ow while compiling/publishing, including when launched through `wf run` aliases, so agents can use the window while it waits for edits. The window displays the agent operation and a stop button. -Poll the run ID until its state is `succeeded`, `failed`, `cancelled`, `timeout` or `disconnected`. +Poll the run ID until its state is `succeeded`, `failed`, `cancelled`, `timeout` or `disconnected`. A `timeout` revokes the +session at once, listener included, so the client may get a refused connection instead of reading that last state: it +then stops polling and reports the outcome as unknown, without starting the mutation again. Exit code 130 means `cancelled` only after a native cancel request or an authenticated page report of an actual local abort; an unrequested script exit 130 is `failed`. The final `result` contains `{exitCode, output, report}`; top-level `output` becomes that final @@ -338,14 +276,14 @@ because they broaden disclosure and require engine-specific qualification. ## Security boundary -Launching the server grants the client authority over the explicitly selected trusted project. -The native controller checks its grant on every start. The launcher generates a separate 256-bit +Enabling automation grants the client authority over the application's trusted project, within the grants its owner fixed. +The native controller checks its grant on every start. `enableAutomation` generates a separate 256-bit single-use window claim and passes it in the frontend URL fragment, which is not sent in HTTP requests. The bootstrap removes the fragment from browser history before submitting its claim. Only that claim selects the browser and releases its page key; an earlier WebSocket connection receives no key and cannot consume the claim. The server checks WebSocket Origin against its content policy, but does not use Host as a window identity, and native local clients can forge -Origin. Window selection therefore depends on the launcher claim, not those headers or connection +Origin. Window selection therefore depends on the launch claim, not those headers or connection order. Preview/test frames opening their own WebSocket are refused by connection identity. Do not disclose the launch URL or its fragment; hostile same-user processes are outside this boundary. Callback packets carry HMAC-SHA-256 proofs over a monotonic counter, method and @@ -366,56 +304,63 @@ with duplicate keys refused. Browser reads/writes still use the existing develop and transactional-publication checks. Untrusted project text cannot modify the native grant list. Build/check/test/preview execute toolchain or project code. Authorized page code and C++ callbacks -retain their application authority. The manifest, origin checks, stdio transport and native grant +retain their application authority. The manifest, origin checks, the MCP token and native grant list do not sandbox that code against the host, stop a malicious same-user process, or prevent an authorized agent from choosing a harmful action after prompt injection. Treat diagnostics, logs, page labels and results as untrusted data. Use a dedicated OS/CI environment with secrets removed and externally controlled network access for untrusted repositories. -Inherited process environment is not automatically sanitized: callers must launch the executable -with the environment/secrets appropriate to the project. Inspection limits and omission of form +Inherited process environment is not automatically sanitized: launch the application with the environment and secrets +appropriate to the project. Inspection limits and omission of form values are data minimization, not a confidentiality guarantee; page text and diagnostics can still contain secrets. Run results and the last 64 native start-authorization decisions are kept in memory, not automatically written to disk. Audit entries carry the actual operation and the assigned run ID (empty for a denial before allocation), and omit arguments/output. Busy, not-ready, malformed requests with valid session authority and lifecycle completions do not evict those decisions. Retention, access to client-side transcripts and secret expurgation remain the caller's responsibility. -Remote/multi-user access, HTTP, arbitrary uninstrumented window discovery and physical device +The loopback MCP listener is decided by [ADR-025](adr/ADR-025-mcp-http-dans-l-application.md); its token protects it +from other users and web pages, not from a process of the same user, which can read `mcp.json`. +Remote/multi-user access (including MCP over HTTPS), arbitrary uninstrumented window discovery and physical device control need their own reviewed authorization/isolation design. ## Validation -The unit tests cover native grants, cross-session rejection, path/option refusal, cancellation races, -deadline revocation, MCP lifecycle/IDs and hostile JSON. Browser Jasmine specs cover shared -dispatch arbitration and the runner. `AutomationMcpWindow` drives a real embedded window through -stdio: structured errors, file correction, check/build/test, preview inspection/actions, -cross-frame rejection, cancellation and POSIX SIGTERM cleanup of the shared owner -(endpoint and temporary profile). This reuses the existing window. A separate `AutomationMcpWatchdog` case -blocks a real renderer inside a test-archive operation body, -without loading/compiling Jasmine just to provoke that hang. It exercises the production signed -callback/runner, native two-second deadline, five-second close grace, stdio EOF and endpoint removal -through MCP; a CLI restart after the forced exit then checks endpoint reuse and Unicode failure reporting. -It delays bootstrap by three seconds to verify that its shorter operation deadline starts only after startup. The -cases retain separate private project/temporary directories and ephemeral ports; the frontend storage limits -listed above still apply. -That regression uses Python's standard library as a test client; Python is not a runtime -dependency of the launcher. It is registered when a Python interpreter and embedded test engine -are available; without xvfb-run on Linux only the optional Automation window tests are skipped with -a warning. The mandatory Jasmine, developer and driver browser coverage still requires a display -runner and configuration fails if it is unavailable. -The maintained [official SDK regression](../test/tools/AutomationSdkClient.py) uses `mcp==2.3.0` -in a separate test environment. It checks initialization, catalogue, structured results, an operation -failure, a real build and detachment from a shared window. It accepts the same path arguments as -`AutomationClient.py`. Configure registers `AutomationSdkWindow` when the selected Python already -has that exact SDK installed; no SDK or package is installed by configure or by a test. To run it -manually, use that Python with `test/tools/AutomationSdkClient.py --agent ... --driver ... ---environment ... --provision ... --registry ... --fixture ... --work ...`. This is tested interop, -not a claim of compliance with every MCP client. +`AutomationMcpHttpTests.cpp` covers the listener: screening of Host, Origin, Sec-Fetch, path, method, token, media types and +lengths; MCP sessions, revisions, batches, notifications and eviction; real sockets with refusals read before a reset, +`Expect: 100-continue`, silent peers, a taken port and revocation; two activations side by side and the cleanup of a vanished +instance. The other unit tests cover native grants, cross-session rejection, path/option refusal, cancellation races, +deadline revocation, the MCP lifecycle and identifiers, and hostile JSON. `AutomationAbsentFromDistribution` checks that +`Enable.hpp` does not compile with `WEBFRONT_DISTRIBUTION`. Browser Jasmine specs cover shared dispatch arbitration and the +runner. + +The window regressions drive `automation_host`, a test application that calls `enableAutomation`, through its URL with +Python's standard library HTTP client: + +- `AutomationMcpWindow`: structured errors, file correction, check/build/test, preview inspection and actions, cross-frame + rejection, a second client sharing the session and cancelling the first one's run, a project set up from nothing + (`create`, `init`, `install`, `restore`, `embed`), and the withdrawal of the listener, record and directory when the window closes. +- `AutomationMcpWatchdog`: a real renderer blocked inside a test-archive operation body, without loading Jasmine to provoke + the hang. It exercises the production signed callback and runner, the native two-second deadline, the five-second close + grace and the withdrawal of the listener, record and directory; a relaunch on the same directory then checks its reuse and + Unicode failure reporting. It delays bootstrap by three seconds to verify that the operation deadline starts after startup. +- `AutomationConsumerWindow`: two applications side by side, each driven through its own URL: refusals of web pages, + rebinding names and the other instance's token, grants, check, build, preview, click, the application's own allow-listed + callback, and cleanup. + +They are registered when a Python interpreter and an embedded test engine are available; without xvfb-run on Linux only these +optional window tests are skipped with a warning. The mandatory Jasmine, developer and driver browser coverage still requires +a display runner and configuration fails if it is unavailable. + +The maintained [official SDK regression](../test/tools/AutomationSdkClient.py) uses `mcp==2.3.0` in a separate test +environment, over Streamable HTTP with the token of `mcp.json`. It checks initialization, instructions, catalogue, +structured results, a refused operation, a real build and a second connection after the first one terminated its MCP +session. Configure registers `AutomationSdkWindow` when the selected Python already has that exact SDK installed; no SDK or +package is installed by configure or by a test. This is tested interop, not a claim of compliance with every MCP client. ### Optional local-model qualification `test/tools/AutomationModelBenchmark.py` is a small MCP host for an already running local Ollama -model. It does not install or download a model, contact a public server, or grant arbitrary shell +model, connected to the MCP URL of the test application. It does not install or download a model, contact a public server, or grant arbitrary shell or filesystem access. It projects the trusted MCP catalogue into function calls and separately permits reading/writing only the generated fixture's `main.ts`. Two tasks ask the model to fix a type error or a failing test. The harness then independently runs check/tests, records successes @@ -423,8 +368,8 @@ and attempts per model, latency, prompt/generated token counts and the host's me token delta. It measures the catalogue with/without tools using identical baseline messages; that delta is host/model-specific, not a universal tokenizer estimate. -Run it with the same agent/driver/environment/provision/registry/fixture/work options as -`AutomationClient.py`, plus `--model INSTALLED_MODEL --report results.json`. Repeat `--model` to +Run it with the same host/driver/environment/provision/registry/fixture/work options as +`AutomationClient.py` (`--host` is the `automation_host` test application of a browser test build), plus `--model INSTALLED_MODEL --report results.json`. Repeat `--model` to compare model classes; `--repeat` defaults to 3 and `--turns` to 24. `--ollama-url` defaults to `http://127.0.0.1:11434/api/chat`; only loopback HTTP endpoints are accepted and redirects are refused. The synthetic source produced by a model is still executable project code: use an isolated @@ -439,5 +384,6 @@ five installed models tested through a separate LM Studio measurement adapter: D Qwen 3.8, Muse Glimmer, Flint and Nemotron Cascade 2. All 30 final sources passed independent host check/tests; 29 model conversations themselves observed both operations succeed. The report includes per-task data, catalogue/token costs, recovered refusals, the Flint response-limit case and native -exit-status validation. This is measured evidence for that setup, not a supported LM Studio mode +exit-status validation. It was measured with the former stdio launcher, before ADR-025; the catalogue and the operations +are the same. This is measured evidence for that setup, not a supported LM Studio mode of the maintained Ollama benchmark or a general success guarantee. diff --git a/docs/BDD.md b/docs/BDD.md new file mode 100644 index 00000000..75a64342 --- /dev/null +++ b/docs/BDD.md @@ -0,0 +1,102 @@ +# Testing with `webfront::bdd` + +`webfront::bdd` is the behaviour-driven test framework that WebFront's own C++ tests use (#647). It is a public interface: +a project that consumes WebFront can write its scenarios with it and have CTest discover them, in place of Catch2. It is a +single header that includes only the standard library, with a CMake function that registers the scenarios. + +| What | Name | +| --- | --- | +| Header | `<webfront/testing/Bdd.hpp>` | +| Namespace | `webfront::bdd` | +| CMake target | `WebFront::Bdd` (`INTERFACE`: the header, C++23 and threads; it needs neither WebFront nor stdnet) | +| CMake function | `webfront_bdd_discover_tests()`, the counterpart of `catch_discover_tests` | +| Package | `WebFrontBdd` (`find_package(WebFrontBdd)`) | + +## Getting it + +With CPM, FetchContent or `add_subdirectory`, the target and the function exist once WebFront is added; nothing else is +built or installed from a project that embeds WebFront: + +```cmake +CPMAddPackage("gh:ambroise-leclerc/WebFront@<version>") +``` + +From an installed WebFront (`cmake --install <build> --prefix <prefix> --component WebFrontBdd` of the top-level project), use the package; it +installs the header, `WebFront::Bdd` and the module that defines `webfront_bdd_discover_tests()`: + +```cmake +find_package(WebFrontBdd REQUIRED) # with -DCMAKE_PREFIX_PATH=<prefix> +``` + +## Writing and registering scenarios + +```cpp +#include <webfront/testing/Bdd.hpp> + +using namespace webfront::bdd; + +const Scenario addition{"Addition", [] { + int sum = 0; + given("two numbers", [&] { + when("they are added", [&] { + sum = 2 + 3; + then("the sum is five", [&] { require(sum == 5); }); + }); + }); +}}; + +int main(int argc, char** argv) { return run(argc, argv); } +``` + +```cmake +add_executable(my_tests main.cpp) +target_link_libraries(my_tests PRIVATE WebFront::Bdd) +webfront_bdd_discover_tests(my_tests TEST_PREFIX "My." PROPERTIES TIMEOUT 30 LABELS fast) +``` + +As in Catch2, a scenario runs again from its start until each leaf section has run once. `require` ends the scenario at the +first failure, `check` records it and goes on, and `requireEventually`, `checkEventually`, `requireReady` and `checkReady` +wait for an asynchronous state. The header documents each of them (Doxygen). + +`webfront_bdd_discover_tests(<target> ...)`: + +| Option | Effect | +| --- | --- | +| `TEST_PREFIX <text>` | Put before `Scenario: ` in the name of each case; refused with `SHARDS` | +| `PROPERTIES <name> <value>...` | Properties of every case (`TIMEOUT`, `LABELS`, `ENVIRONMENT`...); a `SKIP_RETURN_CODE` of yours replaces the default 4 | +| `SHARDS <n>` | Register `<n>` cases, each running a share of the scenarios in one process, instead of one case per scenario | +| `SHARD_NAME <name>` | With `SHARDS` only (refused otherwise): name of the shards, `<name>-<i>` (default `<target>Shards`) | +| `JUNIT_PREFIX <path>` | With `SHARDS` only (refused otherwise): JUnit report of each shard, `<path>-<i>.xml` (default `<binary dir>/<target>-results-<i>.xml`) | + +A value of `PROPERTIES` is kept as one argument whatever it holds (a `;`, a trailing backslash, `]==]`, even the name of an option such as `SHARDS`), so pass such a value as one quoted argument; CMake then reads a `;` in it as a list separator, as `set_tests_properties` does (`ENVIRONMENT "A=1;B=2"` sets two variables). `PROPERTIES` takes pairs of a name and a value. + +Call it once per target without `SHARDS`: a second such call on the same target is refused (it would overwrite the first one's files). A call with `SHARDS` registers its cases at once and can accompany it. + +A change of `PROPERTIES` or `TEST_PREFIX` links the executable again (Makefile and Ninja generators), so that building the target alone registers the new values; a complete build does it with any generator, unless the executable is `EXCLUDE_FROM_ALL` (set before the call), which discovery never brings back. + +After each build the executable lists its scenarios (`--list`) and a post-build step writes one CTest case per scenario, +`Scenario: <title>`, whatever brackets or semicolons the title holds. Each case runs `<target> --exact <title>`; a +scenario that skips itself exits with 4, which the cases treat as skipped. When the target has a `CROSSCOMPILING_EMULATOR` +(or `CMAKE_CROSSCOMPILING_EMULATOR` is set), it lists the scenarios and runs every case. + +The executable's own options are `--list`, `--exact`, `--order`, `--rng-seed`, `--shard-count`, `--shard-index`, `--junit` +and the name filters; run it with `--help`. + +## Options and what stays internal + +- `WEBFRONT_TEST_TIMEOUT_FACTOR` is an environment variable read by the framework: a decimal such as `2` or `2.5` that + multiplies the delays of `requireEventually` and its siblings, for a slow job (sanitizers, emulation). It is public. + CMake does not read it for you: give your cases a `TIMEOUT` that agrees, or pass the variable through `ENVIRONMENT`. +- `WebFront_test_hardening`, `WebFront_warnings`, `WebFront_options`, `WEBFRONT_TEST_UNIT_SHARDS` and + `TimeoutFactor.cmake` belong to WebFront's own tests. They are not part of the interface and are not installed. + +## Compatibility + +The header, the namespace `webfront::bdd` and its names, the semantics above, the `WebFront::Bdd` target and +`webfront_bdd_discover_tests` with its options follow WebFront's semantic versions: an incompatible change waits for a +major version and is listed under `Breaking` in the [changelog](CHANGELOG.md); the framework's additions appear under +`Added`. The installed package accepts a WebFront of the same major version (`SameMajorVersion`). What the header +documents is the interface; the contents of `webfront::bdd::impl` is not. +`BddSelfTest`, `BddDiscovery` and `BddConsumer` (a project that finds the installed package) pin it. + +The header compiles as C++23 and, in a C++26 translation unit, as C++26; an executable must not mix the two standards. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index e5b2d627..d134b8f5 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -10,6 +10,35 @@ these entries stays in the GitHub releases and the Git history. ## Unreleased +## [1.2.0] - 2026-11-24 + +WebFront 1.2 ships with developer environment 1.2.0. The application itself becomes the MCP server that a coding agent drives +(`enableAutomation`), and it can open a second native window, serve HTTPS and run beside other applications on a free port. +It has breaking changes: `WebView2Options` becomes `ViewOptions`, `webfront-agent` is removed and the CEF profile moves; each +entry below gives its migration. + +### Breaking +- `WebView2Options` is now `ViewOptions`, shared with WKWebView: `userDataFolder` moves after `launch`, so a positional initialization of `WebView2Options` stops compiling, and so does a designated one that writes `.userDataFolder` before `.contentPolicy`, `.window`, `.visible` or `.launch` (write it last) (#652, `docs/FRONTENDS.md`). +- `webfront/automation/Enable.hpp` no longer compiles with `WEBFRONT_DISTRIBUTION`: gate `enableAutomation` out of the distribution build, as the guide already advised (#632, ADR-025). +- `webfront-agent` is removed with its JSON CLI, MCP on stdio, `--serve`, `--attach`, `--list` and `--print-mcp-config`, as are `WEBFRONT_BUILD_AUTOMATION`, `WEBFRONT_AUTOMATION_FRONTEND` and `webfront_add_agent()`: connect the MCP client to the URL the application prints (#632, ADR-025, `docs/AUTOMATION.md`). +- `AutomationOptions::listen` becomes `directory` and may stay empty (a private directory named after the session is created), `Automation::endpoint()` becomes `directory()`, and the JSON-lines attachment channel (`ChannelServer`, `ChannelClient`) is gone (#632). +- The CEF profile is now `cef_cache/<executable>`, not `cef_cache`: an application starts with an empty profile (localStorage, cookies); to keep the data, move the old contents of `cef_cache` into `cef_cache/<executable>` once (#617, `docs/HOST_INTEGRATION.md`). + +### Added +- Open a second native window with `app.openSecondaryWindow(page, WindowOptions)` (WebKitGTK, WKWebView, WebView2; elsewhere `std::logic_error`, which `app.canShowSecondaryWindow()` predicts): it shares the server, the `cppFunction`s, the `jsFunction` subscribers and the view proof of the first window; `app.requestClose(page)` closes it, and closing the first closes the others (#616, `docs/FRONTENDS.md`). +- Write your own scenarios with the public `webfront::bdd` framework: `<webfront/testing/Bdd.hpp>`, the `WebFront::Bdd` target, the installable `WebFrontBdd` package and `webfront_bdd_discover_tests()` (prefix, properties, shards) replace the internal `test/unit/Bdd.hpp` and `bdd_discover_tests`, and follow WebFront's versions (#647, `docs/BDD.md`). +- Configure a stable MCP port and application-supplied Bearer token, or explicitly disable authentication for trusted development (#637, ADR-026, `docs/AUTOMATION.md`). +- Connect an MCP client to the application itself: `enableAutomation(app, {.grants = {...}})` serves MCP over Streamable HTTP on a loopback port of its own, prints its URL and writes a private `mcp.json` with the URL and a session Bearer token, so several applications run side by side with no other program (#632, ADR-025, `docs/AUTOMATION.md`). +- Use a custom network provider with `DeveloperAppWithNetwork`. The `BasicDeveloperApp` alias selects the existing TCP provider (#631). +- Pass the MSVC code analysis on the automation host probe and the discovery directory of `Enable.hpp` (C6031, C6244), which stopped the Windows desktop job of a dispatch or pull request at its build (#638). +- Serve HTTPS and WSS with the optional header-only TLS 1.3 listener and reload its PEM identity after renewal (#631, `docs/TLS.md`). +- Start an application with no port setting when `9002` is taken: an empty `WebFrontConfig::port` falls back to a free port, a chosen port is never replaced, and CEF and WebKitGTK give each live instance its own profile directory (#617, `docs/HOST_INTEGRATION.md`). +- Start several applications side by side: the default port follows `WEBFRONT_PORT` (a number from 0 to 65535, `0` asks for a free port, `9002` remains the default), the examples take `--port`, the server announces the port really bound, and a failed bind names the address, the port and the cause (#617, `docs/HOST_INTEGRATION.md`). + +### Fixed +- Check the leftover STA of a WebView2 window only after a page that ran to its end, not after one that closes the window on a load failure: the runtime can keep a COM initialization of its own then, in about one `show()` in 500 under load, and the limit is documented with its measurements (#638, `docs/PROJECT_STATUS.md`). +- Refuse every `Sec-Fetch-*` request header on the MCP listener, including `Sec-Fetch-Dest`, in both authenticated and unauthenticated modes (#637). + ## [1.1.1] - 2026-11-20 WebFront 1.1.1 ships with developer environment 1.0.1. It repairs the desktop CI jobs that the 1.1.0 release exposed (a Windows @@ -38,6 +67,10 @@ in a native pseudoterminal, and a faster, less flashy start of the native window - Choose the colour of the WebKitGTK view under the page with `WindowOptions::background` (WebKitGTK; the other embedded frontends are listed here), and read the start-up milestones of a WebKitGTK view with `WEBFRONT_STARTUP_TRACE=1` (#611, `docs/WEBKITGTK.md`). ### Changed +- The whole C++ code base is reformatted with `clang-format` and every source starts with a normalized header (SPDX, author, creation date, role, thread and allocation model, reading hint); CI checks both (`SourceHeaders` case, `.github/workflows/SourceFormat.yml`), and `.git-blame-ignore-revs` skips the reformatting in `git blame` (#653, `.github/CONTRIBUTING.md`). +- WebKitGTK takes a `startupTimeout` (30 s by default), and WebView2 refuses a secondary window once the first one closed, even for a page already open (#652). +- Open every native window from one `ViewOptions` (`WKWebViewOptions` and `WebView2Options` are aliases), whose test injections reach the secondary windows too (#652, `docs/FRONTENDS.md`). +- Write a native frontend from shared headers: `EmbeddedFrontend` (facade and every `open()` overload), `WindowRegistry`/`InterfaceSession`, `StartupTrace` and `Presentation`, tested on Linux with fake windows (#652, `docs/FRONTENDS.md`). - Reveal the WKWebView window when the document has loaded or after one second (#611, `docs/WKWEBVIEW.md`). - Reveal the WebView2 window after the first frame or one second (#611, `docs/WEBVIEW2.md`). - Show the WebKitGTK window when the page reports its first frame, or when a one-second timer fires, even if the page has not painted, instead of at once; the embedded pages, the starter and the examples use the cheap `sans-serif` and `monospace` font stacks (#611, `docs/WEBKITGTK.md`). @@ -270,7 +303,8 @@ Coroutines and the opt-in developer environment. One **breaking** change to the - Fail decoding when a bridge integer is out of the requested C++ range, instead of invoking undefined behavior. -[Unreleased]: https://github.com/ambroise-leclerc/WebFront/compare/v1.1.1...HEAD +[Unreleased]: https://github.com/ambroise-leclerc/WebFront/compare/v1.2.0...HEAD +[1.2.0]: https://github.com/ambroise-leclerc/WebFront/compare/v1.1.1...v1.2.0 [1.1.1]: https://github.com/ambroise-leclerc/WebFront/compare/v1.1.0...v1.1.1 [1.1.0]: https://github.com/ambroise-leclerc/WebFront/compare/v1.0.0...v1.1.0 [1.0.0]: https://github.com/ambroise-leclerc/WebFront/compare/v0.9.0...v1.0.0 diff --git a/docs/CONTENT_POLICY.md b/docs/CONTENT_POLICY.md index d09b85be..d49442b1 100644 --- a/docs/CONTENT_POLICY.md +++ b/docs/CONTENT_POLICY.md @@ -76,8 +76,9 @@ WebView2 still reports failures to read popup event data or mark it handled as s This is a top-level navigation policy, not a subresource/iframe/network sandbox. Frames, fetches, third-party scripts, downloads, OS protocol handlers and browser extensions need separate host -controls. A same-origin script already has the application's bridge authority. The server exposes -no TLS or user authentication. Keep the default loopback bind unless remote access is deliberate. +controls. A same-origin script already has the application's bridge authority. The optional [TLS listener](TLS.md) +protects the transport and authenticates the server. The application owns client authentication. +Keep the default loopback bind unless remote access is deliberate. DevTools settings control the adapter's engine UI, not inspection by native host code or an external debugger. Custom frontends can opt into `open(address, port, page, const ContentPolicy&)`; `BasicWF` prefers diff --git a/docs/DEVELOPER_ENVIRONMENT.md b/docs/DEVELOPER_ENVIRONMENT.md index 618dd892..1ba59b4e 100644 --- a/docs/DEVELOPER_ENVIRONMENT.md +++ b/docs/DEVELOPER_ENVIRONMENT.md @@ -79,8 +79,8 @@ Each published version is immutable: 0.3.0 introduced the packed-bitset Life sta manifest, `wf restore`, `wf run`, `wf exec`, `wf check` and the complete terminal, and 0.6.0 `wf build`, `wf dev` and `wf test`. The default configuration is generated in `include/webfront/system/DeveloperReleaseData.hpp`; it contains -an exact versioned environment URL and the trusted digest. The 1.0.1 release pin selects -`https://dist.webfront.fr/developer/1.0.1/environment.tgz` (ADR-021). The deployed archive, CORS headers and public +an exact versioned environment URL and the trusted digest. The 1.2.0 release pin selects +`https://dist.webfront.fr/developer/1.2.0/environment.tgz` (ADR-021). The deployed archive, CORS headers and public smoke test were verified before the pin was merged. Earlier publication gates are recorded for [0.6.6](validation/developer-0.6.6-release.md), [0.6.4](validation/developer-0.6.4-release.md) and [0.6.3](validation/developer-0.6.3-release.md). Published 0.6.2 introduced installation of the archives of `@types` packages and the manifest directory; @@ -489,8 +489,8 @@ scheduler@0.28.0 ``` `wf help` lists the `wf` commands; `wf help <command>` gives the usage and purpose of one, and `wf help agents` (or -`wf help --agents`) the model, the sequence for a new interface and the `webfront-agent` commands that run it in JSON or -MCP (environment 0.9.2). The errors a newcomer meets first carry the next steps: a missing manifest names `wf init`, then +`wf help --agents`) the model, the sequence for a new interface and how an agent runs it through the MCP URL of the application +(environment 0.9.2; the MCP URL replaces `webfront-agent` from the environment that follows 1.0.1). The errors a newcomer meets first carry the next steps: a missing manifest names `wf init`, then `wf dev <entry.tsx>` and `wf create app`; a missing entry gives `ui/main.tsx` as an example; `wf create` without or with an unknown starter lists the starters. The line under the terminal that reports the bootstrap ends with `Agents: docs/DEVELOPING_WITH_AGENTS.md`; it comes from the library's embedded loader, not from the environment. @@ -727,7 +727,8 @@ above). Rows before 0.9 were reconstructed from the header of each tag; 0.4.0 pr <!-- compatibility-table:begin --> | Library | Environment | Minimum api | | --- | --- | --- | -| unreleased | 1.0.1 | 1 | +| unreleased | 1.2.0 | 1 | +| 1.2.0 | 1.2.0 | 1 | | 1.1.1 | 1.0.1 | 1 | | 1.1.0 | 1.0.1 | 1 | | 1.0.0 | 1.0.0 | 1 | @@ -793,6 +794,12 @@ checks the pinned header against the published archive. The headers of the core' `@webfront/developer-environment`, `@webfront/app-starter` and `@webfront/life-starter`. They are distributed as static GitHub Pages downloads; no npm publication or scope ownership is required. +The version in `distribution.json` is the version built from the current sources (currently 1.0.3, not yet published). +It can be ahead of `DeveloperReleaseData.hpp`, which pins the published 1.0.2 environment used by applications. The +compatibility table above records that published pin, not the next source build. The default branch receives a new +pin only after the new distribution is published and its files are verified. Before the tag, the release branch carries +the regenerated header, and `wf run build <directory> --refresh-bootstrap` rewrites it locally. + The `SelfBuild*` CTest cases run the scripts on a copy of the sources, with the dependencies installed from the local registry: the build, a repeat build (same bytes), the checked-in bootstrap bundles and checksums rebuilt by wf alone (and the core headers rendered from them by CMake), the staging of the site (a second staging repeats the same bytes, a changed diff --git a/docs/DEVELOPING_WITH_AGENTS.md b/docs/DEVELOPING_WITH_AGENTS.md index 2f26b0fc..2e7d8461 100644 --- a/docs/DEVELOPING_WITH_AGENTS.md +++ b/docs/DEVELOPING_WITH_AGENTS.md @@ -1,9 +1,9 @@ # Developing a WebFront application with an agent This page is what a coding agent needs before it writes the first line of a WebFront application: the model, the -development loop, and how to run every `wf` command itself, in JSON or through MCP, instead of asking a person to type it. -`wf help agents`, the `AGENTS.md` that `wf create` and `webfront_write_agent_guide()` write, the CMake configuration notice -and `webfront-agent --agent-help` all point here. +development loop, and how to run every `wf` command itself, through MCP, instead of asking a person to type it. +`wf help agents`, the `AGENTS.md` that `wf create` and `webfront_write_agent_guide()` write and the CMake configuration notice +all point here. ## The model: C++ with a TypeScript interface @@ -61,24 +61,15 @@ or later; 0.9.1 ignores the argument and prints the list). Declaring `"entries": {"main": "ui/main.ts"}` in `webfront.project.json` lets `wf dev`, `wf build` and `wf preview` run without argument. The [developer environment reference](DEVELOPER_ENVIRONMENT.md) has the details of each command. -## Running wf yourself: JSON and MCP +## Running wf yourself, through MCP -`webfront-agent` runs the same commands in the application's own window and answers in JSON, as a command line or as an MCP -server on stdio. Three things are needed, none of which is on by default. +For a client configured once, the application can set a fixed `mcpPort` and provide the same `mcpToken` on each launch. Copy the first private `mcp.json` URL and Bearer header into the client user configuration, outside the project. Start the application before connecting. This opt-in mode accepts the local server impersonation risk described in [AUTOMATION.md](AUTOMATION.md); the default remains a fresh session token. -**1. The launcher.** It is built when WebFront is configured with `-DWEBFRONT_BUILD_AUTOMATION=ON` and a native window -engine is enabled, which is the default on a desktop where its dependencies are found. The configuration prints one -`WebFront for agents:` line that says whether the launcher is built. +The application runs the same commands in its own window and serves them over MCP: in a development build, it is the MCP +server, at a URL of its own. An MCP client connects to that URL; no other program is built or launched. -```cmake -set(WEBFRONT_BUILD_AUTOMATION ON) # before add_subdirectory / FetchContent / CPM -add_subdirectory(path/to/WebFront) -webfront_add_agent() # checks the webfront-agent target; INSTALL installs it -webfront_write_agent_guide() # writes AGENTS.md at the root of your project, once -``` - -**2. The application opts in**, in a development build. The grants are the owner's decision, fixed in native code: an -agent proposes this code and does not widen it. +**1. The application opts in**, in a development build. The grants are the owner's decision, fixed in native code: an +agent proposes this code and does not widen it. Automation does not compile in a distribution build (`WEBFRONT_DISTRIBUTION`). ```cpp #include <webfront/automation/Enable.hpp> @@ -87,8 +78,7 @@ webfront::NativeApp app{"my-project"}; app.cppFunction("app.greet", greet); app.bootstrap("developer"); auto automation = webfront::automation::enableAutomation(app, - {.grants = {"create", "init", "install", "check", "build", "test", "preview", "embed", "inspect", "interact"}, - .listen = privateDirectory}); // a new directory outside the project + {.grants = {"create", "init", "install", "check", "build", "test", "preview", "embed", "inspect", "interact"}}); app.show(automation->launchPage()); automation->close(); app.shutdown(); @@ -96,44 +86,50 @@ app.shutdown(); Each operation needs its own grant, and only the owner of the application grants it: without `embed` in the list, `embed` is refused with `not_authorized`, and an agent asks the owner instead of widening the list. `embed` replaces its output header; grant it -for a project whose output you accept to regenerate. The application prints the grants and the attach command on stderr and in its terminal. +for a project whose output you accept to regenerate. -**3. Attach.** +**2. The application prints its URL** on stderr, and its terminal shows the grants: -```sh -webfront-agent --list # the shared sessions and their endpoint directory -webfront-agent --attach DIRECTORY --operation check # one operation, one JSON result -webfront-agent --print-mcp-config --attach DIRECTORY > .mcp.json # for Claude Code or another MCP client -webfront-agent --agent-help # the rules; --schema prints the contract +```text +WebFront MCP (grants: check, build, ...): http://127.0.0.1:PORT/mcp - client configuration: /home/me/.local/state/webfront/sessions/SESSION/mcp.json ``` +By default each running instance has its own port, so the URL is printed rather than known in advance. `mcp.json` is the client +configuration of that instance, URL and Bearer token together, in a private directory outside the project: + ```json -{ - "mcpServers": { - "webfront": {"command": "/path/to/webfront-agent", "args": ["--attach", "/path/to/private-directory", "--mcp"]} - } -} +{"mcpServers": {"webfront": {"type": "http", "url": "http://127.0.0.1:PORT/mcp", "headers": {"Authorization": "Bearer TOKEN"}}}} ``` -### Each command, in the terminal, in JSON and in MCP - -The JSON column completes `webfront-agent --attach DIRECTORY`; the MCP column is the `operation` and `arguments` of the -`webfront.start` tool, whose run is then read with `webfront.result`. - -| In the terminal | JSON command line | MCP `webfront.start` | Grant | -| --- | --- | --- | --- | -| `wf create app` | `--operation create --starter app` | `create`, `{"starter": "app"}` | `create` | -| `wf init` | `--operation init` | `init` | `init` | -| `wf install react@19.3.1` | `--operation install --package react@19.3.1` | `install`, `{"package": "react@19.3.1"}` | `install` | -| `wf restore` | `--operation restore` | `restore` | `restore` | -| `wf dev ui/main.ts` | `--operation preview --entry ui/main.ts`, after each edit | `preview`, `{"entry": "ui/main.ts"}` | `preview` | -| `wf check` | `--operation check` | `check` | `check` | -| `wf test [pattern]` | `--operation test [--pattern text]` | `test`, `{"pattern": "text"}` | `test` | -| `wf build [entry]` | `--operation build [--entry ui/main.ts]` | `build`, `{"entry": "ui/main.ts"}` | `build` | -| `wf embed ui/main.ts --output generated/AppUI.hpp` | `--operation embed --entry ui/main.ts --output generated/AppUI.hpp` | `embed`, `{"entry": ..., "output": ...}` | `embed` | -| look at the page | `--operation inspect` | `inspect` | `inspect` | -| click, type | `--operation click --page-id ID --element-id ID`; `fill` adds `--value TEXT` | `click`, `fill` | `interact` | -| call a C++ callback the owner listed | `--operation call --callback app.greet --value TEXT` | `call`, `{"callback": ..., "value": ...}` | `call` | +**3. Connect an MCP client** to it: pass the file to a client that takes one (`claude --mcp-config PATH/mcp.json`), or +copy the URL and the header into the client's **user** configuration. Never copy the token into the project, its `.mcp.json` +included: the developer file bridge reads the project. The token ends with the session; a new run prints a new URL and file. +The application must be running before the client connects. An agent with a shell can start it in the background and wait +for its `mcp.json`, or read the records of the running instances (project, grants, URL, path of `mcp.json`, never the token) +in the per-user sessions directory: `~/.local/state/webfront/sessions` on Linux, `~/Library/Application Support/WebFront/sessions` +on macOS, `%LOCALAPPDATA%\WebFront\sessions` on Windows. + +**4. Call the tools.** `webfront.session` gives the session ID, `webfront.start` starts an operation and returns its `runId` +at once, `webfront.result` reads its state and output until it ends, and `webfront.cancel` stops it. + +### Each command, in the terminal and in MCP + +The MCP column is the `operation` and `arguments` of the `webfront.start` tool, whose run is then read with `webfront.result`. + +| In the terminal | MCP `webfront.start` | Grant | +| --- | --- | --- | +| `wf create app` | `create`, `{"starter": "app"}` | `create` | +| `wf init` | `init` | `init` | +| `wf install react@19.3.1` | `install`, `{"package": "react@19.3.1"}` | `install` | +| `wf restore` | `restore` | `restore` | +| `wf dev ui/main.ts` | `preview`, `{"entry": "ui/main.ts"}`, after each edit | `preview` | +| `wf check` | `check` | `check` | +| `wf test [pattern]` | `test`, `{"pattern": "text"}` | `test` | +| `wf build [entry]` | `build`, `{"entry": "ui/main.ts"}` | `build` | +| `wf embed ui/main.ts --output generated/AppUI.hpp` | `embed`, `{"entry": ..., "output": ...}` | `embed` | +| look at the page | `inspect` | `inspect` | +| click, type | `click` `{"pageId", "elementId"}`, `fill` adds `"value"` | `interact` | +| call a C++ callback the owner listed | `call`, `{"callback": ..., "value": ...}` | `call` | - **`wf dev` has no agent operation.** It is a watch for a person at the window. An agent edits the files with its own tools and runs `preview` again; a person's `wf dev` may stay running meanwhile, and both use the same window. @@ -152,12 +148,12 @@ security boundary. Project code runs with the user's rights; this is not a sandb | Where an agent looks | What it finds | | --- | --- | -| The README, before the tutorial | The model, the three steps above and a `.mcp.json` | +| The README, before the tutorial | The model, the three steps above and the client configuration | | `AGENTS.md` in the project | `wf create` writes it beside the starter's sources; `webfront_write_agent_guide()` writes it at the root of a CMake project, and never replaces an existing file | -| The CMake configuration output | One `WebFront for agents:` line: the model, whether `webfront-agent` is built, and this page | +| The CMake configuration output | One `WebFront for agents:` line: the model, the MCP URL an application prints, and this page | | The terminal | The ready line names this page, `wf help` names `wf help agents` (environment 0.9.2); a missing manifest, a missing entry and an unknown starter answer with the next steps and the starters | -| stderr of the application | One line when a document root is served without the developer environment | -| `webfront-agent --agent-help` | The rules of the contract, starting with the model | +| stderr of the application | Its MCP URL and client configuration when automation is enabled; one line when a document root is served without the developer environment | +| The MCP `initialize` answer | Short `instructions`: how to use the four tools | The terminal texts belong to the developer environment and reach an application with the environment its library pins: the ones described here are in environment 0.9.2 (the ready line, the README, the CMake helpers and the stderr note come with diff --git a/docs/FORMS.md b/docs/FORMS.md index 5cf693c6..d825fed2 100644 --- a/docs/FORMS.md +++ b/docs/FORMS.md @@ -156,7 +156,7 @@ do not compile; the `C++26.FormsReflectionRejects` tests check each message. The result is an ordinary `Description<T>`: forms, inspectors and declarations do not depend on how it was produced. The `FormsReflectionTests` executable checks that the reflected description, its declaration and its form batch equal the hand-written ones; its test framework, the header -`test/unit/Bdd.hpp`, is compiled with the same C++26 flags, so that no executable mixes objects of both standards. CMake builds it only when the compiler +`include/webfront/testing/Bdd.hpp`, is compiled with the same C++26 flags, so that no executable mixes objects of both standards. CMake builds it only when the compiler supports reflection; the Linux CI job sets `-DWEBFRONT_REQUIRE_REFLECTION_TESTS=ON`, so that it cannot be skipped there. diff --git a/docs/FRONTENDS.md b/docs/FRONTENDS.md index 3d0b556d..74b4f650 100644 --- a/docs/FRONTENDS.md +++ b/docs/FRONTENDS.md @@ -17,6 +17,7 @@ A frontend is a type with: | `static constexpr Action action` | What `BasicWF` does once `open()` returns. | | `static void launch(address, port, page)` (optional) | Opens the interface and returns without waiting for it (the system browser spawns its opener command and does not wait for it to end). `BasicWF::start()` requires it; only a frontend without a window loop offers it (the system browser). A `launch(address, port, page, const ContentPolicy&)` overload is preferred when present; neither receives window options or the view-association proof. | | `static constexpr bool endsOnRequest` (optional) | `false` when `requestClose()` cannot end every session (`NativeOrBrowserFrontend` with the plain system browser as fallback); `webfront::UIThread` then refuses the frontend. | +| `static void openSecondaryWindow(address, port, file, policy, window, launch)` and `static bool closeSecondaryWindow(file)` (optional) | A second window beside the one `open()` runs (#616), callable from any thread while it runs; `invokeOnUIThread()` (UIExecutor.hpp) hops to the interface thread. Opening a page a secondary window already shows brings it to the front (a hidden window stays hidden and does not take the focus); the first window's end closes the others. A window is identified by the `file` string as given, query included. `WebKitGTKFrontend`, `WKWebViewFrontend` and `WebView2Frontend` implement it: `BasicWF::openSecondaryWindow()` throws `std::logic_error` for a frontend without it (CEF, the system browser), never opening a browser. `BasicWF::supportsSecondaryWindow` tells it from the frontend type; an optional `static bool secondaryWindowsAvailable()` tells it at run time, and `BasicWF::canShowSecondaryWindow()` combines both. `NativeOrBrowserFrontendFor` offers the functions only when its native frontend does, and reports them unavailable once it fell back to the system browser. The call waits for the interface thread (it runs at once on that thread): a `cppFunction` callback, which runs on the server's thread, schedules it with `app.uiExecutor()` instead of holding every exchange of the application while it waits. A window that cannot start throws the failure to the caller; one that fails to load later closes and writes the failure to stderr (the call has returned: nothing can throw it). A request that runs after the first window closed is refused with `std::logic_error`. A frontend whose first window cannot host another yet throws `frontend::WindowNotReady` (a `std::logic_error`): `BasicWF` and `invokeOnUIThreadWhenReady()` try again from another thread, and pass it to a caller on the interface thread. WebKitGTK shares the first window's network session (cookies, storage; downloads are tracked by the first window) and ignores `WindowOptions::media`. WKWebView shares its nonpersistent website data store and follows the first window's visibility (a hidden application shows no window and does not take the focus). WebView2 creates the second browser from the first window's environment, so the profile (storage, cookies) and the browser process are shared; it follows the first window's visibility, and has its own startup watchdog, with the first window's delay (the one `WebView2FrontendWithOptions` configured). A call made while the first window's environment is still being created waits for it (bounded by that window's watchdog); on the interface thread it throws `std::logic_error`. Placement is left to the toolkit. | | `static bool requestClose()` (optional) | Asks, from any thread, the session that `open()` runs to end as if the user had closed the window; false when nothing is open. `BasicWF::requestClose()` forwards it only for the application whose `show()` owns that session (its thread is the frontend's published interface thread). A frontend with an executor takes `requestClose(std::optional<UISession>)` and drops the request, on its interface thread, if another loop runs by then. | | `static constexpr bool requiresMainThread` (optional) | `open()` belongs to the process main thread; `webfront::UIThread` refuses the frontend at compile time. Undeclared means any thread. | @@ -209,6 +210,7 @@ Registry order determines the initial cache default: the first enabled embedded - `path-encoding`: load `encoded path #.html` and verify that its query and fragment survived. - `content-policy`: block a popup and a foreign-origin top-level navigation while keeping the original page alive. - `navigation-allow-list`: permit the same top-level destination through the explicit navigation allow-list. +- `second-window` (#616): a second window shares storage, a `cppFunction` and a pushed `jsFunction` with the first and carries the embedded-view proof; the same page again opens nothing; closing the second leaves the first usable and it can reopen; closing the first closes the second; a window opened as soon as the loop runs, before the first page connected, opens; a request that runs in the pass where the first window closed is refused (WebKitGTK, WKWebView). Frontends without the capability must refuse with `std::logic_error`. - `host-close`: a host thread exchanges with the page while `show()` runs, then `requestClose()` ends the session; a request before and after the window is refused. - `host-thread` (not CEF): `webfront::UIThread` runs the application on a secondary thread where the frontend allows it; elsewhere a window opened on a secondary thread must be refused with the main-thread diagnostic. - `view-association`: the page of the view connects with the secret of the launch and `UI::isEmbeddedView()` is true; a second connection of that page, from the same loopback address and without the secret, is not associated. @@ -272,7 +274,7 @@ The handle carries `kind` (`win32`: `HWND`, `cocoa`: `NSWindow*`, `gtk`: `GtkWin Call it inside an operation scheduled with `app.uiExecutor()` and do not keep the pointer. The window stays published until the loop ends, including after the user closed it, so check the object with the toolkit when that matters (`IsWindow`, `-[NSWindow isVisible]`). -The connection's window is the frontend's single window, reached through the association of ADR-020 rule 3 (`ui.isEmbeddedView()`); the +The connection's window is the frontend's primary window, reached through the association of ADR-020 rule 3 (`ui.isEmbeddedView()`). For a secondary connection, `ui.nativeWindow()` also identifies the primary window; per-secondary-window native handles are not implemented. The system browser never has one. `portalParent` is the `parent_window` of the desktop portals: under WebKitGTK `x11:<hex XID>` when the window is on X11, `wayland:<handle>` once `gdk_wayland_toplevel_export_handle` succeeds (either is tried every 100 ms for 5 s after the window is presented, until the surface exists and can be exported; empty until then); it is empty on Windows and macOS. A frontend author calls `nativeWindowHostOf<Frontend>().publish(...)` on the interface @@ -422,3 +424,13 @@ the native helper never selects CEF. | `WEBFRONT_EMBED_WKWEBVIEW` | OFF | Link the system Cocoa and WebKit frameworks for WKWebViewFrontend (macOS 13.3+ only) | | `WEBFRONT_EMBED_WEBKITGTK` | OFF | Enable the system WebKitGTK 6.0 embedded frontend (Linux only) | | `WEBFRONT_EMBED_CEF` | OFF | Download and link CEF so CEFFrontend is available (Windows, Linux x86_64 and aarch64, and macOS only). Other platforms fail at configure time | + +## Writing a native frontend + +WebKitGTK, WKWebView, WebView2 and CEF share their toolkit-independent logic in `include/webfront/frontend/`; a new native frontend declares only the calls of its toolkit. The shared parts are tested on Linux with fake windows (`test/unit/WindowRegistryTests.cpp`). + +- `EmbeddedFrontend.hpp`: `EmbeddedFrontend<Derived>` gives `uiExecutor()`, `nativeWindow()`, `requestClose()`, `initialize()`, `openSecondaryWindow()`, `closeSecondaryWindow()` and every overload of `open()`. The frontend declares `Host` (the tag of its executor and window hosts), `Options` (`ViewOptions`, which every native frontend takes: `startupTimeout`, `userDataFolder` (WebView2), `contentPolicy`, `window`, `visible`, `launch` and the test injections `chooseFiles`, `downloadDirectory`, `downloadFinished`, `answerScriptDialog`; a frontend ignores what its toolkit has no use for, and `WKWebViewOptions` and `WebView2Options` are aliases of it), `compiled`, `name` and `enable` (the message of a build without the engine), `secondaryWindows`, and the toolkit calls `openNative`, `closeNative`, `openSecondaryNative`, `closeSecondaryNative` (on the interface thread) and optionally `initializeNative`, `defaultOptions` and `waitsForFirstWindow`. Members that name the engine are instantiated only when `compiled` holds, so no `#if` surrounds them. A frontend without `initializeNative` throws from `initialize()` when it is not compiled; WebView2 declares an empty one, because its COM apartment belongs to each `open()`, and fails there. +- `WindowRegistry.hpp`: `WindowRegistry<Session, Hooks>` is the table of the secondary windows (open, bring to the front, close, retire a window that closed, reap it outside its own callback, clear when the first window ends) and `InterfaceSession<Registry>` is what an `open()` holds while its loop runs (attach, publish, then on every exit, also by exception: clear the secondary windows, withdraw the window, close the host). The hooks are `scheduleReap`, `cancelReap`, `present`, `close` and the `name` of the messages: an idle callback in WebKitGTK, a queued block in WKWebView, a message to the first window in WebView2. +- `StartupTrace.hpp`: `StartupTrace` (`WEBFRONT_STARTUP_TRACE=1`, with the one platform function that tells the age of the process) and `Presentation` (the window shows nearly transparent and becomes opaque once, at the page's first frame or after `Presentation::maximumDelayMs`; the frontend sets the opacity and runs the timer). + +The startup delay (`startupTimeout`) is an option of WKWebView, WebView2 and WebKitGTK (30 s by default, the same message when it expires); CEF has none. WKWebView and WebKitGTK start the secondary windows with the first window's delay and test injections, as WebView2 does. diff --git a/docs/HOST_INTEGRATION.md b/docs/HOST_INTEGRATION.md index e16474ac..c67500f1 100644 --- a/docs/HOST_INTEGRATION.md +++ b/docs/HOST_INTEGRATION.md @@ -157,6 +157,33 @@ host.request_stop(); // the user closed the window firs - Stop the host thread before `shutdown()` or the destruction of the application: no call into WebFront may still be running then. +## Several instances at once + +**The port.** A configuration that leaves `WebFrontConfig::port` empty uses the port in the environment variable +`WEBFRONT_PORT`, or `9002`, and, when `9002` is taken, a free port: several applications, of one program or of several, +start side by side with no setting. `9002` stays the default so that a newcomer's first application keeps one address (the +browser's `localStorage` and the other origin-bound storage follow the port). A port that is chosen, in the configuration or +by `WEBFRONT_PORT`, is never replaced: when it is taken the constructor throws a `std::system_error` that names the address, the +port and the cause. `WEBFRONT_PORT` is a number from 0 to 65535 (anything else throws `std::invalid_argument`) and `0` asks for +a free port at once, which is the setting for tens of instances, as on a server: nothing probes ports one after the other, the +system assigns each, and the frontend and `port()` receive the port really bound. `WebFrontLifeDeveloper`, `WebFrontLifeReact`, +`WebFrontLifeEmbedded` and `WebFrontHostLoop` also take `--port <n>` or `--port=<n>`; `HelloWorld` (whose listing is the README's) +and the PTY example read `WEBFRONT_PORT` only. On Windows a port in use is refused (`SO_EXCLUSIVEADDRUSE`), as on POSIX. + +**Cookies.** Cookies are not isolated by port: a cookie is shared by every port of a host, so state or authentication kept in a +cookie must not assume a port of its own, as the read binding's cookie names already do. + +**Browser profiles.** CEF and WebKitGTK keep one profile directory per executable. The first live instance keeps it, held by a +lock file (`.webfront-lock`), so a fixed port finds its storage again; every other live instance of the same executable gets +a directory of its own beside it (`<directory>.instances/<pid>-<n>`), removed when it ends, and the directories of instances that +died are removed by the next one (`frontend/ProfileLease.hpp`). Without that, Chromium hands the second process over to the first. +The CEF profile is `cef_cache/<executable>` beside the executable, one per executable; data written under the former shared `cef_cache` is not migrated (move it there to keep it). WebView2 shares one user data folder between processes by design, and a WKWebView data store is not persistent. The system +browser is the user's own. `WEBFRONT_STARTUP_TRACE` only writes to the standard error of its process. + +**Other alternatives.** A loopback address of its own (`WebFrontConfig::address = "127.0.0.2"`, any `127.x.y.z` on Linux; macOS +needs the alias) lets instances share a port, and it works today, the origin then differing by its address. A Unix socket is not +offered: a browser cannot connect to one, so it would need a proxy in front, which is the deployment's business. + ## Concurrency and lifetime, in short - Callbacks, handlers and task bodies run on the server thread, one at a time. They must not wait for that thread: diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 53821250..40db4fcd 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -27,6 +27,9 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer system browser, `app.requestClose()` from another thread, or `webfront::UIThread` where the frontend accepts a secondary thread (WebView2); a host loop cannot share the main thread with an embedded window. See [host integration](HOST_INTEGRATION.md). + A second native window of the same application (`app.openSecondaryWindow()`, #616) exists on WebKitGTK, WKWebView and WebView2; CEF + and the system browser refuse it with `std::logic_error` (`app.canShowSecondaryWindow()` tells it beforehand, also after `NativeOrBrowserFrontend` fell back to the browser), and the position of the window is left to the toolkit. The call waits + for the interface thread: a `cppFunction` callback runs it on `app.uiExecutor()` rather than hold the server's thread. - **Native pseudoterminals (opt-in).** `webfront::Pty` uses a Unix PTY on Linux and macOS or ConPTY on Windows 10 version 1809 and later. The page adapter requires a loopback bind and the application’s own browser origin. See the [PTY guide and standalone example](PTY.md). - **Developer environment.** `NativeApp::bootstrap("developer")` loads the verified, pinned environment selected by `DeveloperReleaseData.hpp`. Its terminal provides `wf init`, `create`, @@ -42,15 +45,21 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer covers the console, developer and embedded Game of Life stages; Hello World and the host loop (`examples/host-loop/`, a Boing Ball ray-traced by the host on the CPU or with optional CUDA; see [the host-loop example](HOST_LOOP_EXAMPLE.md) for its measurements and limits) are also in the default build. -- **Developer automation (opt-in).** `webfront-agent` provides local stdio MCP and a JSON CLI - for an explicitly launched developer window. Native grants select check/build/test/preview, - bounded inspection and semantic actions. [Automation](AUTOMATION.md) documents provisioning, - lifecycle, limits and the supported MCP profile. It requires a compatible environment - (0.6.3 or later), supplied as a rebuilt archive or verified published distribution. Explicitly shared human windows support authenticated - native attachment. This does not discover arbitrary processes or isolate untrusted project code. - An application opts in to being driven with `automation::enableAutomation` (its own window and callbacks), shared sessions are - listed by `webfront-agent --list`, and `--print-mcp-config` generates the client configuration. The owner may allow-list application callbacks that an agent reaches through the `call` operation, and the terminal, `wf help` and - the starter's `AGENTS.md` announce automation (environment 0.6.6). Environment 0.6.6 is published; the release pin selects 0.9.2. First-contact guidance for agents (README section, `docs/DEVELOPING_WITH_AGENTS.md`, `webfront_write_agent_guide()`, configuration and startup notices) comes with the library; the `app` starter, `wf help agents` and the errors that give the next steps come with environment 0.9.2 (#561). +- **Developer automation (opt-in).** An application that calls `automation::enableAutomation` serves MCP itself over + Streamable HTTP, on a loopback listener of its own with a session Bearer token, prints its URL and writes a private + `mcp.json` client configuration; no other program is built or launched ([ADR-025](adr/ADR-025-mcp-http-dans-l-application.md), + #632). Native grants select check/build/test/preview, bounded inspection, semantic actions, the setup operations and the + owner's allow-listed callbacks (`call`). Several instances run side by side, each with its own URL and discovery record. + A fixed MCP port and application-supplied token can keep a client configuration stable; authentication can also be + explicitly disabled for development, with the local-process risks described in [Automation](AUTOMATION.md) (#637). + Remote access is out of scope and automation does not compile with `WEBFRONT_DISTRIBUTION`. This does not isolate + untrusted project code. [Automation](AUTOMATION.md) documents the listener, lifecycle, limits and the supported MCP profile. + The `webfront-agent` launcher, its JSON CLI and MCP on stdio were removed. The environment 1.0.2 pinned in + [`DeveloperReleaseData.hpp`](../include/webfront/system/DeveloperReleaseData.hpp) describes MCP; + the starter guidance for stable client configuration is in the 1.0.3 sources and will reach `wf create` in the next + environment release. Until then agents can follow `docs/DEVELOPING_WITH_AGENTS.md`. First-contact + guidance for agents (README section, `docs/DEVELOPING_WITH_AGENTS.md`, `webfront_write_agent_guide()`, configuration and + startup notices) comes with the library. - **Maintaining WebFront.** The repository is itself a `wf` project, selected with `--manifest-dir js/developer`. Build and publish its environment using [PUBLISHING](../js/developer/tools/PUBLISHING.md). Regenerate the core's versioned headers @@ -159,7 +168,9 @@ are retained for investigation; diagnostics alone do not establish a correction. - The developer environment and `NativeDebugFS` are trusted development facilities, not sandboxes. Manifest permissions bound only the scripts' `context` API. Only browser packages install; installation scripts and native add-ons do not run. The [content policy](CONTENT_POLICY.md) - restricts browser origins and navigation but provides neither TLS nor client authentication. + restricts browser origins and navigation. The optional [TLS listener](TLS.md) adds HTTPS and WSS + with TLS 1.3 and ChaCha20-Poly1305. Each listener admits 16 concurrent handshakes on the I/O thread. + Client authentication remains an application responsibility. - `fs::NativeStorage` confines writable storage to a declared root while resolving each path, but on POSIX it cannot prevent the effective user or the superuser from moving a directory out of the root during an operation: it detects such a move before a commit and after each operation, at @@ -175,9 +186,18 @@ are retained for investigation; diagnostics alone do not establish a correction. Windows/macOS CEF deployment is not qualified. WebView2 needs its installed Evergreen runtime; fixed-version runtime packaging, application installers and accessibility remain application work. - `WebView2Frontend::open()` releases the STA it initialized. When a window is closed while the runtime is still - starting and the same thread then opens another one, the WebView2 runtime (observed with 157.0.4341.46) can keep one - COM initialization of its own: the thread then remains in its STA after `open()` returns (#564). A window that ran to - its end leaves none. + starting, or by a page that closes it on a load failure, the WebView2 runtime (observed with 157.0.4341.46) can keep a + COM initialization of its own: the thread is then still in an STA (apartment type 3, qualifier 0) when `open()` returns + (#564, #638). Measured on the Windows CI runner under load, over repeated `show()` calls of the + `WebView2Lifecycle-repeated-show` case (the repetition and its apartment log were temporary): a page whose bridge + connection is rejected and that closes the window (`rejected-ready.html`) left an STA in 2 of 600 calls, then in 1 of 1031 + with `open()` dispatching the messages queued on the thread before it released its apartment, so that drain does not + remove it and was not kept; a page that closes its window (the encoded-path page) and a page that ran to its end and + closed it (`no-bridge.html`) left none in more than 1600 calls each. That is 3 cases in about 1600 calls after a load + failure, of the order of one in 500; the cause is not established. In the one case where another `show()` followed on the + same thread, the remainder was gone after that `show()`, so it can be a delayed release rather than a permanent one; one + case does not prove it. Do not rely on the thread being out of its STA immediately after `open()` returns. The test + checks the apartment only after a page that ran to its end. - The low-level DOM batch command and optional embedded interpreter are implemented; see [the wire contract](adr/ADR-003-protocole-binaire-et-bornes.md#commande-dom-dombatch-code-5-version-1). The per-connection document/node API, events (callbacks or `co_await node.next(name)`) and grouped diff --git a/docs/TEST_TIERS.md b/docs/TEST_TIERS.md index fe1b4334..8eea2701 100644 --- a/docs/TEST_TIERS.md +++ b/docs/TEST_TIERS.md @@ -5,9 +5,9 @@ to the standard tier. | Tier | Label | Content | When it runs | | --- | --- | --- | --- | -| Fast | `fast` | C++ unit tests (`test/unit/Bdd.hpp`) and the Python tool tests; no browser, no nested build | Locally on demand, and as the first test step of every Linux/Windows/macOS desktop job | +| Fast | `fast` | C++ unit tests (`include/webfront/testing/Bdd.hpp`) and the Python tool tests; no browser, no nested build | Locally on demand, and as the first test step of every Linux/Windows/macOS desktop job | | Standard | none, or `web-integration` | Everything but the portability tests: unit tests, real-browser integration, `wf` commands, embedded builds | Every pull request and every push to `develop` or `master` | -| Portability | `portability` | The library consumed from another project: `AddSubdirectoryConsumer` | Weekly, and on every pull request into `master` | +| Portability | `portability` | The library consumed from another project: `AddSubdirectoryConsumer`, `BddConsumer` | Weekly, and on every pull request into `master` | ```sh ctest --test-dir build -L fast --parallel 4 # about one second diff --git a/docs/TLS.md b/docs/TLS.md new file mode 100644 index 00000000..518a6842 --- /dev/null +++ b/docs/TLS.md @@ -0,0 +1,129 @@ +# Serving HTTPS directly + +Include `<webfront/tls/WebFront.hpp>` and use `webfront::tls::WebFront<>` for a +TLS-only listener. It serves HTTP/1.1 and the WebFront bridge over WSS on the same port. +The component is header-only and links without a TLS library. + +> The TLS profile is proposed and its constant-time behavior has not been audited. +> Limit access to controlled networks while it is being qualified. For an +> Internet-facing listener, use a deployment proxy with connection admission +> controls and handshake deadlines. + +```cpp +#include <webfront/tls/WebFront.hpp> + +int main() { + auto credentials = std::make_shared<webfront::tls::Credentials>( + "/path/to/fullchain.pem", "/path/to/privkey.pem"); + webfront::tls::WebFront app({ + .address = "127.0.0.1", + .port = "8443", + .contentPolicy = {.allowMissingOrigin = false}, + .tlsCredentials = credentials, + }); + app.cppFunction("greeting", [] { return std::string("Hello over HTTPS"); }); + app.run(); +} +``` + +Use an ECDSA P-256 leaf certificate whose SAN covers the DNS name users visit. +Supply the PEM chain in leaf-first order and an unencrypted PEM private key +as a single `PRIVATE KEY` (PKCS#8) or `EC PRIVATE KEY` (SEC1) block. The files +accept whitespace around the PEM blocks. Extra text such as `Bag Attributes` +and separate `EC PARAMETERS` blocks are refused. To generate a single SEC1 +block, use `openssl ecparam -name prime256v1 -genkey -noout -out privkey.pem`. +Give the application account read access to the key. +WebFront checks the structure of each certificate and that the leaf matches the +private key, but not validity dates or the chain's trust: the browser does. +After the certificate manager has written both renewed files, call +`credentials->reload(fullchain, privkey)` from the application's renewal hook. +It checks that the leaf and key match before publishing them to new handshakes. +A failed reload throws and preserves the active identity. Existing connections +continue with their negotiated keys. + +Open the deployment URL in the browser. When using `show()` on a local bind, +the certificate must cover the configured address used in the window URL. +`start()` (return at once, system browser) needs a frontend that provides +`launchHttps(address, port, page)`; today only `DefaultBrowserFrontend`, the +default, does. With another frontend, `start()` fails to compile; use `show()` +or open the URL yourself. +The browser verifies the certificate chain and server name. WebFront applies +the usual bridge origin policy. The file-service binding cookie carries `Secure`. +File reads for non-associated clients require an explicit `remoteFileTransport` +declaration, typically `httpsByDeployment`. The default `refused` applies to +TLS listeners as well. Client authentication and authorization belong to the +application. A non-browser client can supply its own `Origin` header. The +example requires the header so requests without one are refused. + +The initial profile negotiates TLS 1.3, X25519, ECDSA P-256 with SHA-256 and +`TLS_CHACHA20_POLY1305_SHA256`. Clients must offer this suite. The profile +uses full handshakes and HTTP/1.1. If a client sends ALPN, it must offer +`http/1.1`. An ALPN offer without it is rejected with `no_application_protocol` +(alert 120). Where clients require AES-GCM, HTTP/2, +or another certificate type, terminate TLS at the deployment proxy and +configure `httpsByDeployment` if file-service reads are enabled. +Client 0-RTT ciphertext offered with a PSK is discarded, up to 64 KiB. + +The handshake parser limits ClientHello to 64 KiB and 128 extensions, and the +receive buffer to 16,640 bytes of ciphertext. Incoming handshake messages may +span records, with one message at a time. The server supports the ClientHello, +optional second ClientHello and Finished sequence described in the +[decision record](adr/ADR-024-tls-integre.md). + +Each listener admits up to 16 concurrent TLS handshakes, with a ten-second +deadline from accept through Finished. When all slots are occupied, a newly +accepted socket is closed immediately. Established connections release their +slot. The two X25519 operations and the CertificateVerify signature run on +the I/O thread. A sustained rate of incoming handshakes can saturate that +thread and cause denial of service, including for established HTTP/WSS +connections. The limit of 16 bounds the work in progress, not an attacker's +reach: sixteen idle connections keep every slot for up to ten seconds and can be +renewed, so it is not a defence against denial of service. Put a rate limiter or +a firewall in front of an exposed listener. WebFront writes a warning to standard error when the integrated +listener is configured outside loopback. Enable +`log::Debug` with a log sink to see handshake failure reasons and error codes. + +On orderly WSS closure initiated by the peer, WebFront answers the WebSocket +Close frame and then sends TLS `close_notify`. The secure queue retains the +active frame and discards other queued frames and subsequent writes once the +peer's Close is accepted. The TCP queue follows its existing stop behavior. +If TLS closure is requested during a send, the alert follows the current +complete TLS record. Local `stop()` during a write can cancel that record, +so the peer sees a truncated TLS stream without `close_notify`. A reset or +failed write can also prevent the alert from being sent. + +A peer's `KeyUpdate(update_requested)` is answered before the next +application data record. The response stays pending while the server is idle. + +When using `tls::Server` directly, run handshakes for each acceptor on its I/O +thread and serialize `Send` calls on each socket. HTTP and WebSocket enforce +this contract when using `tls::WebFront`. + +## Constant-time regression + +On Linux with GCC or Clang, Valgrind and its development headers installed, the optional +`TLSConstantTime` CTest case marks the private inputs to `p256Base` and `x25519` +undefined and checks compiler-generated branches and addresses with Memcheck. +The probe passed locally on x86-64 with GCC 16.1 and Clang 21 at `-Os` and `-O3`. +The probe covers those scalar operations and compiler configurations. It leaves +an audit of the rest of TLS and other targets, including Thumb-2, outstanding. + +## Size, memory and handshake time + +On Linux x86-64 with GCC 16.1, a minimal app with one bridge callback built at +`-Os -DNDEBUG -ffunction-sections -fdata-sections -Wl,--gc-sections` gained +47.3 KiB of `.text` and 5.5 KiB of `.rodata` when the TCP provider was +replaced by the TLS provider. The TLS headers total about 1,500 lines, including the in-tree primitives and comments. + +In the same binaries, 200 open loopback WebSockets increased Linux +`smaps_rollup` private dirty memory by about 3.5 KiB more per idle connection +for WSS than for WS. Giving each socket 16,384 bytes of an incomplete frame +increased the WSS overhead to about 18.8 KiB per connection. These are process +measurements after a warm-up connection and include allocator overhead. +Thumb-2 size and peak memory during the handshake remain unmeasured. + +On an AMD Ryzen 9 3900X, an OpenSSL-backed Python client completed 200 +sequential loopback handshakes in 2.0 ms at the median and 2.2 ms at the 95th +percentile. The measurement starts after TCP connect and ends after TLS +negotiation, following ten warm-up connections. It includes both endpoints +and excludes HTTP traffic. diff --git a/docs/adr/ADR-008-contenu-de-confiance-et-origines.md b/docs/adr/ADR-008-contenu-de-confiance-et-origines.md index 2c493d50..df17f311 100644 --- a/docs/adr/ADR-008-contenu-de-confiance-et-origines.md +++ b/docs/adr/ADR-008-contenu-de-confiance-et-origines.md @@ -37,7 +37,9 @@ peut forger cet en-tête. `Host` ne donne pas une permission de bridge. Que les dérogations de développement demeurent explicites. DevTools et menus restent activés par défaut. Le navigateur système contrôle sa propre navigation ; le serveur y applique néanmoins le contrôle du bridge. Les capacités des moteurs diffèrent, notamment les popups WKWebView. -WebFront cible du contenu de confiance, sans TLS ni authentification intégrés. +WebFront cible du contenu de confiance. Le TLS optionnel ([ADR-024](ADR-024-tls-integre.md)) protège la confidentialité +et l'intégrité du transport. Il authentifie le serveur auprès du navigateur. Le contrôle d'origine reste seul juge +de l'accès au pont et WebFront ne fournit pas d'authentification des clients. Que le secret de lancement d'une vue intégrée (#453) ne s'ajoute pas au contrôle d'origine : il ne donne aucun accès au pont, que le contrôle d'`Origin` règle seul. Il ne sert qu'à savoir si la connexion vient de la vue de diff --git a/docs/adr/ADR-010-composants-et-outils-optionnels.md b/docs/adr/ADR-010-composants-et-outils-optionnels.md index 796e2ad8..96efb47b 100644 --- a/docs/adr/ADR-010-composants-et-outils-optionnels.md +++ b/docs/adr/ADR-010-composants-et-outils-optionnels.md @@ -45,6 +45,8 @@ Le terminal édite les lignes dans le navigateur et appelle les commandes C++. L navigateur peuvent traiter une commande ou la laisser continuer côté C++. Leurs interruptions ne promettent pas d’arrêter une commande C++. +Le TLS serveur est un composant hors du cœur ([ADR-024](ADR-024-tls-integre.md)). + Pour `wf`, HTTPS et vérification SHA-512 se font dans le navigateur. C++ valide les chemins, reçoit les chunks séquentiels et installe via staging puis commit. `ToolStore` conserve `webfront-tools.lock.json` et les fichiers sous `.webfront/tools/`. `PackageFS` utilise le même @@ -56,7 +58,7 @@ l’autorité du bridge de l’application ; c’est une fonction de développem - Étendre le protocole pour chaque composant : évité, réutiliser les types du bridge. - Écraser le handler UI global : remplacé par des abonnements à durée de vie explicite. -- Implémenter TLS ou un registre de paquets C++ dans le cœur : le navigateur fournit HTTPS +- Implémenter un registre de paquets C++ dans le cœur : le navigateur fournit HTTPS et npm fournit métadonnées et distribution. - Installer directement dans le répertoire final : rejeté au profit de transactions pour préserver la version installée en cas d’échec. diff --git a/docs/adr/ADR-012-preuves-et-tests.md b/docs/adr/ADR-012-preuves-et-tests.md index ea52709b..1e26f843 100644 --- a/docs/adr/ADR-012-preuves-et-tests.md +++ b/docs/adr/ADR-012-preuves-et-tests.md @@ -12,11 +12,12 @@ | 1.5 | 2026-10-18 | Acceptée | Ambroise Leclerc | Durcissement des décodeurs, assainisseurs et tests par génération d’entrées dans la CI. | [d6f086d](https://github.com/ambroise-leclerc/WebFront/commit/d6f086d50350379162ab01e7bdba2a734646d24d) | | 1.6 | 2026-10-19 | Acceptée | Ambroise Leclerc | Contrôles hors ligne de fraîcheur et de contenu des ressources gzip reproductibles. | [b031ab5](https://github.com/ambroise-leclerc/WebFront/commit/b031ab58ea9cc32290d701094c1333bab455e67f) | | 1.7 | 2026-11-14 | Acceptée | Ambroise Leclerc | Catch2 remplacé par `test/unit/Bdd.hpp`, un cadre BDD en un seul en-tête. | [54c0d0f](https://github.com/ambroise-leclerc/WebFront/commit/54c0d0fd35a414e01e2cff0c27882695ca9a4e9d) | +| 1.8 | 2026-11-23 | Acceptée | Ambroise Leclerc | Le cadre BDD devient une interface publique maintenue : `WebFront::Bdd`, `webfront_bdd_discover_tests` et `docs/BDD.md`. | [1386947](https://github.com/ambroise-leclerc/WebFront/commit/138694770e3849cd089f7a71120a332ed445f496) | ## État et chronologie **Acceptée.** Décision initiale : **2020-04-19** (version 1.0). -Dernière révision : **2026-11-14** (version 1.7). +Dernière révision : **2026-11-23** (version 1.8). Le présent texte expose la décision en vigueur ; le tableau retrace ses états antérieurs. ## Contexte @@ -28,7 +29,7 @@ comme sous-projet constituent elles aussi des contrats observables. ## Décision Que les tests unitaires, sous `test/unit/`, vérifient unités, états et erreurs à l’aide de simulacres déterministes. -Ils emploient `test/unit/Bdd.hpp`, un cadre BDD tenant dans un seul en-tête : un +Ils emploient `include/webfront/testing/Bdd.hpp`, un cadre BDD tenant dans un seul en-tête, interface publique maintenue (`docs/BDD.md`) : un scénario est un objet `const Scenario` nommé, ses sections `given`/`when`/`then` sont des lambdas, et `require`/`check` situent un échec par `std::source_location`. Le cadre rejoue un scénario jusqu’à avoir parcouru chacune de ses feuilles, une nouvelle par passe, comme le faisait Catch2, dont seul ce sous-ensemble servait et dont la diff --git a/docs/adr/ADR-019-developpement-automatisable-et-agents.md b/docs/adr/ADR-019-developpement-automatisable-et-agents.md index a9d41b61..b67906f3 100644 --- a/docs/adr/ADR-019-developpement-automatisable-et-agents.md +++ b/docs/adr/ADR-019-developpement-automatisable-et-agents.md @@ -9,6 +9,7 @@ | 1.2 | 2026-10-29 | Acceptée | Ambroise Leclerc | Décision fondée sur les livraisons #405, #406 et #407 : contrat v1, CLI/MCP stdio, attachement authentifié, protections et réserves ; qualification de cinq modèles locaux, preuves CI et préparation de la distribution 0.6.3. | [#407](https://github.com/ambroise-leclerc/WebFront/pull/407), tête `4a1c92b`, intégration `22f6795` ; révision ADR `cf1bf15`. | | 1.3 | 2026-11-08 | Proposée | Ambroise Leclerc | Issue #501 : une application consommatrice active l'automatisation par un appel natif explicite (`enableAutomation`), avec les mêmes grants, le même canal privé et la même révocation ; découverte par enregistrement par utilisateur sans capacité (`--list`) ; configuration cliente générée sans grant ni secret. L'exposition de `cppFunction` comme outils MCP typés était écartée en 1.3 (arbitrée en 1.4) : elle exigeait une liste blanche native, des types bornés et ses propres grants, donc une décision distincte. | Issue #501. | | 1.4 | 2026-11-09 | Proposée | Ambroise Leclerc | Issue #501 : arbitrage de l'exposition des callbacks. Une opération `call`, sous la permission `call` du propriétaire, invoque un callback **nommé dans une liste blanche native** (`AutomationOptions::callbacks`, publiée dans la session et le registre de découverte) avec au plus un argument texte et ne rapporte qu'un scalaire ou une courte liste de scalaires. Ni motif, ni nom `webfront.*`, ni liste par le manifeste ou l'agent ; sans liste, tout appel est refusé. Ce n'est pas un outil MCP par callback : l'opération passe par `webfront.start`, dont le contrat reste à quatre outils. | Issue #501. | +| 1.5 | 2026-11-21 | Proposée | Ambroise Leclerc | Issue #632 : amendement par l'[ADR-025](ADR-025-mcp-http-dans-l-application.md). Le MCP Streamable HTTP local, différé ci-dessous, est retenu dans l'application, sur un écouteur loopback distinct authentifié par un jeton Bearer de session ; il remplacera, une fois livré, le relais stdio et l'attachement par `webfront-agent`. Contrat, contrôleur, grants, liaison de page et modèle de menace inchangés. Version 1.2 de l'ADR-025 : `webfront-agent`, son CLI JSON, le MCP stdio et le canal d'attachement sont retirés ; les sections « CLI et MCP local stdio » et « Attachement à la même fenêtre » ci-dessous décrivent l'état antérieur. | Issue #632. | ## État et portée diff --git a/docs/adr/ADR-020-services-systeme.md b/docs/adr/ADR-020-services-systeme.md index 67ff1643..03eb0dbc 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -281,23 +281,25 @@ lève). - **Exposition du jeton.** Chaque réponse de lecture porte `Cache-Control: no-store` et `Referrer-Policy: no-referrer` ; le jeton n'apparaît dans aucun journal HTTP ni diagnostic (chemin masqué). Le cookie de liaison porte `Secure` lorsque la page est servie en HTTPS. -- **Transport : déclaré, jamais déduit.** WebFront ne fournit pas TLS (ADR-008) et ne peut pas savoir comment un client - l'atteint : un mandataire ou un tunnel présente une connexion de boucle locale pour un client distant, et des en-têtes - `Forwarded`/`X-Forwarded-*` peuvent être forgés. WebFront ne lit donc **ni l'adresse ni ces en-têtes** pour décider. +- **Transport : déclaré, jamais déduit.** Par défaut, WebFront ne fournit pas TLS (ADR-008) et ne peut pas savoir comment + un client l'atteint : un mandataire ou un tunnel présente une connexion de boucle locale pour un client distant, et des + en-têtes `Forwarded`/`X-Forwarded-*` peuvent être forgés. WebFront ne lit donc **ni l'adresse ni ces en-têtes** pour + décider. Le fournisseur de TLS intégré ([ADR-024](ADR-024-tls-integre.md)) n'y change rien : il ajoute seulement que + le cookie de liaison porte `Secure` lorsque WebFront termine TLS, sans que le transport devienne local pour autant. Une connexion est de transport local seulement si elle est **associée à la vue d'un frontend intégré** : son secret est remis à la vue par l'adaptateur, dans le processus, sans transiter par une ligne de commande, une URL ou un historique. Aucun secret transmis au navigateur système (fragment de l'URL ouverte) n'atteste le transport : la ligne de commande et l'historique peuvent le divulguer, et un acteur qui le présente le premier depuis un navigateur distant serait accepté ; l'échec ultérieur de l'association légitime ne protège pas cette première connexion. Pour toute connexion non associée, dont celles du navigateur système, le transport est inconnu, quelle que soit son - adresse : lectures et écritures de fichiers y sont refusées, sauf déclaration explicite de l'application sur son - déploiement (`remoteFileTransport`) : + adresse et quel que soit le fournisseur : lectures et écritures de fichiers y sont refusées, sauf déclaration + explicite de l'application sur son déploiement (`remoteFileTransport`) : - `refused` (défaut) ; - `loopbackAttested` : WebFront vérifie que le serveur n'écoute que sur la boucle locale ; l'intégrateur atteste qu'aucun mandataire ni tunnel ne l'expose et que la machine n'est pas partagée avec des utilisateurs non fiables. C'est la déclaration attendue d'une application de bureau qui utilise le navigateur système ; - `encryptedByDeployment` : le déploiement chiffre sous HTTP (VPN, tunnel) alors que le navigateur utilise `http://` : le cookie n'est pas `Secure`, qu'un navigateur refuserait ; - - `httpsByDeployment` : le navigateur atteint l'application en `https://` (mandataire inverse TLS) : le cookie est `Secure` ; + - `httpsByDeployment` : le navigateur atteint l'application en `https://` (TLS intégré ou mandataire inverse TLS) : le cookie est `Secure` ; - `plaintextAccepted` : réseau isolé de confiance. Hors la part vérifiée de `loopbackAttested`, ces déclarations sont des attestations de l'intégrateur, que WebFront ne @@ -506,9 +508,10 @@ autorisations explicites, backend par connexion). peuvent lire les URL les unes des autres. - **Coût accepté :** un cookie de liaison par client, à qualifier dans chaque moteur ; les téléchargements gérés par l'adaptateur doivent le présenter. -- **Risque :** WebFront ne chiffre pas et ne peut pas attester le transport ; `remoteFileTransport` repose sur la - déclaration de l'intégrateur. Une déclaration fausse expose jeton et contenu. Par défaut, toute connexion non - associée est refusée, y compris celle du navigateur système. +- **Risque :** avec le fournisseur TCP, une attestation de transport fausse peut exposer le jeton et le contenu. + Avec le TLS intégré, le chiffrement du transport et le cookie `Secure` protègent l'échange. Le cookie lie un profil + de navigateur et l'application reste responsable de l'authentification du client. La valeur `refused` refuse par défaut + les lectures via toute connexion non associée. - **Coût accepté :** une application qui utilise le navigateur système doit déclarer `loopbackAttested` pour accéder aux fichiers de l'hôte ; sans cette déclaration, seuls les fichiers du client sont disponibles. - **Coût accepté :** les fichiers actifs ne s'affichent pas en ligne ; un aperçu HTML ou un SVG interactif exige une diff --git a/docs/adr/ADR-024-tls-integre.md b/docs/adr/ADR-024-tls-integre.md new file mode 100644 index 00000000..e6fc5a2d --- /dev/null +++ b/docs/adr/ADR-024-tls-integre.md @@ -0,0 +1,35 @@ +# ADR-024 — TLS intégré + +## Versions + +| Version | Date | Statut | Auteur | Changement | Référence | +| --- | --- | --- | --- | --- | --- | +| 1.0 | 2026-11-21 | Proposée | Ambroise Leclerc | Fournisseur TLS 1.3 optionnel et règles de qualification. | [PR #635](https://github.com/ambroise-leclerc/WebFront/pull/635) | + +Un fournisseur réseau optionnel termine TLS 1.3 avant de livrer le flux au serveur HTTP et au pont WebSocket. +Le cœur HTTP garde son fournisseur TCP. Un port TLS sert exclusivement HTTPS et WSS avec HTTP/1.1. +Le profil initial utilise X25519 (avec HelloRetryRequest), ChaCha20-Poly1305, SHA-256 et ECDSA P-256 +avec nonce RFC 6979. AES-GCM reste conditionné à une implémentation à temps constant raisonnable. +La reprise par tickets ajouterait une politique de rotation, une durée de vie et un second chemin de handshake. +Le premier profil fait un handshake complet à chaque connexion. Chaque écoute admet jusqu'à 16 négociations +simultanées et ferme immédiatement les connexions excédentaires. Chaque négociation a un délai de dix secondes. +Le serveur écarte jusqu'à 64 Kio de données anticipées refusées pendant la négociation. La cryptographie s'exécute +sur le thread d'E/S. Un débit soutenu de nouvelles négociations peut saturer ce thread et causer un déni de service +pour les connexions établies. Un déploiement exposé à Internet s'appuie sur un proxy avec contrôle d'admission. + +L'application fournit une chaîne PEM et une clé P-256 via la configuration. Le rechargement explicite +publie une paire complète après validation. Les handshakes en cours conservent leur instantané. +Le navigateur valide la chaîne et le nom du serveur. TLS protège le transport, tandis que la politique +d'origine continue de décider de l'accès au pont. Le profil ne demande aucun certificat au client. +Le serveur sait que le transport est chiffré lorsqu'il termine TLS et marque alors le cookie de liaison `Secure`. +Les lectures de fichiers pour un client non associé restent soumises à une déclaration explicite (ADR-020). + +Le composant demeure header-only, sous `include/webfront/tls/`. Ses primitives sont implémentées dans WebFront à partir des spécifications +[RFC 7748](https://www.rfc-editor.org/rfc/rfc7748), [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439), +[SEC 1](https://www.secg.org/sec1-v2.pdf), [SEC 2](https://www.secg.org/sec2-v2.pdf) et +[RFC 6979](https://www.rfc-editor.org/rfc/rfc6979). La génération de secrets utilise l'aléa de l'OS. Les opérations +sur des secrets visent des accès mémoire et un contrôle de flux indépendants de ces secrets. La qualification +exige une vérification du code produit par les compilateurs et architectures supportés. Cet audit reste à faire. Les vecteurs des RFC, les refus de protocole, +le fuzzing et un test navigateur HTTPS/WSS font partie de la qualification. Les régressions de sécurité +peuvent être signalées en privé aux mainteneurs. La maintenance du composant inclut la revue des primitives, +le suivi des errata des spécifications et des mesures reproductibles de taille et de mémoire. diff --git a/docs/adr/ADR-025-mcp-http-dans-l-application.md b/docs/adr/ADR-025-mcp-http-dans-l-application.md new file mode 100644 index 00000000..6c9bcf56 --- /dev/null +++ b/docs/adr/ADR-025-mcp-http-dans-l-application.md @@ -0,0 +1,251 @@ +# ADR-025 : Servir le MCP en Streamable HTTP depuis l'application, sur la boucle locale + +## Versions + +| Version | Date | État | Auteur | Évolution | Révision Git | +| --- | --- | --- | --- | --- | --- | +| 1.0 | 2026-11-21 | Proposée | Ambroise Leclerc | Issue #632, après #617 (instances simultanées) et #631 (TLS 1.3 intégré) : l'application sert elle-même le MCP en Streamable HTTP sur un écouteur loopback distinct, authentifié par un jeton Bearer de session ; accès distant exclu ; Host et Origin stricts ; découverte par instance ; automatisation refusée à la compilation d'une build de distribution ; ordre de migration et sort de `webfront-agent`. Amende l'ADR-019 (ligne « MCP Streamable HTTP local » du comparatif, section « CLI et MCP local stdio » et ligne « DNS rebinding » du modèle de menace). | — | +| 1.1 | 2026-11-22 | Acceptée (livraison à faire) | Ambroise Leclerc | Décision acceptée avant le code de transport, comme l'exige #632. Précision d'implémentation du point 2 : l'écouteur reprend le modèle d'admission du canal actuel (file, délais, workers) et l'analyseur `http::Request` de `HTTPServer.hpp`, plutôt qu'une instance de `http::Server`, qui n'a ni file bornée ni délai de réception. | Issue #632. | +| 1.2 | 2026-11-22 | Acceptée (livraison à faire) | Ambroise Leclerc | Étape 4, arbitrée par le propriétaire : le but de #632 est un seul exécutable, l'application de l'utilisateur. `webfront-agent` est retiré en entier (relais stdio, CLI JSON, `--serve`, `--attach`, `--list`, `--print-mcp-config`, `webfront_add_agent()`, `WEBFRONT_BUILD_AUTOMATION`), sans exemple `agent-host` ; le canal JSON-lines disparaît avec lui. HTTP devenant le seul transport, l'option `.http` est supprimée et `listen` devient `directory`, facultatif. Les régressions pilotent un programme de test (`automation_host`) qui appelle `enableAutomation`. Les statuts 70 et 71 du lanceur disparaissent avec lui ; le 72 d'`onUnresponsive` reste. | Issue #632. | +| 1.3 | 2026-11-22 | Acceptée (livraison en cours) | Ambroise Leclerc | Revue de la PR #636 : `MCP-Protocol-Version` est aussi vérifié pour `DELETE` et pour les réponses du client, et un message refusé ne compte pas comme activité pour l'éviction ; une réponse du client doit être une réponse JSON-RPC 2.0 ; `Accept` est analysé par type de média et qualité ; la garde de distribution couvre l'inclusion de `Enable.hpp`, pas seulement l'appel. | PR #636. | + +## État et portée + +**Acceptée le 2026-11-22**, avant tout code de transport (critère de #632) ; la livraison suit l'ordre de « Migration ». Elle remplace, +une fois livrée, les parties « CLI et MCP local stdio » et « Attachement à la même fenêtre » de l'[ADR-019](ADR-019-developpement-automatisable-et-agents.md) ; +le contrat v1 (`Contract.hpp`), le contrôleur (`Session.hpp`), les grants natifs, la liste blanche de `call`, la liaison de page +(`Binding.hpp`, secret de lancement, preuves HMAC) et le modèle de menace de l'ADR-019 restent en vigueur. Elle ne modifie pas +le codec binaire (ADR-003), ni le contrôle d'origine du pont (ADR-008), ni le fournisseur TLS (ADR-024). + +## Contexte + +Le MCP passe aujourd'hui par un second exécutable, `webfront-agent`, qui relaie un canal JSON-lines privé (TCP 127.0.0.1, +capacité de 256 bits dans un répertoire privé) vers un MCP sur stdio. Une personne qui découvre WebFront doit comprendre +deux processus, un canal intermédiaire et deux modes (`--serve` et `enableAutomation`), activer `WEBFRONT_BUILD_AUTOMATION`, +appeler `webfront_add_agent()` puis lancer `webfront-agent --attach DIR --mcp` ou générer sa configuration. + +Trois livraisons changent les données : + +- **#619** : le serveur HTTP accepte `POST` sur une route qui l'autorise (`RouteOptions::postBodyLimit`), avec un corps borné + annoncé par `Content-Length`, `Expect: 100-continue`, et les refus 411/413/501 (pas de corps chunked). +- **#617** : plusieurs instances tournent côte à côte. Un port demandé à `0` est attribué par l'OS et connu de l'application + (`Server::port()`), un port choisi n'est jamais remplacé et l'échec de liaison nomme l'adresse, le port et la cause. Il n'y a + donc plus d'URL connue d'avance : la découverte doit désigner une instance. +- **#631** : le TLS 1.3 intégré rend possible un `https://` sans mandataire, donc un agent distant chiffré. TLS protège le + transport et authentifie le serveur, pas les clients (ADR-008, ADR-024). + +Un serveur HTTP loopback est joignable par les pages web de la machine, et l'application embarque justement un navigateur. +L'ADR-019 classait ce transport « différé jusqu'à preuve d'un besoin » et la menace « DNS rebinding » comme critique s'il +était retenu. Le besoin est la **simplicité de compréhension** et la découverte par les agents, pas la réduction du code : +le chiffrage de #632 estime 750 à 900 lignes retirées pour 400 à 500 ajoutées. + +## Possibilités comparées + +| Voie | Intérêt | Limites | Position | +| --- | --- | --- | --- | +| Statu quo : `webfront-agent` relais stdio | Le client lance le processus ; aucun service réseau MCP. | Deux processus, un canal privé, deux modes ; configuration par chemin d'exécutable. | Conservé pendant la migration, puis retiré (voir « Migration »). | +| Route `/mcp` sur le serveur qui sert la page | Un seul port. | Une page de même origine atteint la route ; le contrôle d'origine du pont et le cookie de liaison partagent ce port ; un écouteur TLS ou non loopback l'exposerait. | Écartée. | +| **Écouteur MCP distinct, loopback, jeton Bearer** | Une URL par instance, aucun second exécutable, client MCP standard ; la page n'est jamais sur cette origine. | Service réseau privilégié ; le client ne lance plus l'application ; jeton à transmettre hors du projet. | **Retenue.** | +| MCP HTTPS distant (#631) avec jeton | Agent en conteneur, WSL ou autre machine. | Identité des clients, modèle multi-utilisateur, rotation et révocation, exposition réseau, OAuth attendu par les clients MCP distants. | Hors périmètre ; décision dédiée. | +| MCP sur socket Unix / tube nommé | Pas de port, permissions du système de fichiers. | Peu de clients MCP le prennent en charge ; pas de transport MCP normalisé. | Écartée. | + +## Décision + +### 1. Périmètre : boucle locale seulement + +L'écouteur MCP se lie à `127.0.0.1` et à rien d'autre. Il n'utilise jamais le fournisseur TLS, l'adresse ni le port de +`WebFrontConfig` : une application servie en HTTPS sur une adresse publique garde un MCP loopback en `http://`. `localhost` +est un contexte local et le transport est **déclaré** loopback, conformément à la règle « transport déclaré, jamais déduit » +de l'ADR-020 ; l'écouteur ne se marque jamais sécurisé. L'accès distant, en HTTPS ou non, reste hors périmètre : il exige une +authentification des clients et un modèle multi-utilisateur que ni l'ADR-008 ni l'ADR-024 ne fournissent. Un agent en +conteneur ou en machine virtuelle utilise un transfert de port qu'il établit lui-même ; WebFront ne le promet pas. + +### 2. Écouteur séparé de celui de la page + +Le MCP a son propre écouteur, sur un port distinct de celui de l'application. Il ne sert qu'un chemin, `/mcp` ; tout autre +chemin, y compris `/WebFront.js`, les fichiers, les routes de l'application et les découvertes OAuth (`/.well-known/...`), +reçoit 404. Il n'accepte aucune mise à niveau WebSocket. Le serveur qui sert la page n'a jamais de route `/mcp`. La page de +l'application et une page étrangère sont donc sur une autre origine que le MCP, sans jeton, et soumises aux refus du point 4. + +L'implémentation réutilise l'analyseur `http::Request` et les aides de `HTTPServer.hpp` (longueur annoncée, `Expect: +100-continue`, refus 411/413/501) dans le modèle d'admission du canal actuel (point 7), et non une instance de +`http::Server` : celle-ci sert fichiers et ressources embarquées, et n'a ni file bornée de pairs ni délai de réception. +L'écouteur MCP n'a ni fournisseur de fichiers, ni ressource embarquée, ni gestionnaire d'upgrade. +Le port est celui que l'OS attribue (`0`), selon le mécanisme de #617 ; une option permet un port choisi, avec les règles de +#617 (jamais remplacé, échec qui nomme l'adresse, le port et la cause). Aucune politique de port propre au MCP n'est introduite. + +### 3. Authentification : jeton Bearer de session + +Chaque activation tire un jeton de 256 bits de l'aléa de l'OS, distinct de la capacité du canal JSON-lines, du secret de +lancement de la page et de l'identifiant de session. Chaque requête porte `Authorization: Bearer <jeton>` ; la comparaison +parcourt tout le jeton à temps constant lorsque les longueurs sont égales. Une différence de longueur est rejetée immédiatement. +La comparaison précède la lecture du JSON. Sinon : 401 avec `WWW-Authenticate: Bearer`, sans `resource_metadata`, +car aucun serveur d'autorisation OAuth n'est annoncé. Le jeton vit autant que la session : il est révoqué à sa fermeture +(fermeture normale, échéance native, fenêtre perdue, watchdog, signal que l'application intercepte pour fermer), l'écouteur est alors fermé, et une +nouvelle activation tire un nouveau jeton. Pas de rotation pendant la session. + +Le jeton n'apparaît jamais dans la page, une URL, une ligne de commande, les journaux, le message affiché, l'enregistrement +de découverte ni un fichier du projet, que le pont de fichiers du développeur peut lire. Il est écrit dans le répertoire +privé de l'instance (point 5), dans un fichier de configuration cliente `mcp.json` en mode 0600 (ACL du propriétaire sous +Windows), qui contient l'URL et l'en-tête : + +```json +{"mcpServers": {"<nom>": {"type": "http", "url": "http://127.0.0.1:PORT/mcp", + "headers": {"Authorization": "Bearer <jeton>"}}}} +``` + +Le client l'obtient par ce fichier hors projet : en le passant tel quel à un client qui accepte un fichier de configuration, +en recopiant l'en-tête dans la configuration **utilisateur** du client (hors projet), ou par un `headersHelper` qui lit le +fichier. Une variable d'environnement n'est pas retenue : le jeton change à chaque lancement et l'environnement du client +est fixé avant. Le `.mcp.json` d'un projet ne contient jamais le jeton ; la documentation le dit et `wf` n'en écrit pas. + +### 4. Attaques par navigateur + +Avant l'authentification, et donc même avec un jeton valide : + +- **Host** doit valoir exactement `127.0.0.1:<port>` ou `localhost:<port>` ; sinon 421. Cela écarte le rebinding DNS. +- **Origin** non vide : 403, quelle que soit sa valeur, y compris l'origine de l'application. Un client MCP natif n'envoie + pas d'`Origin` ; un navigateur l'envoie sur tout `POST`. Tout en-tête `Sec-Fetch-*` présent reçoit aussi 403. +- **Content-Type** doit être `application/json` : une requête « simple » de formulaire est refusée (415), et la requête de + pré-vérification `OPTIONS` reçoit 405 sans aucun en-tête CORS. Aucune réponse ne porte `Access-Control-Allow-*`. + +Ces refus ne remplacent pas le jeton : un client natif peut forger `Host` et omettre `Origin` (ADR-008). Le jeton seul +authentifie ; Host, Origin et Content-Type empêchent qu'une page web l'utilise ou sonde la route. + +### 5. Adresse, découverte et nettoyage + +`enableAutomation` n'exige pas de répertoire : il crée un répertoire privé neuf par instance sous le répertoire de +découverte par utilisateur existant (`.../webfront/sessions/<session>/`, 0700), nommé par l'identifiant de session (aléa +de l'OS), donc sans collision entre des centaines d'instances. Un `directory` explicite reste accepté (neuf, hors projet). L'enregistrement `<session>.json` gagne l'URL MCP (sans jeton) +et le chemin de `mcp.json`. L'application affiche une ligne sur stderr (désactivable par `announce = false`) : + +```text +WebFront MCP (grants: check, build): http://127.0.0.1:PORT/mcp — client configuration: <répertoire>/mcp.json +``` + +`Automation::mcpUrl()` et `Automation::clientConfiguration()` rendent la même information au code. À la fermeture, le +répertoire, ses fichiers connus (`mcp.json`) et l'enregistrement sont retirés, sans suppression récursive +d'un contenu inconnu. Après un arrêt non interceptable, l'activation suivante et la liste des sessions retirent les +enregistrements dont le processus n'existe plus, avec leurs fichiers connus. Un identifiant de processus recyclé peut +retarder ce nettoyage ; le jeton d'une instance morte ne sert à rien, son port étant fermé. + +### 6. Protocole + +Profil Streamable HTTP de MCP **2025-11-25**, réduit : + +- Un seul point d'accès `POST /mcp`, un message JSON-RPC par requête ; un tableau (lot) est refusé (`-32600`). Réponse + toujours `application/json`, jamais SSE ; `Accept` doit contenir `application/json`. Une notification ou une réponse + du client reçoit 202 sans corps. `GET /mcp` reçoit 405 (pas de flux serveur). +- Corps borné par `Content-Length` à 60 000 octets (la limite d'entrée actuelle), profondeur JSON 32, clés dupliquées + refusées ; pas de corps chunked (501), `Expect: 100-continue` honoré, limites du serveur actuel. +- `Mcp-Session-Id` est attribué à `initialize` (128 bits de l'OS) ; il route, il n'authentifie pas. Une requête sans lui + hors `initialize` reçoit 400, un identifiant inconnu ou terminé 404 ; `DELETE /mcp` termine la session MCP, pas la + session d'automatisation ni la fenêtre. Seize sessions MCP au plus ; la plus anciennement inactive est évincée. Seul un + message accepté compte comme activité : un message refusé ne protège pas sa session de l'éviction. +- `MCP-Protocol-Version` est vérifié après l'initialisation, pour tout message, réponse du client et `DELETE` compris ; + une version non prise en charge reçoit 400 et reste sans effet sur la session. Une réponse du client doit être une + réponse JSON-RPC 2.0 (un `id`, exactement un de `result` et `error`), sinon 400. +- Le catalogue reste à quatre outils : `webfront.session`, `webfront.start`, `webfront.result`, `webfront.cancel`. Une + opération longue se suit par interrogation de `webfront.result` ; aucune notification de progression n'est poussée. +- La réponse à `initialize` porte des `instructions` courtes (celles de `Instructions.hpp`). Les ressources MCP + (`resources/list`) relèvent d'une évolution indépendante du transport. + +### 7. Garanties reprises du canal actuel + +- File de 64 pairs non authentifiés, éviction du plus ancien, délai de deux secondes pour recevoir en-têtes et corps ; + 32 workers pour les requêtes authentifiées, qu'un pair silencieux ne consomme pas. Une saturation locale peut encore + épuiser l'OS ou le processeur. +- Délai par requête de 30 secondes côté serveur ; les échéances par opération (`timeout`) et de démarrage + (`startupTimeout`) sont inchangées ; la progression ne les prolonge pas. +- Sockets non héritables, fermées à l'exécution sous POSIX. +- Révocation : fermeture de la session, de l'écouteur et du jeton ; watchdog, `closeGrace`, `onUnresponsive` et le statut + 72 de l'application inchangés. Les statuts 70 et 71 restent ceux du lanceur tant qu'il existe. +- Audit des décisions d'autorisation et rétention de 64 runs inchangés ; un refus d'authentification HTTP n'atteint pas le + contrôleur et n'évince pas l'audit. + +### 8. Garde de compilation + +L'automatisation n'existe pas dans une build de distribution : `Enable.hpp`, et tout en-tête qui ouvre un écouteur MCP, +produit une erreur de compilation si `WEBFRONT_DISTRIBUTION` vaut 1. C'est un durcissement voulu : aujourd'hui, la +documentation laisse ce choix à l'application (« gate the call »). Protéger l'appel ne suffit plus : l'application place +sous la même condition de distribution l'inclusion de `Enable.hpp`, l'appel à `enableAutomation` et tout code qui utilise +l'automatisation. Une application qui oublie l'un d'eux ne compile plus en distribution, au lieu d'expédier un écouteur. + +### 9. Démarrage par l'agent + +Avec stdio, le client lance le processus ; avec HTTP, l'application doit déjà tourner. Ce n'est pas compensé par un +lanceur : l'application appartient à la personne qui la développe, qui la lance comme d'habitude. Un agent disposant d'un +shell peut la lancer en arrière-plan puis attendre l'apparition de `mcp.json` ou de l'enregistrement de session ; +`DEVELOPING_WITH_AGENTS.md` décrit cette attente. Un client qui ne peut que lancer des processus stdio n'est plus pris en +charge après la migration. + +### 10. Sort de `webfront-agent`, de son CLI et de `--serve` (version 1.2) + +Le but de #632 est un seul exécutable : l'application de l'utilisateur est le serveur MCP. `webfront-agent` est retiré en +entier, sans être transféré dans les exemples : + +- le relais MCP stdio (`--mcp`, `--attach --mcp`), `--print-mcp-config`, `--list`, `--serve`, le CLI JSON (`--operation`, + `--schema`, `--agent-help`), `webfront_add_agent()`, `WEBFRONT_BUILD_AUTOMATION` et `WEBFRONT_AUTOMATION_FRONTEND` ; + définir l'une de ces options n'a plus d'effet qu'un avertissement de configuration ; +- le canal JSON-lines (`ChannelServer`, `ChannelClient`) et le lecteur stdio ; `Channel.hpp` ne garde que les sockets et les + fichiers privés de l'écouteur ; +- l'option `.http`, puisque HTTP est le seul transport ; `listen` devient `directory`, facultatif ; +- les statuts 70 (amorçage) et 71 (échéance) du lanceur ; `onUnresponsive` garde son statut 72 par défaut. + +Les régressions navigateur pilotent `automation_host`, un programme de test (non livré) qui appelle `enableAutomation` avec +le provisionnement du pilote de test ; les clients Python (`AutomationClient.py`, `AutomationSdkClient.py`, +`AutomationModelBenchmark.py`) parlent HTTP. Le profil temporaire et le nettoyage des processus du navigateur propres au +lanceur disparaissent : une application garde son profil habituel (#617). + +## Modèle de menace : ce qui change + +Les menaces, actifs et risques résiduels de l'ADR-019 restent valables. Ce qui change : + +| Menace et gravité | Mesures | Risque résiduel | +| --- | --- | --- | +| Rebinding DNS, page web qui vise le port MCP — critique | Écouteur loopback distinct ; Host exact ; tout `Origin` et tout `Sec-Fetch-*` refusés ; `application/json` exigé ; aucun CORS ; jeton exigé en plus. | Un navigateur qui omettrait `Origin` sur un `POST` cross-origin et ignorerait la pré-vérification resterait sans jeton. | +| Client local non autorisé — critique | Jeton de 256 bits, comparaison à temps constant à longueur égale, avant tout traitement ; fichier privé hors projet. | La longueur est observable ; un processus du même utilisateur peut lire `mcp.json`, comme il lisait le fichier du canal JSON-lines. | +| Fuite du jeton — élevée | Jamais dans le projet, la page, l'URL, la ligne de commande, les journaux, l'affichage ou l'enregistrement ; vie limitée à la session. | Une personne qui copie le fichier dans le projet ou un dépôt l'expose ; la documentation l'interdit, aucun contrôle ne l'empêche. | +| Exposition réseau — critique | Liaison 127.0.0.1 seule, indépendante de l'adresse et du TLS de l'application ; adresse non configurable. | Un transfert de port établi par l'utilisateur étend l'accès hors de cette décision. | +| Automatisation expédiée — critique | Erreur de compilation sous `WEBFRONT_DISTRIBUTION`. | Une build qui ne définit pas cette macro n'est pas protégée par elle. | +| Épuisement de connexions — élevée | File bornée, délais, workers séparés (point 7) ; sessions MCP bornées. | Une saturation locale de l'OS reste possible. | + +## Migration + +1. **ADR** : cette décision, relue et acceptée avant tout code de transport. +2. **Transport HTTP** dans l'application, à côté de `webfront-agent`, avec les tests unitaires de sécurité (jeton absent, + faux, révoqué ; Host étranger ; `Origin` hostile et de même application ; `Sec-Fetch-*` ; `Content-Type` ; lot ; + `Expect: 100-continue` ; corps trop grand ou chunked ; session MCP absente, inconnue, terminée ; garde de + distribution) et la reprise des scénarios `AutomationMcpWindow`, `AutomationMcpWatchdog`, `AutomationConsumerWindow` + et `AutomationSdkWindow` sur HTTP, plus un scénario à deux instances simultanées. +3. **Documentation centrée sur l'URL** : `AUTOMATION.md`, `DEVELOPING_WITH_AGENTS.md`, README, `AGENTS.md` des starters, + `webfront_write_agent_guide()`, `PROJECT_STATUS.md` et `CHANGELOG.md`. +4. **Retrait** de `webfront-agent` en entier et du canal JSON-lines (point 10, version 1.2). + +## Critères d'acceptation de la livraison + +- Une application qui fait `enableAutomation(app, {.grants = {...}})` répond au MCP ; un client MCP standard (SDK Python + officiel) fait `initialize`, `tools/list` et une opération complète (`check`, `build`), sans autre programme. +- Deux applications simultanées exposent chacune leur MCP sans collision, et l'agent désigne l'instance voulue par son URL + et son `mcp.json`. +- Les cas de sécurité de l'étape 2 sont couverts par des tests, et l'automatisation ne compile pas en distribution. +- Les quatre scénarios cités passent sur le nouveau transport. +- Les guides, le README et `PROJECT_STATUS.md` décrivent le nouveau parcours. + +## Conséquences + +- **Bénéfice :** une URL par instance, un client MCP standard, plus de second exécutable ni de canal intermédiaire pour + le parcours principal ; découverte par l'affichage, `mcp.json` et l'enregistrement de session. +- **Coût accepté :** un service réseau privilégié dans l'application de développement, un jeton à transmettre au client, + l'application qui doit tourner avant que l'agent se connecte, et la perte des clients limités à stdio. +- **Risque :** que l'accès distant soit demandé ensuite ; il exige une décision dédiée sur l'authentification des + clients, et ne doit pas être obtenu en liant l'écouteur ailleurs que sur la boucle locale. + +## Références + +- [ADR-019](ADR-019-developpement-automatisable-et-agents.md), [ADR-008](ADR-008-contenu-de-confiance-et-origines.md), + [ADR-020](ADR-020-services-systeme.md) (transport déclaré), [ADR-024](ADR-024-tls-integre.md), + [AUTOMATION](../AUTOMATION.md), [HOST_INTEGRATION](../HOST_INTEGRATION.md) (port et instances, #617). +- [MCP 2025-11-25, transports](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports) (Streamable HTTP, + `Mcp-Session-Id`, `MCP-Protocol-Version`, validation d'`Origin`). +- [MCP, bonnes pratiques de sécurité](https://modelcontextprotocol.io/docs/2025-11-25/tutorials/security/security_best_practices). diff --git a/docs/adr/ADR-026-configuration-mcp-persistante.md b/docs/adr/ADR-026-configuration-mcp-persistante.md new file mode 100644 index 00000000..dc6ef758 --- /dev/null +++ b/docs/adr/ADR-026-configuration-mcp-persistante.md @@ -0,0 +1,27 @@ +# ADR-026 : Configuration MCP stable en développement + +## Versions + +| Version | Date | État | Auteur | Évolution | Révision Git | +| --- | --- | --- | --- | --- | --- | +| 1.0 | 2026-11-22 | Proposée | Ambroise Leclerc | Configuration persistante par projet (#637). | [110b138](https://github.com/ambroise-leclerc/WebFront/commit/110b138301a4920e0a25d6614644624602943cc3) (historique consigné ; pas de commit distinct) | +| 1.1 | 2026-11-22 | Acceptée, puis suspendue | Ambroise Leclerc | L'usurpation de l'écouteur révèle une exposition du jeton persistant. | [110b138](https://github.com/ambroise-leclerc/WebFront/commit/110b138301a4920e0a25d6614644624602943cc3) (historique consigné ; pas de commit distinct) | +| 1.2 | 2026-11-22 | Acceptée | Ambroise Leclerc | Mode explicite simplifié, compromis de sécurité acceptés ; issue #637 amendée. | [110b138](https://github.com/ambroise-leclerc/WebFront/commit/110b138301a4920e0a25d6614644624602943cc3) ; livraison : [5306a9f](https://github.com/ambroise-leclerc/WebFront/commit/5306a9f520a2c40002318a09b9e629e00aef59f8) | + +## Décision + +La décision 1.2, consignée le 2026-11-22, a été livrée le 2026-11-23 par la fusion de la PR #644. + +Le mode de l'ADR-025 reste le défaut : port choisi par l'OS, jeton aléatoire par session et configuration privée supprimée à la fermeture. L'application peut fixer le port et fournir un jeton Bearer durable, ou désactiver explicitement l'authentification. Le développeur gère le secret et sa rotation ; WebFront ne le persiste pas hors de la configuration privée de session. Le client copie une fois URL et en-tête dans sa configuration utilisateur, hors projet. Il doit lancer l'application avant de se connecter. Un port occupé provoque une erreur explicite ; une autre instance peut utiliser le mode par défaut. La découverte ne contient pas de jeton. + +Ces options concernent uniquement le développement : l'automatisation reste exclue des builds de distribution. L'écoute reste sur loopback ; Host, Origin et Sec-Fetch-* restent vérifiés. La comparaison d'un jeton configuré parcourt tous ses caractères à temps constant lorsque les longueurs sont égales ; elle rejette immédiatement une différence de longueur. Les valeurs malformées et les combinaisons ambiguës sont refusées. + +## Conséquences + +Un autre utilisateur local peut occuper le port pendant l'arrêt de l'application et récupérer un Bearer durable envoyé par le client : ce jeton restera utilisable jusqu'à rotation. Sans authentification, tout processus local pouvant joindre le port peut exercer les grants. Un serveur usurpé peut également renvoyer des réponses mensongères au client. Ces limites sont acceptées uniquement sur choix explicite. Host et Origin protègent contre les requêtes de pages web, pas contre ces processus. Une authentification par défi-réponse, où le client prouve la possession du secret en répondant à un aléa sans transmettre le secret lui-même, exigerait une prise en charge spécifique du client et n'authentifierait pas à elle seule le serveur ; le Bearer fonctionne avec les clients MCP ordinaires. + +Après un crash ou un arrêt forcé, le fichier privé de session peut rester sur disque avec le jeton durable. La découverte tente de nettoyer les répertoires de session par défaut lorsque le processus n'existe plus ; ce nettoyage peut être différé ou échouer, et ne touche pas un répertoire fourni explicitement. La fermeture propre retire la configuration. L'application ou son propriétaire doit gérer les fichiers résiduels et la rotation du secret si nécessaire. + +## Validation + +Relancer l'application deux fois avec la même configuration cliente et appeler initialize puis webfront.session, avec le client HTTP du dépôt et le SDK 2.3.0 s'il est disponible. Vérifier les refus, les instances concurrentes, le conflit de port, l'absence de secret dans la découverte et les protections réseau dans les modes authentifié et sans authentification. Maintenir les guides et AgentGuidance. À la fusion, passer l'état à « Acceptée » et consigner les révisions Git réelles dans l'historique. diff --git a/docs/adr/README.md b/docs/adr/README.md index 8c14f725..7fa27ca0 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -1,7 +1,7 @@ # WebFront architecture decision records This directory describes WebFront’s architectural choices and the constraints to preserve -when making changes or generating code. It contains **22 ADRs**, with unique numbers (19 accepted decisions and 3 proposals). +when making changes or generating code. It contains **26 ADRs**, with unique numbers. The accepted baseline corresponds to commit `b031ab5` dated **2026-10-19**; the developer environment proposals are dated **2026-10-20**, the direct frontend access proposal **2026-10-24**, the DOM access proposal **2026-10-26**, the developer automation proposal **2026-10-28**, accepted **2026-10-29**, the system services proposal **2026-10-31**, and the developer environment publication proposal **2026-11-02**. Each ADR is versioned @@ -54,18 +54,21 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-009](ADR-009-modules-et-assets-reproductibles.md) | Serving modules locally and regenerating assets reproducibly | Accepted | 2023-03-16 | 2.5 — 2026-10-25 | | [ADR-010](ADR-010-composants-et-outils-optionnels.md) | Extending WebFront through optional components and development tools | Accepted | 2026-10-14 | 1.8 — 2026-11-09 | | [ADR-011](ADR-011-diagnostics-optionnels.md) | Confining mddlog behind an optional diagnostics façade | Accepted | 2026-10-01 | 1.2 — 2026-10-02 | -| [ADR-012](ADR-012-preuves-et-tests.md) | Demonstrating contracts through deterministic tests and browser integration | Accepted | 2020-04-19 | 1.6 — 2026-10-19 | +| [ADR-012](ADR-012-preuves-et-tests.md) | Demonstrating contracts through deterministic tests and browser integration | Accepted | 2020-04-19 | 1.8 — 2026-11-23 | | [ADR-013](ADR-013-bootstrap-developpeur-a-la-demande.md) | Bootstrapping a downloaded developer environment | Accepted | 2026-10-20 | 1.0 — 2026-10-24 | | [ADR-014](ADR-014-construction-javascript-dans-le-browser.md) | Resolving npm dependencies and building inside the browser | Accepted | 2026-10-20 | 1.0 — 2026-10-24 | | [ADR-015](ADR-015-ressources-generees-par-application.md) | Generating application-owned embedded resources | Accepted | 2026-10-20 | 1.0 — 2026-10-24 | | [ADR-016](ADR-016-bootstrap-comme-socle.md) | The bootstrap environment as WebFront's foundation | Accepted | 2026-10-22 | 1.6 — 2026-10-26 | | [ADR-017](ADR-017-acces-direct-aux-frontends.md) | Direct access to embedded frontends, with HTML kept normative | Proposed | 2026-10-24 | 1.1 — 2026-10-25 | | [ADR-018](ADR-018-acces-au-dom.md) | DOM access from C++ through a bounded mutation stream, without contesting the DOM of UI libraries | Proposed, partially superseded, partially delivered | 2026-10-26 | 1.5 — 2026-10-30 | -| [ADR-019](ADR-019-developpement-automatisable-et-agents.md) | Automating the developer environment through shared operations and an optional local MCP adapter | Accepted | 2026-10-28 | 1.2 — 2026-10-29 | +| [ADR-019](ADR-019-developpement-automatisable-et-agents.md) | Automating the developer environment through shared operations and an optional local MCP adapter | Accepted (1.2); amendment 1.5 by ADR-025 proposed | 2026-10-28 | 1.5 — 2026-11-21 | | [ADR-020](ADR-020-services-systeme.md) | System services (files, clipboard, shell, notifications…) through optional C++ portals with per-connection backends, granting handles rather than paths | Proposed | 2026-10-31 | 1.8 — 2026-11-09 | | [ADR-021](ADR-021-publication-de-l-environnement-developpeur.md) | Simplifying the publication of the developer environment: automate the release, keep pinned hashes, no dedicated server | Accepted (domain delivered; phase 1 to implement) | 2026-11-02 | 1.0 — 2026-11-02 | | [ADR-022](ADR-022-profils-et-niveaux-de-support.md) | Compiler profiles, GCC 13 S2 minimum, exit clause and LTS build tools | Accepted | 2026-11-11 | 1.1 — 2026-11-11 | | [ADR-023](ADR-023-espace-de-noms-des-commandes-du-terminal.md) | Terminal command names: `wf` stays the prefix of project commands, read-only file commands (`ls`, `cat`, `tree`, `mounts`), file command names reserved ahead, dependency graph with `wf list --tree`, `wf why`, `wf info` | Accepted | 2026-11-14 | 1.0 — 2026-11-14 | +| [ADR-024](ADR-024-tls-integre.md) | Optional integrated TLS 1.3 server | Proposed | 2026-11-21 | 1.0 | +| [ADR-025](ADR-025-mcp-http-dans-l-application.md) | The application serves MCP over Streamable HTTP on its own loopback listener, with a session Bearer token, strict Host/Origin checks, per-instance discovery and no automation in distribution builds; the webfront-agent launcher is removed; amends ADR-019 | Accepted (delivery in progress) | 2026-11-21 | 1.3 — 2026-11-22 | +| [ADR-026](ADR-026-configuration-mcp-persistante.md) | Stable MCP client configuration with explicit development security modes | Accepted | 2026-11-22 | 1.2 — 2026-11-22 | Numbering follows the reading topics; milestones and individual file histories provide the chronology, which does not follow the numerical order. @@ -92,7 +95,7 @@ the chronology, which does not follow the numerical order. | DOM access from C++, generated interfaces, React or other UI library integration | 003, 004, 006, 008, 010, 016, 018 | | Diagnostics and log transport | 006, 011 | | Downloaded development environment, npm libraries and generated application assets | 008, 009, 010, 013, 014, 015, 016 | -| Developer automation, agent access, MCP and consumer UI tests | 004, 006, 008, 012, 013, 014, 016, 019 | +| Developer automation, agent access, MCP and consumer UI tests | 004, 006, 008, 012, 013, 014, 016, 019, 025 | | System services: file dialogs, host files, clipboard, notifications, opening links | 002, 003, 006, 007, 008, 010, 017, 020 | ADRs explain decisions; [AGENTS.md](../../AGENTS.md) sets out working instructions, @@ -111,7 +114,7 @@ Do not replace historical dates with the date of an editorial change to the docu Keep previous rows and update the current version in the index. - Use one `ADR-NNN-description.md` file per decision and one row in this index. The next number - is **ADR-024**. Retain historical numbers and files. + is **ADR-027**. Retain historical numbers and files. - For a new decision that has not been integrated, use **Proposée** (Proposed), its actual proposal date and validation criteria; do not assign an artificial historical commit date. - After integration, record the date and supporting commits, the accepted negative diff --git a/docs/images/automation-agent.svg b/docs/images/automation-agent.svg index 0ae08214..7bca37dc 100644 --- a/docs/images/automation-agent.svg +++ b/docs/images/automation-agent.svg @@ -1,6 +1,6 @@ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 960 540" width="960" height="540" role="img" aria-labelledby="t d"> <title id="t">An agent drives a C++ application's own window -Abridged transcript: the agent lists the shared session, checks, builds and previews the interface, inspects and clicks it, calls an allow-listed C++ callback and is refused another one. +Abridged transcript: the agent connects to the application's MCP URL, checks, builds and previews the interface, inspects and clicks it, calls an allow-listed C++ callback and is refused another one. @@ -11,25 +11,25 @@ your agent -$ webfront-agent --list +→ initialize http://127.0.0.1:41733/mcp bf-app running grants: check build preview inspect interact call -$ webfront-agent --attach ep --operation check +→ webfront.start check ✓ No type errors in 1 project file (TypeScript 6.0.3) -$ webfront-agent --attach ep --operation build +→ webfront.start build ✓ build succeeded: app.js -$ webfront-agent --attach ep --operation preview +→ webfront.start preview ✓ preview is running in bf-app -$ webfront-agent --attach ep --operation click --element-id render +→ webfront.start click {elementId: "render"} ✓ clicked #render -$ webfront-agent --attach ep --operation call \--callback bf.render --value glider +→ webfront.start call{callback: "bf.render", value: "glider"} {"callback":"bf.render","result":"rendered:glider"} -$ webfront-agent --attach ep --operation call \--callback bf.secret +→ webfront.start call{callback: "bf.secret"} ✗ not_authorized: this callback is not allow-listed Your window. Your callbacks. Grants fixed by your C++. @@ -38,9 +38,9 @@ bf-app [automation] -WebFront automation enabled (grants: check, build, -preview, inspect, interact, call; callbacks: bf.render). -Attach with: webfront-agent --attach "ep" --mcp +WebFront MCP (grants: check, build, preview, +inspect, interact, call; callbacks: bf.render): +http://127.0.0.1:41733/mcp > diff --git a/examples/.clang-format b/examples/.clang-format index 45e9ebf1..f0d2f8fa 100644 --- a/examples/.clang-format +++ b/examples/.clang-format @@ -1,6 +1,6 @@ --- # Modern C++20+ clang-format configuration for WebFront project -# Compatible with clang-format 22+ +# Reference version: clang-format 23.1.5 (pinned in .github/workflows/SourceFormat.yml); another major version may format differently Language: Cpp BasedOnStyle: WebKit diff --git a/examples/PortOption.hpp b/examples/PortOption.hpp new file mode 100644 index 00000000..c9d5ee2a --- /dev/null +++ b/examples/PortOption.hpp @@ -0,0 +1,61 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-20 +// +// WebFront — examples +// Role: Handles `--port ` and `--port=` of an example and makes it the default port of the applications that follow. +// Thread: ui-loop | Alloc: heap-init +// LLM: example support; prints the reason and returns false on an invalid value + +#pragma once + +#include + +#include +#include +#include +#include +#include + +namespace webfront::demo { + +/// Handles `--port ` and `--port=` of an example: removes the option from `argv` and makes it the default port of the +/// applications that follow (the environment variable WEBFRONT_PORT, which the example also honours without it). +/// Prints the reason and returns false when the value is not a port number or is missing. +[[nodiscard]] inline bool applyPortOption(int& argc, char** argv) { + for (int i = 1; i < argc; ++i) { + const std::string_view argument = argv[i]; + std::string_view value; + int used = 1; + if (argument == "--port") { + if (i + 1 >= argc) { + std::cerr << "--port needs a port number\n"; + return false; + } + value = argv[i + 1]; + used = 2; + } else if (argument.starts_with("--port=")) { + value = argument.substr(7); + } else { + continue; + } + try { + const std::string port = validatedPort(value, "--port"); +#ifdef _WIN32 + _putenv_s("WEBFRONT_PORT", port.c_str()); +#else + setenv("WEBFRONT_PORT", port.c_str(), 1); +#endif + } catch (const std::invalid_argument& error) { + std::cerr << error.what() << '\n'; + return false; + } + for (int j = i; j + used <= argc; ++j) + argv[j] = argv[j + used]; // moves the trailing null pointer too + argc -= used; + --i; + } + return true; +} + +} // namespace webfront::demo diff --git a/examples/hello-world/HelloWorld.cpp b/examples/hello-world/HelloWorld.cpp index aaa55a73..f7801bb9 100644 --- a/examples/hello-world/HelloWorld.cpp +++ b/examples/hello-world/HelloWorld.cpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2022-02-03 +// +// WebFront — examples +// Role: Minimal example: a C++ callback called from the browser, served by an embedded page. +// Thread: ui-loop | Alloc: unrestricted +// LLM: smallest complete application; the README quick start must stay in step with it + #include // Switching to an embedded Chromium window only changes this alias (CEF must be enabled at diff --git a/examples/host-loop/BoingCuda.cu b/examples/host-loop/BoingCuda.cu index 92cdb998..1d53094b 100644 --- a/examples/host-loop/BoingCuda.cu +++ b/examples/host-loop/BoingCuda.cu @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-16 +// +// WebFront — examples +// Role: CUDA unit of the host-loop example: the ray-traced Boing Ball computed on the device. +// Thread: worker-safe | Alloc: unrestricted +// LLM: optional CUDA build; device memory is allocated lazily and freed by cudaRelease + // The CUDA renderer of the Boing Ball: one thread per pixel runs the same pixel() as the CPU renderer. // Compiled by nvcc at C++17; includes no WebFront header. @@ -25,8 +34,8 @@ const char* failure(cudaError_t status) { } // namespace const char* cudaDevice() { - static char name[256] = ""; - int count = 0; + static char name[256] = ""; + int count = 0; cudaDeviceProp properties; if (name[0] == '\0' && cudaGetDeviceCount(&count) == cudaSuccess && count > 0 && cudaGetDeviceProperties(&properties, 0) == cudaSuccess) for (std::size_t i = 0; i + 1 < sizeof name && properties.name[i] != '\0'; ++i) diff --git a/examples/host-loop/BoingCuda.hpp b/examples/host-loop/BoingCuda.hpp index e05e97c4..8752454b 100644 --- a/examples/host-loop/BoingCuda.hpp +++ b/examples/host-loop/BoingCuda.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-16 +// +// WebFront — examples +// Role: Interface of the optional CUDA unit: device name, whole-image computation, copy back and release. +// Thread: worker-safe | Alloc: zero-hot-path +// LLM: functions return nullptr or the reason of a failure; see docs/HOST_LOOP_EXAMPLE.md + #pragma once // The optional CUDA renderer of the Boing Ball (BoingCuda.cu). Its interface is plain C++ so that the unit nvcc @@ -30,7 +39,7 @@ inline const char* cudaCompute(const Scene&) { inline const char* cudaCopy(std::uint32_t*, std::size_t) { return "this build has no CUDA renderer"; } -inline void cudaRelease() {} +inline void cudaRelease() { } #endif } // namespace boing diff --git a/examples/host-loop/BoingHost.hpp b/examples/host-loop/BoingHost.hpp index 79058942..a410e934 100644 --- a/examples/host-loop/BoingHost.hpp +++ b/examples/host-loop/BoingHost.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-16 +// +// WebFront — examples +// Role: Host of the Boing Ball example: engines, image quality and the frames the host loop produces for the browser. +// Thread: worker-safe | Alloc: unrestricted +// LLM: example of an application keeping its own loop; see docs/HOST_LOOP_EXAMPLE.md + #pragma once // The host application of the example: it owns the scene, its clock, the renderers and its loop. Nothing here knows @@ -265,7 +274,7 @@ class Host { Settings settings; std::uint32_t revision{0}; std::map waiting; - std::set inFlight; // retained until this consumer's delivery begins + std::set inFlight; // retained until this consumer's delivery begins Displayed lastDisplayed; bool stopping{false}, ended{false}; diff --git a/examples/host-loop/BoingScene.hpp b/examples/host-loop/BoingScene.hpp index fdd2c916..89e4a42d 100644 --- a/examples/host-loop/BoingScene.hpp +++ b/examples/host-loop/BoingScene.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-16 +// +// WebFront — examples +// Role: The animated Boing Ball scene and its CPU ray tracer, a pure function of time. +// Thread: worker-safe | Alloc: zero-hot-path +// LLM: deterministic computation; the CUDA unit must produce the same image + #pragma once // The Boing Ball scene: the colour of one pixel as a function of the scene of a frame. The CPU renderer and the CUDA @@ -236,11 +245,11 @@ BOING_FN std::uint32_t pixel(const Scene& scene, int x, int y) { const float toBall = hitBall(scene, camera, direction), toFloor = hitFloor(camera, direction); const auto ray = static_cast(x) * 1973U + static_cast(y) * 9277U + static_cast(sy * 2 + sx) * 26699U; sum = sum - + beamsAlong(scene, - camera, - direction, - toBall > 0.F && (toFloor <= 0.F || toBall < toFloor) ? toBall : toFloor, - static_cast(ray & 255U) / 256.F); + + beamsAlong(scene, + camera, + direction, + toBall > 0.F && (toFloor <= 0.F || toBall < toFloor) ? toBall : toFloor, + static_cast(ray & 255U) / 256.F); } } const float scale = 1.F / static_cast(scene.samples * scene.samples); diff --git a/examples/host-loop/HostLoop.cpp b/examples/host-loop/HostLoop.cpp index 57c3ae4f..f57ff59a 100644 --- a/examples/host-loop/HostLoop.cpp +++ b/examples/host-loop/HostLoop.cpp @@ -1,3 +1,13 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-13 +// +// WebFront — examples +// Role: Host-loop example application: runs the Boing Ball beside a native window or a system browser, or as a benchmark. +// Thread: ui-loop | Alloc: unrestricted +// LLM: example entry point; see docs/HOST_INTEGRATION.md for the three integration paths + +#include "../PortOption.hpp" #include "HostLoopCapture.hpp" #include "HostLoopUI.hpp" #include @@ -79,17 +89,18 @@ int runWithBrowser(boing::Host& host, const Options& options) { int runWithWindow(boing::Host& host, const Options& options) { using App = webfront::WebFrontWithFrontend; // The server's connection handler refers to these; keep them alive until after app is destroyed. - std::mutex uiMutex; + std::mutex uiMutex; std::optional captureUI; - App app{webfront::WebFrontConfig{.window = {.title = "WebFront host loop", .width = options.captureDemo ? 640 : 800, .height = options.captureDemo ? 480 : 600}}}; + App app{webfront::WebFrontConfig{ + .window = {.title = "WebFront host loop", .width = options.captureDemo ? 640 : 800, .height = options.captureDemo ? 480 : 600}}}; boing::install(app, host); app.onUIStarted([&](App::UI ui) { const std::scoped_lock lock{uiMutex}; - captureUI = ui; + captureUI = ui; const std::string mode = options.captureFrames > 1 - ? (options.settings.glass ? "globalThis.hostLoopCapture = {glass: true};" : "globalThis.hostLoopCapture = {glass: false};") : ""; - const std::string style = options.captureDemo - ? "document.querySelector('#host-loop .stats').remove();" : ""; + ? (options.settings.glass ? "globalThis.hostLoopCapture = {glass: true};" : "globalThis.hostLoopCapture = {glass: false};") + : ""; + const std::string style = options.captureDemo ? "document.querySelector('#host-loop .stats').remove();" : ""; ui.addScript(mode + ownPage + style); }); std::atomic showReturned{false}; @@ -134,7 +145,7 @@ int runWithWindow(boing::Host& host, const Options& options) { return; if (options.captureFrames > 1) { const bool glass = options.captureDemo ? i >= options.captureFrames * 2 / 3 : options.settings.glass; - auto drawn = ui->jsFunction("hostLoop.captureNext")(glass); + auto drawn = ui->jsFunction("hostLoop.captureNext")(glass); if (drawn.wait_for(10s) != std::future_status::ready) throw std::runtime_error("No capture: the browser did not draw the next frame"); (void)drawn.get(); @@ -227,24 +238,27 @@ bool parse(std::span arguments, Options& options) { if (options.captureDemo && !captureFramesSpecified) options.captureFrames = 300; return (!(captureFramesSpecified || options.captureDemo) || !options.capture.empty()) - && (!options.captureDemo || (options.captureFrames >= 3 && options.captureFrames % 3 == 0)); + && (!options.captureDemo || (options.captureFrames >= 3 && options.captureFrames % 3 == 0)); } } // namespace int main(int argc, char** argv) { + if (!webfront::demo::applyPortOption(argc, argv)) + return 2; Options options; if (!parse({argv + 1, static_cast(argc - 1)}, options)) { - std::cerr - << "Usage: WebFrontHostLoop [--engine cpu|cuda] [--quality 0-3] [--glass] [--browser] [--stats] [--capture ] [--capture-frames 1-600] [--capture-demo]\n" - " WebFrontHostLoop --benchmark\n" - " --engine the renderer at start (default cpu); cuda is an error where it is unavailable\n" - " --quality 0: 320x240, 1: 640x480, 2: 640x480 with 4 rays per pixel, 3: 960x720 with 4 (default)\n" - " --browser open the system browser even when the native window is built\n" - " --stats print the timings of an image every second\n" - " --capture write a PNG of the native window after six seconds, then stop\n" - " --capture-frames save numbered PNGs with a fixed 25 fps scene clock (default 1); requires --capture\n" - " --capture-demo hide statistics and switch to glass after two thirds (default 300 frames)\n" - " --benchmark time both renderers without any interface, and exit\n"; + std::cerr << "Usage: WebFrontHostLoop [--port ] [--engine cpu|cuda] [--quality 0-3] [--glass] [--browser] [--stats] [--capture ] " + "[--capture-frames 1-600] [--capture-demo]\n" + " WebFrontHostLoop --benchmark\n" + " --engine the renderer at start (default cpu); cuda is an error where it is unavailable\n" + " --quality 0: 320x240, 1: 640x480, 2: 640x480 with 4 rays per pixel, 3: 960x720 with 4 (default)\n" + " --port the port of the browser interface, 0 for a free port (default WEBFRONT_PORT, else 9002)\n" + " --browser open the system browser even when the native window is built\n" + " --stats print the timings of an image every second\n" + " --capture write a PNG of the native window after six seconds, then stop\n" + " --capture-frames save numbered PNGs with a fixed 25 fps scene clock (default 1); requires --capture\n" + " --capture-demo hide statistics and switch to glass after two thirds (default 300 frames)\n" + " --benchmark time both renderers without any interface, and exit\n"; return 2; } // WebFront's warnings on the console: a development build says there that its native window has no sandbox. diff --git a/examples/host-loop/HostLoopCapture.hpp b/examples/host-loop/HostLoopCapture.hpp index 21f73f9f..97b95751 100644 --- a/examples/host-loop/HostLoopCapture.hpp +++ b/examples/host-loop/HostLoopCapture.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-16 +// +// WebFront — examples +// Role: Bounded capture options of the host-loop example: frame count, file naming and checked writes. +// Thread: worker-safe | Alloc: heap-init +// LLM: example support; at most 600 frames at a fixed 25 fps scene clock + #pragma once #include diff --git a/examples/host-loop/HostLoopUI.hpp b/examples/host-loop/HostLoopUI.hpp index 2c24cd54..1fa88556 100644 --- a/examples/host-loop/HostLoopUI.hpp +++ b/examples/host-loop/HostLoopUI.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-16 +// +// WebFront — examples +// Role: The page of the host-loop example and the callbacks that connect it to the host. +// Thread: bridge-io | Alloc: unrestricted +// LLM: example UI; the host must outlive the application that registers its callbacks + #pragma once // The interface WebFront adds to the host: four callbacks and one page. The callbacks run on WebFront's server thread diff --git a/examples/life/Life.hpp b/examples/life/Life.hpp index 590cfd5e..3a2777ba 100644 --- a/examples/life/Life.hpp +++ b/examples/life/Life.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-20 +// +// WebFront — examples +// Role: Game of Life rules shared by the console, developer and embedded stages. +// Thread: worker-safe | Alloc: heap-init +// LLM: pure computation of the walkthrough; no WebFront dependency + #pragma once #include diff --git a/examples/life/LifeConsole.cpp b/examples/life/LifeConsole.cpp index b65a5672..24100c28 100644 --- a/examples/life/LifeConsole.cpp +++ b/examples/life/LifeConsole.cpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-20 +// +// WebFront — examples +// Role: Console stage of the Game of Life walkthrough. +// Thread: ui-loop | Alloc: unrestricted +// LLM: first stage of the README walkthrough + #include "Life.hpp" #include diff --git a/examples/life/LifeDeveloper.cpp b/examples/life/LifeDeveloper.cpp index c369f40f..983f9d58 100644 --- a/examples/life/LifeDeveloper.cpp +++ b/examples/life/LifeDeveloper.cpp @@ -1,16 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-20 +// +// WebFront — examples +// Role: Developer stage of the Game of Life walkthrough: the application opens the developer environment on a project. +// Thread: ui-loop | Alloc: unrestricted +// LLM: uses NativeApp::bootstrap("developer"); options live in LifeDeveloperOptions.hpp + +#include "../PortOption.hpp" #include "Life.hpp" -#include "LifeFrontend.hpp" #include "LifeDeveloperOptions.hpp" +#include "LifeFrontend.hpp" #include #include int main(int argc, char** argv) { + if (!webfront::demo::applyPortOption(argc, argv)) + return 2; const auto options = webfront::demo::parseLifeDeveloperOptions(argc, argv); if (!options) { - std::cerr << "Usage: WebFrontLifeDeveloper [ [ ]]\n" + std::cerr << "Usage: WebFrontLifeDeveloper [--port ] [ [ ]]\n" "Without arguments the project is ./" - << webfront::demo::LifeDeveloperOptions::defaultProject << ", created when missing.\n"; + << webfront::demo::LifeDeveloperOptions::defaultProject << ", created when missing; the port is --port or WEBFRONT_PORT (0: a free port).\n"; return 2; } try { diff --git a/examples/life/LifeDeveloperOptions.hpp b/examples/life/LifeDeveloperOptions.hpp index 822a328e..33a14865 100644 --- a/examples/life/LifeDeveloperOptions.hpp +++ b/examples/life/LifeDeveloperOptions.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-25 +// +// WebFront — examples +// Role: Command line of WebFrontLifeDeveloper: project directory and optional pinned environment tarball. +// Thread: ui-loop | Alloc: heap-init +// LLM: example support; no argument selects life-project in the current directory + #pragma once #include @@ -10,9 +19,9 @@ namespace webfront::demo { struct LifeDeveloperOptions { static constexpr const char* defaultProject = "life-project"; - std::filesystem::path project = defaultProject; - std::optional environment; - std::optional integrity; + std::filesystem::path project = defaultProject; + std::optional environment; + std::optional integrity; }; /// Returns nullopt when the arguments do not follow the usage; no argument selects `life-project` in the diff --git a/examples/life/LifeEmbedded.cpp b/examples/life/LifeEmbedded.cpp index c1484f84..3bdfb6c1 100644 --- a/examples/life/LifeEmbedded.cpp +++ b/examples/life/LifeEmbedded.cpp @@ -1,11 +1,25 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-20 +// +// WebFront — examples +// Role: Embedded stage of the Game of Life walkthrough: the compiled UI served from the embedded provider. +// Thread: ui-loop | Alloc: unrestricted +// LLM: final stage of the README walkthrough; the provider is generated by wf embed + #include #include WEBFRONT_LIFE_ASSETS_HEADER +#include "../PortOption.hpp" #include "Life.hpp" #include "LifeFrontend.hpp" #include -int main() { +int main(int argc, char** argv) { + if (!webfront::demo::applyPortOption(argc, argv) || argc != 1) { + std::cerr << "Usage: WebFrontLifeEmbedded [--port ] (WEBFRONT_PORT=0 asks for a free port)\n"; + return 2; + } try { webfront::demo::LifeAppWithAssets app; app.cppFunction("life.step", &webfront::demo::nextLife); diff --git a/examples/life/LifeFrontend.hpp b/examples/life/LifeFrontend.hpp index 65909e45..7b10764e 100644 --- a/examples/life/LifeFrontend.hpp +++ b/examples/life/LifeFrontend.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-25 +// +// WebFront — examples +// Role: Selects the frontend of the Game of Life examples. +// Thread: ui-loop | Alloc: zero-hot-path +// LLM: alias only; the examples never select CEF + #pragma once #include diff --git a/examples/life/react/LifeReact.cpp b/examples/life/react/LifeReact.cpp index 30435f6e..8e11417a 100644 --- a/examples/life/react/LifeReact.cpp +++ b/examples/life/react/LifeReact.cpp @@ -1,5 +1,15 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-27 +// +// WebFront — examples +// Role: Game of Life variant with a C++ panel inside a React page. +// Thread: ui-loop | Alloc: unrestricted +// LLM: see docs/REACT.md; entry point of the react variant + #include "LifeReact.hpp" +#include "../../PortOption.hpp" #include "../LifeDeveloperOptions.hpp" #include "../LifeFrontend.hpp" @@ -8,10 +18,13 @@ #include int main(int argc, char** argv) { + if (!webfront::demo::applyPortOption(argc, argv)) + return 2; if (argc > 2 || (argc == 2 && *argv[1] == '\0')) { - std::cerr << "Usage: WebFrontLifeReact []\n" + std::cerr << "Usage: WebFrontLifeReact [--port ] []\n" "Without argument the project is ./" - << webfront::demo::LifeDeveloperOptions::defaultProject << ", created empty when missing: copy main.tsx and webfront.project.json from examples/life/react/ into it first.\n"; + << webfront::demo::LifeDeveloperOptions::defaultProject + << ", created empty when missing: copy main.tsx and webfront.project.json from examples/life/react/ into it first.\n"; return 2; } try { diff --git a/examples/life/react/LifeReact.hpp b/examples/life/react/LifeReact.hpp index a4f44fb8..b9e30e1c 100644 --- a/examples/life/react/LifeReact.hpp +++ b/examples/life/react/LifeReact.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-27 +// +// WebFront — examples +// Role: The C++ side of the React variant: per-browser sessions publishing snapshots through a Store. +// Thread: bridge-io | Alloc: unrestricted +// LLM: example of react::Store; one Session per connected browser + #pragma once #include "../Life.hpp" #include diff --git a/examples/pty/main.cpp b/examples/pty/main.cpp index b27495c9..87046dfc 100644 --- a/examples/pty/main.cpp +++ b/examples/pty/main.cpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-19 +// +// WebFront — examples +// Role: Standalone PTY example: a native pseudoterminal shown in an xterm.js page. +// Thread: ui-loop | Alloc: unrestricted +// LLM: has its own CMake entry point; see docs/PTY.md + #include #include #ifdef _WIN32 diff --git a/include/webfront/.clang-format b/include/webfront/.clang-format index 45e9ebf1..f0d2f8fa 100644 --- a/include/webfront/.clang-format +++ b/include/webfront/.clang-format @@ -1,6 +1,6 @@ --- # Modern C++20+ clang-format configuration for WebFront project -# Compatible with clang-format 22+ +# Reference version: clang-format 23.1.5 (pinned in .github/workflows/SourceFormat.yml); another major version may format differently Language: Cpp BasedOnStyle: WebKit diff --git a/include/webfront/ApplicationOrigin.hpp b/include/webfront/ApplicationOrigin.hpp index e64c6eea..03e07eb5 100644 --- a/include/webfront/ApplicationOrigin.hpp +++ b/include/webfront/ApplicationOrigin.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-18 +// +// WebFront — core +// Role: Canonical application authority (host, port, scheme) shared by the HTTP server and the frontend URL builders. +// Thread: worker-safe | Alloc: heap-init +// LLM: pure string helpers; keep in sync with the origin checks of ContentPolicy.hpp + #pragma once #include @@ -25,12 +34,12 @@ inline std::string applicationHost(std::string_view address) { } /** @brief Canonical application authority shared by the HTTP server and frontend URL builders. */ -inline std::string applicationOrigin(std::string_view address, std::string_view port) { +inline std::string applicationOrigin(std::string_view address, std::string_view port, bool secure = false) { if (port.empty()) throw std::invalid_argument("WebFront: empty frontend port"); if (port.find_first_not_of("0123456789") != std::string_view::npos) throw std::invalid_argument("WebFront: invalid frontend port"); - return "http://" + applicationHost(address) + ":" + std::string(port); + return (secure ? "https://" : "http://") + applicationHost(address) + ":" + std::string(port); } } // namespace webfront::detail diff --git a/include/webfront/BridgeError.hpp b/include/webfront/BridgeError.hpp index c9e05c6f..2197cddc 100644 --- a/include/webfront/BridgeError.hpp +++ b/include/webfront/BridgeError.hpp @@ -1,4 +1,12 @@ -/// @brief The failure of a bridge call, with a code that lets the caller tell failures apart. +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-05 +// +// WebFront — core +// Role: The failure of a bridge call, with a code that lets the caller tell failures apart. +// Thread: worker-safe | Alloc: unrestricted +// LLM: public API; reserved `webfront.` codes are part of the wire contract with WebFront.js + #pragma once #include @@ -39,7 +47,7 @@ inline constexpr std::string_view cancelled = "webfront.cancelled"; */ class BridgeError : public std::runtime_error { public: - static constexpr std::size_t maxCodeSize = 64; + static constexpr std::size_t maxCodeSize = 64; static constexpr std::string_view reservedPrefix = "webfront."; /// @throws std::invalid_argument for an ill-formed or reserved code @@ -73,8 +81,8 @@ class BridgeError : public std::runtime_error { private: friend BridgeError detail::makeBridgeError(std::string_view, const std::string&); - struct Bridge {}; - BridgeError(Bridge, std::string errorCode, const std::string& message) : std::runtime_error(message), codeText(std::move(errorCode)) {} + struct Bridge { }; + BridgeError(Bridge, std::string errorCode, const std::string& message) : std::runtime_error(message), codeText(std::move(errorCode)) { } std::string codeText; }; diff --git a/include/webfront/Broadcast.hpp b/include/webfront/Broadcast.hpp index ecabf617..52d7ca85 100644 --- a/include/webfront/Broadcast.hpp +++ b/include/webfront/Broadcast.hpp @@ -1,5 +1,12 @@ // SPDX-License-Identifier: Apache-2.0 OR CECILL-B -/// @brief A JavaScript function called on every connected browser (BasicWF::broadcast). +// Author: Ambroise Leclerc +// Created: 2026-10-30 +// +// WebFront — core +// Role: A JavaScript function called on every connected browser (BasicWF::broadcast), with an optional per-browser backlog limit. +// Thread: thread-safe | Alloc: unrestricted +// LLM: public API; read BroadcastOptions before the sender implementation + #pragma once #include "http/WebSocket.hpp" #include "weblink/CallFrame.hpp" diff --git a/include/webfront/Commands.hpp b/include/webfront/Commands.hpp index 0129c6e0..20cf04c7 100644 --- a/include/webfront/Commands.hpp +++ b/include/webfront/Commands.hpp @@ -1,5 +1,15 @@ -/// @brief Terminal commands of an application: coroutines that the developer environment's terminal discovers and -/// runs, one browser session at a time, streaming their output and cancelled by Ctrl+C, a disconnection or shutdown. +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-22 +// +// WebFront — core +// Role: Terminal commands of an application: coroutines the developer environment's terminal discovers and runs, one browser session at a time. +// Thread: bridge-io | Alloc: unrestricted +// LLM: public API; read the command contract and reserved names before the registration code + +// Terminal commands of an application: coroutines that the developer environment's terminal discovers and +// runs, one browser session at a time, streaming their output and cancelled by Ctrl+C, a disconnection or shutdown. + #pragma once #include "networking/Tasks.hpp" @@ -81,8 +91,8 @@ inline std::vector parseArguments(std::string_view json) { inline void validateName(std::string_view name) { const auto invalid = name.empty() || std::ranges::any_of(name, [](char c) { - return static_cast(c) <= ' ' || c == '\x7f' || c == '\'' || c == '"' || c == '\\'; - }); + return static_cast(c) <= ' ' || c == '\x7f' || c == '\'' || c == '"' || c == '\\'; + }); if (invalid) throw std::invalid_argument("Invalid command name '" + std::string(name) + "'"); if (std::ranges::find(reservedNames, name) != reservedNames.end()) @@ -98,8 +108,8 @@ struct Run { int exitCode = 0; // The command's own stop source, requested with its task's: a copy of the Context that outlives the task still // reads a valid source. - ex::inplace_stop_source stop; - std::atomic disconnected{false}; + ex::inplace_stop_source stop; + std::atomic disconnected{false}; Run(UI caller, std::uint32_t commandId, std::vector args) : ui(std::move(caller)), id(commandId), arguments(std::move(args)) { } @@ -314,19 +324,20 @@ class Registry : public std::enable_shared_from_this> { // command it stopped waiting for. A stopped command still reports: its coroutine was unwound, not this one. struct ForwardStop { Run* run; - void operator()() noexcept { run->stop.request_stop(); } + void operator()() noexcept { + run->stop.request_stop(); + } }; static Task execute(std::weak_ptr registry, std::shared_ptr handler, std::shared_ptr> run) { const auto taskStop = co_await ex::read_env(ex::get_stop_token); // Forwards the task's stop request (Ctrl+C, disconnection, shutdown) to the command's source while it runs. const ex::stop_callback_for_t, ForwardStop> forward{taskStop, ForwardStop{run.get()}}; - bool stopped = false; - std::string error; + bool stopped = false; + std::string error; try { // The command observes its own source: requested before the senders it awaits are stopped. - co_await ex::let_stopped(ex::write_env((*handler)(Context{run}), ex::prop{ex::get_stop_token, run->stop.get_token()}), - [&stopped]() noexcept { + co_await ex::let_stopped(ex::write_env((*handler)(Context{run}), ex::prop{ex::get_stop_token, run->stop.get_token()}), [&stopped]() noexcept { stopped = true; return ex::just(); }); @@ -382,7 +393,8 @@ class Commands { return owner->list(); })); registered(app.template cppFunction( - "webfront.commands.start", [owner = registry](UI ui, std::uint32_t id, const std::string& name, const std::string& arguments) { + "webfront.commands.start", + [owner = registry](UI ui, std::uint32_t id, const std::string& name, const std::string& arguments) { owner->start(std::move(ui), id, name, arguments); })); registered(app.template cppFunction("webfront.commands.cancel", [owner = registry](UI ui, std::uint32_t id) { diff --git a/include/webfront/ContentPolicy.hpp b/include/webfront/ContentPolicy.hpp index 2ad1aecd..91f42648 100644 --- a/include/webfront/ContentPolicy.hpp +++ b/include/webfront/ContentPolicy.hpp @@ -1,3 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-18 +// +// WebFront — core +// Role: Shared per-application content rules (origins, popups, navigation) applied by every frontend. +// Thread: worker-safe | Alloc: heap-init +// LLM: public API; see docs/CONTENT_POLICY.md before changing defaults + #pragma once #include diff --git a/include/webfront/DeferredCalls.hpp b/include/webfront/DeferredCalls.hpp index b45c22e0..e22ded7a 100644 --- a/include/webfront/DeferredCalls.hpp +++ b/include/webfront/DeferredCalls.hpp @@ -1,4 +1,12 @@ -/// @brief The JavaScript calls a C++ callback has not answered yet, per browser connection. +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-05 +// +// WebFront — core +// Role: The JavaScript calls a C++ callback has not answered yet, per browser connection. +// Thread: bridge-io | Alloc: unrestricted +// LLM: internal; completion may come from any thread, keep the per-connection ownership rules intact + #pragma once #include "Task.hpp" @@ -7,8 +15,8 @@ #include #include #include -#include #include +#include #include #include #include @@ -104,11 +112,11 @@ class DeferredCalls { } private: - mutable std::mutex mutex; - std::set inFlightIds; + mutable std::mutex mutex; + std::set inFlightIds; std::map> tasks; - std::uint64_t lastKey = 0; - bool closed = false; + std::uint64_t lastKey = 0; + bool closed = false; }; } // namespace webfront::detail diff --git a/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index 0c4b58de..01420ab6 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -1,4 +1,12 @@ -/// @brief Opt-in developer environment (terminal and wf commands) running in the application window. Downloaded code has project/bridge authority. +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-20 +// +// WebFront — core +// Role: Opt-in developer environment (terminal and wf commands) running in the application window. +// Thread: ui-loop | Alloc: heap-init +// LLM: public API; downloaded code has project and bridge authority, read DeveloperBootstrapOptions first + #pragma once #include "system/DeveloperFS.hpp" @@ -66,21 +74,20 @@ inline constexpr std::string_view defaultRegistry{"https://registry.npmjs.org/"} /// The configuration the environment reads. "registry" always names a usable registry, for environments /// that predate "registryExplicit"; the latter tells whether the application chose it. inline std::string bootstrapConfig(const DeveloperBootstrapOptions& options) { - return "{\"environment\":" + json::quote(options.environment) + ",\"integrity\":" + json::quote(options.integrity) - + ",\"registry\":" + json::quote(options.registry.value_or(std::string(defaultRegistry))) - + ",\"registryExplicit\":" + (options.registry ? "true" : "false") - + (options.manifestDirectory.empty() ? std::string{} : ",\"manifestDirectory\":" + json::quote(options.manifestDirectory)) - + ",\"supported\":{\"protocol\":[" + std::to_string(protocolVersion) + "],\"api\":[" + std::to_string(apiVersion) + "]}}"; + return "{\"environment\":" + json::quote(options.environment) + ",\"integrity\":" + json::quote(options.integrity) + ",\"registry\":" + + json::quote(options.registry.value_or(std::string(defaultRegistry))) + ",\"registryExplicit\":" + (options.registry ? "true" : "false") + + (options.manifestDirectory.empty() ? std::string{} : ",\"manifestDirectory\":" + json::quote(options.manifestDirectory)) + + ",\"supported\":{\"protocol\":[" + std::to_string(protocolVersion) + "],\"api\":[" + std::to_string(apiVersion) + "]}}"; } } // namespace developer -template -class BasicDeveloperApp : public BasicWF, http::DefaultBuffersPolicy, Frontend> { - using Base = BasicWF, http::DefaultBuffersPolicy, Frontend>; +template +class DeveloperAppWithNetwork : public BasicWF, http::DefaultBuffersPolicy, Frontend> { + using Base = BasicWF, http::DefaultBuffersPolicy, Frontend>; public: /// An explicit project is required before enabling development file operations. - explicit BasicDeveloperApp(std::filesystem::path projectDirectory = {}, WebFrontConfig config = {}) + explicit DeveloperAppWithNetwork(std::filesystem::path projectDirectory = {}, WebFrontConfig config = {}) : Base(developer::projectConfig(std::move(config), projectDirectory)), project(projectDirectory.empty() ? std::filesystem::path{} : developer::canonicalDirectory(projectDirectory)) { } @@ -138,6 +145,9 @@ class BasicDeveloperApp : public BasicWF store; }; +template +using BasicDeveloperApp = DeveloperAppWithNetwork; + #if defined(_WIN32) || defined(__APPLE__) || defined(__linux__) using NativeApp = BasicDeveloperApp; diff --git a/include/webfront/JsFunction.hpp b/include/webfront/JsFunction.hpp index 3b1c1863..6541f757 100644 --- a/include/webfront/JsFunction.hpp +++ b/include/webfront/JsFunction.hpp @@ -1,6 +1,12 @@ -/// @date 04/02/2022 13:15:27 -/// @author Ambroise Leclerc -/// @brief A functor which invokes a corresponding javascript function +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2022-02-04 +// +// WebFront — core +// Role: A functor that invokes a corresponding JavaScript function, fire-and-forget or returning a std::future. +// Thread: worker-safe | Alloc: unrestricted +// LLM: public API; the untyped form is fire-and-forget, the typed form returns a future + #pragma once #include "http/WebSocket.hpp" #include "tooling/HexDump.hpp" @@ -12,24 +18,23 @@ #include #include #include +#include #include #include #include #include -#include - namespace webfront { namespace detail { -struct IgnoreJsResult {}; -} +struct IgnoreJsResult { }; +} // namespace detail -template +template class JsFunction { public: JsFunction(std::string_view functionName, WebFront& wf, WebLinkId linkId, WebLinkGeneration connectionGeneration) - : name(functionName), webFront(wf), webLinkId(linkId), generation(connectionGeneration) {} + : name(functionName), webFront(wf), webLinkId(linkId), generation(connectionGeneration) { } auto operator()(auto&&... ts) { msg::FunctionCall command; @@ -58,10 +63,10 @@ class JsFunction { } private: - std::string name; - WebFront& webFront; - WebLinkId webLinkId; + std::string name; + WebFront& webFront; + WebLinkId webLinkId; WebLinkGeneration generation; }; -} // namespace webfront +} // namespace webfront diff --git a/include/webfront/JsFunctionSender.hpp b/include/webfront/JsFunctionSender.hpp index a7ffcf68..273140d3 100644 --- a/include/webfront/JsFunctionSender.hpp +++ b/include/webfront/JsFunctionSender.hpp @@ -1,4 +1,12 @@ -/// @brief Lazy, cancellable C++ to browser calls using C++26 sender completions. +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-10-18 +// +// WebFront — core +// Role: Lazy, cancellable C++ to browser calls using C++26 sender completions. +// Thread: worker-safe | Alloc: unrestricted +// LLM: internal; cancellation is local, a late reply is discarded; see docs/ASYNC_EXECUTION.md + #pragma once #include "http/WebSocket.hpp" #include "weblink/CallFrame.hpp" @@ -199,11 +207,11 @@ class BrowserCallSender { public: using operation_state_concept = ex::operation_state_tag; explicit Operation(std::shared_ptr> value) : state(std::move(value)) { } - Operation(const Operation&) = delete; - Operation(Operation&&) = delete; - Operation& operator=(const Operation&) = delete; - Operation& operator=(Operation&&) = delete; - void start() noexcept { + Operation(const Operation&) = delete; + Operation(Operation&&) = delete; + Operation& operator=(const Operation&) = delete; + Operation& operator=(Operation&&) = delete; + void start() noexcept { auto keepAlive = state; // receiver completion may destroy this operation inline keepAlive->start(); } @@ -249,7 +257,7 @@ class JsFunctionSender { auto operator()(auto&&... arguments) const { msg::FunctionCall command; const auto frame = detail::encodeCall(command, name, std::forward(arguments)...); - std::vector payload; + std::vector payload; payload.reserve(frame.size()); auto buffers = frame.toBuffers(); for (std::size_t i = 1; i < buffers.size(); ++i) { diff --git a/include/webfront/Pty.hpp b/include/webfront/Pty.hpp index 4ee2b3b6..daf1e77c 100644 --- a/include/webfront/Pty.hpp +++ b/include/webfront/Pty.hpp @@ -1,4 +1,12 @@ -/// @brief Optional native pseudoterminal for an application-selected program. +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-19 +// +// WebFront — core +// Role: Optional native pseudoterminal for an application-selected program, with a bounded output ring. +// Thread: worker-safe | Alloc: unrestricted +// LLM: optional component; one worker thread owns the child, see docs/PTY.md + #pragma once #ifdef _WIN32 @@ -23,7 +31,7 @@ namespace webfront::pty::detail { class ByteRing { public: - explicit ByteRing(std::size_t capacity) : storage(capacity) {} + explicit ByteRing(std::size_t capacity) : storage(capacity) { } std::size_t size() const { return used; @@ -78,7 +86,7 @@ class Pty { explicit Pty(PtyOptions options) : native(pty::detail::prepare(std::move(options))), worker([this] { run(); - }) {} + }) { } ~Pty() { hangUp(); diff --git a/include/webfront/PtyPage.hpp b/include/webfront/PtyPage.hpp index fbc1a23c..1eb6a6e9 100644 --- a/include/webfront/PtyPage.hpp +++ b/include/webfront/PtyPage.hpp @@ -1,4 +1,12 @@ -/// @brief Registers an application-chosen PTY for the optional xterm.js adapter. +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-11-19 +// +// WebFront — core +// Role: Registers an application-chosen PTY for the optional xterm.js adapter. +// Thread: bridge-io | Alloc: unrestricted +// LLM: optional component; one session per name, retained across page reloads + #pragma once #include "http/Encodings.hpp" @@ -67,7 +75,7 @@ void registerPtyPage(App& app, PtyOptions options, std::string name = "webfront. launch->generation = state->generation + 1; launch->terminal = std::async(std::launch::async, [options = state->options]() mutable { return std::make_shared(std::move(options)); - }).share(); + }).share(); state->launching = std::move(launch); } auto launch = state->launching; diff --git a/include/webfront/ReadBinding.hpp b/include/webfront/ReadBinding.hpp index ff5e713e..8faae924 100644 --- a/include/webfront/ReadBinding.hpp +++ b/include/webfront/ReadBinding.hpp @@ -1,28 +1,38 @@ // SPDX-License-Identifier: Apache-2.0 OR CECILL-B -/// @brief Binds the plain HTTP reads of a page (``, `